iflow-engine-base 3.11.8 → 3.11.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bim-engine-sdk.es.js +8 -8
- package/dist/bim-engine-sdk.umd.js +2 -2
- package/dist/chunks/{engine-2d-D4gXIdIW.js → engine-2d-qvKNkmsX.js} +3 -3
- package/dist/chunks/{engine-3d-sERn9ZUW.js → engine-3d-BFrs6D9y.js} +5 -5
- package/dist/chunks/{engine-720-D2hMdaHQ.js → engine-720-BUjyPT_z.js} +1 -1
- package/dist/chunks/{engine-gaussian-CaHW8cdj.js → engine-gaussian-BtzqhQBu.js} +1 -1
- package/dist/chunks/{engine-gis-Ueesj4oW.js → engine-gis-CCukjsHp.js} +2 -2
- package/dist/chunks/{sdk-assets-BeBYmpNK.js → sdk-assets-CemZeVpH.js} +1 -1
- package/dist/chunks/{sdk-runtime-5ZDRIuju.js → sdk-runtime-DE-ZoMSy.js} +2 -2
- package/dist/chunks/{sdk-vendor-CiQO5bhM.js → sdk-vendor-8NuRpL1E.js} +1 -1
- package/dist/iflow-engine-base.css +1 -1
- package/package.json +1 -1
|
@@ -5359,7 +5359,7 @@ void main() {
|
|
|
5359
5359
|
#include <tonemapping_fragment>
|
|
5360
5360
|
#include <colorspace_fragment>
|
|
5361
5361
|
|
|
5362
|
-
}`};const noe={turbidity:10,rayleigh:3,mieCoefficient:.005,mieDirectionalG:.7,elevation:2,azimuth:180,exposure:.5,orthoExposureScale:1.5,cloudCoverage:.4,cloudDensity:.4,cloudElevation:.5,showSunDisc:!0},t6="sunrise_clear",ioe=.2,n6=[{id:"sunrise_clear",names:["晴朗日出","晴朗日出","Clear Sunrise"],params:{turbidity:4,rayleigh:1.8,mieCoefficient:.004,mieDirectionalG:.72,elevation:8,azimuth:105,exposure:.42,cloudCoverage:.12,cloudDensity:.2,cloudElevation:.45,showSunDisc:!0}},{id:"morning_mist",names:["晨雾薄云","晨雾薄云","Misty Morning"],params:{turbidity:14,rayleigh:2.4,mieCoefficient:.018,mieDirectionalG:.68,elevation:12,azimuth:120,exposure:.35,cloudCoverage:.45,cloudDensity:.5,cloudElevation:.35,showSunDisc:!0}},{id:"noon_clear",names:["晴空正午","晴空正午","Clear Noon"],params:{turbidity:2,rayleigh:1,mieCoefficient:.002,mieDirectionalG:.82,elevation:68,azimuth:180,exposure:.58,cloudCoverage:.05,cloudDensity:.12,cloudElevation:.55,showSunDisc:!0}},{id:"afternoon_cloudy",names:["午后多云","午后多云","Cloudy Afternoon"],params:{turbidity:8,rayleigh:1.7,mieCoefficient:.008,mieDirectionalG:.74,elevation:42,azimuth:220,exposure:.5,cloudCoverage:.48,cloudDensity:.42,cloudElevation:.52,showSunDisc:!0}},{id:"sunset_glow",names:["落日晚霞","落日晚霞","Sunset Glow"],params:{turbidity:10,rayleigh:2,mieCoefficient:.006,mieDirectionalG:.7,elevation:6,azimuth:245,exposure:.6,cloudCoverage:.3,cloudDensity:.36,cloudElevation:.5,showSunDisc:!0}},{id:"blue_hour",names:["暮色蓝调","暮色蓝调","Blue Hour"],params:{turbidity:7,rayleigh:1.2,mieCoefficient:.003,mieDirectionalG:.76,elevation:-4,azimuth:255,exposure:.22,cloudCoverage:.2,cloudDensity:.24,cloudElevation:.48,showSunDisc:!1}},{id:"overcast_day",names:["阴天白昼","阴天白昼","Overcast Day"],params:{turbidity:20,rayleigh:2,mieCoefficient:.02,mieDirectionalG:.6,elevation:32,azimuth:180,exposure:.38,cloudCoverage:.86,cloudDensity:.68,cloudElevation:.4,showSunDisc:!1}},{id:"storm_rain",names:["暴雨雷云","暴雨雷云","Storm Rain"],params:{turbidity:19,rayleigh:.9,mieCoefficient:.03,mieDirectionalG:.58,elevation:18,azimuth:210,exposure:.2,cloudCoverage:.95,cloudDensity:.9,cloudElevation:.28,showSunDisc:!1}},{id:"snow_day",names:["雪天漫射","雪天漫射","Snowy Day"],params:{turbidity:15,rayleigh:2.6,mieCoefficient:.012,mieDirectionalG:.65,elevation:24,azimuth:170,exposure:.5,cloudCoverage:.78,cloudDensity:.72,cloudElevation:.43,showSunDisc:!1}},{id:"moonlit_night",names:["月夜星空","月夜星空","Moonlit Night"],params:{turbidity:4,rayleigh:.35,mieCoefficient:.001,mieDirectionalG:.82,elevation:-18,azimuth:160,exposure:.14,cloudCoverage:.1,cloudDensity:.14,cloudElevation:.55,showSunDisc:!1}}],roe=n6.reduce((t,e)=>(t[e.id]=e,t),{}),soe=2e6;class AGe{engine;sky=null;sun=new H;params={...noe,...roe[t6].params};currentPreset=t6;currentIntensity=ioe;currentEnvironmentTarget=null;skyScale=45e4;skyName="bim_engine_sky";savedCameraFar=null;previousBackground=null;previousEnvironment=null;previousBackgroundIntensity=1;previousEnvironmentIntensity=1;previousToneMapping=ll;previousToneMappingExposure=1;hasCapturedSceneState=!1;constructor(e){this.engine=e}activate(){if(!this.engine?.scene)return;if(this.sky){this.sky.visible=!0,this._captureSceneState(),this._expandCameraFarForSky(),this._applyParamsToSky();return}const e=new oN;e.scale.setScalar(this.skyScale),e.name=this.skyName,this.sky=e,this.engine.scene.add(e),this._captureSceneState(),this._expandCameraFarForSky(),this.engine.renderer&&(this.engine.renderer.toneMapping=kC,this.engine.scene.background=null),this._applyParamsToSky()}close(e=!0){this.sky&&(this._restoreCameraFar(),this._restoreSceneState(e),e?(this.engine?.scene?.remove(this.sky),this.sky.material.dispose(),this.sky.geometry.dispose(),this.sky=null):this.sky.visible=!1)}isActive(){return this.sky!=null&&this.engine?.scene?.children?.includes(this.sky)}getParams(){return{...this.params}}setParams(e){Object.assign(this.params,e),this._applyParamsToSky(),this.engine?.renderer&&(e.exposure!==void 0||e.orthoExposureScale!==void 0)&&(this.engine.renderer.toneMappingExposure=this._getEffectiveExposure())}setPreset(e){const n=roe[e];n&&(this.currentPreset=e,this.params={...noe,...n.params},this._applyParamsToSky(),this.engine?.renderer&&(this.engine.renderer.toneMappingExposure=this._getEffectiveExposure()))}getCurrentPreset(){return this.currentPreset}getPresetNames(){return n6.map(e=>e.id)}getPresetList(){return n6.map(e=>({id:e.id,names:[...e.names],params:{...e.params}}))}setIntensity(e){if(this.currentIntensity=Math.max(e,0),!(!this.sky?.visible||!this.engine?.scene)){if(!this.currentEnvironmentTarget){this._refreshEnvironmentMap();return}this.engine.scene.environmentIntensity=this.currentIntensity}}getIntensity(){return this.currentIntensity}update(e){if(!this.sky?.visible)return;const n=this.sky.material.uniforms;n&&"time"in n&&(n.time.value=e??performance.now()*.001),this.engine?.renderer&&(this.engine.renderer.toneMappingExposure=this._getEffectiveExposure())}_isOrthographicCamera(){const e=this.engine?.camera;return e!=null&&e.type==="OrthographicCamera"}_getEffectiveExposure(){const e=this.params.exposure;return this._isOrthographicCamera()?e*this.params.orthoExposureScale:e}_expandCameraFarForSky(){const e=this.engine?.camera;if(!e||typeof e.far!="number")return;const n=e.far;n>=soe||(this.savedCameraFar==null&&(this.savedCameraFar=n),e.far=soe,typeof e.updateProjectionMatrix=="function"&&e.updateProjectionMatrix())}_restoreCameraFar(){if(this.savedCameraFar==null||!this.engine?.camera)return;const e=this.engine.camera;typeof e.far=="number"&&(e.far=this.savedCameraFar,typeof e.updateProjectionMatrix=="function"&&e.updateProjectionMatrix(),this.savedCameraFar=null)}_applyParamsToSky(){if(!this.sky)return;const e=this.sky.material.uniforms;this._setUniformValue(e,"turbidity",this.params.turbidity),this._setUniformValue(e,"rayleigh",this.params.rayleigh),this._setUniformValue(e,"mieCoefficient",this.params.mieCoefficient),this._setUniformValue(e,"mieDirectionalG",this.params.mieDirectionalG),this._setUniformValue(e,"cloudCoverage",this.params.cloudCoverage),this._setUniformValue(e,"cloudDensity",this.params.cloudDensity),this._setUniformValue(e,"cloudElevation",this.params.cloudElevation),this._setUniformValue(e,"showSunDisc",this.params.showSunDisc?1:0);const n=Yn.degToRad(90-this.params.elevation),i=Yn.degToRad(this.params.azimuth);this.sun.setFromSphericalCoords(1,n,i),this._setUniformValue(e,"sunPosition",this.sun),this.engine?.renderer&&(this.engine.renderer.toneMapping=kC,this.engine.renderer.toneMappingExposure=this._getEffectiveExposure(),this.sky.visible&&this._refreshEnvironmentMap())}_captureSceneState(){this.hasCapturedSceneState||!this.engine?.scene||(this.previousBackground=this.engine.scene.background,this.previousEnvironment=this.engine.scene.environment,this.previousBackgroundIntensity=this.engine.scene.backgroundIntensity??1,this.previousEnvironmentIntensity=this.engine.scene.environmentIntensity??1,this.previousToneMapping=this.engine.renderer?.toneMapping??ll,this.previousToneMappingExposure=this.engine.renderer?.toneMappingExposure??1,this.hasCapturedSceneState=!0)}_restoreSceneState(e){!this.hasCapturedSceneState||!this.engine?.scene||(this.engine.scene.background=this.previousBackground,this.engine.scene.environment=this.previousEnvironment,this.engine.scene.backgroundIntensity=this.previousBackgroundIntensity,this.engine.scene.environmentIntensity=this.previousEnvironmentIntensity,this.engine.renderer&&(this.engine.renderer.toneMapping=this.previousToneMapping,this.engine.renderer.toneMappingExposure=this.previousToneMappingExposure),e&&(this._disposeEnvironmentTarget(),this.previousBackground=null,this.previousEnvironment=null,this.previousBackgroundIntensity=1,this.previousEnvironmentIntensity=1,this.previousToneMapping=ll,this.previousToneMappingExposure=1,this.hasCapturedSceneState=!1))}_refreshEnvironmentMap(){if(!this.sky||!this.engine?.renderer||!this.engine?.scene)return;this._disposeEnvironmentTarget();const e=new j0,n=this.sky.clone();n.material=this.sky.material.clone(),e.add(n);const i=new cI(this.engine.renderer);this.currentEnvironmentTarget=i.fromScene(e,0,.1,this.skyScale*2),i.dispose(),this.engine.scene.background=null,this.engine.scene.environment=this.currentEnvironmentTarget.texture,this.engine.scene.environmentIntensity=this.currentIntensity,n.material.dispose()}_disposeEnvironmentTarget(){this.currentEnvironmentTarget?.dispose(),this.currentEnvironmentTarget=null}_setUniformValue(e,n,i){const r=e[n];r&&(i instanceof H&&typeof r.value?.copy=="function"?r.value.copy(i):r.value=i)}}class yGe{engine;defaultSettings;settings;environmentApplyVersion=0;constructor(e){this.engine=e,this.defaultSettings=this._buildDefaultSettingsFromModules(),this.settings=this._clone(this.defaultSettings)}init(){this.defaultSettings=this._buildDefaultSettingsFromModules(),this.settings=this._clone(this.defaultSettings)}getSettings(){return this._syncSettingsFromModules(),this._clone(this.settings)}getPresetLists(){const e=this.engine.ground?.getGroundList()||[],n=this.engine.hdr?.getHdrList()||[],i=this.engine.skyManager?.getPresetList()||[];return{ground:e.map(r=>this._toPresetItem(r)),hdr:n.map(r=>this._toPresetItem(r)),sky:i.map(r=>this._toPresetItem(r))}}async setSettings(e){e.render&&(Object.assign(this.settings.render,e.render),this._applyRenderSettings(this.settings.render)),e.display&&(Object.assign(this.settings.display,e.display),this._applyDisplaySettings(this.settings.display)),e.environment&&(this._mergeEnvironmentSettings(e.environment),await this._applyEnvironmentSettings(this._clone(this.settings.environment)))}async resetToDefault(){this.settings=this._clone(this.defaultSettings),this._applyRenderSettings(this.settings.render),this._applyDisplaySettings(this.settings.display),await this._applyEnvironmentSettings(this._clone(this.settings.environment))}setRenderMode(e){this.settings.render.mode=e,this.engine.engineModelModule?.switchModel(e)}setContrast(e){this.settings.render.contrast=e,this.engine.engineModelModule?.setContrastValue(.5+e/100)}setSaturation(e){this.settings.render.saturation=e,this.engine.engineModelModule?.setSaturationValue(.5+e/100)}setShadowIntensity(e){this.settings.render.shadowIntensity=e,this._updateDirectionalLight(n=>{n.shadow.intensity=e/100*2})}setLightIntensity(e){this.settings.render.lightIntensity=e,this.setAmbientLightIntensity(e/100)}setGTAOIntensity(e){this.settings.render.gtaoIntensity=e,this.engine.engineModelModule?.setGTAOIntensity(e/100)}setShowEdge(e){this.settings.display.showEdge=e,e?this.engine.modelEdge?.active():this.engine.modelEdge?.disActive()}setEdgeOpacity(e){this.settings.display.edgeOpacity=e,this.engine.modelEdge?.setOpacity(e/100)}setShowGrid(e){this.settings.display.showGrid=e,e?this.engine.grid?.show():this.engine.grid?.hide()}setShowLevel(e){this.settings.display.showLevel=e,e?this.engine.level?.show():this.engine.level?.hide()}setShowGround(e){this.settings.display.showGround=e,e?this.engine.ground?.show():this.engine.ground?.hide()}setGroundId(e){this.settings.display.groundId=e,this.engine.ground?.setGround(e)}setGroundHeight(e){this.settings.display.groundHeight=e,this.engine.ground?.setHeight(e)}async setEnvironmentType(e){this.settings.environment.type=e,await this._applyEnvironmentSettings(this._clone(this.settings.environment))}async setHdrId(e){this.settings.environment.hdrId=e,this.settings.environment.type==="hdr"&&await this._applyEnvironmentSettings(this._clone(this.settings.environment))}setHdrIntensity(e){this.settings.environment.hdrIntensity=e,this.settings.environment.type==="hdr"&&this.engine.hdr?.setIntensity(e/100)}setSkyPreset(e){this.settings.environment.skyPreset=e,this.settings.environment.skyParams={},this.settings.environment.type==="sky"&&this.engine.skyManager?.setPreset(e)}setSkyParams(e){this.settings.environment.skyParams=this._clone(e),this.settings.environment.type==="sky"&&this.engine.skyManager?.setParams(this.settings.environment.skyParams)}setSkyIntensity(e){this.settings.environment.skyIntensity=e,this.settings.environment.type==="sky"&&this.engine.skyManager?.setIntensity(e/100)}setAmbientLightIntensity(e){const n=this.engine.renderer;n&&(n.toneMapping=lb,n.toneMappingExposure=2*e)}_syncSettingsFromModules(){this.settings=this._readCurrentSettingsFromModules()}_buildDefaultSettingsFromModules(){const e=this.engine.composerModule?.saturationPass?.uniforms?.saturation?.value,n=this.engine.composerModule?.saturationPass?.uniforms?.contrast?.value,i=this.engine.composerModule?.gtaoPass?.blendIntensity,r=this.engine.renderer?.toneMappingExposure,s=this.engine.modelEdge?.getOpacity?.(),o=this.engine.hdr?.getCurrentHdrId?.()??Im,a=this.engine.hdr?.getIntensity?.(),c=this.engine.skyManager?.getIntensity?.(),l=this.engine.skyManager?.getCurrentPreset?.()??t6,u=this.engine.skyManager?.isActive?.()===!0;return{render:{mode:this._toRenderMode(this.engine.engineModelModule?.getCurrentMode?.()),contrast:this._uniformToPercent(n,Zne),saturation:this._uniformToPercent(e,Jne),shadowIntensity:this._shadowToPercent(this._getDirectionalLightShadowIntensity(),NI),lightIntensity:this._exposureToPercent(r,wj),gtaoIntensity:this._unitToPercent(i,Kne)},display:{showEdge:this.engine.modelEdge?.isEnabled?.()??Z5,edgeOpacity:this._unitToPercent(s,e6),showGrid:this.engine.grid?.getVisible?.()??K5,showLevel:this.engine.level?.getVisible?.()??eoe,showGround:this.engine.ground?.getVisible?.()??Jse,groundId:this.engine.ground?.getCurrentId?.()??Qse,groundHeight:this.engine.ground?.getHeight?.()??Kse},environment:{type:u?"sky":o!==Im?"hdr":"none",hdrId:o,hdrIntensity:this._unitToPercent(a,Zse),skyPreset:l,skyParams:{},skyIntensity:this._unitToPercent(c,ioe)}}}_readCurrentSettingsFromModules(){const e=this.engine.composerModule?.saturationPass?.uniforms?.saturation?.value,n=this.engine.composerModule?.saturationPass?.uniforms?.contrast?.value,i=this.engine.composerModule?.gtaoPass?.blendIntensity,r=this.engine.renderer?.toneMappingExposure,s=this.engine.modelEdge?.getOpacity?.(),o=this.engine.hdr?.getCurrentHdrId?.()??this.settings.environment.hdrId,a=this.engine.hdr?.getIntensity?.(),c=this.engine.skyManager?.getIntensity?.(),l=this.engine.skyManager?.getCurrentPreset?.()??this.settings.environment.skyPreset,u=this.engine.skyManager?.getParams?.(),h=this.engine.skyManager?.isActive?.()===!0;return{render:{mode:this._toRenderMode(this.engine.engineModelModule?.getCurrentMode?.()??this.settings.render.mode),contrast:this._uniformToPercent(n,this.settings.render.contrast/100+.5),saturation:this._uniformToPercent(e,this.settings.render.saturation/100+.5),shadowIntensity:this._shadowToPercent(this._getDirectionalLightShadowIntensity(),this.settings.render.shadowIntensity/50),lightIntensity:this._exposureToPercent(r,this.settings.render.lightIntensity/50),gtaoIntensity:this._unitToPercent(i,this.settings.render.gtaoIntensity/100)},display:{showEdge:this.engine.modelEdge?.isEnabled?.()??this.settings.display.showEdge,edgeOpacity:this._unitToPercent(s,this.settings.display.edgeOpacity/100),showGrid:this.engine.grid?.getVisible?.()??this.settings.display.showGrid,showLevel:this.engine.level?.getVisible?.()??this.settings.display.showLevel,showGround:this.engine.ground?.getVisible?.()??this.settings.display.showGround,groundId:this.engine.ground?.getCurrentId?.()??this.settings.display.groundId,groundHeight:this.engine.ground?.getHeight?.()??this.settings.display.groundHeight},environment:{type:h?"sky":o!==Im?"hdr":"none",hdrId:o,hdrIntensity:this._unitToPercent(a,this.settings.environment.hdrIntensity/100),skyPreset:l,skyParams:u?this._clone(u):this._clone(this.settings.environment.skyParams),skyIntensity:this._unitToPercent(c,this.settings.environment.skyIntensity/100)}}}_toRenderMode(e){return e==="simple"||e==="balance"||e==="advanced"?e:kse}_uniformToPercent(e,n){const i=typeof e=="number"?e:n;return this._clampPercent((i-.5)*100)}_shadowToPercent(e,n){const i=typeof e=="number"?e:n;return this._clampPercent(i*50)}_exposureToPercent(e,n){const i=typeof e=="number"?e:n;return this._clampPercent(i*50)}_unitToPercent(e,n){const i=typeof e=="number"?e:n;return this._clampPercent(i*100)}_clampPercent(e){return Math.min(100,Math.max(0,Math.round(e)))}_getDirectionalLightShadowIntensity(){const e=this.engine.scene?.children?.filter(i=>i instanceof ep);return!e||e.length===0?NI:(e.find(i=>i.castShadow)??e[0]).shadow?.intensity??NI}_applyRenderSettings(e){this.setRenderMode(e.mode),this.setContrast(e.contrast),this.setSaturation(e.saturation),this.setShadowIntensity(e.shadowIntensity),this.setLightIntensity(e.lightIntensity),this.setGTAOIntensity(e.gtaoIntensity)}_applyDisplaySettings(e){this.setShowEdge(e.showEdge),this.setEdgeOpacity(e.edgeOpacity),this.setShowGrid(e.showGrid),this.setShowLevel(e.showLevel),this.setShowGround(e.showGround),this.setGroundId(e.groundId),this.setGroundHeight(e.groundHeight)}async _applyEnvironmentSettings(e){const n=++this.environmentApplyVersion;if(await this.engine.hdr?.setHdr(Im),n===this.environmentApplyVersion&&(this.engine.skyManager?.close(!0),n===this.environmentApplyVersion))switch(e.type){case"none":break;case"hdr":if(e.hdrId!==Im){if(await this.engine.hdr?.setHdr(e.hdrId),n!==this.environmentApplyVersion){this._applyEnvironmentSettings(this._clone(this.settings.environment));return}this.engine.hdr?.setIntensity(e.hdrIntensity/100)}break;case"sky":this.engine.skyManager?.activate(),this.engine.skyManager?.setPreset(e.skyPreset),Object.keys(e.skyParams).length>0&&this.engine.skyManager?.setParams(this._clone(e.skyParams)),this.engine.skyManager?.setIntensity(e.skyIntensity/100);break}}_updateDirectionalLight(e){const n=this.engine.scene?.children.find(i=>i instanceof ep);n&&e(n)}_mergeEnvironmentSettings(e){Object.assign(this.settings.environment,e),e.skyPreset!==void 0&&e.skyParams===void 0&&(this.settings.environment.skyParams={}),e.skyParams!==void 0&&(this.settings.environment.skyParams=this._clone(e.skyParams))}_toPresetItem(e){const n=Array.isArray(e.names)?[...e.names]:[];return{id:e.id,name:n[0]??e.id,names:n}}_clone(e){return JSON.parse(JSON.stringify(e))}}function op(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){var e=Math.random()*16|0,n=t=="x"?e:e&3|8;return n.toString(16)})}class og{engine;handelBehaved;setting;constructor(e){this.engine=e,this.handelBehaved=Hj(e),this.handelBehaved.init(this,null),this.setting={unit:"m",precision:3}}getSetting(){return this.setting}saveSetting(e){this.setting=e}active(){this.handelBehaved.active()}disActive(){this.handelBehaved.disActive()}getMeasureText(e,n){if(e==null)return null;let i=this.setting.unit,r=i;return n==1?i=="mm"?e=e*1e3:i=="cm"?e=e*100:i=="dm"?e=e*10:i=="m"?e=e*1:i=="km"&&(e=e*.001):n==2&&(i=="mm"?e=e*1e3*1e3:i=="cm"?e=e*100*100:i=="dm"?e=e*10*10:i=="m"?e=e*1*1:i=="km"&&(e=e*.001*.001),r=r+"²"),e.toFixed(this.setting.precision)+" "+r}cancelCurrentSelectedAnnotation(){let e=this.engine.measure.annotationData;for(let n in e)e[n].forEach(i=>{i.highlight==!0&&(i.highlight=!1,i.container.classList.remove("Hight"),i.container.getElementsByTagName("svg")[0].classList.remove("Hight"))})}handelKeyEscDown(){this.cancelCurrentSelectedAnnotation();let e=this.engine.measure.annotationData,n=!0;for(let i in e)for(let r=e[i].length-1;r>=0;r--){let s=e[i][r];s.isSelect==!0&&(s.container.remove(),e[i].splice(r,1),n=!1)}this.engine.measure.clearAllPoints(),n&&(this.engine.events.trigger("quit_measure_draw",!0),this.engine.modelToolModule.unhighlightAllModels(),this.engine.measure.quitDraw())}handelKeyDeleteDown(){let e=this.engine.measure.annotationData;for(let n in e)for(let i=e[n].length-1;i>=0;i--){let r=e[n][i];r.highlight==!0&&(r.container.remove(),e[n].splice(i,1))}}clearHighlight(){let e=this.engine.measure.annotationData;for(let n in e)e[n].forEach(i=>{i.highlight=!1,i.container.classList.remove("Hight"),i.container.getElementsByTagName("svg")[0].classList.remove("Hight")})}drawNormalAnnotation(){let e=this;const n=new ua(e.engine.camera,e.engine.renderer,e.engine.scene);function i(A){const v=n.worldToScreenIfVisible(A);return v==null?null:(v.x+=e.engine.reactBoundingClientRect.left,v.y+=e.engine.reactBoundingClientRect.top,v)}function r(A,v){A.container!=null&&(A.container.style.display=v?"block":"none")}this.engine.measure.annotationData.normalAnnotation.forEach(A=>{y(A)}),this.engine.measure.annotationData.elevationAnnotation.forEach(A=>{g(A)}),this.engine.measure.annotationData.coordinateAnnotation.forEach(A=>{m(A)}),this.engine.measure.annotationData.angleAnnotation.forEach(A=>{h(A)}),this.engine.measure.annotationData.areaAnnotation.forEach(A=>{d(A)}),this.engine.measure.annotationData.slopeAnnotation.forEach(A=>{p(A)});function h(A){if(A.container==null){let E=['<svg class="measureSvg">','<circle class="measurePointer" cx="50" cy="50" r="5" fill="#f99d0b" />','<circle class="measurePointer" cx="50" cy="50" r="5" fill="#f99d0b" />','<circle class="measurePointer" cx="50" cy="50" r="5" fill="#f99d0b" />','<polyline class="measureLine" stroke="orange" stroke-width="2" points="0,0 0,0" style="fill: none; opacity: 1;"/>','<polyline class="measureLine" stroke="orange" stroke-width="2" points="0,0 0,0" style="fill: none; opacity: 1;"/>','<rect x="0" y="0" width="100" height="25" class="measureBack" />','<text x="50" y="16" text-anchor="middle" class="measureLabel">'+A.text+"</text>","</svg>"].join("");A.container=document.createElement("div"),A.container.className="angle-annotation",A.container.id=A.id,A.container.style.pointerEvents="none",A.container.innerHTML=E,e.engine.measure.annotationContainer.appendChild(A.container),A.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),A.container.getElementsByTagName("svg")[0].classList.add("Hight"),A.highlight=!0,e.engine.events.trigger(Yo.MeasureClick,A)}),A.isSelect&&(A.container.getElementsByTagName("svg")[0].classList.add("Hight"),A.highlight=!0)}let v=i(A.point1),x=i(A.point2),C=i(A.point3);if(v==null||x==null||C==null){r(A,!1);return}r(A,!0);let T=A.container;T.getElementsByTagName("circle")[0].setAttribute("cx",v.x),T.getElementsByTagName("circle")[0].setAttribute("cy",v.y),T.getElementsByTagName("circle")[1].setAttribute("cx",x.x),T.getElementsByTagName("circle")[1].setAttribute("cy",x.y),T.getElementsByTagName("circle")[2].setAttribute("cx",C.x),T.getElementsByTagName("circle")[2].setAttribute("cy",C.y),T.getElementsByTagName("polyline")[0].setAttribute("points",v.x+","+v.y+" "+x.x+","+x.y),T.getElementsByTagName("polyline")[1].setAttribute("points",x.x+","+x.y+" "+C.x+","+C.y);let S=x.x,w=x.y-30;T.getElementsByTagName("rect")[0].setAttribute("x",S-40),T.getElementsByTagName("rect")[0].setAttribute("y",w-12.5),T.getElementsByTagName("text")[0].setAttribute("x",S),T.getElementsByTagName("text")[0].setAttribute("y",w+4),T.getElementsByTagName("text")[0].innerHTML=A.text,T.style.top="0px",T.style.left="0px"}function d(A){if(A.container==null){let P=['<svg class="measureSvg">','<polygon fill="rgba(0, 0, 255, 0.1)" stroke="none" points="" style="opacity: 0.3;"/>','<polyline class="measureLine" stroke="orange" stroke-width="2" points="" style="fill: none; opacity: 1;"/>','<rect x="0" y="0" width="100" height="25" class="measureBack" />','<text x="50" y="16" text-anchor="middle" class="measureLabel"> '+e.getMeasureText(A.text,2)+"</text>","</svg>"].join("");A.container=document.createElement("div"),A.container.className="area-annotation",A.container.id=A.id,A.container.innerHTML=P,e.engine.measure.annotationContainer.appendChild(A.container),A.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),A.container.getElementsByTagName("svg")[0].classList.add("Hight"),A.highlight=!0,e.engine.events.trigger(Yo.MeasureClick,A)}),A.isSelect&&(A.container.getElementsByTagName("svg")[0].classList.add("Hight"),A.highlight=!0)}if(!A.points||A.points.length<2)return;let v=[],x=0,C=0;for(let P=0;P<A.points.length;P++){let I=i(A.points[P]);if(I==null){r(A,!1);return}v.push(I),x+=I.x,C+=I.y}r(A,!0),x=x/v.length,C=C/v.length;let T=v.map(P=>P.x+","+P.y).join(" "),S=[...v];v.length>=3&&S.push(v[0]);let w=S.map(P=>P.x+","+P.y).join(" "),E=A.container;E.getElementsByTagName("polygon")[0].setAttribute("points",v.length>=3?T:""),E.getElementsByTagName("polyline")[0].setAttribute("points",w);let D=x,O=C;E.getElementsByTagName("rect")[0].setAttribute("x",D-40),E.getElementsByTagName("rect")[0].setAttribute("y",O-12.5),E.getElementsByTagName("text")[0].setAttribute("x",D+10),E.getElementsByTagName("text")[0].setAttribute("y",O+4),E.getElementsByTagName("text")[0].innerHTML=e.getMeasureText(A.text,2),E.style.top="0px",E.style.left="0px"}function p(A){if(A.container==null){let w=['<svg class="measureSvg">',"<defs>",'<marker id="slope-arrow-'+A.id+'" markerWidth="10" markerHeight="10" refX="9" refY="3" orient="auto" markerUnits="strokeWidth">','<path class="measureLine" d="M0,0 L0,6 L9,3 z"/>',"</marker>","</defs>",'<polyline class="measureLine" stroke="orange" stroke-width="2" points="0,0 0,0" marker-end="url(#slope-arrow-'+A.id+')" style="fill: none; opacity: 1;"/>','<rect x="0" y="0" width="100" height="25" class="measureBack" />','<text x="50" y="16" text-anchor="middle" class="measureLabel"> '+A.text+"</text>","</svg>"].join("");A.container=document.createElement("div"),A.container.className="slope-annotation",A.container.id=A.id,A.container.innerHTML=w,e.engine.measure.annotationContainer.appendChild(A.container),A.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),A.container.getElementsByTagName("svg")[0].classList.add("Hight"),A.highlight=!0,e.engine.events.trigger(Yo.MeasureClick,A)}),A.isSelect&&(A.container.getElementsByTagName("svg")[0].classList.add("Hight"),A.highlight=!0)}let v=i(A.point1),x=i(A.point2);if(v==null||x==null){r(A,!1);return}r(A,!0);let C=A.container;C.getElementsByTagName("polyline")[0].setAttribute("points",v.x+","+v.y+" "+x.x+","+x.y);let T=(v.x+x.x)/2,S=(v.y+x.y)/2-30;C.getElementsByTagName("rect")[0].setAttribute("x",T-50),C.getElementsByTagName("rect")[0].setAttribute("y",S-12.5),C.getElementsByTagName("text")[0].setAttribute("x",T),C.getElementsByTagName("text")[0].setAttribute("y",S+4),C.getElementsByTagName("text")[0].innerHTML=A.text,C.style.top="0px",C.style.left="0px"}function m(A){if(A.container==null){let E=['<svg class="measureSvg">','<circle class="measurePointer" cx="0" cy="0" r="5" fill="#f99d0b" />','<rect x="0" y="-25" width="100" height="25" class="measureBack" />','<text x="50" y="-11" text-anchor="middle" class="measureLabel"> X: '+e.getMeasureText(A.textX,1)+"</text>",'<rect x="0" y="-10" width="100" height="25" class="measureBack" />','<text x="50" y="25" text-anchor="middle" class="measureLabel"> Y: '+e.getMeasureText(-A.textZ,1)+"</text>",'<rect x="0" y="10" width="100" height="25" class="measureBack" />','<text x="50" y="51" text-anchor="middle" class="measureLabel"> Z: '+e.getMeasureText(A.textY,1)+"</text>","</svg>"].join("");A.container=document.createElement("div"),A.container.className="coordinate-annotation",A.container.id=A.id,A.container.style.position="absolute",A.container.style.pointerEvents="none",A.container.innerHTML=E,e.engine.measure.annotationContainer.appendChild(A.container),A.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),A.container.getElementsByTagName("svg")[0].classList.add("Hight"),A.highlight=!0,e.engine.events.trigger(Yo.MeasureClick,A)}),A.isSelect&&(A.container.getElementsByTagName("svg")[0].classList.add("Hight"),A.highlight=!0)}let v=A.container,x=i(A.point);if(x==null){r(A,!1);return}r(A,!0),v.style.top="0px",v.style.left="0px";let C=v.getElementsByTagName("circle")[0];C&&(C.setAttribute("cx",x.x),C.setAttribute("cy",x.y));let T=v.getElementsByTagName("rect"),S=v.getElementsByTagName("text"),w=-55;T[0]&&(T[0].setAttribute("x",x.x+10),T[0].setAttribute("y",x.y+10+w)),S[0]&&(S[0].setAttribute("x",x.x+10+50),S[0].setAttribute("y",x.y+10+16+w)),T[1]&&(T[1].setAttribute("x",x.x+10),T[1].setAttribute("y",x.y+10+30+w)),S[1]&&(S[1].setAttribute("x",x.x+10+50),S[1].setAttribute("y",x.y+10+46+w)),T[2]&&(T[2].setAttribute("x",x.x+10),T[2].setAttribute("y",x.y+10+60+w)),S[2]&&(S[2].setAttribute("x",x.x+10+50),S[2].setAttribute("y",x.y+10+76+w)),S[0]&&(S[0].innerHTML="X: "+e.getMeasureText(A.textX,1)),S[1]&&(S[1].innerHTML="Y: "+e.getMeasureText(-A.textZ,1)),S[2]&&(S[2].innerHTML="Z: "+e.getMeasureText(A.textY,1))}function g(A){if(A.container==null){let C=['<svg width="100" height="50" class="measureSvg">','<rect x="0" y="0" width="100" height="25" class="measureBack" />','<text x="50" y="16" text-anchor="middle" class="measureLabel"> '+e.getMeasureText(A.text,1)+"</text>",'<polyline class="measureLine" stroke-width="2" points="80,32 0,32 16,48 32,32" style="fill: none; opacity: 1;"/>',"</svg>"].join("");A.container=document.createElement("div"),A.container.className="elevation-annotation",A.container.id=A.id,A.container.style.position="absolute",A.container.style.pointerEvents="none",A.container.innerHTML=C,e.engine.measure.annotationContainer.appendChild(A.container),A.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),A.container.getElementsByTagName("svg")[0].classList.add("Hight"),A.highlight=!0,e.engine.events.trigger(Yo.MeasureClick,A)}),A.isSelect&&(A.container.getElementsByTagName("svg")[0].classList.add("Hight"),A.highlight=!0)}let v=A.container,x=i(A.point);if(x==null){r(A,!1);return}r(A,!0),v.style.top=x.y-48+"px",v.style.left=x.x-16+"px",v.getElementsByTagName("text")[0].innerHTML=e.getMeasureText(A.text,1)}function y(A){if(A.container==null){let T=['<svg class="measureSvg">','<circle class="measurePointer" cx="50" cy="50" r="5" fill="#f99d0b" />','<circle class="measurePointer" cx="50" cy="50" r="5" fill="#f99d0b" />','<polyline class="measureLine" stroke="orange" stroke-width="2" points="80,32 0,32" style="fill: none; opacity: 1;"/>','<rect x="0" y="0" width="100" height="25" class="measureBack" />','<text x="50" y="16" text-anchor="middle" class="measureLabel"> '+e.getMeasureText(A.text,1)+"</text>","</svg>"].join("");A.container=document.createElement("div"),A.container.className="normal-annotation",A.container.id=A.id,A.container.innerHTML=T,e.engine.measure.annotationContainer.appendChild(A.container),A.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),A.container.getElementsByTagName("svg")[0].classList.add("Hight"),A.highlight=!0,e.engine.events.trigger(Yo.MeasureClick,A)}),A.isSelect&&(A.container.getElementsByTagName("svg")[0].classList.add("Hight"),A.highlight=!0)}let v=A.container;if(A.point1==null||A.point2==null){v.style.display="none";return}else v.style.display="block";let x=i(A.point1),C=i(A.point2);if(x==null||C==null){r(A,!1);return}r(A,!0),v.getElementsByTagName("polyline")[0].setAttribute("points",x.x+","+x.y+" "+C.x+","+C.y),v.getElementsByTagName("circle")[0].setAttribute("cx",x.x),v.getElementsByTagName("circle")[0].setAttribute("cy",x.y),v.getElementsByTagName("circle")[1].setAttribute("cx",C.x),v.getElementsByTagName("circle")[1].setAttribute("cy",C.y),v.getElementsByTagName("rect")[0].setAttribute("x",x.x*.5+C.x*.5-40),v.getElementsByTagName("rect")[0].setAttribute("y",x.y*.5+C.y*.5-12.5),v.getElementsByTagName("text")[0].setAttribute("x",x.x*.5+C.x*.5+50-40),v.getElementsByTagName("text")[0].setAttribute("y",x.y*.5+C.y*.5+16-12.5),v.getElementsByTagName("text")[0].innerHTML=e.getMeasureText(A.text,1),v.style.top="0px",v.style.left="0px"}}}class bGe{engine;isActive=!1;tools;points=[];behavior;catchDir=0;type="point";constructor(e){this.engine=e,this.tools=new og(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.isActive=!0,this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1;let e=this.engine.measure.annotationData.normalAnnotation.find(n=>n.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.isActive=!1,this.behavior?.disActive()}clearAllPoints(){this.points=[]}setDirection(e){this.catchDir=e===0?0:1}handelKeyTabDown(e){e.preventDefault(),!e.repeat&&(this.catchDir=this.catchDir===0?1:0)}setSelectType(e){this.type=e}getMeshesMinMaxY(e){if(!Array.isArray(e)||e.length===0)return null;let n=Number.POSITIVE_INFINITY,i=Number.NEGATIVE_INFINITY;for(let r=0;r<e.length;r++){const s=e[r];if(!s)continue;typeof s.updateMatrixWorld=="function"&&s.updateMatrixWorld(!0);const o=new Ln().setFromObject(s);!Number.isFinite(o.min.y)||!Number.isFinite(o.max.y)||(o.min.y<n&&(n=o.min.y),o.max.y>i&&(i=o.max.y))}return!Number.isFinite(n)||!Number.isFinite(i)?null:{minY:n,maxY:i}}handleMouseClick(e){if(e.catch==null)return;let n=e.catch.point;if(this.type=="element"){let s=this.engine.interactionModule.getCatchMeshs(e);var i=this.getMeshesMinMaxY(s);this.catchDir==0?n.set(n.x,i?.minY,n.z):n.set(n.x,i?.maxY,n.z)}else n=e.catch.point;if(this.points.length==0){this.engine.measure.tools.clearHighlight(),this.points.push(n);return}let r=this.engine.measure.annotationData.normalAnnotation.find(s=>s.isSelect==!0);r!=null&&(r.isSelect=!1)}handleMouseMove(e){if(e.catch==null||this.points.length==0)return;let n=this.engine.measure.annotationData.normalAnnotation.find(r=>r.isSelect==!0);n==null&&(n={text:null,id:op(),isSelect:!0,type:"clear-height"},this.engine.measure.annotationData.normalAnnotation.push(n));let i=e.catch;if(this.type=="element"){let r=e.catch.point.clone();r.set(r.x,this.points[0].y,r.z);let s=new Da(r.add(new H(0,.01,0)),new H(0,this.catchDir==0?-1:1,0));i.point=this.points[0];const o=this.engine.clipping?.filterIntersectionsByClipping(this.engine.octreeBox.rayInterationModel(s))??this.engine.octreeBox.rayInterationModel(s);if(o.length===0){n.point2=null;return}n.point1=r,n.point2=o[0].point,n.text=n.point1.clone().distanceTo(n.point2.clone()),this.engine.events.trigger(Yo.MeasureChanged,n)}else{let r=new Da(e.catch.point.clone().add(new H(0,.01,0)),new H(0,this.catchDir==0?-1:1,0));const s=this.engine.clipping?.filterIntersectionsByClipping(this.engine.octreeBox.rayInterationModel(r))??this.engine.octreeBox.rayInterationModel(r);if(s.length===0){n.point2=null;return}n.point1=i.point,n.point2=s[0].point,n.text=n.point1.clone().distanceTo(n.point2.clone()),this.engine.events.trigger(Yo.MeasureChanged,n)}}}class vGe{engine;tools;isActive=!1;points=[];behavior;constructor(e){this.engine=e,this.tools=new og(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.isActive=!0,this.points=[],this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1;let e=this.engine.measure.annotationData.normalAnnotation.find(n=>n.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.points=[],this.isActive=!1,this.engine.handelBehaved.disActive()}clearAllPoints(){this.points=[]}handleMouseClick(e){if(e.catch==null)return;let n=e.catch;if(this.points.length==0)this.engine.measure.tools.clearHighlight(),this.points.push(n.point),this.behavior.setLastPoint(n.point);else if(this.points.length==1){let i=this.engine.measure.annotationData.normalAnnotation.find(r=>r.isSelect==!0);if(i==null)return;i.point2=n.point,i.isSelect=!1,this.points=[],this.engine.events.trigger(Yo.MeasureChanged,i),this.behavior.clearLastPoint()}}handleMouseMove(e){if(e.catch==null)return;let n=e.catch;if(n!=null&&this.points.length==1){let i=this.engine.measure.annotationData.normalAnnotation.find(r=>r.isSelect==!0);i==null&&(i={id:op(),point1:this.points[0].clone(),point2:n.point.clone(),text:this.points[0].clone().distanceTo(n.point.clone()),type:"distance",isSelect:!0},this.engine.measure.annotationData.normalAnnotation.push(i)),i.point2=n.point,i.text=i.point1.clone().distanceTo(i.point2.clone())}}}class xGe{engine;isActive=!1;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new og(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.isActive=!0,this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1;let e=this.engine.measure.annotationData.normalAnnotation.find(n=>n.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.isActive=!1,this.behavior?.disActive()}clearAllPoints(){this.points=[]}handleMouseClick(e){if(e.catch==null)return;if(this.points.length==0){this.engine.measure.tools.clearHighlight(),this.points.push(e.catch.point);return}let n=this.engine.measure.annotationData.normalAnnotation.find(i=>i.isSelect==!0);n!=null&&(n.isSelect=!1)}handleMouseMove(e){if(e.catch==null||this.points.length==0)return;let n=this.engine.measure.annotationData.normalAnnotation.find(o=>o.isSelect==!0);n==null&&(n={text:null,id:op(),isSelect:!0,type:"clear-distance"},this.engine.measure.annotationData.normalAnnotation.push(n));let i=new Da(e.catch.point.clone().add(e.catch.face.normal.clone().setLength(.01)),e.catch.face.normal);const r=this.engine.clipping?.filterIntersectionsByClipping(this.engine.octreeBox.rayInterationModel(i))??this.engine.octreeBox.rayInterationModel(i);if(r.length==0){n.point2=null;return}let s=e.catch;n.point1=s.point,n.point2=r[0].point,n.text=n.point1.clone().distanceTo(n.point2.clone()),this.engine.events.trigger(Yo.MeasureChanged,n)}}class CGe{engine;isActive=!1;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new og(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1,this.isActive=!0;let e=this.engine.measure.annotationData.normalAnnotation.find(n=>n.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.isActive=!1,this.behavior?.disActive()}clearAllPoints(){this.points=[]}handleMouseMove(e){if(e.catch==null)return;let n=this.engine.measure.annotationData.elevationAnnotation.find(i=>i.isSelect==!0);n!=null&&(n.point=e.catch.point.clone(),n.text=e.catch.point.y)}handleMouseClick(e){if(e.catch==null)return;this.engine.measure.tools.clearHighlight();let n=this.engine.measure.annotationData.elevationAnnotation.find(i=>i.isSelect==!0);if(n==null){n={id:op(),point:e.catch.point.clone(),text:e.catch.point.y,isSelect:!0,type:"elevation"},this.engine.measure.annotationData.elevationAnnotation.push(n);return}n.point=e.catch.point.clone(),n.text=e.catch.point.y,n.isSelect=!1,this.engine.events.trigger(Yo.MeasureChanged,n)}}class EGe{engine;isActive=!1;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new og(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1,this.isActive=!0;let e=this.engine.measure.annotationData.normalAnnotation.find(n=>n.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.isActive=!1,this.behavior?.disActive()}clearAllPoints(){this.points=[]}handleMouseUp(e){this.engine.deviceType!="PC"&&this.createMeasure()}handleMouseMove(e){if(e.catch==null)return;let n=this.engine.measure.annotationData.coordinateAnnotation.find(i=>i.isSelect==!0);n!=null&&(n.point=e.catch.point.clone(),n.textX=e.catch.point.x,n.textY=e.catch.point.y,n.textZ=e.catch.point.z)}handleMouseClick(e){if(e.catch==null)return;this.engine.measure.tools.clearHighlight();let n=this.engine.measure.annotationData.coordinateAnnotation.find(i=>i.isSelect==!0);if(n==null){n={id:op(),point:e.catch.point.clone(),text:Math.round(e.catch.point.y)+" m",isSelect:!0,type:"point"},this.engine.measure.annotationData.coordinateAnnotation.push(n);return}n.point=e.catch.point.clone(),n.textX=e.catch.point.x,n.textY=e.catch.point.y,n.textZ=e.catch.point.z,n.isSelect=!1,this.engine.events.trigger(Yo.MeasureChanged,n)}createMeasure(){let e=this.engine.measure.annotationData.coordinateAnnotation.find(n=>n.isSelect==!0);e!=null&&(e.isSelect=!1,this.engine.events.trigger(Yo.MeasureChanged,e))}}class wGe{engine;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new og(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.points=[],this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1;let e=this.engine.measure.annotationData.normalAnnotation.find(n=>n.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.points=[],this.behavior?.disActive()}clearAllPoints(){this.points=[]}calculateAngle(e,n,i){const r=new H().subVectors(e,n),s=new H().subVectors(i,n),o=r.length(),a=s.length();if(o===0||a===0)return 0;const l=r.dot(s)/(o*a),u=Math.max(-1,Math.min(1,l));return Math.acos(u)*(180/Math.PI)}handleMouseClick(e){if(e.catch==null)return;let n=e.catch;if(this.points.length==0)this.engine.measure.tools.clearHighlight(),this.points.push(n.point);else if(this.points.length==1)this.points.push(n.point);else if(this.points.length==2){let i=this.engine.measure.annotationData.angleAnnotation.find(r=>r.isSelect==!0);if(i==null)return;i.point3=n.point.clone(),i.angle=this.calculateAngle(i.point1,i.point2,i.point3),i.text=i.angle.toFixed(2)+"°",i.isSelect=!1,i.type="angle",this.points=[],this.engine.events.trigger(Yo.MeasureChanged,i)}}handleMouseMove(e){if(e.catch!=null&&this.points.length!=1&&this.points.length==2){let n=this.engine.measure.annotationData.angleAnnotation.find(i=>i.isSelect==!0);n==null&&(n={id:op(),point1:this.points[0].clone(),point2:this.points[1].clone(),point3:e.catch.point.clone(),angle:0,text:"0.00°",isSelect:!0,type:"angle"},this.engine.measure.annotationData.angleAnnotation.push(n)),n.point3=e.catch.point.clone(),n.angle=this.calculateAngle(n.point1,n.point2,n.point3),n.text=n.angle.toFixed(2)+"°",console.log("角度",n.text)}}}class TGe{engine;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new og(e)}getCurrentDrawingMeasure(){return this.engine.measure.annotationData.areaAnnotation.find(e=>e.isSelect==!0)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.points=[],this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1;const e=this.engine.measure.annotationData.normalAnnotation.find(n=>n.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.points=[],this.behavior?.disActive()}clearAllPoints(){this.points=[]}calculateArea(e){if(e.length<3)return 0;const n=e.length,i=new H(0,0,0);for(let r=0;r<n;r++){const s=(r+1)%n;i.x+=(e[r].y-e[s].y)*(e[r].z+e[s].z),i.y+=(e[r].z-e[s].z)*(e[r].x+e[s].x),i.z+=(e[r].x-e[s].x)*(e[r].y+e[s].y)}return i.length()/2}handleRightMouseClick(){this.finishMeasure()}handleMouseClick(e){if(e.catch==null)return;const n=e.catch;this.points.length===0&&this.engine.measure.tools.clearHighlight(),this.points.push(n.point.clone());let i=this.getCurrentDrawingMeasure();i==null?(i={id:op(),points:this.points.map(r=>r.clone()),area:0,text:0,isSelect:!0,type:"area"},this.engine.measure.annotationData.areaAnnotation.push(i)):i.points=this.points.map(r=>r.clone()),this.points.length>=3?(i.area=this.calculateArea(this.points),i.text=i.area):(i.area=0,i.text=0)}handleMouseMove(e){if(e.catch!=null&&this.points.length>=1){let n=this.getCurrentDrawingMeasure();n==null&&(n={id:op(),points:[],area:0,text:0,isSelect:!0,type:"area"},this.engine.measure.annotationData.areaAnnotation.push(n));const i=this.points.map(r=>r.clone());i.push(e.catch.point.clone()),n.points=i,i.length>=3?(n.area=this.calculateArea(i),n.text=n.area):(n.area=0,n.text=0)}}handelKeyEnterDown(){this.finishMeasure()}finishMeasure(){const e=this.getCurrentDrawingMeasure();e!=null&&this.points.length>=3?(e.points=this.points.map(n=>n.clone()),e.area=this.calculateArea(e.points),e.text=e.area,e.isSelect=!1,this.points=[],this.engine.events.trigger(Yo.MeasureChanged,e)):this.engine.measure.tools.handelKeyEscDown()}}class WI{engine;tools;static WORLD_UP=new H(0,1,0);static SLOPE_DIRECTION_SNAP_DISTANCE=10;points=[];behavior;constructor(e){this.engine=e,this.tools=new og(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.points=[],this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1;let e=this.engine.measure.annotationData.normalAnnotation.find(n=>n.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.points=[],this.behavior?.disActive()}clearAllPoints(){this.points=[]}calculateSlope(e,n){const i=n.y-e.y,r=n.x-e.x,s=n.z-e.z,o=Math.sqrt(r*r+s*s);if(o===0)return{percentage:0,angle:0,heightDiff:i,horizontalDist:0,type:"slope"};const a=i/o*100,l=Math.atan(i/o)*(180/Math.PI);return{percentage:a,angle:l,heightDiff:i,horizontalDist:o,type:"slope"}}getWorldFaceNormal(e){const n=e?.normal??e?.face?.normal;if(n==null)return null;const i=n.clone(),r=e?.matrix??e?.object?.matrixWorld;return r!=null&&i.transformDirection(r),i.lengthSq()<1e-10?null:i.normalize()}getFaceSlopeDirection(e){const n=this.getWorldFaceNormal(e);if(n==null)return null;const i=new H().crossVectors(n,WI.WORLD_UP);if(i.lengthSq()<1e-10)return null;const r=new H().crossVectors(i.normalize(),n);return r.lengthSq()<1e-10?null:r.normalize()}pointToScreenLineDistance(e,n,i){const r=new Ye().subVectors(i,n),s=r.lengthSq();if(s<1e-10)return e.distanceTo(n);const o=new Ye().subVectors(e,n).dot(r)/s,a=n.clone().add(r.multiplyScalar(o));return e.distanceTo(a)}isNearSlopeDirection(e,n,i,r,s){const o=new ua(this.engine.camera,this.engine.renderer,this.engine.scene),a=o.worldToScreenIfVisible(e);if(a==null)return!1;const c=Number.isFinite(s?.offsetX)&&Number.isFinite(s?.offsetY)?new Ye(s.offsetX,s.offsetY):o.worldToScreenIfVisible(r);if(c==null)return!1;const l=Math.max(e.distanceTo(r),e.distanceTo(i),1),u=e.clone().add(n.clone().multiplyScalar(l)),h=o.worldToScreenIfVisible(u);if(h!=null)return this.pointToScreenLineDistance(c,a,h)<=WI.SLOPE_DIRECTION_SNAP_DISTANCE;const d=o.worldToScreenIfVisible(i);return d!=null&&c.distanceTo(d)<=WI.SLOPE_DIRECTION_SNAP_DISTANCE}getSlopeSnappedPoint(e,n,i){const r=n?.point;if(!(r instanceof H))return e.clone();const s=this.getFaceSlopeDirection(n);if(s==null)return r.clone();const o=new H().subVectors(r,e).dot(s);if(!Number.isFinite(o))return r.clone();const a=e.clone().add(s.clone().multiplyScalar(o));return this.isNearSlopeDirection(e,s,a,r,i)?a:r.clone()}updateSlopeMeasure(e,n,i){e.point2=n.clone();const r=this.calculateSlope(e.point1,e.point2);e.slopePercentage=r.percentage,e.slopeAngle=r.angle,e.heightDiff=r.heightDiff,e.horizontalDist=r.horizontalDist,e.text=r.percentage.toFixed(2)+"%";const s=this.getWorldFaceNormal(i),o=this.getFaceSlopeDirection(i);e.faceNormal=s?.clone(),e.slopeDirection=o?.clone(),e.isSlopeDirectionSnapped=i?.point instanceof H?n.distanceTo(i.point)>1e-8:!1}handleMouseClick(e){if(e.catch==null)return;let n=e.catch;if(this.points.length==0)this.engine.measure.tools.clearHighlight(),this.points.push(n.point.clone());else if(this.points.length==1){let i=this.engine.measure.annotationData.slopeAnnotation.find(s=>s.isSelect==!0);if(i==null)return;const r=this.getSlopeSnappedPoint(i.point1,n,e);this.updateSlopeMeasure(i,r,n),i.isSelect=!1,this.points=[],this.engine.events.trigger(Yo.MeasureChanged,i)}}handleMouseMove(e){if(e.catch==null)return;let n=e.catch;if(n!=null&&this.points.length==1){let i=this.engine.measure.annotationData.slopeAnnotation.find(s=>s.isSelect==!0);i==null&&(i={id:op(),point1:this.points[0].clone(),point2:this.getSlopeSnappedPoint(this.points[0],n,e),slopePercentage:0,slopeAngle:0,heightDiff:0,horizontalDist:0,text:"0.00%",isSelect:!0,type:"slope"},this.engine.measure.annotationData.slopeAnnotation.push(i));const r=this.getSlopeSnappedPoint(i.point1,n,e);this.updateSlopeMeasure(i,r,n)}}}class SGe{engine;isActive=!1;points=[];behavior;constructor(e){this.engine=e}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.isActive=!0,this.points=[],this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1,this.behavior.clearLastPoint?.();let e=this.engine.measure.annotationData.normalAnnotation.find(n=>n.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.points=[],this.isActive=!1,this.behavior?.clearLastPoint?.(),this.behavior?.disActive?.()}clearAllPoints(){this.points=[],this.behavior?.clearLastPoint?.()}handleMouseClick(e){if(e.catch==null)return;if(this.points.length===0){this.engine.measure.tools.clearHighlight(),this.points=[e.catch.point.clone()],this.behavior?.setLastPoint?.(e.catch.point.clone());return}const n=this.getFaceInfo(e.catch);if(n==null)return;const i=this.points[0].clone(),r=this.projectPointToFace(i,n);if(r==null)return;let s=this.engine.measure.annotationData.normalAnnotation.find(o=>o.isSelect==!0);s==null&&(s={id:op(),type:"clear-distance",isSelect:!0},this.engine.measure.annotationData.normalAnnotation.push(s)),s.point1=i,s.point2=r.footPoint,s.text=r.distance,s.facePoint=n.point.clone(),s.faceNormal=n.normal.clone(),s.isSelect=!1,this.points=[],this.behavior?.clearLastPoint?.(),this.engine.events.trigger(Yo.MeasureChanged,s)}handleMouseMove(e){if(e.catch==null||this.points.length!==1)return;const n=this.getFaceInfo(e.catch);if(n==null)return;const i=this.points[0].clone(),r=this.projectPointToFace(i,n);if(r==null)return;let s=this.engine.measure.annotationData.normalAnnotation.find(o=>o.isSelect==!0);s==null&&(s={id:op(),point1:i.clone(),point2:r.footPoint.clone(),text:r.distance,type:"clear-distance",isSelect:!0},this.engine.measure.annotationData.normalAnnotation.push(s)),s.point1=i,s.point2=r.footPoint,s.text=r.distance,s.facePoint=n.point.clone(),s.faceNormal=n.normal.clone()}getFaceInfo(e){if(e?.face==null||e?.point==null)return null;const n=e.point.clone?.(),i=this.getWorldFaceNormal(e);return!(n instanceof H)||i==null?null:{point:n,normal:i}}getWorldFaceNormal(e){const n=e?.normal??e?.face?.normal;if(n==null)return null;const i=n.clone(),r=e?.matrix??e?.object?.matrixWorld;return r!=null&&i.transformDirection(r),i.lengthSq()<1e-10?null:i.normalize()}projectPointToFace(e,n){const i=new H().subVectors(e,n.point).dot(n.normal),r=e.clone().sub(n.normal.clone().multiplyScalar(i));return{footPoint:r,distance:e.distanceTo(r)}}}let IGe=class{isActive=!1;engine;clearHeightMeasure;distanceMeasure;clearDistanceMeasure;elevationMeasure;pointMeasure;angleMeasure;areaMeasure;slopeMeasure;faceDistanceMeasure;tools;annotationContainer;annotationData={normalAnnotation:[],textAnnotation:[],coordinateAnnotation:[],angleAnnotation:[],distanceAnnotation:[],areaAnnotation:[],slopeAnnotation:[],elevationAnnotation:[],volumeAnnotation:[]};constructor(e){this.engine=e,this.clearHeightMeasure=new bGe(e),this.distanceMeasure=new vGe(e),this.clearDistanceMeasure=new xGe(e),this.elevationMeasure=new CGe(e),this.pointMeasure=new EGe(e),this.angleMeasure=new wGe(e),this.areaMeasure=new TGe(e),this.slopeMeasure=new WI(e),this.faceDistanceMeasure=new SGe(e),this.tools=new og(e),this.annotationContainer=document.createElement("div"),this.annotationContainer.className="annotation-container",e.container.appendChild(this.annotationContainer)}setContextMenuDisabled(e){this.engine?.engineStatus!=null&&(this.engine.engineStatus.isDisableContextMenu=e)}active(){this.isActive=!0,this.engine.setIdleFrameRateExempt?.("measure",!0),this.setContextMenuDisabled(!0),this.engine.modelEdge.loadModelEdge(),this.tools.active()}disActive(){this.engine.setIdleFrameRateExempt?.("measure",!1),this.setContextMenuDisabled(!1),this.tools.disActive(),this.clearAll(),this.isActive=!1,this.clearHeightMeasure.disActive(),this.distanceMeasure.disActive(),this.clearDistanceMeasure.disActive(),this.elevationMeasure.disActive(),this.pointMeasure.disActive(),this.angleMeasure.disActive(),this.areaMeasure.disActive(),this.slopeMeasure.disActive(),this.faceDistanceMeasure.disActive(),this.engine.interactionModule.init(),this.engine.interactionModule.active()}quitDraw(){this.setContextMenuDisabled(!1),this.clearHeightMeasure.disActive(),this.distanceMeasure.disActive(),this.clearDistanceMeasure.disActive(),this.elevationMeasure.disActive(),this.pointMeasure.disActive(),this.angleMeasure.disActive(),this.areaMeasure.disActive(),this.slopeMeasure.disActive(),this.faceDistanceMeasure.disActive(),this.engine.interactionModule.init(),this.engine.interactionModule.active()}clearAllPoints(){this.clearHeightMeasure.clearAllPoints(),this.distanceMeasure.clearAllPoints(),this.clearDistanceMeasure.clearAllPoints(),this.elevationMeasure.clearAllPoints(),this.pointMeasure.clearAllPoints(),this.angleMeasure.clearAllPoints(),this.areaMeasure.clearAllPoints(),this.slopeMeasure.clearAllPoints(),this.faceDistanceMeasure.clearAllPoints()}clearAll(){e(this.annotationData.normalAnnotation),e(this.annotationData.textAnnotation),e(this.annotationData.coordinateAnnotation),e(this.annotationData.angleAnnotation),e(this.annotationData.distanceAnnotation),e(this.annotationData.areaAnnotation),e(this.annotationData.slopeAnnotation),e(this.annotationData.elevationAnnotation),e(this.annotationData.volumeAnnotation);function e(n){for(let i=0;i<n.length;i++)n[i].container.remove()}this.annotationData={normalAnnotation:[],textAnnotation:[],coordinateAnnotation:[],angleAnnotation:[],distanceAnnotation:[],areaAnnotation:[],slopeAnnotation:[],elevationAnnotation:[],volumeAnnotation:[]}}saveSetting(e){this.tools.saveSetting(e)}getSetting(){return this.tools.getSetting()}update(){this.isActive&&this.tools.drawNormalAnnotation()}dispose(){this.engine.setIdleFrameRateExempt?.("measure",!1),this.setContextMenuDisabled(!1),this.tools.disActive(),this.clearHeightMeasure.disActive(),this.distanceMeasure.disActive(),this.clearDistanceMeasure.disActive(),this.elevationMeasure.disActive(),this.pointMeasure.disActive(),this.angleMeasure.disActive(),this.areaMeasure.disActive(),this.slopeMeasure.disActive(),this.faceDistanceMeasure.disActive(),this.clearAll(),this.annotationContainer.remove(),this.isActive=!1}};class MGe{engine;isActive=!1;isCtrlDown=!1;listenersAttached=!1;box;pickPoint;pickNormal;pickMesh;box_;plane;meshs;isDrag=!1;maxBox;faceIdleOpacity=0;faceHoverOpacity=.05;mobileLongPressDelay=2e3;mobileLongPressMoveTolerance=10;touchLongPressTimer=null;touchLongPressActive=!1;touchStartPosition=null;touchLatestEvent=null;transformControls=new Map;transformAnchors=new Map;transformHelpers=new Map;faceMetaMap=new Map;isSyncingTransform=!1;transformHandleSize=1.05;transformHandleColor=255;transformHandleHoverColor=16776960;handleNativeMouseDown=e=>{if(e.button!==0||!(this.isCtrlDown||e.ctrlKey))return;const n=this.createRaycasterFromMouseEvent(e),i=n.intersectObjects(this.getInteractiveMeshes(),!1);i.length!==0&&(e.preventDefault(),e.stopImmediatePropagation(),this.handleMouseDown({button:e.button,raycaster:n,intersects:i}))};handleNativeMouseMove=e=>{if(!this.isDrag&&!(this.isCtrlDown||e.ctrlKey)){this.resetMeshOpacity();return}const n=this.createRaycasterFromMouseEvent(e),i=n.intersectObjects(this.getInteractiveMeshes(),!1);this.isDrag&&(e.preventDefault(),e.stopImmediatePropagation()),this.handleMouseMove({raycaster:n,intersects:i})};handleNativeMouseUp=e=>{e.button!==0||!this.isDrag||(e.preventDefault(),e.stopImmediatePropagation(),this.handleMouseUp({button:e.button}))};handleNativeTouchStart=e=>{if(!this.isActive||e.touches.length!==1||!this.isMobileDevice()){this.resetTouchLongPressState();return}const n=this.createMouseEventFromTouch(e);if(!n)return;if(this.createRaycasterFromMouseEvent(n).intersectObjects(this.getInteractiveMeshes(),!1).length===0){this.resetTouchLongPressState();return}e.preventDefault(),e.stopImmediatePropagation(),this.resetTouchLongPressState(),this.touchLatestEvent=n,this.touchStartPosition=this.getTouchPoint(e),this.touchLongPressTimer=window.setTimeout(()=>{const s=this.touchLatestEvent;if(!s||!this.isActive)return;const o=this.createRaycasterFromMouseEvent(s),a=o.intersectObjects(this.getInteractiveMeshes(),!1);a.length!==0&&(this.touchLongPressActive=!0,this.handleMouseDown({button:0,raycaster:o,intersects:a}))},this.mobileLongPressDelay)};handleNativeTouchMove=e=>{if(!this.isMobileDevice())return;if(e.touches.length!==1){this.resetTouchLongPressState();return}const n=this.createMouseEventFromTouch(e);if(!n)return;this.touchLatestEvent=n;const i=this.getTouchPoint(e);if(!this.touchLongPressActive&&this.touchStartPosition&&i&&this.touchStartPosition.distanceTo(i)>this.mobileLongPressMoveTolerance&&this.clearTouchLongPressTimer(),!this.touchLongPressActive)return;e.preventDefault(),e.stopImmediatePropagation();const r=this.createRaycasterFromMouseEvent(n),s=r.intersectObjects(this.getInteractiveMeshes(),!1);this.handleMouseMove({raycaster:r,intersects:s})};handleNativeTouchEnd=e=>{this.isMobileDevice()&&(this.clearTouchLongPressTimer(),this.touchLongPressActive&&(e.preventDefault(),e.stopImmediatePropagation(),this.handleMouseUp({button:0})),this.resetTouchLongPressState())};handleNativeKeyDown=e=>{e.key==="Control"&&(this.isCtrlDown=!0)};handleNativeKeyUp=e=>{e.key==="Control"&&(this.isCtrlDown=!1,this.isDrag&&this.handleMouseUp({button:0}),this.resetMeshOpacity())};constructor(e,n){this.engine=e,this.meshs=[]}active(){this.isActive||(this.attachListeners(),this.init(),this.setTransformControlsVisible(!0),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(n=>{n.name.includes("face")||(n.visible=!0)})}),this.isActive=!0)}disActive(){this.init(!1),this.isActive=!1,this.detachListeners(),this.handleMouseUp({button:0},!1),this.setTransformControlsVisible(!1),this.clearClippingBoxFill(),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(n=>{n.name.includes("face")||(n.visible=!1)})})}disabled(){this.isActive=!1,this.detachListeners(),this.handleMouseUp({button:0},!1),this.setTransformControlsVisible(!1),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(n=>{n.name.includes("face")||(n.visible=!1)})})}recover(){this.isActive||(this.attachListeners(),this.setTransformControlsVisible(!0),this.updateClippingBoxFill(),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(n=>{n.name.includes("face")||(n.visible=!0)})}),this.isActive=!0)}init(e=!0){const n=this.engine.octreeBox.getBoundingBox();n.min.x-=.1,n.min.y-=.1,n.min.z-=.1,n.max.x+=.1,n.max.y+=.1,n.max.z+=.1,this.maxBox=JSON.parse(JSON.stringify(n)),this.box=n,this.updata_face(n),e&&this.updateClippingBoxFill()}getboxXyz(){return{minX:this.box.min.x,minY:this.box.min.y,minZ:this.box.min.z,maxX:this.box.max.x,maxY:this.box.max.y,maxZ:this.box.max.z}}setboxXyz(e){this.box.min.x=e.minX,this.box.min.y=e.minY,this.box.min.z=e.minZ,this.box.max.x=e.maxX,this.box.max.y=e.maxY,this.box.max.z=e.maxZ,this.updata_face(this.box),this.updateClippingBoxFill()}setBox(e){this.box=e,this.updata_face(e),this.updateClippingBoxFill()}reverseBox(){}handleMouseDown(e){const n=e.intersects??e.raycaster.intersectObjects(this.getInteractiveMeshes(),!1);if(n!=null&&n.length>0){this.clearClippingBoxFill();const i=n[0];this.isDrag=!0,this.pickPoint=i.point.clone(),this.pickMesh=i.object;const r=this.pickMesh?.userData?.dragNormal?.clone?.(),s=i.face?.normal?.clone?.();if(this.pickNormal=(r??s??new H(0,0,1)).clone().normalize(),this.engine.controls.enabled=!1,this.box_={min:this.box.min.clone(),max:this.box.max.clone()},this.pickNormal.y==0){const o=new Zi;o.setFromNormalAndCoplanarPoint(new H(0,1,0),this.pickPoint),this.plane=o}else{const o=new H(this.engine.camera.position.x,this.pickPoint.y,this.engine.camera.position.z),a=new Zi;a.setFromNormalAndCoplanarPoint(o.clone().sub(this.pickPoint.clone()).setLength(1),this.pickPoint),this.plane=a}}else this.isDrag=!1}handleMouseUp(e,n=!0){this.isDrag=!1,this.pickPoint=null,this.pickNormal=null,this.pickMesh=null,this.plane=null,this.engine.controls.enabled=!0,n&&this.updateClippingBoxFill()}clampVector3(e,n,i){return new H(Math.max(n.x,Math.min(i.x,e.x)),Math.max(n.y,Math.min(i.y,e.y)),Math.max(n.z,Math.min(i.z,e.z)))}handleMouseMove(e){this.resetMeshOpacity();const n=e.intersects??e.raycaster.intersectObjects(this.getInteractiveMeshes(),!1);if(n!=null&&n.length>0&&(n[0].object.material.opacity=this.faceHoverOpacity),this.pickPoint!=null){const i=new H;if(e.raycaster.ray.intersectPlane(this.plane,i)){const r=i.clone().sub(this.pickPoint.clone()).dot(this.pickNormal.clone());if(!!this.pickMesh?.userData?.isMinFace){const o=this.box_.min.clone().add(this.pickNormal.clone().setLength(r));this.box.min=this.clampVector3(o,this.maxBox.min,this.box.max)}else{const o=this.box_.max.clone().add(this.pickNormal.clone().setLength(r));this.box.max=this.clampVector3(o,this.box.min,this.maxBox.max)}this.updata_face(this.box),this.calculate_ratio()}}}calculate_ratio(){const e=this.maxBox.max.x-this.maxBox.min.x,n=this.maxBox.max.y-this.maxBox.min.y,i=this.maxBox.max.z-this.maxBox.min.z,r=this.toPercent((this.box.min.x-this.maxBox.min.x)/e*100),s=this.toPercent((this.box.max.x-this.maxBox.min.x)/e*100),o=this.toPercent((this.box.min.y-this.maxBox.min.y)/n*100),a=this.toPercent((this.box.max.y-this.maxBox.min.y)/n*100),c=this.toPercent((this.box.min.z-this.maxBox.min.z)/i*100),l=this.toPercent((this.box.max.z-this.maxBox.min.z)/i*100),u={x:{min:r,max:s},y:{min:o,max:a},z:{min:c,max:l}};this.engine.events.trigger(Yo.SectionMove,u)}toPercent(e){return e<0?0:e>100?100:e}getInteractiveMeshes(){return this.meshs.filter(e=>e.type==="Mesh")}createRaycasterFromMouseEvent(e){const n=new Da,i=new Ye,r=this.engine.renderer.domElement.clientWidth,s=this.engine.renderer.domElement.clientHeight;return i.x=e.offsetX/r*2-1,i.y=-(e.offsetY/s)*2+1,n.setFromCamera(i,this.engine.camera),n}isMobileDevice(){return this.engine?.deviceModule?.isMobile?.()===!0||this.engine?.deviceType==="mobile"}getTouchPoint(e){const n=e.touches[0]||e.changedTouches[0];return n?new Ye(n.clientX,n.clientY):null}createMouseEventFromTouch(e){const n=e.touches[0]||e.changedTouches[0],i=this.engine.renderer?.domElement;if(!n||!i)return null;const r=i.getBoundingClientRect();return{offsetX:n.clientX-r.left,offsetY:n.clientY-r.top,clientX:n.clientX,clientY:n.clientY,button:0}}clearTouchLongPressTimer(){this.touchLongPressTimer!=null&&(clearTimeout(this.touchLongPressTimer),this.touchLongPressTimer=null)}resetTouchLongPressState(){this.clearTouchLongPressTimer(),this.touchLongPressActive=!1,this.touchStartPosition=null,this.touchLatestEvent=null}attachListeners(){if(this.listenersAttached)return;const e=this.engine.renderer?.domElement;e&&(e.addEventListener("mousedown",this.handleNativeMouseDown,!0),e.addEventListener("mousemove",this.handleNativeMouseMove,!0),e.addEventListener("mouseup",this.handleNativeMouseUp,!0),e.addEventListener("touchstart",this.handleNativeTouchStart,{capture:!0,passive:!1}),e.addEventListener("touchmove",this.handleNativeTouchMove,{capture:!0,passive:!1}),e.addEventListener("touchend",this.handleNativeTouchEnd,{capture:!0,passive:!1}),e.addEventListener("touchcancel",this.handleNativeTouchEnd,{capture:!0,passive:!1}),window.addEventListener("keydown",this.handleNativeKeyDown),window.addEventListener("keyup",this.handleNativeKeyUp),this.listenersAttached=!0)}detachListeners(){if(!this.listenersAttached)return;const e=this.engine.renderer?.domElement;e&&(e.removeEventListener("mousedown",this.handleNativeMouseDown,!0),e.removeEventListener("mousemove",this.handleNativeMouseMove,!0),e.removeEventListener("mouseup",this.handleNativeMouseUp,!0),e.removeEventListener("touchstart",this.handleNativeTouchStart,!0),e.removeEventListener("touchmove",this.handleNativeTouchMove,!0),e.removeEventListener("touchend",this.handleNativeTouchEnd,!0),e.removeEventListener("touchcancel",this.handleNativeTouchEnd,!0)),window.removeEventListener("keydown",this.handleNativeKeyDown),window.removeEventListener("keyup",this.handleNativeKeyUp),this.listenersAttached=!1,this.isCtrlDown=!1,this.resetTouchLongPressState()}resetMeshOpacity(){this.getInteractiveMeshes().forEach(e=>{e.material&&(e.material.opacity=this.faceIdleOpacity)})}updateClippingBoxFill(){const e=(Array.isArray(this.engine.sectionPlane)?this.engine.sectionPlane:[]).slice(0,6).filter(n=>n instanceof Zi);if(e.length===0){this.clearClippingBoxFill();return}this.engine.clipping?.clippingCSGSimple?.updataFaces?.(e)}clearClippingBoxFill(){this.engine.clipping?.clippingCSGSimple?.clear?.()}getFaceTransformOffset(){if(!this.box)return .06;const e=this.box.min.distanceTo(this.box.max);return Math.max(e*.015,.06)}keepSingleDirectionArrow(e,n="X"){const i=e.getHelper(),r=[];i.traverse(s=>{if(s?.name!==n||!s.geometry)return;const o=s.geometry;o.boundingBox||o.computeBoundingBox();const a=o.boundingBox;if(!a)return;const c=a.getCenter(new H);if(!(n==="X"&&c.x<0||n==="Y"&&c.y<0||n==="Z"&&c.z<0))return;const u=o.parameters,h=u&&u.radiusTop===0&&u.radiusBottom===.04&&u.height===.1,d=u&&u.radiusTop===.2&&u.radiusBottom===0&&u.height===.6;(h||d)&&r.push(s)}),r.forEach(s=>{s.parent?.remove(s)})}setTransformControlsVisible(e){this.transformControls.forEach(n=>{n.enabled=e}),this.transformHelpers.forEach(n=>{n.visible=e}),this.transformAnchors.forEach(n=>{n.visible=e}),e||(this.engine.controls.enabled=!0)}ensureFaceTransformControl(e){if(this.transformControls.has(e)&&this.transformAnchors.has(e))return;const n=this.engine.renderer?.domElement,i=this.engine.camera;if(!n||!i)return;const r=new Ni;r.name=`SectionBoxTransformAnchor_${e}`,r.visible=this.isActive,this.engine.scene.add(r);const s=new tN(i,n);s.name=`SectionBoxTransformControl_${e}`,s.setMode("translate"),s.setSpace("local"),s.showX=!0,s.showY=!1,s.showZ=!1,s.size=this.transformHandleSize,s.setColors(this.transformHandleColor,this.transformHandleColor,this.transformHandleColor,this.transformHandleHoverColor),s.enabled=this.isActive,s.attach(r),this.keepSingleDirectionArrow(s,"X"),s.addEventListener("dragging-changed",a=>{this.engine.controls.enabled=!a.value,a.value===!0?this.clearClippingBoxFill():this.updateClippingBoxFill()}),s.addEventListener("objectChange",()=>{this.handleTransformObjectChange(e)});const o=s.getHelper();o.userData.excludeFromAmbientOcclusion=!0,o.visible=this.isActive,this.engine.scene.add(o),this.transformAnchors.set(e,r),this.transformControls.set(e,s),this.transformHelpers.set(e,o)}updateFaceTransformControl(e,n,i,r){this.ensureFaceTransformControl(e);const s=this.transformAnchors.get(e),o=this.transformControls.get(e);if(!s||!o)return;const a=this.getFaceTransformOffset(),c=new ni().setFromUnitVectors(new H(1,0,0),n.clone().normalize()),l=i.clone().add(n.clone().setLength(a));this.faceMetaMap.set(e,{normal:n.clone().normalize(),isMinFace:r,center:i.clone()}),this.isSyncingTransform=!0,s.position.copy(l),s.quaternion.copy(c),s.visible=this.isActive,o.object!==s&&o.attach(s),o.enabled=this.isActive;const u=this.transformHelpers.get(e);u&&(u.visible=this.isActive),this.isSyncingTransform=!1}getDominantAxis(e){const n=Math.abs(e.x),i=Math.abs(e.y),r=Math.abs(e.z);return n>=i&&n>=r?"x":i>=n&&i>=r?"y":"z"}handleTransformObjectChange(e){if(this.isSyncingTransform)return;const n=this.transformAnchors.get(e),i=this.faceMetaMap.get(e);if(!n||!i||!this.box||!this.maxBox)return;const r=i.normal,s=this.getDominantAxis(r),o=this.getFaceTransformOffset(),a=r[s],c=n.position[s]-a*o;if(i.isMinFace){const l=this.maxBox.min[s],u=this.box.max[s];this.box.min[s]=Math.max(l,Math.min(u,c))}else{const l=this.box.min[s],u=this.maxBox.max[s];this.box.max[s]=Math.max(l,Math.min(u,c))}this.updata_face(this.box),this.calculate_ratio()}updata_face(e){let n=this.engine.scene.children.find(r=>r.type=="Group"&&r.name=="ClippingBox");n==null&&(n=new $r,n.name="ClippingBox",this.engine.scene.add(n)),[{name:"前",normal:new H(0,0,-1),isMinFace:!0,planePoint:e.min,vertices:[new H(e.min.x,e.max.y,e.min.z),new H(e.max.x,e.max.y,e.min.z),new H(e.max.x,e.min.y,e.min.z),new H(e.min.x,e.min.y,e.min.z)]},{name:"后",normal:new H(0,0,1),isMinFace:!1,planePoint:e.max,vertices:[new H(e.min.x,e.min.y,e.max.z),new H(e.max.x,e.min.y,e.max.z),new H(e.max.x,e.max.y,e.max.z),new H(e.min.x,e.max.y,e.max.z)]},{name:"右",normal:new H(1,0,0),isMinFace:!1,planePoint:e.max,vertices:[new H(e.max.x,e.min.y,e.max.z),new H(e.max.x,e.min.y,e.min.z),new H(e.max.x,e.max.y,e.min.z),new H(e.max.x,e.max.y,e.max.z)]},{name:"左",normal:new H(-1,0,0),isMinFace:!0,planePoint:e.min,vertices:[new H(e.min.x,e.min.y,e.min.z),new H(e.min.x,e.min.y,e.max.z),new H(e.min.x,e.max.y,e.max.z),new H(e.min.x,e.max.y,e.min.z)]},{name:"顶",normal:new H(0,1,0),isMinFace:!1,planePoint:e.max,vertices:[new H(e.min.x,e.max.y,e.max.z),new H(e.max.x,e.max.y,e.max.z),new H(e.max.x,e.max.y,e.min.z),new H(e.min.x,e.max.y,e.min.z)]},{name:"底",normal:new H(0,-1,0),isMinFace:!0,planePoint:e.min,vertices:[new H(e.min.x,e.min.y,e.min.z),new H(e.max.x,e.min.y,e.min.z),new H(e.max.x,e.min.y,e.max.z),new H(e.min.x,e.min.y,e.max.z)]}].forEach(r=>{this.createFace(n,r.vertices,r.normal,r.name,r.isMinFace,r.planePoint)}),zj(this.engine).forEach(r=>{r.material&&Array.isArray(r.material)?r.material.forEach(s=>{s.clippingPlanes=this.engine.sectionPlane}):r.material.clippingPlanes=this.engine.sectionPlane})}createFace(e,n,i,r,s,o){const a=new Dn,c=new Float32Array([n[0].x,n[0].y,n[0].z,n[1].x,n[1].y,n[1].z,n[2].x,n[2].y,n[2].z,n[3].x,n[3].y,n[3].z]),l=[0,2,1,0,3,2];a.setAttribute("position",new ji(c,3)),a.setIndex(l);let u=this.meshs.find(A=>A.name===r);if(u==null){const A=new Xi({color:65280,transparent:!0,opacity:this.faceIdleOpacity,side:tr});A.polygonOffset=!0,A.polygonOffsetFactor=1,A.polygonOffsetUnits=4,u=new bt(a,A),u.name=r,e.add(u),this.meshs.push(u)}else u.geometry=a;u.userData={dragNormal:i.clone(),isMinFace:s,faceName:r,excludeFromAmbientOcclusion:!0};const h=new Float32Array([n[0].x,n[0].y,n[0].z,n[1].x,n[1].y,n[1].z,n[2].x,n[2].y,n[2].z,n[3].x,n[3].y,n[3].z,n[0].x,n[0].y,n[0].z]),d=new Bs({color:255}),p=new Dn;p.setAttribute("position",new ji(h,3));let m=this.meshs.find(A=>A.name===r+"Line");m==null?(m=new ho(p,d),m.name=r+"Line",e.add(m),this.meshs.push(m)):(m.geometry=p,m.material=d);const g=new H;n.forEach(A=>g.add(A)),g.multiplyScalar(1/n.length),this.updateFaceTransformControl(r,i,g,s);const y=this.engine.sectionPlane.find(A=>A.name==r);y&&y.setFromNormalAndCoplanarPoint(i.clone().setLength(-1),o)}}class PGe{engine;isActive=!1;isDrag=!1;isCtrlDown=!1;listenersAttached=!1;meshs=[];box=null;pickPoint=null;pickNormal=null;plane=null;angleX=0;angleY=0;angleZ=0;direction=1;normal=new H(0,0,1);distance=0;center=null;current_center=null;dragStartDistance=0;dragStartCenter=null;idleOpacity=0;hoverOpacity=.05;transformControl=null;transformAnchor=null;transformHelper=null;rotateControl=null;rotateAnchor=null;rotateHelper=null;rotatePivot=null;isSyncingTransformControl=!1;isSyncingRotateControl=!1;activeControlMode=null;moveEpsilon=1e-5;transformHandleSize=1.15;rotateHandleSize=.8;transformHandleColor=255;transformHandleHoverColor=16776960;mobileLongPressDelay=2e3;mobileLongPressMoveTolerance=10;touchLongPressTimer=null;touchLongPressActive=!1;touchStartPosition=null;touchLatestEvent=null;handleNativePointerDown=e=>{if(e.button!==0||!this.isActive)return;this.transformControl?.dragging!==!0&&this.rotateControl?.dragging!==!0&&this.releaseControlModeLock();const n=this.pickControlModeFromPointer(e);n&&this.lockControlMode(n)};handleNativePointerUp=()=>{window.setTimeout(()=>{this.transformControl?.dragging===!0||this.rotateControl?.dragging===!0||this.releaseControlModeLock()},0)};handleNativeMouseDown=e=>{if(e.button!==0||!(this.isCtrlDown||e.ctrlKey))return;const n=this.createRaycasterFromMouseEvent(e),i=n.intersectObjects(this.getInteractiveMeshes(),!1);i.length!==0&&(e.preventDefault(),e.stopImmediatePropagation(),this.handleMouseDown({button:e.button,raycaster:n,intersects:i}))};handleNativeMouseMove=e=>{if(!this.isDrag&&!(this.isCtrlDown||e.ctrlKey)){this.resetMeshOpacity();return}const n=this.createRaycasterFromMouseEvent(e),i=n.intersectObjects(this.getInteractiveMeshes(),!1);this.isDrag&&(e.preventDefault(),e.stopImmediatePropagation()),this.handleMouseMove({raycaster:n,intersects:i})};handleNativeMouseUp=e=>{e.button!==0||!this.isDrag||(e.preventDefault(),e.stopImmediatePropagation(),this.handleMouseUp({button:e.button}))};handleNativeTouchStart=e=>{if(!this.isActive||e.touches.length!==1||!this.isMobileDevice()){this.resetTouchLongPressState();return}const n=this.createMouseEventFromTouch(e);if(!n)return;if(this.createRaycasterFromMouseEvent(n).intersectObjects(this.getInteractiveMeshes(),!1).length===0){this.resetTouchLongPressState();return}e.preventDefault(),e.stopImmediatePropagation(),this.resetTouchLongPressState(),this.touchLatestEvent=n,this.touchStartPosition=this.getTouchPoint(e),this.touchLongPressTimer=window.setTimeout(()=>{const s=this.touchLatestEvent;if(!s||!this.isActive)return;const o=this.createRaycasterFromMouseEvent(s),a=o.intersectObjects(this.getInteractiveMeshes(),!1);a.length!==0&&(this.touchLongPressActive=!0,this.handleMouseDown({button:0,raycaster:o,intersects:a}))},this.mobileLongPressDelay)};handleNativeTouchMove=e=>{if(!this.isMobileDevice())return;if(e.touches.length!==1){this.resetTouchLongPressState();return}const n=this.createMouseEventFromTouch(e);if(!n)return;this.touchLatestEvent=n;const i=this.getTouchPoint(e);if(!this.touchLongPressActive&&this.touchStartPosition&&i&&this.touchStartPosition.distanceTo(i)>this.mobileLongPressMoveTolerance&&this.clearTouchLongPressTimer(),!this.touchLongPressActive)return;e.preventDefault(),e.stopImmediatePropagation();const r=this.createRaycasterFromMouseEvent(n),s=r.intersectObjects(this.getInteractiveMeshes(),!1);this.handleMouseMove({raycaster:r,intersects:s})};handleNativeTouchEnd=e=>{this.isMobileDevice()&&(this.clearTouchLongPressTimer(),this.touchLongPressActive&&(e.preventDefault(),e.stopImmediatePropagation(),this.handleMouseUp({button:0})),this.resetTouchLongPressState())};handleNativeKeyDown=e=>{e.key==="Control"&&(this.isCtrlDown=!0)};handleNativeKeyUp=e=>{e.key==="Control"&&(this.isCtrlDown=!1,this.isDrag&&this.handleMouseUp({button:0}),this.resetMeshOpacity())};handleTransformObjectChange=()=>{if(this.isSyncingTransformControl||this.activeControlMode==="rotate"||this.rotateControl?.dragging===!0||!this.transformAnchor||!this.center||!this.current_center)return;const e=this.normal.clone().normalize(),n=this.getEffectiveNormal(e),i=this.getDistanceRange(e),r=this.getTransformHandleOffset(),s=this.current_center.clone().sub(this.center).dot(e),o=this.transformAnchor.position.clone().sub(this.center).dot(e)-r*this.getDirectionSign(),a=Math.min(i.max,Math.max(i.min,o));if(Math.abs(a-Number(this.distance))>this.moveEpsilon){const c=this.current_center.clone().add(e.clone().multiplyScalar(a-s));this.updata_face(a,c)}else Math.abs(o-a)>this.moveEpsilon&&this.updateTransformControl(n)};handleRotateObjectChange=()=>{if(this.isSyncingRotateControl||this.activeControlMode==="translate"||this.transformControl?.dragging===!0||!this.rotateAnchor||!this.center||!this.current_center)return;const n=new H(0,0,1).applyQuaternion(this.rotateAnchor.quaternion).normalize().multiplyScalar(this.getDirectionSign()).normalize(),i=(this.rotatePivot??this.rotateAnchor.position??this.current_center).clone(),r=i.clone().sub(this.center).dot(n);n.lengthSq()<=this.moveEpsilon||(this.normal.copy(n),this.updata_face(r,i))};constructor(e){this.engine=e,this.meshs=[],this.box=null}active(){this.isActive!=!0&&(this.isActive=!0,this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(n=>{n.name.includes("face")&&(n.visible=!0)})}),this.attachListeners(),this.ensureTransformControl(),this.ensureRotateControl(),this.setTransformControlVisible(!0),this.applyClippingToModelMeshes(),this.init())}disActive(){this.init(),this.isActive=!1,this.detachListeners(),this.handleMouseUp({button:0},!1),this.setTransformControlVisible(!1),this.clearClippingFaceFill();const e=this.engine.sectionPlane.find(n=>n.name=="face");e&&(e.constant=1e5),this.engine.scene.children.filter(n=>n.type=="Group"&&n.name=="ClippingBox").forEach(n=>{n.children.forEach(i=>{i.name.includes("face")&&(i.visible=!1)})})}init(e){const n=this.engine.octreeBox.getBoundingBox();this.box=n,this.distance=0,this.center=new H((n.min.x+n.max.x)/2,(n.min.y+n.max.y)/2,(n.min.z+n.max.z)/2),this.current_center=this.center.clone(),!e&&this.updata_face(0)}disabled(){this.isActive=!1,this.detachListeners(),this.handleMouseUp({button:0},!1),this.setTransformControlVisible(!1),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(n=>{n.name.includes("face")&&(n.visible=!1)})})}recover(){this.isActive||(this.attachListeners(),this.setTransformControlVisible(!0),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(n=>{n.name.includes("face")&&(n.visible=!0)})}),this.isActive=!0)}setFaceAngle(e,n,i){this.angleX=e,this.angleY=n,this.angleZ=i,this.distance=0,this.normal=new H(0,1,0).applyAxisAngle(new H(1,0,0),e).applyAxisAngle(new H(0,0,1),n).applyAxisAngle(new H(0,1,0),i).normalize(),this.updata_face(0),this.updateClippingFaceFill()}setFaceNormal(e,n=0){this.normal=e.clone().normalize(),this.distance=n,this.updata_face(n),this.updateClippingFaceFill()}setFaceNormalPlaneOnly(e,n){if(this.normal=e.clone().normalize(),this.distance=n,!this.center||!this.box)return;const i=this.engine.sectionPlane?.find(r=>r.name==="face");if(i){const r=this.center.clone().add(this.normal.clone().multiplyScalar(n));i.setFromNormalAndCoplanarPoint(this.getEffectiveNormal(),r)}this.updateClippingFaceFill()}activateClippingOnly(){this.isActive||(this.isActive=!0,this.applyClippingToModelMeshes())}reverse(){this.direction=-this.getDirectionSign(),this.applyClippingToModelMeshes(),this.updata_face(this.distance),this.updateClippingFaceFill(),this.requestShadowRefresh()}getFaceAngle(){return{angleX:this.angleX,angleY:this.angleY,angleZ:this.angleZ,direction:this.direction}}updata_face(e,n){if(!this.box)return;this.distance=e;let i=this.engine.scene.children.find(T=>T.type=="Group"&&T.name=="ClippingBox");i==null&&(i=new $r,i.name="ClippingBox",this.engine.scene.add(i));const r=this.normal.clone().normalize(),s=this.getEffectiveNormal(r),o=this.center??new H((this.box.min.x+this.box.max.x)/2,(this.box.min.y+this.box.max.y)/2,(this.box.min.z+this.box.max.z)/2);this.center=o.clone();const a=n?.clone()??o.clone().add(r.clone().multiplyScalar(e)),{tangent:c,bitangent:l}=this.getPlaneBasis(r),u=this.getBoxCorners(this.box),h=this.box.min.distanceTo(this.box.max),d=Math.max(h*.02,.01);let p=1/0,m=-1/0,g=1/0,y=-1/0;u.forEach(T=>{const S=T.clone().sub(a),w=S.dot(c),E=S.dot(l);p=Math.min(p,w),m=Math.max(m,w),g=Math.min(g,E),y=Math.max(y,E)}),p-=d,m+=d,g-=d,y+=d;const A=a.clone().add(c.clone().multiplyScalar(p)).add(l.clone().multiplyScalar(g)),v=a.clone().add(c.clone().multiplyScalar(m)).add(l.clone().multiplyScalar(g)),x=a.clone().add(c.clone().multiplyScalar(m)).add(l.clone().multiplyScalar(y)),C=a.clone().add(c.clone().multiplyScalar(p)).add(l.clone().multiplyScalar(y));this.current_center=a.clone(),this.createFace(i,[A,v,x,C],r,"face"),this.updateTransformControl(s),this.updateRotateControl(s)}createFace(e,n,i,r){const s=new Dn,o=new Float32Array([n[0].x,n[0].y,n[0].z,n[1].x,n[1].y,n[1].z,n[2].x,n[2].y,n[2].z,n[3].x,n[3].y,n[3].z]),a=this.getEffectiveNormal(i),c=this.getDirectionSign()===1?[0,1,2,0,2,3]:[0,2,1,0,3,2];s.setAttribute("position",new ji(o,3)),s.setIndex(c),s.computeVertexNormals();let l=this.meshs.find(g=>g.name==r);if(l==null){const g=new Xi({color:65280,transparent:!0,opacity:this.idleOpacity,side:tr});g.polygonOffset=!0,g.polygonOffsetFactor=1,g.polygonOffsetUnits=4,l=new bt(s,g),l.name=r,e.add(l),this.meshs.push(l)}else l.geometry=s;l.normal=a.clone(),l.userData.excludeFromAmbientOcclusion=!0;const u=new Float32Array([n[0].x,n[0].y,n[0].z,n[1].x,n[1].y,n[1].z,n[2].x,n[2].y,n[2].z,n[3].x,n[3].y,n[3].z,n[0].x,n[0].y,n[0].z]),h=new Bs({color:255}),d=new Dn;d.setAttribute("position",new ji(u,3));let p=this.meshs.find(g=>g.name==r+"Line");p==null?(p=new ho(d,h),p.name=r+"Line",e.add(p),this.meshs.push(p)):(p.geometry=d,p.material=h);const m=this.engine.sectionPlane.find(g=>g.name==r);m&&this.current_center&&m.setFromNormalAndCoplanarPoint(a,this.current_center)}getDirectionSign(){return Number(this.direction)===-1?-1:1}getEffectiveNormal(e=this.normal){return e.clone().normalize().multiplyScalar(this.getDirectionSign())}applyClippingToModelMeshes(){const e=this.engine.sectionPlane?.find?.(n=>n.name==="face");zj(this.engine).forEach(n=>{this.applyClippingToMaterial(n.material),this.engine.clipping.clippingStencil?.addMesh(e,n)}),this.requestShadowRefresh()}applyClippingToMaterial(e){if(Array.isArray(e)){e.forEach(n=>this.applyClippingToMaterial(n));return}e&&(e.clippingPlanes=this.engine.sectionPlane,e.clipShadows=!0,e.shadowSide=tr,e.needsUpdate=!0)}requestShadowRefresh(){const e=this.engine?.renderer?.shadowMap;e&&(e.needsUpdate=!0);const n=this.engine?.scene?.dirLight;n?.shadow&&(n.shadow.needsUpdate=!0)}lockControlMode(e){this.activeControlMode=e,this.applyControlModeLock()}releaseControlModeLock(){this.activeControlMode=null,this.applyControlModeLock()}applyControlModeLock(){this.transformControl&&(this.transformControl.enabled=this.isActive&&this.activeControlMode!=="rotate"),this.rotateControl&&(this.rotateControl.enabled=this.isActive&&this.activeControlMode!=="translate")}pickControlModeFromPointer(e){const n=this.raycastTransformControlPicker(this.transformControl,e),i=this.raycastTransformControlPicker(this.rotateControl,e);return n&&i?i.distance<=n.distance?"rotate":"translate":i?"rotate":n?"translate":null}raycastTransformControlPicker(e,n){if(!e||!e.object||!this.engine?.camera||!this.engine?.renderer?.domElement)return null;const i=e._gizmo?.picker?.[e.mode];if(!i)return null;const r=this.engine.renderer.domElement.getBoundingClientRect(),s=new Ye((n.clientX-r.left)/r.width*2-1,-((n.clientY-r.top)/r.height)*2+1),o=new Da;return o.setFromCamera(s,this.engine.camera),o.intersectObject(i,!0).find(c=>c.object.visible)??null}getPlaneBasis(e){const n=new H(1,0,0),i=new H(0,1,0),r=new H(0,0,1),s=Math.abs(e.dot(n)),o=Math.abs(e.dot(i)),a=Math.abs(e.dot(r));let c=n;o<=s&&o<=a?c=i:a<=s&&a<=o&&(c=r),c=c.clone().sub(e.clone().multiplyScalar(c.dot(e))).normalize();const l=new H().crossVectors(e,c).normalize();return{tangent:c,bitangent:l}}getBoxCorners(e){return[new H(e.min.x,e.min.y,e.min.z),new H(e.min.x,e.min.y,e.max.z),new H(e.min.x,e.max.y,e.min.z),new H(e.min.x,e.max.y,e.max.z),new H(e.max.x,e.min.y,e.min.z),new H(e.max.x,e.min.y,e.max.z),new H(e.max.x,e.max.y,e.min.z),new H(e.max.x,e.max.y,e.max.z)]}getDistanceRange(e){if(!this.box)return{min:0,max:0};const n=this.center??new H((this.box.min.x+this.box.max.x)/2,(this.box.min.y+this.box.max.y)/2,(this.box.min.z+this.box.max.z)/2),i=this.getBoxCorners(this.box);let r=1/0,s=-1/0;return i.forEach(o=>{const a=o.clone().sub(n).dot(e);r=Math.min(r,a),s=Math.max(s,a)}),{min:r,max:s}}getInteractiveMeshes(){return this.meshs.filter(e=>e.type==="Mesh")}getTransformHandleOffset(){if(!this.box)return .06;const e=this.box.min.distanceTo(this.box.max);return Math.max(e*.015,.06)}getPlaneQuaternion(e){const{tangent:n,bitangent:i}=this.getPlaneBasis(e),r=new xt().makeBasis(n,i,e.clone().normalize());return new ni().setFromRotationMatrix(r)}keepSingleDirectionArrow(e,n="X"){const i=e.getHelper(),r=[];i.traverse(s=>{if(s?.name!==n||!s.geometry)return;const o=s.geometry;o.boundingBox||o.computeBoundingBox();const a=o.boundingBox;if(!a)return;const c=a.getCenter(new H);if(!(n==="X"&&c.x<0||n==="Y"&&c.y<0||n==="Z"&&c.z<0))return;const u=o.parameters,h=u&&u.radiusTop===0&&u.radiusBottom===.04&&u.height===.1,d=u&&u.radiusTop===.2&&u.radiusBottom===0&&u.height===.6;(h||d)&&r.push(s)}),r.forEach(s=>{s.parent?.remove(s)})}ensureTransformControl(){if(this.transformControl&&this.transformAnchor)return;const e=this.engine.renderer?.domElement,n=this.engine.camera;if(!e||!n)return;const i=new Ni;i.name="SectionFaceTransformAnchor",i.visible=this.isActive,this.engine.scene.add(i);const r=new tN(n,e);r.name="SectionFaceTransformControl",r.setMode("translate"),r.setSpace("local"),r.showX=!0,r.showY=!1,r.showZ=!1,r.size=this.transformHandleSize,r.setColors(this.transformHandleColor,this.transformHandleColor,this.transformHandleColor,this.transformHandleHoverColor),r.enabled=this.isActive,r.attach(i),this.keepSingleDirectionArrow(r,"X"),r.addEventListener("dragging-changed",o=>{this.engine.controls.enabled=!o.value,o.value===!0?(this.lockControlMode("translate"),this.clearClippingFaceFill()):(this.updateClippingFaceFill(),this.releaseControlModeLock())}),r.addEventListener("objectChange",this.handleTransformObjectChange);const s=r.getHelper();s.userData.excludeFromAmbientOcclusion=!0,s.visible=this.isActive,this.engine.scene.add(s),this.transformAnchor=i,this.transformControl=r,this.transformHelper=s}ensureRotateControl(){if(this.rotateControl&&this.rotateAnchor)return;const e=this.engine.renderer?.domElement,n=this.engine.camera;if(!e||!n)return;const i=new Ni;i.name="SectionFaceRotateAnchor",i.visible=this.isActive,this.engine.scene.add(i);const r=new tN(n,e);r.name="SectionFaceRotateControl",r.setMode("rotate"),r.setSpace("local"),r.showX=!0,r.showY=!0,r.showZ=!1,r.size=this.rotateHandleSize,r.setColors(this.transformHandleColor,this.transformHandleColor,this.transformHandleColor,this.transformHandleHoverColor),r.enabled=this.isActive,r.attach(i),r.addEventListener("dragging-changed",o=>{this.engine.controls.enabled=!o.value,o.value===!0?(this.lockControlMode("rotate"),this.rotatePivot=(this.current_center??this.rotateAnchor?.position??null)?.clone?.()??null,this.clearClippingFaceFill()):(this.rotatePivot=null,this.updateClippingFaceFill(),this.releaseControlModeLock())}),r.addEventListener("objectChange",this.handleRotateObjectChange);const s=r.getHelper();s.userData.excludeFromAmbientOcclusion=!0,s.visible=this.isActive,this.engine.scene.add(s),this.rotateAnchor=i,this.rotateControl=r,this.rotateHelper=s}setTransformControlVisible(e){this.ensureTransformControl(),this.ensureRotateControl(),e||(this.activeControlMode=null),this.transformControl&&(this.transformControl.enabled=e&&this.activeControlMode!=="rotate"),this.transformHelper&&(this.transformHelper.visible=e),this.transformAnchor&&(this.transformAnchor.visible=e),this.rotateControl&&(this.rotateControl.enabled=e&&this.activeControlMode!=="translate"),this.rotateHelper&&(this.rotateHelper.visible=e),this.rotateAnchor&&(this.rotateAnchor.visible=e),e||(this.engine.controls.enabled=!0)}updateTransformControl(e){if(this.ensureTransformControl(),!this.transformControl||!this.transformAnchor||!this.current_center)return;const n=this.getTransformHandleOffset(),i=this.current_center.clone().add(e.clone().setLength(n)),r=new ni().setFromUnitVectors(new H(1,0,0),e.clone().normalize().multiplyScalar(-1));this.isSyncingTransformControl=!0,this.transformAnchor.position.copy(i),this.transformAnchor.quaternion.copy(r),this.transformAnchor.visible=this.isActive,this.transformControl.object!==this.transformAnchor&&this.transformControl.attach(this.transformAnchor),this.applyControlModeLock(),this.transformHelper&&(this.transformHelper.visible=this.isActive),this.isSyncingTransformControl=!1}updateRotateControl(e){this.ensureRotateControl(),!(!this.rotateControl||!this.rotateAnchor||!this.current_center)&&(this.isSyncingRotateControl=!0,this.rotateAnchor.position.copy(this.current_center),this.rotateAnchor.quaternion.copy(this.getPlaneQuaternion(e)),this.rotateAnchor.visible=this.isActive,this.rotateControl.object!==this.rotateAnchor&&this.rotateControl.attach(this.rotateAnchor),this.applyControlModeLock(),this.rotateHelper&&(this.rotateHelper.visible=this.isActive),this.isSyncingRotateControl=!1)}createRaycasterFromMouseEvent(e){const n=new Da,i=new Ye,r=this.engine.renderer.domElement.clientWidth,s=this.engine.renderer.domElement.clientHeight;return i.x=e.offsetX/r*2-1,i.y=-(e.offsetY/s)*2+1,n.setFromCamera(i,this.engine.camera),n}isMobileDevice(){return this.engine?.deviceModule?.isMobile?.()===!0||this.engine?.deviceType==="mobile"}getTouchPoint(e){const n=e.touches[0]||e.changedTouches[0];return n?new Ye(n.clientX,n.clientY):null}createMouseEventFromTouch(e){const n=e.touches[0]||e.changedTouches[0],i=this.engine.renderer?.domElement;if(!n||!i)return null;const r=i.getBoundingClientRect();return{offsetX:n.clientX-r.left,offsetY:n.clientY-r.top,clientX:n.clientX,clientY:n.clientY,button:0}}clearTouchLongPressTimer(){this.touchLongPressTimer!=null&&(clearTimeout(this.touchLongPressTimer),this.touchLongPressTimer=null)}resetTouchLongPressState(){this.clearTouchLongPressTimer(),this.touchLongPressActive=!1,this.touchStartPosition=null,this.touchLatestEvent=null}attachListeners(){if(this.listenersAttached)return;const e=this.engine.renderer?.domElement;e&&(e.addEventListener("pointerdown",this.handleNativePointerDown,!0),e.addEventListener("pointerup",this.handleNativePointerUp,!0),e.addEventListener("pointercancel",this.handleNativePointerUp,!0),e.addEventListener("pointerleave",this.handleNativePointerUp,!0),e.addEventListener("mousedown",this.handleNativeMouseDown,!0),e.addEventListener("mousemove",this.handleNativeMouseMove,!0),e.addEventListener("mouseup",this.handleNativeMouseUp,!0),e.addEventListener("touchstart",this.handleNativeTouchStart,{capture:!0,passive:!1}),e.addEventListener("touchmove",this.handleNativeTouchMove,{capture:!0,passive:!1}),e.addEventListener("touchend",this.handleNativeTouchEnd,{capture:!0,passive:!1}),e.addEventListener("touchcancel",this.handleNativeTouchEnd,{capture:!0,passive:!1}),window.addEventListener("keydown",this.handleNativeKeyDown),window.addEventListener("keyup",this.handleNativeKeyUp),this.listenersAttached=!0)}detachListeners(){if(!this.listenersAttached)return;const e=this.engine.renderer?.domElement;e&&(e.removeEventListener("pointerdown",this.handleNativePointerDown,!0),e.removeEventListener("pointerup",this.handleNativePointerUp,!0),e.removeEventListener("pointercancel",this.handleNativePointerUp,!0),e.removeEventListener("pointerleave",this.handleNativePointerUp,!0),e.removeEventListener("mousedown",this.handleNativeMouseDown,!0),e.removeEventListener("mousemove",this.handleNativeMouseMove,!0),e.removeEventListener("mouseup",this.handleNativeMouseUp,!0),e.removeEventListener("touchstart",this.handleNativeTouchStart,!0),e.removeEventListener("touchmove",this.handleNativeTouchMove,!0),e.removeEventListener("touchend",this.handleNativeTouchEnd,!0),e.removeEventListener("touchcancel",this.handleNativeTouchEnd,!0)),window.removeEventListener("keydown",this.handleNativeKeyDown),window.removeEventListener("keyup",this.handleNativeKeyUp),this.listenersAttached=!1,this.isCtrlDown=!1,this.releaseControlModeLock(),this.resetTouchLongPressState()}resetMeshOpacity(){this.getInteractiveMeshes().forEach(e=>{e.material&&(e.material.opacity=this.idleOpacity)})}updateClippingFaceFill(){const e=this.engine.sectionPlane?.find?.(n=>n.name==="face");if(e){this.engine.clipping?.clippingCSGSimple?.updataFace?.(e);return}this.clearClippingFaceFill()}clearClippingFaceFill(){this.engine.clipping?.clippingCSGSimple?.clear?.()}handleMouseDown(e){const n=e.intersects??e.raycaster.intersectObjects(this.getInteractiveMeshes(),!1);if(n!=null&&n.length>0){this.clearClippingFaceFill();const i=n[0],r=i.point.clone();this.isDrag=!0,this.pickPoint=r;const o=(i.face?.normal?.clone()??this.normal.clone()).clone(),a=this.getEffectiveNormal();if(o.dot(a)<0&&o.multiplyScalar(-1),o.normalize(),this.pickNormal=o,this.engine.controls.enabled=!1,this.dragStartDistance=Number(this.distance)||0,this.dragStartCenter=this.current_center?.clone()??null,o.y==0){const c=new Zi;c.setFromNormalAndCoplanarPoint(new H(0,1,0),r),this.plane=c}else{const c=new H(this.engine.camera.position.x,r.y,this.engine.camera.position.z),l=new Zi;l.setFromNormalAndCoplanarPoint(c.clone().sub(r.clone()).setLength(1),r),this.plane=l}}else this.isDrag=!1}handleMouseUp(e,n=!0){this.isDrag=!1,this.pickPoint=null,this.pickNormal=null,this.plane=null,this.dragStartCenter=null,this.engine.controls.enabled=!0,n&&this.updateClippingFaceFill()}handleMouseMove(e){this.resetMeshOpacity();const n=e.intersects??e.raycaster.intersectObjects(this.getInteractiveMeshes(),!1);n!=null&&n.length>0&&(n[0].object.material.opacity=this.hoverOpacity);const i=this.pickPoint,r=this.pickNormal,s=this.plane;if(i!=null&&r!=null&&s!=null){const o=new H;if(e.raycaster.ray.intersectPlane(s,o)){const a=o.clone().sub(i.clone()).dot(r.clone()),c=this.getDistanceRange(this.normal.clone().normalize()),l=r.dot(this.normal.clone().normalize())>=0?1:-1,u=this.dragStartDistance+a*l;this.distance=Math.min(c.max,Math.max(c.min,u));const h=(this.dragStartCenter??this.current_center)?.clone().add(this.normal.clone().normalize().multiplyScalar(this.distance-this.dragStartDistance));this.updata_face(this.distance,h)}}}}class DGe{engine;callback_;isActive;constructor(e){this.engine=e}init(){this.isActive=!0,this.engine.handelBehaved.init(this,{showCatch:!0}),this.engine.handelBehaved.active()}cancel(){this.isActive&&(this.engine.handelBehaved.disActive(),this.engine.interactionModule.init(),this.engine.interactionModule.active(),this.isActive=!1)}catch_face(e){this.callback_=e}handleMouseMove(e){}handleMouseClick(e){if(e.catch?.normal==null&&(e.catch.normal=e.catch.face?.normal),!e.catch?.normal||!e.catch?.point)return;let n=e.catch.normal.setLength(-1);this.engine.handelBehaved.disActive(),this.engine.interactionModule.init(),this.engine.interactionModule.active(),this.isActive=!1,this.callback_({dir:n,position:e.catch.point})}}const ooe=1e-6,RGe=ooe*.5,aoe=Math.pow(10,-Math.log10(ooe)),OGe=RGe*aoe;function Mm(t){return~~(t*aoe+OGe)}function LGe(t){return`${Mm(t.x)},${Mm(t.y)}`}function coe(t){return`${Mm(t.x)},${Mm(t.y)},${Mm(t.z)}`}function BGe(t){return`${Mm(t.x)},${Mm(t.y)},${Mm(t.z)},${Mm(t.w)}`}function NGe(t,e,n){n.direction.subVectors(e,t).normalize();const i=t.dot(n.direction);return n.origin.copy(t).addScaledVector(n.direction,-i),n}function loe(){return typeof SharedArrayBuffer<"u"}function FGe(t){if(t.buffer instanceof SharedArrayBuffer)return t;const e=t.constructor,n=t.buffer,i=new SharedArrayBuffer(n.byteLength),r=new Uint8Array(n);return new Uint8Array(i).set(r,0),new e(i)}function kGe(t,e=ArrayBuffer){return t>65535?new Uint32Array(new e(4*t)):new Uint16Array(new e(2*t))}function UGe(t,e){if(!t.index){const n=t.attributes.position.count,i=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,r=kGe(n,i);t.setIndex(new ji(r,1));for(let s=0;s<n;s++)r[s]=s}}function zGe(t){return t.index?t.index.count:t.attributes.position.count}function i6(t){return zGe(t)/3}const VGe=1e-8,jGe=new H;function HGe(t){return~~(t/3)}function GGe(t){return t%3}function uoe(t,e){return t.start-e.start}function hoe(t,e){return jGe.subVectors(e,t.origin).dot(t.direction)}function qGe(t,e,n,i=VGe){t.sort(uoe),e.sort(uoe);for(let a=0;a<t.length;a++){const c=t[a];for(let l=0;l<e.length;l++){const u=e[l];if(!(u.start>c.end)){if(c.end<u.start||u.end<c.start)continue;if(c.start<=u.start&&c.end>=u.end)s(u.end,c.end)||t.splice(a+1,0,{start:u.end,end:c.end,index:c.index}),c.end=u.start,u.start=0,u.end=0;else if(c.start>=u.start&&c.end<=u.end)s(c.end,u.end)||e.splice(l+1,0,{start:c.end,end:u.end,index:u.index}),u.end=c.start,c.start=0,c.end=0;else if(c.start<=u.start&&c.end<=u.end){const h=c.end;c.end=u.start,u.start=h}else if(c.start>=u.start&&c.end>=u.end){const h=u.end;u.end=c.start,c.start=h}else throw new Error}if(n.has(c.index)||n.set(c.index,[]),n.has(u.index)||n.set(u.index,[]),n.get(c.index).push(u.index),n.get(u.index).push(c.index),o(u)&&(e.splice(l,1),l--),o(c)){t.splice(a,1),a--;break}}}r(t),r(e);function r(a){for(let c=0;c<a.length;c++)o(a[c])&&(a.splice(c,1),c--)}function s(a,c){return Math.abs(c-a)<i}function o(a){return Math.abs(a.end-a.start)<i}}const doe=1e-5,foe=1e-4;class WGe{constructor(){this._rays=[]}addRay(e){this._rays.push(e)}findClosestRay(e){const n=this._rays,i=e.clone();i.direction.multiplyScalar(-1);let r=1/0,s=null;for(let c=0,l=n.length;c<l;c++){const u=n[c];if(o(u,e)&&o(u,i))continue;const h=a(u,e),d=a(u,i),p=Math.min(h,d);p<r&&(r=p,s=u)}return s;function o(c,l){const u=c.origin.distanceTo(l.origin)>doe;return c.direction.angleTo(l.direction)>foe||u}function a(c,l){const u=c.origin.distanceTo(l.origin),h=c.direction.angleTo(l.direction);return u/doe+h/foe}}}const r6=new H,s6=new H,aN=new mm;function YGe(t,e,n){const i=t.attributes,r=t.index,s=i.position,o=new Map,a=new Map,c=Array.from(e),l=new WGe;for(let u=0,h=c.length;u<h;u++){const d=c[u],p=HGe(d),m=GGe(d);let g=3*p+m,y=3*p+(m+1)%3;r&&(g=r.getX(g),y=r.getX(y)),r6.fromBufferAttribute(s,g),s6.fromBufferAttribute(s,y),NGe(r6,s6,aN);let A,v=l.findClosestRay(aN);v===null&&(v=aN.clone(),l.addRay(v)),a.has(v)||a.set(v,{forward:[],reverse:[],ray:v}),A=a.get(v);let x=hoe(v,r6),C=hoe(v,s6);x>C&&([x,C]=[C,x]),aN.direction.dot(v.direction)<0?A.reverse.push({start:x,end:C,index:d}):A.forward.push({start:x,end:C,index:d})}return a.forEach(({forward:u,reverse:h},d)=>{qGe(u,h,o,n),u.length===0&&h.length===0&&a.delete(d)}),{disjointConnectivityMap:o,fragmentMap:a}}const XGe=new Ye,o6=new H,$Ge=new Bi,a6=["","",""];class QGe{constructor(e=null){this.data=null,this.disjointConnections=null,this.unmatchedDisjointEdges=null,this.unmatchedEdges=-1,this.matchedEdges=-1,this.useDrawRange=!0,this.useAllAttributes=!1,this.matchDisjointEdges=!1,this.degenerateEpsilon=1e-8,e&&this.updateFrom(e)}getSiblingTriangleIndex(e,n){const i=this.data[e*3+n];return i===-1?-1:~~(i/3)}getSiblingEdgeIndex(e,n){const i=this.data[e*3+n];return i===-1?-1:i%3}getDisjointSiblingTriangleIndices(e,n){const i=e*3+n,r=this.disjointConnections.get(i);return r?r.map(s=>~~(s/3)):[]}getDisjointSiblingEdgeIndices(e,n){const i=e*3+n,r=this.disjointConnections.get(i);return r?r.map(s=>s%3):[]}isFullyConnected(){return this.unmatchedEdges===0}updateFrom(e){const{useAllAttributes:n,useDrawRange:i,matchDisjointEdges:r,degenerateEpsilon:s}=this,o=n?x:v,a=new Map,{attributes:c}=e,l=n?Object.keys(c):null,u=e.index,h=c.position;let d=i6(e);const p=d;let m=0;i&&(m=e.drawRange.start,e.drawRange.count!==1/0&&(d=~~(e.drawRange.count/3)));let g=this.data;(!g||g.length<3*p)&&(g=new Int32Array(3*p)),g.fill(-1);let y=0,A=new Set;for(let C=m,T=d*3+m;C<T;C+=3){const S=C;for(let w=0;w<3;w++){let E=S+w;u&&(E=u.getX(E)),a6[w]=o(E)}for(let w=0;w<3;w++){const E=(w+1)%3,D=a6[w],O=a6[E],P=`${O}_${D}`;if(a.has(P)){const I=S+w,_=a.get(P);g[I]=_,g[_]=I,a.delete(P),y+=2,A.delete(_)}else{const I=`${D}_${O}`,_=S+w;a.set(I,_),A.add(_)}}}if(r){const{fragmentMap:C,disjointConnectivityMap:T}=YGe(e,A,s);A.clear(),C.forEach(({forward:S,reverse:w})=>{S.forEach(({index:E})=>A.add(E)),w.forEach(({index:E})=>A.add(E))}),this.unmatchedDisjointEdges=C,this.disjointConnections=T,y=d*3-A.size}this.matchedEdges=y,this.unmatchedEdges=A.size,this.data=g;function v(C){return o6.fromBufferAttribute(h,C),coe(o6)}function x(C){let T="";for(let S=0,w=l.length;S<w;S++){const E=c[l[S]];let D;switch(E.itemSize){case 1:D=Mm(E.getX(C));break;case 2:D=LGe(XGe.fromBufferAttribute(E,C));break;case 3:D=coe(o6.fromBufferAttribute(E,C));break;case 4:D=BGe($Ge.fromBufferAttribute(E,C));break}T!==""&&(T+="|"),T+=D}return T}}}class cN extends bt{constructor(...e){super(...e),this.isBrush=!0,this._previousMatrix=new xt,this._previousMatrix.elements.fill(0)}markUpdated(){this._previousMatrix.copy(this.matrix)}isDirty(){const{matrix:e,_previousMatrix:n}=this,i=e.elements,r=n.elements;for(let s=0;s<16;s++)if(i[s]!==r[s])return!0;return!1}prepareGeometry(){const e=this.geometry,n=e.attributes,i=loe();if(i)for(const r in n){const s=n[r];if(s.isInterleavedBufferAttribute)throw new Error("Brush: InterleavedBufferAttributes are not supported.");s.array=FGe(s.array)}if(e.boundsTree||(UGe(e,{useSharedArrayBuffer:i}),e.boundsTree=new OI(e,{maxLeafTris:3,indirect:!0,useSharedArrayBuffer:i})),e.halfEdges||(e.halfEdges=new QGe(e)),!e.groupIndices){const r=i6(e),s=new Uint16Array(r),o=e.groups;for(let a=0,c=o.length;a<c;a++){const{start:l,count:u}=o[a];for(let h=l/3,d=(l+u)/3;h<d;h++)s[h]=a}e.groupIndices=s}}disposeCacheData(){const{geometry:e}=this;e.halfEdges=null,e.boundsTree=null,e.groupIndices=null}}const KGe=1e-14,c6=new H,poe=new H,moe=new H;function iA(t,e=KGe){c6.subVectors(t.b,t.a),poe.subVectors(t.c,t.a),moe.subVectors(t.b,t.c);const n=c6.angleTo(poe),i=c6.angleTo(moe),r=Math.PI-n-i;return Math.abs(n)<e||Math.abs(i)<e||Math.abs(r)<e||t.a.distanceToSquared(t.b)<e||t.a.distanceToSquared(t.c)<e||t.b.distanceToSquared(t.c)<e}const l6=1e-10,YI=1e-10,JGe=1e-10,ag=new Nh,La=new Nh,cg=new H,u6=new H,goe=new H,lN=new Zi,h6=new Vd;class ZGe{constructor(){this._pool=[],this._index=0}getTriangle(){return this._index>=this._pool.length&&this._pool.push(new Ls),this._pool[this._index++]}clear(){this._index=0}reset(){this._pool.length=0,this._index=0}}class e9e{constructor(){this.trianglePool=new ZGe,this.triangles=[],this.normal=new H,this.coplanarTriangleUsed=!1}initialize(e){this.reset();const{triangles:n,trianglePool:i,normal:r}=this;if(Array.isArray(e))for(let s=0,o=e.length;s<o;s++){const a=e[s];if(s===0)a.getNormal(r);else if(Math.abs(1-a.getNormal(cg).dot(r))>l6)throw new Error("Triangle Splitter: Cannot initialize with triangles that have different normals.");const c=i.getTriangle();c.copy(a),n.push(c)}else{e.getNormal(r);const s=i.getTriangle();s.copy(e),n.push(s)}}splitByTriangle(e){const{normal:n,triangles:i}=this;if(e.getNormal(u6).normalize(),Math.abs(1-Math.abs(u6.dot(n)))<JGe){this.coplanarTriangleUsed=!0;for(let s=0,o=i.length;s<o;s++){const a=i[s];a.coplanarCount=0}const r=[e.a,e.b,e.c];for(let s=0;s<3;s++){const o=(s+1)%3,a=r[s],c=r[o];cg.subVectors(c,a).normalize(),goe.crossVectors(u6,cg),lN.setFromNormalAndCoplanarPoint(goe,a),this.splitByPlane(lN,e)}}else e.getPlane(lN),this.splitByPlane(lN,e)}splitByPlane(e,n){const{triangles:i,trianglePool:r}=this;h6.copy(n),h6.needsUpdate=!0;for(let s=0,o=i.length;s<o;s++){const a=i[s];if(!h6.intersectsTriangle(a,ag,!0))continue;const{a:c,b:l,c:u}=a;let h=0,d=-1,p=!1,m=[],g=[];const y=[c,l,u];for(let A=0;A<3;A++){const v=(A+1)%3;ag.start.copy(y[A]),ag.end.copy(y[v]);const x=e.distanceToPoint(ag.start),C=e.distanceToPoint(ag.end);if(Math.abs(x)<YI&&Math.abs(C)<YI){p=!0;break}if(x>0?m.push(A):g.push(A),Math.abs(x)<YI)continue;let T=!!e.intersectLine(ag,cg);!T&&Math.abs(C)<YI&&(cg.copy(ag.end),T=!0),T&&!(cg.distanceTo(ag.start)<l6)&&(cg.distanceTo(ag.end)<l6&&(d=A),h===0?La.start.copy(cg):La.end.copy(cg),h++)}if(!p&&h===2&&La.distance()>YI)if(d!==-1){d=(d+1)%3;let A=0;A===d&&(A=(A+1)%3);let v=A+1;v===d&&(v=(v+1)%3);const x=r.getTriangle();x.a.copy(y[v]),x.b.copy(La.end),x.c.copy(La.start),iA(x)||i.push(x),a.a.copy(y[A]),a.b.copy(La.start),a.c.copy(La.end),iA(a)&&(i.splice(s,1),s--,o--)}else{const A=m.length>=2?g[0]:m[0];if(A===0){let S=La.start;La.start=La.end,La.end=S}const v=(A+1)%3,x=(A+2)%3,C=r.getTriangle(),T=r.getTriangle();y[v].distanceToSquared(La.start)<y[x].distanceToSquared(La.end)?(C.a.copy(y[v]),C.b.copy(La.start),C.c.copy(La.end),T.a.copy(y[v]),T.b.copy(y[x]),T.c.copy(La.start)):(C.a.copy(y[x]),C.b.copy(La.start),C.c.copy(La.end),T.a.copy(y[v]),T.b.copy(y[x]),T.c.copy(La.end)),a.a.copy(y[A]),a.b.copy(La.end),a.c.copy(La.start),iA(C)||i.push(C),iA(T)||i.push(T),iA(a)&&(i.splice(s,1),s--,o--)}else h===3&&console.warn("TriangleClipper: Coplanar clip not handled")}}reset(){this.triangles.length=0,this.trianglePool.clear(),this.coplanarTriangleUsed=!1}}function t9e(t){return t=~~t,t+4-t%4}class _oe{constructor(e,n=500){this.expansionFactor=1.5,this.type=e,this.length=0,this.array=null,this.setSize(n)}setType(e){if(this.length!==0)throw new Error("TypeBackedArray: Cannot change the type while there is used data in the buffer.");const n=this.array.buffer;this.array=new e(n),this.type=e}setSize(e){if(this.array&&e===this.array.length)return;const n=this.type,i=loe()?SharedArrayBuffer:ArrayBuffer,r=new n(new i(t9e(e*n.BYTES_PER_ELEMENT)));this.array&&r.set(this.array,0),this.array=r}expand(){const{array:e,expansionFactor:n}=this;this.setSize(e.length*n)}push(...e){let{array:n,length:i}=this;i+e.length>n.length&&(this.expand(),n=this.array);for(let r=0,s=e.length;r<s;r++)n[i+r]=e[r];this.length+=e.length}clear(){this.length=0}}class n9e{constructor(){this.groupAttributes=[{}],this.groupCount=0}getType(e){return this.groupAttributes[0][e].type}getItemSize(e){return this.groupAttributes[0][e].itemSize}getNormalized(e){return this.groupAttributes[0][e].normalized}getCount(e){if(this.groupCount<=e)return 0;const n=this.getGroupAttrArray("position",e);return n.length/n.itemSize}getTotalLength(e){const{groupCount:n,groupAttributes:i}=this;let r=0;for(let s=0;s<n;s++){const o=i[s];r+=o[e].length}return r}getGroupAttrSet(e=0){const{groupAttributes:n}=this;if(n[e])return this.groupCount=Math.max(this.groupCount,e+1),n[e];const i=n[0];for(this.groupCount=Math.max(this.groupCount,e+1);e>=n.length;){const r={};n.push(r);for(const s in i){const o=i[s],a=new _oe(o.type);a.itemSize=o.itemSize,a.normalized=o.normalized,r[s]=a}}return n[e]}getGroupAttrArray(e,n=0){const{groupAttributes:i}=this;if(!i[0][e])throw new Error(`TypedAttributeData: Attribute with "${e}" has not been initialized`);return this.getGroupAttrSet(n)[e]}initializeArray(e,n,i,r){const{groupAttributes:s}=this,a=s[0][e];if(a){if(a.type!==n)for(let c=0,l=s.length;c<l;c++){const u=s[c][e];u.setType(n),u.itemSize=i,u.normalized=r}}else for(let c=0,l=s.length;c<l;c++){const u=new _oe(n);u.itemSize=i,u.normalized=r,s[c][e]=u}}clear(){this.groupCount=0;const{groupAttributes:e}=this;e.forEach(n=>{for(const i in n)n[i].clear()})}delete(e){this.groupAttributes.forEach(n=>{delete n[e]})}reset(){this.groupAttributes=[],this.groupCount=0}}class Aoe{constructor(){this.intersectionSet={},this.ids=[]}add(e,n){const{intersectionSet:i,ids:r}=this;i[e]||(i[e]=[],r.push(e)),i[e].push(n)}}const i9e=0,r9e=1,s9e=2,yoe=3,o9e=4,boe=5,voe=6,Gd=new mm,xoe=new xt,Cu=new Ls,lg=new H,Coe=new Bi,Eoe=new Bi,woe=new Bi,d6=new Bi,uN=new Bi,hN=new Bi,Toe=new Nh,f6=new H,p6=1e-8,a9e=1e-15,av=-1,cv=1,dN=-2,fN=2,XI=0,lv=1,m6=2,c9e=1e-14;let pN=null;function Soe(t){pN=t}function Ioe(t,e){t.getMidpoint(Gd.origin),t.getNormal(Gd.direction);const n=e.raycastFirst(Gd,tr);return!!(n&&Gd.direction.dot(n.face.normal)>0)?av:cv}function l9e(t,e){function n(){return Math.random()-.5}t.getNormal(f6),Gd.direction.copy(f6),t.getMidpoint(Gd.origin);const i=3;let r=0,s=1/0;for(let o=0;o<i;o++){Gd.direction.x+=n()*p6,Gd.direction.y+=n()*p6,Gd.direction.z+=n()*p6,Gd.direction.multiplyScalar(-1);const a=e.raycastFirst(Gd,tr);if(!!(a&&Gd.direction.dot(a.face.normal)>0)&&r++,a!==null&&(s=Math.min(s,a.distance)),s<=a9e)return a.face.normal.dot(f6)>0?fN:dN;if(r/i>.5||(o-r+1)/i>.5)break}return r/i>.5?av:cv}function u9e(t,e){const n=new Aoe,i=new Aoe;return xoe.copy(t.matrixWorld).invert().multiply(e.matrixWorld),t.geometry.boundsTree.bvhcast(e.geometry.boundsTree,xoe,{intersectsTriangles(r,s,o,a){if(!iA(r)&&!iA(s)){let c=r.intersectsTriangle(s,Toe,!0);if(!c){const l=r.plane,u=s.plane,h=l.normal,d=u.normal;h.dot(d)===1&&Math.abs(l.constant-u.constant)<c9e&&(c=!0)}if(c){let l=t.geometry.boundsTree.resolveTriangleIndex(o),u=e.geometry.boundsTree.resolveTriangleIndex(a);n.add(l,u),i.add(u,l),pN&&(pN.addEdge(Toe),pN.addIntersectingTriangles(o,r,a,s))}}return!1}}),{aIntersections:n,bIntersections:i}}function h9e(t,e,n,i,r,s,o=!1){const a=n.attributes,c=n.index,l=t*3,u=c.getX(l+0),h=c.getX(l+1),d=c.getX(l+2);for(const p in s){const m=a[p],g=s[p];if(!(p in a))throw new Error(`CSG Operations: Attribute ${p} not available on geometry.`);const y=m.itemSize;p==="position"?(Cu.a.fromBufferAttribute(m,u).applyMatrix4(i),Cu.b.fromBufferAttribute(m,h).applyMatrix4(i),Cu.c.fromBufferAttribute(m,d).applyMatrix4(i),g6(Cu.a,Cu.b,Cu.c,e,3,g,o)):p==="normal"?(Cu.a.fromBufferAttribute(m,u).applyNormalMatrix(r),Cu.b.fromBufferAttribute(m,h).applyNormalMatrix(r),Cu.c.fromBufferAttribute(m,d).applyNormalMatrix(r),o&&(Cu.a.multiplyScalar(-1),Cu.b.multiplyScalar(-1),Cu.c.multiplyScalar(-1)),g6(Cu.a,Cu.b,Cu.c,e,3,g,o,!0)):(Coe.fromBufferAttribute(m,u),Eoe.fromBufferAttribute(m,h),woe.fromBufferAttribute(m,d),g6(Coe,Eoe,woe,e,y,g,o))}}function d9e(t,e,n,i,r,s,o,a=!1){_6(t,i,r,s,o,a),_6(a?n:e,i,r,s,o,a),_6(a?e:n,i,r,s,o,a)}function Moe(t,e,n=!1){switch(t){case i9e:if(e===cv||e===fN&&!n)return lv;break;case r9e:if(n){if(e===av)return XI}else if(e===cv||e===dN)return lv;break;case s9e:if(n){if(e===cv||e===dN)return lv}else if(e===av)return XI;break;case o9e:if(e===av)return XI;if(e===cv)return lv;break;case yoe:if(e===av||e===fN&&!n)return lv;break;case boe:if(!n&&(e===cv||e===dN))return lv;break;case voe:if(!n&&(e===av||e===fN))return lv;break;default:throw new Error(`Unrecognized CSG operation enum "${t}".`)}return m6}function g6(t,e,n,i,r,s,o=!1,a=!1){const c=l=>{s.push(l.x),r>1&&s.push(l.y),r>2&&s.push(l.z),r>3&&s.push(l.w)};d6.set(0,0,0,0).addScaledVector(t,i.a.x).addScaledVector(e,i.a.y).addScaledVector(n,i.a.z),uN.set(0,0,0,0).addScaledVector(t,i.b.x).addScaledVector(e,i.b.y).addScaledVector(n,i.b.z),hN.set(0,0,0,0).addScaledVector(t,i.c.x).addScaledVector(e,i.c.y).addScaledVector(n,i.c.z),a&&(d6.normalize(),uN.normalize(),hN.normalize()),c(d6),o?(c(hN),c(uN)):(c(uN),c(hN))}function _6(t,e,n,i,r,s=!1){for(const o in r){const a=e[o],c=r[o];if(!(o in e))throw new Error(`CSG Operations: Attribute ${o} no available on geometry.`);const l=a.itemSize;o==="position"?(lg.fromBufferAttribute(a,t).applyMatrix4(n),c.push(lg.x,lg.y,lg.z)):o==="normal"?(lg.fromBufferAttribute(a,t).applyNormalMatrix(i),s&&lg.multiplyScalar(-1),c.push(lg.x,lg.y,lg.z)):(c.push(a.getX(t)),l>1&&c.push(a.getY(t)),l>2&&c.push(a.getZ(t)),l>3&&c.push(a.getW(t)))}}class f9e{constructor(e){this.triangle=new Ls().copy(e),this.intersects={}}addTriangle(e,n){this.intersects[e]=new Ls().copy(n)}getIntersectArray(){const e=[],{intersects:n}=this;for(const i in n)e.push(n[i]);return e}}class Poe{constructor(){this.data={}}addTriangleIntersection(e,n,i,r){const{data:s}=this;s[e]||(s[e]=new f9e(n)),s[e].addTriangle(i,r)}getTrianglesAsArray(e=null){const{data:n}=this,i=[];if(e!==null)e in n&&i.push(n[e].triangle);else for(const r in n)i.push(n[r].triangle);return i}getTriangleIndices(){return Object.keys(this.data).map(e=>parseInt(e))}getIntersectionIndices(e){const{data:n}=this;return n[e]?Object.keys(n[e].intersects).map(i=>parseInt(i)):[]}getIntersectionsAsArray(e=null,n=null){const{data:i}=this,r=new Set,s=[],o=a=>{if(i[a])if(n!==null)i[a].intersects[n]&&s.push(i[a].intersects[n]);else{const c=i[a].intersects;for(const l in c)r.has(l)||(r.add(l),s.push(c[l]))}};if(e!==null)o(e);else for(const a in i)o(a);return s}reset(){this.data={}}}class p9e{constructor(){this.enabled=!1,this.triangleIntersectsA=new Poe,this.triangleIntersectsB=new Poe,this.intersectionEdges=[]}addIntersectingTriangles(e,n,i,r){const{triangleIntersectsA:s,triangleIntersectsB:o}=this;s.addTriangleIntersection(e,n,i,r),o.addTriangleIntersection(i,r,e,n)}addEdge(e){this.intersectionEdges.push(e.clone())}reset(){this.triangleIntersectsA.reset(),this.triangleIntersectsB.reset(),this.intersectionEdges=[]}init(){this.enabled&&(this.reset(),Soe(this))}complete(){this.enabled&&Soe(null)}}const rA=new xt,mN=new Mi,uv=new Ls,gN=new Ls,sA=new Ls,_N=new Ls,ap=[],hv=[];function m9e(t){for(const e of t)return e}function g9e(t,e,n,i,r,s={}){const{useGroups:o=!0}=s,{aIntersections:a,bIntersections:c}=u9e(t,e),l=[];let u=null,h;return h=o?0:-1,Doe(t,e,a,n,!1,i,r,h),Roe(t,e,a,n,!1,r,h),n.findIndex(p=>p!==voe&&p!==boe)!==-1&&(h=o?t.geometry.groups.length||1:-1,Doe(e,t,c,n,!0,i,r,h),Roe(e,t,c,n,!0,r,h)),ap.length=0,hv.length=0,{groups:l,materials:u}}function Doe(t,e,n,i,r,s,o,a=0){const c=t.matrixWorld.determinant()<0;rA.copy(e.matrixWorld).invert().multiply(t.matrixWorld),mN.getNormalMatrix(t.matrixWorld).multiplyScalar(c?-1:1);const l=t.geometry.groupIndices,u=t.geometry.index,h=t.geometry.attributes.position,d=e.geometry.boundsTree,p=e.geometry.index,m=e.geometry.attributes.position,g=n.ids,y=n.intersectionSet;for(let A=0,v=g.length;A<v;A++){const x=g[A],C=a===-1?0:l[x]+a,T=3*x,S=u.getX(T+0),w=u.getX(T+1),E=u.getX(T+2);uv.a.fromBufferAttribute(h,S).applyMatrix4(rA),uv.b.fromBufferAttribute(h,w).applyMatrix4(rA),uv.c.fromBufferAttribute(h,E).applyMatrix4(rA),s.reset(),s.initialize(uv);const D=y[x];for(let P=0,I=D.length;P<I;P++){const _=3*D[P],M=p.getX(_+0),L=p.getX(_+1),N=p.getX(_+2);gN.a.fromBufferAttribute(m,M),gN.b.fromBufferAttribute(m,L),gN.c.fromBufferAttribute(m,N),s.splitByTriangle(gN)}const O=s.triangles;for(let P=0,I=O.length;P<I;P++){const _=O[P],M=s.coplanarTriangleUsed?l9e(_,d):Ioe(_,d);ap.length=0,hv.length=0;for(let L=0,N=i.length;L<N;L++){const F=Moe(i[L],M,r);F!==m6&&(hv.push(F),ap.push(o[L].getGroupAttrSet(C)))}if(ap.length!==0){uv.getBarycoord(_.a,_N.a),uv.getBarycoord(_.b,_N.b),uv.getBarycoord(_.c,_N.c);for(let L=0,N=ap.length;L<N;L++){const F=ap[L],k=hv[L]===XI;h9e(x,_N,t.geometry,t.matrixWorld,mN,F,c!==k)}}}}return g.length}function Roe(t,e,n,i,r,s,o=0){const a=t.matrixWorld.determinant()<0;rA.copy(e.matrixWorld).invert().multiply(t.matrixWorld),mN.getNormalMatrix(t.matrixWorld).multiplyScalar(a?-1:1);const c=e.geometry.boundsTree,l=t.geometry.groupIndices,u=t.geometry.index,h=t.geometry.attributes,d=h.position,p=[],m=t.geometry.halfEdges,g=new Set,y=i6(t.geometry);for(let A=0,v=y;A<v;A++)A in n.intersectionSet||g.add(A);for(;g.size>0;){const A=m9e(g);g.delete(A),p.push(A);const v=3*A,x=u.getX(v+0),C=u.getX(v+1),T=u.getX(v+2);sA.a.fromBufferAttribute(d,x).applyMatrix4(rA),sA.b.fromBufferAttribute(d,C).applyMatrix4(rA),sA.c.fromBufferAttribute(d,T).applyMatrix4(rA);const S=Ioe(sA,c);hv.length=0,ap.length=0;for(let w=0,E=i.length;w<E;w++){const D=Moe(i[w],S,r);D!==m6&&(hv.push(D),ap.push(s[w]))}for(;p.length>0;){const w=p.pop();for(let E=0;E<3;E++){const D=m.getSiblingTriangleIndex(w,E);D!==-1&&g.has(D)&&(p.push(D),g.delete(D))}if(ap.length!==0){const E=3*w,D=u.getX(E+0),O=u.getX(E+1),P=u.getX(E+2),I=o===-1?0:l[w]+o;if(sA.a.fromBufferAttribute(d,D),sA.b.fromBufferAttribute(d,O),sA.c.fromBufferAttribute(d,P),!iA(sA))for(let _=0,M=ap.length;_<M;_++){const L=hv[_],N=ap[_].getGroupAttrSet(I),F=L===XI;d9e(D,O,P,h,t.matrixWorld,mN,N,F!==a)}}}}}function _9e(t){for(let e=0;e<t.length-1;e++){const n=t[e],i=t[e+1];if(n.materialIndex===i.materialIndex){const r=n.start,s=i.start+i.count;i.start=r,i.count=s-r,t.splice(e,1),e--}}}function A9e(t,e,n,i){n.clear();const r=t.attributes;for(let s=0,o=i.length;s<o;s++){const a=i[s],c=r[a];n.initializeArray(a,c.array.constructor,c.itemSize,c.normalized)}for(const s in n.attributes)i.includes(s)||n.delete(s);for(const s in e.attributes)i.includes(s)||(e.deleteAttribute(s),e.dispose())}function y9e(t,e,n){let i=!1,r=-1;const s=t.attributes,o=e.groupAttributes[0];for(const c in o){const l=e.getTotalLength(c),u=e.getType(c),h=e.getItemSize(c),d=e.getNormalized(c);let p=s[c];(!p||p.array.length<l)&&(p=new ji(new u(l),h,d),t.setAttribute(c,p),i=!0);let m=0;for(let g=0,y=Math.min(n.length,e.groupCount);g<y;g++){const A=n[g].index,{array:v,type:x,length:C}=e.groupAttributes[A][c],T=new x(v.buffer,0,C);p.array.set(T,m),m+=T.length}p.needsUpdate=!0,r=l/p.itemSize}if(t.index){const c=t.index.array;if(c.length<r)t.index=null,i=!0;else for(let l=0,u=c.length;l<u;l++)c[l]=l}let a=0;t.clearGroups();for(let c=0,l=Math.min(n.length,e.groupCount);c<l;c++){const{index:u,materialIndex:h}=n[c],d=e.getCount(u);d!==0&&(t.addGroup(a,d,h),a+=d)}t.setDrawRange(0,r),t.boundsTree=null,i&&t.dispose()}function Ooe(t,e){let n=e;return Array.isArray(e)||(n=[],t.forEach(i=>{n[i.materialIndex]=e})),n}class b9e{constructor(){this.triangleSplitter=new e9e,this.attributeData=[],this.attributes=["position","uv","normal"],this.useGroups=!0,this.consolidateGroups=!0,this.debug=new p9e}getGroupRanges(e){return!this.useGroups||e.groups.length===0?[{start:0,count:1/0,materialIndex:0}]:e.groups.map(n=>({...n}))}evaluate(e,n,i,r=new cN){let s=!0;if(Array.isArray(i)||(i=[i]),Array.isArray(r)||(r=[r],s=!1),r.length!==i.length)throw new Error("Evaluator: operations and target array passed as different sizes.");e.prepareGeometry(),n.prepareGeometry();const{triangleSplitter:o,attributeData:a,attributes:c,useGroups:l,consolidateGroups:u,debug:h}=this;for(;a.length<r.length;)a.push(new n9e);r.forEach((A,v)=>{A9e(e.geometry,A.geometry,a[v],c)}),h.init(),g9e(e,n,i,o,a,{useGroups:l}),h.complete();const d=this.getGroupRanges(e.geometry),p=Ooe(d,e.material),m=this.getGroupRanges(n.geometry),g=Ooe(m,n.material);m.forEach(A=>A.materialIndex+=p.length);let y=[...d,...m].map((A,v)=>({...A,index:v}));if(l){const A=[...p,...g];u&&(y=y.map(x=>{const C=A[x.materialIndex];return x.materialIndex=A.indexOf(C),x}).sort((x,C)=>x.materialIndex-C.materialIndex));const v=[];for(let x=0,C=A.length;x<C;x++){let T=!1;for(let S=0,w=y.length;S<w;S++){const E=y[S];E.materialIndex===x&&(T=!0,E.materialIndex=v.length)}T&&v.push(A[x])}r.forEach(x=>{x.material=v})}else y=[{start:0,count:1/0,index:0,materialIndex:0}],r.forEach(A=>{A.material=p[0]});return r.forEach((A,v)=>{const x=A.geometry;y9e(x,a[v],y),u&&_9e(x.groups)}),s?r:r[0]}evaluateHierarchy(e,n=new cN){e.updateMatrixWorld(!0);const i=(s,o)=>{const a=s.children;for(let c=0,l=a.length;c<l;c++){const u=a[c];u.isOperationGroup?i(u,o):o(u)}},r=s=>{const o=s.children;let a=!1;for(let l=0,u=o.length;l<u;l++){const h=o[l];a=r(h)||a}const c=s.isDirty();if(c&&s.markUpdated(),a&&!s.isOperationGroup){let l;return i(s,u=>{l?l=this.evaluate(l,u,u.operation):l=this.evaluate(s,u,u.operation)}),s._cachedGeometry=l.geometry,s._cachedMaterials=l.material,!0}else return a||c};return r(e),n.geometry=e._cachedGeometry,n.material=e._cachedMaterials,n}reset(){this.triangleSplitter.reset()}}class v9e{engine;evaluator;fillMeshName="ClippingFaceFillMesh";fillMeshes=new Map;maxCandidates=22e5;maxTriangleCountPerMesh=12e4;fillMaterial;fillTextureRepeat=60;fillTextureRotation=0;constructor(e){this.engine=e,this.evaluator=new b9e;const n=Wi("/texture/fill.png",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:gt&>.tagName.toUpperCase()==="SCRIPT"&>.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href),i=new Bd().load(n);i.wrapS=Uc,i.wrapT=Uc,i.center.set(.5,.5),i.rotation=this.fillTextureRotation,this.fillMaterial=new V_({color:14079687,map:i,side:tr,toneMapped:!1}),this.fillMaterial.clipShadows=!0,this.fillMaterial.clippingPlanes=e.sectionPlane}clear(){this.fillMeshes.forEach(e=>{e.parent?.remove(e),e.geometry?.dispose?.();const n=e.material;Array.isArray(n)?n.forEach(i=>i.dispose?.()):n&&n!==this.fillMaterial&&n.dispose?.()}),this.fillMeshes.clear()}updataFace(e){this.clear(),e instanceof Zi&&this.engine.clipping.fillCutFace&&this.buildSinglePlaneFill(e,"face")}updataFaces(e){this.clear(),!(!Array.isArray(e)||e.length===0)&&this.engine.clipping.fillCutFace&&e.forEach((n,i)=>{if(!(n instanceof Zi))return;const r=`plane-${i}-${String(n.name??i)}`;this.buildSinglePlaneFill(n,r)})}buildSinglePlaneFill(e,n){const i=this.engine?.octreeBox?.getBoundingBox?.();if(i==null||i.min==null||i.max==null)return;const r=this.collectCandidateMeshesFromOctree(e);if(r.length===0)return;const s=this.filterMeshesByBoxAndComplexity(e,r);if(s.length===0)return;const o=i.min.distanceTo(i.max),a=o*5,c=.1,l=this.createPlaneBrush(e,a,c),u=[];for(const g of s.slice(0,this.maxCandidates)){const y=this.createWorldBrushFromMesh(g);if(y!=null)try{const v=this.evaluator.evaluate(y,l,yoe)?.geometry;if(!v)continue;const x=this.extractPlaneCapGeometry(v,e,c);x&&u.push(x),v.dispose()}catch{}finally{y.geometry.dispose()}}if(l.geometry.dispose(),u.length===0)return;const h=Cm(u,!1);if(u.forEach(g=>g.dispose()),!h)return;this.applyPlanarUv(h,e);const d=this.getFaceOffsetDistance(o),p=this.getFaceOffsetSign();h.translate(e.normal.x*d*p,e.normal.y*d*p,e.normal.z*d*p);const m=new bt(h,this.fillMaterial);m.name=`${this.fillMeshName}_${n}`,m.frustumCulled=!1,m.renderOrder=20,m.castShadow=!1,m.receiveShadow=!1,this.engine.scene.add(m),this.fillMeshes.set(n,m)}getFaceOffsetDistance(e){return-.001}getFaceOffsetSign(){const e=this.engine?.engineStatus?.clippingFaceOffsetSign;return e===1||e===-1?e:-1}collectCandidateMeshesFromOctree(e){const n=[],i=new Set,r=Array.isArray(this.engine?.models)?this.engine.models:[];for(const s of r){if(!s?.nodesMap)continue;const o=this.getIgnoredIds(s.url),a=Array.isArray(s?.lods)?s.lods:[];for(const c of a){const l=c?.octreeBox;if(!l)continue;const u=this.collectIntersectElementIds(l,e);for(const h of u){if(o.has(h))continue;const d=s.nodesMap.get(h);if(!(d?.instance===!0||!Array.isArray(d?.infos)))for(const p of d.infos){const m=p?.mesh;m instanceof bt&&(i.has(m.uuid)||(i.add(m.uuid),n.push(m)))}}}}return n}getIgnoredIds(e){const n=new Set,i=Array.isArray(this.engine?.engineStatus?.hideModels)?this.engine.engineStatus.hideModels:[],r=Array.isArray(this.engine?.engineStatus?.translucentModels)?this.engine.engineStatus.translucentModels:[],s=i.find(a=>a.url===e)?.ids;Array.isArray(s)&&s.forEach(a=>n.add(a));const o=r.find(a=>a.url===e)?.ids;return Array.isArray(o)&&o.forEach(a=>n.add(a)),n}collectIntersectElementIds(e,n){const i=new Set,r=[e];for(;r.length>0;){const s=r.pop();if(!s)continue;const o=this.octreeNodeToBox3(s);!o||!n.intersectsBox(o)||(Array.isArray(s.elements)&&s.elements.forEach(a=>i.add(a)),Array.isArray(s.children)&&s.children.forEach(a=>r.push(a)))}return i}octreeNodeToBox3(e){if(!e?.min||!e?.max)return null;const n=new H(e.min.X*.3048,e.min.Z*.3048,-e.min.Y*.3048),i=new H(e.max.X*.3048,e.max.Z*.3048,-e.max.Y*.3048),r=new H(Math.min(n.x,i.x),Math.min(n.y,i.y),Math.min(n.z,i.z)),s=new H(Math.max(n.x,i.x),Math.max(n.y,i.y),Math.max(n.z,i.z));return new Ln(r,s)}filterMeshesByBoxAndComplexity(e,n){const i=[],r=new Ln;for(const s of n){const o=s.geometry,a=o?.attributes?.position;!o||!a||a.count===0||(o.index?Math.floor(o.index.count/3):Math.floor(a.count/3))>this.maxTriangleCountPerMesh||(o.boundingBox||o.computeBoundingBox(),o.boundingBox&&(r.copy(o.boundingBox),s.updateWorldMatrix(!0,!1),r.applyMatrix4(s.matrixWorld),e.intersectsBox(r)&&(s.geometry.attributes.position.count>500||i.push(s))))}return i}createPlaneBrush(e,n,i){const r=new so(n,n,i),s=e.coplanarPoint(new H),o=new ni().setFromUnitVectors(new H(0,0,1),e.normal.clone().normalize()),a=new xt().compose(s,o,new H(1,1,1));r.applyMatrix4(a);const c=this.toCsgReadyGeometry(r);return r.dispose(),new cN(c)}createWorldBrushFromMesh(e){const n=e.geometry;if(!n||!n.attributes?.position)return null;e.updateWorldMatrix(!0,!1);const i=n.clone();i.applyMatrix4(e.matrixWorld);const r=this.toCsgReadyGeometry(i);return i.dispose(),new cN(r)}toCsgReadyGeometry(e){const n=e.index?e.toNonIndexed():e.clone();n.getAttribute("normal")||n.computeVertexNormals();const i=n.getAttribute("position");if(i&&!n.getAttribute("uv")){const s=new Float32Array(i.count*2);n.setAttribute("uv",new _n(s,2))}const r=new Set(["position","normal","uv"]);return Object.keys(n.attributes).forEach(s=>{r.has(s)||n.deleteAttribute(s)}),n}extractPlaneCapGeometry(e,n,i){const r=e.index?e.toNonIndexed():e.clone(),s=r.getAttribute("position");if(!s||s.count<3)return r.dispose(),null;const o=n.normal.clone().normalize(),a=new H,c=new H,l=new H,u=new H,h=new H,d=new H,p=new H,m=new H,g=new H,y=Math.max(i*.35,1e-4),A=Math.max(i*.7,1e-4),v=[];for(let C=0;C<s.count;C+=3){if(u.fromBufferAttribute(s,C),h.fromBufferAttribute(s,C+1),d.fromBufferAttribute(s,C+2),c.subVectors(h,u),l.subVectors(d,u),a.crossVectors(c,l),a.lengthSq()<1e-14||(a.normalize(),Math.abs(a.dot(o))<.9))continue;const T=n.distanceToPoint(u),S=n.distanceToPoint(h),w=n.distanceToPoint(d),E=Math.min(T,S,w);if(Math.max(T,S,w)-E>y)continue;const O=(T+S+w)/3;Math.abs(O)>A||O<0||(p.copy(u).addScaledVector(o,-T),m.copy(h).addScaledVector(o,-S),g.copy(d).addScaledVector(o,-w),a.dot(o)<=0?(v.push(p.x,p.y,p.z),v.push(m.x,m.y,m.z),v.push(g.x,g.y,g.z)):(v.push(p.x,p.y,p.z),v.push(g.x,g.y,g.z),v.push(m.x,m.y,m.z)))}if(r.dispose(),v.length<9)return null;const x=new Dn;return x.setAttribute("position",new _n(v,3)),x.computeVertexNormals(),x}applyPlanarUv(e,n){const i=e.getAttribute("position");if(!i||i.count===0)return;const{tangent:r,bitangent:s}=this.getPlaneBasis(n.normal.clone().normalize()),o=new H,a=new Float32Array(i.count*2);let c=1/0,l=-1/0,u=1/0,h=-1/0;for(let m=0;m<i.count;m++){o.fromBufferAttribute(i,m);const g=o.dot(r),y=o.dot(s),A=m*2;a[A]=g,a[A+1]=y,c=Math.min(c,g),l=Math.max(l,g),u=Math.min(u,y),h=Math.max(h,y)}const d=Math.max(l-c,1e-6),p=Math.max(h-u,1e-6);for(let m=0;m<a.length;m+=2)a[m]=(a[m]-c)/d*this.fillTextureRepeat,a[m+1]=(a[m+1]-u)/p*this.fillTextureRepeat;e.setAttribute("uv",new ji(a,2))}getPlaneBasis(e){const n=new H(1,0,0),i=new H(0,1,0),r=new H(0,0,1),s=Math.abs(e.dot(n)),o=Math.abs(e.dot(i)),a=Math.abs(e.dot(r));let c=n;o<=s&&o<=a?c=i:a<=s&&a<=o&&(c=r),c=c.clone().sub(e.clone().multiplyScalar(c.dot(e))).normalize();const l=new H().crossVectors(e,c).normalize();return{tangent:c,bitangent:l}}}class x9e{engine;clippingTolerance=1e-4;sectionBox;sectionFace;clippingStencil;clippingCSGSimple=null;currentClippingMode="";sectionCatchFace;fillCutFace=!0;viewRangePlanes=null;constructor(e){this.engine=e,this.sectionCatchFace=new DGe(this.engine);let n=new Zi(new H(0,0,1),1e5);n.name="前";let i=new Zi(new H(0,0,1),1e5);i.name="左";let r=new Zi(new H(0,0,1),1e5);r.name="后";let s=new Zi(new H(0,0,1),1e5);s.name="右";let o=new Zi(new H(0,0,1),1e5);o.name="顶";let a=new Zi(new H(0,0,1),1e5);a.name="底";let c=new Zi(new H(0,0,1),1e5);c.name="face",this.engine.sectionPlane=[n,i,r,s,o,a,c]}init(){this.sectionBox=new MGe(this.engine),this.sectionFace=new PGe(this.engine),this.clippingCSGSimple=new v9e(this.engine)}scaleBox(){let e=this.engine.octreeBox.getBoundingBox();this.sectionBox.setBox(e)}setFillCutFace(e){this.fillCutFace=e}getFillCutFace(){return this.fillCutFace}clippingModel(e){let n=[];e.forEach(s=>{let o=this.engine.models.find(a=>a.url===s.url);s.ids.forEach(a=>{o.nodesMap.get(a).infos.forEach(c=>{n.push(c.box)})})}),this.active("box");let i=r(n);i.expandByScalar(.1),this.sectionBox.setBox(i);function r(s){let o=new H(1e8,1e9,1e10),a=new H(-1e8,-1e9,-1e10);return s.forEach(c=>{c.min.x<o.x&&(o.x=c.min.x),c.min.y<o.y&&(o.y=c.min.y),c.min.z<o.z&&(o.z=c.min.z),c.max.x>a.x&&(a.x=c.max.x),c.max.y>a.y&&(a.y=c.max.y),c.max.z>a.z&&(a.z=c.max.z)}),new Ln(o,a)}}updateClippingValue(e){let n=this.sectionBox.maxBox,i=n.min.x+(n.max.x-n.min.x)*e.x.min*.01,r=n.min.y+(n.max.y-n.min.y)*e.y.min*.01,s=n.min.z+(n.max.z-n.min.z)*e.z.min*.01,o=n.min.x+(n.max.x-n.min.x)*e.x.max*.01,a=n.min.y+(n.max.y-n.min.y)*e.y.max*.01,c=n.min.z+(n.max.z-n.min.z)*e.z.max*.01;this.sectionBox.setboxXyz({minX:i,minY:r,minZ:s,maxX:o,maxY:a,maxZ:c})}active(e){this.engine.engineStatus.isForceFree=!0,this.sectionFace.disActive(),this.sectionBox.disActive(),this.sectionCatchFace.cancel(),this.viewRangePlanes=null,this.currentClippingMode=e,e=="x"?(this.sectionFace.direction=1,this.sectionFace.init(),this.sectionFace.active(),this.sectionFace.setFaceNormal(new H(-1,0,0))):e=="y"?(this.sectionFace.direction=1,this.sectionFace.init(),this.sectionFace.active(),this.sectionFace.setFaceNormal(new H(0,0,-1))):e=="z"?(this.sectionFace.direction=1,this.sectionFace.init(),this.sectionFace.active(),this.sectionFace.setFaceNormal(new H(0,-1,0))):e=="box"?(this.sectionBox.init(),this.sectionBox.active()):e=="face"&&(this.sectionFace.direction=1,this.sectionCatchFace.init(),this.sectionCatchFace.catch_face(n=>{this.sectionFace.init(),this.sectionFace.active();let i=this.engine.octreeBox.getBoundingBox(),r=i.min.clone().add(i.max.clone()).multiplyScalar(.5),s=n.position.clone().sub(r),o=new H(n.dir.x,n.dir.y,n.dir.z),a=s.dot(o);this.sectionFace.setFaceNormal(n.dir,a)}))}disabled(){this.currentClippingMode=="box"?this.sectionBox.disabled():this.currentClippingMode=="viewRange"?(this.setPlaneConstantsHigh(this.engine.sectionPlane?.slice?.(0,6)),this.clippingCSGSimple?.clear()):this.sectionFace.disabled(),this.engine.engineStatus.isForceFree=!1}recover(){this.currentClippingMode=="box"?this.sectionBox.recover():this.currentClippingMode=="viewRange"?this.applyStoredViewRangePlanes():this.sectionFace.recover()}reverse(){this.currentClippingMode!=="x"&&this.currentClippingMode!=="y"&&this.currentClippingMode!=="z"&&this.currentClippingMode!=="face"||this.sectionFace.reverse()}disActive(){this.sectionFace.disActive(),this.sectionBox.disActive(),this.clippingCSGSimple?.clear(),this.sectionCatchFace.cancel(),this.viewRangePlanes=null,this.currentClippingMode="",this.engine.engineStatus.isForceFree=!1}isPointInClippingRange(e,n=this.clippingTolerance){if(!this.isVector3Like(e))return!1;const i=this.getEffectiveClippingPlanes();return i.length===0?!0:i.every(r=>r.distanceToPoint(e)>=-n)}filterIntersectionsByClipping(e,n=this.clippingTolerance){return!Array.isArray(e)||e.length===0?[]:e.filter(i=>this.isPointInClippingRange(i?.point,n))}doesBoxIntersectClippingRange(e,n=this.clippingTolerance){const i=this.toBox3(e);if(i==null||i.isEmpty())return!1;const r=this.getEffectiveClippingPlanes();return r.length===0?!0:r.every(s=>this.isBoxVisibleAgainstPlane(i,s,n))}getClippedBoundingBox(e){const n=this.toBox3(e??this.engine.octreeBox?.getBoundingBox?.());if(n==null||n.isEmpty())return null;const i=this.getEffectiveClippingPlanes();if(i.length===0)return n.clone();const r=this.getBoxBoundaryPlanes(n).concat(i),s=[];for(let o=0;o<r.length-2;o++)for(let a=o+1;a<r.length-1;a++)for(let c=a+1;c<r.length;c++){const l=this.intersectThreePlanes(r[o],r[a],r[c]);l&&this.isPointInsidePlanes(l,r)&&this.pushUniquePoint(s,l)}return s.length===0?null:new Ln().setFromPoints(s)}getEffectiveClippingPlanes(){const e=Array.isArray(this.engine.sectionPlane)?this.engine.sectionPlane:[];if(this.currentClippingMode==="box"||this.currentClippingMode==="viewRange")return e.slice(0,6).filter(n=>n instanceof Zi);if(this.currentClippingMode==="x"||this.currentClippingMode==="y"||this.currentClippingMode==="z"||this.currentClippingMode==="face"){const n=e[6];return n instanceof Zi?[n]:[]}return[]}toBox3(e){return e==null||e.min==null||e.max==null?null:new Ln(new H(e.min.x,e.min.y,e.min.z),new H(e.max.x,e.max.y,e.max.z))}getBoxBoundaryPlanes(e){return[new Zi(new H(1,0,0),-e.min.x),new Zi(new H(-1,0,0),e.max.x),new Zi(new H(0,1,0),-e.min.y),new Zi(new H(0,-1,0),e.max.y),new Zi(new H(0,0,1),-e.min.z),new Zi(new H(0,0,-1),e.max.z)]}intersectThreePlanes(e,n,i){const r=e.normal,s=n.normal,o=i.normal,a=r.dot(new H().crossVectors(s,o));if(Math.abs(a)<1e-8)return null;const c=new H().crossVectors(s,o).multiplyScalar(-e.constant),l=new H().crossVectors(o,r).multiplyScalar(-n.constant),u=new H().crossVectors(r,s).multiplyScalar(-i.constant);return c.add(l).add(u).divideScalar(a)}isPointInsidePlanes(e,n){return n.every(i=>i.distanceToPoint(e)>=-this.clippingTolerance)}isBoxVisibleAgainstPlane(e,n,i){const r=new H(n.normal.x>=0?e.max.x:e.min.x,n.normal.y>=0?e.max.y:e.min.y,n.normal.z>=0?e.max.z:e.min.z);return n.distanceToPoint(r)>=-i}pushUniquePoint(e,n){e.some(r=>r.distanceToSquared(n)<this.clippingTolerance*this.clippingTolerance)||e.push(n)}isVector3Like(e){return e!=null&&typeof e.x=="number"&&typeof e.y=="number"&&typeof e.z=="number"}setSectionByView(e,n){this.sectionFace.disActive(),this.sectionBox.disActive(),this.viewRangePlanes=null,this.scaleBox(),this.sectionFace.init(!0);const i=this.engine.octreeBox.getBoundingBox(),r=new H((i.min.x+i.max.x)/2,(i.min.y+i.max.y)/2,(i.min.z+i.max.z)/2),o=new H(n.x,n.y,n.z).normalize().clone().negate(),c=new H(e.x,e.y,e.z).clone().sub(r).dot(o);this.sectionFace.setFaceNormalPlaneOnly(o,c),this.sectionFace.activateClippingOnly(),this.currentClippingMode="face"}setSectionPlanesByViewRange(e){const n=Array.isArray(e)?e.filter(i=>i instanceof Zi).slice(0,6):[];n.length===6&&(this.sectionFace.disActive(),this.sectionBox.disActive(),this.sectionCatchFace.cancel(),this.viewRangePlanes=n.map(i=>i.clone()),this.applyStoredViewRangePlanes(),this.currentClippingMode="viewRange",this.engine.engineStatus.isForceFree=!0)}applyStoredViewRangePlanes(){if(!this.viewRangePlanes||this.viewRangePlanes.length!==6)return;const e=Array.isArray(this.engine.sectionPlane)?this.engine.sectionPlane:[];this.viewRangePlanes.forEach((i,r)=>{e[r]instanceof Zi&&e[r].copy(i)});const n=e[6];n instanceof Zi&&(n.constant=1e5),this.applySectionPlanesToModelMeshes(),this.clippingCSGSimple?.updataFaces?.(e.slice(0,6))}applySectionPlanesToModelMeshes(){zj(this.engine).forEach(e=>{e.material&&Array.isArray(e.material)?e.material.forEach(n=>{n.clippingPlanes=this.engine.sectionPlane,n.clipShadows=!0}):e.material&&(e.material.clippingPlanes=this.engine.sectionPlane,e.material.clipShadows=!0)})}setPlaneConstantsHigh(e){Array.isArray(e)&&e.forEach(n=>{n instanceof Zi&&(n.constant=1e5)})}}class C9e{engine;constructor(e){this.engine=e}getLevelTreeData(){let e=[];return(this.engine?.models??[]).forEach(i=>{e.push({children:i.modelTree?.modelTreeLevel,name:i.baseInfo?.name,url:i.url})}),e}getTypeTreeData(){let e=[];return(this.engine?.models??[]).forEach(i=>{e.push({children:i.modelTree?.modelTreeType,name:i.baseInfo?.name,url:i.url})}),e}getMajorTreeData(){let e=[];return(this.engine?.models??[]).forEach(i=>{e.push({children:i.modelTree?.modelTreeMajor,name:i.baseInfo?.name,url:i.url})}),e}}class E9e{engine;constructor(e){this.engine=e}getEngineInfo(){let e=0,n=0,i=0;return!this.engine||!this.engine.scene?{totalVertices:0,totalTriangles:0,meshCount:0}:(this.engine.scene.traverse(r=>{if(r instanceof bt){const s=r.geometry;if(s&&s.attributes){const o=s.attributes.position;if(o){const a=o.count;e+=a;let c=0;s.index?c=s.index.count/3:c=a/3,n+=c}}}}),(this.engine?.models??[]).forEach(r=>{i=i+(Array.isArray(r?.modelEdge)?r.modelEdge.length:0)}),{totalVertices:Math.floor(e),totalTriangles:Math.floor(n),meshCount:i})}}class w9e{engine;extended=new Map;constructor(e){this.engine=e}init(){}updateExtended(e,n){let i=this.extended.get(e);i==null?this.extended.set(e,n):n.forEach((r,s)=>{i.set(s,r)})}getModelPropertiesWithName(e,n,i,r){let s=this.extended.get(e),o=this.engine.engineStatus.models.find(c=>c.url===e);o.properties==null?(iB(this.engine,e,e+"/property"),PB(e+"/property",c=>{let l=JSON.parse(c);o.properties=l,setTimeout(()=>{a(l,i,n,r)},100)},()=>{},o?.key)):a(o.properties,i,n,r);function a(c,l,u,h){let d={},p=c.models[u];p==null&&(p=c.models[u.toString()||""]),p.forEach(m=>{i.includes(c.names[m[1]])&&(d[c.names[m[1]]]=c.values[m[2]])}),s!=null&&s.has(u)&&d.push(s.get(u)),h?.({id:u,properties:d})}}getModelProperties(e,n,i){let r=this.extended.get(e),s=this.engine.engineStatus.models.find(a=>a.url===e);s.properties==null&&(iB(this.engine,e,e+"/property"),PB(e+"/property",a=>{let c=JSON.parse(a);s.properties=c,setTimeout(()=>{o(c,n,i)},100)},()=>{},s?.key)),o(s.properties,n,i);function o(a,c,l){let u=[],h=a.models[c];h==null&&(h=a.models[c.toString()||""]);let d=h.map(m=>m[0]);d=d.filter((m,g)=>d.indexOf(m)===g),d.forEach(m=>{let g={name:a.categorys[m],children:[]};u.push(g),h.filter(y=>y[0]===m).forEach(y=>{g.children.push({name:a.names[y[1]],value:a.values[y[2]]})})}),r!=null&&r.has(c)&&u.push(r.get(c));const p={基础数据:0,基礎信息:0,标识数据:1,尺寸标注:2,文字:3,约束:4,阶段化:5,结构:6,图形:7,材质和装饰:8,构造:9,分析属性:10,其他:11,基礎資料:0,識別資料:1,尺寸:2,約束:4,階段:5,結構:6,圖形:7,材料及飾面:8,構造:9,分析性質:10};u.sort((m,g)=>{const y=p[m.name]??99;return(p[g.name]??99)-y}),l?.({properties:u,materials:u})}}}const T9e='<svg width="18" height="18" viewBox="0 0 24 24" fill="none" aria-hidden="true"><circle cx="10.8" cy="10.8" r="6.5" stroke="currentColor" stroke-width="2"/><path d="m16 16 4.3 4.3" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>';class S9e{manager;wrapper;input;status;list;pagination;results=[];activeIndex=-1;currentPage=1;pageSize=20;debounceTimer=null;constructor(e,n){this.manager=n,this.wrapper=document.createElement("div"),this.wrapper.className="engine-3d-search",this.wrapper.innerHTML=`
|
|
5362
|
+
}`};const noe={turbidity:10,rayleigh:3,mieCoefficient:.005,mieDirectionalG:.7,elevation:2,azimuth:180,exposure:.5,orthoExposureScale:1.5,cloudCoverage:.4,cloudDensity:.4,cloudElevation:.5,showSunDisc:!0},t6="sunrise_clear",ioe=.2,n6=[{id:"sunrise_clear",names:["晴朗日出","晴朗日出","Clear Sunrise"],params:{turbidity:4,rayleigh:1.8,mieCoefficient:.004,mieDirectionalG:.72,elevation:8,azimuth:105,exposure:.42,cloudCoverage:.12,cloudDensity:.2,cloudElevation:.45,showSunDisc:!0}},{id:"morning_mist",names:["晨雾薄云","晨雾薄云","Misty Morning"],params:{turbidity:14,rayleigh:2.4,mieCoefficient:.018,mieDirectionalG:.68,elevation:12,azimuth:120,exposure:.35,cloudCoverage:.45,cloudDensity:.5,cloudElevation:.35,showSunDisc:!0}},{id:"noon_clear",names:["晴空正午","晴空正午","Clear Noon"],params:{turbidity:2,rayleigh:1,mieCoefficient:.002,mieDirectionalG:.82,elevation:68,azimuth:180,exposure:.58,cloudCoverage:.05,cloudDensity:.12,cloudElevation:.55,showSunDisc:!0}},{id:"afternoon_cloudy",names:["午后多云","午后多云","Cloudy Afternoon"],params:{turbidity:8,rayleigh:1.7,mieCoefficient:.008,mieDirectionalG:.74,elevation:42,azimuth:220,exposure:.5,cloudCoverage:.48,cloudDensity:.42,cloudElevation:.52,showSunDisc:!0}},{id:"sunset_glow",names:["落日晚霞","落日晚霞","Sunset Glow"],params:{turbidity:10,rayleigh:2,mieCoefficient:.006,mieDirectionalG:.7,elevation:6,azimuth:245,exposure:.6,cloudCoverage:.3,cloudDensity:.36,cloudElevation:.5,showSunDisc:!0}},{id:"blue_hour",names:["暮色蓝调","暮色蓝调","Blue Hour"],params:{turbidity:7,rayleigh:1.2,mieCoefficient:.003,mieDirectionalG:.76,elevation:-4,azimuth:255,exposure:.22,cloudCoverage:.2,cloudDensity:.24,cloudElevation:.48,showSunDisc:!1}},{id:"overcast_day",names:["阴天白昼","阴天白昼","Overcast Day"],params:{turbidity:20,rayleigh:2,mieCoefficient:.02,mieDirectionalG:.6,elevation:32,azimuth:180,exposure:.38,cloudCoverage:.86,cloudDensity:.68,cloudElevation:.4,showSunDisc:!1}},{id:"storm_rain",names:["暴雨雷云","暴雨雷云","Storm Rain"],params:{turbidity:19,rayleigh:.9,mieCoefficient:.03,mieDirectionalG:.58,elevation:18,azimuth:210,exposure:.2,cloudCoverage:.95,cloudDensity:.9,cloudElevation:.28,showSunDisc:!1}},{id:"snow_day",names:["雪天漫射","雪天漫射","Snowy Day"],params:{turbidity:15,rayleigh:2.6,mieCoefficient:.012,mieDirectionalG:.65,elevation:24,azimuth:170,exposure:.5,cloudCoverage:.78,cloudDensity:.72,cloudElevation:.43,showSunDisc:!1}},{id:"moonlit_night",names:["月夜星空","月夜星空","Moonlit Night"],params:{turbidity:4,rayleigh:.35,mieCoefficient:.001,mieDirectionalG:.82,elevation:-18,azimuth:160,exposure:.14,cloudCoverage:.1,cloudDensity:.14,cloudElevation:.55,showSunDisc:!1}}],roe=n6.reduce((t,e)=>(t[e.id]=e,t),{}),soe=2e6;class AGe{engine;sky=null;sun=new H;params={...noe,...roe[t6].params};currentPreset=t6;currentIntensity=ioe;currentEnvironmentTarget=null;skyScale=45e4;skyName="bim_engine_sky";savedCameraFar=null;previousBackground=null;previousEnvironment=null;previousBackgroundIntensity=1;previousEnvironmentIntensity=1;previousToneMapping=ll;previousToneMappingExposure=1;hasCapturedSceneState=!1;constructor(e){this.engine=e}activate(){if(!this.engine?.scene)return;if(this.sky){this.sky.visible=!0,this._captureSceneState(),this._expandCameraFarForSky(),this._applyParamsToSky();return}const e=new oN;e.scale.setScalar(this.skyScale),e.name=this.skyName,this.sky=e,this.engine.scene.add(e),this._captureSceneState(),this._expandCameraFarForSky(),this.engine.renderer&&(this.engine.renderer.toneMapping=kC,this.engine.scene.background=null),this._applyParamsToSky()}close(e=!0){this.sky&&(this._restoreCameraFar(),this._restoreSceneState(e),e?(this.engine?.scene?.remove(this.sky),this.sky.material.dispose(),this.sky.geometry.dispose(),this.sky=null):this.sky.visible=!1)}isActive(){return this.sky!=null&&this.engine?.scene?.children?.includes(this.sky)}getParams(){return{...this.params}}setParams(e){Object.assign(this.params,e),this._applyParamsToSky(),this.engine?.renderer&&(e.exposure!==void 0||e.orthoExposureScale!==void 0)&&(this.engine.renderer.toneMappingExposure=this._getEffectiveExposure())}setPreset(e){const n=roe[e];n&&(this.currentPreset=e,this.params={...noe,...n.params},this._applyParamsToSky(),this.engine?.renderer&&(this.engine.renderer.toneMappingExposure=this._getEffectiveExposure()))}getCurrentPreset(){return this.currentPreset}getPresetNames(){return n6.map(e=>e.id)}getPresetList(){return n6.map(e=>({id:e.id,names:[...e.names],params:{...e.params}}))}setIntensity(e){if(this.currentIntensity=Math.max(e,0),!(!this.sky?.visible||!this.engine?.scene)){if(!this.currentEnvironmentTarget){this._refreshEnvironmentMap();return}this.engine.scene.environmentIntensity=this.currentIntensity}}getIntensity(){return this.currentIntensity}update(e){if(!this.sky?.visible)return;const n=this.sky.material.uniforms;n&&"time"in n&&(n.time.value=e??performance.now()*.001),this.engine?.renderer&&(this.engine.renderer.toneMappingExposure=this._getEffectiveExposure())}_isOrthographicCamera(){const e=this.engine?.camera;return e!=null&&e.type==="OrthographicCamera"}_getEffectiveExposure(){const e=this.params.exposure;return this._isOrthographicCamera()?e*this.params.orthoExposureScale:e}_expandCameraFarForSky(){const e=this.engine?.camera;if(!e||typeof e.far!="number")return;const n=e.far;n>=soe||(this.savedCameraFar==null&&(this.savedCameraFar=n),e.far=soe,typeof e.updateProjectionMatrix=="function"&&e.updateProjectionMatrix())}_restoreCameraFar(){if(this.savedCameraFar==null||!this.engine?.camera)return;const e=this.engine.camera;typeof e.far=="number"&&(e.far=this.savedCameraFar,typeof e.updateProjectionMatrix=="function"&&e.updateProjectionMatrix(),this.savedCameraFar=null)}_applyParamsToSky(){if(!this.sky)return;const e=this.sky.material.uniforms;this._setUniformValue(e,"turbidity",this.params.turbidity),this._setUniformValue(e,"rayleigh",this.params.rayleigh),this._setUniformValue(e,"mieCoefficient",this.params.mieCoefficient),this._setUniformValue(e,"mieDirectionalG",this.params.mieDirectionalG),this._setUniformValue(e,"cloudCoverage",this.params.cloudCoverage),this._setUniformValue(e,"cloudDensity",this.params.cloudDensity),this._setUniformValue(e,"cloudElevation",this.params.cloudElevation),this._setUniformValue(e,"showSunDisc",this.params.showSunDisc?1:0);const n=Yn.degToRad(90-this.params.elevation),i=Yn.degToRad(this.params.azimuth);this.sun.setFromSphericalCoords(1,n,i),this._setUniformValue(e,"sunPosition",this.sun),this.engine?.renderer&&(this.engine.renderer.toneMapping=kC,this.engine.renderer.toneMappingExposure=this._getEffectiveExposure(),this.sky.visible&&this._refreshEnvironmentMap())}_captureSceneState(){this.hasCapturedSceneState||!this.engine?.scene||(this.previousBackground=this.engine.scene.background,this.previousEnvironment=this.engine.scene.environment,this.previousBackgroundIntensity=this.engine.scene.backgroundIntensity??1,this.previousEnvironmentIntensity=this.engine.scene.environmentIntensity??1,this.previousToneMapping=this.engine.renderer?.toneMapping??ll,this.previousToneMappingExposure=this.engine.renderer?.toneMappingExposure??1,this.hasCapturedSceneState=!0)}_restoreSceneState(e){!this.hasCapturedSceneState||!this.engine?.scene||(this.engine.scene.background=this.previousBackground,this.engine.scene.environment=this.previousEnvironment,this.engine.scene.backgroundIntensity=this.previousBackgroundIntensity,this.engine.scene.environmentIntensity=this.previousEnvironmentIntensity,this.engine.renderer&&(this.engine.renderer.toneMapping=this.previousToneMapping,this.engine.renderer.toneMappingExposure=this.previousToneMappingExposure),e&&(this._disposeEnvironmentTarget(),this.previousBackground=null,this.previousEnvironment=null,this.previousBackgroundIntensity=1,this.previousEnvironmentIntensity=1,this.previousToneMapping=ll,this.previousToneMappingExposure=1,this.hasCapturedSceneState=!1))}_refreshEnvironmentMap(){if(!this.sky||!this.engine?.renderer||!this.engine?.scene)return;this._disposeEnvironmentTarget();const e=new j0,n=this.sky.clone();n.material=this.sky.material.clone(),e.add(n);const i=new cI(this.engine.renderer);this.currentEnvironmentTarget=i.fromScene(e,0,.1,this.skyScale*2),i.dispose(),this.engine.scene.background=null,this.engine.scene.environment=this.currentEnvironmentTarget.texture,this.engine.scene.environmentIntensity=this.currentIntensity,n.material.dispose()}_disposeEnvironmentTarget(){this.currentEnvironmentTarget?.dispose(),this.currentEnvironmentTarget=null}_setUniformValue(e,n,i){const r=e[n];r&&(i instanceof H&&typeof r.value?.copy=="function"?r.value.copy(i):r.value=i)}}class yGe{engine;defaultSettings;settings;environmentApplyVersion=0;constructor(e){this.engine=e,this.defaultSettings=this._buildDefaultSettingsFromModules(),this.settings=this._clone(this.defaultSettings)}init(){this.defaultSettings=this._buildDefaultSettingsFromModules(),this.settings=this._clone(this.defaultSettings)}getSettings(){return this._syncSettingsFromModules(),this._clone(this.settings)}getPresetLists(){const e=this.engine.ground?.getGroundList()||[],n=this.engine.hdr?.getHdrList()||[],i=this.engine.skyManager?.getPresetList()||[];return{ground:e.map(r=>this._toPresetItem(r)),hdr:n.map(r=>this._toPresetItem(r)),sky:i.map(r=>this._toPresetItem(r))}}async setSettings(e){e.render&&(Object.assign(this.settings.render,e.render),this._applyRenderSettings(this.settings.render)),e.display&&(Object.assign(this.settings.display,e.display),this._applyDisplaySettings(this.settings.display)),e.environment&&(this._mergeEnvironmentSettings(e.environment),await this._applyEnvironmentSettings(this._clone(this.settings.environment)))}async resetToDefault(){this.settings=this._clone(this.defaultSettings),this._applyRenderSettings(this.settings.render),this._applyDisplaySettings(this.settings.display),await this._applyEnvironmentSettings(this._clone(this.settings.environment))}setRenderMode(e){this.settings.render.mode=e,this.engine.engineModelModule?.switchModel(e)}setContrast(e){this.settings.render.contrast=e,this.engine.engineModelModule?.setContrastValue(.5+e/100)}setSaturation(e){this.settings.render.saturation=e,this.engine.engineModelModule?.setSaturationValue(.5+e/100)}setShadowIntensity(e){this.settings.render.shadowIntensity=e,this._updateDirectionalLight(n=>{n.shadow.intensity=e/100*2})}setLightIntensity(e){this.settings.render.lightIntensity=e,this.setAmbientLightIntensity(e/100)}setGTAOIntensity(e){this.settings.render.gtaoIntensity=e,this.engine.engineModelModule?.setGTAOIntensity(e/100)}setShowEdge(e){this.settings.display.showEdge=e,e?this.engine.modelEdge?.active():this.engine.modelEdge?.disActive()}setEdgeOpacity(e){this.settings.display.edgeOpacity=e,this.engine.modelEdge?.setOpacity(e/100)}setShowGrid(e){this.settings.display.showGrid=e,e?this.engine.grid?.show():this.engine.grid?.hide()}setShowLevel(e){this.settings.display.showLevel=e,e?this.engine.level?.show():this.engine.level?.hide()}setShowGround(e){this.settings.display.showGround=e,e?this.engine.ground?.show():this.engine.ground?.hide()}setGroundId(e){this.settings.display.groundId=e,this.engine.ground?.setGround(e)}setGroundHeight(e){this.settings.display.groundHeight=e,this.engine.ground?.setHeight(e)}async setEnvironmentType(e){this.settings.environment.type=e,await this._applyEnvironmentSettings(this._clone(this.settings.environment))}async setHdrId(e){this.settings.environment.hdrId=e,this.settings.environment.type==="hdr"&&await this._applyEnvironmentSettings(this._clone(this.settings.environment))}setHdrIntensity(e){this.settings.environment.hdrIntensity=e,this.settings.environment.type==="hdr"&&this.engine.hdr?.setIntensity(e/100)}setSkyPreset(e){this.settings.environment.skyPreset=e,this.settings.environment.skyParams={},this.settings.environment.type==="sky"&&this.engine.skyManager?.setPreset(e)}setSkyParams(e){this.settings.environment.skyParams=this._clone(e),this.settings.environment.type==="sky"&&this.engine.skyManager?.setParams(this.settings.environment.skyParams)}setSkyIntensity(e){this.settings.environment.skyIntensity=e,this.settings.environment.type==="sky"&&this.engine.skyManager?.setIntensity(e/100)}setAmbientLightIntensity(e){const n=this.engine.renderer;n&&(n.toneMapping=lb,n.toneMappingExposure=2*e)}_syncSettingsFromModules(){this.settings=this._readCurrentSettingsFromModules()}_buildDefaultSettingsFromModules(){const e=this.engine.composerModule?.saturationPass?.uniforms?.saturation?.value,n=this.engine.composerModule?.saturationPass?.uniforms?.contrast?.value,i=this.engine.composerModule?.gtaoPass?.blendIntensity,r=this.engine.renderer?.toneMappingExposure,s=this.engine.modelEdge?.getOpacity?.(),o=this.engine.hdr?.getCurrentHdrId?.()??Im,a=this.engine.hdr?.getIntensity?.(),c=this.engine.skyManager?.getIntensity?.(),l=this.engine.skyManager?.getCurrentPreset?.()??t6,u=this.engine.skyManager?.isActive?.()===!0;return{render:{mode:this._toRenderMode(this.engine.engineModelModule?.getCurrentMode?.()),contrast:this._uniformToPercent(n,Zne),saturation:this._uniformToPercent(e,Jne),shadowIntensity:this._shadowToPercent(this._getDirectionalLightShadowIntensity(),NI),lightIntensity:this._exposureToPercent(r,wj),gtaoIntensity:this._unitToPercent(i,Kne)},display:{showEdge:this.engine.modelEdge?.isEnabled?.()??Z5,edgeOpacity:this._unitToPercent(s,e6),showGrid:this.engine.grid?.getVisible?.()??K5,showLevel:this.engine.level?.getVisible?.()??eoe,showGround:this.engine.ground?.getVisible?.()??Jse,groundId:this.engine.ground?.getCurrentId?.()??Qse,groundHeight:this.engine.ground?.getHeight?.()??Kse},environment:{type:u?"sky":o!==Im?"hdr":"none",hdrId:o,hdrIntensity:this._unitToPercent(a,Zse),skyPreset:l,skyParams:{},skyIntensity:this._unitToPercent(c,ioe)}}}_readCurrentSettingsFromModules(){const e=this.engine.composerModule?.saturationPass?.uniforms?.saturation?.value,n=this.engine.composerModule?.saturationPass?.uniforms?.contrast?.value,i=this.engine.composerModule?.gtaoPass?.blendIntensity,r=this.engine.renderer?.toneMappingExposure,s=this.engine.modelEdge?.getOpacity?.(),o=this.engine.hdr?.getCurrentHdrId?.()??this.settings.environment.hdrId,a=this.engine.hdr?.getIntensity?.(),c=this.engine.skyManager?.getIntensity?.(),l=this.engine.skyManager?.getCurrentPreset?.()??this.settings.environment.skyPreset,u=this.engine.skyManager?.getParams?.(),h=this.engine.skyManager?.isActive?.()===!0;return{render:{mode:this._toRenderMode(this.engine.engineModelModule?.getCurrentMode?.()??this.settings.render.mode),contrast:this._uniformToPercent(n,this.settings.render.contrast/100+.5),saturation:this._uniformToPercent(e,this.settings.render.saturation/100+.5),shadowIntensity:this._shadowToPercent(this._getDirectionalLightShadowIntensity(),this.settings.render.shadowIntensity/50),lightIntensity:this._exposureToPercent(r,this.settings.render.lightIntensity/50),gtaoIntensity:this._unitToPercent(i,this.settings.render.gtaoIntensity/100)},display:{showEdge:this.engine.modelEdge?.isEnabled?.()??this.settings.display.showEdge,edgeOpacity:this._unitToPercent(s,this.settings.display.edgeOpacity/100),showGrid:this.engine.grid?.getVisible?.()??this.settings.display.showGrid,showLevel:this.engine.level?.getVisible?.()??this.settings.display.showLevel,showGround:this.engine.ground?.getVisible?.()??this.settings.display.showGround,groundId:this.engine.ground?.getCurrentId?.()??this.settings.display.groundId,groundHeight:this.engine.ground?.getHeight?.()??this.settings.display.groundHeight},environment:{type:h?"sky":o!==Im?"hdr":"none",hdrId:o,hdrIntensity:this._unitToPercent(a,this.settings.environment.hdrIntensity/100),skyPreset:l,skyParams:u?this._clone(u):this._clone(this.settings.environment.skyParams),skyIntensity:this._unitToPercent(c,this.settings.environment.skyIntensity/100)}}}_toRenderMode(e){return e==="simple"||e==="balance"||e==="advanced"?e:kse}_uniformToPercent(e,n){const i=typeof e=="number"?e:n;return this._clampPercent((i-.5)*100)}_shadowToPercent(e,n){const i=typeof e=="number"?e:n;return this._clampPercent(i*50)}_exposureToPercent(e,n){const i=typeof e=="number"?e:n;return this._clampPercent(i*50)}_unitToPercent(e,n){const i=typeof e=="number"?e:n;return this._clampPercent(i*100)}_clampPercent(e){return Math.min(100,Math.max(0,Math.round(e)))}_getDirectionalLightShadowIntensity(){const e=this.engine.scene?.children?.filter(i=>i instanceof ep);return!e||e.length===0?NI:(e.find(i=>i.castShadow)??e[0]).shadow?.intensity??NI}_applyRenderSettings(e){this.setRenderMode(e.mode),this.setContrast(e.contrast),this.setSaturation(e.saturation),this.setShadowIntensity(e.shadowIntensity),this.setLightIntensity(e.lightIntensity),this.setGTAOIntensity(e.gtaoIntensity)}_applyDisplaySettings(e){this.setShowEdge(e.showEdge),this.setEdgeOpacity(e.edgeOpacity),this.setShowGrid(e.showGrid),this.setShowLevel(e.showLevel),this.setShowGround(e.showGround),this.setGroundId(e.groundId),this.setGroundHeight(e.groundHeight)}async _applyEnvironmentSettings(e){const n=++this.environmentApplyVersion;if(await this.engine.hdr?.setHdr(Im),n===this.environmentApplyVersion&&(this.engine.skyManager?.close(!0),n===this.environmentApplyVersion))switch(e.type){case"none":break;case"hdr":if(e.hdrId!==Im){if(await this.engine.hdr?.setHdr(e.hdrId),n!==this.environmentApplyVersion){this._applyEnvironmentSettings(this._clone(this.settings.environment));return}this.engine.hdr?.setIntensity(e.hdrIntensity/100)}break;case"sky":this.engine.skyManager?.activate(),this.engine.skyManager?.setPreset(e.skyPreset),Object.keys(e.skyParams).length>0&&this.engine.skyManager?.setParams(this._clone(e.skyParams)),this.engine.skyManager?.setIntensity(e.skyIntensity/100);break}}_updateDirectionalLight(e){const n=this.engine.scene?.children.find(i=>i instanceof ep);n&&e(n)}_mergeEnvironmentSettings(e){Object.assign(this.settings.environment,e),e.skyPreset!==void 0&&e.skyParams===void 0&&(this.settings.environment.skyParams={}),e.skyParams!==void 0&&(this.settings.environment.skyParams=this._clone(e.skyParams))}_toPresetItem(e){const n=Array.isArray(e.names)?[...e.names]:[];return{id:e.id,name:n[0]??e.id,names:n}}_clone(e){return JSON.parse(JSON.stringify(e))}}function op(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){var e=Math.random()*16|0,n=t=="x"?e:e&3|8;return n.toString(16)})}class og{engine;handelBehaved;setting;constructor(e){this.engine=e,this.handelBehaved=Hj(e),this.handelBehaved.init(this,null),this.setting={unit:"m",precision:3}}getSetting(){return this.setting}saveSetting(e){this.setting=e}active(){this.handelBehaved.active()}disActive(){this.handelBehaved.disActive()}getMeasureText(e,n){if(e==null)return null;let i=this.setting.unit,r=i;return n==1?i=="mm"?e=e*1e3:i=="cm"?e=e*100:i=="dm"?e=e*10:i=="m"?e=e*1:i=="km"&&(e=e*.001):n==2&&(i=="mm"?e=e*1e3*1e3:i=="cm"?e=e*100*100:i=="dm"?e=e*10*10:i=="m"?e=e*1*1:i=="km"&&(e=e*.001*.001),r=r+"²"),e.toFixed(this.setting.precision)+" "+r}cancelCurrentSelectedAnnotation(){let e=this.engine.measure.annotationData;for(let n in e)e[n].forEach(i=>{i.highlight==!0&&(i.highlight=!1,i.container.classList.remove("Hight"),i.container.getElementsByTagName("svg")[0].classList.remove("Hight"))})}handelKeyEscDown(){this.cancelCurrentSelectedAnnotation();let e=this.engine.measure.annotationData,n=!0;for(let i in e)for(let r=e[i].length-1;r>=0;r--){let s=e[i][r];s.isSelect==!0&&(s.container.remove(),e[i].splice(r,1),n=!1)}this.engine.measure.clearAllPoints(),n&&(this.engine.events.trigger("quit_measure_draw",!0),this.engine.modelToolModule.unhighlightAllModels(),this.engine.measure.quitDraw())}handelKeyDeleteDown(){let e=this.engine.measure.annotationData;for(let n in e)for(let i=e[n].length-1;i>=0;i--){let r=e[n][i];r.highlight==!0&&(r.container.remove(),e[n].splice(i,1))}}clearHighlight(){let e=this.engine.measure.annotationData;for(let n in e)e[n].forEach(i=>{i.highlight=!1,i.container.classList.remove("Hight"),i.container.getElementsByTagName("svg")[0].classList.remove("Hight")})}drawNormalAnnotation(){let e=this;const n=new ua(e.engine.camera,e.engine.renderer,e.engine.scene);function i(A){const v=n.worldToScreenIfVisible(A);return v==null?null:(v.x+=e.engine.reactBoundingClientRect.left,v.y+=e.engine.reactBoundingClientRect.top,v)}function r(A,v){A.container!=null&&(A.container.style.display=v?"block":"none")}this.engine.measure.annotationData.normalAnnotation.forEach(A=>{y(A)}),this.engine.measure.annotationData.elevationAnnotation.forEach(A=>{g(A)}),this.engine.measure.annotationData.coordinateAnnotation.forEach(A=>{m(A)}),this.engine.measure.annotationData.angleAnnotation.forEach(A=>{h(A)}),this.engine.measure.annotationData.areaAnnotation.forEach(A=>{d(A)}),this.engine.measure.annotationData.slopeAnnotation.forEach(A=>{p(A)});function h(A){if(A.container==null){let E=['<svg class="measureSvg">','<circle class="measurePointer" cx="50" cy="50" r="5" fill="#f99d0b" />','<circle class="measurePointer" cx="50" cy="50" r="5" fill="#f99d0b" />','<circle class="measurePointer" cx="50" cy="50" r="5" fill="#f99d0b" />','<polyline class="measureLine" stroke="orange" stroke-width="2" points="0,0 0,0" style="fill: none; opacity: 1;"/>','<polyline class="measureLine" stroke="orange" stroke-width="2" points="0,0 0,0" style="fill: none; opacity: 1;"/>','<rect x="0" y="0" width="100" height="25" class="measureBack" />','<text x="50" y="16" text-anchor="middle" class="measureLabel">'+A.text+"</text>","</svg>"].join("");A.container=document.createElement("div"),A.container.className="angle-annotation",A.container.id=A.id,A.container.style.pointerEvents="none",A.container.innerHTML=E,e.engine.measure.annotationContainer.appendChild(A.container),A.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),A.container.getElementsByTagName("svg")[0].classList.add("Hight"),A.highlight=!0,e.engine.events.trigger(Yo.MeasureClick,A)}),A.isSelect&&(A.container.getElementsByTagName("svg")[0].classList.add("Hight"),A.highlight=!0)}let v=i(A.point1),x=i(A.point2),C=i(A.point3);if(v==null||x==null||C==null){r(A,!1);return}r(A,!0);let T=A.container;T.getElementsByTagName("circle")[0].setAttribute("cx",v.x),T.getElementsByTagName("circle")[0].setAttribute("cy",v.y),T.getElementsByTagName("circle")[1].setAttribute("cx",x.x),T.getElementsByTagName("circle")[1].setAttribute("cy",x.y),T.getElementsByTagName("circle")[2].setAttribute("cx",C.x),T.getElementsByTagName("circle")[2].setAttribute("cy",C.y),T.getElementsByTagName("polyline")[0].setAttribute("points",v.x+","+v.y+" "+x.x+","+x.y),T.getElementsByTagName("polyline")[1].setAttribute("points",x.x+","+x.y+" "+C.x+","+C.y);let S=x.x,w=x.y-30;T.getElementsByTagName("rect")[0].setAttribute("x",S-40),T.getElementsByTagName("rect")[0].setAttribute("y",w-12.5),T.getElementsByTagName("text")[0].setAttribute("x",S),T.getElementsByTagName("text")[0].setAttribute("y",w+4),T.getElementsByTagName("text")[0].innerHTML=A.text,T.style.top="0px",T.style.left="0px"}function d(A){if(A.container==null){let P=['<svg class="measureSvg">','<polygon fill="rgba(0, 0, 255, 0.1)" stroke="none" points="" style="opacity: 0.3;"/>','<polyline class="measureLine" stroke="orange" stroke-width="2" points="" style="fill: none; opacity: 1;"/>','<rect x="0" y="0" width="100" height="25" class="measureBack" />','<text x="50" y="16" text-anchor="middle" class="measureLabel"> '+e.getMeasureText(A.text,2)+"</text>","</svg>"].join("");A.container=document.createElement("div"),A.container.className="area-annotation",A.container.id=A.id,A.container.innerHTML=P,e.engine.measure.annotationContainer.appendChild(A.container),A.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),A.container.getElementsByTagName("svg")[0].classList.add("Hight"),A.highlight=!0,e.engine.events.trigger(Yo.MeasureClick,A)}),A.isSelect&&(A.container.getElementsByTagName("svg")[0].classList.add("Hight"),A.highlight=!0)}if(!A.points||A.points.length<2)return;let v=[],x=0,C=0;for(let P=0;P<A.points.length;P++){let I=i(A.points[P]);if(I==null){r(A,!1);return}v.push(I),x+=I.x,C+=I.y}r(A,!0),x=x/v.length,C=C/v.length;let T=v.map(P=>P.x+","+P.y).join(" "),S=[...v];v.length>=3&&S.push(v[0]);let w=S.map(P=>P.x+","+P.y).join(" "),E=A.container;E.getElementsByTagName("polygon")[0].setAttribute("points",v.length>=3?T:""),E.getElementsByTagName("polyline")[0].setAttribute("points",w);let D=x,O=C;E.getElementsByTagName("rect")[0].setAttribute("x",D-40),E.getElementsByTagName("rect")[0].setAttribute("y",O-12.5),E.getElementsByTagName("text")[0].setAttribute("x",D+10),E.getElementsByTagName("text")[0].setAttribute("y",O+4),E.getElementsByTagName("text")[0].innerHTML=e.getMeasureText(A.text,2),E.style.top="0px",E.style.left="0px"}function p(A){if(A.container==null){let w=['<svg class="measureSvg">',"<defs>",'<marker id="slope-arrow-'+A.id+'" markerWidth="10" markerHeight="10" refX="9" refY="3" orient="auto" markerUnits="strokeWidth">','<path class="measureLine" d="M0,0 L0,6 L9,3 z"/>',"</marker>","</defs>",'<polyline class="measureLine" stroke="orange" stroke-width="2" points="0,0 0,0" marker-end="url(#slope-arrow-'+A.id+')" style="fill: none; opacity: 1;"/>','<rect x="0" y="0" width="100" height="25" class="measureBack" />','<text x="50" y="16" text-anchor="middle" class="measureLabel"> '+A.text+"</text>","</svg>"].join("");A.container=document.createElement("div"),A.container.className="slope-annotation",A.container.id=A.id,A.container.innerHTML=w,e.engine.measure.annotationContainer.appendChild(A.container),A.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),A.container.getElementsByTagName("svg")[0].classList.add("Hight"),A.highlight=!0,e.engine.events.trigger(Yo.MeasureClick,A)}),A.isSelect&&(A.container.getElementsByTagName("svg")[0].classList.add("Hight"),A.highlight=!0)}let v=i(A.point1),x=i(A.point2);if(v==null||x==null){r(A,!1);return}r(A,!0);let C=A.container;C.getElementsByTagName("polyline")[0].setAttribute("points",v.x+","+v.y+" "+x.x+","+x.y);let T=(v.x+x.x)/2,S=(v.y+x.y)/2-30;C.getElementsByTagName("rect")[0].setAttribute("x",T-50),C.getElementsByTagName("rect")[0].setAttribute("y",S-12.5),C.getElementsByTagName("text")[0].setAttribute("x",T),C.getElementsByTagName("text")[0].setAttribute("y",S+4),C.getElementsByTagName("text")[0].innerHTML=A.text,C.style.top="0px",C.style.left="0px"}function m(A){if(A.container==null){let E=['<svg class="measureSvg">','<circle class="measurePointer" cx="0" cy="0" r="5" fill="#f99d0b" />','<rect x="0" y="-25" width="100" height="25" class="measureBack" />','<text x="50" y="-11" text-anchor="middle" class="measureLabel"> X: '+e.getMeasureText(A.textX,1)+"</text>",'<rect x="0" y="-10" width="100" height="25" class="measureBack" />','<text x="50" y="25" text-anchor="middle" class="measureLabel"> Y: '+e.getMeasureText(-A.textZ,1)+"</text>",'<rect x="0" y="10" width="100" height="25" class="measureBack" />','<text x="50" y="51" text-anchor="middle" class="measureLabel"> Z: '+e.getMeasureText(A.textY,1)+"</text>","</svg>"].join("");A.container=document.createElement("div"),A.container.className="coordinate-annotation",A.container.id=A.id,A.container.style.position="absolute",A.container.style.pointerEvents="none",A.container.innerHTML=E,e.engine.measure.annotationContainer.appendChild(A.container),A.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),A.container.getElementsByTagName("svg")[0].classList.add("Hight"),A.highlight=!0,e.engine.events.trigger(Yo.MeasureClick,A)}),A.isSelect&&(A.container.getElementsByTagName("svg")[0].classList.add("Hight"),A.highlight=!0)}let v=A.container,x=i(A.point);if(x==null){r(A,!1);return}r(A,!0),v.style.top="0px",v.style.left="0px";let C=v.getElementsByTagName("circle")[0];C&&(C.setAttribute("cx",x.x),C.setAttribute("cy",x.y));let T=v.getElementsByTagName("rect"),S=v.getElementsByTagName("text"),w=-55;T[0]&&(T[0].setAttribute("x",x.x+10),T[0].setAttribute("y",x.y+10+w)),S[0]&&(S[0].setAttribute("x",x.x+10+50),S[0].setAttribute("y",x.y+10+16+w)),T[1]&&(T[1].setAttribute("x",x.x+10),T[1].setAttribute("y",x.y+10+30+w)),S[1]&&(S[1].setAttribute("x",x.x+10+50),S[1].setAttribute("y",x.y+10+46+w)),T[2]&&(T[2].setAttribute("x",x.x+10),T[2].setAttribute("y",x.y+10+60+w)),S[2]&&(S[2].setAttribute("x",x.x+10+50),S[2].setAttribute("y",x.y+10+76+w)),S[0]&&(S[0].innerHTML="X: "+e.getMeasureText(A.textX,1)),S[1]&&(S[1].innerHTML="Y: "+e.getMeasureText(-A.textZ,1)),S[2]&&(S[2].innerHTML="Z: "+e.getMeasureText(A.textY,1))}function g(A){if(A.container==null){let C=['<svg width="100" height="50" class="measureSvg">','<rect x="0" y="0" width="100" height="25" class="measureBack" />','<text x="50" y="16" text-anchor="middle" class="measureLabel"> '+e.getMeasureText(A.text,1)+"</text>",'<polyline class="measureLine" stroke-width="2" points="80,32 0,32 16,48 32,32" style="fill: none; opacity: 1;"/>',"</svg>"].join("");A.container=document.createElement("div"),A.container.className="elevation-annotation",A.container.id=A.id,A.container.style.position="absolute",A.container.style.pointerEvents="none",A.container.innerHTML=C,e.engine.measure.annotationContainer.appendChild(A.container),A.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),A.container.getElementsByTagName("svg")[0].classList.add("Hight"),A.highlight=!0,e.engine.events.trigger(Yo.MeasureClick,A)}),A.isSelect&&(A.container.getElementsByTagName("svg")[0].classList.add("Hight"),A.highlight=!0)}let v=A.container,x=i(A.point);if(x==null){r(A,!1);return}r(A,!0),v.style.top=x.y-48+"px",v.style.left=x.x-16+"px",v.getElementsByTagName("text")[0].innerHTML=e.getMeasureText(A.text,1)}function y(A){if(A.container==null){let T=['<svg class="measureSvg">','<circle class="measurePointer" cx="50" cy="50" r="5" fill="#f99d0b" />','<circle class="measurePointer" cx="50" cy="50" r="5" fill="#f99d0b" />','<polyline class="measureLine" stroke="orange" stroke-width="2" points="80,32 0,32" style="fill: none; opacity: 1;"/>','<rect x="0" y="0" width="100" height="25" class="measureBack" />','<text x="50" y="16" text-anchor="middle" class="measureLabel"> '+e.getMeasureText(A.text,1)+"</text>","</svg>"].join("");A.container=document.createElement("div"),A.container.className="normal-annotation",A.container.id=A.id,A.container.innerHTML=T,e.engine.measure.annotationContainer.appendChild(A.container),A.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),A.container.getElementsByTagName("svg")[0].classList.add("Hight"),A.highlight=!0,e.engine.events.trigger(Yo.MeasureClick,A)}),A.isSelect&&(A.container.getElementsByTagName("svg")[0].classList.add("Hight"),A.highlight=!0)}let v=A.container;if(A.point1==null||A.point2==null){v.style.display="none";return}else v.style.display="block";let x=i(A.point1),C=i(A.point2);if(x==null||C==null){r(A,!1);return}r(A,!0),v.getElementsByTagName("polyline")[0].setAttribute("points",x.x+","+x.y+" "+C.x+","+C.y),v.getElementsByTagName("circle")[0].setAttribute("cx",x.x),v.getElementsByTagName("circle")[0].setAttribute("cy",x.y),v.getElementsByTagName("circle")[1].setAttribute("cx",C.x),v.getElementsByTagName("circle")[1].setAttribute("cy",C.y),v.getElementsByTagName("rect")[0].setAttribute("x",x.x*.5+C.x*.5-40),v.getElementsByTagName("rect")[0].setAttribute("y",x.y*.5+C.y*.5-12.5),v.getElementsByTagName("text")[0].setAttribute("x",x.x*.5+C.x*.5+50-40),v.getElementsByTagName("text")[0].setAttribute("y",x.y*.5+C.y*.5+16-12.5),v.getElementsByTagName("text")[0].innerHTML=e.getMeasureText(A.text,1),v.style.top="0px",v.style.left="0px"}}}class bGe{engine;isActive=!1;tools;points=[];behavior;catchDir=0;type="point";constructor(e){this.engine=e,this.tools=new og(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.isActive=!0,this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1;let e=this.engine.measure.annotationData.normalAnnotation.find(n=>n.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.isActive=!1,this.behavior?.disActive()}clearAllPoints(){this.points=[]}setDirection(e){this.catchDir=e===0?0:1}handelKeyTabDown(e){e.preventDefault(),!e.repeat&&(this.catchDir=this.catchDir===0?1:0)}setSelectType(e){this.type=e}getMeshesMinMaxY(e){if(!Array.isArray(e)||e.length===0)return null;let n=Number.POSITIVE_INFINITY,i=Number.NEGATIVE_INFINITY;for(let r=0;r<e.length;r++){const s=e[r];if(!s)continue;typeof s.updateMatrixWorld=="function"&&s.updateMatrixWorld(!0);const o=new Ln().setFromObject(s);!Number.isFinite(o.min.y)||!Number.isFinite(o.max.y)||(o.min.y<n&&(n=o.min.y),o.max.y>i&&(i=o.max.y))}return!Number.isFinite(n)||!Number.isFinite(i)?null:{minY:n,maxY:i}}handleMouseClick(e){if(e.catch==null)return;let n=e.catch.point;if(this.type=="element"){let s=this.engine.interactionModule.getCatchMeshs(e);var i=this.getMeshesMinMaxY(s);this.catchDir==0?n.set(n.x,i?.minY,n.z):n.set(n.x,i?.maxY,n.z)}else n=e.catch.point;if(this.points.length==0){this.engine.measure.tools.clearHighlight(),this.points.push(n);return}let r=this.engine.measure.annotationData.normalAnnotation.find(s=>s.isSelect==!0);r!=null&&(r.isSelect=!1)}handleMouseMove(e){if(e.catch==null||this.points.length==0)return;let n=this.engine.measure.annotationData.normalAnnotation.find(r=>r.isSelect==!0);n==null&&(n={text:null,id:op(),isSelect:!0,type:"clear-height"},this.engine.measure.annotationData.normalAnnotation.push(n));let i=e.catch;if(this.type=="element"){let r=e.catch.point.clone();r.set(r.x,this.points[0].y,r.z);let s=new Da(r.add(new H(0,.01,0)),new H(0,this.catchDir==0?-1:1,0));i.point=this.points[0];const o=this.engine.clipping?.filterIntersectionsByClipping(this.engine.octreeBox.rayInterationModel(s))??this.engine.octreeBox.rayInterationModel(s);if(o.length===0){n.point2=null;return}n.point1=r,n.point2=o[0].point,n.text=n.point1.clone().distanceTo(n.point2.clone()),this.engine.events.trigger(Yo.MeasureChanged,n)}else{let r=new Da(e.catch.point.clone().add(new H(0,.01,0)),new H(0,this.catchDir==0?-1:1,0));const s=this.engine.clipping?.filterIntersectionsByClipping(this.engine.octreeBox.rayInterationModel(r))??this.engine.octreeBox.rayInterationModel(r);if(s.length===0){n.point2=null;return}n.point1=i.point,n.point2=s[0].point,n.text=n.point1.clone().distanceTo(n.point2.clone()),this.engine.events.trigger(Yo.MeasureChanged,n)}}}class vGe{engine;tools;isActive=!1;points=[];behavior;constructor(e){this.engine=e,this.tools=new og(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.isActive=!0,this.points=[],this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1;let e=this.engine.measure.annotationData.normalAnnotation.find(n=>n.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.points=[],this.isActive=!1,this.engine.handelBehaved.disActive()}clearAllPoints(){this.points=[]}handleMouseClick(e){if(e.catch==null)return;let n=e.catch;if(this.points.length==0)this.engine.measure.tools.clearHighlight(),this.points.push(n.point),this.behavior.setLastPoint(n.point);else if(this.points.length==1){let i=this.engine.measure.annotationData.normalAnnotation.find(r=>r.isSelect==!0);if(i==null)return;i.point2=n.point,i.isSelect=!1,this.points=[],this.engine.events.trigger(Yo.MeasureChanged,i),this.behavior.clearLastPoint()}}handleMouseMove(e){if(e.catch==null)return;let n=e.catch;if(n!=null&&this.points.length==1){let i=this.engine.measure.annotationData.normalAnnotation.find(r=>r.isSelect==!0);i==null&&(i={id:op(),point1:this.points[0].clone(),point2:n.point.clone(),text:this.points[0].clone().distanceTo(n.point.clone()),type:"distance",isSelect:!0},this.engine.measure.annotationData.normalAnnotation.push(i)),i.point2=n.point,i.text=i.point1.clone().distanceTo(i.point2.clone())}}}class xGe{engine;isActive=!1;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new og(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.isActive=!0,this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1;let e=this.engine.measure.annotationData.normalAnnotation.find(n=>n.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.isActive=!1,this.behavior?.disActive()}clearAllPoints(){this.points=[]}handleMouseClick(e){if(e.catch==null)return;if(this.points.length==0){this.engine.measure.tools.clearHighlight(),this.points.push(e.catch.point);return}let n=this.engine.measure.annotationData.normalAnnotation.find(i=>i.isSelect==!0);n!=null&&(n.isSelect=!1)}handleMouseMove(e){if(e.catch==null||this.points.length==0)return;let n=this.engine.measure.annotationData.normalAnnotation.find(o=>o.isSelect==!0);n==null&&(n={text:null,id:op(),isSelect:!0,type:"clear-distance"},this.engine.measure.annotationData.normalAnnotation.push(n));let i=new Da(e.catch.point.clone().add(e.catch.face.normal.clone().setLength(.01)),e.catch.face.normal);const r=this.engine.clipping?.filterIntersectionsByClipping(this.engine.octreeBox.rayInterationModel(i))??this.engine.octreeBox.rayInterationModel(i);if(r.length==0){n.point2=null;return}let s=e.catch;n.point1=s.point,n.point2=r[0].point,n.text=n.point1.clone().distanceTo(n.point2.clone()),this.engine.events.trigger(Yo.MeasureChanged,n)}}class CGe{engine;isActive=!1;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new og(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1,this.isActive=!0;let e=this.engine.measure.annotationData.normalAnnotation.find(n=>n.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.isActive=!1,this.behavior?.disActive()}clearAllPoints(){this.points=[]}handleMouseMove(e){if(e.catch==null)return;let n=this.engine.measure.annotationData.elevationAnnotation.find(i=>i.isSelect==!0);n!=null&&(n.point=e.catch.point.clone(),n.text=e.catch.point.y)}handleMouseClick(e){if(e.catch==null)return;this.engine.measure.tools.clearHighlight();let n=this.engine.measure.annotationData.elevationAnnotation.find(i=>i.isSelect==!0);if(n==null){n={id:op(),point:e.catch.point.clone(),text:e.catch.point.y,isSelect:!0,type:"elevation"},this.engine.measure.annotationData.elevationAnnotation.push(n);return}n.point=e.catch.point.clone(),n.text=e.catch.point.y,n.isSelect=!1,this.engine.events.trigger(Yo.MeasureChanged,n)}}class EGe{engine;isActive=!1;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new og(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1,this.isActive=!0;let e=this.engine.measure.annotationData.normalAnnotation.find(n=>n.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.isActive=!1,this.behavior?.disActive()}clearAllPoints(){this.points=[]}handleMouseUp(e){this.engine.deviceType!="PC"&&this.createMeasure()}handleMouseMove(e){if(e.catch==null)return;let n=this.engine.measure.annotationData.coordinateAnnotation.find(i=>i.isSelect==!0);n!=null&&(n.point=e.catch.point.clone(),n.textX=e.catch.point.x,n.textY=e.catch.point.y,n.textZ=e.catch.point.z)}handleMouseClick(e){if(e.catch==null)return;this.engine.measure.tools.clearHighlight();let n=this.engine.measure.annotationData.coordinateAnnotation.find(i=>i.isSelect==!0);if(n==null){n={id:op(),point:e.catch.point.clone(),text:Math.round(e.catch.point.y)+" m",isSelect:!0,type:"point"},this.engine.measure.annotationData.coordinateAnnotation.push(n);return}n.point=e.catch.point.clone(),n.textX=e.catch.point.x,n.textY=e.catch.point.y,n.textZ=e.catch.point.z,n.isSelect=!1,this.engine.events.trigger(Yo.MeasureChanged,n)}createMeasure(){let e=this.engine.measure.annotationData.coordinateAnnotation.find(n=>n.isSelect==!0);e!=null&&(e.isSelect=!1,this.engine.events.trigger(Yo.MeasureChanged,e))}}class wGe{engine;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new og(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.points=[],this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1;let e=this.engine.measure.annotationData.normalAnnotation.find(n=>n.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.points=[],this.behavior?.disActive()}clearAllPoints(){this.points=[]}calculateAngle(e,n,i){const r=new H().subVectors(e,n),s=new H().subVectors(i,n),o=r.length(),a=s.length();if(o===0||a===0)return 0;const l=r.dot(s)/(o*a),u=Math.max(-1,Math.min(1,l));return Math.acos(u)*(180/Math.PI)}handleMouseClick(e){if(e.catch==null)return;let n=e.catch;if(this.points.length==0)this.engine.measure.tools.clearHighlight(),this.points.push(n.point);else if(this.points.length==1)this.points.push(n.point);else if(this.points.length==2){let i=this.engine.measure.annotationData.angleAnnotation.find(r=>r.isSelect==!0);if(i==null)return;i.point3=n.point.clone(),i.angle=this.calculateAngle(i.point1,i.point2,i.point3),i.text=i.angle.toFixed(2)+"°",i.isSelect=!1,i.type="angle",this.points=[],this.engine.events.trigger(Yo.MeasureChanged,i)}}handleMouseMove(e){if(e.catch!=null&&this.points.length!=1&&this.points.length==2){let n=this.engine.measure.annotationData.angleAnnotation.find(i=>i.isSelect==!0);n==null&&(n={id:op(),point1:this.points[0].clone(),point2:this.points[1].clone(),point3:e.catch.point.clone(),angle:0,text:"0.00°",isSelect:!0,type:"angle"},this.engine.measure.annotationData.angleAnnotation.push(n)),n.point3=e.catch.point.clone(),n.angle=this.calculateAngle(n.point1,n.point2,n.point3),n.text=n.angle.toFixed(2)+"°",console.log("角度",n.text)}}}class TGe{engine;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new og(e)}getCurrentDrawingMeasure(){return this.engine.measure.annotationData.areaAnnotation.find(e=>e.isSelect==!0)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.points=[],this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1;const e=this.engine.measure.annotationData.normalAnnotation.find(n=>n.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.points=[],this.behavior?.disActive()}clearAllPoints(){this.points=[]}calculateArea(e){if(e.length<3)return 0;const n=e.length,i=new H(0,0,0);for(let r=0;r<n;r++){const s=(r+1)%n;i.x+=(e[r].y-e[s].y)*(e[r].z+e[s].z),i.y+=(e[r].z-e[s].z)*(e[r].x+e[s].x),i.z+=(e[r].x-e[s].x)*(e[r].y+e[s].y)}return i.length()/2}handleRightMouseClick(){this.finishMeasure()}handleMouseClick(e){if(e.catch==null)return;const n=e.catch;this.points.length===0&&this.engine.measure.tools.clearHighlight(),this.points.push(n.point.clone());let i=this.getCurrentDrawingMeasure();i==null?(i={id:op(),points:this.points.map(r=>r.clone()),area:0,text:0,isSelect:!0,type:"area"},this.engine.measure.annotationData.areaAnnotation.push(i)):i.points=this.points.map(r=>r.clone()),this.points.length>=3?(i.area=this.calculateArea(this.points),i.text=i.area):(i.area=0,i.text=0)}handleMouseMove(e){if(e.catch!=null&&this.points.length>=1){let n=this.getCurrentDrawingMeasure();n==null&&(n={id:op(),points:[],area:0,text:0,isSelect:!0,type:"area"},this.engine.measure.annotationData.areaAnnotation.push(n));const i=this.points.map(r=>r.clone());i.push(e.catch.point.clone()),n.points=i,i.length>=3?(n.area=this.calculateArea(i),n.text=n.area):(n.area=0,n.text=0)}}handelKeyEnterDown(){this.finishMeasure()}finishMeasure(){const e=this.getCurrentDrawingMeasure();e!=null&&this.points.length>=3?(e.points=this.points.map(n=>n.clone()),e.area=this.calculateArea(e.points),e.text=e.area,e.isSelect=!1,this.points=[],this.engine.events.trigger(Yo.MeasureChanged,e)):this.engine.measure.tools.handelKeyEscDown()}}class WI{engine;tools;static WORLD_UP=new H(0,1,0);static SLOPE_DIRECTION_SNAP_DISTANCE=10;points=[];behavior;constructor(e){this.engine=e,this.tools=new og(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.points=[],this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1;let e=this.engine.measure.annotationData.normalAnnotation.find(n=>n.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.points=[],this.behavior?.disActive()}clearAllPoints(){this.points=[]}calculateSlope(e,n){const i=n.y-e.y,r=n.x-e.x,s=n.z-e.z,o=Math.sqrt(r*r+s*s);if(o===0)return{percentage:0,angle:0,heightDiff:i,horizontalDist:0,type:"slope"};const a=i/o*100,l=Math.atan(i/o)*(180/Math.PI);return{percentage:a,angle:l,heightDiff:i,horizontalDist:o,type:"slope"}}getWorldFaceNormal(e){const n=e?.normal??e?.face?.normal;if(n==null)return null;const i=n.clone(),r=e?.matrix??e?.object?.matrixWorld;return r!=null&&i.transformDirection(r),i.lengthSq()<1e-10?null:i.normalize()}getFaceSlopeDirection(e){const n=this.getWorldFaceNormal(e);if(n==null)return null;const i=new H().crossVectors(n,WI.WORLD_UP);if(i.lengthSq()<1e-10)return null;const r=new H().crossVectors(i.normalize(),n);return r.lengthSq()<1e-10?null:r.normalize()}pointToScreenLineDistance(e,n,i){const r=new Ye().subVectors(i,n),s=r.lengthSq();if(s<1e-10)return e.distanceTo(n);const o=new Ye().subVectors(e,n).dot(r)/s,a=n.clone().add(r.multiplyScalar(o));return e.distanceTo(a)}isNearSlopeDirection(e,n,i,r,s){const o=new ua(this.engine.camera,this.engine.renderer,this.engine.scene),a=o.worldToScreenIfVisible(e);if(a==null)return!1;const c=Number.isFinite(s?.offsetX)&&Number.isFinite(s?.offsetY)?new Ye(s.offsetX,s.offsetY):o.worldToScreenIfVisible(r);if(c==null)return!1;const l=Math.max(e.distanceTo(r),e.distanceTo(i),1),u=e.clone().add(n.clone().multiplyScalar(l)),h=o.worldToScreenIfVisible(u);if(h!=null)return this.pointToScreenLineDistance(c,a,h)<=WI.SLOPE_DIRECTION_SNAP_DISTANCE;const d=o.worldToScreenIfVisible(i);return d!=null&&c.distanceTo(d)<=WI.SLOPE_DIRECTION_SNAP_DISTANCE}getSlopeSnappedPoint(e,n,i){const r=n?.point;if(!(r instanceof H))return e.clone();const s=this.getFaceSlopeDirection(n);if(s==null)return r.clone();const o=new H().subVectors(r,e).dot(s);if(!Number.isFinite(o))return r.clone();const a=e.clone().add(s.clone().multiplyScalar(o));return this.isNearSlopeDirection(e,s,a,r,i)?a:r.clone()}updateSlopeMeasure(e,n,i){e.point2=n.clone();const r=this.calculateSlope(e.point1,e.point2);e.slopePercentage=r.percentage,e.slopeAngle=r.angle,e.heightDiff=r.heightDiff,e.horizontalDist=r.horizontalDist,e.text=r.percentage.toFixed(2)+"%";const s=this.getWorldFaceNormal(i),o=this.getFaceSlopeDirection(i);e.faceNormal=s?.clone(),e.slopeDirection=o?.clone(),e.isSlopeDirectionSnapped=i?.point instanceof H?n.distanceTo(i.point)>1e-8:!1}handleMouseClick(e){if(e.catch==null)return;let n=e.catch;if(this.points.length==0)this.engine.measure.tools.clearHighlight(),this.points.push(n.point.clone());else if(this.points.length==1){let i=this.engine.measure.annotationData.slopeAnnotation.find(s=>s.isSelect==!0);if(i==null)return;const r=this.getSlopeSnappedPoint(i.point1,n,e);this.updateSlopeMeasure(i,r,n),i.isSelect=!1,this.points=[],this.engine.events.trigger(Yo.MeasureChanged,i)}}handleMouseMove(e){if(e.catch==null)return;let n=e.catch;if(n!=null&&this.points.length==1){let i=this.engine.measure.annotationData.slopeAnnotation.find(s=>s.isSelect==!0);i==null&&(i={id:op(),point1:this.points[0].clone(),point2:this.getSlopeSnappedPoint(this.points[0],n,e),slopePercentage:0,slopeAngle:0,heightDiff:0,horizontalDist:0,text:"0.00%",isSelect:!0,type:"slope"},this.engine.measure.annotationData.slopeAnnotation.push(i));const r=this.getSlopeSnappedPoint(i.point1,n,e);this.updateSlopeMeasure(i,r,n)}}}class SGe{engine;isActive=!1;points=[];behavior;constructor(e){this.engine=e}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.isActive=!0,this.points=[],this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1,this.behavior.clearLastPoint?.();let e=this.engine.measure.annotationData.normalAnnotation.find(n=>n.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.points=[],this.isActive=!1,this.behavior?.clearLastPoint?.(),this.behavior?.disActive?.()}clearAllPoints(){this.points=[],this.behavior?.clearLastPoint?.()}handleMouseClick(e){if(e.catch==null)return;if(this.points.length===0){this.engine.measure.tools.clearHighlight(),this.points=[e.catch.point.clone()],this.behavior?.setLastPoint?.(e.catch.point.clone());return}const n=this.getFaceInfo(e.catch);if(n==null)return;const i=this.points[0].clone(),r=this.projectPointToFace(i,n);if(r==null)return;let s=this.engine.measure.annotationData.normalAnnotation.find(o=>o.isSelect==!0);s==null&&(s={id:op(),type:"clear-distance",isSelect:!0},this.engine.measure.annotationData.normalAnnotation.push(s)),s.point1=i,s.point2=r.footPoint,s.text=r.distance,s.facePoint=n.point.clone(),s.faceNormal=n.normal.clone(),s.isSelect=!1,this.points=[],this.behavior?.clearLastPoint?.(),this.engine.events.trigger(Yo.MeasureChanged,s)}handleMouseMove(e){if(e.catch==null||this.points.length!==1)return;const n=this.getFaceInfo(e.catch);if(n==null)return;const i=this.points[0].clone(),r=this.projectPointToFace(i,n);if(r==null)return;let s=this.engine.measure.annotationData.normalAnnotation.find(o=>o.isSelect==!0);s==null&&(s={id:op(),point1:i.clone(),point2:r.footPoint.clone(),text:r.distance,type:"clear-distance",isSelect:!0},this.engine.measure.annotationData.normalAnnotation.push(s)),s.point1=i,s.point2=r.footPoint,s.text=r.distance,s.facePoint=n.point.clone(),s.faceNormal=n.normal.clone()}getFaceInfo(e){if(e?.face==null||e?.point==null)return null;const n=e.point.clone?.(),i=this.getWorldFaceNormal(e);return!(n instanceof H)||i==null?null:{point:n,normal:i}}getWorldFaceNormal(e){const n=e?.normal??e?.face?.normal;if(n==null)return null;const i=n.clone(),r=e?.matrix??e?.object?.matrixWorld;return r!=null&&i.transformDirection(r),i.lengthSq()<1e-10?null:i.normalize()}projectPointToFace(e,n){const i=new H().subVectors(e,n.point).dot(n.normal),r=e.clone().sub(n.normal.clone().multiplyScalar(i));return{footPoint:r,distance:e.distanceTo(r)}}}let IGe=class{isActive=!1;engine;clearHeightMeasure;distanceMeasure;clearDistanceMeasure;elevationMeasure;pointMeasure;angleMeasure;areaMeasure;slopeMeasure;faceDistanceMeasure;tools;annotationContainer;annotationData={normalAnnotation:[],textAnnotation:[],coordinateAnnotation:[],angleAnnotation:[],distanceAnnotation:[],areaAnnotation:[],slopeAnnotation:[],elevationAnnotation:[],volumeAnnotation:[]};constructor(e){this.engine=e,this.clearHeightMeasure=new bGe(e),this.distanceMeasure=new vGe(e),this.clearDistanceMeasure=new xGe(e),this.elevationMeasure=new CGe(e),this.pointMeasure=new EGe(e),this.angleMeasure=new wGe(e),this.areaMeasure=new TGe(e),this.slopeMeasure=new WI(e),this.faceDistanceMeasure=new SGe(e),this.tools=new og(e),this.annotationContainer=document.createElement("div"),this.annotationContainer.className="annotation-container",e.container.appendChild(this.annotationContainer)}setContextMenuDisabled(e){this.engine?.engineStatus!=null&&(this.engine.engineStatus.isDisableContextMenu=e)}active(){this.isActive=!0,this.engine.setIdleFrameRateExempt?.("measure",!0),this.setContextMenuDisabled(!0),this.engine.modelEdge.loadModelEdge(),this.tools.active()}disActive(){this.engine.setIdleFrameRateExempt?.("measure",!1),this.setContextMenuDisabled(!1),this.tools.disActive(),this.clearAll(),this.isActive=!1,this.clearHeightMeasure.disActive(),this.distanceMeasure.disActive(),this.clearDistanceMeasure.disActive(),this.elevationMeasure.disActive(),this.pointMeasure.disActive(),this.angleMeasure.disActive(),this.areaMeasure.disActive(),this.slopeMeasure.disActive(),this.faceDistanceMeasure.disActive(),this.engine.interactionModule.init(),this.engine.interactionModule.active()}quitDraw(){this.setContextMenuDisabled(!1),this.clearHeightMeasure.disActive(),this.distanceMeasure.disActive(),this.clearDistanceMeasure.disActive(),this.elevationMeasure.disActive(),this.pointMeasure.disActive(),this.angleMeasure.disActive(),this.areaMeasure.disActive(),this.slopeMeasure.disActive(),this.faceDistanceMeasure.disActive(),this.engine.interactionModule.init(),this.engine.interactionModule.active()}clearAllPoints(){this.clearHeightMeasure.clearAllPoints(),this.distanceMeasure.clearAllPoints(),this.clearDistanceMeasure.clearAllPoints(),this.elevationMeasure.clearAllPoints(),this.pointMeasure.clearAllPoints(),this.angleMeasure.clearAllPoints(),this.areaMeasure.clearAllPoints(),this.slopeMeasure.clearAllPoints(),this.faceDistanceMeasure.clearAllPoints()}clearAll(){e(this.annotationData.normalAnnotation),e(this.annotationData.textAnnotation),e(this.annotationData.coordinateAnnotation),e(this.annotationData.angleAnnotation),e(this.annotationData.distanceAnnotation),e(this.annotationData.areaAnnotation),e(this.annotationData.slopeAnnotation),e(this.annotationData.elevationAnnotation),e(this.annotationData.volumeAnnotation);function e(n){for(let i=0;i<n.length;i++)n[i].container.remove()}this.annotationData={normalAnnotation:[],textAnnotation:[],coordinateAnnotation:[],angleAnnotation:[],distanceAnnotation:[],areaAnnotation:[],slopeAnnotation:[],elevationAnnotation:[],volumeAnnotation:[]}}saveSetting(e){this.tools.saveSetting(e)}getSetting(){return this.tools.getSetting()}update(){this.isActive&&this.tools.drawNormalAnnotation()}dispose(){this.engine.setIdleFrameRateExempt?.("measure",!1),this.setContextMenuDisabled(!1),this.tools.disActive(),this.clearHeightMeasure.disActive(),this.distanceMeasure.disActive(),this.clearDistanceMeasure.disActive(),this.elevationMeasure.disActive(),this.pointMeasure.disActive(),this.angleMeasure.disActive(),this.areaMeasure.disActive(),this.slopeMeasure.disActive(),this.faceDistanceMeasure.disActive(),this.clearAll(),this.annotationContainer.remove(),this.isActive=!1}};class MGe{engine;isActive=!1;isCtrlDown=!1;listenersAttached=!1;box;pickPoint;pickNormal;pickMesh;box_;plane;meshs;isDrag=!1;maxBox;faceIdleOpacity=0;faceHoverOpacity=.05;mobileLongPressDelay=2e3;mobileLongPressMoveTolerance=10;touchLongPressTimer=null;touchLongPressActive=!1;touchStartPosition=null;touchLatestEvent=null;transformControls=new Map;transformAnchors=new Map;transformHelpers=new Map;faceMetaMap=new Map;isSyncingTransform=!1;transformHandleSize=1.05;transformHandleColor=255;transformHandleHoverColor=16776960;handleNativeMouseDown=e=>{if(e.button!==0||!(this.isCtrlDown||e.ctrlKey))return;const n=this.createRaycasterFromMouseEvent(e),i=n.intersectObjects(this.getInteractiveMeshes(),!1);i.length!==0&&(e.preventDefault(),e.stopImmediatePropagation(),this.handleMouseDown({button:e.button,raycaster:n,intersects:i}))};handleNativeMouseMove=e=>{if(!this.isDrag&&!(this.isCtrlDown||e.ctrlKey)){this.resetMeshOpacity();return}const n=this.createRaycasterFromMouseEvent(e),i=n.intersectObjects(this.getInteractiveMeshes(),!1);this.isDrag&&(e.preventDefault(),e.stopImmediatePropagation()),this.handleMouseMove({raycaster:n,intersects:i})};handleNativeMouseUp=e=>{e.button!==0||!this.isDrag||(e.preventDefault(),e.stopImmediatePropagation(),this.handleMouseUp({button:e.button}))};handleNativeTouchStart=e=>{if(!this.isActive||e.touches.length!==1||!this.isMobileDevice()){this.resetTouchLongPressState();return}const n=this.createMouseEventFromTouch(e);if(!n)return;if(this.createRaycasterFromMouseEvent(n).intersectObjects(this.getInteractiveMeshes(),!1).length===0){this.resetTouchLongPressState();return}e.preventDefault(),e.stopImmediatePropagation(),this.resetTouchLongPressState(),this.touchLatestEvent=n,this.touchStartPosition=this.getTouchPoint(e),this.touchLongPressTimer=window.setTimeout(()=>{const s=this.touchLatestEvent;if(!s||!this.isActive)return;const o=this.createRaycasterFromMouseEvent(s),a=o.intersectObjects(this.getInteractiveMeshes(),!1);a.length!==0&&(this.touchLongPressActive=!0,this.handleMouseDown({button:0,raycaster:o,intersects:a}))},this.mobileLongPressDelay)};handleNativeTouchMove=e=>{if(!this.isMobileDevice())return;if(e.touches.length!==1){this.resetTouchLongPressState();return}const n=this.createMouseEventFromTouch(e);if(!n)return;this.touchLatestEvent=n;const i=this.getTouchPoint(e);if(!this.touchLongPressActive&&this.touchStartPosition&&i&&this.touchStartPosition.distanceTo(i)>this.mobileLongPressMoveTolerance&&this.clearTouchLongPressTimer(),!this.touchLongPressActive)return;e.preventDefault(),e.stopImmediatePropagation();const r=this.createRaycasterFromMouseEvent(n),s=r.intersectObjects(this.getInteractiveMeshes(),!1);this.handleMouseMove({raycaster:r,intersects:s})};handleNativeTouchEnd=e=>{this.isMobileDevice()&&(this.clearTouchLongPressTimer(),this.touchLongPressActive&&(e.preventDefault(),e.stopImmediatePropagation(),this.handleMouseUp({button:0})),this.resetTouchLongPressState())};handleNativeKeyDown=e=>{e.key==="Control"&&(this.isCtrlDown=!0)};handleNativeKeyUp=e=>{e.key==="Control"&&(this.isCtrlDown=!1,this.isDrag&&this.handleMouseUp({button:0}),this.resetMeshOpacity())};constructor(e,n){this.engine=e,this.meshs=[]}active(){this.isActive||(this.attachListeners(),this.init(),this.setTransformControlsVisible(!0),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(n=>{n.name.includes("face")||(n.visible=!0)})}),this.isActive=!0)}disActive(){this.init(!1),this.isActive=!1,this.detachListeners(),this.handleMouseUp({button:0},!1),this.setTransformControlsVisible(!1),this.clearClippingBoxFill(),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(n=>{n.name.includes("face")||(n.visible=!1)})})}disabled(){this.isActive=!1,this.detachListeners(),this.handleMouseUp({button:0},!1),this.setTransformControlsVisible(!1),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(n=>{n.name.includes("face")||(n.visible=!1)})})}recover(){this.isActive||(this.attachListeners(),this.setTransformControlsVisible(!0),this.updateClippingBoxFill(),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(n=>{n.name.includes("face")||(n.visible=!0)})}),this.isActive=!0)}init(e=!0){const n=this.engine.octreeBox.getBoundingBox();n.min.x-=.1,n.min.y-=.1,n.min.z-=.1,n.max.x+=.1,n.max.y+=.1,n.max.z+=.1,this.maxBox=JSON.parse(JSON.stringify(n)),this.box=n,this.updata_face(n),e&&this.updateClippingBoxFill()}getboxXyz(){return{minX:this.box.min.x,minY:this.box.min.y,minZ:this.box.min.z,maxX:this.box.max.x,maxY:this.box.max.y,maxZ:this.box.max.z}}setboxXyz(e){this.box.min.x=e.minX,this.box.min.y=e.minY,this.box.min.z=e.minZ,this.box.max.x=e.maxX,this.box.max.y=e.maxY,this.box.max.z=e.maxZ,this.updata_face(this.box),this.updateClippingBoxFill()}setBox(e){this.box=e,this.updata_face(e),this.updateClippingBoxFill()}reverseBox(){}handleMouseDown(e){const n=e.intersects??e.raycaster.intersectObjects(this.getInteractiveMeshes(),!1);if(n!=null&&n.length>0){this.clearClippingBoxFill();const i=n[0];this.isDrag=!0,this.pickPoint=i.point.clone(),this.pickMesh=i.object;const r=this.pickMesh?.userData?.dragNormal?.clone?.(),s=i.face?.normal?.clone?.();if(this.pickNormal=(r??s??new H(0,0,1)).clone().normalize(),this.engine.controls.enabled=!1,this.box_={min:this.box.min.clone(),max:this.box.max.clone()},this.pickNormal.y==0){const o=new Zi;o.setFromNormalAndCoplanarPoint(new H(0,1,0),this.pickPoint),this.plane=o}else{const o=new H(this.engine.camera.position.x,this.pickPoint.y,this.engine.camera.position.z),a=new Zi;a.setFromNormalAndCoplanarPoint(o.clone().sub(this.pickPoint.clone()).setLength(1),this.pickPoint),this.plane=a}}else this.isDrag=!1}handleMouseUp(e,n=!0){this.isDrag=!1,this.pickPoint=null,this.pickNormal=null,this.pickMesh=null,this.plane=null,this.engine.controls.enabled=!0,n&&this.updateClippingBoxFill()}clampVector3(e,n,i){return new H(Math.max(n.x,Math.min(i.x,e.x)),Math.max(n.y,Math.min(i.y,e.y)),Math.max(n.z,Math.min(i.z,e.z)))}handleMouseMove(e){this.resetMeshOpacity();const n=e.intersects??e.raycaster.intersectObjects(this.getInteractiveMeshes(),!1);if(n!=null&&n.length>0&&(n[0].object.material.opacity=this.faceHoverOpacity),this.pickPoint!=null){const i=new H;if(e.raycaster.ray.intersectPlane(this.plane,i)){const r=i.clone().sub(this.pickPoint.clone()).dot(this.pickNormal.clone());if(!!this.pickMesh?.userData?.isMinFace){const o=this.box_.min.clone().add(this.pickNormal.clone().setLength(r));this.box.min=this.clampVector3(o,this.maxBox.min,this.box.max)}else{const o=this.box_.max.clone().add(this.pickNormal.clone().setLength(r));this.box.max=this.clampVector3(o,this.box.min,this.maxBox.max)}this.updata_face(this.box),this.calculate_ratio()}}}calculate_ratio(){const e=this.maxBox.max.x-this.maxBox.min.x,n=this.maxBox.max.y-this.maxBox.min.y,i=this.maxBox.max.z-this.maxBox.min.z,r=this.toPercent((this.box.min.x-this.maxBox.min.x)/e*100),s=this.toPercent((this.box.max.x-this.maxBox.min.x)/e*100),o=this.toPercent((this.box.min.y-this.maxBox.min.y)/n*100),a=this.toPercent((this.box.max.y-this.maxBox.min.y)/n*100),c=this.toPercent((this.box.min.z-this.maxBox.min.z)/i*100),l=this.toPercent((this.box.max.z-this.maxBox.min.z)/i*100),u={x:{min:r,max:s},y:{min:o,max:a},z:{min:c,max:l}};this.engine.events.trigger(Yo.SectionMove,u)}toPercent(e){return e<0?0:e>100?100:e}getInteractiveMeshes(){return this.meshs.filter(e=>e.type==="Mesh")}createRaycasterFromMouseEvent(e){const n=new Da,i=new Ye,r=this.engine.renderer.domElement.clientWidth,s=this.engine.renderer.domElement.clientHeight;return i.x=e.offsetX/r*2-1,i.y=-(e.offsetY/s)*2+1,n.setFromCamera(i,this.engine.camera),n}isMobileDevice(){return this.engine?.deviceModule?.isMobile?.()===!0||this.engine?.deviceType==="mobile"}getTouchPoint(e){const n=e.touches[0]||e.changedTouches[0];return n?new Ye(n.clientX,n.clientY):null}createMouseEventFromTouch(e){const n=e.touches[0]||e.changedTouches[0],i=this.engine.renderer?.domElement;if(!n||!i)return null;const r=i.getBoundingClientRect();return{offsetX:n.clientX-r.left,offsetY:n.clientY-r.top,clientX:n.clientX,clientY:n.clientY,button:0}}clearTouchLongPressTimer(){this.touchLongPressTimer!=null&&(clearTimeout(this.touchLongPressTimer),this.touchLongPressTimer=null)}resetTouchLongPressState(){this.clearTouchLongPressTimer(),this.touchLongPressActive=!1,this.touchStartPosition=null,this.touchLatestEvent=null}attachListeners(){if(this.listenersAttached)return;const e=this.engine.renderer?.domElement;e&&(e.addEventListener("mousedown",this.handleNativeMouseDown,!0),e.addEventListener("mousemove",this.handleNativeMouseMove,!0),e.addEventListener("mouseup",this.handleNativeMouseUp,!0),e.addEventListener("touchstart",this.handleNativeTouchStart,{capture:!0,passive:!1}),e.addEventListener("touchmove",this.handleNativeTouchMove,{capture:!0,passive:!1}),e.addEventListener("touchend",this.handleNativeTouchEnd,{capture:!0,passive:!1}),e.addEventListener("touchcancel",this.handleNativeTouchEnd,{capture:!0,passive:!1}),window.addEventListener("keydown",this.handleNativeKeyDown),window.addEventListener("keyup",this.handleNativeKeyUp),this.listenersAttached=!0)}detachListeners(){if(!this.listenersAttached)return;const e=this.engine.renderer?.domElement;e&&(e.removeEventListener("mousedown",this.handleNativeMouseDown,!0),e.removeEventListener("mousemove",this.handleNativeMouseMove,!0),e.removeEventListener("mouseup",this.handleNativeMouseUp,!0),e.removeEventListener("touchstart",this.handleNativeTouchStart,!0),e.removeEventListener("touchmove",this.handleNativeTouchMove,!0),e.removeEventListener("touchend",this.handleNativeTouchEnd,!0),e.removeEventListener("touchcancel",this.handleNativeTouchEnd,!0)),window.removeEventListener("keydown",this.handleNativeKeyDown),window.removeEventListener("keyup",this.handleNativeKeyUp),this.listenersAttached=!1,this.isCtrlDown=!1,this.resetTouchLongPressState()}resetMeshOpacity(){this.getInteractiveMeshes().forEach(e=>{e.material&&(e.material.opacity=this.faceIdleOpacity)})}updateClippingBoxFill(){const e=(Array.isArray(this.engine.sectionPlane)?this.engine.sectionPlane:[]).slice(0,6).filter(n=>n instanceof Zi);if(e.length===0){this.clearClippingBoxFill();return}this.engine.clipping?.clippingCSGSimple?.updataFaces?.(e)}clearClippingBoxFill(){this.engine.clipping?.clippingCSGSimple?.clear?.()}getFaceTransformOffset(){if(!this.box)return .06;const e=this.box.min.distanceTo(this.box.max);return Math.max(e*.015,.06)}keepSingleDirectionArrow(e,n="X"){const i=e.getHelper(),r=[];i.traverse(s=>{if(s?.name!==n||!s.geometry)return;const o=s.geometry;o.boundingBox||o.computeBoundingBox();const a=o.boundingBox;if(!a)return;const c=a.getCenter(new H);if(!(n==="X"&&c.x<0||n==="Y"&&c.y<0||n==="Z"&&c.z<0))return;const u=o.parameters,h=u&&u.radiusTop===0&&u.radiusBottom===.04&&u.height===.1,d=u&&u.radiusTop===.2&&u.radiusBottom===0&&u.height===.6;(h||d)&&r.push(s)}),r.forEach(s=>{s.parent?.remove(s)})}setTransformControlsVisible(e){this.transformControls.forEach(n=>{n.enabled=e}),this.transformHelpers.forEach(n=>{n.visible=e}),this.transformAnchors.forEach(n=>{n.visible=e}),e||(this.engine.controls.enabled=!0)}ensureFaceTransformControl(e){if(this.transformControls.has(e)&&this.transformAnchors.has(e))return;const n=this.engine.renderer?.domElement,i=this.engine.camera;if(!n||!i)return;const r=new Ni;r.name=`SectionBoxTransformAnchor_${e}`,r.visible=this.isActive,this.engine.scene.add(r);const s=new tN(i,n);s.name=`SectionBoxTransformControl_${e}`,s.setMode("translate"),s.setSpace("local"),s.showX=!0,s.showY=!1,s.showZ=!1,s.size=this.transformHandleSize,s.setColors(this.transformHandleColor,this.transformHandleColor,this.transformHandleColor,this.transformHandleHoverColor),s.enabled=this.isActive,s.attach(r),this.keepSingleDirectionArrow(s,"X"),s.addEventListener("dragging-changed",a=>{this.engine.controls.enabled=!a.value,a.value===!0?this.clearClippingBoxFill():this.updateClippingBoxFill()}),s.addEventListener("objectChange",()=>{this.handleTransformObjectChange(e)});const o=s.getHelper();o.userData.excludeFromAmbientOcclusion=!0,o.visible=this.isActive,this.engine.scene.add(o),this.transformAnchors.set(e,r),this.transformControls.set(e,s),this.transformHelpers.set(e,o)}updateFaceTransformControl(e,n,i,r){this.ensureFaceTransformControl(e);const s=this.transformAnchors.get(e),o=this.transformControls.get(e);if(!s||!o)return;const a=this.getFaceTransformOffset(),c=new ni().setFromUnitVectors(new H(1,0,0),n.clone().normalize()),l=i.clone().add(n.clone().setLength(a));this.faceMetaMap.set(e,{normal:n.clone().normalize(),isMinFace:r,center:i.clone()}),this.isSyncingTransform=!0,s.position.copy(l),s.quaternion.copy(c),s.visible=this.isActive,o.object!==s&&o.attach(s),o.enabled=this.isActive;const u=this.transformHelpers.get(e);u&&(u.visible=this.isActive),this.isSyncingTransform=!1}getDominantAxis(e){const n=Math.abs(e.x),i=Math.abs(e.y),r=Math.abs(e.z);return n>=i&&n>=r?"x":i>=n&&i>=r?"y":"z"}handleTransformObjectChange(e){if(this.isSyncingTransform)return;const n=this.transformAnchors.get(e),i=this.faceMetaMap.get(e);if(!n||!i||!this.box||!this.maxBox)return;const r=i.normal,s=this.getDominantAxis(r),o=this.getFaceTransformOffset(),a=r[s],c=n.position[s]-a*o;if(i.isMinFace){const l=this.maxBox.min[s],u=this.box.max[s];this.box.min[s]=Math.max(l,Math.min(u,c))}else{const l=this.box.min[s],u=this.maxBox.max[s];this.box.max[s]=Math.max(l,Math.min(u,c))}this.updata_face(this.box),this.calculate_ratio()}updata_face(e){let n=this.engine.scene.children.find(r=>r.type=="Group"&&r.name=="ClippingBox");n==null&&(n=new $r,n.name="ClippingBox",this.engine.scene.add(n)),[{name:"前",normal:new H(0,0,-1),isMinFace:!0,planePoint:e.min,vertices:[new H(e.min.x,e.max.y,e.min.z),new H(e.max.x,e.max.y,e.min.z),new H(e.max.x,e.min.y,e.min.z),new H(e.min.x,e.min.y,e.min.z)]},{name:"后",normal:new H(0,0,1),isMinFace:!1,planePoint:e.max,vertices:[new H(e.min.x,e.min.y,e.max.z),new H(e.max.x,e.min.y,e.max.z),new H(e.max.x,e.max.y,e.max.z),new H(e.min.x,e.max.y,e.max.z)]},{name:"右",normal:new H(1,0,0),isMinFace:!1,planePoint:e.max,vertices:[new H(e.max.x,e.min.y,e.max.z),new H(e.max.x,e.min.y,e.min.z),new H(e.max.x,e.max.y,e.min.z),new H(e.max.x,e.max.y,e.max.z)]},{name:"左",normal:new H(-1,0,0),isMinFace:!0,planePoint:e.min,vertices:[new H(e.min.x,e.min.y,e.min.z),new H(e.min.x,e.min.y,e.max.z),new H(e.min.x,e.max.y,e.max.z),new H(e.min.x,e.max.y,e.min.z)]},{name:"顶",normal:new H(0,1,0),isMinFace:!1,planePoint:e.max,vertices:[new H(e.min.x,e.max.y,e.max.z),new H(e.max.x,e.max.y,e.max.z),new H(e.max.x,e.max.y,e.min.z),new H(e.min.x,e.max.y,e.min.z)]},{name:"底",normal:new H(0,-1,0),isMinFace:!0,planePoint:e.min,vertices:[new H(e.min.x,e.min.y,e.min.z),new H(e.max.x,e.min.y,e.min.z),new H(e.max.x,e.min.y,e.max.z),new H(e.min.x,e.min.y,e.max.z)]}].forEach(r=>{this.createFace(n,r.vertices,r.normal,r.name,r.isMinFace,r.planePoint)}),zj(this.engine).forEach(r=>{r.material&&Array.isArray(r.material)?r.material.forEach(s=>{s.clippingPlanes=this.engine.sectionPlane}):r.material.clippingPlanes=this.engine.sectionPlane})}createFace(e,n,i,r,s,o){const a=new Dn,c=new Float32Array([n[0].x,n[0].y,n[0].z,n[1].x,n[1].y,n[1].z,n[2].x,n[2].y,n[2].z,n[3].x,n[3].y,n[3].z]),l=[0,2,1,0,3,2];a.setAttribute("position",new ji(c,3)),a.setIndex(l);let u=this.meshs.find(A=>A.name===r);if(u==null){const A=new Xi({color:65280,transparent:!0,opacity:this.faceIdleOpacity,side:tr});A.polygonOffset=!0,A.polygonOffsetFactor=1,A.polygonOffsetUnits=4,u=new bt(a,A),u.name=r,e.add(u),this.meshs.push(u)}else u.geometry=a;u.userData={dragNormal:i.clone(),isMinFace:s,faceName:r,excludeFromAmbientOcclusion:!0};const h=new Float32Array([n[0].x,n[0].y,n[0].z,n[1].x,n[1].y,n[1].z,n[2].x,n[2].y,n[2].z,n[3].x,n[3].y,n[3].z,n[0].x,n[0].y,n[0].z]),d=new Bs({color:255}),p=new Dn;p.setAttribute("position",new ji(h,3));let m=this.meshs.find(A=>A.name===r+"Line");m==null?(m=new ho(p,d),m.name=r+"Line",e.add(m),this.meshs.push(m)):(m.geometry=p,m.material=d);const g=new H;n.forEach(A=>g.add(A)),g.multiplyScalar(1/n.length),this.updateFaceTransformControl(r,i,g,s);const y=this.engine.sectionPlane.find(A=>A.name==r);y&&y.setFromNormalAndCoplanarPoint(i.clone().setLength(-1),o)}}class PGe{engine;isActive=!1;isDrag=!1;isCtrlDown=!1;listenersAttached=!1;meshs=[];box=null;pickPoint=null;pickNormal=null;plane=null;angleX=0;angleY=0;angleZ=0;direction=1;normal=new H(0,0,1);distance=0;center=null;current_center=null;dragStartDistance=0;dragStartCenter=null;idleOpacity=0;hoverOpacity=.05;transformControl=null;transformAnchor=null;transformHelper=null;rotateControl=null;rotateAnchor=null;rotateHelper=null;rotatePivot=null;isSyncingTransformControl=!1;isSyncingRotateControl=!1;activeControlMode=null;moveEpsilon=1e-5;transformHandleSize=1.15;rotateHandleSize=.8;transformHandleColor=255;transformHandleHoverColor=16776960;mobileLongPressDelay=2e3;mobileLongPressMoveTolerance=10;touchLongPressTimer=null;touchLongPressActive=!1;touchStartPosition=null;touchLatestEvent=null;handleNativePointerDown=e=>{if(e.button!==0||!this.isActive)return;this.transformControl?.dragging!==!0&&this.rotateControl?.dragging!==!0&&this.releaseControlModeLock();const n=this.pickControlModeFromPointer(e);n&&this.lockControlMode(n)};handleNativePointerUp=()=>{window.setTimeout(()=>{this.transformControl?.dragging===!0||this.rotateControl?.dragging===!0||this.releaseControlModeLock()},0)};handleNativeMouseDown=e=>{if(e.button!==0||!(this.isCtrlDown||e.ctrlKey))return;const n=this.createRaycasterFromMouseEvent(e),i=n.intersectObjects(this.getInteractiveMeshes(),!1);i.length!==0&&(e.preventDefault(),e.stopImmediatePropagation(),this.handleMouseDown({button:e.button,raycaster:n,intersects:i}))};handleNativeMouseMove=e=>{if(!this.isDrag&&!(this.isCtrlDown||e.ctrlKey)){this.resetMeshOpacity();return}const n=this.createRaycasterFromMouseEvent(e),i=n.intersectObjects(this.getInteractiveMeshes(),!1);this.isDrag&&(e.preventDefault(),e.stopImmediatePropagation()),this.handleMouseMove({raycaster:n,intersects:i})};handleNativeMouseUp=e=>{e.button!==0||!this.isDrag||(e.preventDefault(),e.stopImmediatePropagation(),this.handleMouseUp({button:e.button}))};handleNativeTouchStart=e=>{if(!this.isActive||e.touches.length!==1||!this.isMobileDevice()){this.resetTouchLongPressState();return}const n=this.createMouseEventFromTouch(e);if(!n)return;if(this.createRaycasterFromMouseEvent(n).intersectObjects(this.getInteractiveMeshes(),!1).length===0){this.resetTouchLongPressState();return}e.preventDefault(),e.stopImmediatePropagation(),this.resetTouchLongPressState(),this.touchLatestEvent=n,this.touchStartPosition=this.getTouchPoint(e),this.touchLongPressTimer=window.setTimeout(()=>{const s=this.touchLatestEvent;if(!s||!this.isActive)return;const o=this.createRaycasterFromMouseEvent(s),a=o.intersectObjects(this.getInteractiveMeshes(),!1);a.length!==0&&(this.touchLongPressActive=!0,this.handleMouseDown({button:0,raycaster:o,intersects:a}))},this.mobileLongPressDelay)};handleNativeTouchMove=e=>{if(!this.isMobileDevice())return;if(e.touches.length!==1){this.resetTouchLongPressState();return}const n=this.createMouseEventFromTouch(e);if(!n)return;this.touchLatestEvent=n;const i=this.getTouchPoint(e);if(!this.touchLongPressActive&&this.touchStartPosition&&i&&this.touchStartPosition.distanceTo(i)>this.mobileLongPressMoveTolerance&&this.clearTouchLongPressTimer(),!this.touchLongPressActive)return;e.preventDefault(),e.stopImmediatePropagation();const r=this.createRaycasterFromMouseEvent(n),s=r.intersectObjects(this.getInteractiveMeshes(),!1);this.handleMouseMove({raycaster:r,intersects:s})};handleNativeTouchEnd=e=>{this.isMobileDevice()&&(this.clearTouchLongPressTimer(),this.touchLongPressActive&&(e.preventDefault(),e.stopImmediatePropagation(),this.handleMouseUp({button:0})),this.resetTouchLongPressState())};handleNativeKeyDown=e=>{e.key==="Control"&&(this.isCtrlDown=!0)};handleNativeKeyUp=e=>{e.key==="Control"&&(this.isCtrlDown=!1,this.isDrag&&this.handleMouseUp({button:0}),this.resetMeshOpacity())};handleTransformObjectChange=()=>{if(this.isSyncingTransformControl||this.activeControlMode==="rotate"||this.rotateControl?.dragging===!0||!this.transformAnchor||!this.center||!this.current_center)return;const e=this.normal.clone().normalize(),n=this.getEffectiveNormal(e),i=this.getDistanceRange(e),r=this.getTransformHandleOffset(),s=this.current_center.clone().sub(this.center).dot(e),o=this.transformAnchor.position.clone().sub(this.center).dot(e)-r*this.getDirectionSign(),a=Math.min(i.max,Math.max(i.min,o));if(Math.abs(a-Number(this.distance))>this.moveEpsilon){const c=this.current_center.clone().add(e.clone().multiplyScalar(a-s));this.updata_face(a,c)}else Math.abs(o-a)>this.moveEpsilon&&this.updateTransformControl(n)};handleRotateObjectChange=()=>{if(this.isSyncingRotateControl||this.activeControlMode==="translate"||this.transformControl?.dragging===!0||!this.rotateAnchor||!this.center||!this.current_center)return;const n=new H(0,0,1).applyQuaternion(this.rotateAnchor.quaternion).normalize().multiplyScalar(this.getDirectionSign()).normalize(),i=(this.rotatePivot??this.rotateAnchor.position??this.current_center).clone(),r=i.clone().sub(this.center).dot(n);n.lengthSq()<=this.moveEpsilon||(this.normal.copy(n),this.updata_face(r,i))};constructor(e){this.engine=e,this.meshs=[],this.box=null}active(){this.isActive!=!0&&(this.isActive=!0,this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(n=>{n.name.includes("face")&&(n.visible=!0)})}),this.attachListeners(),this.ensureTransformControl(),this.ensureRotateControl(),this.setTransformControlVisible(!0),this.applyClippingToModelMeshes(),this.init())}disActive(){this.init(),this.isActive=!1,this.detachListeners(),this.handleMouseUp({button:0},!1),this.setTransformControlVisible(!1),this.clearClippingFaceFill();const e=this.engine.sectionPlane.find(n=>n.name=="face");e&&(e.constant=1e5),this.engine.scene.children.filter(n=>n.type=="Group"&&n.name=="ClippingBox").forEach(n=>{n.children.forEach(i=>{i.name.includes("face")&&(i.visible=!1)})})}init(e){const n=this.engine.octreeBox.getBoundingBox();this.box=n,this.distance=0,this.center=new H((n.min.x+n.max.x)/2,(n.min.y+n.max.y)/2,(n.min.z+n.max.z)/2),this.current_center=this.center.clone(),!e&&this.updata_face(0)}disabled(){this.isActive=!1,this.detachListeners(),this.handleMouseUp({button:0},!1),this.setTransformControlVisible(!1),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(n=>{n.name.includes("face")&&(n.visible=!1)})})}recover(){this.isActive||(this.attachListeners(),this.setTransformControlVisible(!0),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(n=>{n.name.includes("face")&&(n.visible=!0)})}),this.isActive=!0)}setFaceAngle(e,n,i){this.angleX=e,this.angleY=n,this.angleZ=i,this.distance=0,this.normal=new H(0,1,0).applyAxisAngle(new H(1,0,0),e).applyAxisAngle(new H(0,0,1),n).applyAxisAngle(new H(0,1,0),i).normalize(),this.updata_face(0),this.updateClippingFaceFill()}setFaceNormal(e,n=0){this.normal=e.clone().normalize(),this.distance=n,this.updata_face(n),this.updateClippingFaceFill()}setFaceNormalPlaneOnly(e,n){if(this.normal=e.clone().normalize(),this.distance=n,!this.center||!this.box)return;const i=this.engine.sectionPlane?.find(r=>r.name==="face");if(i){const r=this.center.clone().add(this.normal.clone().multiplyScalar(n));i.setFromNormalAndCoplanarPoint(this.getEffectiveNormal(),r)}this.updateClippingFaceFill()}activateClippingOnly(){this.isActive||(this.isActive=!0,this.applyClippingToModelMeshes())}reverse(){this.direction=-this.getDirectionSign(),this.applyClippingToModelMeshes(),this.updata_face(this.distance),this.updateClippingFaceFill(),this.requestShadowRefresh()}getFaceAngle(){return{angleX:this.angleX,angleY:this.angleY,angleZ:this.angleZ,direction:this.direction}}updata_face(e,n){if(!this.box)return;this.distance=e;let i=this.engine.scene.children.find(T=>T.type=="Group"&&T.name=="ClippingBox");i==null&&(i=new $r,i.name="ClippingBox",this.engine.scene.add(i));const r=this.normal.clone().normalize(),s=this.getEffectiveNormal(r),o=this.center??new H((this.box.min.x+this.box.max.x)/2,(this.box.min.y+this.box.max.y)/2,(this.box.min.z+this.box.max.z)/2);this.center=o.clone();const a=n?.clone()??o.clone().add(r.clone().multiplyScalar(e)),{tangent:c,bitangent:l}=this.getPlaneBasis(r),u=this.getBoxCorners(this.box),h=this.box.min.distanceTo(this.box.max),d=Math.max(h*.02,.01);let p=1/0,m=-1/0,g=1/0,y=-1/0;u.forEach(T=>{const S=T.clone().sub(a),w=S.dot(c),E=S.dot(l);p=Math.min(p,w),m=Math.max(m,w),g=Math.min(g,E),y=Math.max(y,E)}),p-=d,m+=d,g-=d,y+=d;const A=a.clone().add(c.clone().multiplyScalar(p)).add(l.clone().multiplyScalar(g)),v=a.clone().add(c.clone().multiplyScalar(m)).add(l.clone().multiplyScalar(g)),x=a.clone().add(c.clone().multiplyScalar(m)).add(l.clone().multiplyScalar(y)),C=a.clone().add(c.clone().multiplyScalar(p)).add(l.clone().multiplyScalar(y));this.current_center=a.clone(),this.createFace(i,[A,v,x,C],r,"face"),this.updateTransformControl(s),this.updateRotateControl(s)}createFace(e,n,i,r){const s=new Dn,o=new Float32Array([n[0].x,n[0].y,n[0].z,n[1].x,n[1].y,n[1].z,n[2].x,n[2].y,n[2].z,n[3].x,n[3].y,n[3].z]),a=this.getEffectiveNormal(i),c=this.getDirectionSign()===1?[0,1,2,0,2,3]:[0,2,1,0,3,2];s.setAttribute("position",new ji(o,3)),s.setIndex(c),s.computeVertexNormals();let l=this.meshs.find(g=>g.name==r);if(l==null){const g=new Xi({color:65280,transparent:!0,opacity:this.idleOpacity,side:tr});g.polygonOffset=!0,g.polygonOffsetFactor=1,g.polygonOffsetUnits=4,l=new bt(s,g),l.name=r,e.add(l),this.meshs.push(l)}else l.geometry=s;l.normal=a.clone(),l.userData.excludeFromAmbientOcclusion=!0;const u=new Float32Array([n[0].x,n[0].y,n[0].z,n[1].x,n[1].y,n[1].z,n[2].x,n[2].y,n[2].z,n[3].x,n[3].y,n[3].z,n[0].x,n[0].y,n[0].z]),h=new Bs({color:255}),d=new Dn;d.setAttribute("position",new ji(u,3));let p=this.meshs.find(g=>g.name==r+"Line");p==null?(p=new ho(d,h),p.name=r+"Line",e.add(p),this.meshs.push(p)):(p.geometry=d,p.material=h);const m=this.engine.sectionPlane.find(g=>g.name==r);m&&this.current_center&&m.setFromNormalAndCoplanarPoint(a,this.current_center)}getDirectionSign(){return Number(this.direction)===-1?-1:1}getEffectiveNormal(e=this.normal){return e.clone().normalize().multiplyScalar(this.getDirectionSign())}applyClippingToModelMeshes(){const e=this.engine.sectionPlane?.find?.(n=>n.name==="face");zj(this.engine).forEach(n=>{this.applyClippingToMaterial(n.material),this.engine.clipping.clippingStencil?.addMesh(e,n)}),this.requestShadowRefresh()}applyClippingToMaterial(e){if(Array.isArray(e)){e.forEach(n=>this.applyClippingToMaterial(n));return}e&&(e.clippingPlanes=this.engine.sectionPlane,e.clipShadows=!0,e.shadowSide=tr,e.needsUpdate=!0)}requestShadowRefresh(){const e=this.engine?.renderer?.shadowMap;e&&(e.needsUpdate=!0);const n=this.engine?.scene?.dirLight;n?.shadow&&(n.shadow.needsUpdate=!0)}lockControlMode(e){this.activeControlMode=e,this.applyControlModeLock()}releaseControlModeLock(){this.activeControlMode=null,this.applyControlModeLock()}applyControlModeLock(){this.transformControl&&(this.transformControl.enabled=this.isActive&&this.activeControlMode!=="rotate"),this.rotateControl&&(this.rotateControl.enabled=this.isActive&&this.activeControlMode!=="translate")}pickControlModeFromPointer(e){const n=this.raycastTransformControlPicker(this.transformControl,e),i=this.raycastTransformControlPicker(this.rotateControl,e);return n&&i?i.distance<=n.distance?"rotate":"translate":i?"rotate":n?"translate":null}raycastTransformControlPicker(e,n){if(!e||!e.object||!this.engine?.camera||!this.engine?.renderer?.domElement)return null;const i=e._gizmo?.picker?.[e.mode];if(!i)return null;const r=this.engine.renderer.domElement.getBoundingClientRect(),s=new Ye((n.clientX-r.left)/r.width*2-1,-((n.clientY-r.top)/r.height)*2+1),o=new Da;return o.setFromCamera(s,this.engine.camera),o.intersectObject(i,!0).find(c=>c.object.visible)??null}getPlaneBasis(e){const n=new H(1,0,0),i=new H(0,1,0),r=new H(0,0,1),s=Math.abs(e.dot(n)),o=Math.abs(e.dot(i)),a=Math.abs(e.dot(r));let c=n;o<=s&&o<=a?c=i:a<=s&&a<=o&&(c=r),c=c.clone().sub(e.clone().multiplyScalar(c.dot(e))).normalize();const l=new H().crossVectors(e,c).normalize();return{tangent:c,bitangent:l}}getBoxCorners(e){return[new H(e.min.x,e.min.y,e.min.z),new H(e.min.x,e.min.y,e.max.z),new H(e.min.x,e.max.y,e.min.z),new H(e.min.x,e.max.y,e.max.z),new H(e.max.x,e.min.y,e.min.z),new H(e.max.x,e.min.y,e.max.z),new H(e.max.x,e.max.y,e.min.z),new H(e.max.x,e.max.y,e.max.z)]}getDistanceRange(e){if(!this.box)return{min:0,max:0};const n=this.center??new H((this.box.min.x+this.box.max.x)/2,(this.box.min.y+this.box.max.y)/2,(this.box.min.z+this.box.max.z)/2),i=this.getBoxCorners(this.box);let r=1/0,s=-1/0;return i.forEach(o=>{const a=o.clone().sub(n).dot(e);r=Math.min(r,a),s=Math.max(s,a)}),{min:r,max:s}}getInteractiveMeshes(){return this.meshs.filter(e=>e.type==="Mesh")}getTransformHandleOffset(){if(!this.box)return .06;const e=this.box.min.distanceTo(this.box.max);return Math.max(e*.015,.06)}getPlaneQuaternion(e){const{tangent:n,bitangent:i}=this.getPlaneBasis(e),r=new xt().makeBasis(n,i,e.clone().normalize());return new ni().setFromRotationMatrix(r)}keepSingleDirectionArrow(e,n="X"){const i=e.getHelper(),r=[];i.traverse(s=>{if(s?.name!==n||!s.geometry)return;const o=s.geometry;o.boundingBox||o.computeBoundingBox();const a=o.boundingBox;if(!a)return;const c=a.getCenter(new H);if(!(n==="X"&&c.x<0||n==="Y"&&c.y<0||n==="Z"&&c.z<0))return;const u=o.parameters,h=u&&u.radiusTop===0&&u.radiusBottom===.04&&u.height===.1,d=u&&u.radiusTop===.2&&u.radiusBottom===0&&u.height===.6;(h||d)&&r.push(s)}),r.forEach(s=>{s.parent?.remove(s)})}ensureTransformControl(){if(this.transformControl&&this.transformAnchor)return;const e=this.engine.renderer?.domElement,n=this.engine.camera;if(!e||!n)return;const i=new Ni;i.name="SectionFaceTransformAnchor",i.visible=this.isActive,this.engine.scene.add(i);const r=new tN(n,e);r.name="SectionFaceTransformControl",r.setMode("translate"),r.setSpace("local"),r.showX=!0,r.showY=!1,r.showZ=!1,r.size=this.transformHandleSize,r.setColors(this.transformHandleColor,this.transformHandleColor,this.transformHandleColor,this.transformHandleHoverColor),r.enabled=this.isActive,r.attach(i),this.keepSingleDirectionArrow(r,"X"),r.addEventListener("dragging-changed",o=>{this.engine.controls.enabled=!o.value,o.value===!0?(this.lockControlMode("translate"),this.clearClippingFaceFill()):(this.updateClippingFaceFill(),this.releaseControlModeLock())}),r.addEventListener("objectChange",this.handleTransformObjectChange);const s=r.getHelper();s.userData.excludeFromAmbientOcclusion=!0,s.visible=this.isActive,this.engine.scene.add(s),this.transformAnchor=i,this.transformControl=r,this.transformHelper=s}ensureRotateControl(){if(this.rotateControl&&this.rotateAnchor)return;const e=this.engine.renderer?.domElement,n=this.engine.camera;if(!e||!n)return;const i=new Ni;i.name="SectionFaceRotateAnchor",i.visible=this.isActive,this.engine.scene.add(i);const r=new tN(n,e);r.name="SectionFaceRotateControl",r.setMode("rotate"),r.setSpace("local"),r.showX=!0,r.showY=!0,r.showZ=!1,r.size=this.rotateHandleSize,r.setColors(this.transformHandleColor,this.transformHandleColor,this.transformHandleColor,this.transformHandleHoverColor),r.enabled=this.isActive,r.attach(i),r.addEventListener("dragging-changed",o=>{this.engine.controls.enabled=!o.value,o.value===!0?(this.lockControlMode("rotate"),this.rotatePivot=(this.current_center??this.rotateAnchor?.position??null)?.clone?.()??null,this.clearClippingFaceFill()):(this.rotatePivot=null,this.updateClippingFaceFill(),this.releaseControlModeLock())}),r.addEventListener("objectChange",this.handleRotateObjectChange);const s=r.getHelper();s.userData.excludeFromAmbientOcclusion=!0,s.visible=this.isActive,this.engine.scene.add(s),this.rotateAnchor=i,this.rotateControl=r,this.rotateHelper=s}setTransformControlVisible(e){this.ensureTransformControl(),this.ensureRotateControl(),e||(this.activeControlMode=null),this.transformControl&&(this.transformControl.enabled=e&&this.activeControlMode!=="rotate"),this.transformHelper&&(this.transformHelper.visible=e),this.transformAnchor&&(this.transformAnchor.visible=e),this.rotateControl&&(this.rotateControl.enabled=e&&this.activeControlMode!=="translate"),this.rotateHelper&&(this.rotateHelper.visible=e),this.rotateAnchor&&(this.rotateAnchor.visible=e),e||(this.engine.controls.enabled=!0)}updateTransformControl(e){if(this.ensureTransformControl(),!this.transformControl||!this.transformAnchor||!this.current_center)return;const n=this.getTransformHandleOffset(),i=this.current_center.clone().add(e.clone().setLength(n)),r=new ni().setFromUnitVectors(new H(1,0,0),e.clone().normalize().multiplyScalar(-1));this.isSyncingTransformControl=!0,this.transformAnchor.position.copy(i),this.transformAnchor.quaternion.copy(r),this.transformAnchor.visible=this.isActive,this.transformControl.object!==this.transformAnchor&&this.transformControl.attach(this.transformAnchor),this.applyControlModeLock(),this.transformHelper&&(this.transformHelper.visible=this.isActive),this.isSyncingTransformControl=!1}updateRotateControl(e){this.ensureRotateControl(),!(!this.rotateControl||!this.rotateAnchor||!this.current_center)&&(this.isSyncingRotateControl=!0,this.rotateAnchor.position.copy(this.current_center),this.rotateAnchor.quaternion.copy(this.getPlaneQuaternion(e)),this.rotateAnchor.visible=this.isActive,this.rotateControl.object!==this.rotateAnchor&&this.rotateControl.attach(this.rotateAnchor),this.applyControlModeLock(),this.rotateHelper&&(this.rotateHelper.visible=this.isActive),this.isSyncingRotateControl=!1)}createRaycasterFromMouseEvent(e){const n=new Da,i=new Ye,r=this.engine.renderer.domElement.clientWidth,s=this.engine.renderer.domElement.clientHeight;return i.x=e.offsetX/r*2-1,i.y=-(e.offsetY/s)*2+1,n.setFromCamera(i,this.engine.camera),n}isMobileDevice(){return this.engine?.deviceModule?.isMobile?.()===!0||this.engine?.deviceType==="mobile"}getTouchPoint(e){const n=e.touches[0]||e.changedTouches[0];return n?new Ye(n.clientX,n.clientY):null}createMouseEventFromTouch(e){const n=e.touches[0]||e.changedTouches[0],i=this.engine.renderer?.domElement;if(!n||!i)return null;const r=i.getBoundingClientRect();return{offsetX:n.clientX-r.left,offsetY:n.clientY-r.top,clientX:n.clientX,clientY:n.clientY,button:0}}clearTouchLongPressTimer(){this.touchLongPressTimer!=null&&(clearTimeout(this.touchLongPressTimer),this.touchLongPressTimer=null)}resetTouchLongPressState(){this.clearTouchLongPressTimer(),this.touchLongPressActive=!1,this.touchStartPosition=null,this.touchLatestEvent=null}attachListeners(){if(this.listenersAttached)return;const e=this.engine.renderer?.domElement;e&&(e.addEventListener("pointerdown",this.handleNativePointerDown,!0),e.addEventListener("pointerup",this.handleNativePointerUp,!0),e.addEventListener("pointercancel",this.handleNativePointerUp,!0),e.addEventListener("pointerleave",this.handleNativePointerUp,!0),e.addEventListener("mousedown",this.handleNativeMouseDown,!0),e.addEventListener("mousemove",this.handleNativeMouseMove,!0),e.addEventListener("mouseup",this.handleNativeMouseUp,!0),e.addEventListener("touchstart",this.handleNativeTouchStart,{capture:!0,passive:!1}),e.addEventListener("touchmove",this.handleNativeTouchMove,{capture:!0,passive:!1}),e.addEventListener("touchend",this.handleNativeTouchEnd,{capture:!0,passive:!1}),e.addEventListener("touchcancel",this.handleNativeTouchEnd,{capture:!0,passive:!1}),window.addEventListener("keydown",this.handleNativeKeyDown),window.addEventListener("keyup",this.handleNativeKeyUp),this.listenersAttached=!0)}detachListeners(){if(!this.listenersAttached)return;const e=this.engine.renderer?.domElement;e&&(e.removeEventListener("pointerdown",this.handleNativePointerDown,!0),e.removeEventListener("pointerup",this.handleNativePointerUp,!0),e.removeEventListener("pointercancel",this.handleNativePointerUp,!0),e.removeEventListener("pointerleave",this.handleNativePointerUp,!0),e.removeEventListener("mousedown",this.handleNativeMouseDown,!0),e.removeEventListener("mousemove",this.handleNativeMouseMove,!0),e.removeEventListener("mouseup",this.handleNativeMouseUp,!0),e.removeEventListener("touchstart",this.handleNativeTouchStart,!0),e.removeEventListener("touchmove",this.handleNativeTouchMove,!0),e.removeEventListener("touchend",this.handleNativeTouchEnd,!0),e.removeEventListener("touchcancel",this.handleNativeTouchEnd,!0)),window.removeEventListener("keydown",this.handleNativeKeyDown),window.removeEventListener("keyup",this.handleNativeKeyUp),this.listenersAttached=!1,this.isCtrlDown=!1,this.releaseControlModeLock(),this.resetTouchLongPressState()}resetMeshOpacity(){this.getInteractiveMeshes().forEach(e=>{e.material&&(e.material.opacity=this.idleOpacity)})}updateClippingFaceFill(){const e=this.engine.sectionPlane?.find?.(n=>n.name==="face");if(e){this.engine.clipping?.clippingCSGSimple?.updataFace?.(e);return}this.clearClippingFaceFill()}clearClippingFaceFill(){this.engine.clipping?.clippingCSGSimple?.clear?.()}handleMouseDown(e){const n=e.intersects??e.raycaster.intersectObjects(this.getInteractiveMeshes(),!1);if(n!=null&&n.length>0){this.clearClippingFaceFill();const i=n[0],r=i.point.clone();this.isDrag=!0,this.pickPoint=r;const o=(i.face?.normal?.clone()??this.normal.clone()).clone(),a=this.getEffectiveNormal();if(o.dot(a)<0&&o.multiplyScalar(-1),o.normalize(),this.pickNormal=o,this.engine.controls.enabled=!1,this.dragStartDistance=Number(this.distance)||0,this.dragStartCenter=this.current_center?.clone()??null,o.y==0){const c=new Zi;c.setFromNormalAndCoplanarPoint(new H(0,1,0),r),this.plane=c}else{const c=new H(this.engine.camera.position.x,r.y,this.engine.camera.position.z),l=new Zi;l.setFromNormalAndCoplanarPoint(c.clone().sub(r.clone()).setLength(1),r),this.plane=l}}else this.isDrag=!1}handleMouseUp(e,n=!0){this.isDrag=!1,this.pickPoint=null,this.pickNormal=null,this.plane=null,this.dragStartCenter=null,this.engine.controls.enabled=!0,n&&this.updateClippingFaceFill()}handleMouseMove(e){this.resetMeshOpacity();const n=e.intersects??e.raycaster.intersectObjects(this.getInteractiveMeshes(),!1);n!=null&&n.length>0&&(n[0].object.material.opacity=this.hoverOpacity);const i=this.pickPoint,r=this.pickNormal,s=this.plane;if(i!=null&&r!=null&&s!=null){const o=new H;if(e.raycaster.ray.intersectPlane(s,o)){const a=o.clone().sub(i.clone()).dot(r.clone()),c=this.getDistanceRange(this.normal.clone().normalize()),l=r.dot(this.normal.clone().normalize())>=0?1:-1,u=this.dragStartDistance+a*l;this.distance=Math.min(c.max,Math.max(c.min,u));const h=(this.dragStartCenter??this.current_center)?.clone().add(this.normal.clone().normalize().multiplyScalar(this.distance-this.dragStartDistance));this.updata_face(this.distance,h)}}}}class DGe{engine;callback_;isActive;constructor(e){this.engine=e}init(){this.isActive=!0,this.engine.handelBehaved.init(this,{showCatch:!0}),this.engine.handelBehaved.active()}cancel(){this.isActive&&(this.engine.handelBehaved.disActive(),this.engine.interactionModule.init(),this.engine.interactionModule.active(),this.isActive=!1)}catch_face(e){this.callback_=e}handleMouseMove(e){}handleMouseClick(e){if(e.catch?.normal==null&&(e.catch.normal=e.catch.face?.normal),!e.catch?.normal||!e.catch?.point)return;let n=e.catch.normal.setLength(-1);this.engine.handelBehaved.disActive(),this.engine.interactionModule.init(),this.engine.interactionModule.active(),this.isActive=!1,this.callback_({dir:n,position:e.catch.point})}}const ooe=1e-6,RGe=ooe*.5,aoe=Math.pow(10,-Math.log10(ooe)),OGe=RGe*aoe;function Mm(t){return~~(t*aoe+OGe)}function LGe(t){return`${Mm(t.x)},${Mm(t.y)}`}function coe(t){return`${Mm(t.x)},${Mm(t.y)},${Mm(t.z)}`}function BGe(t){return`${Mm(t.x)},${Mm(t.y)},${Mm(t.z)},${Mm(t.w)}`}function NGe(t,e,n){n.direction.subVectors(e,t).normalize();const i=t.dot(n.direction);return n.origin.copy(t).addScaledVector(n.direction,-i),n}function loe(){return typeof SharedArrayBuffer<"u"}function FGe(t){if(t.buffer instanceof SharedArrayBuffer)return t;const e=t.constructor,n=t.buffer,i=new SharedArrayBuffer(n.byteLength),r=new Uint8Array(n);return new Uint8Array(i).set(r,0),new e(i)}function kGe(t,e=ArrayBuffer){return t>65535?new Uint32Array(new e(4*t)):new Uint16Array(new e(2*t))}function UGe(t,e){if(!t.index){const n=t.attributes.position.count,i=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,r=kGe(n,i);t.setIndex(new ji(r,1));for(let s=0;s<n;s++)r[s]=s}}function zGe(t){return t.index?t.index.count:t.attributes.position.count}function i6(t){return zGe(t)/3}const VGe=1e-8,jGe=new H;function HGe(t){return~~(t/3)}function GGe(t){return t%3}function uoe(t,e){return t.start-e.start}function hoe(t,e){return jGe.subVectors(e,t.origin).dot(t.direction)}function qGe(t,e,n,i=VGe){t.sort(uoe),e.sort(uoe);for(let a=0;a<t.length;a++){const c=t[a];for(let l=0;l<e.length;l++){const u=e[l];if(!(u.start>c.end)){if(c.end<u.start||u.end<c.start)continue;if(c.start<=u.start&&c.end>=u.end)s(u.end,c.end)||t.splice(a+1,0,{start:u.end,end:c.end,index:c.index}),c.end=u.start,u.start=0,u.end=0;else if(c.start>=u.start&&c.end<=u.end)s(c.end,u.end)||e.splice(l+1,0,{start:c.end,end:u.end,index:u.index}),u.end=c.start,c.start=0,c.end=0;else if(c.start<=u.start&&c.end<=u.end){const h=c.end;c.end=u.start,u.start=h}else if(c.start>=u.start&&c.end>=u.end){const h=u.end;u.end=c.start,c.start=h}else throw new Error}if(n.has(c.index)||n.set(c.index,[]),n.has(u.index)||n.set(u.index,[]),n.get(c.index).push(u.index),n.get(u.index).push(c.index),o(u)&&(e.splice(l,1),l--),o(c)){t.splice(a,1),a--;break}}}r(t),r(e);function r(a){for(let c=0;c<a.length;c++)o(a[c])&&(a.splice(c,1),c--)}function s(a,c){return Math.abs(c-a)<i}function o(a){return Math.abs(a.end-a.start)<i}}const doe=1e-5,foe=1e-4;class WGe{constructor(){this._rays=[]}addRay(e){this._rays.push(e)}findClosestRay(e){const n=this._rays,i=e.clone();i.direction.multiplyScalar(-1);let r=1/0,s=null;for(let c=0,l=n.length;c<l;c++){const u=n[c];if(o(u,e)&&o(u,i))continue;const h=a(u,e),d=a(u,i),p=Math.min(h,d);p<r&&(r=p,s=u)}return s;function o(c,l){const u=c.origin.distanceTo(l.origin)>doe;return c.direction.angleTo(l.direction)>foe||u}function a(c,l){const u=c.origin.distanceTo(l.origin),h=c.direction.angleTo(l.direction);return u/doe+h/foe}}}const r6=new H,s6=new H,aN=new mm;function YGe(t,e,n){const i=t.attributes,r=t.index,s=i.position,o=new Map,a=new Map,c=Array.from(e),l=new WGe;for(let u=0,h=c.length;u<h;u++){const d=c[u],p=HGe(d),m=GGe(d);let g=3*p+m,y=3*p+(m+1)%3;r&&(g=r.getX(g),y=r.getX(y)),r6.fromBufferAttribute(s,g),s6.fromBufferAttribute(s,y),NGe(r6,s6,aN);let A,v=l.findClosestRay(aN);v===null&&(v=aN.clone(),l.addRay(v)),a.has(v)||a.set(v,{forward:[],reverse:[],ray:v}),A=a.get(v);let x=hoe(v,r6),C=hoe(v,s6);x>C&&([x,C]=[C,x]),aN.direction.dot(v.direction)<0?A.reverse.push({start:x,end:C,index:d}):A.forward.push({start:x,end:C,index:d})}return a.forEach(({forward:u,reverse:h},d)=>{qGe(u,h,o,n),u.length===0&&h.length===0&&a.delete(d)}),{disjointConnectivityMap:o,fragmentMap:a}}const XGe=new Ye,o6=new H,$Ge=new Bi,a6=["","",""];class QGe{constructor(e=null){this.data=null,this.disjointConnections=null,this.unmatchedDisjointEdges=null,this.unmatchedEdges=-1,this.matchedEdges=-1,this.useDrawRange=!0,this.useAllAttributes=!1,this.matchDisjointEdges=!1,this.degenerateEpsilon=1e-8,e&&this.updateFrom(e)}getSiblingTriangleIndex(e,n){const i=this.data[e*3+n];return i===-1?-1:~~(i/3)}getSiblingEdgeIndex(e,n){const i=this.data[e*3+n];return i===-1?-1:i%3}getDisjointSiblingTriangleIndices(e,n){const i=e*3+n,r=this.disjointConnections.get(i);return r?r.map(s=>~~(s/3)):[]}getDisjointSiblingEdgeIndices(e,n){const i=e*3+n,r=this.disjointConnections.get(i);return r?r.map(s=>s%3):[]}isFullyConnected(){return this.unmatchedEdges===0}updateFrom(e){const{useAllAttributes:n,useDrawRange:i,matchDisjointEdges:r,degenerateEpsilon:s}=this,o=n?x:v,a=new Map,{attributes:c}=e,l=n?Object.keys(c):null,u=e.index,h=c.position;let d=i6(e);const p=d;let m=0;i&&(m=e.drawRange.start,e.drawRange.count!==1/0&&(d=~~(e.drawRange.count/3)));let g=this.data;(!g||g.length<3*p)&&(g=new Int32Array(3*p)),g.fill(-1);let y=0,A=new Set;for(let C=m,T=d*3+m;C<T;C+=3){const S=C;for(let w=0;w<3;w++){let E=S+w;u&&(E=u.getX(E)),a6[w]=o(E)}for(let w=0;w<3;w++){const E=(w+1)%3,D=a6[w],O=a6[E],P=`${O}_${D}`;if(a.has(P)){const I=S+w,_=a.get(P);g[I]=_,g[_]=I,a.delete(P),y+=2,A.delete(_)}else{const I=`${D}_${O}`,_=S+w;a.set(I,_),A.add(_)}}}if(r){const{fragmentMap:C,disjointConnectivityMap:T}=YGe(e,A,s);A.clear(),C.forEach(({forward:S,reverse:w})=>{S.forEach(({index:E})=>A.add(E)),w.forEach(({index:E})=>A.add(E))}),this.unmatchedDisjointEdges=C,this.disjointConnections=T,y=d*3-A.size}this.matchedEdges=y,this.unmatchedEdges=A.size,this.data=g;function v(C){return o6.fromBufferAttribute(h,C),coe(o6)}function x(C){let T="";for(let S=0,w=l.length;S<w;S++){const E=c[l[S]];let D;switch(E.itemSize){case 1:D=Mm(E.getX(C));break;case 2:D=LGe(XGe.fromBufferAttribute(E,C));break;case 3:D=coe(o6.fromBufferAttribute(E,C));break;case 4:D=BGe($Ge.fromBufferAttribute(E,C));break}T!==""&&(T+="|"),T+=D}return T}}}class cN extends bt{constructor(...e){super(...e),this.isBrush=!0,this._previousMatrix=new xt,this._previousMatrix.elements.fill(0)}markUpdated(){this._previousMatrix.copy(this.matrix)}isDirty(){const{matrix:e,_previousMatrix:n}=this,i=e.elements,r=n.elements;for(let s=0;s<16;s++)if(i[s]!==r[s])return!0;return!1}prepareGeometry(){const e=this.geometry,n=e.attributes,i=loe();if(i)for(const r in n){const s=n[r];if(s.isInterleavedBufferAttribute)throw new Error("Brush: InterleavedBufferAttributes are not supported.");s.array=FGe(s.array)}if(e.boundsTree||(UGe(e,{useSharedArrayBuffer:i}),e.boundsTree=new OI(e,{maxLeafTris:3,indirect:!0,useSharedArrayBuffer:i})),e.halfEdges||(e.halfEdges=new QGe(e)),!e.groupIndices){const r=i6(e),s=new Uint16Array(r),o=e.groups;for(let a=0,c=o.length;a<c;a++){const{start:l,count:u}=o[a];for(let h=l/3,d=(l+u)/3;h<d;h++)s[h]=a}e.groupIndices=s}}disposeCacheData(){const{geometry:e}=this;e.halfEdges=null,e.boundsTree=null,e.groupIndices=null}}const KGe=1e-14,c6=new H,poe=new H,moe=new H;function iA(t,e=KGe){c6.subVectors(t.b,t.a),poe.subVectors(t.c,t.a),moe.subVectors(t.b,t.c);const n=c6.angleTo(poe),i=c6.angleTo(moe),r=Math.PI-n-i;return Math.abs(n)<e||Math.abs(i)<e||Math.abs(r)<e||t.a.distanceToSquared(t.b)<e||t.a.distanceToSquared(t.c)<e||t.b.distanceToSquared(t.c)<e}const l6=1e-10,YI=1e-10,JGe=1e-10,ag=new Nh,La=new Nh,cg=new H,u6=new H,goe=new H,lN=new Zi,h6=new Vd;class ZGe{constructor(){this._pool=[],this._index=0}getTriangle(){return this._index>=this._pool.length&&this._pool.push(new Ls),this._pool[this._index++]}clear(){this._index=0}reset(){this._pool.length=0,this._index=0}}class e9e{constructor(){this.trianglePool=new ZGe,this.triangles=[],this.normal=new H,this.coplanarTriangleUsed=!1}initialize(e){this.reset();const{triangles:n,trianglePool:i,normal:r}=this;if(Array.isArray(e))for(let s=0,o=e.length;s<o;s++){const a=e[s];if(s===0)a.getNormal(r);else if(Math.abs(1-a.getNormal(cg).dot(r))>l6)throw new Error("Triangle Splitter: Cannot initialize with triangles that have different normals.");const c=i.getTriangle();c.copy(a),n.push(c)}else{e.getNormal(r);const s=i.getTriangle();s.copy(e),n.push(s)}}splitByTriangle(e){const{normal:n,triangles:i}=this;if(e.getNormal(u6).normalize(),Math.abs(1-Math.abs(u6.dot(n)))<JGe){this.coplanarTriangleUsed=!0;for(let s=0,o=i.length;s<o;s++){const a=i[s];a.coplanarCount=0}const r=[e.a,e.b,e.c];for(let s=0;s<3;s++){const o=(s+1)%3,a=r[s],c=r[o];cg.subVectors(c,a).normalize(),goe.crossVectors(u6,cg),lN.setFromNormalAndCoplanarPoint(goe,a),this.splitByPlane(lN,e)}}else e.getPlane(lN),this.splitByPlane(lN,e)}splitByPlane(e,n){const{triangles:i,trianglePool:r}=this;h6.copy(n),h6.needsUpdate=!0;for(let s=0,o=i.length;s<o;s++){const a=i[s];if(!h6.intersectsTriangle(a,ag,!0))continue;const{a:c,b:l,c:u}=a;let h=0,d=-1,p=!1,m=[],g=[];const y=[c,l,u];for(let A=0;A<3;A++){const v=(A+1)%3;ag.start.copy(y[A]),ag.end.copy(y[v]);const x=e.distanceToPoint(ag.start),C=e.distanceToPoint(ag.end);if(Math.abs(x)<YI&&Math.abs(C)<YI){p=!0;break}if(x>0?m.push(A):g.push(A),Math.abs(x)<YI)continue;let T=!!e.intersectLine(ag,cg);!T&&Math.abs(C)<YI&&(cg.copy(ag.end),T=!0),T&&!(cg.distanceTo(ag.start)<l6)&&(cg.distanceTo(ag.end)<l6&&(d=A),h===0?La.start.copy(cg):La.end.copy(cg),h++)}if(!p&&h===2&&La.distance()>YI)if(d!==-1){d=(d+1)%3;let A=0;A===d&&(A=(A+1)%3);let v=A+1;v===d&&(v=(v+1)%3);const x=r.getTriangle();x.a.copy(y[v]),x.b.copy(La.end),x.c.copy(La.start),iA(x)||i.push(x),a.a.copy(y[A]),a.b.copy(La.start),a.c.copy(La.end),iA(a)&&(i.splice(s,1),s--,o--)}else{const A=m.length>=2?g[0]:m[0];if(A===0){let S=La.start;La.start=La.end,La.end=S}const v=(A+1)%3,x=(A+2)%3,C=r.getTriangle(),T=r.getTriangle();y[v].distanceToSquared(La.start)<y[x].distanceToSquared(La.end)?(C.a.copy(y[v]),C.b.copy(La.start),C.c.copy(La.end),T.a.copy(y[v]),T.b.copy(y[x]),T.c.copy(La.start)):(C.a.copy(y[x]),C.b.copy(La.start),C.c.copy(La.end),T.a.copy(y[v]),T.b.copy(y[x]),T.c.copy(La.end)),a.a.copy(y[A]),a.b.copy(La.end),a.c.copy(La.start),iA(C)||i.push(C),iA(T)||i.push(T),iA(a)&&(i.splice(s,1),s--,o--)}else h===3&&console.warn("TriangleClipper: Coplanar clip not handled")}}reset(){this.triangles.length=0,this.trianglePool.clear(),this.coplanarTriangleUsed=!1}}function t9e(t){return t=~~t,t+4-t%4}class _oe{constructor(e,n=500){this.expansionFactor=1.5,this.type=e,this.length=0,this.array=null,this.setSize(n)}setType(e){if(this.length!==0)throw new Error("TypeBackedArray: Cannot change the type while there is used data in the buffer.");const n=this.array.buffer;this.array=new e(n),this.type=e}setSize(e){if(this.array&&e===this.array.length)return;const n=this.type,i=loe()?SharedArrayBuffer:ArrayBuffer,r=new n(new i(t9e(e*n.BYTES_PER_ELEMENT)));this.array&&r.set(this.array,0),this.array=r}expand(){const{array:e,expansionFactor:n}=this;this.setSize(e.length*n)}push(...e){let{array:n,length:i}=this;i+e.length>n.length&&(this.expand(),n=this.array);for(let r=0,s=e.length;r<s;r++)n[i+r]=e[r];this.length+=e.length}clear(){this.length=0}}class n9e{constructor(){this.groupAttributes=[{}],this.groupCount=0}getType(e){return this.groupAttributes[0][e].type}getItemSize(e){return this.groupAttributes[0][e].itemSize}getNormalized(e){return this.groupAttributes[0][e].normalized}getCount(e){if(this.groupCount<=e)return 0;const n=this.getGroupAttrArray("position",e);return n.length/n.itemSize}getTotalLength(e){const{groupCount:n,groupAttributes:i}=this;let r=0;for(let s=0;s<n;s++){const o=i[s];r+=o[e].length}return r}getGroupAttrSet(e=0){const{groupAttributes:n}=this;if(n[e])return this.groupCount=Math.max(this.groupCount,e+1),n[e];const i=n[0];for(this.groupCount=Math.max(this.groupCount,e+1);e>=n.length;){const r={};n.push(r);for(const s in i){const o=i[s],a=new _oe(o.type);a.itemSize=o.itemSize,a.normalized=o.normalized,r[s]=a}}return n[e]}getGroupAttrArray(e,n=0){const{groupAttributes:i}=this;if(!i[0][e])throw new Error(`TypedAttributeData: Attribute with "${e}" has not been initialized`);return this.getGroupAttrSet(n)[e]}initializeArray(e,n,i,r){const{groupAttributes:s}=this,a=s[0][e];if(a){if(a.type!==n)for(let c=0,l=s.length;c<l;c++){const u=s[c][e];u.setType(n),u.itemSize=i,u.normalized=r}}else for(let c=0,l=s.length;c<l;c++){const u=new _oe(n);u.itemSize=i,u.normalized=r,s[c][e]=u}}clear(){this.groupCount=0;const{groupAttributes:e}=this;e.forEach(n=>{for(const i in n)n[i].clear()})}delete(e){this.groupAttributes.forEach(n=>{delete n[e]})}reset(){this.groupAttributes=[],this.groupCount=0}}class Aoe{constructor(){this.intersectionSet={},this.ids=[]}add(e,n){const{intersectionSet:i,ids:r}=this;i[e]||(i[e]=[],r.push(e)),i[e].push(n)}}const i9e=0,r9e=1,s9e=2,yoe=3,o9e=4,boe=5,voe=6,Gd=new mm,xoe=new xt,Cu=new Ls,lg=new H,Coe=new Bi,Eoe=new Bi,woe=new Bi,d6=new Bi,uN=new Bi,hN=new Bi,Toe=new Nh,f6=new H,p6=1e-8,a9e=1e-15,av=-1,cv=1,dN=-2,fN=2,XI=0,lv=1,m6=2,c9e=1e-14;let pN=null;function Soe(t){pN=t}function Ioe(t,e){t.getMidpoint(Gd.origin),t.getNormal(Gd.direction);const n=e.raycastFirst(Gd,tr);return!!(n&&Gd.direction.dot(n.face.normal)>0)?av:cv}function l9e(t,e){function n(){return Math.random()-.5}t.getNormal(f6),Gd.direction.copy(f6),t.getMidpoint(Gd.origin);const i=3;let r=0,s=1/0;for(let o=0;o<i;o++){Gd.direction.x+=n()*p6,Gd.direction.y+=n()*p6,Gd.direction.z+=n()*p6,Gd.direction.multiplyScalar(-1);const a=e.raycastFirst(Gd,tr);if(!!(a&&Gd.direction.dot(a.face.normal)>0)&&r++,a!==null&&(s=Math.min(s,a.distance)),s<=a9e)return a.face.normal.dot(f6)>0?fN:dN;if(r/i>.5||(o-r+1)/i>.5)break}return r/i>.5?av:cv}function u9e(t,e){const n=new Aoe,i=new Aoe;return xoe.copy(t.matrixWorld).invert().multiply(e.matrixWorld),t.geometry.boundsTree.bvhcast(e.geometry.boundsTree,xoe,{intersectsTriangles(r,s,o,a){if(!iA(r)&&!iA(s)){let c=r.intersectsTriangle(s,Toe,!0);if(!c){const l=r.plane,u=s.plane,h=l.normal,d=u.normal;h.dot(d)===1&&Math.abs(l.constant-u.constant)<c9e&&(c=!0)}if(c){let l=t.geometry.boundsTree.resolveTriangleIndex(o),u=e.geometry.boundsTree.resolveTriangleIndex(a);n.add(l,u),i.add(u,l),pN&&(pN.addEdge(Toe),pN.addIntersectingTriangles(o,r,a,s))}}return!1}}),{aIntersections:n,bIntersections:i}}function h9e(t,e,n,i,r,s,o=!1){const a=n.attributes,c=n.index,l=t*3,u=c.getX(l+0),h=c.getX(l+1),d=c.getX(l+2);for(const p in s){const m=a[p],g=s[p];if(!(p in a))throw new Error(`CSG Operations: Attribute ${p} not available on geometry.`);const y=m.itemSize;p==="position"?(Cu.a.fromBufferAttribute(m,u).applyMatrix4(i),Cu.b.fromBufferAttribute(m,h).applyMatrix4(i),Cu.c.fromBufferAttribute(m,d).applyMatrix4(i),g6(Cu.a,Cu.b,Cu.c,e,3,g,o)):p==="normal"?(Cu.a.fromBufferAttribute(m,u).applyNormalMatrix(r),Cu.b.fromBufferAttribute(m,h).applyNormalMatrix(r),Cu.c.fromBufferAttribute(m,d).applyNormalMatrix(r),o&&(Cu.a.multiplyScalar(-1),Cu.b.multiplyScalar(-1),Cu.c.multiplyScalar(-1)),g6(Cu.a,Cu.b,Cu.c,e,3,g,o,!0)):(Coe.fromBufferAttribute(m,u),Eoe.fromBufferAttribute(m,h),woe.fromBufferAttribute(m,d),g6(Coe,Eoe,woe,e,y,g,o))}}function d9e(t,e,n,i,r,s,o,a=!1){_6(t,i,r,s,o,a),_6(a?n:e,i,r,s,o,a),_6(a?e:n,i,r,s,o,a)}function Moe(t,e,n=!1){switch(t){case i9e:if(e===cv||e===fN&&!n)return lv;break;case r9e:if(n){if(e===av)return XI}else if(e===cv||e===dN)return lv;break;case s9e:if(n){if(e===cv||e===dN)return lv}else if(e===av)return XI;break;case o9e:if(e===av)return XI;if(e===cv)return lv;break;case yoe:if(e===av||e===fN&&!n)return lv;break;case boe:if(!n&&(e===cv||e===dN))return lv;break;case voe:if(!n&&(e===av||e===fN))return lv;break;default:throw new Error(`Unrecognized CSG operation enum "${t}".`)}return m6}function g6(t,e,n,i,r,s,o=!1,a=!1){const c=l=>{s.push(l.x),r>1&&s.push(l.y),r>2&&s.push(l.z),r>3&&s.push(l.w)};d6.set(0,0,0,0).addScaledVector(t,i.a.x).addScaledVector(e,i.a.y).addScaledVector(n,i.a.z),uN.set(0,0,0,0).addScaledVector(t,i.b.x).addScaledVector(e,i.b.y).addScaledVector(n,i.b.z),hN.set(0,0,0,0).addScaledVector(t,i.c.x).addScaledVector(e,i.c.y).addScaledVector(n,i.c.z),a&&(d6.normalize(),uN.normalize(),hN.normalize()),c(d6),o?(c(hN),c(uN)):(c(uN),c(hN))}function _6(t,e,n,i,r,s=!1){for(const o in r){const a=e[o],c=r[o];if(!(o in e))throw new Error(`CSG Operations: Attribute ${o} no available on geometry.`);const l=a.itemSize;o==="position"?(lg.fromBufferAttribute(a,t).applyMatrix4(n),c.push(lg.x,lg.y,lg.z)):o==="normal"?(lg.fromBufferAttribute(a,t).applyNormalMatrix(i),s&&lg.multiplyScalar(-1),c.push(lg.x,lg.y,lg.z)):(c.push(a.getX(t)),l>1&&c.push(a.getY(t)),l>2&&c.push(a.getZ(t)),l>3&&c.push(a.getW(t)))}}class f9e{constructor(e){this.triangle=new Ls().copy(e),this.intersects={}}addTriangle(e,n){this.intersects[e]=new Ls().copy(n)}getIntersectArray(){const e=[],{intersects:n}=this;for(const i in n)e.push(n[i]);return e}}class Poe{constructor(){this.data={}}addTriangleIntersection(e,n,i,r){const{data:s}=this;s[e]||(s[e]=new f9e(n)),s[e].addTriangle(i,r)}getTrianglesAsArray(e=null){const{data:n}=this,i=[];if(e!==null)e in n&&i.push(n[e].triangle);else for(const r in n)i.push(n[r].triangle);return i}getTriangleIndices(){return Object.keys(this.data).map(e=>parseInt(e))}getIntersectionIndices(e){const{data:n}=this;return n[e]?Object.keys(n[e].intersects).map(i=>parseInt(i)):[]}getIntersectionsAsArray(e=null,n=null){const{data:i}=this,r=new Set,s=[],o=a=>{if(i[a])if(n!==null)i[a].intersects[n]&&s.push(i[a].intersects[n]);else{const c=i[a].intersects;for(const l in c)r.has(l)||(r.add(l),s.push(c[l]))}};if(e!==null)o(e);else for(const a in i)o(a);return s}reset(){this.data={}}}class p9e{constructor(){this.enabled=!1,this.triangleIntersectsA=new Poe,this.triangleIntersectsB=new Poe,this.intersectionEdges=[]}addIntersectingTriangles(e,n,i,r){const{triangleIntersectsA:s,triangleIntersectsB:o}=this;s.addTriangleIntersection(e,n,i,r),o.addTriangleIntersection(i,r,e,n)}addEdge(e){this.intersectionEdges.push(e.clone())}reset(){this.triangleIntersectsA.reset(),this.triangleIntersectsB.reset(),this.intersectionEdges=[]}init(){this.enabled&&(this.reset(),Soe(this))}complete(){this.enabled&&Soe(null)}}const rA=new xt,mN=new Mi,uv=new Ls,gN=new Ls,sA=new Ls,_N=new Ls,ap=[],hv=[];function m9e(t){for(const e of t)return e}function g9e(t,e,n,i,r,s={}){const{useGroups:o=!0}=s,{aIntersections:a,bIntersections:c}=u9e(t,e),l=[];let u=null,h;return h=o?0:-1,Doe(t,e,a,n,!1,i,r,h),Roe(t,e,a,n,!1,r,h),n.findIndex(p=>p!==voe&&p!==boe)!==-1&&(h=o?t.geometry.groups.length||1:-1,Doe(e,t,c,n,!0,i,r,h),Roe(e,t,c,n,!0,r,h)),ap.length=0,hv.length=0,{groups:l,materials:u}}function Doe(t,e,n,i,r,s,o,a=0){const c=t.matrixWorld.determinant()<0;rA.copy(e.matrixWorld).invert().multiply(t.matrixWorld),mN.getNormalMatrix(t.matrixWorld).multiplyScalar(c?-1:1);const l=t.geometry.groupIndices,u=t.geometry.index,h=t.geometry.attributes.position,d=e.geometry.boundsTree,p=e.geometry.index,m=e.geometry.attributes.position,g=n.ids,y=n.intersectionSet;for(let A=0,v=g.length;A<v;A++){const x=g[A],C=a===-1?0:l[x]+a,T=3*x,S=u.getX(T+0),w=u.getX(T+1),E=u.getX(T+2);uv.a.fromBufferAttribute(h,S).applyMatrix4(rA),uv.b.fromBufferAttribute(h,w).applyMatrix4(rA),uv.c.fromBufferAttribute(h,E).applyMatrix4(rA),s.reset(),s.initialize(uv);const D=y[x];for(let P=0,I=D.length;P<I;P++){const _=3*D[P],M=p.getX(_+0),L=p.getX(_+1),N=p.getX(_+2);gN.a.fromBufferAttribute(m,M),gN.b.fromBufferAttribute(m,L),gN.c.fromBufferAttribute(m,N),s.splitByTriangle(gN)}const O=s.triangles;for(let P=0,I=O.length;P<I;P++){const _=O[P],M=s.coplanarTriangleUsed?l9e(_,d):Ioe(_,d);ap.length=0,hv.length=0;for(let L=0,N=i.length;L<N;L++){const F=Moe(i[L],M,r);F!==m6&&(hv.push(F),ap.push(o[L].getGroupAttrSet(C)))}if(ap.length!==0){uv.getBarycoord(_.a,_N.a),uv.getBarycoord(_.b,_N.b),uv.getBarycoord(_.c,_N.c);for(let L=0,N=ap.length;L<N;L++){const F=ap[L],k=hv[L]===XI;h9e(x,_N,t.geometry,t.matrixWorld,mN,F,c!==k)}}}}return g.length}function Roe(t,e,n,i,r,s,o=0){const a=t.matrixWorld.determinant()<0;rA.copy(e.matrixWorld).invert().multiply(t.matrixWorld),mN.getNormalMatrix(t.matrixWorld).multiplyScalar(a?-1:1);const c=e.geometry.boundsTree,l=t.geometry.groupIndices,u=t.geometry.index,h=t.geometry.attributes,d=h.position,p=[],m=t.geometry.halfEdges,g=new Set,y=i6(t.geometry);for(let A=0,v=y;A<v;A++)A in n.intersectionSet||g.add(A);for(;g.size>0;){const A=m9e(g);g.delete(A),p.push(A);const v=3*A,x=u.getX(v+0),C=u.getX(v+1),T=u.getX(v+2);sA.a.fromBufferAttribute(d,x).applyMatrix4(rA),sA.b.fromBufferAttribute(d,C).applyMatrix4(rA),sA.c.fromBufferAttribute(d,T).applyMatrix4(rA);const S=Ioe(sA,c);hv.length=0,ap.length=0;for(let w=0,E=i.length;w<E;w++){const D=Moe(i[w],S,r);D!==m6&&(hv.push(D),ap.push(s[w]))}for(;p.length>0;){const w=p.pop();for(let E=0;E<3;E++){const D=m.getSiblingTriangleIndex(w,E);D!==-1&&g.has(D)&&(p.push(D),g.delete(D))}if(ap.length!==0){const E=3*w,D=u.getX(E+0),O=u.getX(E+1),P=u.getX(E+2),I=o===-1?0:l[w]+o;if(sA.a.fromBufferAttribute(d,D),sA.b.fromBufferAttribute(d,O),sA.c.fromBufferAttribute(d,P),!iA(sA))for(let _=0,M=ap.length;_<M;_++){const L=hv[_],N=ap[_].getGroupAttrSet(I),F=L===XI;d9e(D,O,P,h,t.matrixWorld,mN,N,F!==a)}}}}}function _9e(t){for(let e=0;e<t.length-1;e++){const n=t[e],i=t[e+1];if(n.materialIndex===i.materialIndex){const r=n.start,s=i.start+i.count;i.start=r,i.count=s-r,t.splice(e,1),e--}}}function A9e(t,e,n,i){n.clear();const r=t.attributes;for(let s=0,o=i.length;s<o;s++){const a=i[s],c=r[a];n.initializeArray(a,c.array.constructor,c.itemSize,c.normalized)}for(const s in n.attributes)i.includes(s)||n.delete(s);for(const s in e.attributes)i.includes(s)||(e.deleteAttribute(s),e.dispose())}function y9e(t,e,n){let i=!1,r=-1;const s=t.attributes,o=e.groupAttributes[0];for(const c in o){const l=e.getTotalLength(c),u=e.getType(c),h=e.getItemSize(c),d=e.getNormalized(c);let p=s[c];(!p||p.array.length<l)&&(p=new ji(new u(l),h,d),t.setAttribute(c,p),i=!0);let m=0;for(let g=0,y=Math.min(n.length,e.groupCount);g<y;g++){const A=n[g].index,{array:v,type:x,length:C}=e.groupAttributes[A][c],T=new x(v.buffer,0,C);p.array.set(T,m),m+=T.length}p.needsUpdate=!0,r=l/p.itemSize}if(t.index){const c=t.index.array;if(c.length<r)t.index=null,i=!0;else for(let l=0,u=c.length;l<u;l++)c[l]=l}let a=0;t.clearGroups();for(let c=0,l=Math.min(n.length,e.groupCount);c<l;c++){const{index:u,materialIndex:h}=n[c],d=e.getCount(u);d!==0&&(t.addGroup(a,d,h),a+=d)}t.setDrawRange(0,r),t.boundsTree=null,i&&t.dispose()}function Ooe(t,e){let n=e;return Array.isArray(e)||(n=[],t.forEach(i=>{n[i.materialIndex]=e})),n}class b9e{constructor(){this.triangleSplitter=new e9e,this.attributeData=[],this.attributes=["position","uv","normal"],this.useGroups=!0,this.consolidateGroups=!0,this.debug=new p9e}getGroupRanges(e){return!this.useGroups||e.groups.length===0?[{start:0,count:1/0,materialIndex:0}]:e.groups.map(n=>({...n}))}evaluate(e,n,i,r=new cN){let s=!0;if(Array.isArray(i)||(i=[i]),Array.isArray(r)||(r=[r],s=!1),r.length!==i.length)throw new Error("Evaluator: operations and target array passed as different sizes.");e.prepareGeometry(),n.prepareGeometry();const{triangleSplitter:o,attributeData:a,attributes:c,useGroups:l,consolidateGroups:u,debug:h}=this;for(;a.length<r.length;)a.push(new n9e);r.forEach((A,v)=>{A9e(e.geometry,A.geometry,a[v],c)}),h.init(),g9e(e,n,i,o,a,{useGroups:l}),h.complete();const d=this.getGroupRanges(e.geometry),p=Ooe(d,e.material),m=this.getGroupRanges(n.geometry),g=Ooe(m,n.material);m.forEach(A=>A.materialIndex+=p.length);let y=[...d,...m].map((A,v)=>({...A,index:v}));if(l){const A=[...p,...g];u&&(y=y.map(x=>{const C=A[x.materialIndex];return x.materialIndex=A.indexOf(C),x}).sort((x,C)=>x.materialIndex-C.materialIndex));const v=[];for(let x=0,C=A.length;x<C;x++){let T=!1;for(let S=0,w=y.length;S<w;S++){const E=y[S];E.materialIndex===x&&(T=!0,E.materialIndex=v.length)}T&&v.push(A[x])}r.forEach(x=>{x.material=v})}else y=[{start:0,count:1/0,index:0,materialIndex:0}],r.forEach(A=>{A.material=p[0]});return r.forEach((A,v)=>{const x=A.geometry;y9e(x,a[v],y),u&&_9e(x.groups)}),s?r:r[0]}evaluateHierarchy(e,n=new cN){e.updateMatrixWorld(!0);const i=(s,o)=>{const a=s.children;for(let c=0,l=a.length;c<l;c++){const u=a[c];u.isOperationGroup?i(u,o):o(u)}},r=s=>{const o=s.children;let a=!1;for(let l=0,u=o.length;l<u;l++){const h=o[l];a=r(h)||a}const c=s.isDirty();if(c&&s.markUpdated(),a&&!s.isOperationGroup){let l;return i(s,u=>{l?l=this.evaluate(l,u,u.operation):l=this.evaluate(s,u,u.operation)}),s._cachedGeometry=l.geometry,s._cachedMaterials=l.material,!0}else return a||c};return r(e),n.geometry=e._cachedGeometry,n.material=e._cachedMaterials,n}reset(){this.triangleSplitter.reset()}}class v9e{engine;evaluator;fillMeshName="ClippingFaceFillMesh";fillMeshes=new Map;maxCandidates=22e5;maxTriangleCountPerMesh=12e4;fillMaterial;fillTextureRepeat=60;fillTextureRotation=0;constructor(e){this.engine=e,this.evaluator=new b9e;const n=Wi("/texture/fill.png",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:gt&>.tagName.toUpperCase()==="SCRIPT"&>.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href),i=new Bd().load(n);i.wrapS=Uc,i.wrapT=Uc,i.center.set(.5,.5),i.rotation=this.fillTextureRotation,this.fillMaterial=new V_({color:14079687,map:i,side:tr,toneMapped:!1}),this.fillMaterial.clipShadows=!0,this.fillMaterial.clippingPlanes=e.sectionPlane}clear(){this.fillMeshes.forEach(e=>{e.parent?.remove(e),e.geometry?.dispose?.();const n=e.material;Array.isArray(n)?n.forEach(i=>i.dispose?.()):n&&n!==this.fillMaterial&&n.dispose?.()}),this.fillMeshes.clear()}updataFace(e){this.clear(),e instanceof Zi&&this.engine.clipping.fillCutFace&&this.buildSinglePlaneFill(e,"face")}updataFaces(e){this.clear(),!(!Array.isArray(e)||e.length===0)&&this.engine.clipping.fillCutFace&&e.forEach((n,i)=>{if(!(n instanceof Zi))return;const r=`plane-${i}-${String(n.name??i)}`;this.buildSinglePlaneFill(n,r)})}buildSinglePlaneFill(e,n){const i=this.engine?.octreeBox?.getBoundingBox?.();if(i==null||i.min==null||i.max==null)return;const r=this.collectCandidateMeshesFromOctree(e);if(r.length===0)return;const s=this.filterMeshesByBoxAndComplexity(e,r);if(s.length===0)return;const o=i.min.distanceTo(i.max),a=o*5,c=.1,l=this.createPlaneBrush(e,a,c),u=[];for(const g of s.slice(0,this.maxCandidates)){const y=this.createWorldBrushFromMesh(g);if(y!=null)try{const v=this.evaluator.evaluate(y,l,yoe)?.geometry;if(!v)continue;const x=this.extractPlaneCapGeometry(v,e,c);x&&u.push(x),v.dispose()}catch{}finally{y.geometry.dispose()}}if(l.geometry.dispose(),u.length===0)return;const h=Cm(u,!1);if(u.forEach(g=>g.dispose()),!h)return;this.applyPlanarUv(h,e);const d=this.getFaceOffsetDistance(o),p=this.getFaceOffsetSign();h.translate(e.normal.x*d*p,e.normal.y*d*p,e.normal.z*d*p);const m=new bt(h,this.fillMaterial);m.name=`${this.fillMeshName}_${n}`,m.frustumCulled=!1,m.renderOrder=20,m.castShadow=!1,m.receiveShadow=!1,this.engine.scene.add(m),this.fillMeshes.set(n,m)}getFaceOffsetDistance(e){return-.001}getFaceOffsetSign(){const e=this.engine?.engineStatus?.clippingFaceOffsetSign;return e===1||e===-1?e:-1}collectCandidateMeshesFromOctree(e){const n=[],i=new Set,r=Array.isArray(this.engine?.models)?this.engine.models:[];for(const s of r){if(!s?.nodesMap)continue;const o=this.getIgnoredIds(s.url),a=Array.isArray(s?.lods)?s.lods:[];for(const c of a){const l=c?.octreeBox;if(!l)continue;const u=this.collectIntersectElementIds(l,e);for(const h of u){if(o.has(h))continue;const d=s.nodesMap.get(h);if(!(d?.instance===!0||!Array.isArray(d?.infos)))for(const p of d.infos){const m=p?.mesh;m instanceof bt&&(i.has(m.uuid)||(i.add(m.uuid),n.push(m)))}}}}return n}getIgnoredIds(e){const n=new Set,i=Array.isArray(this.engine?.engineStatus?.hideModels)?this.engine.engineStatus.hideModels:[],r=Array.isArray(this.engine?.engineStatus?.translucentModels)?this.engine.engineStatus.translucentModels:[],s=i.find(a=>a.url===e)?.ids;Array.isArray(s)&&s.forEach(a=>n.add(a));const o=r.find(a=>a.url===e)?.ids;return Array.isArray(o)&&o.forEach(a=>n.add(a)),n}collectIntersectElementIds(e,n){const i=new Set,r=[e];for(;r.length>0;){const s=r.pop();if(!s)continue;const o=this.octreeNodeToBox3(s);!o||!n.intersectsBox(o)||(Array.isArray(s.elements)&&s.elements.forEach(a=>i.add(a)),Array.isArray(s.children)&&s.children.forEach(a=>r.push(a)))}return i}octreeNodeToBox3(e){if(!e?.min||!e?.max)return null;const n=new H(e.min.X*.3048,e.min.Z*.3048,-e.min.Y*.3048),i=new H(e.max.X*.3048,e.max.Z*.3048,-e.max.Y*.3048),r=new H(Math.min(n.x,i.x),Math.min(n.y,i.y),Math.min(n.z,i.z)),s=new H(Math.max(n.x,i.x),Math.max(n.y,i.y),Math.max(n.z,i.z));return new Ln(r,s)}filterMeshesByBoxAndComplexity(e,n){const i=[],r=new Ln;for(const s of n){const o=s.geometry,a=o?.attributes?.position;!o||!a||a.count===0||(o.index?Math.floor(o.index.count/3):Math.floor(a.count/3))>this.maxTriangleCountPerMesh||(o.boundingBox||o.computeBoundingBox(),o.boundingBox&&(r.copy(o.boundingBox),s.updateWorldMatrix(!0,!1),r.applyMatrix4(s.matrixWorld),e.intersectsBox(r)&&(s.geometry.attributes.position.count>500||i.push(s))))}return i}createPlaneBrush(e,n,i){const r=new so(n,n,i),s=e.coplanarPoint(new H),o=new ni().setFromUnitVectors(new H(0,0,1),e.normal.clone().normalize()),a=new xt().compose(s,o,new H(1,1,1));r.applyMatrix4(a);const c=this.toCsgReadyGeometry(r);return r.dispose(),new cN(c)}createWorldBrushFromMesh(e){const n=e.geometry;if(!n||!n.attributes?.position)return null;e.updateWorldMatrix(!0,!1);const i=n.clone();i.applyMatrix4(e.matrixWorld);const r=this.toCsgReadyGeometry(i);return i.dispose(),new cN(r)}toCsgReadyGeometry(e){const n=e.index?e.toNonIndexed():e.clone();n.getAttribute("normal")||n.computeVertexNormals();const i=n.getAttribute("position");if(i&&!n.getAttribute("uv")){const s=new Float32Array(i.count*2);n.setAttribute("uv",new _n(s,2))}const r=new Set(["position","normal","uv"]);return Object.keys(n.attributes).forEach(s=>{r.has(s)||n.deleteAttribute(s)}),n}extractPlaneCapGeometry(e,n,i){const r=e.index?e.toNonIndexed():e.clone(),s=r.getAttribute("position");if(!s||s.count<3)return r.dispose(),null;const o=n.normal.clone().normalize(),a=new H,c=new H,l=new H,u=new H,h=new H,d=new H,p=new H,m=new H,g=new H,y=Math.max(i*.35,1e-4),A=Math.max(i*.7,1e-4),v=[];for(let C=0;C<s.count;C+=3){if(u.fromBufferAttribute(s,C),h.fromBufferAttribute(s,C+1),d.fromBufferAttribute(s,C+2),c.subVectors(h,u),l.subVectors(d,u),a.crossVectors(c,l),a.lengthSq()<1e-14||(a.normalize(),Math.abs(a.dot(o))<.9))continue;const T=n.distanceToPoint(u),S=n.distanceToPoint(h),w=n.distanceToPoint(d),E=Math.min(T,S,w);if(Math.max(T,S,w)-E>y)continue;const O=(T+S+w)/3;Math.abs(O)>A||O<0||(p.copy(u).addScaledVector(o,-T),m.copy(h).addScaledVector(o,-S),g.copy(d).addScaledVector(o,-w),a.dot(o)<=0?(v.push(p.x,p.y,p.z),v.push(m.x,m.y,m.z),v.push(g.x,g.y,g.z)):(v.push(p.x,p.y,p.z),v.push(g.x,g.y,g.z),v.push(m.x,m.y,m.z)))}if(r.dispose(),v.length<9)return null;const x=new Dn;return x.setAttribute("position",new _n(v,3)),x.computeVertexNormals(),x}applyPlanarUv(e,n){const i=e.getAttribute("position");if(!i||i.count===0)return;const{tangent:r,bitangent:s}=this.getPlaneBasis(n.normal.clone().normalize()),o=new H,a=new Float32Array(i.count*2);let c=1/0,l=-1/0,u=1/0,h=-1/0;for(let m=0;m<i.count;m++){o.fromBufferAttribute(i,m);const g=o.dot(r),y=o.dot(s),A=m*2;a[A]=g,a[A+1]=y,c=Math.min(c,g),l=Math.max(l,g),u=Math.min(u,y),h=Math.max(h,y)}const d=Math.max(l-c,1e-6),p=Math.max(h-u,1e-6);for(let m=0;m<a.length;m+=2)a[m]=(a[m]-c)/d*this.fillTextureRepeat,a[m+1]=(a[m+1]-u)/p*this.fillTextureRepeat;e.setAttribute("uv",new ji(a,2))}getPlaneBasis(e){const n=new H(1,0,0),i=new H(0,1,0),r=new H(0,0,1),s=Math.abs(e.dot(n)),o=Math.abs(e.dot(i)),a=Math.abs(e.dot(r));let c=n;o<=s&&o<=a?c=i:a<=s&&a<=o&&(c=r),c=c.clone().sub(e.clone().multiplyScalar(c.dot(e))).normalize();const l=new H().crossVectors(e,c).normalize();return{tangent:c,bitangent:l}}}class x9e{engine;clippingTolerance=1e-4;sectionBox;sectionFace;clippingStencil;clippingCSGSimple=null;currentClippingMode="";sectionCatchFace;fillCutFace=!0;viewRangePlanes=null;constructor(e){this.engine=e,this.sectionCatchFace=new DGe(this.engine);let n=new Zi(new H(0,0,1),1e5);n.name="前";let i=new Zi(new H(0,0,1),1e5);i.name="左";let r=new Zi(new H(0,0,1),1e5);r.name="后";let s=new Zi(new H(0,0,1),1e5);s.name="右";let o=new Zi(new H(0,0,1),1e5);o.name="顶";let a=new Zi(new H(0,0,1),1e5);a.name="底";let c=new Zi(new H(0,0,1),1e5);c.name="face",this.engine.sectionPlane=[n,i,r,s,o,a,c]}init(){this.sectionBox=new MGe(this.engine),this.sectionFace=new PGe(this.engine),this.clippingCSGSimple=new v9e(this.engine)}scaleBox(){let e=this.engine.octreeBox.getBoundingBox();this.sectionBox.setBox(e)}setFillCutFace(e){this.fillCutFace=e}getFillCutFace(){return this.fillCutFace}clippingModel(e){let n=[];e.forEach(s=>{let o=this.engine.models.find(a=>a.url===s.url);s.ids.forEach(a=>{o.nodesMap.get(a).infos.forEach(c=>{n.push(c.box)})})}),this.active("box");let i=r(n);i.expandByScalar(.1),this.sectionBox.setBox(i);function r(s){let o=new H(1e8,1e9,1e10),a=new H(-1e8,-1e9,-1e10);return s.forEach(c=>{c.min.x<o.x&&(o.x=c.min.x),c.min.y<o.y&&(o.y=c.min.y),c.min.z<o.z&&(o.z=c.min.z),c.max.x>a.x&&(a.x=c.max.x),c.max.y>a.y&&(a.y=c.max.y),c.max.z>a.z&&(a.z=c.max.z)}),new Ln(o,a)}}updateClippingValue(e){let n=this.sectionBox.maxBox,i=n.min.x+(n.max.x-n.min.x)*e.x.min*.01,r=n.min.y+(n.max.y-n.min.y)*e.y.min*.01,s=n.min.z+(n.max.z-n.min.z)*e.z.min*.01,o=n.min.x+(n.max.x-n.min.x)*e.x.max*.01,a=n.min.y+(n.max.y-n.min.y)*e.y.max*.01,c=n.min.z+(n.max.z-n.min.z)*e.z.max*.01;this.sectionBox.setboxXyz({minX:i,minY:r,minZ:s,maxX:o,maxY:a,maxZ:c})}active(e){this.engine.engineStatus.isForceFree=!0,this.sectionFace.disActive(),this.sectionBox.disActive(),this.sectionCatchFace.cancel(),this.viewRangePlanes=null,this.currentClippingMode=e,e=="x"?(this.sectionFace.direction=1,this.sectionFace.init(),this.sectionFace.active(),this.sectionFace.setFaceNormal(new H(-1,0,0))):e=="y"?(this.sectionFace.direction=1,this.sectionFace.init(),this.sectionFace.active(),this.sectionFace.setFaceNormal(new H(0,0,-1))):e=="z"?(this.sectionFace.direction=1,this.sectionFace.init(),this.sectionFace.active(),this.sectionFace.setFaceNormal(new H(0,-1,0))):e=="box"?(this.sectionBox.init(),this.sectionBox.active()):e=="face"&&(this.sectionFace.direction=1,this.sectionCatchFace.init(),this.sectionCatchFace.catch_face(n=>{this.sectionFace.init(),this.sectionFace.active();let i=this.engine.octreeBox.getBoundingBox(),r=i.min.clone().add(i.max.clone()).multiplyScalar(.5),s=n.position.clone().sub(r),o=new H(n.dir.x,n.dir.y,n.dir.z),a=s.dot(o);this.sectionFace.setFaceNormal(n.dir,a)}))}disabled(){this.currentClippingMode=="box"?this.sectionBox.disabled():this.currentClippingMode=="viewRange"?(this.setPlaneConstantsHigh(this.engine.sectionPlane?.slice?.(0,6)),this.clippingCSGSimple?.clear()):this.sectionFace.disabled(),this.engine.engineStatus.isForceFree=!1}recover(){this.currentClippingMode=="box"?this.sectionBox.recover():this.currentClippingMode=="viewRange"?this.applyStoredViewRangePlanes():this.sectionFace.recover()}reverse(){this.currentClippingMode!=="x"&&this.currentClippingMode!=="y"&&this.currentClippingMode!=="z"&&this.currentClippingMode!=="face"||this.sectionFace.reverse()}disActive(){this.sectionFace.disActive(),this.sectionBox.disActive(),this.clippingCSGSimple?.clear(),this.sectionCatchFace.cancel(),this.viewRangePlanes=null,this.currentClippingMode="",this.engine.engineStatus.isForceFree=!1}isPointInClippingRange(e,n=this.clippingTolerance){if(!this.isVector3Like(e))return!1;const i=this.getEffectiveClippingPlanes();return i.length===0?!0:i.every(r=>r.distanceToPoint(e)>=-n)}filterIntersectionsByClipping(e,n=this.clippingTolerance){return!Array.isArray(e)||e.length===0?[]:e.filter(i=>this.isPointInClippingRange(i?.point,n))}doesBoxIntersectClippingRange(e,n=this.clippingTolerance){const i=this.toBox3(e);if(i==null||i.isEmpty())return!1;const r=this.getEffectiveClippingPlanes();return r.length===0?!0:r.every(s=>this.isBoxVisibleAgainstPlane(i,s,n))}getClippedBoundingBox(e){const n=this.toBox3(e??this.engine.octreeBox?.getBoundingBox?.());if(n==null||n.isEmpty())return null;const i=this.getEffectiveClippingPlanes();if(i.length===0)return n.clone();const r=this.getBoxBoundaryPlanes(n).concat(i),s=[];for(let o=0;o<r.length-2;o++)for(let a=o+1;a<r.length-1;a++)for(let c=a+1;c<r.length;c++){const l=this.intersectThreePlanes(r[o],r[a],r[c]);l&&this.isPointInsidePlanes(l,r)&&this.pushUniquePoint(s,l)}return s.length===0?null:new Ln().setFromPoints(s)}getEffectiveClippingPlanes(){const e=Array.isArray(this.engine.sectionPlane)?this.engine.sectionPlane:[];if(this.currentClippingMode==="box"||this.currentClippingMode==="viewRange")return e.slice(0,6).filter(n=>n instanceof Zi);if(this.currentClippingMode==="x"||this.currentClippingMode==="y"||this.currentClippingMode==="z"||this.currentClippingMode==="face"){const n=e[6];return n instanceof Zi?[n]:[]}return[]}toBox3(e){return e==null||e.min==null||e.max==null?null:new Ln(new H(e.min.x,e.min.y,e.min.z),new H(e.max.x,e.max.y,e.max.z))}getBoxBoundaryPlanes(e){return[new Zi(new H(1,0,0),-e.min.x),new Zi(new H(-1,0,0),e.max.x),new Zi(new H(0,1,0),-e.min.y),new Zi(new H(0,-1,0),e.max.y),new Zi(new H(0,0,1),-e.min.z),new Zi(new H(0,0,-1),e.max.z)]}intersectThreePlanes(e,n,i){const r=e.normal,s=n.normal,o=i.normal,a=r.dot(new H().crossVectors(s,o));if(Math.abs(a)<1e-8)return null;const c=new H().crossVectors(s,o).multiplyScalar(-e.constant),l=new H().crossVectors(o,r).multiplyScalar(-n.constant),u=new H().crossVectors(r,s).multiplyScalar(-i.constant);return c.add(l).add(u).divideScalar(a)}isPointInsidePlanes(e,n){return n.every(i=>i.distanceToPoint(e)>=-this.clippingTolerance)}isBoxVisibleAgainstPlane(e,n,i){const r=new H(n.normal.x>=0?e.max.x:e.min.x,n.normal.y>=0?e.max.y:e.min.y,n.normal.z>=0?e.max.z:e.min.z);return n.distanceToPoint(r)>=-i}pushUniquePoint(e,n){e.some(r=>r.distanceToSquared(n)<this.clippingTolerance*this.clippingTolerance)||e.push(n)}isVector3Like(e){return e!=null&&typeof e.x=="number"&&typeof e.y=="number"&&typeof e.z=="number"}setSectionByView(e,n){this.sectionFace.disActive(),this.sectionBox.disActive(),this.viewRangePlanes=null,this.scaleBox(),this.sectionFace.init(!0);const i=this.engine.octreeBox.getBoundingBox(),r=new H((i.min.x+i.max.x)/2,(i.min.y+i.max.y)/2,(i.min.z+i.max.z)/2),o=new H(n.x,n.y,n.z).normalize().clone().negate(),c=new H(e.x,e.y,e.z).clone().sub(r).dot(o);this.sectionFace.setFaceNormalPlaneOnly(o,c),this.sectionFace.activateClippingOnly(),this.currentClippingMode="face"}setSectionPlanesByViewRange(e){const n=Array.isArray(e)?e.filter(i=>i instanceof Zi).slice(0,6):[];n.length===6&&(this.sectionFace.disActive(),this.sectionBox.disActive(),this.sectionCatchFace.cancel(),this.viewRangePlanes=n.map(i=>i.clone()),this.applyStoredViewRangePlanes(),this.currentClippingMode="viewRange",this.engine.engineStatus.isForceFree=!0)}applyStoredViewRangePlanes(){if(!this.viewRangePlanes||this.viewRangePlanes.length!==6)return;const e=Array.isArray(this.engine.sectionPlane)?this.engine.sectionPlane:[];this.viewRangePlanes.forEach((i,r)=>{e[r]instanceof Zi&&e[r].copy(i)});const n=e[6];n instanceof Zi&&(n.constant=1e5),this.applySectionPlanesToModelMeshes(),this.clippingCSGSimple?.updataFaces?.(e.slice(0,6))}applySectionPlanesToModelMeshes(){zj(this.engine).forEach(e=>{e.material&&Array.isArray(e.material)?e.material.forEach(n=>{n.clippingPlanes=this.engine.sectionPlane,n.clipShadows=!0}):e.material&&(e.material.clippingPlanes=this.engine.sectionPlane,e.material.clipShadows=!0)})}setPlaneConstantsHigh(e){Array.isArray(e)&&e.forEach(n=>{n instanceof Zi&&(n.constant=1e5)})}}class C9e{engine;constructor(e){this.engine=e}getLevelTreeData(){let e=[];return(this.engine?.models??[]).forEach(i=>{e.push({children:i.modelTree?.modelTreeLevel,name:i.baseInfo?.name,url:i.url})}),e}getTypeTreeData(){let e=[];return(this.engine?.models??[]).forEach(i=>{e.push({children:i.modelTree?.modelTreeType,name:i.baseInfo?.name,url:i.url})}),e}getMajorTreeData(){let e=[];return(this.engine?.models??[]).forEach(i=>{e.push({children:i.modelTree?.modelTreeMajor,name:i.baseInfo?.name,url:i.url})}),e}}class E9e{engine;constructor(e){this.engine=e}getEngineInfo(){let e=0,n=0,i=0;return!this.engine||!this.engine.scene?{totalVertices:0,totalTriangles:0,meshCount:0}:(this.engine.scene.traverse(r=>{if(r instanceof bt){const s=r.geometry;if(s&&s.attributes){const o=s.attributes.position;if(o){const a=o.count;e+=a;let c=0;s.index?c=s.index.count/3:c=a/3,n+=c}}}}),(this.engine?.models??[]).forEach(r=>{i=i+r.nodesMap.size}),{totalVertices:Math.floor(e),totalTriangles:Math.floor(n),meshCount:i})}}class w9e{engine;extended=new Map;constructor(e){this.engine=e}init(){}updateExtended(e,n){let i=this.extended.get(e);i==null?this.extended.set(e,n):n.forEach((r,s)=>{i.set(s,r)})}getModelPropertiesWithName(e,n,i,r){let s=this.extended.get(e),o=this.engine.engineStatus.models.find(c=>c.url===e);o.properties==null?(iB(this.engine,e,e+"/property"),PB(e+"/property",c=>{let l=JSON.parse(c);o.properties=l,setTimeout(()=>{a(l,i,n,r)},100)},()=>{},o?.key)):a(o.properties,i,n,r);function a(c,l,u,h){let d={},p=c.models[u];p==null&&(p=c.models[u.toString()||""]),p.forEach(m=>{i.includes(c.names[m[1]])&&(d[c.names[m[1]]]=c.values[m[2]])}),s!=null&&s.has(u)&&d.push(s.get(u)),h?.({id:u,properties:d})}}getModelProperties(e,n,i){let r=this.extended.get(e),s=this.engine.engineStatus.models.find(a=>a.url===e);s.properties==null&&(iB(this.engine,e,e+"/property"),PB(e+"/property",a=>{let c=JSON.parse(a);s.properties=c,setTimeout(()=>{o(c,n,i)},100)},()=>{},s?.key)),o(s.properties,n,i);function o(a,c,l){let u=[],h=a.models[c];h==null&&(h=a.models[c.toString()||""]);let d=h.map(m=>m[0]);d=d.filter((m,g)=>d.indexOf(m)===g),d.forEach(m=>{let g={name:a.categorys[m],children:[]};u.push(g),h.filter(y=>y[0]===m).forEach(y=>{g.children.push({name:a.names[y[1]],value:a.values[y[2]]})})}),r!=null&&r.has(c)&&u.push(r.get(c));const p={基础数据:0,基礎信息:0,标识数据:1,尺寸标注:2,文字:3,约束:4,阶段化:5,结构:6,图形:7,材质和装饰:8,构造:9,分析属性:10,其他:11,基礎資料:0,識別資料:1,尺寸:2,約束:4,階段:5,結構:6,圖形:7,材料及飾面:8,構造:9,分析性質:10};u.sort((m,g)=>{const y=p[m.name]??99;return(p[g.name]??99)-y}),l?.({properties:u,materials:u})}}}const T9e='<svg width="18" height="18" viewBox="0 0 24 24" fill="none" aria-hidden="true"><circle cx="10.8" cy="10.8" r="6.5" stroke="currentColor" stroke-width="2"/><path d="m16 16 4.3 4.3" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>';class S9e{manager;wrapper;input;status;list;pagination;results=[];activeIndex=-1;currentPage=1;pageSize=20;debounceTimer=null;constructor(e,n){this.manager=n,this.wrapper=document.createElement("div"),this.wrapper.className="engine-3d-search",this.wrapper.innerHTML=`
|
|
5363
5363
|
<section class="engine-3d-search__box" role="dialog" aria-label="模型检索">
|
|
5364
5364
|
<div class="engine-3d-search__input-row">
|
|
5365
5365
|
<span class="engine-3d-search__icon">${T9e}</span>
|
|
@@ -6012,7 +6012,7 @@ void main() {
|
|
|
6012
6012
|
|
|
6013
6013
|
gl_FragColor = vec4(color, clamp(alpha, 0.0, 1.0));
|
|
6014
6014
|
}
|
|
6015
|
-
`});return h.clippingPlanes=this.engine.sectionPlane,n.alwaysOnTop&&(h.depthTest=!1),h}createPulseMaterial(e,n,i,r,s,o,a){return this.createSurfaceMaterial({color:`#${e.getHexString()}`,opacity:n,style:i,effect:{...r,pulse:r.pulse?.enabled?r.pulse:{enabled:!0,speed:1.4,minOpacity:.55,maxOpacity:1}},axisMode:s,axisMin:o,axisMax:a})}axisModeToNumber(e){return e==="x"?0:e==="y"?1:e==="z"?2:e==="uvx"?3:4}getGradientStops(e,n){if(!Array.isArray(n)||n.length===0)return[{offset:0,color:e,alpha:1},{offset:1,color:e,alpha:.08}];const i=[...n].sort((o,a)=>o.offset-a.offset),r=i[0],s=i[i.length-1];return[{offset:0,color:r.color,alpha:r.alpha??1},{offset:1,color:s.color,alpha:s.alpha??.08}]}}const UM={color:"#7ffcff",opacity:.92,fillColor:"#7ffcff",fillOpacity:.18,depthTest:!0,alwaysOnTop:!1,lineWidth:.18,point:{mode:"sprite",size:0,iconSize:32,billboard:!0,anchorY:0},line:{dashed:!1,closed:!1},polygon:{showEdge:!0,edgeColor:"#d9ffff",edgeWidth:1},volume:{height:10,showTop:!0,showSide:!0,showBottom:!1,edgeColor:"#d9ffff"}},IKe={background:"rgba(10, 18, 28, 0.92)",color:"#ffffff",border:"1px solid rgba(127, 252, 255, 0.72)",borderRadius:"10px",padding:"12px",boxShadow:"0 10px 30px rgba(0, 0, 0, 0.32)",minWidth:"120px",pointerEvents:"auto"},MKe="bim-engine-annotation3d-panels";class PKe{normalizeData(e){return{...e,id:e.id??`annotation3d-${Date.now()}-${Math.random().toString(16).slice(2)}`,points:_F(e.points??[]),visible:e.visible??!0,selectable:e.selectable??!0,style:this.mergeStyle(e.style),effect:this.mergeEffect(e.effect),panel:e.panel?this.normalizePanel(e.panel):void 0}}mergeData(e,n,i,r){const s=i.panel===void 0?e.panel?{...e.panel,actions:n}:void 0:i.panel==null?void 0:{...e.panel,...i.panel,style:{...e.panel?.style??{},...i.panel.style??{}},actions:i.panel.actions??n};return this.normalizeData({id:r,type:i.type??e.type,points:i.points?_F(i.points):_F(e.points),visible:i.visible??e.visible,selectable:i.selectable??e.selectable,style:{...e.style,...i.style??{},point:{...e.style.point??{},...i.style?.point??{}},line:{...e.style.line??{},...i.style?.line??{}},polygon:{...e.style.polygon??{},...i.style?.polygon??{}},volume:{...e.style.volume??{},...i.style?.volume??{}}},effect:{...e.effect,...i.effect??{}},panel:s,data:i.data??e.data})}mergeStyle(e){return{...UM,...e,point:{...UM.point,...e?.point??{}},line:{...UM.line,...e?.line??{}},polygon:{...UM.polygon,...e?.polygon??{}},volume:{...UM.volume,...e?.volume??{}}}}mergeEffect(e){return{...e,gradient:e?.gradient?{enabled:e.gradient.enabled,direction:e.gradient.direction??"vertical",stops:e.gradient.stops??[]}:void 0,glow:e?.glow?{...e.glow}:void 0,flow:e?.flow?{enabled:e.flow.enabled,speed:e.flow.speed??.6,width:e.flow.width??.18,direction:e.flow.direction??"forward"}:void 0,pulse:e?.pulse?{enabled:e.pulse.enabled,speed:e.pulse.speed??1.4,minOpacity:e.pulse.minOpacity??.55,maxOpacity:e.pulse.maxOpacity??1}:void 0,ripple:e?.ripple?{enabled:e.ripple.enabled,count:e.ripple.count??2,speed:e.ripple.speed??.9,maxRadius:e.ripple.maxRadius??12}:void 0,pillar:e?.pillar?{enabled:e.pillar.enabled,height:e.pillar.height??16,width:e.pillar.width??1.5}:void 0,baseRing:e?.baseRing?{enabled:e.baseRing.enabled,radius:e.baseRing.radius??3,rotateSpeed:e.baseRing.rotateSpeed??.8}:void 0,layers:e?.layers?{enabled:e.layers.enabled,count:e.layers.count??3,offsetY:e.layers.offsetY??3}:void 0,scan:e?.scan?{enabled:e.scan.enabled,speed:e.scan.speed??.8,width:e.scan.width??.18}:void 0}}normalizePanel(e){return{visible:e.visible??!0,trigger:e.trigger??"manual",mode:e.mode??(e.html?"html":"text"),text:e.text??"",html:e.html??"",anchor:e.anchor,offset:{...e.offset??{}},screenOffset:{...e.screenOffset??{}},className:e.className,style:{...IKe,...e.style??{}},interactive:e.interactive??!0,occlusion:e.occlusion??"show",actions:e.actions}}}function DKe(t,e,n){const i=t.camera;if(!i)return!1;const r=n.clone().sub(i.position),s=r.length();if(s<=1e-6)return!1;e.set(i.position,r.normalize());let o=t.octreeBox?.rayInterationModel?.(e,!0,!1)??[];o=t.clipping?.filterIntersectionsByClipping?.(o)??o;const a=o.sort((c,l)=>c.distance-l.distance)[0];return!!(a&&a.distance<s-.05)}class RKe{constructor(e,n){this.engine=e,this.isAnchorOccluded=n,this.container=document.createElement("div"),this.container.className=MKe,this.container.style.cssText=["position:absolute","left:0","top:0","width:100%","height:100%","pointer-events:none","overflow:hidden","z-index:1250"].join(";"),this.engine.container.appendChild(this.container),this.worldToScreen=new ua(this.engine.camera,this.engine.renderer,this.engine.scene)}container;worldToScreen;updateProjectionState(){this.worldToScreen.updateCamera(this.engine.camera),this.worldToScreen.updateRenderer(this.engine.renderer),this.worldToScreen.updateScene(this.engine.scene)}createPanelElement(e,n){const i=document.createElement("div");return i.className=`bim-annotation3d-panel ${n.className??""}`.trim(),i.dataset.annotationId=e.id,i.style.cssText=["position:absolute","left:0","top:0","transform:translate(-50%, -100%)","display:none",n.interactive===!1?"pointer-events:none":"pointer-events:auto"].join(";"),n.mode==="html"?i.innerHTML=n.html??"":i.textContent=n.text??"",Object.entries(n.style??{}).forEach(([r,s])=>{i.style.setProperty(CKe(r),s)}),i}updateRecord(e){if(!e.panelElement||!e.instance.panel)return;const n=e.instance.panel;if(!(n.visible!==!1&&this.shouldShowPanel(e))||!e.instance.visible){e.panelElement.style.display="none";return}const r=this.getPanelAnchorPoint(e),s=this.worldToScreen.worldToScreenIfVisible(r);if(!s){e.panelElement.style.display="none";return}if(n.occlusion==="hide"&&this.isAnchorOccluded(r)){e.panelElement.style.display="none";return}const o=n.screenOffset??{};e.panelElement.style.display="block",e.panelElement.style.left=`${s.x+(o.x??0)}px`,e.panelElement.style.top=`${s.y+(o.y??0)}px`}dispose(){this.container.remove()}shouldShowPanel(e){const n=e.instance.panel?.trigger??"manual";return n==="always"?!0:n==="hover"?e.instance.hovered:n==="click"||n==="manual"?e.instance.panelVisible:!1}getPanelAnchorPoint(e){const n=e.instance.panel?.anchor??EKe(e.instance.type),i=e.instance.panel?.offset??{};let r=new H;if(e.instance.type==="point")r.copy(Hh(e.instance.points[0])),n==="top"&&(r.y+=e.volumeHeight??e.instance.style.point?.anchorY??0);else if(e.instance.type==="polyline")n==="start"?r.copy(Hh(e.instance.points[0])):n==="end"?r.copy(Hh(e.instance.points[e.instance.points.length-1])):e.anchorCurve?r.copy(e.anchorCurve.getPoint(.5)):r.copy(AF(e.instance.points));else if(e.instance.type==="polygon")r.copy(AF(e.instance.points));else if(e.instance.type==="extrudePolygon")r.copy(AF(e.instance.points)),n==="top"&&e.anchorNormal&&r.add(e.anchorNormal.clone().multiplyScalar(e.volumeHeight??0));else if(e.instance.type==="box"&&(r.copy(AF(e.instance.points)),n==="top"&&e.instance.points.length>=2)){const s=Hh(e.instance.points[0]),o=Hh(e.instance.points[1]);r.y=Math.max(s.y,o.y)}return r.add(new H(i.x??0,i.y??0,i.z??0)),r}}class OKe{engine;rootGroup;records;panelContainer;onRecordVisualChange;onEmit;raycaster=new Da;hoveredId=null;constructor(e){this.engine=e.engine,this.rootGroup=e.rootGroup,this.records=e.records,this.panelContainer=e.panelContainer,this.onRecordVisualChange=e.onRecordVisualChange,this.onEmit=e.onEmit}bind(){this.engine.renderer?.domElement?.addEventListener?.("click",this.handleCanvasClick,!1),this.engine.renderer?.domElement?.addEventListener?.("mousemove",this.handleCanvasMove,!1),this.engine.renderer?.domElement?.addEventListener?.("mouseleave",this.handleCanvasLeave,!1),this.panelContainer.addEventListener("click",this.handlePanelClick,!1)}unbind(){this.engine.renderer?.domElement?.removeEventListener?.("click",this.handleCanvasClick,!1),this.engine.renderer?.domElement?.removeEventListener?.("mousemove",this.handleCanvasMove,!1),this.engine.renderer?.domElement?.removeEventListener?.("mouseleave",this.handleCanvasLeave,!1),this.panelContainer.removeEventListener("click",this.handlePanelClick,!1)}handleRecordRemoved(e){this.hoveredId===e&&(this.hoveredId=null)}pickAnnotation(e){const n=this.engine.renderer?.domElement,i=this.engine.camera;if(!n||!i)return null;const r=n.getBoundingClientRect(),s=e.clientX-r.left,o=e.clientY-r.top,a=new Ye(s/r.width*2-1,-(o/r.height)*2+1);this.raycaster.setFromCamera(a,i);const c=this.raycaster.intersectObjects(this.rootGroup.children,!0);for(const l of c){let u=l.object;for(;u;){const h=u.userData?.annotationId;if(h&&this.records.has(h)){const d=this.records.get(h);return d.instance.selectable!==!1&&d.instance.visible?d:null}u=u.parent}}return null}handleCanvasClick=e=>{const n=this.pickAnnotation(e);n&&(n.instance.panel?.trigger==="click"&&(n.instance.panelVisible=!n.instance.panelVisible,this.onRecordVisualChange(n),this.onEmit(n.instance.panelVisible?"annotation3d-panel-open":"annotation3d-panel-close",this.toEventPayload(n,e))),this.onEmit("annotation3d-click",this.toEventPayload(n,e)))};handleCanvasMove=e=>{const n=this.pickAnnotation(e),i=n?.instance.id??null;if(i!==this.hoveredId){if(this.hoveredId&&this.records.has(this.hoveredId)){const r=this.records.get(this.hoveredId);r.instance.hovered=!1,this.onRecordVisualChange(r),this.onEmit("annotation3d-leave",this.toEventPayload(r,e))}this.hoveredId=i,n&&(n.instance.hovered=!0,this.onRecordVisualChange(n),this.onEmit("annotation3d-hover",this.toEventPayload(n,e)))}};handleCanvasLeave=e=>{if(!this.hoveredId||!this.records.has(this.hoveredId)){this.hoveredId=null;return}const n=this.records.get(this.hoveredId);n.instance.hovered=!1,this.onRecordVisualChange(n),this.onEmit("annotation3d-leave",this.toEventPayload(n,e)),this.hoveredId=null};handlePanelClick=e=>{const n=e.target;if(!n)return;const i=n.closest("[data-annotation-id]");if(!i)return;const r=i.dataset.annotationId;if(!r||!this.records.has(r))return;const s=this.records.get(r);this.onEmit("annotation3d-panel-click",this.toEventPayload(s,e));const o=n.closest("[data-action]"),a=o?.dataset?.action;if(!a||!s.actions?.[a])return;const c={engine:this.engine,id:r,annotation:s.instance,action:a,element:o,originalEvent:e};s.actions[a]?.(c),this.onEmit("annotation3d-action",{...this.toEventPayload(s,e),action:a,target:o})};toEventPayload(e,n){return{id:e.instance.id,annotation:e.instance,originalEvent:n}}}function LKe(t){const{actions:e,...n}=t;return n}function BKe(t){return{id:t.instance.id,type:t.instance.type,points:_F(t.instance.points),visible:t.instance.visible,selectable:t.instance.selectable,style:yF(t.instance.style),effect:yF(t.instance.effect),panel:t.instance.panel?yF(t.instance.panel):void 0,data:yF(t.instance.data)}}function yF(t){return t===void 0?t:JSON.parse(JSON.stringify(t))}class NKe{engine;rootGroup;records=new Map;textureLoader=new Bd;occlusionRaycaster=new Da;normalizer=new PKe;materialFactory;geometryBuilder;effectsController;panelLayer;interaction;currentTime=0;constructor(e){this.engine=e,this.rootGroup=new $r,this.rootGroup.name="Annotation3dRoot",this.engine.scene.add(this.rootGroup),this.materialFactory=new SKe(this.engine),this.geometryBuilder=new wKe(this.engine,this.textureLoader,this.materialFactory),this.effectsController=new TKe(this.engine),this.panelLayer=new RKe(this.engine,n=>DKe(this.engine,this.occlusionRaycaster,n)),this.interaction=new OKe({engine:this.engine,rootGroup:this.rootGroup,records:this.records,panelContainer:this.panelLayer.container,onRecordVisualChange:n=>this.panelLayer.updateRecord(n),onEmit:(n,i)=>this.emit(n,i)}),this.interaction.bind()}add(e){const n=this.normalizer.normalizeData(e),i=this.buildRecord(n);return this.attachRecord(i),this.emit("annotation3d-created",this.toEventPayload(i)),n.id}addMany(e){return e.map(n=>this.add(n))}async pickPoint(){if(typeof this.engine.label?.pickPoint!="function")return null;const e=await this.engine.label.pickPoint();return e==null?null:{x:e.x,y:e.y,z:e.z}}update(e,n){const i=this.records.get(e);if(!i)return!1;const r=this.normalizer.mergeData(i.instance,i.actions,n,e);this.removeInternal(e,!1);const s=this.buildRecord(r);return this.attachRecord(s),this.emit("annotation3d-updated",this.toEventPayload(s)),!0}remove(e){return this.removeInternal(e,!0)}clear(){Array.from(this.records.keys()).forEach(e=>this.removeInternal(e,!1))}get(e){return this.records.get(e)?.instance}getAll(){return Array.from(this.records.values()).map(e=>e.instance)}show(e){return this.setVisible(e,!0)}hide(e){return this.setVisible(e,!1)}setVisible(e,n){const i=this.records.get(e);return i?(i.instance.visible=n,this.applyVisibility(i),!0):!1}showPanel(e){const n=this.records.get(e);return!n||!n.instance.panel?!1:(n.instance.panelVisible=!0,this.panelLayer.updateRecord(n),this.emit("annotation3d-panel-open",this.toEventPayload(n)),!0)}hidePanel(e){const n=this.records.get(e);return!n||!n.instance.panel?!1:(n.instance.panelVisible=!1,this.panelLayer.updateRecord(n),this.emit("annotation3d-panel-close",this.toEventPayload(n)),!0)}togglePanel(e){const n=this.records.get(e);return!n||!n.instance.panel?!1:n.instance.panelVisible?this.hidePanel(e):this.showPanel(e)}updatePanel(e,n){const i=this.records.get(e);if(!i||!i.instance.panel)return!1;const r={...i.instance.panel,...n,style:{...i.instance.panel.style??{},...n.style??{}},actions:n.actions??i.actions};return this.update(e,{panel:r})}getData(){return Array.from(this.records.values()).map(e=>BKe(e))}restoreData(e){this.clear(),e.forEach(n=>this.add(n))}updateFrame(e=1/60){this.currentTime+=e,this.panelLayer.updateProjectionState(),this.records.forEach(n=>{this.effectsController.updateRecord(n,this.currentTime),this.panelLayer.updateRecord(n)})}dispose(){this.interaction.unbind(),this.clear(),this.rootGroup.removeFromParent(),this.panelLayer.dispose()}buildRecord(e){const n=new $r;n.name=e.id;const i={id:e.id,type:e.type,points:e.points,visible:e.visible??!0,selectable:e.selectable??!0,style:e.style,effect:e.effect??{},panel:e.panel?LKe(e.panel):void 0,data:e.data,panelVisible:e.panel?.trigger==="always",hovered:!1,root:n},r={instance:i,actions:e.panel?.actions,panelElement:e.panel?this.panelLayer.createPanelElement(i,e.panel):null,timeSeed:Math.random()*Math.PI*2,pulseMaterials:[],rippleMeshes:[],baseRingMeshes:[],animatedMaterials:[]};return this.geometryBuilder.build(r),vKe(n,i.id),r}attachRecord(e){this.records.set(e.instance.id,e),this.rootGroup.add(e.instance.root),e.panelElement&&this.panelLayer.container.appendChild(e.panelElement),this.applyVisibility(e)}removeInternal(e,n){const i=this.records.get(e);return i?(this.interaction.handleRecordRemoved(e),xKe(i.instance.root),i.instance.root.removeFromParent(),i.panelElement?.remove(),this.records.delete(e),n&&this.emit("annotation3d-removed",{id:e}),!0):!1}applyVisibility(e){e.instance.root.visible=e.instance.visible,e.instance.style.alwaysOnTop&&e.instance.root.traverse(n=>{n.renderOrder=Math.max(n.renderOrder,1200)}),this.panelLayer.updateRecord(e)}toEventPayload(e,n){return{id:e.instance.id,annotation:e.instance,originalEvent:n}}emit(e,n){this.engine.events?.trigger?.(e,n)}}class ww{constructor(e){this.engine=e}static svgNamespace="http://www.w3.org/2000/svg";static sourceColor="#00bcd4";static targetColor="#ff9800";matrices=new Map;pointCalibrationUrl=null;pointCalibrationPoints=[];behavior;type="point-calibration";apply(e){if(!e?.url||e.matrix==null)return!1;const n=this.toThreeMatrix(e.matrix),i=FE(this.engine,e.url);return i.matrixAutoUpdate=!1,i.matrix.copy(n),i.matrixWorldNeedsUpdate=!0,i.updateMatrixWorld(!0),this.clearRuntimeWorldBoxCache(i),this.engine.octreeBox?.invalidateModelWorldCache?.(e.url),this.matrices.set(e.url,n.clone()),this.updateCachedModelBox(e.url,i),this.engine.modelEdge?.setModelEdgeTransform?.(e.url,n),this.engine.requestComposerRender?.(),!0}setCalibration(e){return this.apply(e)}alignBySegments(e){if(!e?.url||e.source==null||e.target==null)return!1;const n=this.toVector3(e.source.start),i=this.toVector3(e.source.end),r=this.toVector3(e.target.start),s=this.toVector3(e.target.end),o=i.clone().sub(n),a=s.clone().sub(r);if(o.lengthSq()<1e-10||a.lengthSq()<1e-10)throw new Error("[Calibration] source and target segments must have valid length");o.normalize(),a.normalize();const c=new xt().makeRotationFromQuaternion(new ni().setFromUnitVectors(o,a)),l=new xt().makeTranslation(r.x,r.y,r.z).multiply(c).multiply(new xt().makeTranslation(-n.x,-n.y,-n.z)),u=this.getMatrix(e.url);return this.apply({url:e.url,matrix:l.multiply(u)})}startPointCalibration(e){return!e?.url||(this.behavior=this.engine.handelBehaved,!this.behavior?.init||!this.behavior?.active||!this.behavior?.disActive)?!1:(this.pointCalibrationUrl=e.url,this.pointCalibrationPoints=[],this.engine.setIdleFrameRateExempt?.("point-calibration",!0),this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1,!0)}handleMouseClick(e){const n=e?.catch?.point;if(!(n instanceof H)||this.pointCalibrationUrl==null)return;if(this.pointCalibrationPoints.push(n.clone()),this.pointCalibrationPoints.length!==4){this.drawPointCalibrationOverlay(n);return}const[i,r,s,o]=this.pointCalibrationPoints;try{this.alignBySegments({url:this.pointCalibrationUrl,source:{start:i,end:r},target:{start:s,end:o}})}catch(a){console.warn("四点模型校准失败:",a)}this.finishPointCalibration()}handleMouseMove(e){const n=e?.catch?.point;this.drawPointCalibrationOverlay(n instanceof H?n:null)}handelKeyEscDown(){this.finishPointCalibration()}disActive(){this.engine.setIdleFrameRateExempt?.("point-calibration",!1),this.pointCalibrationPoints=[],this.pointCalibrationUrl=null,this.clearPointCalibrationOverlay(),this.behavior?.disActive()}finishPointCalibration(){this.disActive(),this.engine.interactionModule?.init?.(),this.engine.interactionModule?.active?.()}drawPointCalibrationOverlay(e){const n=this.engine.catchSvg;if(n==null)return;n.innerHTML="";const i=this.pointCalibrationPoints,r=i.slice(0,2),s=i.slice(2,4);this.drawCalibrationSegment(n,r,ww.sourceColor,i.length<2?e:null),this.drawCalibrationSegment(n,s,ww.targetColor,i.length>=2&&i.length<4?e:null)}drawCalibrationSegment(e,n,i,r){const s=n.map(a=>this.toSvgPoint(a)).filter(a=>a!=null),o=r==null?null:this.toSvgPoint(r);s.length===2&&this.appendSvgLine(e,s[0],s[1],i),s.length===1&&o!=null&&this.appendSvgLine(e,s[0],o,i,!0),s.forEach(a=>this.appendSvgPoint(e,a,i)),o!=null&&this.appendSvgPoint(e,o,i,!0)}toSvgPoint(e){const n=this.engine.worldToScreen?.worldToScreenIfVisible?.(e)??this.engine.worldToScreen?.worldToScreen?.(e);if(n==null||!Number.isFinite(n.x)||!Number.isFinite(n.y))return null;const i=this.engine.reactBoundingClientRect;return new Ye(n.x+(Number.isFinite(i?.left)?i.left:0),n.y+(Number.isFinite(i?.top)?i.top:0))}appendSvgLine(e,n,i,r,s=!1){const o=document.createElementNS(ww.svgNamespace,"line");o.setAttribute("x1",`${n.x}`),o.setAttribute("y1",`${n.y}`),o.setAttribute("x2",`${i.x}`),o.setAttribute("y2",`${i.y}`),o.setAttribute("stroke",r),o.setAttribute("stroke-width",s?"2":"3"),s&&o.setAttribute("stroke-dasharray","6 4"),e.appendChild(o)}appendSvgPoint(e,n,i,r=!1){const s=document.createElementNS(ww.svgNamespace,"circle");s.setAttribute("cx",`${n.x}`),s.setAttribute("cy",`${n.y}`),s.setAttribute("r",r?"6":"5"),s.setAttribute("fill",r?"transparent":i),s.setAttribute("fill-opacity",r?"0":"1"),s.setAttribute("stroke",i),s.setAttribute("stroke-width",r?"2":"1"),r&&s.setAttribute("stroke-dasharray","3 2"),e.appendChild(s)}clearPointCalibrationOverlay(){this.engine.catchSvg&&(this.engine.catchSvg.innerHTML="")}getMatrix(e){const n=this.matrices.get(e);if(n!=null)return n.clone();const i=$b(this.engine,e);return i==null?new xt:i.matrix.clone()}clear(e){const n=$b(this.engine,e);return n==null?!1:(n.matrixAutoUpdate=!1,n.matrix.identity(),n.matrixWorldNeedsUpdate=!0,n.updateMatrixWorld(!0),this.clearRuntimeWorldBoxCache(n),this.engine.octreeBox?.invalidateModelWorldCache?.(e),this.matrices.delete(e),this.updateCachedModelBox(e,n),this.engine.modelEdge?.setModelEdgeTransform?.(e,new xt),this.engine.requestComposerRender?.(),!0)}updateCachedModelBox(e,n){const i=this.engine.models?.find?.(s=>s.url===e);if(i?.boundingBox==null)return;i.localBoundingBox==null&&(i.localBoundingBox={min:i.boundingBox.min.clone(),max:i.boundingBox.max.clone()});const r=new Ln(i.localBoundingBox.min.clone(),i.localBoundingBox.max.clone());n.updateWorldMatrix(!0,!1),r.applyMatrix4(n.matrixWorld),i.boundingBox={min:r.min,max:r.max}}clearRuntimeWorldBoxCache(e){e.traverse(n=>{n?.box instanceof Ln&&delete n.box})}toThreeMatrix(e){if(e instanceof xt)return e.clone();if(Array.isArray(e)&&Array.isArray(e[0])){const i=e;if(i.length!==4||i.some(r=>!Array.isArray(r)||r.length!==4))throw new Error("[Calibration] matrix must be a 4x4 array");return new xt().set(i[0][0],i[0][1],i[0][2],i[0][3],i[1][0],i[1][1],i[1][2],i[1][3],i[2][0],i[2][1],i[2][2],i[2][3],i[3][0],i[3][1],i[3][2],i[3][3])}const n=Array.from(e);if(n.length!==16)throw new Error("[Calibration] matrix must contain 16 numbers");return new xt().fromArray(n)}toVector3(e){if(e instanceof H)return e.clone();if(Array.isArray(e)){if(e.length!==3)throw new Error("[Calibration] point array must contain 3 numbers");return new H(e[0],e[1],e[2])}return"x"in e?new H(e.x,e.y,e.z):new H(e.X,e.Y,e.Z)}}const FKe=.001,kKe=.65,UKe=1;class zKe{engine;loader=new Mj;modelList=new Map;modelTransforms=[];transformControl=null;transformHelper=null;selectedModelId=null;copiedModelData=null;editingEnabled=!1;isRestoring=!1;isUndoing=!1;isPasting=!1;pendingModelIds=new Set;bimHighlightDisabledBeforeEditing=null;selectionPointerDown=null;onPointerDown;onPointerUp;onKeyDown;constructor(e){this.engine=e,this.onPointerDown=this.handlePointerDown.bind(this),this.onPointerUp=this.handlePointerUp.bind(this),this.onKeyDown=this.handleKeyDown.bind(this),this.engine.renderer?.domElement?.addEventListener("pointerdown",this.onPointerDown),this.engine.renderer?.domElement?.addEventListener("pointerup",this.onPointerUp),window.addEventListener("keydown",this.onKeyDown),this.ensureTransformControl()}dispose(){this.engine.renderer?.domElement?.removeEventListener("pointerdown",this.onPointerDown),this.engine.renderer?.domElement?.removeEventListener("pointerup",this.onPointerUp),window.removeEventListener("keydown",this.onKeyDown),this.transformControl?.detach(),this.transformHelper?.parent?.remove(this.transformHelper),this.modelList.forEach(e=>this.removeObject(e.object)),this.modelList.clear(),this.modelTransforms.length=0,this.disableModelEditing()}update(){this.syncTransformControlCamera()}async placeModel(e){if(!e?.url)throw new Error("放置模型失败:url 不能为空。");const n=e.id??this.createId();if(this.modelList.has(n)||this.pendingModelIds.has(n))throw new Error(`放置模型失败:模型 id “${n}” 已存在。`);this.pendingModelIds.add(n);try{if(e.position){const i=this.normalizeData({...e,id:n,materials:[]});return this.saveHistory(),await this.loadRecord(i),this.editModel(n),this.cloneData(i)}return await this.placePreparedModel(this.normalizeData({...e,id:n,position:[0,0,0],materials:[]}))}finally{this.pendingModelIds.delete(n)}}async placePreparedModel(e){this.enableModelEditing(),this.clearSelection();const n=await this.createRecord(e);n.object.visible=!1,this.engine.scene?.add(n.object);try{const i=await this.pickPlacementPoint(r=>{n.object.visible=r!=null,r&&n.object.position.copy(r.position),this.requestRender()},()=>{n.object.rotateOnWorldAxis(new H(0,1,0),Math.PI/2),n.data.rotation=n.object.rotation.toArray(),this.requestRender()});n.data.position=i.position.toArray(),n.object.position.copy(i.position),n.object.visible=!0,this.saveHistory(),this.addRecord(n)}catch(i){throw this.removeObject(n.object),i}return this.editModel(e.id),this.cloneData(n.data)}editModel(e,n="translate"){const i=this.modelList.get(e);if(!i)throw new Error(`编辑模型失败:未找到模型 “${e}”。`);this.enableModelEditing(),this.selectedModelId=e,this.ensureTransformControl(),this.transformControl?.setMode(n),this.transformControl?.attach(i.object),this.transformHelper&&(this.transformHelper.visible=!0),this.engine.events?.trigger?.(eh.ModelPlaceSelected,{modelId:e,data:this.cloneData(i.data),object:i.object}),this.requestRender()}endEdit(){this.clearSelection(),this.disableModelEditing()}getSelectedModelId(){return this.selectedModelId}copySelectedModel(){this.syncSelectedTransform();const e=this.selectedModelId?this.modelList.get(this.selectedModelId):null;return e?(this.copiedModelData=this.cloneData(e.data),!0):!1}async pasteModel(){if(!this.copiedModelData||this.isPasting)return null;const e=this.createId();this.isPasting=!0,this.pendingModelIds.add(e);try{return await this.placePreparedModel(this.normalizeData({...this.cloneData(this.copiedModelData),id:e,position:[0,0,0]}))}finally{this.pendingModelIds.delete(e),this.isPasting=!1}}async replaceMaterial(e,n,i){const r=this.requireRecord(e);if(!i)throw new Error("替换材质失败:贴图 url 不能为空。");const s=this.getMaterials(r.object),o=this.getMaterialIndices(s,n);if(o.length===0){const a=typeof n=="number"?`槽位 ${n}`:`名称 “${n}”`;throw new Error(`替换材质失败:模型不存在材质${a}。`)}this.saveHistory(),await Promise.all(o.map(async a=>{const c=s[a],l=await new Bd().loadAsync(i);l.colorSpace=Xr,c.map=l,c.needsUpdate=!0;const u=r.data.materials.find(h=>h.materialIndex===a);u?(u.materialName=c.name||void 0,u.mapUrl=i):r.data.materials.push({materialIndex:a,materialName:c.name||void 0,mapUrl:i})})),this.requestRender()}getModelMaterials(e){return this.getMaterials(this.requireRecord(e).object).map((n,i)=>({materialIndex:i,materialName:n.name}))}deleteModel(e){const n=this.requireRecord(e);this.saveHistory(),this.removeObject(n.object),this.modelList.delete(e),this.selectedModelId===e&&this.clearSelection(),this.requestRender()}clearModels(){this.modelList.size!==0&&(this.saveHistory(),this.endEdit(),this.modelList.forEach(e=>this.removeObject(e.object)),this.modelList.clear(),this.requestRender())}hideModel(e){const n=this.requireRecord(e);this.saveHistory(),n.object.visible=!1,n.data.visible=!1,this.selectedModelId===e&&this.clearSelection(),this.requestRender()}showAllModels(){this.saveHistory(),this.modelList.forEach(e=>{e.object.visible=!0,e.data.visible=!0}),this.requestRender()}getSceneModels(){return this.syncSelectedTransform(),Array.from(this.modelList.values(),e=>this.cloneData(e.data))}async restoreSceneModels(e){if(!Array.isArray(e))throw new Error("还原场景失败:场景模型数据必须是数组。");this.isRestoring||this.saveHistory(),this.isRestoring=!0;try{this.endEdit(),this.modelList.forEach(n=>this.removeObject(n.object)),this.modelList.clear();for(const n of e)await this.loadRecord(this.normalizeData(n));return this.getSceneModels()}finally{this.isRestoring=!1,this.requestRender()}}async undo(){if(this.isUndoing)return!1;const e=this.modelTransforms.pop();if(!e)return!1;this.isUndoing=!0;try{return this.isRestoring=!0,await this.restoreSceneModels(e),!0}finally{this.isUndoing=!1}}async loadRecord(e){this.addRecord(await this.createRecord(e))}async createRecord(e){const i=(await this.loader.loadAsync(e.url)).scene;i.name=e.name,i.position.fromArray(e.position),i.rotation.fromArray(e.rotation),i.scale.fromArray(e.scale),i.visible=e.visible;const r={data:this.cloneData(e),object:i};for(const s of e.materials)s.mapUrl&&await this.applyTexture(r,s,s.mapUrl);return r}addRecord(e){e.object.userData.modelPlaceId=e.data.id,this.engine.scene?.add(e.object),this.modelList.set(e.data.id,e)}async applyTexture(e,n,i){const r=this.getMaterials(e.object),s=n.materialName?r.find(a=>a.name===n.materialName)??r[n.materialIndex]:r[n.materialIndex];if(!s)return;const o=await new Bd().loadAsync(i);o.colorSpace=Xr,s.map=o,s.needsUpdate=!0}ensureTransformControl(){if(this.transformControl){this.syncTransformControlCamera();return}!this.engine.camera||!this.engine.renderer||!this.engine.scene||(this.transformControl=new tN(this.engine.camera,this.engine.renderer.domElement),this.transformControl.addEventListener("dragging-changed",e=>{this.engine.controls&&(this.engine.controls.enabled=!e.value),e.value?this.saveHistory():this.syncSelectedTransform()}),this.transformControl.addEventListener("objectChange",()=>this.requestRender()),this.transformHelper=this.transformControl.getHelper(),this.transformHelper.visible=!1,this.engine.scene.add(this.transformHelper),this.syncTransformControlCamera())}syncTransformControlCamera(){!this.transformControl||!this.engine.camera||(this.transformControl.camera=this.engine.camera,this.transformControl.size=this.engine.camera.isPerspectiveCamera?kKe:UKe)}pickPlacementPoint(e,n){const i=this.engine.handelBehaved;return!i?.init||!i?.active||!i?.disActive?Promise.reject(new Error("放置模型失败:引擎捕捉交互尚未初始化。")):new Promise((r,s)=>{let o=!1;const a=l=>{o||(o=!0,i.disActive(),this.engine.catchSvg&&(this.engine.catchSvg.innerHTML=""),this.engine.interactionModule?.init?.(),this.engine.interactionModule?.active?.(),l())},c={type:"model-place",handleMouseMove:l=>e?.(this.getPlacementPoint(l?.catch)),handleMouseClick:l=>{const u=this.getPlacementPoint(l?.catch);u&&a(()=>r(u))},handelKeyEscDown:()=>{a(()=>s(new Error("已取消第三方模型放置。")))},handelKeySpaceDown:l=>{l.preventDefault(),n?.()},disActive:()=>{a(()=>s(new Error("第三方模型放置已被其他交互操作取消。")))}};i.init(c,{showCatch:!0}),i.active()})}getPlacementPoint(e){const n=e?.point;if(!(n instanceof H))return null;const i=n.clone(),r=e?.normal??e?.face?.normal;if(r==null)return{position:i,normal:null};const s=r.clone(),o=e?.matrix??e?.object?.matrixWorld;return o&&s.transformDirection(o),s.lengthSq()<1e-10?{position:i,normal:null}:(s.normalize(),i.addScaledVector(s,FKe),{position:i,normal:s})}handlePointerDown(e){if(!(!this.editingEnabled||!this.engine.camera||!this.engine.renderer)){if(this.transformControl?.axis!=null){this.selectionPointerDown=null;return}this.selectionPointerDown=new Ye(e.clientX,e.clientY)}}handlePointerUp(e){if(!this.editingEnabled||!this.engine.camera||!this.engine.renderer||!this.selectionPointerDown)return;const n=this.selectionPointerDown;if(this.selectionPointerDown=null,n.distanceTo(new Ye(e.clientX,e.clientY))>4)return;const i=this.engine.renderer.domElement.getBoundingClientRect(),r=new Ye((e.clientX-i.left)/i.width*2-1,-((e.clientY-i.top)/i.height)*2+1),s=new Da;s.setFromCamera(r,this.engine.camera);const o=s.intersectObjects(Array.from(this.modelList.values(),c=>c.object),!0)[0];if(!o){this.clearSelection();return}let a=o.object;for(;a&&!a.userData.modelPlaceId;)a=a.parent;a?.userData.modelPlaceId?this.editModel(a.userData.modelPlaceId):this.clearSelection()}handleKeyDown(e){if(this.isCopyShortcut(e)){e.preventDefault(),this.copySelectedModel();return}if(this.isPasteShortcut(e)){e.preventDefault(),this.pasteModel().catch(n=>console.error("第三方模型粘贴失败:",n));return}if(this.isDeleteShortcut(e)){e.preventDefault(),this.deleteModel(this.selectedModelId);return}if(this.isUndoShortcut(e)){e.preventDefault(),this.undo().catch(n=>console.error("第三方模型撤回失败:",n));return}if(this.isTransformModeShortcut(e)){e.preventDefault(),this.switchTransformMode(e.shiftKey?-1:1);return}(e.key==="Escape"||e.keyCode===27)&&this.editingEnabled&&this.selectedModelId&&this.clearSelection()}isUndoShortcut(e){return!e.ctrlKey&&!e.metaKey||e.shiftKey||e.altKey||e.key.toLowerCase()!=="z"||this.isTextInputTarget(e)?!1:this.modelTransforms.length>0&&!this.isUndoing}isCopyShortcut(e){return(e.ctrlKey||e.metaKey)&&!e.shiftKey&&!e.altKey&&e.key.toLowerCase()==="c"&&!this.isTextInputTarget(e)&&this.selectedModelId!=null}isPasteShortcut(e){return(e.ctrlKey||e.metaKey)&&!e.shiftKey&&!e.altKey&&e.key.toLowerCase()==="v"&&!this.isTextInputTarget(e)&&this.copiedModelData!=null&&!this.isPasting}isDeleteShortcut(e){return e.key==="Delete"&&!e.ctrlKey&&!e.metaKey&&!e.altKey&&!this.isTextInputTarget(e)&&this.selectedModelId!=null}isTextInputTarget(e){const n=e.target;return!!(n?.isContentEditable||["INPUT","TEXTAREA","SELECT"].includes(n?.tagName??""))}isTransformModeShortcut(e){return e.key!=="Tab"||e.ctrlKey||e.metaKey||e.altKey||this.isTextInputTarget(e)?!1:this.editingEnabled&&this.selectedModelId!=null&&this.transformHelper?.visible===!0}switchTransformMode(e){const n=["translate","rotate","scale"],i=this.transformControl?.mode,s=(Math.max(0,n.indexOf(i??"translate"))+e+n.length)%n.length;this.transformControl?.setMode(n[s]),this.requestRender()}clearSelection(){this.selectedModelId=null,this.transformControl?.detach(),this.transformHelper&&(this.transformHelper.visible=!1),this.requestRender()}enableModelEditing(){this.editingEnabled=!0,this.bimHighlightDisabledBeforeEditing==null&&(this.bimHighlightDisabledBeforeEditing=!!this.engine.engineStatus?.disableModelInteractionHighlight),this.engine.engineStatus&&(this.engine.engineStatus.disableModelInteractionHighlight=!0),this.engine.modelToolModule?.unhighlightAllModels?.(),this.engine.hoverHighLight?.clearHighlight?.(),this.engine.hoverHighLight?.showModelNameTag?.(null,null)}disableModelEditing(){this.editingEnabled=!1,this.selectionPointerDown=null,this.bimHighlightDisabledBeforeEditing!=null&&this.engine.engineStatus&&(this.engine.engineStatus.disableModelInteractionHighlight=this.bimHighlightDisabledBeforeEditing),this.bimHighlightDisabledBeforeEditing=null}syncSelectedTransform(){if(!this.selectedModelId)return;const e=this.modelList.get(this.selectedModelId);e&&(e.data.position=e.object.position.toArray(),e.data.rotation=e.object.rotation.toArray(),e.data.scale=e.object.scale.toArray())}saveHistory(){this.isRestoring||this.modelTransforms.push(this.getSceneModels())}requireRecord(e){const n=this.modelList.get(e);if(!n)throw new Error(`未找到模型 “${e}”。`);return n}getMaterials(e){const n=[];return e.traverse(i=>{if(!i.isMesh)return;(Array.isArray(i.material)?i.material:[i.material]).forEach(s=>{s&&!n.includes(s)&&n.push(s)})}),n}getMaterialIndices(e,n){return typeof n=="number"?Number.isInteger(n)&&n>=0&&n<e.length?[n]:[]:e.reduce((i,r,s)=>(r.name===n&&i.push(s),i),[])}normalizeData(e){return{id:e.id??this.createId(),url:e.url,name:e.name??"第三方模型",position:e.position??[0,0,0],rotation:e.rotation??[0,0,0,"XYZ"],scale:e.scale??[1,1,1],visible:e.visible??!0,materials:e.materials??[]}}cloneData(e){return JSON.parse(JSON.stringify(e))}createId(){return`model-place-${Date.now()}-${Math.random().toString(36).slice(2,9)}`}removeObject(e){e.parent?.remove(e),e.traverse(n=>{n.geometry?.dispose?.(),(Array.isArray(n.material)?n.material:[n.material]).forEach(i=>{i?.map?.dispose?.(),i?.dispose?.()})})}requestRender(){this.engine.requestComposerRender?.()}}const yg={version:"3.11.8"}.version;function XH(){const t=globalThis.crypto?.subtle;if(!t)throw new Error("[BimEngine] Web Crypto API is required for secure sdkAuth credentials mode");return t}function zM(t){return new TextEncoder().encode(t)}function VM(t){return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}function jue(t){let e="";return t.forEach(n=>{e+=String.fromCharCode(n)}),btoa(e)}function VKe(t){const e=t.getUTCFullYear(),n=String(t.getUTCMonth()+1).padStart(2,"0"),i=String(t.getUTCDate()).padStart(2,"0");return`${e}${n}${i}`}async function jKe(t){const e=await XH().digest("SHA-256",VM(zM(t)));return Array.from(new Uint8Array(e)).map(n=>n.toString(16).padStart(2,"0")).join("")}async function HKe(t,e){const n=XH(),i=await n.importKey("raw",VM(t),{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return n.sign("HMAC",i,VM(zM(e)))}function GKe(t){return zM([t.appId,t.engineType,t.requestDate,String(t.timestamp),t.nonce].join("|"))}async function qKe(t){const e=XH(),n=new Date,i=n.getTime(),r=VKe(n),s=globalThis.crypto.randomUUID(),o=globalThis.crypto.getRandomValues(new Uint8Array(12)),a=await jKe(t.appSecret),c=await HKe(zM(a),r),l=await e.importKey("raw",c,"AES-GCM",!1,["encrypt"]),u=JSON.stringify({appKey:t.appKey,appSecret:t.appSecret}),h=await e.encrypt({name:"AES-GCM",iv:o,additionalData:VM(GKe({appId:t.appId,engineType:t.engineType,requestDate:r,timestamp:i,nonce:s})),tagLength:128},l,VM(zM(u)));return{appId:t.appId,engineType:t.engineType,requestDate:r,timestamp:i,nonce:s,iv:jue(o),cipherText:jue(new Uint8Array(h)),sdkVersion:t.sdkVersion,origin:t.origin,product:t.product}}const $H=new Map;function bF(t){return t.replace(/\/+$/,"")}function vF(t){if(t)return t;if(typeof window<"u"&&typeof window.location?.origin=="string")return window.location.origin}function WKe(t,e){return JSON.stringify({endpoint:bF(t.endpoint),token:t.token??"",appId:t.appId??"",appKey:t.appKey??"",appSecret:t.appSecret??"",origin:vF(t.origin)??"",product:t.product??"",engineType:e,sdkVersion:yg})}async function QH(t,e,n){const i=typeof AbortController<"u"?new AbortController:void 0,r=i?setTimeout(()=>i.abort(),n):void 0;try{const s=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:i?.signal}),o=await s.json().catch(()=>({}));if(!s.ok){const a=o?.error?.message??o?.message??`SDK authentication failed with status ${s.status}`;throw new Error(a)}return o}finally{r!=null&&clearTimeout(r)}}async function YKe(t,e){const n=await QH(`${bF(t.endpoint)}/oauth/sdk-verify`,{sdkToken:t.token,engineType:e,sdkVersion:yg,origin:vF(t.origin),product:t.product},t.timeoutMs??8e3);return n.sdkToken=t.token,n}async function XKe(t,e){const n=await qKe({appId:t.appId,appKey:t.appKey,appSecret:t.appSecret,engineType:e,sdkVersion:yg,origin:vF(t.origin),product:t.product}),i=await QH(`${bF(t.endpoint)}/oauth/sdk-token/secure`,n,t.timeoutMs??8e3),r=await QH(`${bF(t.endpoint)}/oauth/sdk-verify`,{sdkToken:i.sdkToken,engineType:e,sdkVersion:yg,origin:vF(t.origin),product:t.product},t.timeoutMs??8e3);return r.sdkToken=i.sdkToken,r}async function $Ke(t,e){const n=t?.sdkAuth;if(!n)return null;if(!n.endpoint)throw new Error("[BimEngine] sdkAuth.endpoint is required");if(!n.token&&!(n.appId&&n.appKey&&n.appSecret))return null;const i=WKe(n,e),r=$H.get(i);if(r){const o=await r;return t&&(t.__sdkAuthSession=o),o}const s=(n.token?YKe(n,e):XKe(n,e)).then(o=>{if(o.authorized!==!0)throw new Error("[BimEngine] SDK authorization rejected");return t&&(t.__sdkAuthSession=o),o}).catch(o=>{throw $H.delete(i),o});return $H.set(i,s),s}var KH,Hue;function mr(){return Hue||(Hue=1,KH={options:{usePureJavaScript:!1}}),KH}var JH={exports:{}},ZH,Gue;function QKe(){if(Gue)return ZH;Gue=1;var t={};ZH=t;var e={};t.encode=function(i,r,s){if(typeof r!="string")throw new TypeError('"alphabet" must be a string.');if(s!==void 0&&typeof s!="number")throw new TypeError('"maxline" must be a number.');var o="";if(!(i instanceof Uint8Array))o=n(i,r);else{var a=0,c=r.length,l=r.charAt(0),u=[0];for(a=0;a<i.length;++a){for(var h=0,d=i[a];h<u.length;++h)d+=u[h]<<8,u[h]=d%c,d=d/c|0;for(;d>0;)u.push(d%c),d=d/c|0}for(a=0;i[a]===0&&a<i.length-1;++a)o+=l;for(a=u.length-1;a>=0;--a)o+=r[u[a]]}if(s){var p=new RegExp(".{1,"+s+"}","g");o=o.match(p).join(`\r
|
|
6015
|
+
`});return h.clippingPlanes=this.engine.sectionPlane,n.alwaysOnTop&&(h.depthTest=!1),h}createPulseMaterial(e,n,i,r,s,o,a){return this.createSurfaceMaterial({color:`#${e.getHexString()}`,opacity:n,style:i,effect:{...r,pulse:r.pulse?.enabled?r.pulse:{enabled:!0,speed:1.4,minOpacity:.55,maxOpacity:1}},axisMode:s,axisMin:o,axisMax:a})}axisModeToNumber(e){return e==="x"?0:e==="y"?1:e==="z"?2:e==="uvx"?3:4}getGradientStops(e,n){if(!Array.isArray(n)||n.length===0)return[{offset:0,color:e,alpha:1},{offset:1,color:e,alpha:.08}];const i=[...n].sort((o,a)=>o.offset-a.offset),r=i[0],s=i[i.length-1];return[{offset:0,color:r.color,alpha:r.alpha??1},{offset:1,color:s.color,alpha:s.alpha??.08}]}}const UM={color:"#7ffcff",opacity:.92,fillColor:"#7ffcff",fillOpacity:.18,depthTest:!0,alwaysOnTop:!1,lineWidth:.18,point:{mode:"sprite",size:0,iconSize:32,billboard:!0,anchorY:0},line:{dashed:!1,closed:!1},polygon:{showEdge:!0,edgeColor:"#d9ffff",edgeWidth:1},volume:{height:10,showTop:!0,showSide:!0,showBottom:!1,edgeColor:"#d9ffff"}},IKe={background:"rgba(10, 18, 28, 0.92)",color:"#ffffff",border:"1px solid rgba(127, 252, 255, 0.72)",borderRadius:"10px",padding:"12px",boxShadow:"0 10px 30px rgba(0, 0, 0, 0.32)",minWidth:"120px",pointerEvents:"auto"},MKe="bim-engine-annotation3d-panels";class PKe{normalizeData(e){return{...e,id:e.id??`annotation3d-${Date.now()}-${Math.random().toString(16).slice(2)}`,points:_F(e.points??[]),visible:e.visible??!0,selectable:e.selectable??!0,style:this.mergeStyle(e.style),effect:this.mergeEffect(e.effect),panel:e.panel?this.normalizePanel(e.panel):void 0}}mergeData(e,n,i,r){const s=i.panel===void 0?e.panel?{...e.panel,actions:n}:void 0:i.panel==null?void 0:{...e.panel,...i.panel,style:{...e.panel?.style??{},...i.panel.style??{}},actions:i.panel.actions??n};return this.normalizeData({id:r,type:i.type??e.type,points:i.points?_F(i.points):_F(e.points),visible:i.visible??e.visible,selectable:i.selectable??e.selectable,style:{...e.style,...i.style??{},point:{...e.style.point??{},...i.style?.point??{}},line:{...e.style.line??{},...i.style?.line??{}},polygon:{...e.style.polygon??{},...i.style?.polygon??{}},volume:{...e.style.volume??{},...i.style?.volume??{}}},effect:{...e.effect,...i.effect??{}},panel:s,data:i.data??e.data})}mergeStyle(e){return{...UM,...e,point:{...UM.point,...e?.point??{}},line:{...UM.line,...e?.line??{}},polygon:{...UM.polygon,...e?.polygon??{}},volume:{...UM.volume,...e?.volume??{}}}}mergeEffect(e){return{...e,gradient:e?.gradient?{enabled:e.gradient.enabled,direction:e.gradient.direction??"vertical",stops:e.gradient.stops??[]}:void 0,glow:e?.glow?{...e.glow}:void 0,flow:e?.flow?{enabled:e.flow.enabled,speed:e.flow.speed??.6,width:e.flow.width??.18,direction:e.flow.direction??"forward"}:void 0,pulse:e?.pulse?{enabled:e.pulse.enabled,speed:e.pulse.speed??1.4,minOpacity:e.pulse.minOpacity??.55,maxOpacity:e.pulse.maxOpacity??1}:void 0,ripple:e?.ripple?{enabled:e.ripple.enabled,count:e.ripple.count??2,speed:e.ripple.speed??.9,maxRadius:e.ripple.maxRadius??12}:void 0,pillar:e?.pillar?{enabled:e.pillar.enabled,height:e.pillar.height??16,width:e.pillar.width??1.5}:void 0,baseRing:e?.baseRing?{enabled:e.baseRing.enabled,radius:e.baseRing.radius??3,rotateSpeed:e.baseRing.rotateSpeed??.8}:void 0,layers:e?.layers?{enabled:e.layers.enabled,count:e.layers.count??3,offsetY:e.layers.offsetY??3}:void 0,scan:e?.scan?{enabled:e.scan.enabled,speed:e.scan.speed??.8,width:e.scan.width??.18}:void 0}}normalizePanel(e){return{visible:e.visible??!0,trigger:e.trigger??"manual",mode:e.mode??(e.html?"html":"text"),text:e.text??"",html:e.html??"",anchor:e.anchor,offset:{...e.offset??{}},screenOffset:{...e.screenOffset??{}},className:e.className,style:{...IKe,...e.style??{}},interactive:e.interactive??!0,occlusion:e.occlusion??"show",actions:e.actions}}}function DKe(t,e,n){const i=t.camera;if(!i)return!1;const r=n.clone().sub(i.position),s=r.length();if(s<=1e-6)return!1;e.set(i.position,r.normalize());let o=t.octreeBox?.rayInterationModel?.(e,!0,!1)??[];o=t.clipping?.filterIntersectionsByClipping?.(o)??o;const a=o.sort((c,l)=>c.distance-l.distance)[0];return!!(a&&a.distance<s-.05)}class RKe{constructor(e,n){this.engine=e,this.isAnchorOccluded=n,this.container=document.createElement("div"),this.container.className=MKe,this.container.style.cssText=["position:absolute","left:0","top:0","width:100%","height:100%","pointer-events:none","overflow:hidden","z-index:1250"].join(";"),this.engine.container.appendChild(this.container),this.worldToScreen=new ua(this.engine.camera,this.engine.renderer,this.engine.scene)}container;worldToScreen;updateProjectionState(){this.worldToScreen.updateCamera(this.engine.camera),this.worldToScreen.updateRenderer(this.engine.renderer),this.worldToScreen.updateScene(this.engine.scene)}createPanelElement(e,n){const i=document.createElement("div");return i.className=`bim-annotation3d-panel ${n.className??""}`.trim(),i.dataset.annotationId=e.id,i.style.cssText=["position:absolute","left:0","top:0","transform:translate(-50%, -100%)","display:none",n.interactive===!1?"pointer-events:none":"pointer-events:auto"].join(";"),n.mode==="html"?i.innerHTML=n.html??"":i.textContent=n.text??"",Object.entries(n.style??{}).forEach(([r,s])=>{i.style.setProperty(CKe(r),s)}),i}updateRecord(e){if(!e.panelElement||!e.instance.panel)return;const n=e.instance.panel;if(!(n.visible!==!1&&this.shouldShowPanel(e))||!e.instance.visible){e.panelElement.style.display="none";return}const r=this.getPanelAnchorPoint(e),s=this.worldToScreen.worldToScreenIfVisible(r);if(!s){e.panelElement.style.display="none";return}if(n.occlusion==="hide"&&this.isAnchorOccluded(r)){e.panelElement.style.display="none";return}const o=n.screenOffset??{};e.panelElement.style.display="block",e.panelElement.style.left=`${s.x+(o.x??0)}px`,e.panelElement.style.top=`${s.y+(o.y??0)}px`}dispose(){this.container.remove()}shouldShowPanel(e){const n=e.instance.panel?.trigger??"manual";return n==="always"?!0:n==="hover"?e.instance.hovered:n==="click"||n==="manual"?e.instance.panelVisible:!1}getPanelAnchorPoint(e){const n=e.instance.panel?.anchor??EKe(e.instance.type),i=e.instance.panel?.offset??{};let r=new H;if(e.instance.type==="point")r.copy(Hh(e.instance.points[0])),n==="top"&&(r.y+=e.volumeHeight??e.instance.style.point?.anchorY??0);else if(e.instance.type==="polyline")n==="start"?r.copy(Hh(e.instance.points[0])):n==="end"?r.copy(Hh(e.instance.points[e.instance.points.length-1])):e.anchorCurve?r.copy(e.anchorCurve.getPoint(.5)):r.copy(AF(e.instance.points));else if(e.instance.type==="polygon")r.copy(AF(e.instance.points));else if(e.instance.type==="extrudePolygon")r.copy(AF(e.instance.points)),n==="top"&&e.anchorNormal&&r.add(e.anchorNormal.clone().multiplyScalar(e.volumeHeight??0));else if(e.instance.type==="box"&&(r.copy(AF(e.instance.points)),n==="top"&&e.instance.points.length>=2)){const s=Hh(e.instance.points[0]),o=Hh(e.instance.points[1]);r.y=Math.max(s.y,o.y)}return r.add(new H(i.x??0,i.y??0,i.z??0)),r}}class OKe{engine;rootGroup;records;panelContainer;onRecordVisualChange;onEmit;raycaster=new Da;hoveredId=null;constructor(e){this.engine=e.engine,this.rootGroup=e.rootGroup,this.records=e.records,this.panelContainer=e.panelContainer,this.onRecordVisualChange=e.onRecordVisualChange,this.onEmit=e.onEmit}bind(){this.engine.renderer?.domElement?.addEventListener?.("click",this.handleCanvasClick,!1),this.engine.renderer?.domElement?.addEventListener?.("mousemove",this.handleCanvasMove,!1),this.engine.renderer?.domElement?.addEventListener?.("mouseleave",this.handleCanvasLeave,!1),this.panelContainer.addEventListener("click",this.handlePanelClick,!1)}unbind(){this.engine.renderer?.domElement?.removeEventListener?.("click",this.handleCanvasClick,!1),this.engine.renderer?.domElement?.removeEventListener?.("mousemove",this.handleCanvasMove,!1),this.engine.renderer?.domElement?.removeEventListener?.("mouseleave",this.handleCanvasLeave,!1),this.panelContainer.removeEventListener("click",this.handlePanelClick,!1)}handleRecordRemoved(e){this.hoveredId===e&&(this.hoveredId=null)}pickAnnotation(e){const n=this.engine.renderer?.domElement,i=this.engine.camera;if(!n||!i)return null;const r=n.getBoundingClientRect(),s=e.clientX-r.left,o=e.clientY-r.top,a=new Ye(s/r.width*2-1,-(o/r.height)*2+1);this.raycaster.setFromCamera(a,i);const c=this.raycaster.intersectObjects(this.rootGroup.children,!0);for(const l of c){let u=l.object;for(;u;){const h=u.userData?.annotationId;if(h&&this.records.has(h)){const d=this.records.get(h);return d.instance.selectable!==!1&&d.instance.visible?d:null}u=u.parent}}return null}handleCanvasClick=e=>{const n=this.pickAnnotation(e);n&&(n.instance.panel?.trigger==="click"&&(n.instance.panelVisible=!n.instance.panelVisible,this.onRecordVisualChange(n),this.onEmit(n.instance.panelVisible?"annotation3d-panel-open":"annotation3d-panel-close",this.toEventPayload(n,e))),this.onEmit("annotation3d-click",this.toEventPayload(n,e)))};handleCanvasMove=e=>{const n=this.pickAnnotation(e),i=n?.instance.id??null;if(i!==this.hoveredId){if(this.hoveredId&&this.records.has(this.hoveredId)){const r=this.records.get(this.hoveredId);r.instance.hovered=!1,this.onRecordVisualChange(r),this.onEmit("annotation3d-leave",this.toEventPayload(r,e))}this.hoveredId=i,n&&(n.instance.hovered=!0,this.onRecordVisualChange(n),this.onEmit("annotation3d-hover",this.toEventPayload(n,e)))}};handleCanvasLeave=e=>{if(!this.hoveredId||!this.records.has(this.hoveredId)){this.hoveredId=null;return}const n=this.records.get(this.hoveredId);n.instance.hovered=!1,this.onRecordVisualChange(n),this.onEmit("annotation3d-leave",this.toEventPayload(n,e)),this.hoveredId=null};handlePanelClick=e=>{const n=e.target;if(!n)return;const i=n.closest("[data-annotation-id]");if(!i)return;const r=i.dataset.annotationId;if(!r||!this.records.has(r))return;const s=this.records.get(r);this.onEmit("annotation3d-panel-click",this.toEventPayload(s,e));const o=n.closest("[data-action]"),a=o?.dataset?.action;if(!a||!s.actions?.[a])return;const c={engine:this.engine,id:r,annotation:s.instance,action:a,element:o,originalEvent:e};s.actions[a]?.(c),this.onEmit("annotation3d-action",{...this.toEventPayload(s,e),action:a,target:o})};toEventPayload(e,n){return{id:e.instance.id,annotation:e.instance,originalEvent:n}}}function LKe(t){const{actions:e,...n}=t;return n}function BKe(t){return{id:t.instance.id,type:t.instance.type,points:_F(t.instance.points),visible:t.instance.visible,selectable:t.instance.selectable,style:yF(t.instance.style),effect:yF(t.instance.effect),panel:t.instance.panel?yF(t.instance.panel):void 0,data:yF(t.instance.data)}}function yF(t){return t===void 0?t:JSON.parse(JSON.stringify(t))}class NKe{engine;rootGroup;records=new Map;textureLoader=new Bd;occlusionRaycaster=new Da;normalizer=new PKe;materialFactory;geometryBuilder;effectsController;panelLayer;interaction;currentTime=0;constructor(e){this.engine=e,this.rootGroup=new $r,this.rootGroup.name="Annotation3dRoot",this.engine.scene.add(this.rootGroup),this.materialFactory=new SKe(this.engine),this.geometryBuilder=new wKe(this.engine,this.textureLoader,this.materialFactory),this.effectsController=new TKe(this.engine),this.panelLayer=new RKe(this.engine,n=>DKe(this.engine,this.occlusionRaycaster,n)),this.interaction=new OKe({engine:this.engine,rootGroup:this.rootGroup,records:this.records,panelContainer:this.panelLayer.container,onRecordVisualChange:n=>this.panelLayer.updateRecord(n),onEmit:(n,i)=>this.emit(n,i)}),this.interaction.bind()}add(e){const n=this.normalizer.normalizeData(e),i=this.buildRecord(n);return this.attachRecord(i),this.emit("annotation3d-created",this.toEventPayload(i)),n.id}addMany(e){return e.map(n=>this.add(n))}async pickPoint(){if(typeof this.engine.label?.pickPoint!="function")return null;const e=await this.engine.label.pickPoint();return e==null?null:{x:e.x,y:e.y,z:e.z}}update(e,n){const i=this.records.get(e);if(!i)return!1;const r=this.normalizer.mergeData(i.instance,i.actions,n,e);this.removeInternal(e,!1);const s=this.buildRecord(r);return this.attachRecord(s),this.emit("annotation3d-updated",this.toEventPayload(s)),!0}remove(e){return this.removeInternal(e,!0)}clear(){Array.from(this.records.keys()).forEach(e=>this.removeInternal(e,!1))}get(e){return this.records.get(e)?.instance}getAll(){return Array.from(this.records.values()).map(e=>e.instance)}show(e){return this.setVisible(e,!0)}hide(e){return this.setVisible(e,!1)}setVisible(e,n){const i=this.records.get(e);return i?(i.instance.visible=n,this.applyVisibility(i),!0):!1}showPanel(e){const n=this.records.get(e);return!n||!n.instance.panel?!1:(n.instance.panelVisible=!0,this.panelLayer.updateRecord(n),this.emit("annotation3d-panel-open",this.toEventPayload(n)),!0)}hidePanel(e){const n=this.records.get(e);return!n||!n.instance.panel?!1:(n.instance.panelVisible=!1,this.panelLayer.updateRecord(n),this.emit("annotation3d-panel-close",this.toEventPayload(n)),!0)}togglePanel(e){const n=this.records.get(e);return!n||!n.instance.panel?!1:n.instance.panelVisible?this.hidePanel(e):this.showPanel(e)}updatePanel(e,n){const i=this.records.get(e);if(!i||!i.instance.panel)return!1;const r={...i.instance.panel,...n,style:{...i.instance.panel.style??{},...n.style??{}},actions:n.actions??i.actions};return this.update(e,{panel:r})}getData(){return Array.from(this.records.values()).map(e=>BKe(e))}restoreData(e){this.clear(),e.forEach(n=>this.add(n))}updateFrame(e=1/60){this.currentTime+=e,this.panelLayer.updateProjectionState(),this.records.forEach(n=>{this.effectsController.updateRecord(n,this.currentTime),this.panelLayer.updateRecord(n)})}dispose(){this.interaction.unbind(),this.clear(),this.rootGroup.removeFromParent(),this.panelLayer.dispose()}buildRecord(e){const n=new $r;n.name=e.id;const i={id:e.id,type:e.type,points:e.points,visible:e.visible??!0,selectable:e.selectable??!0,style:e.style,effect:e.effect??{},panel:e.panel?LKe(e.panel):void 0,data:e.data,panelVisible:e.panel?.trigger==="always",hovered:!1,root:n},r={instance:i,actions:e.panel?.actions,panelElement:e.panel?this.panelLayer.createPanelElement(i,e.panel):null,timeSeed:Math.random()*Math.PI*2,pulseMaterials:[],rippleMeshes:[],baseRingMeshes:[],animatedMaterials:[]};return this.geometryBuilder.build(r),vKe(n,i.id),r}attachRecord(e){this.records.set(e.instance.id,e),this.rootGroup.add(e.instance.root),e.panelElement&&this.panelLayer.container.appendChild(e.panelElement),this.applyVisibility(e)}removeInternal(e,n){const i=this.records.get(e);return i?(this.interaction.handleRecordRemoved(e),xKe(i.instance.root),i.instance.root.removeFromParent(),i.panelElement?.remove(),this.records.delete(e),n&&this.emit("annotation3d-removed",{id:e}),!0):!1}applyVisibility(e){e.instance.root.visible=e.instance.visible,e.instance.style.alwaysOnTop&&e.instance.root.traverse(n=>{n.renderOrder=Math.max(n.renderOrder,1200)}),this.panelLayer.updateRecord(e)}toEventPayload(e,n){return{id:e.instance.id,annotation:e.instance,originalEvent:n}}emit(e,n){this.engine.events?.trigger?.(e,n)}}class ww{constructor(e){this.engine=e}static svgNamespace="http://www.w3.org/2000/svg";static sourceColor="#00bcd4";static targetColor="#ff9800";matrices=new Map;pointCalibrationUrl=null;pointCalibrationPoints=[];behavior;type="point-calibration";apply(e){if(!e?.url||e.matrix==null)return!1;const n=this.toThreeMatrix(e.matrix),i=FE(this.engine,e.url);return i.matrixAutoUpdate=!1,i.matrix.copy(n),i.matrixWorldNeedsUpdate=!0,i.updateMatrixWorld(!0),this.clearRuntimeWorldBoxCache(i),this.engine.octreeBox?.invalidateModelWorldCache?.(e.url),this.matrices.set(e.url,n.clone()),this.updateCachedModelBox(e.url,i),this.engine.modelEdge?.setModelEdgeTransform?.(e.url,n),this.engine.requestComposerRender?.(),!0}setCalibration(e){return this.apply(e)}alignBySegments(e){if(!e?.url||e.source==null||e.target==null)return!1;const n=this.toVector3(e.source.start),i=this.toVector3(e.source.end),r=this.toVector3(e.target.start),s=this.toVector3(e.target.end),o=i.clone().sub(n),a=s.clone().sub(r);if(o.lengthSq()<1e-10||a.lengthSq()<1e-10)throw new Error("[Calibration] source and target segments must have valid length");o.normalize(),a.normalize();const c=new xt().makeRotationFromQuaternion(new ni().setFromUnitVectors(o,a)),l=new xt().makeTranslation(r.x,r.y,r.z).multiply(c).multiply(new xt().makeTranslation(-n.x,-n.y,-n.z)),u=this.getMatrix(e.url);return this.apply({url:e.url,matrix:l.multiply(u)})}startPointCalibration(e){return!e?.url||(this.behavior=this.engine.handelBehaved,!this.behavior?.init||!this.behavior?.active||!this.behavior?.disActive)?!1:(this.pointCalibrationUrl=e.url,this.pointCalibrationPoints=[],this.engine.setIdleFrameRateExempt?.("point-calibration",!0),this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1,!0)}handleMouseClick(e){const n=e?.catch?.point;if(!(n instanceof H)||this.pointCalibrationUrl==null)return;if(this.pointCalibrationPoints.push(n.clone()),this.pointCalibrationPoints.length!==4){this.drawPointCalibrationOverlay(n);return}const[i,r,s,o]=this.pointCalibrationPoints;try{this.alignBySegments({url:this.pointCalibrationUrl,source:{start:i,end:r},target:{start:s,end:o}})}catch(a){console.warn("四点模型校准失败:",a)}this.finishPointCalibration()}handleMouseMove(e){const n=e?.catch?.point;this.drawPointCalibrationOverlay(n instanceof H?n:null)}handelKeyEscDown(){this.finishPointCalibration()}disActive(){this.engine.setIdleFrameRateExempt?.("point-calibration",!1),this.pointCalibrationPoints=[],this.pointCalibrationUrl=null,this.clearPointCalibrationOverlay(),this.behavior?.disActive()}finishPointCalibration(){this.disActive(),this.engine.interactionModule?.init?.(),this.engine.interactionModule?.active?.()}drawPointCalibrationOverlay(e){const n=this.engine.catchSvg;if(n==null)return;n.innerHTML="";const i=this.pointCalibrationPoints,r=i.slice(0,2),s=i.slice(2,4);this.drawCalibrationSegment(n,r,ww.sourceColor,i.length<2?e:null),this.drawCalibrationSegment(n,s,ww.targetColor,i.length>=2&&i.length<4?e:null)}drawCalibrationSegment(e,n,i,r){const s=n.map(a=>this.toSvgPoint(a)).filter(a=>a!=null),o=r==null?null:this.toSvgPoint(r);s.length===2&&this.appendSvgLine(e,s[0],s[1],i),s.length===1&&o!=null&&this.appendSvgLine(e,s[0],o,i,!0),s.forEach(a=>this.appendSvgPoint(e,a,i)),o!=null&&this.appendSvgPoint(e,o,i,!0)}toSvgPoint(e){const n=this.engine.worldToScreen?.worldToScreenIfVisible?.(e)??this.engine.worldToScreen?.worldToScreen?.(e);if(n==null||!Number.isFinite(n.x)||!Number.isFinite(n.y))return null;const i=this.engine.reactBoundingClientRect;return new Ye(n.x+(Number.isFinite(i?.left)?i.left:0),n.y+(Number.isFinite(i?.top)?i.top:0))}appendSvgLine(e,n,i,r,s=!1){const o=document.createElementNS(ww.svgNamespace,"line");o.setAttribute("x1",`${n.x}`),o.setAttribute("y1",`${n.y}`),o.setAttribute("x2",`${i.x}`),o.setAttribute("y2",`${i.y}`),o.setAttribute("stroke",r),o.setAttribute("stroke-width",s?"2":"3"),s&&o.setAttribute("stroke-dasharray","6 4"),e.appendChild(o)}appendSvgPoint(e,n,i,r=!1){const s=document.createElementNS(ww.svgNamespace,"circle");s.setAttribute("cx",`${n.x}`),s.setAttribute("cy",`${n.y}`),s.setAttribute("r",r?"6":"5"),s.setAttribute("fill",r?"transparent":i),s.setAttribute("fill-opacity",r?"0":"1"),s.setAttribute("stroke",i),s.setAttribute("stroke-width",r?"2":"1"),r&&s.setAttribute("stroke-dasharray","3 2"),e.appendChild(s)}clearPointCalibrationOverlay(){this.engine.catchSvg&&(this.engine.catchSvg.innerHTML="")}getMatrix(e){const n=this.matrices.get(e);if(n!=null)return n.clone();const i=$b(this.engine,e);return i==null?new xt:i.matrix.clone()}clear(e){const n=$b(this.engine,e);return n==null?!1:(n.matrixAutoUpdate=!1,n.matrix.identity(),n.matrixWorldNeedsUpdate=!0,n.updateMatrixWorld(!0),this.clearRuntimeWorldBoxCache(n),this.engine.octreeBox?.invalidateModelWorldCache?.(e),this.matrices.delete(e),this.updateCachedModelBox(e,n),this.engine.modelEdge?.setModelEdgeTransform?.(e,new xt),this.engine.requestComposerRender?.(),!0)}updateCachedModelBox(e,n){const i=this.engine.models?.find?.(s=>s.url===e);if(i?.boundingBox==null)return;i.localBoundingBox==null&&(i.localBoundingBox={min:i.boundingBox.min.clone(),max:i.boundingBox.max.clone()});const r=new Ln(i.localBoundingBox.min.clone(),i.localBoundingBox.max.clone());n.updateWorldMatrix(!0,!1),r.applyMatrix4(n.matrixWorld),i.boundingBox={min:r.min,max:r.max}}clearRuntimeWorldBoxCache(e){e.traverse(n=>{n?.box instanceof Ln&&delete n.box})}toThreeMatrix(e){if(e instanceof xt)return e.clone();if(Array.isArray(e)&&Array.isArray(e[0])){const i=e;if(i.length!==4||i.some(r=>!Array.isArray(r)||r.length!==4))throw new Error("[Calibration] matrix must be a 4x4 array");return new xt().set(i[0][0],i[0][1],i[0][2],i[0][3],i[1][0],i[1][1],i[1][2],i[1][3],i[2][0],i[2][1],i[2][2],i[2][3],i[3][0],i[3][1],i[3][2],i[3][3])}const n=Array.from(e);if(n.length!==16)throw new Error("[Calibration] matrix must contain 16 numbers");return new xt().fromArray(n)}toVector3(e){if(e instanceof H)return e.clone();if(Array.isArray(e)){if(e.length!==3)throw new Error("[Calibration] point array must contain 3 numbers");return new H(e[0],e[1],e[2])}return"x"in e?new H(e.x,e.y,e.z):new H(e.X,e.Y,e.Z)}}const FKe=.001,kKe=.65,UKe=1;class zKe{engine;loader=new Mj;modelList=new Map;modelTransforms=[];transformControl=null;transformHelper=null;selectedModelId=null;copiedModelData=null;editingEnabled=!1;isRestoring=!1;isUndoing=!1;isPasting=!1;pendingModelIds=new Set;bimHighlightDisabledBeforeEditing=null;selectionPointerDown=null;onPointerDown;onPointerUp;onKeyDown;constructor(e){this.engine=e,this.onPointerDown=this.handlePointerDown.bind(this),this.onPointerUp=this.handlePointerUp.bind(this),this.onKeyDown=this.handleKeyDown.bind(this),this.engine.renderer?.domElement?.addEventListener("pointerdown",this.onPointerDown),this.engine.renderer?.domElement?.addEventListener("pointerup",this.onPointerUp),window.addEventListener("keydown",this.onKeyDown),this.ensureTransformControl()}dispose(){this.engine.renderer?.domElement?.removeEventListener("pointerdown",this.onPointerDown),this.engine.renderer?.domElement?.removeEventListener("pointerup",this.onPointerUp),window.removeEventListener("keydown",this.onKeyDown),this.transformControl?.detach(),this.transformHelper?.parent?.remove(this.transformHelper),this.modelList.forEach(e=>this.removeObject(e.object)),this.modelList.clear(),this.modelTransforms.length=0,this.disableModelEditing()}update(){this.syncTransformControlCamera()}async placeModel(e){if(!e?.url)throw new Error("放置模型失败:url 不能为空。");const n=e.id??this.createId();if(this.modelList.has(n)||this.pendingModelIds.has(n))throw new Error(`放置模型失败:模型 id “${n}” 已存在。`);this.pendingModelIds.add(n);try{if(e.position){const i=this.normalizeData({...e,id:n,materials:[]});return this.saveHistory(),await this.loadRecord(i),this.editModel(n),this.cloneData(i)}return await this.placePreparedModel(this.normalizeData({...e,id:n,position:[0,0,0],materials:[]}))}finally{this.pendingModelIds.delete(n)}}async placePreparedModel(e){this.enableModelEditing(),this.clearSelection();const n=await this.createRecord(e);n.object.visible=!1,this.engine.scene?.add(n.object);try{const i=await this.pickPlacementPoint(r=>{n.object.visible=r!=null,r&&n.object.position.copy(r.position),this.requestRender()},()=>{n.object.rotateOnWorldAxis(new H(0,1,0),Math.PI/2),n.data.rotation=n.object.rotation.toArray(),this.requestRender()});n.data.position=i.position.toArray(),n.object.position.copy(i.position),n.object.visible=!0,this.saveHistory(),this.addRecord(n)}catch(i){throw this.removeObject(n.object),i}return this.editModel(e.id),this.cloneData(n.data)}editModel(e,n="translate"){const i=this.modelList.get(e);if(!i)throw new Error(`编辑模型失败:未找到模型 “${e}”。`);this.enableModelEditing(),this.selectedModelId=e,this.ensureTransformControl(),this.transformControl?.setMode(n),this.transformControl?.attach(i.object),this.transformHelper&&(this.transformHelper.visible=!0),this.engine.events?.trigger?.(eh.ModelPlaceSelected,{modelId:e,data:this.cloneData(i.data),object:i.object}),this.requestRender()}endEdit(){this.clearSelection(),this.disableModelEditing()}getSelectedModelId(){return this.selectedModelId}copySelectedModel(){this.syncSelectedTransform();const e=this.selectedModelId?this.modelList.get(this.selectedModelId):null;return e?(this.copiedModelData=this.cloneData(e.data),!0):!1}async pasteModel(){if(!this.copiedModelData||this.isPasting)return null;const e=this.createId();this.isPasting=!0,this.pendingModelIds.add(e);try{return await this.placePreparedModel(this.normalizeData({...this.cloneData(this.copiedModelData),id:e,position:[0,0,0]}))}finally{this.pendingModelIds.delete(e),this.isPasting=!1}}async replaceMaterial(e,n,i){const r=this.requireRecord(e);if(!i)throw new Error("替换材质失败:贴图 url 不能为空。");const s=this.getMaterials(r.object),o=this.getMaterialIndices(s,n);if(o.length===0){const a=typeof n=="number"?`槽位 ${n}`:`名称 “${n}”`;throw new Error(`替换材质失败:模型不存在材质${a}。`)}this.saveHistory(),await Promise.all(o.map(async a=>{const c=s[a],l=await new Bd().loadAsync(i);l.colorSpace=Xr,c.map=l,c.needsUpdate=!0;const u=r.data.materials.find(h=>h.materialIndex===a);u?(u.materialName=c.name||void 0,u.mapUrl=i):r.data.materials.push({materialIndex:a,materialName:c.name||void 0,mapUrl:i})})),this.requestRender()}getModelMaterials(e){return this.getMaterials(this.requireRecord(e).object).map((n,i)=>({materialIndex:i,materialName:n.name}))}deleteModel(e){const n=this.requireRecord(e);this.saveHistory(),this.removeObject(n.object),this.modelList.delete(e),this.selectedModelId===e&&this.clearSelection(),this.requestRender()}clearModels(){this.modelList.size!==0&&(this.saveHistory(),this.endEdit(),this.modelList.forEach(e=>this.removeObject(e.object)),this.modelList.clear(),this.requestRender())}hideModel(e){const n=this.requireRecord(e);this.saveHistory(),n.object.visible=!1,n.data.visible=!1,this.selectedModelId===e&&this.clearSelection(),this.requestRender()}showAllModels(){this.saveHistory(),this.modelList.forEach(e=>{e.object.visible=!0,e.data.visible=!0}),this.requestRender()}getSceneModels(){return this.syncSelectedTransform(),Array.from(this.modelList.values(),e=>this.cloneData(e.data))}async restoreSceneModels(e){if(!Array.isArray(e))throw new Error("还原场景失败:场景模型数据必须是数组。");this.isRestoring||this.saveHistory(),this.isRestoring=!0;try{this.endEdit(),this.modelList.forEach(n=>this.removeObject(n.object)),this.modelList.clear();for(const n of e)await this.loadRecord(this.normalizeData(n));return this.getSceneModels()}finally{this.isRestoring=!1,this.requestRender()}}async undo(){if(this.isUndoing)return!1;const e=this.modelTransforms.pop();if(!e)return!1;this.isUndoing=!0;try{return this.isRestoring=!0,await this.restoreSceneModels(e),!0}finally{this.isUndoing=!1}}async loadRecord(e){this.addRecord(await this.createRecord(e))}async createRecord(e){const i=(await this.loader.loadAsync(e.url)).scene;i.name=e.name,i.position.fromArray(e.position),i.rotation.fromArray(e.rotation),i.scale.fromArray(e.scale),i.visible=e.visible;const r={data:this.cloneData(e),object:i};for(const s of e.materials)s.mapUrl&&await this.applyTexture(r,s,s.mapUrl);return r}addRecord(e){e.object.userData.modelPlaceId=e.data.id,this.engine.scene?.add(e.object),this.modelList.set(e.data.id,e)}async applyTexture(e,n,i){const r=this.getMaterials(e.object),s=n.materialName?r.find(a=>a.name===n.materialName)??r[n.materialIndex]:r[n.materialIndex];if(!s)return;const o=await new Bd().loadAsync(i);o.colorSpace=Xr,s.map=o,s.needsUpdate=!0}ensureTransformControl(){if(this.transformControl){this.syncTransformControlCamera();return}!this.engine.camera||!this.engine.renderer||!this.engine.scene||(this.transformControl=new tN(this.engine.camera,this.engine.renderer.domElement),this.transformControl.addEventListener("dragging-changed",e=>{this.engine.controls&&(this.engine.controls.enabled=!e.value),e.value?this.saveHistory():this.syncSelectedTransform()}),this.transformControl.addEventListener("objectChange",()=>this.requestRender()),this.transformHelper=this.transformControl.getHelper(),this.transformHelper.visible=!1,this.engine.scene.add(this.transformHelper),this.syncTransformControlCamera())}syncTransformControlCamera(){!this.transformControl||!this.engine.camera||(this.transformControl.camera=this.engine.camera,this.transformControl.size=this.engine.camera.isPerspectiveCamera?kKe:UKe)}pickPlacementPoint(e,n){const i=this.engine.handelBehaved;return!i?.init||!i?.active||!i?.disActive?Promise.reject(new Error("放置模型失败:引擎捕捉交互尚未初始化。")):new Promise((r,s)=>{let o=!1;const a=l=>{o||(o=!0,i.disActive(),this.engine.catchSvg&&(this.engine.catchSvg.innerHTML=""),this.engine.interactionModule?.init?.(),this.engine.interactionModule?.active?.(),l())},c={type:"model-place",handleMouseMove:l=>e?.(this.getPlacementPoint(l?.catch)),handleMouseClick:l=>{const u=this.getPlacementPoint(l?.catch);u&&a(()=>r(u))},handelKeyEscDown:()=>{a(()=>s(new Error("已取消第三方模型放置。")))},handelKeySpaceDown:l=>{l.preventDefault(),n?.()},disActive:()=>{a(()=>s(new Error("第三方模型放置已被其他交互操作取消。")))}};i.init(c,{showCatch:!0}),i.active()})}getPlacementPoint(e){const n=e?.point;if(!(n instanceof H))return null;const i=n.clone(),r=e?.normal??e?.face?.normal;if(r==null)return{position:i,normal:null};const s=r.clone(),o=e?.matrix??e?.object?.matrixWorld;return o&&s.transformDirection(o),s.lengthSq()<1e-10?{position:i,normal:null}:(s.normalize(),i.addScaledVector(s,FKe),{position:i,normal:s})}handlePointerDown(e){if(!(!this.editingEnabled||!this.engine.camera||!this.engine.renderer)){if(this.transformControl?.axis!=null){this.selectionPointerDown=null;return}this.selectionPointerDown=new Ye(e.clientX,e.clientY)}}handlePointerUp(e){if(!this.editingEnabled||!this.engine.camera||!this.engine.renderer||!this.selectionPointerDown)return;const n=this.selectionPointerDown;if(this.selectionPointerDown=null,n.distanceTo(new Ye(e.clientX,e.clientY))>4)return;const i=this.engine.renderer.domElement.getBoundingClientRect(),r=new Ye((e.clientX-i.left)/i.width*2-1,-((e.clientY-i.top)/i.height)*2+1),s=new Da;s.setFromCamera(r,this.engine.camera);const o=s.intersectObjects(Array.from(this.modelList.values(),c=>c.object),!0)[0];if(!o){this.clearSelection();return}let a=o.object;for(;a&&!a.userData.modelPlaceId;)a=a.parent;a?.userData.modelPlaceId?this.editModel(a.userData.modelPlaceId):this.clearSelection()}handleKeyDown(e){if(this.isCopyShortcut(e)){e.preventDefault(),this.copySelectedModel();return}if(this.isPasteShortcut(e)){e.preventDefault(),this.pasteModel().catch(n=>console.error("第三方模型粘贴失败:",n));return}if(this.isDeleteShortcut(e)){e.preventDefault(),this.deleteModel(this.selectedModelId);return}if(this.isUndoShortcut(e)){e.preventDefault(),this.undo().catch(n=>console.error("第三方模型撤回失败:",n));return}if(this.isTransformModeShortcut(e)){e.preventDefault(),this.switchTransformMode(e.shiftKey?-1:1);return}(e.key==="Escape"||e.keyCode===27)&&this.editingEnabled&&this.selectedModelId&&this.clearSelection()}isUndoShortcut(e){return!e.ctrlKey&&!e.metaKey||e.shiftKey||e.altKey||e.key.toLowerCase()!=="z"||this.isTextInputTarget(e)?!1:this.modelTransforms.length>0&&!this.isUndoing}isCopyShortcut(e){return(e.ctrlKey||e.metaKey)&&!e.shiftKey&&!e.altKey&&e.key.toLowerCase()==="c"&&!this.isTextInputTarget(e)&&this.selectedModelId!=null}isPasteShortcut(e){return(e.ctrlKey||e.metaKey)&&!e.shiftKey&&!e.altKey&&e.key.toLowerCase()==="v"&&!this.isTextInputTarget(e)&&this.copiedModelData!=null&&!this.isPasting}isDeleteShortcut(e){return e.key==="Delete"&&!e.ctrlKey&&!e.metaKey&&!e.altKey&&!this.isTextInputTarget(e)&&this.selectedModelId!=null}isTextInputTarget(e){const n=e.target;return!!(n?.isContentEditable||["INPUT","TEXTAREA","SELECT"].includes(n?.tagName??""))}isTransformModeShortcut(e){return e.key!=="Tab"||e.ctrlKey||e.metaKey||e.altKey||this.isTextInputTarget(e)?!1:this.editingEnabled&&this.selectedModelId!=null&&this.transformHelper?.visible===!0}switchTransformMode(e){const n=["translate","rotate","scale"],i=this.transformControl?.mode,s=(Math.max(0,n.indexOf(i??"translate"))+e+n.length)%n.length;this.transformControl?.setMode(n[s]),this.requestRender()}clearSelection(){this.selectedModelId=null,this.transformControl?.detach(),this.transformHelper&&(this.transformHelper.visible=!1),this.requestRender()}enableModelEditing(){this.editingEnabled=!0,this.bimHighlightDisabledBeforeEditing==null&&(this.bimHighlightDisabledBeforeEditing=!!this.engine.engineStatus?.disableModelInteractionHighlight),this.engine.engineStatus&&(this.engine.engineStatus.disableModelInteractionHighlight=!0),this.engine.modelToolModule?.unhighlightAllModels?.(),this.engine.hoverHighLight?.clearHighlight?.(),this.engine.hoverHighLight?.showModelNameTag?.(null,null)}disableModelEditing(){this.editingEnabled=!1,this.selectionPointerDown=null,this.bimHighlightDisabledBeforeEditing!=null&&this.engine.engineStatus&&(this.engine.engineStatus.disableModelInteractionHighlight=this.bimHighlightDisabledBeforeEditing),this.bimHighlightDisabledBeforeEditing=null}syncSelectedTransform(){if(!this.selectedModelId)return;const e=this.modelList.get(this.selectedModelId);e&&(e.data.position=e.object.position.toArray(),e.data.rotation=e.object.rotation.toArray(),e.data.scale=e.object.scale.toArray())}saveHistory(){this.isRestoring||this.modelTransforms.push(this.getSceneModels())}requireRecord(e){const n=this.modelList.get(e);if(!n)throw new Error(`未找到模型 “${e}”。`);return n}getMaterials(e){const n=[];return e.traverse(i=>{if(!i.isMesh)return;(Array.isArray(i.material)?i.material:[i.material]).forEach(s=>{s&&!n.includes(s)&&n.push(s)})}),n}getMaterialIndices(e,n){return typeof n=="number"?Number.isInteger(n)&&n>=0&&n<e.length?[n]:[]:e.reduce((i,r,s)=>(r.name===n&&i.push(s),i),[])}normalizeData(e){return{id:e.id??this.createId(),url:e.url,name:e.name??"第三方模型",position:e.position??[0,0,0],rotation:e.rotation??[0,0,0,"XYZ"],scale:e.scale??[1,1,1],visible:e.visible??!0,materials:e.materials??[]}}cloneData(e){return JSON.parse(JSON.stringify(e))}createId(){return`model-place-${Date.now()}-${Math.random().toString(36).slice(2,9)}`}removeObject(e){e.parent?.remove(e),e.traverse(n=>{n.geometry?.dispose?.(),(Array.isArray(n.material)?n.material:[n.material]).forEach(i=>{i?.map?.dispose?.(),i?.dispose?.()})})}requestRender(){this.engine.requestComposerRender?.()}}const yg={version:"3.11.10"}.version;function XH(){const t=globalThis.crypto?.subtle;if(!t)throw new Error("[BimEngine] Web Crypto API is required for secure sdkAuth credentials mode");return t}function zM(t){return new TextEncoder().encode(t)}function VM(t){return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}function jue(t){let e="";return t.forEach(n=>{e+=String.fromCharCode(n)}),btoa(e)}function VKe(t){const e=t.getUTCFullYear(),n=String(t.getUTCMonth()+1).padStart(2,"0"),i=String(t.getUTCDate()).padStart(2,"0");return`${e}${n}${i}`}async function jKe(t){const e=await XH().digest("SHA-256",VM(zM(t)));return Array.from(new Uint8Array(e)).map(n=>n.toString(16).padStart(2,"0")).join("")}async function HKe(t,e){const n=XH(),i=await n.importKey("raw",VM(t),{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return n.sign("HMAC",i,VM(zM(e)))}function GKe(t){return zM([t.appId,t.engineType,t.requestDate,String(t.timestamp),t.nonce].join("|"))}async function qKe(t){const e=XH(),n=new Date,i=n.getTime(),r=VKe(n),s=globalThis.crypto.randomUUID(),o=globalThis.crypto.getRandomValues(new Uint8Array(12)),a=await jKe(t.appSecret),c=await HKe(zM(a),r),l=await e.importKey("raw",c,"AES-GCM",!1,["encrypt"]),u=JSON.stringify({appKey:t.appKey,appSecret:t.appSecret}),h=await e.encrypt({name:"AES-GCM",iv:o,additionalData:VM(GKe({appId:t.appId,engineType:t.engineType,requestDate:r,timestamp:i,nonce:s})),tagLength:128},l,VM(zM(u)));return{appId:t.appId,engineType:t.engineType,requestDate:r,timestamp:i,nonce:s,iv:jue(o),cipherText:jue(new Uint8Array(h)),sdkVersion:t.sdkVersion,origin:t.origin,product:t.product}}const $H=new Map;function bF(t){return t.replace(/\/+$/,"")}function vF(t){if(t)return t;if(typeof window<"u"&&typeof window.location?.origin=="string")return window.location.origin}function WKe(t,e){return JSON.stringify({endpoint:bF(t.endpoint),token:t.token??"",appId:t.appId??"",appKey:t.appKey??"",appSecret:t.appSecret??"",origin:vF(t.origin)??"",product:t.product??"",engineType:e,sdkVersion:yg})}async function QH(t,e,n){const i=typeof AbortController<"u"?new AbortController:void 0,r=i?setTimeout(()=>i.abort(),n):void 0;try{const s=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:i?.signal}),o=await s.json().catch(()=>({}));if(!s.ok){const a=o?.error?.message??o?.message??`SDK authentication failed with status ${s.status}`;throw new Error(a)}return o}finally{r!=null&&clearTimeout(r)}}async function YKe(t,e){const n=await QH(`${bF(t.endpoint)}/oauth/sdk-verify`,{sdkToken:t.token,engineType:e,sdkVersion:yg,origin:vF(t.origin),product:t.product},t.timeoutMs??8e3);return n.sdkToken=t.token,n}async function XKe(t,e){const n=await qKe({appId:t.appId,appKey:t.appKey,appSecret:t.appSecret,engineType:e,sdkVersion:yg,origin:vF(t.origin),product:t.product}),i=await QH(`${bF(t.endpoint)}/oauth/sdk-token/secure`,n,t.timeoutMs??8e3),r=await QH(`${bF(t.endpoint)}/oauth/sdk-verify`,{sdkToken:i.sdkToken,engineType:e,sdkVersion:yg,origin:vF(t.origin),product:t.product},t.timeoutMs??8e3);return r.sdkToken=i.sdkToken,r}async function $Ke(t,e){const n=t?.sdkAuth;if(!n)return null;if(!n.endpoint)throw new Error("[BimEngine] sdkAuth.endpoint is required");if(!n.token&&!(n.appId&&n.appKey&&n.appSecret))return null;const i=WKe(n,e),r=$H.get(i);if(r){const o=await r;return t&&(t.__sdkAuthSession=o),o}const s=(n.token?YKe(n,e):XKe(n,e)).then(o=>{if(o.authorized!==!0)throw new Error("[BimEngine] SDK authorization rejected");return t&&(t.__sdkAuthSession=o),o}).catch(o=>{throw $H.delete(i),o});return $H.set(i,s),s}var KH,Hue;function mr(){return Hue||(Hue=1,KH={options:{usePureJavaScript:!1}}),KH}var JH={exports:{}},ZH,Gue;function QKe(){if(Gue)return ZH;Gue=1;var t={};ZH=t;var e={};t.encode=function(i,r,s){if(typeof r!="string")throw new TypeError('"alphabet" must be a string.');if(s!==void 0&&typeof s!="number")throw new TypeError('"maxline" must be a number.');var o="";if(!(i instanceof Uint8Array))o=n(i,r);else{var a=0,c=r.length,l=r.charAt(0),u=[0];for(a=0;a<i.length;++a){for(var h=0,d=i[a];h<u.length;++h)d+=u[h]<<8,u[h]=d%c,d=d/c|0;for(;d>0;)u.push(d%c),d=d/c|0}for(a=0;i[a]===0&&a<i.length-1;++a)o+=l;for(a=u.length-1;a>=0;--a)o+=r[u[a]]}if(s){var p=new RegExp(".{1,"+s+"}","g");o=o.match(p).join(`\r
|
|
6016
6016
|
`)}return o},t.decode=function(i,r){if(typeof i!="string")throw new TypeError('"input" must be a string.');if(typeof r!="string")throw new TypeError('"alphabet" must be a string.');var s=e[r];if(!s){s=e[r]=[];for(var o=0;o<r.length;++o)s[r.charCodeAt(o)]=o}i=i.replace(/\s/g,"");for(var a=r.length,c=r.charAt(0),l=[0],o=0;o<i.length;o++){var u=s[i.charCodeAt(o)];if(u===void 0)return;for(var h=0,d=u;h<l.length;++h)d+=l[h]*a,l[h]=d&255,d>>=8;for(;d>0;)l.push(d&255),d>>=8}for(var p=0;i[p]===c&&p<i.length-1;++p)l.push(0);return typeof Buffer<"u"?Buffer.from(l.reverse()):new Uint8Array(l.reverse())};function n(i,r){var s=0,o=r.length,a=r.charAt(0),c=[0];for(s=0;s<i.length();++s){for(var l=0,u=i.at(s);l<c.length;++l)u+=c[l]<<8,c[l]=u%o,u=u/o|0;for(;u>0;)c.push(u%o),u=u/o|0}var h="";for(s=0;i.at(s)===0&&s<i.length()-1;++s)h+=a;for(s=c.length-1;s>=0;--s)h+=r[c[s]];return h}return ZH}var que;function cs(){if(que)return JH.exports;que=1;var t=mr(),e=QKe(),n=JH.exports=t.util=t.util||{};(function(){if(typeof process<"u"&&process.nextTick&&!process.browser){n.nextTick=process.nextTick,typeof setImmediate=="function"?n.setImmediate=setImmediate:n.setImmediate=n.nextTick;return}if(typeof setImmediate=="function"){n.setImmediate=function(){return setImmediate.apply(void 0,arguments)},n.nextTick=function(w){return setImmediate(w)};return}if(n.setImmediate=function(w){setTimeout(w,0)},typeof window<"u"&&typeof window.postMessage=="function"){let w=function(E){if(E.source===window&&E.data===A){E.stopPropagation();var D=v.slice();v.length=0,D.forEach(function(O){O()})}};var A="forge.setImmediate",v=[];n.setImmediate=function(E){v.push(E),v.length===1&&window.postMessage(A,"*")},window.addEventListener("message",w,!0)}if(typeof MutationObserver<"u"){var x=Date.now(),C=!0,T=document.createElement("div"),v=[];new MutationObserver(function(){var E=v.slice();v.length=0,E.forEach(function(D){D()})}).observe(T,{attributes:!0});var S=n.setImmediate;n.setImmediate=function(E){Date.now()-x>15?(x=Date.now(),S(E)):(v.push(E),v.length===1&&T.setAttribute("a",C=!C))}}n.nextTick=n.setImmediate})(),n.isNodejs=typeof process<"u"&&process.versions&&process.versions.node,n.globalScope=(function(){return n.isNodejs?Wb:typeof self>"u"?window:self})(),n.isArray=Array.isArray||function(A){return Object.prototype.toString.call(A)==="[object Array]"},n.isArrayBuffer=function(A){return typeof ArrayBuffer<"u"&&A instanceof ArrayBuffer},n.isArrayBufferView=function(A){return A&&n.isArrayBuffer(A.buffer)&&A.byteLength!==void 0};function i(A){if(!(A===8||A===16||A===24||A===32))throw new Error("Only 8, 16, 24, or 32 bits supported: "+A)}n.ByteBuffer=r;function r(A){if(this.data="",this.read=0,typeof A=="string")this.data=A;else if(n.isArrayBuffer(A)||n.isArrayBufferView(A))if(typeof Buffer<"u"&&A instanceof Buffer)this.data=A.toString("binary");else{var v=new Uint8Array(A);try{this.data=String.fromCharCode.apply(null,v)}catch{for(var x=0;x<v.length;++x)this.putByte(v[x])}}else(A instanceof r||typeof A=="object"&&typeof A.data=="string"&&typeof A.read=="number")&&(this.data=A.data,this.read=A.read);this._constructedStringLength=0}n.ByteStringBuffer=r;var s=4096;n.ByteStringBuffer.prototype._optimizeConstructedString=function(A){this._constructedStringLength+=A,this._constructedStringLength>s&&(this.data.substr(0,1),this._constructedStringLength=0)},n.ByteStringBuffer.prototype.length=function(){return this.data.length-this.read},n.ByteStringBuffer.prototype.isEmpty=function(){return this.length()<=0},n.ByteStringBuffer.prototype.putByte=function(A){return this.putBytes(String.fromCharCode(A))},n.ByteStringBuffer.prototype.fillWithByte=function(A,v){A=String.fromCharCode(A);for(var x=this.data;v>0;)v&1&&(x+=A),v>>>=1,v>0&&(A+=A);return this.data=x,this._optimizeConstructedString(v),this},n.ByteStringBuffer.prototype.putBytes=function(A){return this.data+=A,this._optimizeConstructedString(A.length),this},n.ByteStringBuffer.prototype.putString=function(A){return this.putBytes(n.encodeUtf8(A))},n.ByteStringBuffer.prototype.putInt16=function(A){return this.putBytes(String.fromCharCode(A>>8&255)+String.fromCharCode(A&255))},n.ByteStringBuffer.prototype.putInt24=function(A){return this.putBytes(String.fromCharCode(A>>16&255)+String.fromCharCode(A>>8&255)+String.fromCharCode(A&255))},n.ByteStringBuffer.prototype.putInt32=function(A){return this.putBytes(String.fromCharCode(A>>24&255)+String.fromCharCode(A>>16&255)+String.fromCharCode(A>>8&255)+String.fromCharCode(A&255))},n.ByteStringBuffer.prototype.putInt16Le=function(A){return this.putBytes(String.fromCharCode(A&255)+String.fromCharCode(A>>8&255))},n.ByteStringBuffer.prototype.putInt24Le=function(A){return this.putBytes(String.fromCharCode(A&255)+String.fromCharCode(A>>8&255)+String.fromCharCode(A>>16&255))},n.ByteStringBuffer.prototype.putInt32Le=function(A){return this.putBytes(String.fromCharCode(A&255)+String.fromCharCode(A>>8&255)+String.fromCharCode(A>>16&255)+String.fromCharCode(A>>24&255))},n.ByteStringBuffer.prototype.putInt=function(A,v){i(v);var x="";do v-=8,x+=String.fromCharCode(A>>v&255);while(v>0);return this.putBytes(x)},n.ByteStringBuffer.prototype.putSignedInt=function(A,v){return A<0&&(A+=2<<v-1),this.putInt(A,v)},n.ByteStringBuffer.prototype.putBuffer=function(A){return this.putBytes(A.getBytes())},n.ByteStringBuffer.prototype.getByte=function(){return this.data.charCodeAt(this.read++)},n.ByteStringBuffer.prototype.getInt16=function(){var A=this.data.charCodeAt(this.read)<<8^this.data.charCodeAt(this.read+1);return this.read+=2,A},n.ByteStringBuffer.prototype.getInt24=function(){var A=this.data.charCodeAt(this.read)<<16^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2);return this.read+=3,A},n.ByteStringBuffer.prototype.getInt32=function(){var A=this.data.charCodeAt(this.read)<<24^this.data.charCodeAt(this.read+1)<<16^this.data.charCodeAt(this.read+2)<<8^this.data.charCodeAt(this.read+3);return this.read+=4,A},n.ByteStringBuffer.prototype.getInt16Le=function(){var A=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8;return this.read+=2,A},n.ByteStringBuffer.prototype.getInt24Le=function(){var A=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2)<<16;return this.read+=3,A},n.ByteStringBuffer.prototype.getInt32Le=function(){var A=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2)<<16^this.data.charCodeAt(this.read+3)<<24;return this.read+=4,A},n.ByteStringBuffer.prototype.getInt=function(A){i(A);var v=0;do v=(v<<8)+this.data.charCodeAt(this.read++),A-=8;while(A>0);return v},n.ByteStringBuffer.prototype.getSignedInt=function(A){var v=this.getInt(A),x=2<<A-2;return v>=x&&(v-=x<<1),v},n.ByteStringBuffer.prototype.getBytes=function(A){var v;return A?(A=Math.min(this.length(),A),v=this.data.slice(this.read,this.read+A),this.read+=A):A===0?v="":(v=this.read===0?this.data:this.data.slice(this.read),this.clear()),v},n.ByteStringBuffer.prototype.bytes=function(A){return typeof A>"u"?this.data.slice(this.read):this.data.slice(this.read,this.read+A)},n.ByteStringBuffer.prototype.at=function(A){return this.data.charCodeAt(this.read+A)},n.ByteStringBuffer.prototype.setAt=function(A,v){return this.data=this.data.substr(0,this.read+A)+String.fromCharCode(v)+this.data.substr(this.read+A+1),this},n.ByteStringBuffer.prototype.last=function(){return this.data.charCodeAt(this.data.length-1)},n.ByteStringBuffer.prototype.copy=function(){var A=n.createBuffer(this.data);return A.read=this.read,A},n.ByteStringBuffer.prototype.compact=function(){return this.read>0&&(this.data=this.data.slice(this.read),this.read=0),this},n.ByteStringBuffer.prototype.clear=function(){return this.data="",this.read=0,this},n.ByteStringBuffer.prototype.truncate=function(A){var v=Math.max(0,this.length()-A);return this.data=this.data.substr(this.read,v),this.read=0,this},n.ByteStringBuffer.prototype.toHex=function(){for(var A="",v=this.read;v<this.data.length;++v){var x=this.data.charCodeAt(v);x<16&&(A+="0"),A+=x.toString(16)}return A},n.ByteStringBuffer.prototype.toString=function(){return n.decodeUtf8(this.bytes())};function o(A,v){v=v||{},this.read=v.readOffset||0,this.growSize=v.growSize||1024;var x=n.isArrayBuffer(A),C=n.isArrayBufferView(A);if(x||C){x?this.data=new DataView(A):this.data=new DataView(A.buffer,A.byteOffset,A.byteLength),this.write="writeOffset"in v?v.writeOffset:this.data.byteLength;return}this.data=new DataView(new ArrayBuffer(0)),this.write=0,A!=null&&this.putBytes(A),"writeOffset"in v&&(this.write=v.writeOffset)}n.DataBuffer=o,n.DataBuffer.prototype.length=function(){return this.write-this.read},n.DataBuffer.prototype.isEmpty=function(){return this.length()<=0},n.DataBuffer.prototype.accommodate=function(A,v){if(this.length()>=A)return this;v=Math.max(v||this.growSize,A);var x=new Uint8Array(this.data.buffer,this.data.byteOffset,this.data.byteLength),C=new Uint8Array(this.length()+v);return C.set(x),this.data=new DataView(C.buffer),this},n.DataBuffer.prototype.putByte=function(A){return this.accommodate(1),this.data.setUint8(this.write++,A),this},n.DataBuffer.prototype.fillWithByte=function(A,v){this.accommodate(v);for(var x=0;x<v;++x)this.data.setUint8(A);return this},n.DataBuffer.prototype.putBytes=function(A,v){if(n.isArrayBufferView(A)){var x=new Uint8Array(A.buffer,A.byteOffset,A.byteLength),C=x.byteLength-x.byteOffset;this.accommodate(C);var T=new Uint8Array(this.data.buffer,this.write);return T.set(x),this.write+=C,this}if(n.isArrayBuffer(A)){var x=new Uint8Array(A);this.accommodate(x.byteLength);var T=new Uint8Array(this.data.buffer);return T.set(x,this.write),this.write+=x.byteLength,this}if(A instanceof n.DataBuffer||typeof A=="object"&&typeof A.read=="number"&&typeof A.write=="number"&&n.isArrayBufferView(A.data)){var x=new Uint8Array(A.data.byteLength,A.read,A.length());this.accommodate(x.byteLength);var T=new Uint8Array(A.data.byteLength,this.write);return T.set(x),this.write+=x.byteLength,this}if(A instanceof n.ByteStringBuffer&&(A=A.data,v="binary"),v=v||"binary",typeof A=="string"){var S;if(v==="hex")return this.accommodate(Math.ceil(A.length/2)),S=new Uint8Array(this.data.buffer,this.write),this.write+=n.binary.hex.decode(A,S,this.write),this;if(v==="base64")return this.accommodate(Math.ceil(A.length/4)*3),S=new Uint8Array(this.data.buffer,this.write),this.write+=n.binary.base64.decode(A,S,this.write),this;if(v==="utf8"&&(A=n.encodeUtf8(A),v="binary"),v==="binary"||v==="raw")return this.accommodate(A.length),S=new Uint8Array(this.data.buffer,this.write),this.write+=n.binary.raw.decode(S),this;if(v==="utf16")return this.accommodate(A.length*2),S=new Uint16Array(this.data.buffer,this.write),this.write+=n.text.utf16.encode(S),this;throw new Error("Invalid encoding: "+v)}throw Error("Invalid parameter: "+A)},n.DataBuffer.prototype.putBuffer=function(A){return this.putBytes(A),A.clear(),this},n.DataBuffer.prototype.putString=function(A){return this.putBytes(A,"utf16")},n.DataBuffer.prototype.putInt16=function(A){return this.accommodate(2),this.data.setInt16(this.write,A),this.write+=2,this},n.DataBuffer.prototype.putInt24=function(A){return this.accommodate(3),this.data.setInt16(this.write,A>>8&65535),this.data.setInt8(this.write,A>>16&255),this.write+=3,this},n.DataBuffer.prototype.putInt32=function(A){return this.accommodate(4),this.data.setInt32(this.write,A),this.write+=4,this},n.DataBuffer.prototype.putInt16Le=function(A){return this.accommodate(2),this.data.setInt16(this.write,A,!0),this.write+=2,this},n.DataBuffer.prototype.putInt24Le=function(A){return this.accommodate(3),this.data.setInt8(this.write,A>>16&255),this.data.setInt16(this.write,A>>8&65535,!0),this.write+=3,this},n.DataBuffer.prototype.putInt32Le=function(A){return this.accommodate(4),this.data.setInt32(this.write,A,!0),this.write+=4,this},n.DataBuffer.prototype.putInt=function(A,v){i(v),this.accommodate(v/8);do v-=8,this.data.setInt8(this.write++,A>>v&255);while(v>0);return this},n.DataBuffer.prototype.putSignedInt=function(A,v){return i(v),this.accommodate(v/8),A<0&&(A+=2<<v-1),this.putInt(A,v)},n.DataBuffer.prototype.getByte=function(){return this.data.getInt8(this.read++)},n.DataBuffer.prototype.getInt16=function(){var A=this.data.getInt16(this.read);return this.read+=2,A},n.DataBuffer.prototype.getInt24=function(){var A=this.data.getInt16(this.read)<<8^this.data.getInt8(this.read+2);return this.read+=3,A},n.DataBuffer.prototype.getInt32=function(){var A=this.data.getInt32(this.read);return this.read+=4,A},n.DataBuffer.prototype.getInt16Le=function(){var A=this.data.getInt16(this.read,!0);return this.read+=2,A},n.DataBuffer.prototype.getInt24Le=function(){var A=this.data.getInt8(this.read)^this.data.getInt16(this.read+1,!0)<<8;return this.read+=3,A},n.DataBuffer.prototype.getInt32Le=function(){var A=this.data.getInt32(this.read,!0);return this.read+=4,A},n.DataBuffer.prototype.getInt=function(A){i(A);var v=0;do v=(v<<8)+this.data.getInt8(this.read++),A-=8;while(A>0);return v},n.DataBuffer.prototype.getSignedInt=function(A){var v=this.getInt(A),x=2<<A-2;return v>=x&&(v-=x<<1),v},n.DataBuffer.prototype.getBytes=function(A){var v;return A?(A=Math.min(this.length(),A),v=this.data.slice(this.read,this.read+A),this.read+=A):A===0?v="":(v=this.read===0?this.data:this.data.slice(this.read),this.clear()),v},n.DataBuffer.prototype.bytes=function(A){return typeof A>"u"?this.data.slice(this.read):this.data.slice(this.read,this.read+A)},n.DataBuffer.prototype.at=function(A){return this.data.getUint8(this.read+A)},n.DataBuffer.prototype.setAt=function(A,v){return this.data.setUint8(A,v),this},n.DataBuffer.prototype.last=function(){return this.data.getUint8(this.write-1)},n.DataBuffer.prototype.copy=function(){return new n.DataBuffer(this)},n.DataBuffer.prototype.compact=function(){if(this.read>0){var A=new Uint8Array(this.data.buffer,this.read),v=new Uint8Array(A.byteLength);v.set(A),this.data=new DataView(v),this.write-=this.read,this.read=0}return this},n.DataBuffer.prototype.clear=function(){return this.data=new DataView(new ArrayBuffer(0)),this.read=this.write=0,this},n.DataBuffer.prototype.truncate=function(A){return this.write=Math.max(0,this.length()-A),this.read=Math.min(this.read,this.write),this},n.DataBuffer.prototype.toHex=function(){for(var A="",v=this.read;v<this.data.byteLength;++v){var x=this.data.getUint8(v);x<16&&(A+="0"),A+=x.toString(16)}return A},n.DataBuffer.prototype.toString=function(A){var v=new Uint8Array(this.data,this.read,this.length());if(A=A||"utf8",A==="binary"||A==="raw")return n.binary.raw.encode(v);if(A==="hex")return n.binary.hex.encode(v);if(A==="base64")return n.binary.base64.encode(v);if(A==="utf8")return n.text.utf8.decode(v);if(A==="utf16")return n.text.utf16.decode(v);throw new Error("Invalid encoding: "+A)},n.createBuffer=function(A,v){return v=v||"raw",A!==void 0&&v==="utf8"&&(A=n.encodeUtf8(A)),new n.ByteBuffer(A)},n.fillString=function(A,v){for(var x="";v>0;)v&1&&(x+=A),v>>>=1,v>0&&(A+=A);return x},n.xorBytes=function(A,v,x){for(var C="",T="",S="",w=0,E=0;x>0;--x,++w)T=A.charCodeAt(w)^v.charCodeAt(w),E>=10&&(C+=S,S="",E=0),S+=String.fromCharCode(T),++E;return C+=S,C},n.hexToBytes=function(A){var v="",x=0;for(A.length&!0&&(x=1,v+=String.fromCharCode(parseInt(A[0],16)));x<A.length;x+=2)v+=String.fromCharCode(parseInt(A.substr(x,2),16));return v},n.bytesToHex=function(A){return n.createBuffer(A).toHex()},n.int32ToBytes=function(A){return String.fromCharCode(A>>24&255)+String.fromCharCode(A>>16&255)+String.fromCharCode(A>>8&255)+String.fromCharCode(A&255)};var a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",c=[62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,64,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51],l="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";n.encode64=function(A,v){for(var x="",C="",T,S,w,E=0;E<A.length;)T=A.charCodeAt(E++),S=A.charCodeAt(E++),w=A.charCodeAt(E++),x+=a.charAt(T>>2),x+=a.charAt((T&3)<<4|S>>4),isNaN(S)?x+="==":(x+=a.charAt((S&15)<<2|w>>6),x+=isNaN(w)?"=":a.charAt(w&63)),v&&x.length>v&&(C+=x.substr(0,v)+`\r
|
|
6017
6017
|
`,x=x.substr(v));return C+=x,C},n.decode64=function(A){A=A.replace(/[^A-Za-z0-9\+\/\=]/g,"");for(var v="",x,C,T,S,w=0;w<A.length;)x=c[A.charCodeAt(w++)-43],C=c[A.charCodeAt(w++)-43],T=c[A.charCodeAt(w++)-43],S=c[A.charCodeAt(w++)-43],v+=String.fromCharCode(x<<2|C>>4),T!==64&&(v+=String.fromCharCode((C&15)<<4|T>>2),S!==64&&(v+=String.fromCharCode((T&3)<<6|S)));return v},n.encodeUtf8=function(A){return unescape(encodeURIComponent(A))},n.decodeUtf8=function(A){return decodeURIComponent(escape(A))},n.binary={raw:{},hex:{},base64:{},base58:{},baseN:{encode:e.encode,decode:e.decode}},n.binary.raw.encode=function(A){return String.fromCharCode.apply(null,A)},n.binary.raw.decode=function(A,v,x){var C=v;C||(C=new Uint8Array(A.length)),x=x||0;for(var T=x,S=0;S<A.length;++S)C[T++]=A.charCodeAt(S);return v?T-x:C},n.binary.hex.encode=n.bytesToHex,n.binary.hex.decode=function(A,v,x){var C=v;C||(C=new Uint8Array(Math.ceil(A.length/2))),x=x||0;var T=0,S=x;for(A.length&1&&(T=1,C[S++]=parseInt(A[0],16));T<A.length;T+=2)C[S++]=parseInt(A.substr(T,2),16);return v?S-x:C},n.binary.base64.encode=function(A,v){for(var x="",C="",T,S,w,E=0;E<A.byteLength;)T=A[E++],S=A[E++],w=A[E++],x+=a.charAt(T>>2),x+=a.charAt((T&3)<<4|S>>4),isNaN(S)?x+="==":(x+=a.charAt((S&15)<<2|w>>6),x+=isNaN(w)?"=":a.charAt(w&63)),v&&x.length>v&&(C+=x.substr(0,v)+`\r
|
|
6018
6018
|
`,x=x.substr(v));return C+=x,C},n.binary.base64.decode=function(A,v,x){var C=v;C||(C=new Uint8Array(Math.ceil(A.length/4)*3)),A=A.replace(/[^A-Za-z0-9\+\/\=]/g,""),x=x||0;for(var T,S,w,E,D=0,O=x;D<A.length;)T=c[A.charCodeAt(D++)-43],S=c[A.charCodeAt(D++)-43],w=c[A.charCodeAt(D++)-43],E=c[A.charCodeAt(D++)-43],C[O++]=T<<2|S>>4,w!==64&&(C[O++]=(S&15)<<4|w>>2,E!==64&&(C[O++]=(w&3)<<6|E));return v?O-x:C.subarray(0,O)},n.binary.base58.encode=function(A,v){return n.binary.baseN.encode(A,l,v)},n.binary.base58.decode=function(A,v){return n.binary.baseN.decode(A,l,v)},n.text={utf8:{},utf16:{}},n.text.utf8.encode=function(A,v,x){A=n.encodeUtf8(A);var C=v;C||(C=new Uint8Array(A.length)),x=x||0;for(var T=x,S=0;S<A.length;++S)C[T++]=A.charCodeAt(S);return v?T-x:C},n.text.utf8.decode=function(A){return n.decodeUtf8(String.fromCharCode.apply(null,A))},n.text.utf16.encode=function(A,v,x){var C=v;C||(C=new Uint8Array(A.length*2));var T=new Uint16Array(C.buffer);x=x||0;for(var S=x,w=x,E=0;E<A.length;++E)T[w++]=A.charCodeAt(E),S+=2;return v?S-x:C},n.text.utf16.decode=function(A){return String.fromCharCode.apply(null,new Uint16Array(A.buffer))},n.deflate=function(A,v,x){if(v=n.decode64(A.deflate(n.encode64(v)).rval),x){var C=2,T=v.charCodeAt(1);T&32&&(C=6),v=v.substring(C,v.length-4)}return v},n.inflate=function(A,v,x){var C=A.inflate(n.encode64(v)).rval;return C===null?null:n.decode64(C)};var u=function(A,v,x){if(!A)throw new Error("WebStorage not available.");var C;if(x===null?C=A.removeItem(v):(x=n.encode64(JSON.stringify(x)),C=A.setItem(v,x)),typeof C<"u"&&C.rval!==!0){var T=new Error(C.error.message);throw T.id=C.error.id,T.name=C.error.name,T}},h=function(A,v){if(!A)throw new Error("WebStorage not available.");var x=A.getItem(v);if(A.init)if(x.rval===null){if(x.error){var C=new Error(x.error.message);throw C.id=x.error.id,C.name=x.error.name,C}x=null}else x=x.rval;return x!==null&&(x=JSON.parse(n.decode64(x))),x},d=function(A,v,x,C){var T=h(A,v);T===null&&(T={}),T[x]=C,u(A,v,T)},p=function(A,v,x){var C=h(A,v);return C!==null&&(C=x in C?C[x]:null),C},m=function(A,v,x){var C=h(A,v);if(C!==null&&x in C){delete C[x];var T=!0;for(var S in C){T=!1;break}T&&(C=null),u(A,v,C)}},g=function(A,v){u(A,v,null)},y=function(A,v,x){var C=null;typeof x>"u"&&(x=["web","flash"]);var T,S=!1,w=null;for(var E in x){T=x[E];try{if(T==="flash"||T==="both"){if(v[0]===null)throw new Error("Flash local storage not available.");C=A.apply(this,v),S=T==="flash"}(T==="web"||T==="both")&&(v[0]=localStorage,C=A.apply(this,v),S=!0)}catch(D){w=D}if(S)break}if(!S)throw w;return C};return n.setItem=function(A,v,x,C,T){y(d,arguments,T)},n.getItem=function(A,v,x,C){return y(p,arguments,C)},n.removeItem=function(A,v,x,C){y(m,arguments,C)},n.clearItems=function(A,v,x){y(g,arguments,x)},n.isEmpty=function(A){for(var v in A)if(A.hasOwnProperty(v))return!1;return!0},n.format=function(A){for(var v=/%./g,x,C,T=0,S=[],w=0;x=v.exec(A);){C=A.substring(w,v.lastIndex-2),C.length>0&&S.push(C),w=v.lastIndex;var E=x[0][1];switch(E){case"s":case"o":T<arguments.length?S.push(arguments[T+++1]):S.push("<?>");break;case"%":S.push("%");break;default:S.push("<%"+E+"?>")}}return S.push(A.substring(w)),S.join("")},n.formatNumber=function(A,v,x,C){var T=A,S=isNaN(v=Math.abs(v))?2:v,w=x===void 0?",":x,E=C===void 0?".":C,D=T<0?"-":"",O=parseInt(T=Math.abs(+T||0).toFixed(S),10)+"",P=O.length>3?O.length%3:0;return D+(P?O.substr(0,P)+E:"")+O.substr(P).replace(/(\d{3})(?=\d)/g,"$1"+E)+(S?w+Math.abs(T-O).toFixed(S).slice(2):"")},n.formatSize=function(A){return A>=1073741824?A=n.formatNumber(A/1073741824,2,".","")+" GiB":A>=1048576?A=n.formatNumber(A/1048576,2,".","")+" MiB":A>=1024?A=n.formatNumber(A/1024,0)+" KiB":A=n.formatNumber(A,0)+" bytes",A},n.bytesFromIP=function(A){return A.indexOf(".")!==-1?n.bytesFromIPv4(A):A.indexOf(":")!==-1?n.bytesFromIPv6(A):null},n.bytesFromIPv4=function(A){if(A=A.split("."),A.length!==4)return null;for(var v=n.createBuffer(),x=0;x<A.length;++x){var C=parseInt(A[x],10);if(isNaN(C))return null;v.putByte(C)}return v.getBytes()},n.bytesFromIPv6=function(A){var v=0;A=A.split(":").filter(function(w){return w.length===0&&++v,!0});for(var x=(8-A.length+v)*2,C=n.createBuffer(),T=0;T<8;++T){if(!A[T]||A[T].length===0){C.fillWithByte(0,x),x=0;continue}var S=n.hexToBytes(A[T]);S.length<2&&C.putByte(0),C.putBytes(S)}return C.getBytes()},n.bytesToIP=function(A){return A.length===4?n.bytesToIPv4(A):A.length===16?n.bytesToIPv6(A):null},n.bytesToIPv4=function(A){if(A.length!==4)return null;for(var v=[],x=0;x<A.length;++x)v.push(A.charCodeAt(x));return v.join(".")},n.bytesToIPv6=function(A){if(A.length!==16)return null;for(var v=[],x=[],C=0,T=0;T<A.length;T+=2){for(var S=n.bytesToHex(A[T]+A[T+1]);S[0]==="0"&&S!=="0";)S=S.substr(1);if(S==="0"){var w=x[x.length-1],E=v.length;!w||E!==w.end+1?x.push({start:E,end:E}):(w.end=E,w.end-w.start>x[C].end-x[C].start&&(C=x.length-1))}v.push(S)}if(x.length>0){var D=x[C];D.end-D.start>0&&(v.splice(D.start,D.end-D.start+1,""),D.start===0&&v.unshift(""),D.end===7&&v.push(""))}return v.join(":")},n.estimateCores=function(A,v){if(typeof A=="function"&&(v=A,A={}),A=A||{},"cores"in n&&!A.update)return v(null,n.cores);if(typeof navigator<"u"&&"hardwareConcurrency"in navigator&&navigator.hardwareConcurrency>0)return n.cores=navigator.hardwareConcurrency,v(null,n.cores);if(typeof Worker>"u")return n.cores=1,v(null,n.cores);if(typeof Blob>"u")return n.cores=2,v(null,n.cores);var x=URL.createObjectURL(new Blob(["(",(function(){self.addEventListener("message",function(w){var E=Date.now(),D=E+4;self.postMessage({st:E,et:D})})}).toString(),")()"],{type:"application/javascript"}));C([],5,16);function C(w,E,D){if(E===0){var O=Math.floor(w.reduce(function(P,I){return P+I},0)/w.length);return n.cores=Math.max(1,O),URL.revokeObjectURL(x),v(null,n.cores)}T(D,function(P,I){w.push(S(D,I)),C(w,E-1,D)})}function T(w,E){for(var D=[],O=[],P=0;P<w;++P){var I=new Worker(x);I.addEventListener("message",function(_){if(O.push(_.data),O.length===w){for(var M=0;M<w;++M)D[M].terminate();E(null,O)}}),D.push(I)}for(var P=0;P<w;++P)D[P].postMessage(P)}function S(w,E){for(var D=[],O=0;O<w;++O)for(var P=E[O],I=D[O]=[],_=0;_<w;++_)if(O!==_){var M=E[_];(P.st>M.st&&P.st<M.et||M.st>P.st&&M.st<P.et)&&I.push(_)}return D.reduce(function(L,N){return Math.max(L,N.length)},0)}},JH.exports}var eG,Wue;function tG(){if(Wue)return eG;Wue=1;var t=mr();cs(),eG=t.cipher=t.cipher||{},t.cipher.algorithms=t.cipher.algorithms||{},t.cipher.createCipher=function(n,i){var r=n;if(typeof r=="string"&&(r=t.cipher.getAlgorithm(r),r&&(r=r())),!r)throw new Error("Unsupported algorithm: "+n);return new t.cipher.BlockCipher({algorithm:r,key:i,decrypt:!1})},t.cipher.createDecipher=function(n,i){var r=n;if(typeof r=="string"&&(r=t.cipher.getAlgorithm(r),r&&(r=r())),!r)throw new Error("Unsupported algorithm: "+n);return new t.cipher.BlockCipher({algorithm:r,key:i,decrypt:!0})},t.cipher.registerAlgorithm=function(n,i){n=n.toUpperCase(),t.cipher.algorithms[n]=i},t.cipher.getAlgorithm=function(n){return n=n.toUpperCase(),n in t.cipher.algorithms?t.cipher.algorithms[n]:null};var e=t.cipher.BlockCipher=function(n){this.algorithm=n.algorithm,this.mode=this.algorithm.mode,this.blockSize=this.mode.blockSize,this._finish=!1,this._input=null,this.output=null,this._op=n.decrypt?this.mode.decrypt:this.mode.encrypt,this._decrypt=n.decrypt,this.algorithm.initialize(n)};return e.prototype.start=function(n){n=n||{};var i={};for(var r in n)i[r]=n[r];i.decrypt=this._decrypt,this._finish=!1,this._input=t.util.createBuffer(),this.output=n.output||t.util.createBuffer(),this.mode.start(i)},e.prototype.update=function(n){for(n&&this._input.putBuffer(n);!this._op.call(this.mode,this._input,this.output,this._finish)&&!this._finish;);this._input.compact()},e.prototype.finish=function(n){n&&(this.mode.name==="ECB"||this.mode.name==="CBC")&&(this.mode.pad=function(r){return n(this.blockSize,r,!1)},this.mode.unpad=function(r){return n(this.blockSize,r,!0)});var i={};return i.decrypt=this._decrypt,i.overflow=this._input.length()%this.blockSize,!(!this._decrypt&&this.mode.pad&&!this.mode.pad(this._input,i)||(this._finish=!0,this.update(),this._decrypt&&this.mode.unpad&&!this.mode.unpad(this.output,i))||this.mode.afterFinish&&!this.mode.afterFinish(this.output,i))},eG}var nG={exports:{}},Yue;function Xue(){if(Yue)return nG.exports;Yue=1;var t=mr();cs(),t.cipher=t.cipher||{};var e=nG.exports=t.cipher.modes=t.cipher.modes||{};e.ecb=function(s){s=s||{},this.name="ECB",this.cipher=s.cipher,this.blockSize=s.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints)},e.ecb.prototype.start=function(s){},e.ecb.prototype.encrypt=function(s,o,a){if(s.length()<this.blockSize&&!(a&&s.length()>0))return!0;for(var c=0;c<this._ints;++c)this._inBlock[c]=s.getInt32();this.cipher.encrypt(this._inBlock,this._outBlock);for(var c=0;c<this._ints;++c)o.putInt32(this._outBlock[c])},e.ecb.prototype.decrypt=function(s,o,a){if(s.length()<this.blockSize&&!(a&&s.length()>0))return!0;for(var c=0;c<this._ints;++c)this._inBlock[c]=s.getInt32();this.cipher.decrypt(this._inBlock,this._outBlock);for(var c=0;c<this._ints;++c)o.putInt32(this._outBlock[c])},e.ecb.prototype.pad=function(s,o){var a=s.length()===this.blockSize?this.blockSize:this.blockSize-s.length();return s.fillWithByte(a,a),!0},e.ecb.prototype.unpad=function(s,o){if(o.overflow>0)return!1;var a=s.length(),c=s.at(a-1);return c>this.blockSize<<2?!1:(s.truncate(c),!0)},e.cbc=function(s){s=s||{},this.name="CBC",this.cipher=s.cipher,this.blockSize=s.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints)},e.cbc.prototype.start=function(s){if(s.iv===null){if(!this._prev)throw new Error("Invalid IV parameter.");this._iv=this._prev.slice(0)}else if("iv"in s)this._iv=n(s.iv,this.blockSize),this._prev=this._iv.slice(0);else throw new Error("Invalid IV parameter.")},e.cbc.prototype.encrypt=function(s,o,a){if(s.length()<this.blockSize&&!(a&&s.length()>0))return!0;for(var c=0;c<this._ints;++c)this._inBlock[c]=this._prev[c]^s.getInt32();this.cipher.encrypt(this._inBlock,this._outBlock);for(var c=0;c<this._ints;++c)o.putInt32(this._outBlock[c]);this._prev=this._outBlock},e.cbc.prototype.decrypt=function(s,o,a){if(s.length()<this.blockSize&&!(a&&s.length()>0))return!0;for(var c=0;c<this._ints;++c)this._inBlock[c]=s.getInt32();this.cipher.decrypt(this._inBlock,this._outBlock);for(var c=0;c<this._ints;++c)o.putInt32(this._prev[c]^this._outBlock[c]);this._prev=this._inBlock.slice(0)},e.cbc.prototype.pad=function(s,o){var a=s.length()===this.blockSize?this.blockSize:this.blockSize-s.length();return s.fillWithByte(a,a),!0},e.cbc.prototype.unpad=function(s,o){if(o.overflow>0)return!1;var a=s.length(),c=s.at(a-1);return c>this.blockSize<<2?!1:(s.truncate(c),!0)},e.cfb=function(s){s=s||{},this.name="CFB",this.cipher=s.cipher,this.blockSize=s.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialBlock=new Array(this._ints),this._partialOutput=t.util.createBuffer(),this._partialBytes=0},e.cfb.prototype.start=function(s){if(!("iv"in s))throw new Error("Invalid IV parameter.");this._iv=n(s.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},e.cfb.prototype.encrypt=function(s,o,a){var c=s.length();if(c===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&c>=this.blockSize){for(var l=0;l<this._ints;++l)this._inBlock[l]=s.getInt32()^this._outBlock[l],o.putInt32(this._inBlock[l]);return}var u=(this.blockSize-c)%this.blockSize;u>0&&(u=this.blockSize-u),this._partialOutput.clear();for(var l=0;l<this._ints;++l)this._partialBlock[l]=s.getInt32()^this._outBlock[l],this._partialOutput.putInt32(this._partialBlock[l]);if(u>0)s.read-=this.blockSize;else for(var l=0;l<this._ints;++l)this._inBlock[l]=this._partialBlock[l];if(this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),u>0&&!a)return o.putBytes(this._partialOutput.getBytes(u-this._partialBytes)),this._partialBytes=u,!0;o.putBytes(this._partialOutput.getBytes(c-this._partialBytes)),this._partialBytes=0},e.cfb.prototype.decrypt=function(s,o,a){var c=s.length();if(c===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&c>=this.blockSize){for(var l=0;l<this._ints;++l)this._inBlock[l]=s.getInt32(),o.putInt32(this._inBlock[l]^this._outBlock[l]);return}var u=(this.blockSize-c)%this.blockSize;u>0&&(u=this.blockSize-u),this._partialOutput.clear();for(var l=0;l<this._ints;++l)this._partialBlock[l]=s.getInt32(),this._partialOutput.putInt32(this._partialBlock[l]^this._outBlock[l]);if(u>0)s.read-=this.blockSize;else for(var l=0;l<this._ints;++l)this._inBlock[l]=this._partialBlock[l];if(this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),u>0&&!a)return o.putBytes(this._partialOutput.getBytes(u-this._partialBytes)),this._partialBytes=u,!0;o.putBytes(this._partialOutput.getBytes(c-this._partialBytes)),this._partialBytes=0},e.ofb=function(s){s=s||{},this.name="OFB",this.cipher=s.cipher,this.blockSize=s.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialOutput=t.util.createBuffer(),this._partialBytes=0},e.ofb.prototype.start=function(s){if(!("iv"in s))throw new Error("Invalid IV parameter.");this._iv=n(s.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},e.ofb.prototype.encrypt=function(s,o,a){var c=s.length();if(s.length()===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&c>=this.blockSize){for(var l=0;l<this._ints;++l)o.putInt32(s.getInt32()^this._outBlock[l]),this._inBlock[l]=this._outBlock[l];return}var u=(this.blockSize-c)%this.blockSize;u>0&&(u=this.blockSize-u),this._partialOutput.clear();for(var l=0;l<this._ints;++l)this._partialOutput.putInt32(s.getInt32()^this._outBlock[l]);if(u>0)s.read-=this.blockSize;else for(var l=0;l<this._ints;++l)this._inBlock[l]=this._outBlock[l];if(this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),u>0&&!a)return o.putBytes(this._partialOutput.getBytes(u-this._partialBytes)),this._partialBytes=u,!0;o.putBytes(this._partialOutput.getBytes(c-this._partialBytes)),this._partialBytes=0},e.ofb.prototype.decrypt=e.ofb.prototype.encrypt,e.ctr=function(s){s=s||{},this.name="CTR",this.cipher=s.cipher,this.blockSize=s.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialOutput=t.util.createBuffer(),this._partialBytes=0},e.ctr.prototype.start=function(s){if(!("iv"in s))throw new Error("Invalid IV parameter.");this._iv=n(s.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},e.ctr.prototype.encrypt=function(s,o,a){var c=s.length();if(c===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&c>=this.blockSize)for(var l=0;l<this._ints;++l)o.putInt32(s.getInt32()^this._outBlock[l]);else{var u=(this.blockSize-c)%this.blockSize;u>0&&(u=this.blockSize-u),this._partialOutput.clear();for(var l=0;l<this._ints;++l)this._partialOutput.putInt32(s.getInt32()^this._outBlock[l]);if(u>0&&(s.read-=this.blockSize),this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),u>0&&!a)return o.putBytes(this._partialOutput.getBytes(u-this._partialBytes)),this._partialBytes=u,!0;o.putBytes(this._partialOutput.getBytes(c-this._partialBytes)),this._partialBytes=0}i(this._inBlock)},e.ctr.prototype.decrypt=e.ctr.prototype.encrypt,e.gcm=function(s){s=s||{},this.name="GCM",this.cipher=s.cipher,this.blockSize=s.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints),this._partialOutput=t.util.createBuffer(),this._partialBytes=0,this._R=3774873600},e.gcm.prototype.start=function(s){if(!("iv"in s))throw new Error("Invalid IV parameter.");var o=t.util.createBuffer(s.iv);this._cipherLength=0;var a;if("additionalData"in s?a=t.util.createBuffer(s.additionalData):a=t.util.createBuffer(),"tagLength"in s?this._tagLength=s.tagLength:this._tagLength=128,this._tag=null,s.decrypt&&(this._tag=t.util.createBuffer(s.tag).getBytes(),this._tag.length!==this._tagLength/8))throw new Error("Authentication tag does not match tag length.");this._hashBlock=new Array(this._ints),this.tag=null,this._hashSubkey=new Array(this._ints),this.cipher.encrypt([0,0,0,0],this._hashSubkey),this.componentBits=4,this._m=this.generateHashTable(this._hashSubkey,this.componentBits);var c=o.length();if(c===12)this._j0=[o.getInt32(),o.getInt32(),o.getInt32(),1];else{for(this._j0=[0,0,0,0];o.length()>0;)this._j0=this.ghash(this._hashSubkey,this._j0,[o.getInt32(),o.getInt32(),o.getInt32(),o.getInt32()]);this._j0=this.ghash(this._hashSubkey,this._j0,[0,0].concat(r(c*8)))}this._inBlock=this._j0.slice(0),i(this._inBlock),this._partialBytes=0,a=t.util.createBuffer(a),this._aDataLength=r(a.length()*8);var l=a.length()%this.blockSize;for(l&&a.fillWithByte(0,this.blockSize-l),this._s=[0,0,0,0];a.length()>0;)this._s=this.ghash(this._hashSubkey,this._s,[a.getInt32(),a.getInt32(),a.getInt32(),a.getInt32()])},e.gcm.prototype.encrypt=function(s,o,a){var c=s.length();if(c===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&c>=this.blockSize){for(var l=0;l<this._ints;++l)o.putInt32(this._outBlock[l]^=s.getInt32());this._cipherLength+=this.blockSize}else{var u=(this.blockSize-c)%this.blockSize;u>0&&(u=this.blockSize-u),this._partialOutput.clear();for(var l=0;l<this._ints;++l)this._partialOutput.putInt32(s.getInt32()^this._outBlock[l]);if(u<=0||a){if(a){var h=c%this.blockSize;this._cipherLength+=h,this._partialOutput.truncate(this.blockSize-h)}else this._cipherLength+=this.blockSize;for(var l=0;l<this._ints;++l)this._outBlock[l]=this._partialOutput.getInt32();this._partialOutput.read-=this.blockSize}if(this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),u>0&&!a)return s.read-=this.blockSize,o.putBytes(this._partialOutput.getBytes(u-this._partialBytes)),this._partialBytes=u,!0;o.putBytes(this._partialOutput.getBytes(c-this._partialBytes)),this._partialBytes=0}this._s=this.ghash(this._hashSubkey,this._s,this._outBlock),i(this._inBlock)},e.gcm.prototype.decrypt=function(s,o,a){var c=s.length();if(c<this.blockSize&&!(a&&c>0))return!0;this.cipher.encrypt(this._inBlock,this._outBlock),i(this._inBlock),this._hashBlock[0]=s.getInt32(),this._hashBlock[1]=s.getInt32(),this._hashBlock[2]=s.getInt32(),this._hashBlock[3]=s.getInt32(),this._s=this.ghash(this._hashSubkey,this._s,this._hashBlock);for(var l=0;l<this._ints;++l)o.putInt32(this._outBlock[l]^this._hashBlock[l]);c<this.blockSize?this._cipherLength+=c%this.blockSize:this._cipherLength+=this.blockSize},e.gcm.prototype.afterFinish=function(s,o){var a=!0;o.decrypt&&o.overflow&&s.truncate(this.blockSize-o.overflow),this.tag=t.util.createBuffer();var c=this._aDataLength.concat(r(this._cipherLength*8));this._s=this.ghash(this._hashSubkey,this._s,c);var l=[];this.cipher.encrypt(this._j0,l);for(var u=0;u<this._ints;++u)this.tag.putInt32(this._s[u]^l[u]);return this.tag.truncate(this.tag.length()%(this._tagLength/8)),o.decrypt&&this.tag.bytes()!==this._tag&&(a=!1),a},e.gcm.prototype.multiply=function(s,o){for(var a=[0,0,0,0],c=o.slice(0),l=0;l<128;++l){var u=s[l/32|0]&1<<31-l%32;u&&(a[0]^=c[0],a[1]^=c[1],a[2]^=c[2],a[3]^=c[3]),this.pow(c,c)}return a},e.gcm.prototype.pow=function(s,o){for(var a=s[3]&1,c=3;c>0;--c)o[c]=s[c]>>>1|(s[c-1]&1)<<31;o[0]=s[0]>>>1,a&&(o[0]^=this._R)},e.gcm.prototype.tableMultiply=function(s){for(var o=[0,0,0,0],a=0;a<32;++a){var c=a/8|0,l=s[c]>>>(7-a%8)*4&15,u=this._m[a][l];o[0]^=u[0],o[1]^=u[1],o[2]^=u[2],o[3]^=u[3]}return o},e.gcm.prototype.ghash=function(s,o,a){return o[0]^=a[0],o[1]^=a[1],o[2]^=a[2],o[3]^=a[3],this.tableMultiply(o)},e.gcm.prototype.generateHashTable=function(s,o){for(var a=8/o,c=4*a,l=16*a,u=new Array(l),h=0;h<l;++h){var d=[0,0,0,0],p=h/c|0,m=(c-1-h%c)*o;d[p]=1<<o-1<<m,u[h]=this.generateSubHashTable(this.multiply(d,s),o)}return u},e.gcm.prototype.generateSubHashTable=function(s,o){var a=1<<o,c=a>>>1,l=new Array(a);l[c]=s.slice(0);for(var u=c>>>1;u>0;)this.pow(l[2*u],l[u]=[]),u>>=1;for(u=2;u<c;){for(var h=1;h<u;++h){var d=l[u],p=l[h];l[u+h]=[d[0]^p[0],d[1]^p[1],d[2]^p[2],d[3]^p[3]]}u*=2}for(l[0]=[0,0,0,0],u=c+1;u<a;++u){var m=l[u^c];l[u]=[s[0]^m[0],s[1]^m[1],s[2]^m[2],s[3]^m[3]]}return l};function n(s,o){if(typeof s=="string"&&(s=t.util.createBuffer(s)),t.util.isArray(s)&&s.length>4){var a=s;s=t.util.createBuffer();for(var c=0;c<a.length;++c)s.putByte(a[c])}if(s.length()<o)throw new Error("Invalid IV length; got "+s.length()+" bytes and expected "+o+" bytes.");if(!t.util.isArray(s)){for(var l=[],u=o/4,c=0;c<u;++c)l.push(s.getInt32());s=l}return s}function i(s){s[s.length-1]=s[s.length-1]+1&4294967295}function r(s){return[s/4294967296|0,s&4294967295]}return nG.exports}var iG,$ue;function Dv(){if($ue)return iG;$ue=1;var t=mr();tG(),Xue(),cs(),iG=t.aes=t.aes||{},t.aes.startEncrypting=function(p,m,g,y){var A=d({key:p,output:g,decrypt:!1,mode:y});return A.start(m),A},t.aes.createEncryptionCipher=function(p,m){return d({key:p,output:null,decrypt:!1,mode:m})},t.aes.startDecrypting=function(p,m,g,y){var A=d({key:p,output:g,decrypt:!0,mode:y});return A.start(m),A},t.aes.createDecryptionCipher=function(p,m){return d({key:p,output:null,decrypt:!0,mode:m})},t.aes.Algorithm=function(p,m){n||l();var g=this;g.name=p,g.mode=new m({blockSize:16,cipher:{encrypt:function(y,A){return h(g._w,y,A,!1)},decrypt:function(y,A){return h(g._w,y,A,!0)}}}),g._init=!1},t.aes.Algorithm.prototype.initialize=function(p){if(!this._init){var m=p.key,g;if(typeof m=="string"&&(m.length===16||m.length===24||m.length===32))m=t.util.createBuffer(m);else if(t.util.isArray(m)&&(m.length===16||m.length===24||m.length===32)){g=m,m=t.util.createBuffer();for(var y=0;y<g.length;++y)m.putByte(g[y])}if(!t.util.isArray(m)){g=m,m=[];var A=g.length();if(A===16||A===24||A===32){A=A>>>2;for(var y=0;y<A;++y)m.push(g.getInt32())}}if(!t.util.isArray(m)||!(m.length===4||m.length===6||m.length===8))throw new Error("Invalid key parameter.");var v=this.mode.name,x=["CFB","OFB","CTR","GCM"].indexOf(v)!==-1;this._w=u(m,p.decrypt&&!x),this._init=!0}},t.aes._expandKey=function(p,m){return n||l(),u(p,m)},t.aes._updateBlock=h,e("AES-ECB",t.cipher.modes.ecb),e("AES-CBC",t.cipher.modes.cbc),e("AES-CFB",t.cipher.modes.cfb),e("AES-OFB",t.cipher.modes.ofb),e("AES-CTR",t.cipher.modes.ctr),e("AES-GCM",t.cipher.modes.gcm);function e(p,m){var g=function(){return new t.aes.Algorithm(p,m)};t.cipher.registerAlgorithm(p,g)}var n=!1,i=4,r,s,o,a,c;function l(){n=!0,o=[0,1,2,4,8,16,32,64,128,27,54];for(var p=new Array(256),m=0;m<128;++m)p[m]=m<<1,p[m+128]=m+128<<1^283;r=new Array(256),s=new Array(256),a=new Array(4),c=new Array(4);for(var m=0;m<4;++m)a[m]=new Array(256),c[m]=new Array(256);for(var g=0,y=0,A,v,x,C,T,S,w,m=0;m<256;++m){C=y^y<<1^y<<2^y<<3^y<<4,C=C>>8^C&255^99,r[g]=C,s[C]=g,T=p[C],A=p[g],v=p[A],x=p[v],S=T<<24^C<<16^C<<8^(C^T),w=(A^v^x)<<24^(g^x)<<16^(g^v^x)<<8^(g^A^x);for(var E=0;E<4;++E)a[E][g]=S,c[E][C]=w,S=S<<24|S>>>8,w=w<<24|w>>>8;g===0?g=y=1:(g=A^p[p[p[A^x]]],y^=p[p[y]])}}function u(p,m){for(var g=p.slice(0),y,A=1,v=g.length,x=v+6+1,C=i*x,T=v;T<C;++T)y=g[T-1],T%v===0?(y=r[y>>>16&255]<<24^r[y>>>8&255]<<16^r[y&255]<<8^r[y>>>24]^o[A]<<24,A++):v>6&&T%v===4&&(y=r[y>>>24]<<24^r[y>>>16&255]<<16^r[y>>>8&255]<<8^r[y&255]),g[T]=g[T-v]^y;if(m){var S,w=c[0],E=c[1],D=c[2],O=c[3],P=g.slice(0);C=g.length;for(var T=0,I=C-i;T<C;T+=i,I-=i)if(T===0||T===C-i)P[T]=g[I],P[T+1]=g[I+3],P[T+2]=g[I+2],P[T+3]=g[I+1];else for(var _=0;_<i;++_)S=g[I+_],P[T+(3&-_)]=w[r[S>>>24]]^E[r[S>>>16&255]]^D[r[S>>>8&255]]^O[r[S&255]];g=P}return g}function h(p,m,g,y){var A=p.length/4-1,v,x,C,T,S;y?(v=c[0],x=c[1],C=c[2],T=c[3],S=s):(v=a[0],x=a[1],C=a[2],T=a[3],S=r);var w,E,D,O,P,I,_;w=m[0]^p[0],E=m[y?3:1]^p[1],D=m[2]^p[2],O=m[y?1:3]^p[3];for(var M=3,L=1;L<A;++L)P=v[w>>>24]^x[E>>>16&255]^C[D>>>8&255]^T[O&255]^p[++M],I=v[E>>>24]^x[D>>>16&255]^C[O>>>8&255]^T[w&255]^p[++M],_=v[D>>>24]^x[O>>>16&255]^C[w>>>8&255]^T[E&255]^p[++M],O=v[O>>>24]^x[w>>>16&255]^C[E>>>8&255]^T[D&255]^p[++M],w=P,E=I,D=_;g[0]=S[w>>>24]<<24^S[E>>>16&255]<<16^S[D>>>8&255]<<8^S[O&255]^p[++M],g[y?3:1]=S[E>>>24]<<24^S[D>>>16&255]<<16^S[O>>>8&255]<<8^S[w&255]^p[++M],g[2]=S[D>>>24]<<24^S[O>>>16&255]<<16^S[w>>>8&255]<<8^S[E&255]^p[++M],g[y?1:3]=S[O>>>24]<<24^S[w>>>16&255]<<16^S[E>>>8&255]<<8^S[D&255]^p[++M]}function d(p){p=p||{};var m=(p.mode||"CBC").toUpperCase(),g="AES-"+m,y;p.decrypt?y=t.cipher.createDecipher(g,p.key):y=t.cipher.createCipher(g,p.key);var A=y.start;return y.start=function(v,x){var C=null;x instanceof t.util.ByteBuffer&&(C=x,x={}),x=x||{},x.output=C,x.iv=v,A.call(y,x)},y}return iG}var rG={exports:{}},sG={exports:{}},oG={exports:{}},Que;function Rv(){if(Que)return oG.exports;Que=1;var t=mr();t.pki=t.pki||{};var e=oG.exports=t.pki.oids=t.oids=t.oids||{};function n(r,s){e[r]=s,e[s]=r}function i(r,s){e[r]=s}return n("1.2.840.113549.1.1.1","rsaEncryption"),n("1.2.840.113549.1.1.4","md5WithRSAEncryption"),n("1.2.840.113549.1.1.5","sha1WithRSAEncryption"),n("1.2.840.113549.1.1.7","RSAES-OAEP"),n("1.2.840.113549.1.1.8","mgf1"),n("1.2.840.113549.1.1.9","pSpecified"),n("1.2.840.113549.1.1.10","RSASSA-PSS"),n("1.2.840.113549.1.1.11","sha256WithRSAEncryption"),n("1.2.840.113549.1.1.12","sha384WithRSAEncryption"),n("1.2.840.113549.1.1.13","sha512WithRSAEncryption"),n("1.3.101.112","EdDSA25519"),n("1.2.840.10040.4.3","dsa-with-sha1"),n("1.3.14.3.2.7","desCBC"),n("1.3.14.3.2.26","sha1"),n("1.3.14.3.2.29","sha1WithRSASignature"),n("2.16.840.1.101.3.4.2.1","sha256"),n("2.16.840.1.101.3.4.2.2","sha384"),n("2.16.840.1.101.3.4.2.3","sha512"),n("2.16.840.1.101.3.4.2.4","sha224"),n("2.16.840.1.101.3.4.2.5","sha512-224"),n("2.16.840.1.101.3.4.2.6","sha512-256"),n("1.2.840.113549.2.2","md2"),n("1.2.840.113549.2.5","md5"),n("1.2.840.113549.1.7.1","data"),n("1.2.840.113549.1.7.2","signedData"),n("1.2.840.113549.1.7.3","envelopedData"),n("1.2.840.113549.1.7.4","signedAndEnvelopedData"),n("1.2.840.113549.1.7.5","digestedData"),n("1.2.840.113549.1.7.6","encryptedData"),n("1.2.840.113549.1.9.1","emailAddress"),n("1.2.840.113549.1.9.2","unstructuredName"),n("1.2.840.113549.1.9.3","contentType"),n("1.2.840.113549.1.9.4","messageDigest"),n("1.2.840.113549.1.9.5","signingTime"),n("1.2.840.113549.1.9.6","counterSignature"),n("1.2.840.113549.1.9.7","challengePassword"),n("1.2.840.113549.1.9.8","unstructuredAddress"),n("1.2.840.113549.1.9.14","extensionRequest"),n("1.2.840.113549.1.9.20","friendlyName"),n("1.2.840.113549.1.9.21","localKeyId"),n("1.2.840.113549.1.9.22.1","x509Certificate"),n("1.2.840.113549.1.12.10.1.1","keyBag"),n("1.2.840.113549.1.12.10.1.2","pkcs8ShroudedKeyBag"),n("1.2.840.113549.1.12.10.1.3","certBag"),n("1.2.840.113549.1.12.10.1.4","crlBag"),n("1.2.840.113549.1.12.10.1.5","secretBag"),n("1.2.840.113549.1.12.10.1.6","safeContentsBag"),n("1.2.840.113549.1.5.13","pkcs5PBES2"),n("1.2.840.113549.1.5.12","pkcs5PBKDF2"),n("1.2.840.113549.1.12.1.1","pbeWithSHAAnd128BitRC4"),n("1.2.840.113549.1.12.1.2","pbeWithSHAAnd40BitRC4"),n("1.2.840.113549.1.12.1.3","pbeWithSHAAnd3-KeyTripleDES-CBC"),n("1.2.840.113549.1.12.1.4","pbeWithSHAAnd2-KeyTripleDES-CBC"),n("1.2.840.113549.1.12.1.5","pbeWithSHAAnd128BitRC2-CBC"),n("1.2.840.113549.1.12.1.6","pbewithSHAAnd40BitRC2-CBC"),n("1.2.840.113549.2.7","hmacWithSHA1"),n("1.2.840.113549.2.8","hmacWithSHA224"),n("1.2.840.113549.2.9","hmacWithSHA256"),n("1.2.840.113549.2.10","hmacWithSHA384"),n("1.2.840.113549.2.11","hmacWithSHA512"),n("1.2.840.113549.3.7","des-EDE3-CBC"),n("2.16.840.1.101.3.4.1.2","aes128-CBC"),n("2.16.840.1.101.3.4.1.22","aes192-CBC"),n("2.16.840.1.101.3.4.1.42","aes256-CBC"),n("2.5.4.3","commonName"),n("2.5.4.4","surname"),n("2.5.4.5","serialNumber"),n("2.5.4.6","countryName"),n("2.5.4.7","localityName"),n("2.5.4.8","stateOrProvinceName"),n("2.5.4.9","streetAddress"),n("2.5.4.10","organizationName"),n("2.5.4.11","organizationalUnitName"),n("2.5.4.12","title"),n("2.5.4.13","description"),n("2.5.4.15","businessCategory"),n("2.5.4.17","postalCode"),n("2.5.4.42","givenName"),n("2.5.4.65","pseudonym"),n("1.3.6.1.4.1.311.60.2.1.2","jurisdictionOfIncorporationStateOrProvinceName"),n("1.3.6.1.4.1.311.60.2.1.3","jurisdictionOfIncorporationCountryName"),n("2.16.840.1.113730.1.1","nsCertType"),n("2.16.840.1.113730.1.13","nsComment"),i("2.5.29.1","authorityKeyIdentifier"),i("2.5.29.2","keyAttributes"),i("2.5.29.3","certificatePolicies"),i("2.5.29.4","keyUsageRestriction"),i("2.5.29.5","policyMapping"),i("2.5.29.6","subtreesConstraint"),i("2.5.29.7","subjectAltName"),i("2.5.29.8","issuerAltName"),i("2.5.29.9","subjectDirectoryAttributes"),i("2.5.29.10","basicConstraints"),i("2.5.29.11","nameConstraints"),i("2.5.29.12","policyConstraints"),i("2.5.29.13","basicConstraints"),n("2.5.29.14","subjectKeyIdentifier"),n("2.5.29.15","keyUsage"),i("2.5.29.16","privateKeyUsagePeriod"),n("2.5.29.17","subjectAltName"),n("2.5.29.18","issuerAltName"),n("2.5.29.19","basicConstraints"),i("2.5.29.20","cRLNumber"),i("2.5.29.21","cRLReason"),i("2.5.29.22","expirationDate"),i("2.5.29.23","instructionCode"),i("2.5.29.24","invalidityDate"),i("2.5.29.25","cRLDistributionPoints"),i("2.5.29.26","issuingDistributionPoint"),i("2.5.29.27","deltaCRLIndicator"),i("2.5.29.28","issuingDistributionPoint"),i("2.5.29.29","certificateIssuer"),i("2.5.29.30","nameConstraints"),n("2.5.29.31","cRLDistributionPoints"),n("2.5.29.32","certificatePolicies"),i("2.5.29.33","policyMappings"),i("2.5.29.34","policyConstraints"),n("2.5.29.35","authorityKeyIdentifier"),i("2.5.29.36","policyConstraints"),n("2.5.29.37","extKeyUsage"),i("2.5.29.46","freshestCRL"),i("2.5.29.54","inhibitAnyPolicy"),n("1.3.6.1.4.1.11129.2.4.2","timestampList"),n("1.3.6.1.5.5.7.1.1","authorityInfoAccess"),n("1.3.6.1.5.5.7.3.1","serverAuth"),n("1.3.6.1.5.5.7.3.2","clientAuth"),n("1.3.6.1.5.5.7.3.3","codeSigning"),n("1.3.6.1.5.5.7.3.4","emailProtection"),n("1.3.6.1.5.5.7.3.8","timeStamping"),oG.exports}var Kue;function Um(){if(Kue)return sG.exports;Kue=1;var t=mr();cs(),Rv();var e=sG.exports=t.asn1=t.asn1||{};e.Class={UNIVERSAL:0,APPLICATION:64,CONTEXT_SPECIFIC:128,PRIVATE:192},e.Type={NONE:0,BOOLEAN:1,INTEGER:2,BITSTRING:3,OCTETSTRING:4,NULL:5,OID:6,ODESC:7,EXTERNAL:8,REAL:9,ENUMERATED:10,EMBEDDED:11,UTF8:12,ROID:13,SEQUENCE:16,SET:17,PRINTABLESTRING:19,IA5STRING:22,UTCTIME:23,GENERALIZEDTIME:24,BMPSTRING:30},e.maxDepth=256,e.create=function(o,a,c,l,u){if(t.util.isArray(l)){for(var h=[],d=0;d<l.length;++d)l[d]!==void 0&&h.push(l[d]);l=h}var p={tagClass:o,type:a,constructed:c,composed:c||t.util.isArray(l),value:l};return u&&"bitStringContents"in u&&(p.bitStringContents=u.bitStringContents,p.original=e.copy(p)),p},e.copy=function(o,a){var c;if(t.util.isArray(o)){c=[];for(var l=0;l<o.length;++l)c.push(e.copy(o[l],a));return c}return typeof o=="string"?o:(c={tagClass:o.tagClass,type:o.type,constructed:o.constructed,composed:o.composed,value:e.copy(o.value,a)},a&&!a.excludeBitStringContents&&(c.bitStringContents=o.bitStringContents),c)},e.equals=function(o,a,c){if(t.util.isArray(o)){if(!t.util.isArray(a)||o.length!==a.length)return!1;for(var l=0;l<o.length;++l)if(!e.equals(o[l],a[l]))return!1;return!0}if(typeof o!=typeof a)return!1;if(typeof o=="string")return o===a;var u=o.tagClass===a.tagClass&&o.type===a.type&&o.constructed===a.constructed&&o.composed===a.composed&&e.equals(o.value,a.value);return c&&c.includeBitStringContents&&(u=u&&o.bitStringContents===a.bitStringContents),u},e.getBerValueLength=function(o){var a=o.getByte();if(a!==128){var c,l=a&128;return l?c=o.getInt((a&127)<<3):c=a,c}};function n(o,a,c){if(c>a){var l=new Error("Too few bytes to parse DER.");throw l.available=o.length(),l.remaining=a,l.requested=c,l}}var i=function(o,a){var c=o.getByte();if(a--,c!==128){var l,u=c&128;if(!u)l=c;else{var h=c&127;n(o,a,h),l=o.getInt(h<<3)}if(l<0)throw new Error("Negative length: "+l);return l}};e.fromDer=function(o,a){a===void 0&&(a={strict:!0,parseAllBytes:!0,decodeBitStrings:!0}),typeof a=="boolean"&&(a={strict:a,parseAllBytes:!0,decodeBitStrings:!0}),"strict"in a||(a.strict=!0),"parseAllBytes"in a||(a.parseAllBytes=!0),"decodeBitStrings"in a||(a.decodeBitStrings=!0),"maxDepth"in a||(a.maxDepth=e.maxDepth),typeof o=="string"&&(o=t.util.createBuffer(o));var c=o.length(),l=r(o,o.length(),0,a);if(a.parseAllBytes&&o.length()!==0){var u=new Error("Unparsed DER bytes remain after ASN.1 parsing.");throw u.byteCount=c,u.remaining=o.length(),u}return l};function r(o,a,c,l){if(c>=l.maxDepth)throw new Error("ASN.1 parsing error: Max depth exceeded.");var u;n(o,a,2);var h=o.getByte();a--;var d=h&192,p=h&31;u=o.length();var m=i(o,a);if(a-=u-o.length(),m!==void 0&&m>a){if(l.strict){var g=new Error("Too few bytes to read ASN.1 value.");throw g.available=o.length(),g.remaining=a,g.requested=m,g}m=a}var y,A,v=(h&32)===32;if(v)if(y=[],m===void 0)for(;;){if(n(o,a,2),o.bytes(2)==="\0\0"){o.getBytes(2),a-=2;break}u=o.length(),y.push(r(o,a,c+1,l)),a-=u-o.length()}else for(;m>0;)u=o.length(),y.push(r(o,m,c+1,l)),a-=u-o.length(),m-=u-o.length();if(y===void 0&&d===e.Class.UNIVERSAL&&p===e.Type.BITSTRING&&(A=o.bytes(m)),y===void 0&&l.decodeBitStrings&&d===e.Class.UNIVERSAL&&p===e.Type.BITSTRING&&m>1){var x=o.read,C=a,T=0;if(p===e.Type.BITSTRING&&(n(o,a,1),T=o.getByte(),a--),T===0)try{u=o.length();var S={strict:!0,decodeBitStrings:!0},w=r(o,a,c+1,S),E=u-o.length();a-=E,p==e.Type.BITSTRING&&E++;var D=w.tagClass;E===m&&(D===e.Class.UNIVERSAL||D===e.Class.CONTEXT_SPECIFIC)&&(y=[w])}catch{}y===void 0&&(o.read=x,a=C)}if(y===void 0){if(m===void 0){if(l.strict)throw new Error("Non-constructed ASN.1 object of indefinite length.");m=a}if(p===e.Type.BMPSTRING)for(y="";m>0;m-=2)n(o,a,2),y+=String.fromCharCode(o.getInt16()),a-=2;else y=o.getBytes(m),a-=m}var O=A===void 0?null:{bitStringContents:A};return e.create(d,p,v,y,O)}e.toDer=function(o){var a=t.util.createBuffer(),c=o.tagClass|o.type,l=t.util.createBuffer(),u=!1;if("bitStringContents"in o&&(u=!0,o.original&&(u=e.equals(o,o.original))),u)l.putBytes(o.bitStringContents);else if(o.composed){o.constructed?c|=32:l.putByte(0);for(var h=0;h<o.value.length;++h)o.value[h]!==void 0&&l.putBuffer(e.toDer(o.value[h]))}else if(o.type===e.Type.BMPSTRING)for(var h=0;h<o.value.length;++h)l.putInt16(o.value.charCodeAt(h));else o.type===e.Type.INTEGER&&o.value.length>1&&(o.value.charCodeAt(0)===0&&(o.value.charCodeAt(1)&128)===0||o.value.charCodeAt(0)===255&&(o.value.charCodeAt(1)&128)===128)?l.putBytes(o.value.substr(1)):l.putBytes(o.value);if(a.putByte(c),l.length()<=127)a.putByte(l.length()&127);else{var d=l.length(),p="";do p+=String.fromCharCode(d&255),d=d>>>8;while(d>0);a.putByte(p.length|128);for(var h=p.length-1;h>=0;--h)a.putByte(p.charCodeAt(h))}return a.putBuffer(l),a},e.oidToDer=function(o){var a=o.split("."),c=t.util.createBuffer();c.putByte(40*parseInt(a[0],10)+parseInt(a[1],10));for(var l,u,h,d,p=2;p<a.length;++p){if(l=!0,u=[],h=parseInt(a[p],10),h>4294967295)throw new Error("OID value too large; max is 32-bits.");do d=h&127,h=h>>>7,l||(d|=128),u.push(d),l=!1;while(h>0);for(var m=u.length-1;m>=0;--m)c.putByte(u[m])}return c},e.derToOid=function(o){var a;typeof o=="string"&&(o=t.util.createBuffer(o));var c=o.getByte();a=Math.floor(c/40)+"."+c%40;for(var l=0;o.length()>0;){if(l>70368744177663)throw new Error("OID value too large; max is 53-bits.");c=o.getByte(),l=l*128,c&128?l+=c&127:(a+="."+(l+c),l=0)}return a},e.utcTimeToDate=function(o){var a=new Date,c=parseInt(o.substr(0,2),10);c=c>=50?1900+c:2e3+c;var l=parseInt(o.substr(2,2),10)-1,u=parseInt(o.substr(4,2),10),h=parseInt(o.substr(6,2),10),d=parseInt(o.substr(8,2),10),p=0;if(o.length>11){var m=o.charAt(10),g=10;m!=="+"&&m!=="-"&&(p=parseInt(o.substr(10,2),10),g+=2)}if(a.setUTCFullYear(c,l,u),a.setUTCHours(h,d,p,0),g&&(m=o.charAt(g),m==="+"||m==="-")){var y=parseInt(o.substr(g+1,2),10),A=parseInt(o.substr(g+4,2),10),v=y*60+A;v*=6e4,m==="+"?a.setTime(+a-v):a.setTime(+a+v)}return a},e.generalizedTimeToDate=function(o){var a=new Date,c=parseInt(o.substr(0,4),10),l=parseInt(o.substr(4,2),10)-1,u=parseInt(o.substr(6,2),10),h=parseInt(o.substr(8,2),10),d=parseInt(o.substr(10,2),10),p=parseInt(o.substr(12,2),10),m=0,g=0,y=!1;o.charAt(o.length-1)==="Z"&&(y=!0);var A=o.length-5,v=o.charAt(A);if(v==="+"||v==="-"){var x=parseInt(o.substr(A+1,2),10),C=parseInt(o.substr(A+4,2),10);g=x*60+C,g*=6e4,v==="+"&&(g*=-1),y=!0}return o.charAt(14)==="."&&(m=parseFloat(o.substr(14),10)*1e3),y?(a.setUTCFullYear(c,l,u),a.setUTCHours(h,d,p,m),a.setTime(+a+g)):(a.setFullYear(c,l,u),a.setHours(h,d,p,m)),a},e.dateToUtcTime=function(o){if(typeof o=="string")return o;var a="",c=[];c.push((""+o.getUTCFullYear()).substr(2)),c.push(""+(o.getUTCMonth()+1)),c.push(""+o.getUTCDate()),c.push(""+o.getUTCHours()),c.push(""+o.getUTCMinutes()),c.push(""+o.getUTCSeconds());for(var l=0;l<c.length;++l)c[l].length<2&&(a+="0"),a+=c[l];return a+="Z",a},e.dateToGeneralizedTime=function(o){if(typeof o=="string")return o;var a="",c=[];c.push(""+o.getUTCFullYear()),c.push(""+(o.getUTCMonth()+1)),c.push(""+o.getUTCDate()),c.push(""+o.getUTCHours()),c.push(""+o.getUTCMinutes()),c.push(""+o.getUTCSeconds());for(var l=0;l<c.length;++l)c[l].length<2&&(a+="0"),a+=c[l];return a+="Z",a},e.integerToDer=function(o){var a=t.util.createBuffer();if(o>=-128&&o<128)return a.putSignedInt(o,8);if(o>=-32768&&o<32768)return a.putSignedInt(o,16);if(o>=-8388608&&o<8388608)return a.putSignedInt(o,24);if(o>=-2147483648&&o<2147483648)return a.putSignedInt(o,32);var c=new Error("Integer too large; max is 32-bits.");throw c.integer=o,c},e.derToInteger=function(o){typeof o=="string"&&(o=t.util.createBuffer(o));var a=o.length()*8;if(a>32)throw new Error("Integer too large; max is 32-bits.");return o.getSignedInt(a)},e.validate=function(o,a,c,l){var u=!1;if((o.tagClass===a.tagClass||typeof a.tagClass>"u")&&(o.type===a.type||typeof a.type>"u"))if(o.constructed===a.constructed||typeof a.constructed>"u"){if(u=!0,a.value&&t.util.isArray(a.value))for(var h=0,d=0;u&&d<a.value.length;++d){var p=a.value[d];u=!!p.optional;var m=o.value[h];if(!m){p.optional||(u=!1,l&&l.push("["+a.name+'] Missing required element. Expected tag class "'+p.tagClass+'", type "'+p.type+'"'));continue}var g=typeof p.tagClass<"u"&&typeof p.type<"u";if(g&&(m.tagClass!==p.tagClass||m.type!==p.type))if(p.optional){u=!0;continue}else{u=!1,l&&l.push("["+a.name+"] Tag mismatch. Expected ("+p.tagClass+","+p.type+"), got ("+m.tagClass+","+m.type+")");break}var y=e.validate(m,p,c,l);if(y)++h,u=!0;else if(p.optional)u=!0;else{u=!1;break}}if(u&&c&&(a.capture&&(c[a.capture]=o.value),a.captureAsn1&&(c[a.captureAsn1]=o),a.captureBitStringContents&&"bitStringContents"in o&&(c[a.captureBitStringContents]=o.bitStringContents),a.captureBitStringValue&&"bitStringContents"in o))if(o.bitStringContents.length<2)c[a.captureBitStringValue]="";else{var A=o.bitStringContents.charCodeAt(0);if(A!==0)throw new Error("captureBitStringValue only supported for zero unused bits");c[a.captureBitStringValue]=o.bitStringContents.slice(1)}}else l&&l.push("["+a.name+'] Expected constructed "'+a.constructed+'", got "'+o.constructed+'"');else l&&(o.tagClass!==a.tagClass&&l.push("["+a.name+'] Expected tag class "'+a.tagClass+'", got "'+o.tagClass+'"'),o.type!==a.type&&l.push("["+a.name+'] Expected type "'+a.type+'", got "'+o.type+'"'));return u};var s=/[^\\u0000-\\u00ff]/;return e.prettyPrint=function(o,a,c){var l="";a=a||0,c=c||2,a>0&&(l+=`
|