iflow-engine-base-3d 4.0.1 → 4.0.2
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.
|
@@ -4217,7 +4217,7 @@ void main() {
|
|
|
4217
4217
|
|
|
4218
4218
|
}
|
|
4219
4219
|
|
|
4220
|
-
}`;class TU{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(A,t){if(this.texture===null){const e=new Sd(A.texture);(A.depthNear!==t.depthNear||A.depthFar!==t.depthFar)&&(this.depthNear=A.depthNear,this.depthFar=A.depthFar),this.texture=e}}getMesh(A){if(this.texture!==null&&this.mesh===null){const t=A.cameras[0].viewport,e=new $t({vertexShader:WU,fragmentShader:GU,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new bA(new gn(20,20),e)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class KU extends os{constructor(A,t){super();const e=this;let i=null,n=1,o=null,g="local-floor",a=1,r=null,I=null,l=null,h=null,B=null,E=null;const c=typeof XRWebGLBinding<"u",Q=new TU,C={},d=t.getContextAttributes();let M=null,y=null;const w=[],D=[],p=new MA;let f=null,u=null;const Y=new Ce;Y.viewport=new Ct;const b=new Ce;b.viewport=new Ct;const m=[Y,b],T=new yu;let F=null,j=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(BA){let _=w[BA];return _===void 0&&(_=new Zh,w[BA]=_),_.getTargetRaySpace()},this.getControllerGrip=function(BA){let _=w[BA];return _===void 0&&(_=new Zh,w[BA]=_),_.getGripSpace()},this.getHand=function(BA){let _=w[BA];return _===void 0&&(_=new Zh,w[BA]=_),_.getHandSpace()};function X(BA){const _=D.indexOf(BA.inputSource);if(_===-1)return;const G=w[_];G!==void 0&&(G.update(BA.inputSource,BA.frame,r||o),G.dispatchEvent({type:BA.type,data:BA.inputSource}))}function v(){i.removeEventListener("select",X),i.removeEventListener("selectstart",X),i.removeEventListener("selectend",X),i.removeEventListener("squeeze",X),i.removeEventListener("squeezestart",X),i.removeEventListener("squeezeend",X),i.removeEventListener("end",v),i.removeEventListener("inputsourceschange",k);for(let BA=0;BA<w.length;BA++){const _=D[BA];_!==null&&(D[BA]=null,w[BA].disconnect(_))}F=null,j=null,Q.reset();for(const BA in C)delete C[BA];if(A.setRenderTarget(M),B=null,h=null,l=null,i=null,y=null,dA.stop(),e.isPresenting=!1,A.setPixelRatio(f),A.setSize(p.width,p.height,!1),u!==null){const BA=u.camera;BA.fov=u.fov,BA.zoom=u.zoom,BA.updateProjectionMatrix(),u=null}e.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(BA){n=BA,e.isPresenting===!0&&_A("WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(BA){g=BA,e.isPresenting===!0&&_A("WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return r||o},this.setReferenceSpace=function(BA){r=BA},this.getBaseLayer=function(){return h!==null?h:B},this.getBinding=function(){return l===null&&c&&(l=new XRWebGLBinding(i,t)),l},this.getFrame=function(){return E},this.getSession=function(){return i},this.setSession=async function(BA){if(i=BA,i!==null){if(M=A.getRenderTarget(),i.addEventListener("select",X),i.addEventListener("selectstart",X),i.addEventListener("selectend",X),i.addEventListener("squeeze",X),i.addEventListener("squeezestart",X),i.addEventListener("squeezeend",X),i.addEventListener("end",v),i.addEventListener("inputsourceschange",k),d.xrCompatible!==!0&&await t.makeXRCompatible(),f=A.getPixelRatio(),A.getSize(p),c&&"createProjectionLayer"in XRWebGLBinding.prototype){let G=null,x=null,U=null;d.depth&&(U=d.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,G=d.stencil?nn:sn,x=d.stencil?ho:Es);const J={colorFormat:t.RGBA8,depthFormat:U,scaleFactor:n};l=this.getBinding(),h=l.createProjectionLayer(J),i.updateRenderState({layers:[h]}),A.setPixelRatio(1),A.setSize(h.textureWidth,h.textureHeight,!1),y=new pe(h.textureWidth,h.textureHeight,{format:re,type:Bt,depthTexture:new wo(h.textureWidth,h.textureHeight,x,void 0,void 0,void 0,void 0,void 0,void 0,G),stencilBuffer:d.stencil,colorSpace:A.outputColorSpace,samples:d.antialias?4:0,resolveDepthBuffer:h.ignoreDepthValues===!1,resolveStencilBuffer:h.ignoreDepthValues===!1,storeMultisampledDepthBuffer:h.ignoreDepthValues===!1,storeMultisampledStencilBuffer:h.ignoreDepthValues===!1})}else{const G={antialias:d.antialias,alpha:!0,depth:d.depth,stencil:d.stencil,framebufferScaleFactor:n};B=new XRWebGLLayer(i,t,G),i.updateRenderState({baseLayer:B}),A.setPixelRatio(1),A.setSize(B.framebufferWidth,B.framebufferHeight,!1),y=new pe(B.framebufferWidth,B.framebufferHeight,{format:re,type:Bt,colorSpace:A.outputColorSpace,stencilBuffer:d.stencil,resolveDepthBuffer:B.ignoreDepthValues===!1,resolveStencilBuffer:B.ignoreDepthValues===!1,storeMultisampledDepthBuffer:B.ignoreDepthValues===!1,storeMultisampledStencilBuffer:B.ignoreDepthValues===!1})}y.isXRRenderTarget=!0,this.setFoveation(a),r=null,o=await i.requestReferenceSpace(g),dA.setContext(i),dA.start(),e.isPresenting=!0,e.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(i!==null)return i.environmentBlendMode},this.getDepthTexture=function(){return Q.getDepthTexture()};function k(BA){for(let _=0;_<BA.removed.length;_++){const G=BA.removed[_],x=D.indexOf(G);x>=0&&(D[x]=null,w[x].disconnect(G))}for(let _=0;_<BA.added.length;_++){const G=BA.added[_];let x=D.indexOf(G);if(x===-1){for(let J=0;J<w.length;J++)if(J>=D.length){D.push(G),x=J;break}else if(D[J]===null){D[J]=G,x=J;break}if(x===-1)break}const U=w[x];U&&U.connect(G)}}const K=new S,z=new S;function H(BA,_,G){K.setFromMatrixPosition(_.matrixWorld),z.setFromMatrixPosition(G.matrixWorld);const x=K.distanceTo(z),U=_.projectionMatrix.elements,J=G.projectionMatrix.elements,W=U[14]/(U[10]-1),P=U[14]/(U[10]+1),R=(U[9]+1)/U[5],q=(U[9]-1)/U[5],L=(U[8]-1)/U[0],O=(J[8]+1)/J[0],tA=W*L,gA=W*O,hA=x/(-L+O),rA=hA*-L;if(_.matrixWorld.decompose(BA.position,BA.quaternion,BA.scale),BA.translateX(rA),BA.translateZ(hA),BA.matrixWorld.compose(BA.position,BA.quaternion,BA.scale),BA.matrixWorldInverse.copy(BA.matrixWorld).invert(),U[10]===-1)BA.projectionMatrix.copy(_.projectionMatrix),BA.projectionMatrixInverse.copy(_.projectionMatrixInverse);else{const sA=W+hA,GA=P+hA,uA=tA-rA,iA=gA+(x-rA),Z=R*P/GA*sA,IA=q*P/GA*sA;BA.projectionMatrix.makePerspective(uA,iA,Z,IA,sA,GA),BA.projectionMatrixInverse.copy(BA.projectionMatrix).invert()}}function eA(BA,_){_===null?BA.matrixWorld.copy(BA.matrix):BA.matrixWorld.multiplyMatrices(_.matrixWorld,BA.matrix),BA.matrixWorldInverse.copy(BA.matrixWorld).invert()}this.updateCamera=function(BA){if(i===null)return;let _=BA.near,G=BA.far;Q.texture!==null&&(Q.depthNear>0&&(_=Q.depthNear),Q.depthFar>0&&(G=Q.depthFar)),T.near=b.near=Y.near=_,T.far=b.far=Y.far=G,(F!==T.near||j!==T.far)&&(i.updateRenderState({depthNear:T.near,depthFar:T.far}),F=T.near,j=T.far),T.layers.mask=BA.layers.mask|6,Y.layers.mask=T.layers.mask&-5,b.layers.mask=T.layers.mask&-3;const x=BA.parent,U=T.cameras;eA(T,x);for(let J=0;J<U.length;J++)eA(U[J],x);U.length===2?H(T,Y,b):T.projectionMatrix.copy(Y.projectionMatrix),u===null&&BA.isPerspectiveCamera&&(u={camera:BA,fov:BA.fov,zoom:BA.zoom}),nA(BA,T,x)};function nA(BA,_,G){G===null?BA.matrix.copy(_.matrixWorld):(BA.matrix.copy(G.matrixWorld),BA.matrix.invert(),BA.matrix.multiply(_.matrixWorld)),BA.matrix.decompose(BA.position,BA.quaternion,BA.scale),BA.updateMatrixWorld(!0),BA.projectionMatrix.copy(_.projectionMatrix),BA.projectionMatrixInverse.copy(_.projectionMatrixInverse),BA.isPerspectiveCamera&&(BA.fov=Za*2*Math.atan(1/BA.projectionMatrix.elements[5]),BA.zoom=1)}this.getCamera=function(){return T},this.getFoveation=function(){if(!(h===null&&B===null))return a},this.setFoveation=function(BA){a=BA,h!==null&&(h.fixedFoveation=BA),B!==null&&B.fixedFoveation!==void 0&&(B.fixedFoveation=BA)},this.hasDepthSensing=function(){return Q.texture!==null},this.getDepthSensingMesh=function(){return Q.getMesh(T)},this.getCameraTexture=function(BA){return C[BA]};let lA=null;function oA(BA,_){if(I=_.getViewerPose(r||o),E=_,I!==null){const G=I.views;B!==null&&(A.setRenderTargetFramebuffer(y,B.framebuffer),A.setRenderTarget(y));let x=!1;G.length!==T.cameras.length&&(T.cameras.length=0,x=!0);for(let P=0;P<G.length;P++){const R=G[P];let q=null;if(B!==null)q=B.getViewport(R);else{const O=l.getViewSubImage(h,R);q=O.viewport,P===0&&(A.setRenderTargetTextures(y,O.colorTexture,O.depthStencilTexture),A.setRenderTarget(y))}let L=m[P];L===void 0&&(L=new Ce,L.layers.enable(P),L.viewport=new Ct,m[P]=L),L.matrix.fromArray(R.transform.matrix),L.matrix.decompose(L.position,L.quaternion,L.scale),L.projectionMatrix.fromArray(R.projectionMatrix),L.projectionMatrixInverse.copy(L.projectionMatrix).invert(),L.viewport.set(q.x,q.y,q.width,q.height),P===0&&(T.matrix.copy(L.matrix),T.matrix.decompose(T.position,T.quaternion,T.scale)),x===!0&&T.cameras.push(L)}const U=i.enabledFeatures;if(U&&U.includes("depth-sensing")&&i.depthUsage=="gpu-optimized"&&c){l=e.getBinding();const P=l.getDepthInformation(G[0]);P&&P.isValid&&P.texture&&Q.init(P,i.renderState)}if(U&&U.includes("camera-access")&&c){A.state.unbindTexture(),l=e.getBinding();for(let P=0;P<G.length;P++){const R=G[P].camera;if(R){let q=C[R];q||(q=new Sd,C[R]=q);const L=l.getCameraImage(R);q.sourceTexture=L}}}}for(let G=0;G<w.length;G++){const x=D[G],U=w[G];x!==null&&U!==void 0&&U.update(x,_,r||o)}lA&&lA(BA,_),_.detectedPlanes&&e.dispatchEvent({type:"planesdetected",data:_}),E=null}const dA=new Nu;dA.setAnimationLoop(oA),this.setAnimationLoop=function(BA){lA=BA},this.dispose=function(){}}}const jU=new RA,hm=new ht;hm.set(-1,0,0,0,1,0,0,0,1);function RU(s,A){function t(Q,C){Q.matrixAutoUpdate===!0&&Q.updateMatrix(),C.value.copy(Q.matrix)}function e(Q,C){C.color.getRGB(Q.fogColor.value,kw(s)),C.isFog?(Q.fogNear.value=C.near,Q.fogFar.value=C.far):C.isFogExp2&&(Q.fogDensity.value=C.density)}function i(Q,C,d,M,y){C.isNodeMaterial?C.uniformsNeedUpdate=!1:C.isMeshBasicMaterial?n(Q,C):C.isMeshLambertMaterial?(n(Q,C),C.envMap&&(Q.envMapIntensity.value=C.envMapIntensity)):C.isMeshToonMaterial?(n(Q,C),l(Q,C)):C.isMeshPhongMaterial?(n(Q,C),I(Q,C),C.envMap&&(Q.envMapIntensity.value=C.envMapIntensity)):C.isMeshStandardMaterial?(n(Q,C),h(Q,C),C.isMeshPhysicalMaterial&&B(Q,C,y)):C.isMeshMatcapMaterial?(n(Q,C),E(Q,C)):C.isMeshDepthMaterial?n(Q,C):C.isMeshDistanceMaterial?(n(Q,C),c(Q,C)):C.isMeshNormalMaterial?n(Q,C):C.isLineBasicMaterial?(o(Q,C),C.isLineDashedMaterial&&g(Q,C)):C.isPointsMaterial?a(Q,C,d,M):C.isSpriteMaterial?r(Q,C):C.isShadowMaterial?(Q.color.value.copy(C.color),Q.opacity.value=C.opacity):C.isShaderMaterial&&(C.uniformsNeedUpdate=!1)}function n(Q,C){Q.opacity.value=C.opacity,C.color&&Q.diffuse.value.copy(C.color),C.emissive&&Q.emissive.value.copy(C.emissive).multiplyScalar(C.emissiveIntensity),C.map&&(Q.map.value=C.map,t(C.map,Q.mapTransform)),C.alphaMap&&(Q.alphaMap.value=C.alphaMap,t(C.alphaMap,Q.alphaMapTransform)),C.bumpMap&&(Q.bumpMap.value=C.bumpMap,t(C.bumpMap,Q.bumpMapTransform),Q.bumpScale.value=C.bumpScale,C.side===Ne&&(Q.bumpScale.value*=-1)),C.normalMap&&(Q.normalMap.value=C.normalMap,t(C.normalMap,Q.normalMapTransform),Q.normalScale.value.copy(C.normalScale),C.side===Ne&&Q.normalScale.value.negate()),C.displacementMap&&(Q.displacementMap.value=C.displacementMap,t(C.displacementMap,Q.displacementMapTransform),Q.displacementScale.value=C.displacementScale,Q.displacementBias.value=C.displacementBias),C.emissiveMap&&(Q.emissiveMap.value=C.emissiveMap,t(C.emissiveMap,Q.emissiveMapTransform)),C.specularMap&&(Q.specularMap.value=C.specularMap,t(C.specularMap,Q.specularMapTransform)),C.alphaTest>0&&(Q.alphaTest.value=C.alphaTest);const d=A.get(C),M=d.envMap,y=d.envMapRotation;M&&(Q.envMap.value=M,Q.envMapRotation.value.setFromMatrix4(jU.makeRotationFromEuler(y)).transpose(),M.isCubeTexture&&M.isRenderTargetTexture===!1&&Q.envMapRotation.value.premultiply(hm),Q.reflectivity.value=C.reflectivity,Q.ior.value=C.ior,Q.refractionRatio.value=C.refractionRatio),C.lightMap&&(Q.lightMap.value=C.lightMap,Q.lightMapIntensity.value=C.lightMapIntensity,t(C.lightMap,Q.lightMapTransform)),C.aoMap&&(Q.aoMap.value=C.aoMap,Q.aoMapIntensity.value=C.aoMapIntensity,t(C.aoMap,Q.aoMapTransform))}function o(Q,C){Q.diffuse.value.copy(C.color),Q.opacity.value=C.opacity,C.map&&(Q.map.value=C.map,t(C.map,Q.mapTransform))}function g(Q,C){Q.dashSize.value=C.dashSize,Q.totalSize.value=C.dashSize+C.gapSize,Q.scale.value=C.scale}function a(Q,C,d,M){Q.diffuse.value.copy(C.color),Q.opacity.value=C.opacity,Q.size.value=C.size*d,Q.scale.value=M*.5,C.map&&(Q.map.value=C.map,t(C.map,Q.uvTransform)),C.alphaMap&&(Q.alphaMap.value=C.alphaMap,t(C.alphaMap,Q.alphaMapTransform)),C.alphaTest>0&&(Q.alphaTest.value=C.alphaTest)}function r(Q,C){Q.diffuse.value.copy(C.color),Q.opacity.value=C.opacity,Q.rotation.value=C.rotation,C.map&&(Q.map.value=C.map,t(C.map,Q.mapTransform)),C.alphaMap&&(Q.alphaMap.value=C.alphaMap,t(C.alphaMap,Q.alphaMapTransform)),C.alphaTest>0&&(Q.alphaTest.value=C.alphaTest)}function I(Q,C){Q.specular.value.copy(C.specular),Q.shininess.value=Math.max(C.shininess,1e-4)}function l(Q,C){C.gradientMap&&(Q.gradientMap.value=C.gradientMap)}function h(Q,C){Q.metalness.value=C.metalness,C.metalnessMap&&(Q.metalnessMap.value=C.metalnessMap,t(C.metalnessMap,Q.metalnessMapTransform)),Q.roughness.value=C.roughness,C.roughnessMap&&(Q.roughnessMap.value=C.roughnessMap,t(C.roughnessMap,Q.roughnessMapTransform)),C.envMap&&(Q.envMapIntensity.value=C.envMapIntensity)}function B(Q,C,d){Q.ior.value=C.ior,C.sheen>0&&(Q.sheenColor.value.copy(C.sheenColor).multiplyScalar(C.sheen),Q.sheenRoughness.value=C.sheenRoughness,C.sheenColorMap&&(Q.sheenColorMap.value=C.sheenColorMap,t(C.sheenColorMap,Q.sheenColorMapTransform)),C.sheenRoughnessMap&&(Q.sheenRoughnessMap.value=C.sheenRoughnessMap,t(C.sheenRoughnessMap,Q.sheenRoughnessMapTransform))),C.clearcoat>0&&(Q.clearcoat.value=C.clearcoat,Q.clearcoatRoughness.value=C.clearcoatRoughness,C.clearcoatMap&&(Q.clearcoatMap.value=C.clearcoatMap,t(C.clearcoatMap,Q.clearcoatMapTransform)),C.clearcoatRoughnessMap&&(Q.clearcoatRoughnessMap.value=C.clearcoatRoughnessMap,t(C.clearcoatRoughnessMap,Q.clearcoatRoughnessMapTransform)),C.clearcoatNormalMap&&(Q.clearcoatNormalMap.value=C.clearcoatNormalMap,t(C.clearcoatNormalMap,Q.clearcoatNormalMapTransform),Q.clearcoatNormalScale.value.copy(C.clearcoatNormalScale),C.side===Ne&&Q.clearcoatNormalScale.value.negate())),C.dispersion>0&&(Q.dispersion.value=C.dispersion),C.retroreflectivity>0&&(Q.retroreflectivity.value=C.retroreflectivity),C.iridescence>0&&(Q.iridescence.value=C.iridescence,Q.iridescenceIOR.value=C.iridescenceIOR,Q.iridescenceThicknessMinimum.value=C.iridescenceThicknessRange[0],Q.iridescenceThicknessMaximum.value=C.iridescenceThicknessRange[1],C.iridescenceMap&&(Q.iridescenceMap.value=C.iridescenceMap,t(C.iridescenceMap,Q.iridescenceMapTransform)),C.iridescenceThicknessMap&&(Q.iridescenceThicknessMap.value=C.iridescenceThicknessMap,t(C.iridescenceThicknessMap,Q.iridescenceThicknessMapTransform))),C.transmission>0&&(Q.transmission.value=C.transmission,Q.transmissionSamplerMap.value=d.texture,Q.transmissionSamplerSize.value.set(d.width,d.height),C.transmissionMap&&(Q.transmissionMap.value=C.transmissionMap,t(C.transmissionMap,Q.transmissionMapTransform)),Q.thickness.value=C.thickness,C.thicknessMap&&(Q.thicknessMap.value=C.thicknessMap,t(C.thicknessMap,Q.thicknessMapTransform)),Q.attenuationDistance.value=C.attenuationDistance,Q.attenuationColor.value.copy(C.attenuationColor)),C.anisotropy>0&&(Q.anisotropyVector.value.set(C.anisotropy*Math.cos(C.anisotropyRotation),C.anisotropy*Math.sin(C.anisotropyRotation)),C.anisotropyMap&&(Q.anisotropyMap.value=C.anisotropyMap,t(C.anisotropyMap,Q.anisotropyMapTransform))),Q.specularIntensity.value=C.specularIntensity,Q.specularColor.value.copy(C.specularColor),C.specularColorMap&&(Q.specularColorMap.value=C.specularColorMap,t(C.specularColorMap,Q.specularColorMapTransform)),C.specularIntensityMap&&(Q.specularIntensityMap.value=C.specularIntensityMap,t(C.specularIntensityMap,Q.specularIntensityMapTransform))}function E(Q,C){C.matcap&&(Q.matcap.value=C.matcap)}function c(Q,C){const d=A.get(C).light;Q.referencePosition.value.setFromMatrixPosition(d.matrixWorld),Q.nearDistance.value=d.shadow.camera.near,Q.farDistance.value=d.shadow.camera.far}return{refreshFogUniforms:e,refreshMaterialUniforms:i}}function ZU(s,A,t,e){let i={},n={},o=[];const g=s.getParameter(s.MAX_UNIFORM_BUFFER_BINDINGS);function a(y,w){const D=w.program;e.uniformBlockBinding(y,D)}function r(y,w){let D=i[y.id];D===void 0&&(Q(y),D=I(y),i[y.id]=D,y.addEventListener("dispose",d));const p=w.program;e.updateUBOMapping(y,p);const f=A.render.frame;n[y.id]!==f&&(h(y),n[y.id]=f)}function I(y){const w=l();y.__bindingPointIndex=w;const D=s.createBuffer(),p=y.__size,f=y.usage;return s.bindBuffer(s.UNIFORM_BUFFER,D),s.bufferData(s.UNIFORM_BUFFER,p,f),s.bindBuffer(s.UNIFORM_BUFFER,null),s.bindBufferBase(s.UNIFORM_BUFFER,w,D),D}function l(){for(let y=0;y<g;y++)if(o.indexOf(y)===-1)return o.push(y),y;return gt("WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function h(y){const w=i[y.id],D=y.uniforms,p=y.__cache;s.bindBuffer(s.UNIFORM_BUFFER,w);for(let f=0,u=D.length;f<u;f++){const Y=D[f];if(Array.isArray(Y))for(let b=0,m=Y.length;b<m;b++)B(Y[b],f,b,p);else B(Y,f,0,p)}s.bindBuffer(s.UNIFORM_BUFFER,null)}function B(y,w,D,p){if(c(y,w,D,p)===!0){const f=y.__offset,u=y.value;if(Array.isArray(u)){let Y=0;for(let b=0;b<u.length;b++){const m=u[b],T=C(m);E(m,y.__data,Y),typeof m!="number"&&typeof m!="boolean"&&!m.isMatrix3&&!ArrayBuffer.isView(m)&&(Y+=T.storage/Float32Array.BYTES_PER_ELEMENT)}}else E(u,y.__data,0);s.bufferSubData(s.UNIFORM_BUFFER,f,y.__data)}}function E(y,w,D){typeof y=="number"||typeof y=="boolean"?w[0]=y:y.isMatrix3?(w[0]=y.elements[0],w[1]=y.elements[1],w[2]=y.elements[2],w[3]=0,w[4]=y.elements[3],w[5]=y.elements[4],w[6]=y.elements[5],w[7]=0,w[8]=y.elements[6],w[9]=y.elements[7],w[10]=y.elements[8],w[11]=0):ArrayBuffer.isView(y)?w.set(new y.constructor(y.buffer,y.byteOffset,w.length)):y.toArray(w,D)}function c(y,w,D,p){const f=y.value,u=w+"_"+D;if(p[u]===void 0)return typeof f=="number"||typeof f=="boolean"?p[u]=f:ArrayBuffer.isView(f)?p[u]=f.slice():p[u]=f.clone(),!0;{const Y=p[u];if(typeof f=="number"||typeof f=="boolean"){if(Y!==f)return p[u]=f,!0}else{if(ArrayBuffer.isView(f))return!0;if(Y.equals(f)===!1)return Y.copy(f),!0}}return!1}function Q(y){const w=y.uniforms;let D=0;const p=16;for(let u=0,Y=w.length;u<Y;u++){const b=Array.isArray(w[u])?w[u]:[w[u]];for(let m=0,T=b.length;m<T;m++){const F=b[m],j=Array.isArray(F.value)?F.value:[F.value];for(let X=0,v=j.length;X<v;X++){const k=j[X],K=C(k),z=D%p,H=z%K.boundary,eA=z+H;D+=H,eA!==0&&p-eA<K.storage&&(D+=p-eA),F.__data=new Float32Array(K.storage/Float32Array.BYTES_PER_ELEMENT),F.__offset=D,D+=K.storage}}}const f=D%p;return f>0&&(D+=p-f),y.__size=D,y.__cache={},this}function C(y){const w={boundary:0,storage:0};return typeof y=="number"||typeof y=="boolean"?(w.boundary=4,w.storage=4):y.isVector2?(w.boundary=8,w.storage=8):y.isVector3||y.isColor?(w.boundary=16,w.storage=12):y.isVector4?(w.boundary=16,w.storage=16):y.isMatrix3?(w.boundary=48,w.storage=48):y.isMatrix4?(w.boundary=64,w.storage=64):y.isTexture?_A("WebGLRenderer: Texture samplers can not be part of an uniforms group."):ArrayBuffer.isView(y)?(w.boundary=16,w.storage=y.byteLength):_A("WebGLRenderer: Unsupported uniform value type.",y),w}function d(y){const w=y.target;w.removeEventListener("dispose",d);const D=o.indexOf(w.__bindingPointIndex);o.splice(D,1),s.deleteBuffer(i[w.id]),delete i[w.id],delete n[w.id]}function M(){for(const y in i)s.deleteBuffer(i[y]);o=[],i={},n={}}return{bind:a,update:r,dispose:M}}const NU=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]);let ln=null;function UU(){return ln===null&&(ln=new wi(NU,16,16,ss,qt),ln.name="DFG_LUT",ln.minFilter=Yt,ln.magFilter=Yt,ln.wrapS=Gi,ln.wrapT=Gi,ln.generateMipmaps=!1,ln.needsUpdate=!0),ln}class AE{constructor(A={}){const{canvas:t=RD(),context:e=null,depth:i=!0,stencil:n=!1,alpha:o=!1,antialias:g=!1,premultipliedAlpha:a=!0,preserveDrawingBuffer:r=!1,powerPreference:I="default",failIfMajorPerformanceCaveat:l=!1,reversedDepthBuffer:h=!1,outputBufferType:B=Bt}=A;this.isWebGLRenderer=!0;let E;if(e!==null){if(typeof WebGLRenderingContext<"u"&&e instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");E=e.getContextAttributes().alpha}else E=o;const c=B,Q=new Set([Bh,lh,EI]),C=new Set([Bt,Es,Bo,ho,rh,Ih]),d=new Uint32Array(4),M=new Int32Array(4),y=new S;let w=null,D=null;const p=[],f=[];let u=null;this.domElement=t,this.debug={checkShaderErrors:!0,diagnostics:{keywords:!1},onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=li,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const Y=this;let b=!1,m=null,T=null,F=null,j=null;this._outputColorSpace=Rt;let X=0,v=0,k=null,K=-1,z=null;const H=new Ct,eA=new Ct;let nA=null;const lA=new XA(0);let oA=0,dA=t.width,BA=t.height,_=1,G=null,x=null;const U=new Ct(0,0,dA,BA),J=new Ct(0,0,dA,BA);let W=!1;const P=new Do;let R=!1,q=!1;const L=new RA,O=new S,tA=new Ct,gA={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let hA=!1;function rA(){return k===null?_:1}let sA=e;function GA($,EA){return t.getContext($,EA)}let uA,iA,Z,IA,cA,yA,jA,NA,fA,YA,JA,OA,xA,kA,At,st,ot,CA,HA,TA,zA,VA,KA;try{const $={alpha:!0,depth:i,stencil:n,antialias:g,premultipliedAlpha:a,preserveDrawingBuffer:r,powerPreference:I,failIfMajorPerformanceCaveat:l};if("setAttribute"in t&&t.setAttribute("data-engine",`three.js r${fa}`),t.addEventListener("webglcontextlost",Qt,!1),t.addEventListener("webglcontextrestored",lt,!1),t.addEventListener("webglcontextcreationerror",Jt,!1),sA===null){const EA="webgl2";if(sA=GA(EA,$),sA===null)throw GA(EA)?new Error("THREE.WebGLRenderer: Error creating WebGL context with your selected attributes."):new Error("THREE.WebGLRenderer: Error creating WebGL context.")}tt()}catch($){throw t.removeEventListener("webglcontextlost",Qt,!1),t.removeEventListener("webglcontextrestored",lt,!1),t.removeEventListener("webglcontextcreationerror",Jt,!1),gt("WebGLRenderer: "+$.message),$}function tt(){uA=new XZ(sA),uA.init(),zA=new Bm(sA,uA),iA=new bZ(sA,uA,A,zA),Z=new FU(sA,uA),iA.reversedDepthBuffer&&h&&Z.buffers.depth.setReversed(!0),T=sA.createFramebuffer(),F=sA.createFramebuffer(),j=sA.createFramebuffer(),IA=new kZ(sA),cA=new cU,yA=new bU(sA,uA,Z,cA,iA,zA,IA),jA=new UZ(Y),NA=new mR(sA),VA=new YZ(sA,NA),fA=new JZ(sA,NA,IA,VA),YA=new HZ(sA,fA,NA,VA,IA),CA=new VZ(sA,iA,yA),At=new WZ(cA),JA=new EU(Y,jA,uA,iA,VA,At),OA=new RU(Y,cA),xA=new dU,kA=new wU(uA),ot=new SZ(Y,jA,Z,YA,E,a),st=new YU(Y,YA,iA),KA=new ZU(sA,IA,iA,Z),HA=new FZ(sA,uA,IA),TA=new xZ(sA,uA,IA),IA.programs=JA.programs,Y.capabilities=iA,Y.extensions=uA,Y.properties=cA,Y.renderLists=xA,Y.shadowMap=st,Y.state=Z,Y.info=IA}c!==Bt&&(u=new LZ(c,t.width,t.height,g,i,n));const qA=new KU(Y,sA);this.xr=qA,this.getContext=function(){return sA},this.getContextAttributes=function(){return sA.getContextAttributes()},this.forceContextLoss=function(){const $=uA.get("WEBGL_lose_context");$&&$.loseContext()},this.forceContextRestore=function(){const $=uA.get("WEBGL_lose_context");$&&$.restoreContext()},this.getPixelRatio=function(){return _},this.setPixelRatio=function($){$!==void 0&&(_=$,this.setSize(dA,BA,!1))},this.getSize=function($){return $.set(dA,BA)},this.setSize=function($,EA,mA=!0){if(qA.isPresenting){_A("WebGLRenderer: Can't change size while VR device is presenting.");return}dA=$,BA=EA,t.width=Math.floor($*_),t.height=Math.floor(EA*_),mA===!0&&(t.style.width=$+"px",t.style.height=EA+"px"),u!==null&&u.setSize(t.width,t.height),this.setViewport(0,0,$,EA)},this.getDrawingBufferSize=function($){return $.set(dA*_,BA*_).floor()},this.setDrawingBufferSize=function($,EA,mA){dA=$,BA=EA,_=mA,t.width=Math.floor($*mA),t.height=Math.floor(EA*mA),this.setViewport(0,0,$,EA)},this.setEffects=function($){if(c===Bt){gt("WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.");return}if($){for(let EA=0;EA<$.length;EA++)if($[EA].isOutputPass===!0){_A("WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.");break}}u.setEffects($||[])},this.getCurrentViewport=function($){return $.copy(H)},this.getViewport=function($){return $.copy(U)},this.setViewport=function($,EA,mA,DA){$.isVector4?U.set($.x,$.y,$.z,$.w):U.set($,EA,mA,DA),Z.viewport(H.copy(U).multiplyScalar(_).round())},this.getScissor=function($){return $.copy(J)},this.setScissor=function($,EA,mA,DA){$.isVector4?J.set($.x,$.y,$.z,$.w):J.set($,EA,mA,DA),Z.scissor(eA.copy(J).multiplyScalar(_).round())},this.getScissorTest=function(){return W},this.setScissorTest=function($){Z.setScissorTest(W=$)},this.setOpaqueSort=function($){G=$},this.setTransparentSort=function($){x=$},this.getClearColor=function($){return $.copy(ot.getClearColor())},this.setClearColor=function(){ot.setClearColor(...arguments)},this.getClearAlpha=function(){return ot.getClearAlpha()},this.setClearAlpha=function(){ot.setClearAlpha(...arguments)},this.clear=function($=!0,EA=!0,mA=!0){let DA=0;if($){let wA=!1;if(k!==null){const N=k.texture.format;wA=Q.has(N)}if(wA){const N=k.texture.type,V=C.has(N),AA=ot.getClearColor(),aA=ot.getClearAlpha(),pA=AA.r,FA=AA.g,UA=AA.b;V?(d[0]=pA,d[1]=FA,d[2]=UA,d[3]=aA,sA.clearBufferuiv(sA.COLOR,0,d)):(M[0]=pA,M[1]=FA,M[2]=UA,M[3]=aA,sA.clearBufferiv(sA.COLOR,0,M))}else DA|=sA.COLOR_BUFFER_BIT}EA&&(DA|=sA.DEPTH_BUFFER_BIT,this.state.buffers.depth.setMask(!0)),mA&&(DA|=sA.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),DA!==0&&sA.clear(DA)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.setNodesHandler=function($){$.setRenderer(this),m=$},this.dispose=function(){t.removeEventListener("webglcontextlost",Qt,!1),t.removeEventListener("webglcontextrestored",lt,!1),t.removeEventListener("webglcontextcreationerror",Jt,!1),ot.dispose(),xA.dispose(),kA.dispose(),cA.dispose(),jA.dispose(),YA.dispose(),VA.dispose(),KA.dispose(),JA.dispose(),qA.dispose(),qA.removeEventListener("sessionstart",Fe),qA.removeEventListener("sessionend",Re),ne.stop()};function Qt($){$.preventDefault(),YI("WebGLRenderer: Context Lost."),b=!0}function lt(){YI("WebGLRenderer: Context Restored."),b=!1;const $=IA.autoReset,EA=st.enabled,mA=st.autoUpdate,DA=st.needsUpdate,wA=st.type;tt(),IA.autoReset=$,st.enabled=EA,st.autoUpdate=mA,st.needsUpdate=DA,st.type=wA}function Jt($){gt("WebGLRenderer: A WebGL context could not be created. Reason: ",$.statusMessage)}function Ht($){const EA=$.target;EA.removeEventListener("dispose",Ht),He(EA)}function He($){Oe($),cA.remove($)}function Oe($){const EA=cA.get($).programs;EA!==void 0&&(EA.forEach(function(mA){JA.releaseProgram(mA)}),$.isShaderMaterial&&JA.releaseShaderCache($))}this.renderBufferDirect=function($,EA,mA,DA,wA,N){EA===null&&(EA=gA);const V=wA.isMesh&&wA.matrixWorld.determinantAffine()<0,AA=Vp($,EA,mA,DA,wA);Z.setMaterial(DA,V);let aA=mA.index,pA=1;if(DA.wireframe===!0){if(aA=fA.getWireframeAttribute(mA),aA===void 0)return;pA=2}const FA=mA.drawRange,UA=mA.attributes.position;let WA=FA.start*pA,at=(FA.start+FA.count)*pA;N!==null&&(WA=Math.max(WA,N.start*pA),at=Math.min(at,(N.start+N.count)*pA)),aA!==null?(WA=Math.max(WA,0),at=Math.min(at,aA.count)):UA!=null&&(WA=Math.max(WA,0),at=Math.min(at,UA.count));const St=at-WA;if(St<0||St===1/0)return;VA.setup(wA,DA,AA,mA,aA);let Gt,mt=HA;if(aA!==null&&(Gt=NA.get(aA),mt=TA,mt.setIndex(Gt)),wA.isMesh)DA.wireframe===!0?(Z.setLineWidth(DA.wireframeLinewidth*rA()),mt.setMode(sA.LINES)):mt.setMode(sA.TRIANGLES);else if(wA.isLine){let oe=DA.linewidth;oe===void 0&&(oe=1),Z.setLineWidth(oe*rA()),wA.isLineSegments?mt.setMode(sA.LINES):wA.isLineLoop?mt.setMode(sA.LINE_LOOP):mt.setMode(sA.LINE_STRIP)}else wA.isPoints?mt.setMode(sA.POINTS):wA.isSprite&&mt.setMode(sA.TRIANGLES);if(wA.isBatchedMesh)if(uA.get("WEBGL_multi_draw"))mt.renderMultiDraw(wA._multiDrawStarts,wA._multiDrawCounts,wA._multiDrawCount);else{const oe=wA._multiDrawStarts,it=wA._multiDrawCounts,ie=wA._multiDrawCount,dt=aA?NA.get(aA).bytesPerElement:1,Mi=cA.get(DA).currentProgram.getUniforms();for(let ii=0;ii<ie;ii++)Mi.setValue(sA,"_gl_DrawID",ii),mt.render(oe[ii]/dt,it[ii])}else if(wA.isInstancedMesh)mt.renderInstances(WA,St,wA.count);else if(mA.isInstancedBufferGeometry){const oe=mA._maxInstanceCount!==void 0?mA._maxInstanceCount:1/0,it=Math.min(mA.instanceCount,oe);mt.renderInstances(WA,St,it)}else mt.render(WA,St)};function je($,EA,mA,DA){m!==null&&$.isNodeMaterial&&m.setObject(DA,$),R===!0&&At.setState($,mA,!1),$.transparent===!0&&$.side===Tt&&$.forceSinglePass===!1?($.side=Ne,$.needsUpdate=!0,nI($,EA,DA),$.side=es,$.needsUpdate=!0,nI($,EA,DA),$.side=Tt):nI($,EA,DA)}this.compile=function($,EA,mA=null){mA===null&&(mA=$),m!==null&&m.renderStart($,EA,mA),D=kA.get(mA),D.init(EA),f.push(D),mA.traverseVisible(function(wA){wA.isLight&&wA.layers.test(EA.layers)&&(D.pushLight(wA),wA.castShadow&&D.pushShadow(wA))}),$!==mA&&$.traverseVisible(function(wA){wA.isLight&&wA.layers.test(EA.layers)&&(D.pushLight(wA),wA.castShadow&&D.pushShadow(wA))}),D.setupLights(),m!==null&&m.updateLights(D.state.lightsArray),q=this.localClippingEnabled,R=At.init(this.clippingPlanes,q),R===!0&&At.setGlobalState(this.clippingPlanes,EA),m!==null&&st.render(D.state.shadowsArray,mA,EA);const DA=new Set;return $.traverse(function(wA){if(!(wA.isMesh||wA.isPoints||wA.isLine||wA.isSprite))return;const N=wA.material;if(N)if(Array.isArray(N))for(let V=0;V<N.length;V++){const AA=N[V];je(AA,mA,EA,wA),DA.add(AA)}else je(N,mA,EA,wA),DA.add(N)}),D=f.pop(),m!==null&&m.renderEnd(),DA},this.compileAsync=function($,EA,mA=null){const DA=this.compile($,EA,mA);return new Promise(wA=>{function N(){if(DA.forEach(function(V){const aA=cA.get(V).currentProgram;(aA===void 0||aA.isReady())&&DA.delete(V)}),DA.size===0){wA($);return}setTimeout(N,10)}uA.get("KHR_parallel_shader_compile")!==null?N():setTimeout(N,10)})};let Ye=null;function de($){Ye&&Ye($)}function Fe(){ne.stop()}function Re(){ne.start()}const ne=new Nu;ne.setAnimationLoop(de),typeof self<"u"&&ne.setContext(self),this.setAnimationLoop=function($){Ye=$,qA.setAnimationLoop($),$===null?ne.stop():ne.start()},qA.addEventListener("sessionstart",Fe),qA.addEventListener("sessionend",Re),this.render=function($,EA){if(EA!==void 0&&EA.isCamera!==!0){gt("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(b===!0)return;m!==null&&m.renderStart($,EA);const mA=qA.enabled===!0&&qA.isPresenting===!0,DA=u!==null&&(k===null||mA)&&u.begin(Y,k);if($.matrixWorldAutoUpdate===!0&&$.updateMatrixWorld(),EA.parent===null&&EA.matrixWorldAutoUpdate===!0&&EA.updateMatrixWorld(),qA.enabled===!0&&qA.isPresenting===!0&&(u===null||u.isCompositing()===!1)&&(qA.cameraAutoUpdate===!0&&qA.updateCamera(EA),EA=qA.getCamera()),$.isScene===!0&&$.onBeforeRender(Y,$,EA,k),D=kA.get($,f.length),D.init(EA),D.state.textureUnits=yA.getTextureUnits(),f.push(D),L.multiplyMatrices(EA.projectionMatrix,EA.matrixWorldInverse),P.setFromProjectionMatrix(L,ns,EA.reversedDepth),q=this.localClippingEnabled,R=At.init(this.clippingPlanes,q),w=xA.get($,p.length),w.init(),p.push(w),qA.enabled===!0&&qA.isPresenting===!0){const V=Y.xr.getDepthSensingMesh();V!==null&&VB(V,EA,-1/0,Y.sortObjects)}VB($,EA,0,Y.sortObjects),w.finish(),m!==null&&m.updateLights(D.state.lightsArray),Y.sortObjects===!0&&w.sort(G,x),hA=qA.enabled===!1||qA.isPresenting===!1||qA.hasDepthSensing()===!1,hA&&ot.addToRenderList(w,$),this.info.render.frame++,this.info.autoReset===!0&&this.info.reset(),R===!0&&At.beginShadows();const wA=D.state.shadowsArray;if(st.render(wA,$,EA),R===!0&&At.endShadows(),(DA&&u.hasRenderPass())===!1){const V=w.opaque,AA=w.transmissive;if(D.setupLights(),EA.isArrayCamera){const aA=EA.cameras;if(AA.length>0)for(let pA=0,FA=aA.length;pA<FA;pA++){const UA=aA[pA];PQ(V,AA,$,UA)}hA&&ot.render($);for(let pA=0,FA=aA.length;pA<FA;pA++){const UA=aA[pA];mQ(w,$,UA,UA.viewport)}}else AA.length>0&&PQ(V,AA,$,EA),hA&&ot.render($),mQ(w,$,EA)}k!==null&&v===0&&(yA.updateMultisampleRenderTarget(k),yA.updateRenderTargetMipmap(k)),DA&&u.end(Y),$.isScene===!0&&$.onAfterRender(Y,$,EA),VA.resetDefaultState(),K=-1,z=null,f.pop(),f.length>0?(D=f[f.length-1],yA.setTextureUnits(D.state.textureUnits),R===!0&&At.setGlobalState(Y.clippingPlanes,D.state.camera)):D=null,p.pop(),p.length>0?w=p[p.length-1]:w=null,m!==null&&m.renderEnd()};function VB($,EA,mA,DA){if($.visible===!1)return;if($.layers.test(EA.layers)){if($.isGroup)mA=$.renderOrder;else if($.isLOD)$.autoUpdate===!0&&$.update(EA);else if($.isLightProbeGrid)D.pushLightProbeGrid($);else if($.isLight)D.pushLight($),$.castShadow&&D.pushShadow($);else if($.isSprite){if(!$.frustumCulled||$.intersectsFrustum(P)){DA&&tA.setFromMatrixPosition($.matrixWorld).applyMatrix4(L);const V=YA.update($),AA=$.material;AA.visible&&w.push($,V,AA,mA,tA.z,null,EA)}}else if(($.isMesh||$.isLine||$.isPoints)&&(!$.frustumCulled||$.intersectsFrustum(P))){const V=YA.update($),AA=$.material;if(DA&&($.boundingSphere!==void 0?($.boundingSphere===null&&$.computeBoundingSphere(),tA.copy($.boundingSphere.center)):(V.boundingSphere===null&&V.computeBoundingSphere(),tA.copy(V.boundingSphere.center)),tA.applyMatrix4($.matrixWorld).applyMatrix4(L)),Array.isArray(AA)){const aA=V.groups;for(let pA=0,FA=aA.length;pA<FA;pA++){const UA=aA[pA],WA=AA[UA.materialIndex];WA&&WA.visible&&w.push($,V,WA,mA,tA.z,UA,EA)}}else AA.visible&&w.push($,V,AA,mA,tA.z,null,EA)}}const N=$.children;for(let V=0,AA=N.length;V<AA;V++)VB(N[V],EA,mA,DA)}function mQ($,EA,mA,DA){const{opaque:wA,transmissive:N,transparent:V}=$;D.setupLightsView(mA),R===!0&&At.setGlobalState(Y.clippingPlanes,mA),DA&&Z.viewport(H.copy(DA)),wA.length>0&&tn(wA,EA,mA),N.length>0&&tn(N,EA,mA),V.length>0&&tn(V,EA,mA),Z.buffers.depth.setTest(!0),Z.buffers.depth.setMask(!0),Z.buffers.color.setMask(!0),Z.setPolygonOffset(!1)}function PQ($,EA,mA,DA){if((mA.isScene===!0?mA.overrideMaterial:null)!==null)return;if(D.state.transmissionRenderTarget[DA.id]===void 0){const WA=uA.has("EXT_color_buffer_half_float")||uA.has("EXT_color_buffer_float");D.state.transmissionRenderTarget[DA.id]=new pe(1,1,{generateMipmaps:!0,type:WA?qt:Bt,minFilter:Oi,samples:Math.max(4,iA.samples),stencilBuffer:n,resolveDepthBuffer:!1,resolveStencilBuffer:!1,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!1,colorSpace:ft.workingColorSpace})}const N=D.state.transmissionRenderTarget[DA.id],V=DA.viewport||H;N.setSize(V.z*Y.transmissionResolutionScale,V.w*Y.transmissionResolutionScale);const AA=Y.getRenderTarget(),aA=Y.getActiveCubeFace(),pA=Y.getActiveMipmapLevel();Y.setRenderTarget(N),Y.getClearColor(lA),oA=Y.getClearAlpha(),oA<1&&Y.setClearColor(16777215,.5),Y.clear(),hA&&ot.render(mA);const FA=Y.toneMapping;Y.toneMapping=li;const UA=DA.viewport;if(DA.viewport!==void 0&&(DA.viewport=void 0),D.setupLightsView(DA),R===!0&&At.setGlobalState(Y.clippingPlanes,DA),tn($,mA,DA),yA.updateMultisampleRenderTarget(N),yA.updateRenderTargetMipmap(N),uA.has("WEBGL_multisampled_render_to_texture")===!1){let WA=!1;for(let at=0,St=EA.length;at<St;at++){const Gt=EA[at],{object:mt,geometry:oe,material:it,group:ie}=Gt;if(it.side===Tt&&mt.layers.test(DA.layers)){const dt=it.side;it.side=Ne,it.needsUpdate=!0,SQ(mt,mA,DA,oe,it,ie),it.side=dt,it.needsUpdate=!0,WA=!0}}WA===!0&&(yA.updateMultisampleRenderTarget(N),yA.updateRenderTargetMipmap(N))}Y.setRenderTarget(AA,aA,pA),Y.setClearColor(lA,oA),UA!==void 0&&(DA.viewport=UA),Y.toneMapping=FA}function tn($,EA,mA){const DA=EA.isScene===!0?EA.overrideMaterial:null;for(let wA=0,N=$.length;wA<N;wA++){const V=$[wA],{object:AA,geometry:aA,group:pA}=V;let FA=V.material;FA.allowOverride===!0&&DA!==null&&(FA=DA),AA.layers.test(mA.layers)&&SQ(AA,EA,mA,aA,FA,pA)}}function SQ($,EA,mA,DA,wA,N){m!==null&&wA.isNodeMaterial&&m.setObject($,wA),$.onBeforeRender(Y,EA,mA,DA,wA,N),$.modelViewMatrix.multiplyMatrices(mA.matrixWorldInverse,$.matrixWorld),$.normalMatrix.getNormalMatrix($.modelViewMatrix),wA.onBeforeRender(Y,EA,mA,DA,$,N),wA.transparent===!0&&wA.side===Tt&&wA.forceSinglePass===!1?(wA.side=Ne,wA.needsUpdate=!0,Y.renderBufferDirect(mA,EA,DA,wA,$,N),wA.side=es,wA.needsUpdate=!0,Y.renderBufferDirect(mA,EA,DA,wA,$,N),wA.side=Tt):Y.renderBufferDirect(mA,EA,DA,wA,$,N),$.onAfterRender(Y,EA,mA,DA,wA,N)}function nI($,EA,mA){EA.isScene!==!0&&(EA=gA);const DA=cA.get($),wA=D.state.lights,N=D.state.shadowsArray,V=wA.state.version,AA=JA.getParameters($,wA.state,N,EA,mA,D.state.lightProbeGridArray),aA=JA.getProgramCacheKey(AA);let pA=DA.programs;DA.environment=$.isMeshStandardMaterial||$.isMeshLambertMaterial||$.isMeshPhongMaterial?EA.environment:null,DA.fog=EA.fog;const FA=$.isMeshStandardMaterial||$.isMeshLambertMaterial&&!$.envMap||$.isMeshPhongMaterial&&!$.envMap;DA.envMap=jA.get($.envMap||DA.environment,FA),DA.envMapRotation=DA.environment!==null&&$.envMap===null?EA.environmentRotation:$.envMapRotation,pA===void 0&&($.addEventListener("dispose",Ht),pA=new Map,DA.programs=pA);let UA=pA.get(aA);if(UA!==void 0){if(DA.currentProgram===UA&&DA.lightsStateVersion===V)return FQ($,AA),UA}else AA.uniforms=JA.getUniforms($),m!==null&&$.isNodeMaterial&&m.build($,mA,AA),$.onBeforeCompile(AA,Y),UA=JA.acquireProgram(AA,aA),pA.set(aA,UA),DA.uniforms=AA.uniforms;const WA=DA.uniforms;return(!$.isShaderMaterial&&!$.isRawShaderMaterial||$.clipping===!0)&&(WA.clippingPlanes=At.uniform),FQ($,AA),DA.needsLights=Op($),DA.lightsStateVersion=V,DA.needsLights&&(WA.ambientLightColor.value=wA.state.ambient,WA.lightProbe.value=wA.state.probe,WA.sunLights.value=wA.state.sun,WA.sunLightShadows.value=wA.state.sunShadow,WA.directionalLights.value=wA.state.directional,WA.directionalLightShadows.value=wA.state.directionalShadow,WA.spotLights.value=wA.state.spot,WA.spotLightShadows.value=wA.state.spotShadow,WA.rectAreaLights.value=wA.state.rectArea,WA.ltc_1.value=wA.state.rectAreaLTC1,WA.ltc_2.value=wA.state.rectAreaLTC2,WA.pointLights.value=wA.state.point,WA.pointLightShadows.value=wA.state.pointShadow,WA.hemisphereLights.value=wA.state.hemi,WA.sunShadowMatrix.value=wA.state.sunShadowMatrix,WA.sunShadowCascade.value=wA.state.sunShadowCascade,WA.directionalShadowMatrix.value=wA.state.directionalShadowMatrix,WA.spotLightMatrix.value=wA.state.spotLightMatrix,WA.spotLightMap.value=wA.state.spotLightMap,WA.pointShadowMatrix.value=wA.state.pointShadowMatrix),DA.lightProbeGrid=D.state.lightProbeGridArray.length>0,DA.currentProgram=UA,DA.uniformsList=null,UA}function YQ($){if($.uniformsList===null){const EA=$.currentProgram.getUniforms();$.uniformsList=qC.seqWithValue(EA.seq,$.uniforms)}return $.uniformsList}function FQ($,EA){const mA=cA.get($);mA.outputColorSpace=EA.outputColorSpace,mA.batching=EA.batching,mA.batchingColor=EA.batchingColor,mA.instancing=EA.instancing,mA.instancingColor=EA.instancingColor,mA.instancingMorph=EA.instancingMorph,mA.skinning=EA.skinning,mA.morphTargets=EA.morphTargets,mA.morphNormals=EA.morphNormals,mA.morphColors=EA.morphColors,mA.morphTargetsCount=EA.morphTargetsCount,mA.numClippingPlanes=EA.numClippingPlanes,mA.numIntersection=EA.numClipIntersection,mA.vertexAlphas=EA.vertexAlphas,mA.vertexTangents=EA.vertexTangents,mA.toneMapping=EA.toneMapping}function kp($,EA){if($.length===0)return null;if($.length===1)return $[0].texture!==null?$[0]:null;y.setFromMatrixPosition(EA.matrixWorld);for(let mA=0,DA=$.length;mA<DA;mA++){const wA=$[mA];if(wA.texture!==null&&wA.boundingBox.containsPoint(y))return wA}return null}function Vp($,EA,mA,DA,wA){EA.isScene!==!0&&(EA=gA),yA.resetTextureUnits();const N=EA.fog,V=DA.isMeshStandardMaterial||DA.isMeshLambertMaterial||DA.isMeshPhongMaterial?EA.environment:null,AA=k===null?Y.outputColorSpace:k.isXRRenderTarget===!0?k.texture.colorSpace:ft.workingColorSpace,aA=DA.isMeshStandardMaterial||DA.isMeshLambertMaterial&&!DA.envMap||DA.isMeshPhongMaterial&&!DA.envMap,pA=jA.get(DA.envMap||V,aA),FA=DA.vertexColors===!0&&!!mA.attributes.color&&mA.attributes.color.itemSize===4,UA=!!mA.attributes.tangent&&(!!DA.normalMap||DA.anisotropy>0),WA=!!mA.morphAttributes.position,at=!!mA.morphAttributes.normal,St=!!mA.morphAttributes.color;let Gt=li;DA.toneMapped&&(k===null||k.isXRRenderTarget===!0)&&(Gt=Y.toneMapping);const mt=mA.morphAttributes.position||mA.morphAttributes.normal||mA.morphAttributes.color,oe=mt!==void 0?mt.length:0,it=cA.get(DA),ie=D.state.lights;if(R===!0&&(q===!0||$!==z)){const ge=$===z&&DA.id===K;At.setState(DA,$,ge)}let dt=!1;DA.version===it.__version?(it.needsLights&&it.lightsStateVersion!==ie.state.version||it.outputColorSpace!==AA||wA.isBatchedMesh&&it.batching===!1||!wA.isBatchedMesh&&it.batching===!0||wA.isBatchedMesh&&it.batchingColor===!0&&wA._colorsTexture===null||wA.isBatchedMesh&&it.batchingColor===!1&&wA._colorsTexture!==null||wA.isInstancedMesh&&it.instancing===!1||!wA.isInstancedMesh&&it.instancing===!0||wA.isSkinnedMesh&&it.skinning===!1||!wA.isSkinnedMesh&&it.skinning===!0||wA.isInstancedMesh&&it.instancingColor===!0&&wA.instanceColor===null||wA.isInstancedMesh&&it.instancingColor===!1&&wA.instanceColor!==null||wA.isInstancedMesh&&it.instancingMorph===!0&&wA.morphTexture===null||wA.isInstancedMesh&&it.instancingMorph===!1&&wA.morphTexture!==null||it.envMap!==pA||DA.fog===!0&&it.fog!==N||it.numClippingPlanes!==void 0&&(it.numClippingPlanes!==At.numPlanes||it.numIntersection!==At.numIntersection)||it.vertexAlphas!==FA||it.vertexTangents!==UA||it.morphTargets!==WA||it.morphNormals!==at||it.morphColors!==St||it.toneMapping!==Gt||it.morphTargetsCount!==oe||!!it.lightProbeGrid!=D.state.lightProbeGridArray.length>0)&&(dt=!0):(dt=!0,it.__version=DA.version);let Mi=it.currentProgram;dt===!0&&(Mi=nI(DA,EA,wA),m&&DA.isNodeMaterial&&m.onUpdateProgram(DA,Mi,it));let ii=!1,bs=!1,oI=!1;const _t=Mi.getUniforms(),Ze=it.uniforms;if(Z.useProgram(Mi.program)&&(ii=!0,bs=!0,oI=!0),DA.id!==K&&(K=DA.id,bs=!0),it.needsLights){const ge=kp(D.state.lightProbeGridArray,wA);it.lightProbeGrid!==ge&&(it.lightProbeGrid=ge,bs=!0)}if(ii||z!==$){Z.buffers.depth.getReversed()&&$.reversedDepth!==!0&&($._reversedDepth=!0,$.updateProjectionMatrix()),_t.setValue(sA,"projectionMatrix",$.projectionMatrix),_t.setValue(sA,"viewMatrix",$.matrixWorldInverse);const eg=_t.map.cameraPosition;eg!==void 0&&eg.setValue(sA,O.setFromMatrixPosition($.matrixWorld)),iA.logarithmicDepthBuffer&&_t.setValue(sA,"logDepthBufFC",2/(Math.log($.far+1)/Math.LN2)),(DA.isMeshPhongMaterial||DA.isMeshToonMaterial||DA.isMeshLambertMaterial||DA.isMeshBasicMaterial||DA.isMeshStandardMaterial||DA.isShaderMaterial)&&_t.setValue(sA,"isOrthographic",$.isOrthographicCamera===!0),z!==$&&(z=$,bs=!0,oI=!0)}if(it.needsLights&&(ie.state.sunShadowMap.length>0&&_t.setValue(sA,"sunShadowMap",ie.state.sunShadowMap,yA),ie.state.directionalShadowMap.length>0&&_t.setValue(sA,"directionalShadowMap",ie.state.directionalShadowMap,yA),ie.state.spotShadowMap.length>0&&_t.setValue(sA,"spotShadowMap",ie.state.spotShadowMap,yA),ie.state.pointShadowMap.length>0&&_t.setValue(sA,"pointShadowMap",ie.state.pointShadowMap,yA)),wA.isSkinnedMesh){_t.setOptional(sA,wA,"bindMatrix"),_t.setOptional(sA,wA,"bindMatrixInverse");const ge=wA.skeleton;ge&&(ge.boneTexture===null&&ge.computeBoneTexture(),_t.setValue(sA,"boneTexture",ge.boneTexture,yA))}wA.isBatchedMesh&&(_t.setOptional(sA,wA,"batchingTexture"),_t.setValue(sA,"batchingTexture",wA._matricesTexture,yA),_t.setOptional(sA,wA,"batchingIdTexture"),_t.setValue(sA,"batchingIdTexture",wA._indirectTexture,yA),_t.setOptional(sA,wA,"batchingColorTexture"),wA._colorsTexture!==null&&_t.setValue(sA,"batchingColorTexture",wA._colorsTexture,yA));const tg=mA.morphAttributes;if((tg.position!==void 0||tg.normal!==void 0||tg.color!==void 0)&&CA.update(wA,mA,Mi),(bs||it.receiveShadow!==wA.receiveShadow)&&(it.receiveShadow=wA.receiveShadow,_t.setValue(sA,"receiveShadow",wA.receiveShadow)),(DA.isMeshStandardMaterial||DA.isMeshLambertMaterial||DA.isMeshPhongMaterial)&&DA.envMap===null&&EA.environment!==null&&(Ze.envMapIntensity.value=EA.environmentIntensity),Ze.dfgLUT!==void 0&&(Ze.dfgLUT.value=UU()),bs){if(_t.setValue(sA,"toneMappingExposure",Y.toneMappingExposure),it.needsLights&&Hp(Ze,oI),N&&DA.fog===!0&&OA.refreshFogUniforms(Ze,N),OA.refreshMaterialUniforms(Ze,DA,_,BA,D.state.transmissionRenderTarget[$.id]),it.needsLights&&it.lightProbeGrid){const ge=it.lightProbeGrid;Ze.probesSH.value=ge.texture,Ze.probesMin.value.copy(ge.boundingBox.min),Ze.probesMax.value.copy(ge.boundingBox.max),Ze.probesResolution.value.copy(ge.resolution)}qC.upload(sA,YQ(it),Ze,yA)}if(DA.isShaderMaterial&&DA.uniformsNeedUpdate===!0&&(qC.upload(sA,YQ(it),Ze,yA),DA.uniformsNeedUpdate=!1),DA.isSpriteMaterial&&_t.setValue(sA,"center",wA.center),_t.setValue(sA,"modelViewMatrix",wA.modelViewMatrix),_t.setValue(sA,"normalMatrix",wA.normalMatrix),_t.setValue(sA,"modelMatrix",wA.matrixWorld),DA.uniformsGroups!==void 0){const ge=DA.uniformsGroups;for(let eg=0,gI=ge.length;eg<gI;eg++){const TG=ge[eg];KA.update(TG,Mi),KA.bind(TG,Mi)}}return Mi}function Hp($,EA){$.ambientLightColor.needsUpdate=EA,$.lightProbe.needsUpdate=EA,$.sunLights.needsUpdate=EA,$.sunLightShadows.needsUpdate=EA,$.directionalLights.needsUpdate=EA,$.directionalLightShadows.needsUpdate=EA,$.pointLights.needsUpdate=EA,$.pointLightShadows.needsUpdate=EA,$.spotLights.needsUpdate=EA,$.spotLightShadows.needsUpdate=EA,$.rectAreaLights.needsUpdate=EA,$.hemisphereLights.needsUpdate=EA}function Op($){return $.isMeshLambertMaterial||$.isMeshToonMaterial||$.isMeshPhongMaterial||$.isMeshStandardMaterial||$.isShadowMaterial||$.isShaderMaterial&&$.lights===!0}this.getActiveCubeFace=function(){return X},this.getActiveMipmapLevel=function(){return v},this.getRenderTarget=function(){return k},this.setRenderTargetTextures=function($,EA,mA){const DA=cA.get($);DA.__autoAllocateDepthBuffer=$.resolveDepthBuffer===!1,DA.__autoAllocateDepthBuffer===!1&&(DA.__useRenderToTexture=!1),cA.get($.texture).__webglTexture=EA,cA.get($.depthTexture).__webglTexture=DA.__autoAllocateDepthBuffer?void 0:mA,DA.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function($,EA){const mA=cA.get($);mA.__webglFramebuffer=EA,mA.__useDefaultFramebuffer=EA===void 0},this.setRenderTarget=function($,EA=0,mA=0){k=$,X=EA,v=mA;let DA=null,wA=!1,N=!1;if($){const AA=cA.get($);if(AA.__useDefaultFramebuffer!==void 0){Z.bindFramebuffer(sA.FRAMEBUFFER,AA.__webglFramebuffer),H.copy($.viewport),eA.copy($.scissor),nA=$.scissorTest,Z.viewport(H),Z.scissor(eA),Z.setScissorTest(nA),K=-1;return}else if(AA.__webglFramebuffer===void 0)yA.setupRenderTarget($);else if(AA.__hasExternalTextures)yA.rebindTextures($,cA.get($.texture).__webglTexture,cA.get($.depthTexture).__webglTexture);else if($.depthBuffer){const FA=$.depthTexture;if(AA.__boundDepthTexture!==FA){if(FA!==null&&cA.has(FA)&&($.width!==FA.image.width||$.height!==FA.image.height))throw new Error("THREE.WebGLRenderer: Attached DepthTexture is initialized to the incorrect size.");yA.setupDepthRenderbuffer($)}}const aA=$.texture;(aA.isData3DTexture||aA.isDataArrayTexture||aA.isCompressedArrayTexture)&&(N=!0);const pA=cA.get($).__webglFramebuffer;$.isWebGLCubeRenderTarget?(Array.isArray(pA[EA])?DA=pA[EA][mA]:DA=pA[EA],wA=!0):$.samples>0&&yA.useMultisampledRTT($)===!1?DA=cA.get($).__webglMultisampledFramebuffer:Array.isArray(pA)?DA=pA[mA]:DA=pA,H.copy($.viewport),eA.copy($.scissor),nA=$.scissorTest}else H.copy(U).multiplyScalar(_).floor(),eA.copy(J).multiplyScalar(_).floor(),nA=W;if(mA!==0&&(DA=T),Z.bindFramebuffer(sA.FRAMEBUFFER,DA)&&Z.drawBuffers($,DA),Z.viewport(H),Z.scissor(eA),Z.setScissorTest(nA),wA){const AA=cA.get($.texture);sA.framebufferTexture2D(sA.FRAMEBUFFER,sA.COLOR_ATTACHMENT0,sA.TEXTURE_CUBE_MAP_POSITIVE_X+EA,AA.__webglTexture,mA)}else if(N){const AA=EA;for(let aA=0;aA<$.textures.length;aA++){const pA=cA.get($.textures[aA]);sA.framebufferTextureLayer(sA.FRAMEBUFFER,sA.COLOR_ATTACHMENT0+aA,pA.__webglTexture,mA,AA)}}else if($!==null&&mA!==0){const AA=cA.get($.texture);sA.framebufferTexture2D(sA.FRAMEBUFFER,sA.COLOR_ATTACHMENT0,sA.TEXTURE_2D,AA.__webglTexture,mA)}K=-1};function bQ($){const EA=cA.get($);return(EA.__readFormat!==$.format||EA.__readType!==$.type)&&(EA.__readFormat=$.format,EA.__readType=$.type,EA.__formatReadable=iA.textureFormatReadable($.format),EA.__typeReadable=iA.textureTypeReadable($.type)),EA}this.readRenderTargetPixels=function($,EA,mA,DA,wA,N,V,AA=0){if(!($&&$.isWebGLRenderTarget)){gt("WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let aA=cA.get($).__webglFramebuffer;if($.isWebGLCubeRenderTarget&&V!==void 0&&(aA=aA[V]),aA){Z.bindFramebuffer(sA.FRAMEBUFFER,aA);try{const pA=$.textures[AA],FA=pA.format,UA=pA.type;$.textures.length>1&&sA.readBuffer(sA.COLOR_ATTACHMENT0+AA);const WA=bQ(pA);if(WA.__formatReadable===!1){gt("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(WA.__typeReadable===!1){gt("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}EA>=0&&EA<=$.width-DA&&mA>=0&&mA<=$.height-wA&&sA.readPixels(EA,mA,DA,wA,zA.convert(FA),zA.convert(UA),N)}finally{const pA=k!==null?cA.get(k).__webglFramebuffer:null;Z.bindFramebuffer(sA.FRAMEBUFFER,pA)}}},this.readRenderTargetPixelsAsync=async function($,EA,mA,DA,wA,N,V,AA=0){if(!($&&$.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let aA=cA.get($).__webglFramebuffer;if($.isWebGLCubeRenderTarget&&V!==void 0&&(aA=aA[V]),aA)if(EA>=0&&EA<=$.width-DA&&mA>=0&&mA<=$.height-wA){Z.bindFramebuffer(sA.FRAMEBUFFER,aA);const pA=$.textures[AA],FA=pA.format,UA=pA.type;$.textures.length>1&&sA.readBuffer(sA.COLOR_ATTACHMENT0+AA);const WA=bQ(pA);if(WA.__formatReadable===!1)throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(WA.__typeReadable===!1)throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const at=sA.createBuffer();sA.bindBuffer(sA.PIXEL_PACK_BUFFER,at),sA.bufferData(sA.PIXEL_PACK_BUFFER,N.byteLength,sA.STREAM_READ),sA.readPixels(EA,mA,DA,wA,zA.convert(FA),zA.convert(UA),0),sA.bindBuffer(sA.PIXEL_PACK_BUFFER,null);const St=k!==null?cA.get(k).__webglFramebuffer:null;Z.bindFramebuffer(sA.FRAMEBUFFER,St);const Gt=sA.fenceSync(sA.SYNC_GPU_COMMANDS_COMPLETE,0);return sA.flush(),await TT(sA,Gt,4),sA.bindBuffer(sA.PIXEL_PACK_BUFFER,at),sA.getBufferSubData(sA.PIXEL_PACK_BUFFER,0,N),sA.bindBuffer(sA.PIXEL_PACK_BUFFER,null),sA.deleteBuffer(at),sA.deleteSync(Gt),N}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function($,EA=null,mA=0){const DA=Math.pow(2,-mA),wA=Math.floor($.image.width*DA),N=Math.floor($.image.height*DA),V=EA!==null?EA.x:0,AA=EA!==null?EA.y:0;yA.setTexture2D($,0),sA.copyTexSubImage2D(sA.TEXTURE_2D,mA,0,0,V,AA,wA,N),Z.unbindTexture()},this.copyTextureToTexture=function($,EA,mA=null,DA=null,wA=0,N=0){let V,AA,aA,pA,FA,UA,WA,at,St;const Gt=$.isCompressedTexture?$.mipmaps[N]:$.image;if(mA!==null)V=mA.max.x-mA.min.x,AA=mA.max.y-mA.min.y,aA=mA.isBox3?mA.max.z-mA.min.z:1,pA=mA.min.x,FA=mA.min.y,UA=mA.isBox3?mA.min.z:0;else{const Ze=Math.pow(2,-wA);V=Math.floor(Gt.width*Ze),AA=Math.floor(Gt.height*Ze),$.isDataArrayTexture?aA=Gt.depth:$.isData3DTexture?aA=Math.floor(Gt.depth*Ze):aA=1,pA=0,FA=0,UA=0}DA!==null?(WA=DA.x,at=DA.y,St=DA.z):(WA=0,at=0,St=0);const mt=zA.convert(EA.format),oe=zA.convert(EA.type);let it;EA.isData3DTexture?(yA.setTexture3D(EA,0),it=sA.TEXTURE_3D):EA.isDataArrayTexture||EA.isCompressedArrayTexture?(yA.setTexture2DArray(EA,0),it=sA.TEXTURE_2D_ARRAY):(yA.setTexture2D(EA,0),it=sA.TEXTURE_2D),Z.activeTexture(sA.TEXTURE0),Z.pixelStorei(sA.UNPACK_FLIP_Y_WEBGL,EA.flipY),Z.pixelStorei(sA.UNPACK_PREMULTIPLY_ALPHA_WEBGL,EA.premultiplyAlpha),Z.pixelStorei(sA.UNPACK_ALIGNMENT,EA.unpackAlignment);const ie=Z.getParameter(sA.UNPACK_ROW_LENGTH),dt=Z.getParameter(sA.UNPACK_IMAGE_HEIGHT),Mi=Z.getParameter(sA.UNPACK_SKIP_PIXELS),ii=Z.getParameter(sA.UNPACK_SKIP_ROWS),bs=Z.getParameter(sA.UNPACK_SKIP_IMAGES);Z.pixelStorei(sA.UNPACK_ROW_LENGTH,Gt.width),Z.pixelStorei(sA.UNPACK_IMAGE_HEIGHT,Gt.height),Z.pixelStorei(sA.UNPACK_SKIP_PIXELS,pA),Z.pixelStorei(sA.UNPACK_SKIP_ROWS,FA),Z.pixelStorei(sA.UNPACK_SKIP_IMAGES,UA);const oI=$.isDataArrayTexture||$.isData3DTexture,_t=EA.isDataArrayTexture||EA.isData3DTexture;if($.isDepthTexture){const Ze=cA.get($),tg=cA.get(EA),ge=cA.get(Ze.__renderTarget),eg=cA.get(tg.__renderTarget);Z.bindFramebuffer(sA.READ_FRAMEBUFFER,ge.__webglFramebuffer),Z.bindFramebuffer(sA.DRAW_FRAMEBUFFER,eg.__webglFramebuffer);for(let gI=0;gI<aA;gI++)oI&&(sA.framebufferTextureLayer(sA.READ_FRAMEBUFFER,sA.COLOR_ATTACHMENT0,cA.get($).__webglTexture,wA,UA+gI),sA.framebufferTextureLayer(sA.DRAW_FRAMEBUFFER,sA.COLOR_ATTACHMENT0,cA.get(EA).__webglTexture,N,St+gI)),sA.blitFramebuffer(pA,FA,V,AA,WA,at,V,AA,sA.DEPTH_BUFFER_BIT,sA.NEAREST);Z.bindFramebuffer(sA.READ_FRAMEBUFFER,null),Z.bindFramebuffer(sA.DRAW_FRAMEBUFFER,null)}else if(wA!==0||$.isRenderTargetTexture||cA.has($)){const Ze=cA.get($),tg=cA.get(EA);Z.bindFramebuffer(sA.READ_FRAMEBUFFER,F),Z.bindFramebuffer(sA.DRAW_FRAMEBUFFER,j);for(let ge=0;ge<aA;ge++)oI?sA.framebufferTextureLayer(sA.READ_FRAMEBUFFER,sA.COLOR_ATTACHMENT0,Ze.__webglTexture,wA,UA+ge):sA.framebufferTexture2D(sA.READ_FRAMEBUFFER,sA.COLOR_ATTACHMENT0,sA.TEXTURE_2D,Ze.__webglTexture,wA),_t?sA.framebufferTextureLayer(sA.DRAW_FRAMEBUFFER,sA.COLOR_ATTACHMENT0,tg.__webglTexture,N,St+ge):sA.framebufferTexture2D(sA.DRAW_FRAMEBUFFER,sA.COLOR_ATTACHMENT0,sA.TEXTURE_2D,tg.__webglTexture,N),wA!==0?sA.blitFramebuffer(pA,FA,V,AA,WA,at,V,AA,sA.COLOR_BUFFER_BIT,sA.NEAREST):_t?sA.copyTexSubImage3D(it,N,WA,at,St+ge,pA,FA,V,AA):sA.copyTexSubImage2D(it,N,WA,at,pA,FA,V,AA);Z.bindFramebuffer(sA.READ_FRAMEBUFFER,null),Z.bindFramebuffer(sA.DRAW_FRAMEBUFFER,null)}else _t?$.isDataTexture||$.isData3DTexture?sA.texSubImage3D(it,N,WA,at,St,V,AA,aA,mt,oe,Gt.data):EA.isCompressedArrayTexture?sA.compressedTexSubImage3D(it,N,WA,at,St,V,AA,aA,mt,Gt.data):sA.texSubImage3D(it,N,WA,at,St,V,AA,aA,mt,oe,Gt):$.isDataTexture?sA.texSubImage2D(sA.TEXTURE_2D,N,WA,at,V,AA,mt,oe,Gt.data):$.isCompressedTexture?sA.compressedTexSubImage2D(sA.TEXTURE_2D,N,WA,at,Gt.width,Gt.height,mt,Gt.data):sA.texSubImage2D(sA.TEXTURE_2D,N,WA,at,V,AA,mt,oe,Gt);Z.pixelStorei(sA.UNPACK_ROW_LENGTH,ie),Z.pixelStorei(sA.UNPACK_IMAGE_HEIGHT,dt),Z.pixelStorei(sA.UNPACK_SKIP_PIXELS,Mi),Z.pixelStorei(sA.UNPACK_SKIP_ROWS,ii),Z.pixelStorei(sA.UNPACK_SKIP_IMAGES,bs),N===0&&EA.generateMipmaps&&sA.generateMipmap(it),Z.unbindTexture()},this.initRenderTarget=function($){cA.get($).__webglFramebuffer===void 0&&yA.setupRenderTarget($)},this.initTexture=function($){$.isCubeTexture?yA.setTextureCube($,0):$.isData3DTexture?yA.setTexture3D($,0):$.isDataArrayTexture||$.isCompressedArrayTexture?yA.setTexture2DArray($,0):yA.setTexture2D($,0),Z.unbindTexture()},this.resetState=function(){X=0,v=0,k=null,Z.reset(),VA.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return ns}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(A){this._outputColorSpace=A;const t=this.getContext();t.drawingBufferColorSpace=ft._getDrawingBufferColorSpace(A),t.unpackColorSpace=ft._getUnpackColorSpace()}}const Cm=Object.freeze(Object.defineProperty({__proto__:null,ACESFilmicToneMapping:wa,AddEquation:is,AddOperation:DD,AdditiveAnimationBlendMode:OQ,AdditiveBlending:OB,AgXToneMapping:oh,AlphaFormat:xQ,AlwaysCompare:KD,AlwaysDepth:vB,AlwaysStencilFunc:YD,AmbientLight:hr,AnimationAction:uu,AnimationClip:lr,AnimationLoader:uj,AnimationMixer:I0,AnimationObjectGroup:vj,AnimationUtils:fj,ArcCurve:Sw,ArrayCamera:yu,ArrowHelper:dR,AttachedBindMode:UQ,Audio:pu,AudioAnalyser:Uj,AudioContext:o0,AudioListener:Rj,AudioLoader:Gj,AxesHelper:fR,BackSide:Ne,BasicDepthPacking:PD,BasicShadowMap:xG,BatchedMesh:ud,BezierInterpolant:Au,Bone:gC,BooleanKeyframeTrack:Dg,Box2:Fu,Box3:vA,Box3Helper:cR,BoxGeometry:zt,BoxHelper:ER,BufferAttribute:yt,BufferGeometry:et,BufferGeometryLoader:Cu,ByteType:XQ,Cache:rn,Camera:NC,CameraHelper:CR,CanvasTexture:mw,CapsuleGeometry:MC,CatmullRomCurve3:Kd,CineonToneMapping:sh,CircleGeometry:yC,ClampToEdgeWrapping:Gi,Clock:eR,Color:XA,ColorKeyframeTrack:vd,ColorManagement:ft,Compatibility:ST,CompressedArrayTexture:ww,CompressedCubeTexture:uw,CompressedTexture:sr,CompressedTextureLoader:mj,ConeGeometry:vI,ConstantAlphaFactor:MD,ConstantColorFactor:dD,Controls:Q0,CubeCamera:Mu,CubeDepthTexture:Pw,CubeReflectionMapping:en,CubeRefractionMapping:lo,CubeTexture:zI,CubeTextureLoader:Pj,CubeUVReflectionMapping:ma,CubicBezierCurve:jd,CubicBezierCurve3:Ww,CubicInterpolant:qw,CullFaceBack:KQ,CullFaceFront:oD,CullFaceFrontBack:JG,CullFaceNone:nD,Curve:Ks,CurvePath:Jd,CustomBlending:LB,CustomToneMapping:nh,CylinderGeometry:Je,Cylindrical:iR,Data3DTexture:bI,DataArrayTexture:Th,DataTexture:wi,DataTextureLoader:nu,DataUtils:jI,DecrementStencilOp:nT,DecrementWrapStencilOp:gT,DefaultLoadingManager:qd,DepthFormat:sn,DepthStencilFormat:nn,DepthTexture:wo,DetachedBindMode:wD,DirectionalLight:Zs,DirectionalLightHelper:hR,DiscreteInterpolant:$w,DodecahedronGeometry:pC,DoubleSide:Tt,DstAlphaFactor:aI,DstColorFactor:rI,DynamicCopyUsage:pT,DynamicDrawUsage:cT,DynamicReadUsage:fT,EdgesGeometry:Fd,EllipseCurve:mC,EqualCompare:WD,EqualDepth:qB,EqualStencilFunc:lT,EquirectangularReflectionMapping:ua,EquirectangularRefractionMapping:lI,Euler:Le,EventDispatcher:os,ExternalTexture:Sd,ExtrudeGeometry:or,FileLoader:mi,Float16BufferAttribute:dK,Float32BufferAttribute:$A,FloatType:fe,Fog:Xh,FogExp2:Uh,FramebufferTexture:ZK,FrontSide:es,Frustum:Do,FrustumArray:IC,GLBufferAttribute:tR,GLSL1:wT,GLSL3:zQ,GreaterCompare:GD,GreaterDepth:Ah,GreaterEqualCompare:Wh,GreaterEqualDepth:$B,GreaterEqualStencilFunc:ET,GreaterStencilFunc:hT,GridHelper:lR,Group:Ot,HTMLTexture:NK,HalfFloatType:qt,HemisphereLight:ou,HemisphereLightHelper:IR,IcosahedronGeometry:FC,ImageBitmapLoader:Qu,ImageLoader:al,ImageUtils:kD,IncrementStencilOp:sT,IncrementWrapStencilOp:oT,InstancedBufferAttribute:Un,InstancedBufferGeometry:i0,InstancedInterleavedBuffer:JC,InstancedMesh:ct,Int16BufferAttribute:cK,Int32BufferAttribute:QK,Int8BufferAttribute:hK,IntType:ah,InterleavedBuffer:va,InterleavedBufferAttribute:ji,Interpolant:pg,InterpolateBezier:HQ,InterpolateDiscrete:Ka,InterpolateLinear:ja,InterpolateSmooth:Ph,InterpolationSamplingMode:PT,InterpolationSamplingType:mT,InvertStencilOp:aT,KeepStencilOp:Fh,KeyframeTrack:fs,LOD:sw,LatheGeometry:bC,Layers:jh,LessCompare:bD,LessDepth:_B,LessEqualCompare:bh,LessEqualDepth:Da,LessEqualStencilFunc:BT,LessStencilFunc:IT,Light:Vn,LightProbe:Bu,LightShadow:jC,Line:he,Line3:vi,LineBasicMaterial:se,LineCurve:Rd,LineCurve3:Zd,LineDashedMaterial:zw,LineLoop:er,LineSegments:Bi,LinearFilter:Yt,LinearInterpolant:zd,LinearMipMapLinearFilter:LG,LinearMipMapNearestFilter:OG,LinearMipmapLinearFilter:Oi,LinearMipmapNearestFilter:Sa,LinearSRGBColorSpace:si,LinearToneMapping:eh,LinearTransfer:PI,Loader:hi,LoaderUtils:Ns,LoadingManager:_d,LoopOnce:kQ,LoopPingPong:uD,LoopRepeat:VQ,MOUSE:ig,Material:Ie,MaterialBlending:kG,MaterialLoader:UC,MathUtils:rt,Matrix2:h0,Matrix3:ht,Matrix4:RA,MaxEquation:lD,Mesh:bA,MeshBasicMaterial:Kt,MeshDepthMaterial:Hd,MeshDistanceMaterial:Od,MeshLambertMaterial:Ow,MeshMatcapMaterial:Lw,MeshNormalMaterial:KC,MeshPhongMaterial:Vw,MeshPhysicalMaterial:ds,MeshStandardMaterial:mo,MeshToonMaterial:Hw,MinEquation:ID,MirroredRepeatWrapping:Pa,MixOperation:pD,MultiplyBlending:RQ,MultiplyOperation:II,NearestFilter:xt,NearestMipMapLinearFilter:HG,NearestMipMapNearestFilter:VG,NearestMipmapLinearFilter:ng,NearestMipmapNearestFilter:BI,NeutralToneMapping:sg,NeverCompare:FD,NeverDepth:zB,NeverStencilFunc:rT,NoBlending:ae,NoColorSpace:cs,NoNormalPacking:$G,NoToneMapping:li,NormalAnimationBlendMode:Sh,NormalBlending:pa,NormalGAPacking:tT,NormalRGPacking:AT,NotEqualCompare:TD,NotEqualDepth:th,NotEqualStencilFunc:CT,NumberKeyframeTrack:rr,Object3D:Et,ObjectLoader:bj,ObjectSpaceNormalMap:SD,OctahedronGeometry:Xn,OneFactor:BD,OneMinusConstantAlphaFactor:yD,OneMinusConstantColorFactor:fD,OneMinusDstAlphaFactor:ED,OneMinusDstColorFactor:cD,OneMinusSrcAlphaFactor:NQ,OneMinusSrcColorFactor:CD,OrthographicCamera:ze,PCFShadowMap:Ma,PCFSoftShadowMap:gD,PMREMGenerator:ll,Path:$I,PerspectiveCamera:Ce,Plane:pt,PlaneGeometry:gn,PlaneHelper:QR,PointLight:t0,PointLightHelper:aR,Points:ir,PointsMaterial:QC,PolarGridHelper:BR,PolyhedronGeometry:uo,PositionalAudio:Nj,PropertyBinding:jt,PropertyMixer:wu,QuadraticBezierCurve:Nd,QuadraticBezierCurve3:Ud,Quaternion:wt,QuaternionKeyframeTrack:Ir,QuaternionLinearInterpolant:iu,R11_EAC_Format:fI,RED_GREEN_RGTC2_Format:Ta,RED_RGTC1_Format:DI,REVISION:fa,RG11_EAC_Format:Ga,RGBADepthPacking:vG,RGBAFormat:re,RGBAIntegerFormat:Bh,RGBA_ASTC_10x10_Format:Dh,RGBA_ASTC_10x5_Format:Mh,RGBA_ASTC_10x6_Format:yh,RGBA_ASTC_10x8_Format:ph,RGBA_ASTC_12x10_Format:wh,RGBA_ASTC_12x12_Format:uh,RGBA_ASTC_4x4_Format:co,RGBA_ASTC_5x4_Format:Ch,RGBA_ASTC_5x5_Format:Eh,RGBA_ASTC_6x5_Format:ch,RGBA_ASTC_6x6_Format:ag,RGBA_ASTC_8x5_Format:Qh,RGBA_ASTC_8x6_Format:dh,RGBA_ASTC_8x8_Format:fh,RGBA_BPTC_Format:rg,RGBA_ETC2_EAC_Format:Wa,RGBA_PVRTC_2BPPV1_Format:Fa,RGBA_PVRTC_4BPPV1_Format:gg,RGBA_S3TC_DXT1_Format:Co,RGBA_S3TC_DXT3_Format:cI,RGBA_S3TC_DXT5_Format:Eo,RGBDepthPacking:_G,RGBFormat:Ya,RGBIntegerFormat:zG,RGB_BPTC_SIGNED_Format:mh,RGB_BPTC_UNSIGNED_Format:pI,RGB_ETC1_Format:dI,RGB_ETC2_Format:ba,RGB_PVRTC_2BPPV1_Format:hh,RGB_PVRTC_4BPPV1_Format:QI,RGB_S3TC_DXT1_Format:og,RGDepthPacking:qG,RGFormat:ss,RGIntegerFormat:lh,RawShaderMaterial:TC,Ray:Nn,Raycaster:De,RectAreaLight:lu,RedFormat:on,RedIntegerFormat:EI,ReinhardToneMapping:ih,RenderObjectRefreshType:YT,RenderTarget:td,RenderTarget3D:qj,RepeatWrapping:Ue,ReplaceStencilOp:iT,ReverseSubtractEquation:rD,RingGeometry:gr,SIGNED_R11_EAC_Format:MI,SIGNED_RED_GREEN_RGTC2_Format:uI,SIGNED_RED_RGTC1_Format:wI,SIGNED_RG11_EAC_Format:yI,SRGBColorSpace:Rt,SRGBTransfer:Xt,Scene:GI,ShaderChunk:ut,ShaderLib:Zi,ShaderMaterial:$t,ShadowMaterial:Jw,Shape:Mg,ShapeGeometry:sl,ShapePath:MR,ShapeUtils:js,ShortType:JQ,Skeleton:kI,SkeletonHelper:gR,SkinnedMesh:pd,Source:AK,Sphere:be,SphereGeometry:an,Spherical:Su,SphericalHarmonics3:e0,SplineCurve:Xd,SpotLight:A0,SpotLightHelper:oR,Sprite:JI,SpriteMaterial:Hh,SrcAlphaFactor:ZQ,SrcAlphaSaturateFactor:QD,SrcColorFactor:hD,StaticCopyUsage:yT,StaticDrawUsage:Gh,StaticReadUsage:dT,StereoCamera:Tj,StreamCopyUsage:DT,StreamDrawUsage:QT,StreamReadUsage:MT,StringKeyframeTrack:wg,SubtractEquation:aD,SubtractiveBlending:jQ,TOUCH:XG,TangentSpaceNormalMap:Yn,TetrahedronGeometry:WC,Texture:Ft,TextureLoader:kn,TextureSource:Wn,TextureUtils:uR,Timer:rl,TimestampQuery:uT,TorusGeometry:Jn,TorusKnotGeometry:GC,Triangle:Lt,TriangleFanDrawMode:Yh,TriangleStripDrawMode:LQ,TrianglesDrawMode:mD,TubeGeometry:nl,UVMapping:gh,Uint16BufferAttribute:Bd,Uint32BufferAttribute:hd,Uint8BufferAttribute:CK,Uint8ClampedBufferAttribute:EK,Uniform:l0,UniformsGroup:AR,UniformsLib:LA,UniformsUtils:oi,UnsignedByteType:Bt,UnsignedInt101111Type:CI,UnsignedInt248Type:ho,UnsignedInt5999Type:hI,UnsignedIntType:Es,UnsignedShort4444Type:rh,UnsignedShort5551Type:Ih,UnsignedShortType:Bo,VSMShadowMap:ya,Vector2:MA,Vector3:S,Vector4:Ct,VectorKeyframeTrack:gl,VideoFrameTexture:RK,VideoTexture:Dw,WebGL3DRenderTarget:iK,WebGLArrayRenderTarget:eK,WebGLCoordinateSystem:ns,WebGLCubeRenderTarget:D0,WebGLRenderTarget:pe,WebGLRenderer:AE,WebGLUtils:Bm,WebGPUCoordinateSystem:Bg,WebXRController:Zh,WireframeGeometry:Vd,WrapAroundEnding:mI,ZeroCurvatureEnding:Ig,ZeroFactor:Io,ZeroSlopeEnding:lg,ZeroStencilOp:eT,createCanvasElement:RD,error:gt,getConsoleFunction:GT,log:YI,setConsoleFunction:WT,warn:_A,warnOnce:Fn},Symbol.toStringTag,{value:"Module"}));class XU{engine;scene;constructor(A){this.engine=A,this.scene=new GI;let t=new Ot;t.name="groupEdge",this.scene.add(t)}}var yr=Object.freeze({Linear:Object.freeze({None:function(s){return s},In:function(s){return s},Out:function(s){return s},InOut:function(s){return s}}),Quadratic:Object.freeze({In:function(s){return s*s},Out:function(s){return s*(2-s)},InOut:function(s){return(s*=2)<1?.5*s*s:-.5*(--s*(s-2)-1)}}),Cubic:Object.freeze({In:function(s){return s*s*s},Out:function(s){return--s*s*s+1},InOut:function(s){return(s*=2)<1?.5*s*s*s:.5*((s-=2)*s*s+2)}}),Quartic:Object.freeze({In:function(s){return s*s*s*s},Out:function(s){return 1- --s*s*s*s},InOut:function(s){return(s*=2)<1?.5*s*s*s*s:-.5*((s-=2)*s*s*s-2)}}),Quintic:Object.freeze({In:function(s){return s*s*s*s*s},Out:function(s){return--s*s*s*s*s+1},InOut:function(s){return(s*=2)<1?.5*s*s*s*s*s:.5*((s-=2)*s*s*s*s+2)}}),Sinusoidal:Object.freeze({In:function(s){return 1-Math.sin((1-s)*Math.PI/2)},Out:function(s){return Math.sin(s*Math.PI/2)},InOut:function(s){return .5*(1-Math.sin(Math.PI*(.5-s)))}}),Exponential:Object.freeze({In:function(s){return s===0?0:Math.pow(1024,s-1)},Out:function(s){return s===1?1:1-Math.pow(2,-10*s)},InOut:function(s){return s===0?0:s===1?1:(s*=2)<1?.5*Math.pow(1024,s-1):.5*(-Math.pow(2,-10*(s-1))+2)}}),Circular:Object.freeze({In:function(s){return 1-Math.sqrt(1-s*s)},Out:function(s){return Math.sqrt(1- --s*s)},InOut:function(s){return(s*=2)<1?-.5*(Math.sqrt(1-s*s)-1):.5*(Math.sqrt(1-(s-=2)*s)+1)}}),Elastic:Object.freeze({In:function(s){return s===0?0:s===1?1:-Math.pow(2,10*(s-1))*Math.sin((s-1.1)*5*Math.PI)},Out:function(s){return s===0?0:s===1?1:Math.pow(2,-10*s)*Math.sin((s-.1)*5*Math.PI)+1},InOut:function(s){return s===0?0:s===1?1:(s*=2,s<1?-.5*Math.pow(2,10*(s-1))*Math.sin((s-1.1)*5*Math.PI):.5*Math.pow(2,-10*(s-1))*Math.sin((s-1.1)*5*Math.PI)+1)}}),Back:Object.freeze({In:function(s){var A=1.70158;return s===1?1:s*s*((A+1)*s-A)},Out:function(s){var A=1.70158;return s===0?0:--s*s*((A+1)*s+A)+1},InOut:function(s){var A=2.5949095;return(s*=2)<1?.5*(s*s*((A+1)*s-A)):.5*((s-=2)*s*((A+1)*s+A)+2)}}),Bounce:Object.freeze({In:function(s){return 1-yr.Bounce.Out(1-s)},Out:function(s){return s<1/2.75?7.5625*s*s:s<2/2.75?7.5625*(s-=1.5/2.75)*s+.75:s<2.5/2.75?7.5625*(s-=2.25/2.75)*s+.9375:7.5625*(s-=2.625/2.75)*s+.984375},InOut:function(s){return s<.5?yr.Bounce.In(s*2)*.5:yr.Bounce.Out(s*2-1)*.5+.5}}),generatePow:function(s){return s===void 0&&(s=4),s=s<Number.EPSILON?Number.EPSILON:s,s=s>1e4?1e4:s,{In:function(A){return Math.pow(A,s)},Out:function(A){return 1-Math.pow(1-A,s)},InOut:function(A){return A<.5?Math.pow(A*2,s)/2:(1-Math.pow(2-A*2,s))/2+.5}}}}),Cl=function(){return performance.now()},JU=(function(){function s(){this._tweens={},this._tweensAddedDuringUpdate={}}return s.prototype.getAll=function(){var A=this;return Object.keys(this._tweens).map(function(t){return A._tweens[t]})},s.prototype.removeAll=function(){this._tweens={}},s.prototype.add=function(A){this._tweens[A.getId()]=A,this._tweensAddedDuringUpdate[A.getId()]=A},s.prototype.remove=function(A){delete this._tweens[A.getId()],delete this._tweensAddedDuringUpdate[A.getId()]},s.prototype.update=function(A,t){A===void 0&&(A=Cl()),t===void 0&&(t=!1);var e=Object.keys(this._tweens);if(e.length===0)return!1;for(;e.length>0;){this._tweensAddedDuringUpdate={};for(var i=0;i<e.length;i++){var n=this._tweens[e[i]],o=!t;n&&n.update(A,o)===!1&&!t&&delete this._tweens[e[i]]}e=Object.keys(this._tweensAddedDuringUpdate)}return!0},s})(),S0={Linear:function(s,A){var t=s.length-1,e=t*A,i=Math.floor(e),n=S0.Utils.Linear;return A<0?n(s[0],s[1],e):A>1?n(s[t],s[t-1],t-e):n(s[i],s[i+1>t?t:i+1],e-i)},Utils:{Linear:function(s,A,t){return(A-s)*t+s}}},Em=(function(){function s(){}return s.nextId=function(){return s._nextId++},s._nextId=0,s})(),Y0=new JU,xU=(function(){function s(A,t){t===void 0&&(t=Y0),this._object=A,this._group=t,this._isPaused=!1,this._pauseStart=0,this._valuesStart={},this._valuesEnd={},this._valuesStartRepeat={},this._duration=1e3,this._isDynamic=!1,this._initialRepeat=0,this._repeat=0,this._yoyo=!1,this._isPlaying=!1,this._reversed=!1,this._delayTime=0,this._startTime=0,this._easingFunction=yr.Linear.None,this._interpolationFunction=S0.Linear,this._chainedTweens=[],this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._id=Em.nextId(),this._isChainStopped=!1,this._propertiesAreSetUp=!1,this._goToEnd=!1}return s.prototype.getId=function(){return this._id},s.prototype.isPlaying=function(){return this._isPlaying},s.prototype.isPaused=function(){return this._isPaused},s.prototype.getDuration=function(){return this._duration},s.prototype.to=function(A,t){if(t===void 0&&(t=1e3),this._isPlaying)throw new Error("Can not call Tween.to() while Tween is already started or paused. Stop the Tween first.");return this._valuesEnd=A,this._propertiesAreSetUp=!1,this._duration=t<0?0:t,this},s.prototype.duration=function(A){return A===void 0&&(A=1e3),this._duration=A<0?0:A,this},s.prototype.dynamic=function(A){return A===void 0&&(A=!1),this._isDynamic=A,this},s.prototype.start=function(A,t){if(A===void 0&&(A=Cl()),t===void 0&&(t=!1),this._isPlaying)return this;if(this._group&&this._group.add(this),this._repeat=this._initialRepeat,this._reversed){this._reversed=!1;for(var e in this._valuesStartRepeat)this._swapEndStartRepeatValues(e),this._valuesStart[e]=this._valuesStartRepeat[e]}if(this._isPlaying=!0,this._isPaused=!1,this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._isChainStopped=!1,this._startTime=A,this._startTime+=this._delayTime,!this._propertiesAreSetUp||t){if(this._propertiesAreSetUp=!0,!this._isDynamic){var i={};for(var n in this._valuesEnd)i[n]=this._valuesEnd[n];this._valuesEnd=i}this._setupProperties(this._object,this._valuesStart,this._valuesEnd,this._valuesStartRepeat,t)}return this},s.prototype.startFromCurrentValues=function(A){return this.start(A,!0)},s.prototype._setupProperties=function(A,t,e,i,n){for(var o in e){var g=A[o],a=Array.isArray(g),r=a?"array":typeof g,I=!a&&Array.isArray(e[o]);if(!(r==="undefined"||r==="function")){if(I){var l=e[o];if(l.length===0)continue;for(var h=[g],B=0,E=l.length;B<E;B+=1){var c=this._handleRelativeValue(g,l[B]);if(isNaN(c)){I=!1,console.warn("Found invalid interpolation list. Skipping.");break}h.push(c)}I&&(e[o]=h)}if((r==="object"||a)&&g&&!I){t[o]=a?[]:{};var Q=g;for(var C in Q)t[o][C]=Q[C];i[o]=a?[]:{};var l=e[o];if(!this._isDynamic){var d={};for(var C in l)d[C]=l[C];e[o]=l=d}this._setupProperties(Q,t[o],l,i[o],n)}else(typeof t[o]>"u"||n)&&(t[o]=g),a||(t[o]*=1),I?i[o]=e[o].slice().reverse():i[o]=t[o]||0}}},s.prototype.stop=function(){return this._isChainStopped||(this._isChainStopped=!0,this.stopChainedTweens()),this._isPlaying?(this._group&&this._group.remove(this),this._isPlaying=!1,this._isPaused=!1,this._onStopCallback&&this._onStopCallback(this._object),this):this},s.prototype.end=function(){return this._goToEnd=!0,this.update(1/0),this},s.prototype.pause=function(A){return A===void 0&&(A=Cl()),this._isPaused||!this._isPlaying?this:(this._isPaused=!0,this._pauseStart=A,this._group&&this._group.remove(this),this)},s.prototype.resume=function(A){return A===void 0&&(A=Cl()),!this._isPaused||!this._isPlaying?this:(this._isPaused=!1,this._startTime+=A-this._pauseStart,this._pauseStart=0,this._group&&this._group.add(this),this)},s.prototype.stopChainedTweens=function(){for(var A=0,t=this._chainedTweens.length;A<t;A++)this._chainedTweens[A].stop();return this},s.prototype.group=function(A){return A===void 0&&(A=Y0),this._group=A,this},s.prototype.delay=function(A){return A===void 0&&(A=0),this._delayTime=A,this},s.prototype.repeat=function(A){return A===void 0&&(A=0),this._initialRepeat=A,this._repeat=A,this},s.prototype.repeatDelay=function(A){return this._repeatDelayTime=A,this},s.prototype.yoyo=function(A){return A===void 0&&(A=!1),this._yoyo=A,this},s.prototype.easing=function(A){return A===void 0&&(A=yr.Linear.None),this._easingFunction=A,this},s.prototype.interpolation=function(A){return A===void 0&&(A=S0.Linear),this._interpolationFunction=A,this},s.prototype.chain=function(){for(var A=[],t=0;t<arguments.length;t++)A[t]=arguments[t];return this._chainedTweens=A,this},s.prototype.onStart=function(A){return this._onStartCallback=A,this},s.prototype.onEveryStart=function(A){return this._onEveryStartCallback=A,this},s.prototype.onUpdate=function(A){return this._onUpdateCallback=A,this},s.prototype.onRepeat=function(A){return this._onRepeatCallback=A,this},s.prototype.onComplete=function(A){return this._onCompleteCallback=A,this},s.prototype.onStop=function(A){return this._onStopCallback=A,this},s.prototype.update=function(A,t){var e=this,i;if(A===void 0&&(A=Cl()),t===void 0&&(t=!0),this._isPaused)return!0;var n,o=this._startTime+this._duration;if(!this._goToEnd&&!this._isPlaying){if(A>o)return!1;t&&this.start(A,!0)}if(this._goToEnd=!1,A<this._startTime)return!0;this._onStartCallbackFired===!1&&(this._onStartCallback&&this._onStartCallback(this._object),this._onStartCallbackFired=!0),this._onEveryStartCallbackFired===!1&&(this._onEveryStartCallback&&this._onEveryStartCallback(this._object),this._onEveryStartCallbackFired=!0);var g=A-this._startTime,a=this._duration+((i=this._repeatDelayTime)!==null&&i!==void 0?i:this._delayTime),r=this._duration+this._repeat*a,I=function(){if(e._duration===0||g>r)return 1;var Q=Math.trunc(g/a),C=g-Q*a,d=Math.min(C/e._duration,1);return d===0&&g===e._duration?1:d},l=I(),h=this._easingFunction(l);if(this._updateProperties(this._object,this._valuesStart,this._valuesEnd,h),this._onUpdateCallback&&this._onUpdateCallback(this._object,l),this._duration===0||g>=this._duration)if(this._repeat>0){var B=Math.min(Math.trunc((g-this._duration)/a)+1,this._repeat);isFinite(this._repeat)&&(this._repeat-=B);for(n in this._valuesStartRepeat)!this._yoyo&&typeof this._valuesEnd[n]=="string"&&(this._valuesStartRepeat[n]=this._valuesStartRepeat[n]+parseFloat(this._valuesEnd[n])),this._yoyo&&this._swapEndStartRepeatValues(n),this._valuesStart[n]=this._valuesStartRepeat[n];return this._yoyo&&(this._reversed=!this._reversed),this._startTime+=a*B,this._onRepeatCallback&&this._onRepeatCallback(this._object),this._onEveryStartCallbackFired=!1,!0}else{this._onCompleteCallback&&this._onCompleteCallback(this._object);for(var E=0,c=this._chainedTweens.length;E<c;E++)this._chainedTweens[E].start(this._startTime+this._duration,!1);return this._isPlaying=!1,!1}return!0},s.prototype._updateProperties=function(A,t,e,i){for(var n in e)if(t[n]!==void 0){var o=t[n]||0,g=e[n],a=Array.isArray(A[n]),r=Array.isArray(g),I=!a&&r;I?A[n]=this._interpolationFunction(g,i):typeof g=="object"&&g?this._updateProperties(A[n],o,g,i):(g=this._handleRelativeValue(o,g),typeof g=="number"&&(A[n]=o+(g-o)*i))}},s.prototype._handleRelativeValue=function(A,t){return typeof t!="string"?t:t.charAt(0)==="+"||t.charAt(0)==="-"?A+parseFloat(t):parseFloat(t)},s.prototype._swapEndStartRepeatValues=function(A){var t=this._valuesStartRepeat[A],e=this._valuesEnd[A];typeof e=="string"?this._valuesStartRepeat[A]=this._valuesStartRepeat[A]+parseFloat(e):this._valuesStartRepeat[A]=this._valuesEnd[A],this._valuesEnd[A]=t},s})();Em.nextId;var Bn=Y0;Bn.getAll.bind(Bn),Bn.removeAll.bind(Bn),Bn.add.bind(Bn),Bn.remove.bind(Bn),Bn.update.bind(Bn);var Wg={Easing:yr,Tween:xU};class gi{constructor(A,t,e){this.camera=A,this.renderer=t,this.scene=e,this.raycaster=new De}raycaster;worldToScreenNormalized(A){const t=A.clone();return t.project(this.camera),new MA(t.x,t.y)}worldToScreen(A){const t=new S;return t.copy(A).project(this.camera),t.x=t.x*this.renderer.domElement.clientWidth*.5,t.y=-t.y*this.renderer.domElement.clientHeight*.5,t.z=(t.z+1)*.5,t.x+=this.renderer.domElement.clientWidth*.5,t.y+=this.renderer.domElement.clientHeight*.5,new MA(t.x,t.y)}worldToScreenIfVisible(A){if(this.camera.updateMatrixWorld(!0),this.camera instanceof Ce&&A.clone().applyMatrix4(this.camera.matrixWorldInverse).z>=0)return null;const t=A.clone().project(this.camera);if(!Number.isFinite(t.x)||!Number.isFinite(t.y)||!Number.isFinite(t.z)||t.z<-1||t.z>1)return null;const e=this.renderer.domElement.clientWidth,i=this.renderer.domElement.clientHeight;return new MA(t.x*e*.5+e*.5,-t.y*i*.5+i*.5)}screenToNormalized(A,t){const e=this.renderer.domElement.clientWidth,i=this.renderer.domElement.clientHeight,n=A/e*2-1,o=-(t/i*2-1);return new MA(n,o)}screenToWorld(A,t,e){if(!this.scene&&!e)return console.warn("WorldToScreen: 需要提供 scene 或 objects 参数才能进行屏幕坐标转世界坐标"),null;const i=this.screenToNormalized(A,t);this.raycaster.setFromCamera(i,this.camera);const n=e||this.scene.children,o=this.raycaster.intersectObjects(n,!0);return o.length>0?o[0].point:null}screenToWorldWithDepth(A,t,e=0){const i=this.screenToNormalized(A,t);this.raycaster.setFromCamera(i,this.camera);const n=new S;return this.raycaster.ray.at(e,n),n}updateCamera(A){this.camera=A}updateRenderer(A){this.renderer=A}updateScene(A){this.scene=A}}var Yo=(s=>(s.PERSPECTIVE="perspective",s.ORTHOGRAPHIC="orthographic",s))(Yo||{});class Ee{static MIN_VISIBLE_HEIGHT=1e-4;static MIN_CAMERA_DISTANCE=1e-4;static CAMERA_ANIMATION_IDLE_EXEMPT_REASON="camera-module-animation";engine;perspectiveCamera;orthographicCamera;cameraAnimationFrame=null;constructor(A){this.engine=A,this.perspectiveCamera=new Ce(45,this.engine.container.clientWidth/this.engine.container.clientHeight,.1,1e3),this.perspectiveCamera.position.set(2,2,2),this.perspectiveCamera.lookAt(0,0,0);const t=50,e=this.engine.container.clientWidth/this.engine.container.clientHeight;this.orthographicCamera=new ze(t*e/-2,t*e/2,t/2,t/-2,.1,1e3)}exitDrawingPinView(){this.engine.drawingPin?.exitViewMode?.()}getCameraAspect(A){const t=A?.width??this.engine.container?.clientWidth??1,e=A?.height??this.engine.container?.clientHeight??1;return e>0?t/e:1}getPerspectiveVisibleHeight(A,t){const e=Math.max(A.position.distanceTo(t),Ee.MIN_CAMERA_DISTANCE),i=rt.degToRad(A.getEffectiveFOV()*.5);return Math.max(2*e*Math.tan(i),Ee.MIN_VISIBLE_HEIGHT)}getOrthographicVisibleHeight(A=this.orthographicCamera){return Math.max((A.top-A.bottom)/A.zoom,Ee.MIN_VISIBLE_HEIGHT)}setOrthographicVisibleHeight(A,t=this.orthographicCamera,e){const i=Math.max(A,Ee.MIN_VISIBLE_HEIGHT),n=Number.isFinite(e)&&e>0?e:this.getCameraAspect(),o=Math.max(t.zoom||1,Ee.MIN_CAMERA_DISTANCE),g=i*o*.5,a=g*n;t.left=-a,t.right=a,t.top=g,t.bottom=-g}getViewDirection(A,t,e){const i=new S().subVectors(A,t);return i.lengthSq()>Ee.MIN_CAMERA_DISTANCE?i.normalize():new S(0,0,1).applyQuaternion(e).normalize()}getStableCameraUp(A){const t=A.clone().normalize();if(t.lengthSq()<=Ee.MIN_CAMERA_DISTANCE)return new S(0,1,0);const e=[new S(0,1,0),new S(0,0,1),new S(1,0,0)];for(const i of e){const n=i.clone().sub(t.clone().multiplyScalar(i.dot(t)));if(n.lengthSq()>Ee.MIN_CAMERA_DISTANCE)return n.normalize()}return new S(0,1,0)}updateComposerCamera(){if(!this.engine.composerModule?.composer)return;const A=this.engine.camera,t=this.engine.composerModule.composer;if(t.passes)for(const e of t.passes)e.camera!==void 0&&(e.camera=A)}applySwitchedCamera(A,t){this.engine.camera=A,this.engine.scene.camera=A,this.engine.controls?.target&&this.engine.controls.target.copy(t),this.engine.controls&&(this.engine.controls.object=A),this.engine.controlModule.orbitControls.object=A,this.engine.controlModule.firstPersonControls.camera=A,this.engine.controlModule.firstPersonControls.object=A,this.engine.controlModule.firstPersonControls.syncRotationStateFromCamera?.(),this.engine.controlModule.firstPersonControls.syncSharedTargetFromCamera?.(),this.engine.controlModule.thirdPersonControls&&(this.engine.controlModule.thirdPersonControls.camera=A,this.engine.controlModule.thirdPersonControls.object=A,this.engine.controlModule.thirdPersonControls.syncRotationStateFromCamera?.(),this.engine.controlModule.thirdPersonControls.syncSharedTargetFromAvatar?.()),A.updateProjectionMatrix?.(),A.updateMatrixWorld(),this.updateComposerCamera(),this.engine.controls?.update&&this.engine.controls.update(),this.engine.worldToScreen=new gi(this.engine.camera,this.engine.renderer,this.engine.scene)}resolvePoseReferenceUp(A,t){if(A.referenceUp){const a=new S(A.referenceUp.x,A.referenceUp.y,A.referenceUp.z);if(a.lengthSq()>Ee.MIN_CAMERA_DISTANCE)return a.normalize()}if(!A.up||!t)return;const e=new S(A.up.x,A.up.y,A.up.z);if(e.lengthSq()<=Ee.MIN_CAMERA_DISTANCE)return;const i=t.clone().sub(this.engine.camera.position);if(i.lengthSq()<=Ee.MIN_CAMERA_DISTANCE)return;i.normalize(),e.normalize();const n=[new S(0,1,0),new S(0,-1,0),new S(0,0,1),new S(0,0,-1),new S(1,0,0),new S(-1,0,0)];let o,g=-1/0;for(const a of n){const r=a.clone().sub(i.clone().multiplyScalar(a.dot(i)));if(r.lengthSq()<=Ee.MIN_CAMERA_DISTANCE)continue;const I=r.normalize().dot(e);I>g&&(g=I,o=a.clone())}return o}syncControlsAfterPoseRestore(A,t,e,i){const n=this.engine.camera;if(!n)return;A&&this.engine.controls?.target&&this.engine.controls.target.copy(A);const o=this.engine.controlModule?.orbitControls;o&&(A&&typeof o.syncStateFromCamera=="function"?o.syncStateFromCamera(n,A,{origin:t??"target",referenceUp:e,viewRight:i}):(o.object=n,A&&o.target&&o.target.copy(A),t&&o.origin?o.origin.copy(t):A&&o.origin&&o.origin.copy(A),e&&o._referenceUp?.copy&&o._referenceUp.copy(e).normalize(),i&&o._viewRight?.copy&&o._viewRight.copy(i).normalize(),o._rotateVelocity?.set?.(0,0),o._panVelocity?.set?.(0,0),typeof o._zoomVelocity=="number"&&(o._zoomVelocity=0),o._lastPosition?.copy?.(n.position),o._lastTarget?.copy?.(o.target),o._lastUp?.copy?.(n.up),o._lastQuaternion?.copy?.(n.quaternion),o._lastZoom=n.zoom,o.saveState?.()));const g=this.engine.controlModule?.firstPersonControls;g&&(g.camera=n,g.object=n,g.syncRotationStateFromCamera?.(),g.syncSharedTargetFromCamera?.());const a=this.engine.controlModule?.thirdPersonControls;a&&(a.camera=n,a.object=n,a.syncRotationStateFromCamera?.(),a.syncSharedTargetFromAvatar?.()),this.engine.worldToScreen=new gi(this.engine.camera,this.engine.renderer,this.engine.scene)}inferTargetFromRestoredCamera(A){const t=new S;A.getWorldDirection(t),t.lengthSq()<=Ee.MIN_CAMERA_DISTANCE&&t.set(0,0,-1);const i=this.engine.controls?.target?.distanceTo?.(A.position),n=this.engine.octreeBox?.getBoundingBox?.(),o=n?.min&&n?.max?n.max.distanceTo(n.min)*.8:0;let g=10;return typeof i=="number"&&Number.isFinite(i)&&i>Ee.MIN_CAMERA_DISTANCE?g=i:o>Ee.MIN_CAMERA_DISTANCE&&(g=o),A.position.clone().add(t.normalize().multiplyScalar(g))}switchCurrentCamera(){this.engine.camera===this.perspectiveCamera?this.switchToOrthographicCamera():this.switchToPerspectiveCamera()}setPerspectiveFov(A,t){const e=this.perspectiveCamera,i=e.fov,n=Math.max(1,Math.min(120,A));if(t?.adjustDistance!==!1&&this.engine.camera===e&&this.engine.controls?.target){const g=this.engine.controls.target.clone(),a=e.position.clone(),r=a.distanceTo(g);if(r>1e-6){const I=rt.degToRad(i*.5),l=rt.degToRad(n*.5),h=Math.tan(I)/Math.tan(l),B=r*h,E=new S().subVectors(a,g).normalize();e.position.copy(g).add(E.multiplyScalar(B))}}e.fov=n,e.updateProjectionMatrix()}switchToPerspectiveCamera(){if(this.exitDrawingPinView(),!this.engine.controls)return;const A=this.engine.camera;if(!A)return;const t=A.position.clone(),e=this.engine.controls.target.clone(),i=A.quaternion.clone(),n=A.up.clone(),o=this.perspectiveCamera,g=this.getViewDirection(t,e,i),a=A instanceof ze?this.getOrthographicVisibleHeight(A):this.getPerspectiveVisibleHeight(A,e),r=rt.degToRad(o.getEffectiveFOV()*.5),I=Math.max(a/(2*Math.tan(r)),Ee.MIN_CAMERA_DISTANCE);o.near=A.near,o.far=A.far,o.aspect=this.getCameraAspect(),o.up.copy(n),o.position.copy(e).add(g.multiplyScalar(I)),o.lookAt(e),this.engine.camera=o,this.applySwitchedCamera(o,e)}switchToOrthographicCamera(){if(this.exitDrawingPinView(),!this.engine.controls)return;const A=this.engine.camera;if(!A)return;const t=A.position.clone(),e=this.engine.controls.target.clone(),i=A.quaternion.clone(),n=A.up.clone(),o=this.orthographicCamera,g=this.getViewDirection(t,e,i),a=A instanceof Ce?this.getPerspectiveVisibleHeight(A,e):this.getOrthographicVisibleHeight(A),r=rt.degToRad(A.getEffectiveFOV()*.5),I=Math.max(a/(2*Math.tan(r)),Ee.MIN_CAMERA_DISTANCE);o.near=A.near,o.far=A.far,o.zoom=1,this.setOrthographicVisibleHeight(a,o),o.up.copy(n);const l=this.engine.octreeBox?.getBoundingBox?.(),h=l?l.max.distanceTo(l.min)*.8:I,B=Math.max(h,Ee.MIN_CAMERA_DISTANCE);o.position.copy(e).add(g.clone().multiplyScalar(B)),o.quaternion.copy(i),this.engine.camera=o,this.applySwitchedCamera(o,e)}getCameraType(){return this.engine.camera===this.perspectiveCamera?"perspective":this.engine.camera===this.orthographicCamera?"orthographic":"perspective"}getCameraPose(){const A=this.engine.camera,t=this.getCameraType(),e={type:t,position:{x:A.position.x,y:A.position.y,z:A.position.z},rotation:{x:A.rotation.x,y:A.rotation.y,z:A.rotation.z},quaternion:{x:A.quaternion.x,y:A.quaternion.y,z:A.quaternion.z,w:A.quaternion.w},up:{x:A.up.x,y:A.up.y,z:A.up.z}};this.engine.controls?.target&&(e.target={x:this.engine.controls.target.x,y:this.engine.controls.target.y,z:this.engine.controls.target.z});const i=this.engine.controlModule?.orbitControls;return i?.origin&&(e.origin={x:i.origin.x,y:i.origin.y,z:i.origin.z}),i?._referenceUp&&(e.referenceUp={x:i._referenceUp.x,y:i._referenceUp.y,z:i._referenceUp.z}),i?._viewRight&&(e.viewRight={x:i._viewRight.x,y:i._viewRight.y,z:i._viewRight.z}),t==="orthographic"&&(e.zoom=A.zoom,e.orthographicHeight=this.getOrthographicVisibleHeight(A)),e}restoreCameraPose(A){this.exitDrawingPinView(),this.getCameraType()!==A.type&&(A.type==="perspective"?this.switchToPerspectiveCamera():this.switchToOrthographicCamera());const e=this.engine.camera;e.position.set(A.position.x,A.position.y,A.position.z),A.up&&e.up.set(A.up.x,A.up.y,A.up.z),A.quaternion?e.quaternion.set(A.quaternion.x,A.quaternion.y,A.quaternion.z,A.quaternion.w):A.rotation&&e.rotation.set(A.rotation.x,A.rotation.y,A.rotation.z);let i;A.target&&(i=new S(A.target.x,A.target.y,A.target.z));const n=A.origin?new S(A.origin.x,A.origin.y,A.origin.z):i?.clone();if(A.type==="orthographic"){const a=e;A.zoom!==void 0&&(a.zoom=A.zoom),A.orthographicHeight!==void 0&&this.setOrthographicVisibleHeight(A.orthographicHeight,a),a.updateProjectionMatrix()}e.updateMatrix(),e.updateMatrixWorld(!0),i||(i=this.inferTargetFromRestoredCamera(e));const o=this.resolvePoseReferenceUp(A,i),g=A.viewRight?new S(A.viewRight.x,A.viewRight.y,A.viewRight.z):void 0;this.syncControlsAfterPoseRestore(i,n,o,g)}setViewFromOriginAndDirection(A,t,e=null,i,n=0,o){this.exitDrawingPinView();const g=new S(t.x,t.y,t.z).normalize(),a=new S(A.x,A.y,A.z);let r=i??null;if(r==null||r<=0){const h=this.engine.octreeBox?.getBoundingBox?.();if(h&&h.min&&h.max){const B=new S().subVectors(h.max,h.min);r=Math.max(B.x,B.y,B.z)*1.2}else r=50}const I=a.clone().add(g.clone().negate().multiplyScalar(r));if(this.engine.camera){if(e||(e=this.getStableCameraUp(g)),n>0){this.animateCameraToTarget(I,a,e,n,o);return}this.applyCameraPose(I,a,e),o?.()}}rotateToTarget(A,t=0,e){const i=this.engine.camera;if(!i)return;const n=new S(A.x,A.y,A.z);if(i.position.distanceToSquared(n)<=Ee.MIN_CAMERA_DISTANCE){e?.();return}const o=i.position.clone(),g=i.up.lengthSq()>Ee.MIN_CAMERA_DISTANCE?i.up.clone().normalize():this.getStableCameraUp(n.clone().sub(o));if(t>0){this.animateCameraToTarget(o,n,g,t,e);return}this.applyCameraPose(o,n,g),e?.()}applyCameraPose(A,t,e){const i=this.engine.camera;i&&(i.position.copy(A),i.up.copy(e),this.engine.controls?.target&&this.engine.controls.target.copy(t),typeof this.engine.controls?.setScreenUp=="function"?this.engine.controls.setScreenUp(e):i.lookAt(t),this.engine.controls?.update&&this.engine.controls.update(),i.updateMatrix(),i.updateMatrixWorld(!0))}animateCameraToTarget(A,t,e,i,n){const o=this.engine.camera,g=this.engine.controls;if(!o||!g?.target){this.applyCameraPose(A,t,e),n?.();return}const a=()=>{this.engine.renderer&&(this.engine.renderer.interactionActive=!0),this.engine.setIdleFrameRateExempt?.(Ee.CAMERA_ANIMATION_IDLE_EXEMPT_REASON,!0),this.engine.events?.trigger?.("engine-busy"),this.engine.requestComposerRender?.()},r=()=>{this.engine.renderer&&(this.engine.renderer.interactionActive=!1),this.engine.setIdleFrameRateExempt?.(Ee.CAMERA_ANIMATION_IDLE_EXEMPT_REASON,!1),this.engine.events?.trigger?.("engine-free")};this.cameraAnimationFrame!=null&&(cancelAnimationFrame(this.cameraAnimationFrame),this.cameraAnimationFrame=null,r());const I=new Wg.Tween({px:o.position.x,py:o.position.y,pz:o.position.z,tx:g.target.x,ty:g.target.y,tz:g.target.z,ux:o.up.x,uy:o.up.y,uz:o.up.z}).to({px:A.x,py:A.y,pz:A.z,tx:t.x,ty:t.y,tz:t.z,ux:e.x,uy:e.y,uz:e.z},i);I.easing(Wg.Easing.Cubic.InOut),I.onUpdate(h=>{o.position.set(h.px,h.py,h.pz),g.target.set(h.tx,h.ty,h.tz),o.up.set(h.ux,h.uy,h.uz).normalize(),typeof g.setScreenUp=="function"?g.setScreenUp(o.up.clone()):o.lookAt(g.target),g.auto=!0,g.update?.(),o.updateMatrix(),o.updateMatrixWorld(!0),this.engine.requestComposerRender?.()}),I.onComplete(()=>{g.auto=!1,this.cameraAnimationFrame=null,this.applyCameraPose(A,t,e),this.engine.requestComposerRender?.(),r(),n?.()});const l=()=>{I.update()&&(this.cameraAnimationFrame=requestAnimationFrame(l))};a(),I.start(),l()}}class kU{engine;deviceType;constructor(A){this.engine=A,this.deviceType=this.detectDeviceType()}detectDeviceType(){const A=[/Android/i,/webOS/i,/iPhone/i,/iPad/i,/iPod/i,/BlackBerry/i,/Windows Phone/i,/Mobile/i],t=navigator.userAgent||globalThis.opera,e=A.some(I=>I.test(t)),i="ontouchstart"in globalThis||navigator.maxTouchPoints>0||navigator.msMaxTouchPoints>0,n=globalThis.screen.width,o=globalThis.screen.height,g=n<=768||o<=768,r=(globalThis.devicePixelRatio||1)>=2;return e||i&&g||i&&r?"mobile":"PC"}getDeviceType(){return this.deviceType}isMobile(){return this.deviceType==="mobile"}isPC(){return this.deviceType==="PC"}redetectDeviceType(){return this.deviceType=this.detectDeviceType(),this.deviceType}getContainerSize(){return{width:this.engine.container.clientWidth,height:this.engine.container.clientHeight}}}const VU="iflowbim.cn",HU=512,OU=128,LU=150,zU=38,tE=290,F0=190;class vU{THREE;text;scene;camera;material;sprites=[];size;viewportWidth=0;viewportHeight=0;constructor(A,t=VU){this.THREE=A,this.text=t,this.scene=new A.Scene,this.camera=new A.OrthographicCamera(0,1,1,0,-10,10),this.material=new A.SpriteMaterial({map:new A.CanvasTexture(this.createTextTexture()),transparent:!0,opacity:.46,depthTest:!1,depthWrite:!1,toneMapped:!1}),this.size=new A.Vector2}render(A){}dispose(){this.material.map?.dispose?.(),this.material.dispose?.(),this.sprites.length=0}createTextTexture(){const A=document.createElement("canvas");A.width=HU,A.height=OU;const t=A.getContext("2d");return t&&(t.clearRect(0,0,A.width,A.height),t.textAlign="center",t.textBaseline="middle",t.font="600 54px Arial, Helvetica, sans-serif",t.lineWidth=3,t.strokeStyle="rgba(0, 0, 0, 0.20)",t.fillStyle="rgba(255, 255, 255, 0.24)",t.strokeText(this.text,A.width/2,A.height/2),t.fillText(this.text,A.width/2,A.height/2)),A}updateLayout(A,t){if(A===this.viewportWidth&&t===this.viewportHeight)return;this.viewportWidth=A,this.viewportHeight=t,this.camera.left=-A/2,this.camera.right=A/2,this.camera.top=t/2,this.camera.bottom=-t/2,this.camera.updateProjectionMatrix();const e=Math.ceil(A/tE)+2,i=Math.ceil(t/F0)+2,n=e*i;this.ensureSpriteCount(n);let o=0;const g=-A/2-tE/2,a=-t/2-F0/2;for(let r=0;r<i;r+=1)for(let I=0;I<e;I+=1){const l=this.sprites[o],h=g+I*tE+r%2*(tE/2),B=a+r*F0;l.position.set(h,B,0),l.visible=!0,o+=1}for(let r=o;r<this.sprites.length;r+=1)this.sprites[r].visible=!1}ensureSpriteCount(A){for(;this.sprites.length<A;){const t=new this.THREE.Sprite(this.material);t.scale.set(LU,zU,1),t.rotation.z=-.32,t.renderOrder=999999,this.scene.add(t),this.sprites.push(t)}}}const b0=1.1;function cm(s){return s?.deviceModule?.isMobile?.()===!0?1:window.devicePixelRatio||1}class _U{engine;renderer;watermark;constructor(A){this.engine=A,this.renderer=null,this.watermark=new vU(Cm)}createRenderer(){const{width:A,height:t}=this.engine.deviceModule.getContainerSize(),e=this.engine.deviceModule.isMobile();return ft.enabled=!0,this.renderer=new AE({antialias:e?!1:this.engine.options.antialias??!0,alpha:!0,premultipliedAlpha:!1,stencil:!0,preserveDrawingBuffer:!e}),this.renderer.setClearColor(0,0),this.renderer.setSize(A,t,!1),this.renderer.setPixelRatio(cm(this.engine)),this.renderer.domElement.style.width="100%",this.renderer.domElement.style.width="100%",this.renderer.domElement.style.height="100%",this.renderer.domElement.style.display="block",this.renderer.shadowMap.enabled=!e,this.renderer.shadowMap.type=Ma,this.renderer.localClippingEnabled=!0,this.renderer.outputColorSpace=Rt,this.renderer.toneMapping=sg,this.renderer.toneMappingExposure=b0,this.engine.container.appendChild(this.renderer.domElement),this.renderer}disposeRenderer(){this.watermark.dispose(),this.renderer?.dispose()}drawWatermark(){this.renderer&&this.watermark.render(this.renderer)}}const qU={type:"change"},Qm={type:"start"},dm={type:"end"},Nt=1e-6,W0=Math.PI*2,qe={NONE:-1,ROTATE:0,PAN:1,DOLLY:2,TOUCH_ROTATE:3,TOUCH_DOLLY_PAN:4},G0=new S(1,0,0),$U=new S(0,1,0),AX=new S(0,0,1),pr=new S,eE=new S,Ni=new S,Zt=new S,Ms=new S,ai=new S,ys=new S,tX=new S,iE=new wt,T0=new wt,fm=new Set(["KeyW","KeyA","KeyS","KeyD","KeyQ","KeyE","ArrowUp","ArrowLeft","ArrowDown","ArrowRight","ShiftLeft","ShiftRight"]);function sE(s,A,t){return Math.max(A,Math.min(t,s))}function Mm(s){return{width:Math.max(s?.clientWidth||1,1),height:Math.max(s?.clientHeight||1,1)}}function Fo(s){return s&&typeof s.x=="number"&&typeof s.y=="number"&&typeof s.z=="number"}function ym(s){const A=s?.tagName?.toLowerCase?.();return s?.isContentEditable===!0||A==="input"||A==="textarea"||A==="select"}class pm extends Q0{constructor(A,t,e=null){super(t,e),this.engine=A,this.target=new S,this.origin=new S,this.cursor=new S,this.showOriginIcon=!0,this.auto=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.enableRotate=!0,this.enablePan=!0,this.enableZoom=!0,this.enableDamping=!1,this.rotateSpeed=.51,this.panSpeed=1,this.zoomSpeed=1,this.touchZoomSpeed=1.35,this.dampingFactor=.08,this.keyRotateSpeed=1,this.keyPanSpeed=7,this.keyMoveSpeed=.5,this.keyMoveBoost=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:ig.ROTATE,MIDDLE:ig.DOLLY,RIGHT:ig.PAN},this.state=qe.NONE,this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this.up0=this.object.up.clone(),this.origin0=this.origin.clone(),this._lastZoom=this.object.zoom,this._lastPosition=this.object.position.clone(),this._lastTarget=this.target.clone(),this._lastUp=this.object.up.clone(),this._lastQuaternion=this.object.quaternion.clone(),this._referenceUp=this.object.up.clone().normalize(),this._viewRight=new S(1,0,0).applyQuaternion(this.object.quaternion).normalize(),this._rotateVelocity=new MA,this._panVelocity=new MA,this._zoomVelocity=0,this._mouseStart=new MA,this._touchCenter=new MA,this._touchDistance=0,this._pointers=new Map,this._pressedKeys=new Set,this._keyboardAnimationId=null,this._lastKeyboardMoveTime=0,this._isInteracting=!1,this._keyDomElement=null,this._touchAction="",this._onContextMenu=this._handleContextMenu.bind(this),this._onPointerDown=this._handlePointerDown.bind(this),this._onPointerMove=this._handlePointerMove.bind(this),this._onPointerUp=this._handlePointerUp.bind(this),this._onPointerCancel=this._handlePointerUp.bind(this),this._onWheel=this._handleWheel.bind(this),this._onKeyDown=this._handleKeyDown.bind(this),this._onKeyUp=this._handleKeyUp.bind(this),this.domElement&&this.connect(this.domElement),this.update(),this.saveState()}connect(A){A&&(this.disconnect(),this.domElement=A,this._touchAction=A.style.touchAction,A.style.touchAction="none",A.addEventListener("contextmenu",this._onContextMenu),A.addEventListener("pointerdown",this._onPointerDown),A.addEventListener("pointermove",this._onPointerMove),A.addEventListener("pointerup",this._onPointerUp),A.addEventListener("pointercancel",this._onPointerCancel),A.addEventListener("wheel",this._onWheel,{passive:!1}),this.listenToKeyEvents(window))}disconnect(){this.domElement&&(this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerCancel),this.domElement.removeEventListener("wheel",this._onWheel),this.domElement.style.touchAction=this._touchAction,this.stopListenToKeyEvents())}dispose(){this.disconnect(),this._pointers.clear(),this._pressedKeys.clear(),this._stopKeyboardMoveLoop(),this.state=qe.NONE}listenToKeyEvents(A){this.stopListenToKeyEvents(),this._keyDomElement=A,this._keyDomElement?.addEventListener("keydown",this._onKeyDown),this._keyDomElement?.addEventListener("keyup",this._onKeyUp)}stopListenToKeyEvents(){this._keyDomElement&&(this._keyDomElement.removeEventListener("keydown",this._onKeyDown),this._keyDomElement.removeEventListener("keyup",this._onKeyUp),this._keyDomElement=null,this._pressedKeys.clear(),this._stopKeyboardMoveLoop())}saveState(){this.target0.copy(this.target),this.position0.copy(this.object.position),this.zoom0=this.object.zoom,this.up0.copy(this.object.up),Fo(this.origin)&&this.origin0.copy(this.origin)}reset(){this.target.copy(this.target0),this.object.position.copy(this.position0),this.object.zoom=this.zoom0,this.object.up.copy(this.up0),Fo(this.origin)&&this.origin.copy(this.origin0),this._rotateVelocity.set(0,0),this._panVelocity.set(0,0),this._zoomVelocity=0,this.object.updateProjectionMatrix?.(),this.update(!0),this.state=qe.NONE}setScreenUp(A){return!Fo(A)||(ai.copy(this.target).sub(this.object.position),ai.lengthSq()<Nt)||(ai.normalize(),Ms.copy(A).normalize(),Zt.crossVectors(ai,Ms),Zt.lengthSq()<Nt)?!1:(this._viewRight.copy(Zt.normalize()),this.update(!0),!0)}syncStateFromCamera(A=this.object,t=this.target,e={}){if(!A)return!1;this.object=A,Fo(t)&&this.target.copy(t),e.origin==="target"?this.origin.copy(this.target):Fo(e.origin)&&this.origin.copy(e.origin);const i=this.target.clone().sub(A.position),n=Fo(e.referenceUp)?new S(e.referenceUp.x,e.referenceUp.y,e.referenceUp.z).normalize():A.up.clone().normalize();return n.lengthSq()>Nt&&this._referenceUp.copy(n),Fo(e.viewRight)?this._viewRight.copy(e.viewRight).normalize():i.lengthSq()>Nt&&(i.normalize(),Zt.crossVectors(i,this._referenceUp),Zt.lengthSq()>Nt?this._viewRight.copy(Zt.normalize()):this._viewRight.set(1,0,0).applyQuaternion(A.quaternion).normalize()),this._rotateVelocity.set(0,0),this._panVelocity.set(0,0),this._zoomVelocity=0,this._mouseStart.set(0,0),this._touchCenter.set(0,0),this._touchDistance=0,this._pointers.clear(),this._pressedKeys.clear(),this._isInteracting=!1,this.state=qe.NONE,this._lastPosition.copy(A.position),this._lastTarget.copy(this.target),this._lastUp.copy(A.up),this._lastQuaternion.copy(A.quaternion),this._lastZoom=A.zoom,this.saveState(),!0}update(A=null,t=!1){const e=typeof A=="number"?A:null,i=typeof A=="boolean"?A:!!t,n=this._applyPendingMotion(e);this._alignCamera();const o=i||n||this._hasCameraStateChanged();return o&&(this.dispatchEvent(qU),this._rememberState()),o}_applyPendingMotion(A){let t=!1;this.autoRotate&&this.state===qe.NONE&&this.auto===!1&&(this._rotateVelocity.x+=this._getAutoRotateAngle(A)),this._applyKeyboardMove(A)&&(t=!0);const e=this._consumeVector2(this._rotateVelocity);e.lengthSq()>Nt&&this.enableRotate&&(this._applyRotation(e.x,e.y),t=!0);const i=this._consumeVector2(this._panVelocity);i.lengthSq()>Nt&&this.enablePan&&(this._applyPan(i.x,i.y),t=!0);const n=this._consumeNumber("_zoomVelocity");return Math.abs(n)>Nt&&this.enableZoom&&(this._applyZoom(n),t=!0),t}_applyKeyboardMove(A){if(!this.enabled||!this.object?.isPerspectiveCamera||this._pressedKeys.size===0||(ys.set(0,0,0),(this._pressedKeys.has("KeyW")||this._pressedKeys.has("ArrowUp"))&&(ys.z+=1),(this._pressedKeys.has("KeyS")||this._pressedKeys.has("ArrowDown"))&&(ys.z-=1),(this._pressedKeys.has("KeyA")||this._pressedKeys.has("ArrowLeft"))&&(ys.x-=1),(this._pressedKeys.has("KeyD")||this._pressedKeys.has("ArrowRight"))&&(ys.x+=1),this._pressedKeys.has("KeyQ")&&(ys.y+=1),this._pressedKeys.has("KeyE")&&(ys.y-=1),ys.lengthSq()<=Nt)||(ys.normalize(),Zt.copy(G0).applyQuaternion(this.object.quaternion).normalize(),ai.set(0,0,-1).applyQuaternion(this.object.quaternion).normalize(),Ms.copy(this._referenceUp).normalize(),Ms.lengthSq()<=Nt&&Ms.copy(this.object.up).normalize(),Ni.set(0,0,0),Ni.addScaledVector(Zt,ys.x),Ni.addScaledVector(ai,ys.z),Ni.addScaledVector(Ms,ys.y),Ni.lengthSq()<=Nt))return!1;Ni.normalize();const t=Number.isFinite(A)&&A>0?A:1/60,e=Math.max(this.object.position.distanceTo(this.target),1),i=this._pressedKeys.has("ShiftLeft")||this._pressedKeys.has("ShiftRight")?this.keyMoveBoost:1,n=Math.max(e*.8,1)*this.keyMoveSpeed*t*i;return Ni.multiplyScalar(n),this.object.position.add(Ni),this.target.add(Ni),this.origin.add(Ni),!0}_startKeyboardMoveLoop(){if(this._keyboardAnimationId!=null)return;this._lastKeyboardMoveTime=performance.now();const A=t=>{if(this._keyboardAnimationId=null,!this.enabled||this._pressedKeys.size===0){this._lastKeyboardMoveTime=0;return}const e=Math.min(Math.max((t-this._lastKeyboardMoveTime)/1e3,0),.05);this._lastKeyboardMoveTime=t,this.update(e),this._keyboardAnimationId=requestAnimationFrame(A)};this._keyboardAnimationId=requestAnimationFrame(A)}_stopKeyboardMoveLoop(){this._keyboardAnimationId!=null&&(cancelAnimationFrame(this._keyboardAnimationId),this._keyboardAnimationId=null),this._lastKeyboardMoveTime=0}_consumeVector2(A){if(!this.enableDamping){const i=A.clone();return A.set(0,0),i}const t=sE(this.dampingFactor,0,1),e=A.clone().multiplyScalar(t);return A.sub(e),A.lengthSq()<Nt&&A.set(0,0),e}_consumeNumber(A){if(!this.enableDamping){const i=this[A];return this[A]=0,i}const t=sE(this.dampingFactor,0,1),e=this[A]*t;return this[A]-=e,Math.abs(this[A])<Nt&&(this[A]=0),e}_applyRotation(A,t){const e=this._getRotatePivot(),i=this.object.position;pr.copy(i).sub(e),pr.lengthSq()<Nt&&pr.set(0,0,Math.max(this.minDistance,1)),eE.copy(this.target).sub(e),ai.copy(this.target).sub(i).normalize(),Math.abs(A)>Nt&&(iE.setFromAxisAngle(this._referenceUp,-A),pr.applyQuaternion(iE),eE.applyQuaternion(iE),ai.applyQuaternion(iE).normalize()),Zt.copy(this._getStableRightAxis(ai)),Math.abs(t)>Nt&&Zt.lengthSq()>Nt&&(T0.setFromAxisAngle(Zt,-t),pr.applyQuaternion(T0),eE.applyQuaternion(T0)),i.copy(e).add(pr),this.target.copy(e).add(eE)}_applyPan(A,t){const{width:e,height:i}=Mm(this.domElement);Zt.copy(G0).applyQuaternion(this.object.quaternion).normalize(),Ms.copy($U).applyQuaternion(this.object.quaternion).normalize();let n=0,o=0;if(this.object.isPerspectiveCamera){const a=2*Math.max(this.object.position.distanceTo(this.target),Nt)*Math.tan(rt.degToRad(this.object.getEffectiveFOV()*.5)),r=a*this.object.aspect;n=A/e*r*this.panSpeed,o=t/i*a*this.panSpeed}else if(this.object.isOrthographicCamera){const g=(this.object.right-this.object.left)/this.object.zoom,a=(this.object.top-this.object.bottom)/this.object.zoom;n=A/e*g*this.panSpeed,o=t/i*a*this.panSpeed}else return;Ni.set(0,0,0),Ni.addScaledVector(Zt,-n),Ni.addScaledVector(Ms,o),this.object.position.add(Ni),this.target.add(Ni)}_applyZoom(A){const t=Math.pow(.95,this.zoomSpeed*A);if(this.object.isPerspectiveCamera){ai.copy(this.object.position).sub(this.target);const e=Math.max(ai.length(),Nt),i=sE(e/t,this.minDistance,this.maxDistance);ai.setLength(i),this.object.position.copy(this.target).add(ai);return}this.object.isOrthographicCamera&&(this.object.zoom=sE(this.object.zoom*t,this.minZoom,this.maxZoom),this.object.updateProjectionMatrix())}_alignCamera(){ai.copy(this.target).sub(this.object.position),!(ai.lengthSq()<Nt)&&(ai.normalize(),Zt.copy(this._getStableRightAxis(ai)),Ms.crossVectors(Zt,ai).normalize(),Ms.lengthSq()<Nt&&Ms.copy(this._referenceUp),this._viewRight.copy(Zt),this.object.up.copy(Ms),this.object.lookAt(this.target),this.object.updateMatrixWorld())}_getStableRightAxis(A){return Zt.crossVectors(A,this._referenceUp),Zt.lengthSq()<Nt&&(Zt.copy(this._viewRight),Zt.addScaledVector(A,-Zt.dot(A))),Zt.lengthSq()<Nt&&(Zt.copy(G0),Zt.addScaledVector(A,-Zt.dot(A))),Zt.lengthSq()<Nt&&(Zt.copy(AX),Zt.addScaledVector(A,-Zt.dot(A))),Zt.normalize(),this._viewRight.lengthSq()>Nt&&Zt.dot(this._viewRight)<0&&Zt.negate(),Zt}_getRotatePivot(){return Fo(this.origin)?this.origin.distanceToSquared(this.target)<Nt?this.target:tX.copy(this.origin):this.target}_hasCameraStateChanged(){const A=this.object.isOrthographicCamera&&Math.abs(this.object.zoom-this._lastZoom)>Nt;return this._lastPosition.distanceToSquared(this.object.position)>Nt||this._lastTarget.distanceToSquared(this.target)>Nt||this._lastUp.distanceToSquared(this.object.up)>Nt||8*(1-Math.abs(this._lastQuaternion.dot(this.object.quaternion)))>Nt||A}_rememberState(){this._lastPosition.copy(this.object.position),this._lastTarget.copy(this.target),this._lastUp.copy(this.object.up),this._lastQuaternion.copy(this.object.quaternion),this._lastZoom=this.object.zoom}_getAutoRotateAngle(A){return A!=null?W0/60*this.autoRotateSpeed*A:W0/3600*this.autoRotateSpeed}_beginInteraction(A){this._isInteracting||(this.dispatchEvent(Qm),this._isInteracting=!0),this.state=A}_endInteraction(){this._isInteracting&&(this._isInteracting=!1,this.state=qe.NONE,this.dispatchEvent(dm))}_handleContextMenu(A){A.preventDefault()}_handlePointerDown(A){if(!this.enabled||!this.domElement)return;if(this.domElement.setPointerCapture?.(A.pointerId),this._pointers.set(A.pointerId,{x:A.clientX,y:A.clientY,pointerType:A.pointerType,button:A.button}),A.pointerType==="touch"){this._handleTouchStart();return}const t=this._resolveMouseAction(A);t!=null&&(this._mouseStart.set(A.clientX,A.clientY),this._beginInteraction(t))}_handlePointerMove(A){const t=this._pointers.get(A.pointerId);if(!t)return;if(A.pointerType==="touch"){t.x=A.clientX,t.y=A.clientY,this._handleTouchMove();return}if(!this.enabled||this.state===qe.NONE)return;const e=A.clientX-this._mouseStart.x,i=A.clientY-this._mouseStart.y;this._mouseStart.set(A.clientX,A.clientY),this.state===qe.ROTATE?this._queueRotate(e,i):this.state===qe.PAN?this._queuePan(e,i):this.state===qe.DOLLY&&this._queueZoom(i*.01),this.update()}_handlePointerUp(A){if(this._pointers.has(A.pointerId)){if(this.domElement?.releasePointerCapture?.(A.pointerId),this._pointers.delete(A.pointerId),A.pointerType==="touch"){this._pointers.size>0?this._restartTouchGesture():this._endInteraction();return}this._endInteraction()}}_handleWheel(A){!this.enabled||!this.enableZoom||(A.preventDefault(),this.dispatchEvent(Qm),this._queueZoom(Math.sign(A.deltaY)),this.update(),this.dispatchEvent(dm))}_handleKeyDown(A){if(!this.enabled)return;const t=A.code||A.key;if(this.object?.isPerspectiveCamera&&fm.has(t)){ym(A.target)||(this._pressedKeys.add(t),this._startKeyboardMoveLoop(),A.preventDefault());return}let e=!1;switch(t){case this.keys.UP:A.ctrlKey||A.metaKey||A.shiftKey?this._queuePan(0,this.keyPanSpeed):this._queueRotate(0,this.keyRotateSpeed),e=!0;break;case this.keys.BOTTOM:A.ctrlKey||A.metaKey||A.shiftKey?this._queuePan(0,-this.keyPanSpeed):this._queueRotate(0,-this.keyRotateSpeed),e=!0;break;case this.keys.LEFT:A.ctrlKey||A.metaKey||A.shiftKey?this._queuePan(this.keyPanSpeed,0):this._queueRotate(this.keyRotateSpeed,0),e=!0;break;case this.keys.RIGHT:A.ctrlKey||A.metaKey||A.shiftKey?this._queuePan(-this.keyPanSpeed,0):this._queueRotate(-this.keyRotateSpeed,0),e=!0;break}e&&(A.preventDefault(),this.update())}_handleKeyUp(A){const t=A.code||A.key;fm.has(t)&&(this._pressedKeys.delete(t),this._pressedKeys.size===0&&this._stopKeyboardMoveLoop(),this.object?.isPerspectiveCamera&&!ym(A.target)&&A.preventDefault())}_handleTouchStart(){const A=Array.from(this._pointers.values());if(A.length===1){this._touchCenter.set(A[0].x,A[0].y),this._touchDistance=0,this._beginInteraction(qe.TOUCH_ROTATE);return}if(A.length>=2){const t=(A[0].x+A[1].x)*.5,e=(A[0].y+A[1].y)*.5,i=Math.hypot(A[0].x-A[1].x,A[0].y-A[1].y);this._touchCenter.set(t,e),this._touchDistance=i,this._beginInteraction(qe.TOUCH_DOLLY_PAN)}}_restartTouchGesture(){const A=Array.from(this._pointers.values());if(A.length===1){this.state=qe.TOUCH_ROTATE,this._touchCenter.set(A[0].x,A[0].y),this._touchDistance=0;return}A.length>=2&&(this.state=qe.TOUCH_DOLLY_PAN,this._touchCenter.set((A[0].x+A[1].x)*.5,(A[0].y+A[1].y)*.5),this._touchDistance=Math.hypot(A[0].x-A[1].x,A[0].y-A[1].y))}_handleTouchMove(){if(!this.enabled)return;const A=Array.from(this._pointers.values());if(A.length===1&&this.state===qe.TOUCH_ROTATE){const n=A[0].x-this._touchCenter.x,o=A[0].y-this._touchCenter.y;this._touchCenter.set(A[0].x,A[0].y),this._queueRotate(n,o),this.update();return}if(A.length<2||this.state!==qe.TOUCH_DOLLY_PAN)return;const t=(A[0].x+A[1].x)*.5,e=(A[0].y+A[1].y)*.5,i=Math.hypot(A[0].x-A[1].x,A[0].y-A[1].y);if(this._queuePan(t-this._touchCenter.x,e-this._touchCenter.y),this._touchCenter.set(t,e),this._touchDistance>0&&i>0){const n=i/this._touchDistance,o=Math.pow(n,Math.max(this.touchZoomSpeed||1,Nt));this._queueZoom(Math.log(o)/Math.log(.95))}this._touchDistance=i,this.update()}_resolveMouseAction(A){let t=null;return A.button===0?t=A.ctrlKey||A.metaKey||A.shiftKey?this.mouseButtons.RIGHT:this.mouseButtons.LEFT:A.button===1?t=this.mouseButtons.MIDDLE:A.button===2&&(t=this.mouseButtons.RIGHT),t===ig.ROTATE&&this.enableRotate?qe.ROTATE:t===ig.PAN&&this.enablePan?qe.PAN:t===ig.DOLLY&&this.enableZoom?qe.DOLLY:null}_queueRotate(A,t){if(!this.enableRotate||!this.domElement)return;const{height:e}=Mm(this.domElement),i=W0/e;this._rotateVelocity.x+=A*i*this.rotateSpeed,this._rotateVelocity.y+=t*i*this.rotateSpeed}_queuePan(A,t){this.enablePan&&(this._panVelocity.x+=A,this._panVelocity.y+=t)}_queueZoom(A){this.enableZoom&&(this._zoomVelocity+=A)}}class Dm extends os{constructor(A,t,e,i){super(),this._Engine=A,this.camera=t,this.object=t,this.domElement=e,this._isEnabled=!1,this._rayOriginOffset=new S(0,-1,0),this._camerLocalDirection=new S,this._tmpVector=new S,this._lookDirection=new S,this._rayCaster=new De,this._fallingTime=0,this._isMouseInElement=!1,this._euler=new Le(0,0,0,"YZX"),this._prevMouseX=0,this._prevMouseY=0,this._pointerLookActive=!1,this._externalLookActive=!1,this._interactionActive=!1,this._sharedTargetDistance=10,this.target=this.camera.position.clone().add(new S(0,0,-1).applyQuaternion(this.camera.quaternion).normalize().multiplyScalar(this._sharedTargetDistance)),this.applyGravity=!1,this.gravityMinHeight=!0,this.applyCollision=!0,this.positionEasing=!0,this.lookflag=1,this.lookHorizontalFlag=1,this.lookSpeed=.003,this.moveSpeed=.02,this.playerHeight=1.6,this.jumpSpeed=.24,this.jumpGravity=.012,this.maxRotateX=Math.PI*.5-.01,this.g=9.8,this.bindmousedown=this._Engine&&this._Engine.deviceType!=="PC"?this.onTouchStart.bind(this):this.onMouseDown.bind(this),this.bindmouseup=this._Engine&&this._Engine.deviceType!=="PC"?this.onTouchEnd.bind(this):this.onMouseUp.bind(this),this.bindmousemove=this._Engine&&this._Engine.deviceType!=="PC"?this.onTouchMove.bind(this):this.onMouseMove.bind(this),this.bindonKeyDown=this.onKeyDown.bind(this),this.bindonKeyUp=this.onKeyUp.bind(this),this.bindWindowBlur=this.onWindowBlur.bind(this),this.bindVisibilityChange=this.onVisibilityChange.bind(this),this.bindMousewheel=this.onMousewheel.bind(this),this.bindMouseEnter=this.onMouseEnter.bind(this),this.bindMouseLeave=this.onMouseLeave.bind(this),this.needMousewheel=!1,this.moveWheelRun=!0,this.moveWheelStop=!1,this.wheelClock,this.keydown=!1,this.shiftDown=!1,this._verticalVelocity=0,this._isJumping=!1,this._isJumpKeyDown=!1,this._jumpStartHeight=this.camera.position.y,this.gravityTestCount=5,this.catchTestCount=10,this.GetEngine=()=>A,this.syncRotationStateFromCamera(),this.sanitizeCameraOrientation(),this.syncSharedTargetFromCamera()}set colliders(A){this._rayCastObjects=A}set enabled(A){this._isEnabled!==A&&(this._isEnabled=A,A?(this.syncRotationStateFromCamera(),this.sanitizeCameraOrientation(),this.syncSharedTargetFromCamera(),this.addEvents()):(this.removeEvents(),this.setPointerLookActive(!1),this.setExternalLookActive(!1),this.resetMovementState?.(),this.syncRotationStateFromCamera(),this.syncSharedTargetFromCamera()))}get enabled(){return this._isEnabled}hasMoveInput(){return this._camerLocalDirection.lengthSq()>1e-8}setPointerLookActive(A){this._pointerLookActive=A===!0,this.syncInteractionState()}setExternalLookActive(A){this._externalLookActive=A===!0,this.syncInteractionState()}syncInteractionState(){const A=this._pointerLookActive||this._externalLookActive||this.hasMoveInput()||this._isJumping;this._interactionActive!==A&&(this._interactionActive=A,this.dispatchEvent({type:A?"start":"end"}))}dispatchCameraChange(){window.dispatchEvent(new CustomEvent("bimengine:camerachange",{detail:""})),this.dispatchEvent({type:"change"})}isPcDevice(){const A=this._Engine?.deviceModule?.getDeviceType?.()??this._Engine?.deviceType??this._Engine?.DeviceType;return A==="PC"||!A}addEvents(){this.isPcDevice()?(this.domElement.addEventListener("mousedown",this.bindmousedown,!1),this.domElement.addEventListener("mouseup",this.bindmouseup,!1)):(this.domElement.addEventListener("touchstart",this.bindmousedown,!1),this.domElement.addEventListener("touchend",this.bindmouseup,!1)),this.domElement.addEventListener("mouseenter",this.bindMouseEnter,!1),this.domElement.addEventListener("mouseleave",this.bindMouseLeave,!1),window.addEventListener("keydown",this.bindonKeyDown,!1),window.addEventListener("keyup",this.bindonKeyUp,!1),window.addEventListener("blur",this.bindWindowBlur,!1),document.addEventListener("visibilitychange",this.bindVisibilityChange,!1),this.needMousewheel&&(document.addEventListener&&document.addEventListener("DOMMouseScroll",this.bindMousewheel,!1),window.addEventListener("mousewheel",this.bindMousewheel,!1))}removeEvents(){this.isPcDevice()?(this.domElement.removeEventListener("mousedown",this.bindmousedown),this.domElement.removeEventListener("mouseup",this.bindmouseup),this.domElement.removeEventListener("mousemove",this.bindmousemove)):(this.domElement.removeEventListener("touchstart",this.bindmousedown),this.domElement.removeEventListener("touchend",this.bindmouseup),this.domElement.removeEventListener("touchmove",this.bindmousemove)),this.domElement.removeEventListener("mouseenter",this.bindMouseEnter),this.domElement.removeEventListener("mouseleave",this.bindMouseLeave),window.removeEventListener("keydown",this.bindonKeyDown),window.removeEventListener("keyup",this.bindonKeyUp),window.removeEventListener("blur",this.bindWindowBlur),document.removeEventListener("visibilitychange",this.bindVisibilityChange),this.needMousewheel&&(document.addEventListener&&document.removeEventListener("DOMMouseScroll",this.bindMousewheel),window.removeEventListener("mousewheel",this.bindMousewheel))}onMouseEnter(A){this._isMouseInElement=!0}onMouseLeave(A){this._isMouseInElement=!1,this.setPointerLookActive(!1),this.setExternalLookActive(!1),this.resetMovementState()}onWindowBlur(){this.setPointerLookActive(!1),this.setExternalLookActive(!1),this.resetMovementState()}onVisibilityChange(){document.hidden&&(this.setPointerLookActive(!1),this.setExternalLookActive(!1),this.resetMovementState())}onMousewheel(A){let t;switch(A.wheelDelta?(A.wheelDelta>0&&(t="up"),A.wheelDelta<0&&(t="down")):A.detail&&(A.detail<0&&(t="up"),A.detail>0&&(t="down")),t){case"up":this._camerLocalDirection.z=1;break;case"down":this._camerLocalDirection.z=-1;break}this.moveWheelRun==!0?(this.moveWheelRun=!1,this.moveWheelStop=!0,this.wheelClock=setTimeout(()=>{this.moveWheelStop==!0&&(this.moveWheelStop=!1,this.moveWheelRun=!0,this._camerLocalDirection.z=0,this.syncInteractionState())},200)):(clearTimeout(this.wheelClock),this.wheelClock=setTimeout(()=>{this.moveWheelStop==!0&&(this.moveWheelStop=!1,this.moveWheelRun=!0,this._camerLocalDirection.z=0,this.syncInteractionState())},150)),this.syncInteractionState()}onMouseDown(A){console.log("[FirstPersonCameraControl] onMouseDown",A),this.domElement.addEventListener("mousemove",this.bindmousemove,!1),this.syncRotationStateFromCamera(),this.setPointerLookActive(!0),this._prevMouseX=A.screenX,this._prevMouseY=A.screenY}onMouseMove(A){if(this._isEnabled==!1)return;let t=this._prevMouseX?A.screenX-this._prevMouseX:0,e=this._prevMouseY?A.screenY-this._prevMouseY:0,i=this._euler.x-e*this.lookflag*this.lookSpeed;i>=0?i<this.maxRotateX?this._euler.x=i:this._euler.x=this.maxRotateX:i>-this.maxRotateX?this._euler.x=i:this._euler.x=-this.maxRotateX,this._euler.y-=t*this.lookHorizontalFlag*this.lookSpeed,this.camera.quaternion.setFromEuler(this._euler),this.syncSharedTargetFromCamera(),this._prevMouseX=A.screenX,this._prevMouseY=A.screenY;let n=this.GetEngine();n.movefirst=!0,this.dispatchCameraChange()}onMouseUp(A){let t=this.GetEngine();t.movefirst=!1,this.setPointerLookActive(!1),this.domElement.removeEventListener("mousemove",this.bindmousemove)}onTouchStart(A){this.domElement.addEventListener("touchmove",this.bindmousemove,!1),this.syncRotationStateFromCamera(),this.setPointerLookActive(!0),this._prevMouseX=A.targetTouches[0].clientX,this._prevMouseY=A.targetTouches[0].clientY}onTouchMove(A){if(this._isEnabled==!1)return;let t=this._prevMouseX?this._prevMouseX-A.targetTouches[0].clientX:0,e=this._prevMouseY?this._prevMouseY-A.targetTouches[0].clientY:0,i=this._euler.x-e*this.lookflag*this.lookSpeed;i>=0?i<this.maxRotateX?this._euler.x=i:this._euler.x=this.maxRotateX:i>-this.maxRotateX?this._euler.x=i:this._euler.x=-this.maxRotateX,this._euler.y-=t*this.lookHorizontalFlag*this.lookSpeed,this.camera.quaternion.setFromEuler(this._euler),this.syncSharedTargetFromCamera(),this._prevMouseX=A.targetTouches[0].clientX,this._prevMouseY=A.targetTouches[0].clientY;let n=this.GetEngine();n.movefirst=!0,this.dispatchCameraChange()}onTouchEnd(A){let t=this.GetEngine();t.movefirst=!1,this.setPointerLookActive(!1),this.domElement.removeEventListener("touchmove",this.bindmousemove)}onKeyDown(A){if(!this._isMouseInElement)return;let t=this.GetEngine();switch(t.movefirst=!0,this.dispatchCameraChange(),A.keyCode){case 38:this._camerLocalDirection.z=1;break;case 81:if(this.applyGravity){this.keydown=!1,this._camerLocalDirection.y=0;break}this.keydown=!0,this._camerLocalDirection.y=1;break;case 69:if(this.applyGravity){this.keydown=!1,this._camerLocalDirection.y=0;break}this._camerLocalDirection.y=-1;break;case 87:this._camerLocalDirection.z=1;break;case 37:this._camerLocalDirection.x=-1;break;case 65:this._camerLocalDirection.x=-1;break;case 40:this._camerLocalDirection.z=-1;break;case 83:this._camerLocalDirection.z=-1;break;case 39:this._camerLocalDirection.x=1;break;case 68:this._camerLocalDirection.x=1;break;case 32:A.preventDefault?.(),A.stopPropagation?.(),this._isJumpKeyDown||(this._isJumpKeyDown=!0,this.jump());break;case 16:this.shiftDown=!0;break}this.syncInteractionState()}onKeyUp(A){let t=this.GetEngine();switch(A.keyCode){case 38:case 87:this._camerLocalDirection.z=0;break;case 37:case 65:this._camerLocalDirection.x=0;break;case 40:case 83:this._camerLocalDirection.z=0;break;case 39:case 68:this._camerLocalDirection.x=0;break;case 81:case 69:this.keydown=!1,this._camerLocalDirection.y=0;break;case 32:A.preventDefault?.(),A.stopPropagation?.(),this._isJumpKeyDown=!1;break;case 16:this.shiftDown=!1;break}t.movefirst=this._camerLocalDirection.x!==0||this._camerLocalDirection.y!==0||this._camerLocalDirection.z!==0,this.syncInteractionState()}rotateX(A){this.syncRotationStateFromCamera(),this._euler.y-=A*this.lookHorizontalFlag*this.lookSpeed,this.camera.quaternion.setFromEuler(this._euler),this.syncSharedTargetFromCamera(),this.dispatchCameraChange()}rotateY(A){this.syncRotationStateFromCamera();let t=this._euler.x-A*this.lookflag*.5*this.lookSpeed;t>=0?t<this.maxRotateX?this._euler.x=t:this._euler.x=this.maxRotateX:t>-this.maxRotateX?this._euler.x=t:this._euler.x=-this.maxRotateX,this.camera.quaternion.setFromEuler(this._euler),this.syncSharedTargetFromCamera(),this.dispatchCameraChange()}setLookDirection({horizontal:A,vertical:t}={}){(A===1||A===-1)&&(this.lookHorizontalFlag=A),(t===1||t===-1)&&(this.lookflag=t)}update(){const A=this.camera.position.clone(),t=this.camera.quaternion.clone();this.applyGravity&&(this.keydown=!1,this._camerLocalDirection.y=0),this.updateJump(),!this.keydown&&!this._isJumping&&this.gravityTest(),this.collisionTest(),this.syncSharedTargetFromCamera(),this.syncInteractionState(),(A.distanceToSquared(this.camera.position)>1e-12||1-Math.abs(t.dot(this.camera.quaternion))>1e-12)&&this.dispatchCameraChange()}syncRotationStateFromCamera(){this.camera&&(this.object=this.camera,this.camera.updateMatrixWorld?.(),this._euler.setFromQuaternion(this.camera.quaternion,"YZX"))}sanitizeCameraOrientation(){this.camera&&(this.syncRotationStateFromCamera(),this._euler.x=rt.clamp(this._euler.x,-this.maxRotateX,this.maxRotateX),this._euler.z=0,this.camera.up.set(0,1,0),this.camera.quaternion.setFromEuler(this._euler),this.camera.updateMatrixWorld?.(!0))}syncSharedTargetFromCamera(){if(!this.camera)return;this.object=this.camera;let A=this.GetEngine();const t=[],e=i=>{!i?.target||t.includes(i)||t.push(i)};if(e(this),e(A?.controls),e(A?.controlModule?.orbitControls),t.length!==0){this.camera.getWorldDirection(this._lookDirection);for(const i of t){const n=this.camera.position.distanceTo(i.target);Number.isFinite(n)&&n>.001&&(this._sharedTargetDistance=n),i.target.copy(this.camera.position).addScaledVector(this._lookDirection,this._sharedTargetDistance)}}}setScreenUp(A){return!A||typeof A.x!="number"||typeof A.y!="number"||typeof A.z!="number"||!this.camera?!1:(this.camera.up.copy(A).normalize(),this.target&&this.camera.lookAt(this.target),this.camera.updateMatrixWorld?.(!0),this.syncRotationStateFromCamera(),this.sanitizeCameraOrientation(),this.syncSharedTargetFromCamera(),!0)}resetMovementState(){this._camerLocalDirection.set(0,0,0),this.keydown=!1,this.shiftDown=!1,this._verticalVelocity=0,this._isJumping=!1,this._isJumpKeyDown=!1;let A=this.GetEngine();A&&(A.movefirst=!1),this.syncInteractionState()}resetMovementState(){this._camerLocalDirection.set(0,0,0),this.keydown=!1,this.shiftDown=!1,this._verticalVelocity=0,this._isJumping=!1,this._isJumpKeyDown=!1;let A=this.GetEngine();A&&(A.movefirst=!1),this.syncInteractionState()}jump(){this._isJumping||(this._jumpStartHeight=this.camera.position.y,this._verticalVelocity=this.jumpSpeed,this._isJumping=!0,this.syncInteractionState())}updateJump(){if(!this._isJumping)return;this.setCameraHeight(this.camera.position.y+this._verticalVelocity),this._verticalVelocity-=this.jumpGravity;const A=this.getJumpFloorCameraHeight();this._verticalVelocity<=0&&this.camera.position.y<=A&&(this.setCameraHeight(A),this._verticalVelocity=0,this._isJumping=!1,this._fallingTime=0,this.syncInteractionState())}getJumpFloorCameraHeight(){const A=this.hitTest(new S(0,-1,0),this.playerHeight+3);if(A?.point)return A.point.y+this.playerHeight;const t=this.getMinHeight();return Math.max(this._jumpStartHeight,t??-1/0)}gravityTest(){if(!(this._camerLocalDirection.y==0&&this._camerLocalDirection.z==0&&this._camerLocalDirection.x==0))if(this.applyGravity){let A=!0;this._fallingTime+=.01,this._tmpVector.set(0,-1,0);const t=this.hitTest(this._tmpVector,this.playerHeight+3);if(t==null)return;if(t){const e=t.point.add(new S(0,this.playerHeight,0));if(this.positionEasing){if(e.y>=this.camera.position.y||e.y-this.camera.position.y<.2){this.setCameraHeight(this.camera.position.y+(e.y-this.camera.position.y)*.08),this._fallingTime=0,A=!1;return}}else t.distance<this.playerHeight&&(this.setCameraHeight(e.y),this._fallingTime=0,A=!1)}A&&this.setCameraHeight(this.camera.position.y-this.g*Math.pow(this._fallingTime,2))}else this.setCameraHeight(this.camera.position.y)}collisionTest(){this._camerLocalDirection.x!==0&&this.collisionTestX(),this._camerLocalDirection.z!==0&&this.collisionTestZ(),!this.applyGravity&&this._camerLocalDirection.y!==0&&this.collisionTestY()}collisionTestX(){let A=this.GetEngine();if(A.movefirst=!0,this._tmpVector.setFromMatrixColumn(this.camera.matrix,0),this._tmpVector.multiplyScalar(this._camerLocalDirection.x),this._tmpVector.set(this._tmpVector.x,0,this._tmpVector.z),this._tmpVector=this._tmpVector.normalize(),this.applyCollision){const t=this.hitTest(this._tmpVector);if(t&&t.distance<.3)return}this.camera.position.addScaledVector(this._tmpVector,this.moveSpeed*(this.shiftDown?2:1))}collisionTestZ(){let A=this.GetEngine();if(A.movefirst=!0,this._tmpVector.setFromMatrixColumn(this.camera.matrix,0),this._tmpVector.crossVectors(this.camera.up,this._tmpVector),this._tmpVector.multiplyScalar(this._camerLocalDirection.z),this._tmpVector.set(this._tmpVector.x,0,this._tmpVector.z),this._tmpVector=this._tmpVector.normalize(),this.applyCollision){const t=this.hitTest(this._tmpVector);if(t&&t.distance<.3)return}this.camera.position.addScaledVector(this._tmpVector,this.moveSpeed*(this.shiftDown?2:1))}collisionTestY(){let A=this.GetEngine();if(A.movefirst=!0,this._tmpVector.setFromMatrixColumn(this.camera.matrix,0),this._tmpVector=new S(0,1,0),this._tmpVector.multiplyScalar(this._camerLocalDirection.y),this.applyCollision){const e=this.hitTest(this._tmpVector);if(e&&e.distance<.3)return}let t=this.camera.position.clone().addScaledVector(this._tmpVector,this.moveSpeed*(this.shiftDown?2:1));this.setCameraHeight(t.y)}setCameraHeight(A){let t=this.getMinHeight();this.gravityMinHeight&&t!==void 0&&A<t?this.camera.position.y=t:this.camera.position.y=A}getMinHeight(){let A,t=this.GetEngine(),e=t.ToolUntils?t.ToolUntils.GetBoundingBox(t):null;return t&&e&&(A=e.min.y),A}hitTest(A=this._tmpVector,t=1/0){const e=this.camera.position.clone().add(this._rayOriginOffset);this._rayCaster.ray.origin=e,this._rayCaster.ray.direction=A,this._rayCaster.far=t;let i=this.GetEngine();var n=i.scene.ground;n&&n.material.type;let o={},g=i.handelBehaved.handle_catch(this._rayCaster,o,!1);if(this._rayCaster.far=1/0,g==null)return null;let a=g.object.name,r=g.object.url,I=i.models.find(l=>l.url==r);if(I!=null){let l=I.nodesMap.get(a);if(l.infos!=null&&l.infos.length!=0&&l.infos[0].name&&(l.infos[0].name.includes("门")||l.infos[0].name.includes("門")||l.infos[0].name.includes("door")))return null}return g}}function El(s,A=!1){const t=s[0].index!==null,e=new Set(Object.keys(s[0].attributes)),i=new Set(Object.keys(s[0].morphAttributes)),n={},o={},g=s[0].morphTargetsRelative,a=new et;let r=0;for(let I=0;I<s.length;++I){const l=s[I];let h=0;if(t!==(l.index!==null))return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+I+". All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them."),null;for(const B in l.attributes){if(!e.has(B))return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+I+'. All geometries must have compatible attributes; make sure "'+B+'" attribute exists among all geometries, or in none of them.'),null;n[B]===void 0&&(n[B]=[]),n[B].push(l.attributes[B]),h++}if(h!==e.size)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+I+". Make sure all geometries have the same number of attributes."),null;if(g!==l.morphTargetsRelative)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+I+". .morphTargetsRelative must be consistent throughout all geometries."),null;for(const B in l.morphAttributes){if(!i.has(B))return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+I+". .morphAttributes must be consistent throughout all geometries."),null;o[B]===void 0&&(o[B]=[]),o[B].push(l.morphAttributes[B])}if(A){let B;if(t)B=l.index.count;else if(l.attributes.position!==void 0)B=l.attributes.position.count;else return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+I+". The geometry must have either an index or a position attribute"),null;a.addGroup(r,B,I),r+=B}}if(t){let I=0;const l=[];for(let h=0;h<s.length;++h){const B=s[h].index;for(let E=0;E<B.count;++E)l.push(B.getX(E)+I);I+=s[h].attributes.position.count}a.setIndex(l)}for(const I in n){const l=wm(n[I]);if(!l)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the "+I+" attribute."),null;a.setAttribute(I,l)}for(const I in o){const l=o[I][0].length;if(l!==0){a.morphAttributes=a.morphAttributes||{},a.morphAttributes[I]=[];for(let h=0;h<l;++h){const B=[];for(let c=0;c<o[I].length;++c)B.push(o[I][c][h]);const E=wm(B);if(!E)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the "+I+" morphAttribute."),null;a.morphAttributes[I].push(E)}}}return a}function wm(s){let A,t,e,i=-1,n=0;for(let r=0;r<s.length;++r){const I=s[r];if(A===void 0&&(A=I.array.constructor),A!==I.array.constructor)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.array must be of consistent array types across matching attributes."),null;if(t===void 0&&(t=I.itemSize),t!==I.itemSize)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.itemSize must be consistent across matching attributes."),null;if(e===void 0&&(e=I.normalized),e!==I.normalized)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.normalized must be consistent across matching attributes."),null;if(i===-1&&(i=I.gpuType),i!==I.gpuType)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.gpuType must be consistent across matching attributes."),null;n+=I.count*t}const o=new A(n),g=new yt(o,t,e);let a=0;for(let r=0;r<s.length;++r){const I=s[r];if(I.isInterleavedBufferAttribute){const l=a/t;for(let h=0,B=I.count;h<B;h++)for(let E=0;E<t;E++){const c=I.getComponent(h,E);g.setComponent(h+l,E,c)}}else o.set(I.array,a);a+=I.count*t}return i!==void 0&&(g.gpuType=i),g}function um(s,A){if(A===mD)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),s;if(A===Yh||A===LQ){let t=s.getIndex();if(t===null){const n=[],o=s.getAttribute("position");if(o!==void 0){for(let g=0;g<o.count;g++)n.push(g);s.setIndex(n),t=s.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),s}const e=t.count-2,i=[];if(A===Yh)for(let n=1;n<=e;n++)i.push(t.getX(0)),i.push(t.getX(n)),i.push(t.getX(n+1));else for(let n=0;n<e;n++)n%2===0?(i.push(t.getX(n)),i.push(t.getX(n+1)),i.push(t.getX(n+2))):(i.push(t.getX(n+2)),i.push(t.getX(n+1)),i.push(t.getX(n)));return i.length/3!==e&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles."),s.setIndex(i),s.clearGroups(),s}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",A),s}function eX(s){const A=new Map,t=new Map,e=s.clone();return mm(s,e,function(i,n){A.set(n,i),t.set(i,n)}),e.traverse(function(i){if(!i.isSkinnedMesh)return;const n=i,o=A.get(i),g=o.skeleton.bones;n.skeleton=o.skeleton.clone(),n.bindMatrix.copy(o.bindMatrix),n.skeleton.bones=g.map(function(a){return t.get(a)}),n.bind(n.skeleton,n.bindMatrix)}),e}function mm(s,A,t){t(s,A);for(let e=0;e<s.children.length;e++)mm(s.children[e],A.children[e],t)}class K0 extends hi{constructor(A){super(A),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new gX(t)}),this.register(function(t){return new aX(t)}),this.register(function(t){return new QX(t)}),this.register(function(t){return new dX(t)}),this.register(function(t){return new fX(t)}),this.register(function(t){return new IX(t)}),this.register(function(t){return new lX(t)}),this.register(function(t){return new BX(t)}),this.register(function(t){return new hX(t)}),this.register(function(t){return new oX(t)}),this.register(function(t){return new CX(t)}),this.register(function(t){return new rX(t)}),this.register(function(t){return new cX(t)}),this.register(function(t){return new EX(t)}),this.register(function(t){return new sX(t)}),this.register(function(t){return new Pm(t,bt.EXT_MESHOPT_COMPRESSION)}),this.register(function(t){return new Pm(t,bt.KHR_MESHOPT_COMPRESSION)}),this.register(function(t){return new MX(t)})}load(A,t,e,i){const n=this;let o;if(this.resourcePath!=="")o=this.resourcePath;else if(this.path!==""){const r=Ns.extractUrlBase(A);o=Ns.resolveURL(r,this.path)}else o=Ns.extractUrlBase(A);this.manager.itemStart(A);const g=function(r){i?i(r):console.error(r),n.manager.itemError(A),n.manager.itemEnd(A)},a=new mi(this.manager);a.setPath(this.path),a.setResponseType("arraybuffer"),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(A,function(r){try{n.parse(r,o,function(I){t(I),n.manager.itemEnd(A)},g)}catch(I){g(I)}},e,g)}setDRACOLoader(A){return this.dracoLoader=A,this}setKTX2Loader(A){return this.ktx2Loader=A,this}setMeshoptDecoder(A){return this.meshoptDecoder=A,this}register(A){return this.pluginCallbacks.indexOf(A)===-1&&this.pluginCallbacks.push(A),this}unregister(A){return this.pluginCallbacks.indexOf(A)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(A),1),this}parse(A,t,e,i){let n;const o={},g={},a=new TextDecoder;if(typeof A=="string")n=JSON.parse(A);else if(A instanceof ArrayBuffer)if(a.decode(new Uint8Array(A,0,4))===Sm){try{o[bt.KHR_BINARY_GLTF]=new yX(A)}catch(l){i&&i(l);return}n=JSON.parse(o[bt.KHR_BINARY_GLTF].content)}else n=JSON.parse(a.decode(A));else n=A;if(n.asset===void 0||n.asset.version[0]<2){i&&i(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}const r=new TX(n,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});r.fileLoader.setRequestHeader(this.requestHeader);for(let I=0;I<this.pluginCallbacks.length;I++){const l=this.pluginCallbacks[I](r);l.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),g[l.name]=l,o[l.name]=!0}if(n.extensionsUsed)for(let I=0;I<n.extensionsUsed.length;++I){const l=n.extensionsUsed[I],h=n.extensionsRequired||[];switch(l){case bt.KHR_MATERIALS_UNLIT:o[l]=new nX;break;case bt.KHR_DRACO_MESH_COMPRESSION:o[l]=new pX(n,this.dracoLoader);break;case bt.KHR_TEXTURE_TRANSFORM:o[l]=new DX;break;case bt.KHR_MESH_QUANTIZATION:o[l]=new wX;break;default:h.indexOf(l)>=0&&g[l]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+l+'".')}}r.setExtensions(o),r.setPlugins(g),r.parse(e,i)}parseAsync(A,t){const e=this;return new Promise(function(i,n){e.parse(A,t,i,n)})}}function iX(){let s={};return{get:function(A){return s[A]},add:function(A,t){s[A]=t},remove:function(A){delete s[A]},removeAll:function(){s={}}}}function Ge(s,A,t){const e=s.json.materials[A];return e.extensions&&e.extensions[t]?e.extensions[t]:null}const bt={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",KHR_MESHOPT_COMPRESSION:"KHR_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class sX{constructor(A){this.parser=A,this.name=bt.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const A=this.parser,t=this.parser.json.nodes||[];for(let e=0,i=t.length;e<i;e++){const n=t[e];n.extensions&&n.extensions[this.name]&&n.extensions[this.name].light!==void 0&&A._addNodeRef(this.cache,n.extensions[this.name].light)}}_loadLight(A){const t=this.parser,e="light:"+A;let i=t.cache.get(e);if(i)return i;const n=t.json,a=((n.extensions&&n.extensions[this.name]||{}).lights||[])[A];let r;const I=new XA(16777215);a.color!==void 0&&I.setRGB(a.color[0],a.color[1],a.color[2],si);const l=a.range!==void 0?a.range:0;switch(a.type){case"directional":r=new Zs(I),r.target.position.set(0,0,-1),r.add(r.target);break;case"point":r=new t0(I),r.distance=l;break;case"spot":r=new A0(I),r.distance=l,a.spot=a.spot||{},a.spot.innerConeAngle=a.spot.innerConeAngle!==void 0?a.spot.innerConeAngle:0,a.spot.outerConeAngle=a.spot.outerConeAngle!==void 0?a.spot.outerConeAngle:Math.PI/4,r.angle=a.spot.outerConeAngle,r.penumbra=1-a.spot.innerConeAngle/a.spot.outerConeAngle,r.target.position.set(0,0,-1),r.add(r.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+a.type)}return r.position.set(0,0,0),hn(r,a),a.intensity!==void 0&&(r.intensity=a.intensity),r.name=t.createUniqueName(a.name||"light_"+A),i=Promise.resolve(r),t.cache.add(e,i),i}getDependency(A,t){if(A==="light")return this._loadLight(t)}createNodeAttachment(A){const t=this,e=this.parser,n=e.json.nodes[A],g=(n.extensions&&n.extensions[this.name]||{}).light;return g===void 0?null:this._loadLight(g).then(function(a){return e._getNodeRef(t.cache,g,a)})}}class nX{constructor(){this.name=bt.KHR_MATERIALS_UNLIT}getMaterialType(){return Kt}extendParams(A,t,e){const i=[];A.color=new XA(1,1,1),A.opacity=1;const n=t.pbrMetallicRoughness;if(n){if(Array.isArray(n.baseColorFactor)){const o=n.baseColorFactor;A.color.setRGB(o[0],o[1],o[2],si),A.opacity=o[3]}n.baseColorTexture!==void 0&&i.push(e.assignTexture(A,"map",n.baseColorTexture,Rt))}return Promise.all(i)}}class oX{constructor(A){this.parser=A,this.name=bt.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(A,t){const e=Ge(this.parser,A,this.name);return e===null||e.emissiveStrength!==void 0&&(t.emissiveIntensity=e.emissiveStrength),Promise.resolve()}}class gX{constructor(A){this.parser=A,this.name=bt.KHR_MATERIALS_CLEARCOAT}getMaterialType(A){return Ge(this.parser,A,this.name)!==null?ds:null}extendMaterialParams(A,t){const e=Ge(this.parser,A,this.name);if(e===null)return Promise.resolve();const i=[];if(e.clearcoatFactor!==void 0&&(t.clearcoat=e.clearcoatFactor),e.clearcoatTexture!==void 0&&i.push(this.parser.assignTexture(t,"clearcoatMap",e.clearcoatTexture)),e.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=e.clearcoatRoughnessFactor),e.clearcoatRoughnessTexture!==void 0&&i.push(this.parser.assignTexture(t,"clearcoatRoughnessMap",e.clearcoatRoughnessTexture)),e.clearcoatNormalTexture!==void 0&&(i.push(this.parser.assignTexture(t,"clearcoatNormalMap",e.clearcoatNormalTexture)),e.clearcoatNormalTexture.scale!==void 0)){const n=e.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new MA(n,n)}return Promise.all(i)}}class aX{constructor(A){this.parser=A,this.name=bt.KHR_MATERIALS_DISPERSION}getMaterialType(A){return Ge(this.parser,A,this.name)!==null?ds:null}extendMaterialParams(A,t){const e=Ge(this.parser,A,this.name);return e===null||(t.dispersion=e.dispersion!==void 0?e.dispersion:0),Promise.resolve()}}class rX{constructor(A){this.parser=A,this.name=bt.KHR_MATERIALS_IRIDESCENCE}getMaterialType(A){return Ge(this.parser,A,this.name)!==null?ds:null}extendMaterialParams(A,t){const e=Ge(this.parser,A,this.name);if(e===null)return Promise.resolve();const i=[];return e.iridescenceFactor!==void 0&&(t.iridescence=e.iridescenceFactor),e.iridescenceTexture!==void 0&&i.push(this.parser.assignTexture(t,"iridescenceMap",e.iridescenceTexture)),e.iridescenceIor!==void 0&&(t.iridescenceIOR=e.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),e.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=e.iridescenceThicknessMinimum),e.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=e.iridescenceThicknessMaximum),e.iridescenceThicknessTexture!==void 0&&i.push(this.parser.assignTexture(t,"iridescenceThicknessMap",e.iridescenceThicknessTexture)),Promise.all(i)}}class IX{constructor(A){this.parser=A,this.name=bt.KHR_MATERIALS_SHEEN}getMaterialType(A){return Ge(this.parser,A,this.name)!==null?ds:null}extendMaterialParams(A,t){const e=Ge(this.parser,A,this.name);if(e===null)return Promise.resolve();const i=[];if(t.sheenColor=new XA(0,0,0),t.sheenRoughness=0,t.sheen=1,e.sheenColorFactor!==void 0){const n=e.sheenColorFactor;t.sheenColor.setRGB(n[0],n[1],n[2],si)}return e.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=e.sheenRoughnessFactor),e.sheenColorTexture!==void 0&&i.push(this.parser.assignTexture(t,"sheenColorMap",e.sheenColorTexture,Rt)),e.sheenRoughnessTexture!==void 0&&i.push(this.parser.assignTexture(t,"sheenRoughnessMap",e.sheenRoughnessTexture)),Promise.all(i)}}class lX{constructor(A){this.parser=A,this.name=bt.KHR_MATERIALS_TRANSMISSION}getMaterialType(A){return Ge(this.parser,A,this.name)!==null?ds:null}extendMaterialParams(A,t){const e=Ge(this.parser,A,this.name);if(e===null)return Promise.resolve();const i=[];return e.transmissionFactor!==void 0&&(t.transmission=e.transmissionFactor),e.transmissionTexture!==void 0&&i.push(this.parser.assignTexture(t,"transmissionMap",e.transmissionTexture)),Promise.all(i)}}class BX{constructor(A){this.parser=A,this.name=bt.KHR_MATERIALS_VOLUME}getMaterialType(A){return Ge(this.parser,A,this.name)!==null?ds:null}extendMaterialParams(A,t){const e=Ge(this.parser,A,this.name);if(e===null)return Promise.resolve();const i=[];t.thickness=e.thicknessFactor!==void 0?e.thicknessFactor:0,e.thicknessTexture!==void 0&&i.push(this.parser.assignTexture(t,"thicknessMap",e.thicknessTexture)),t.attenuationDistance=e.attenuationDistance||1/0;const n=e.attenuationColor||[1,1,1];return t.attenuationColor=new XA().setRGB(n[0],n[1],n[2],si),Promise.all(i)}}class hX{constructor(A){this.parser=A,this.name=bt.KHR_MATERIALS_IOR}getMaterialType(A){return Ge(this.parser,A,this.name)!==null?ds:null}extendMaterialParams(A,t){const e=Ge(this.parser,A,this.name);return e===null||(t.ior=e.ior!==void 0?e.ior:1.5,t.ior===0&&(t.ior=1e3)),Promise.resolve()}}class CX{constructor(A){this.parser=A,this.name=bt.KHR_MATERIALS_SPECULAR}getMaterialType(A){return Ge(this.parser,A,this.name)!==null?ds:null}extendMaterialParams(A,t){const e=Ge(this.parser,A,this.name);if(e===null)return Promise.resolve();const i=[];t.specularIntensity=e.specularFactor!==void 0?e.specularFactor:1,e.specularTexture!==void 0&&i.push(this.parser.assignTexture(t,"specularIntensityMap",e.specularTexture));const n=e.specularColorFactor||[1,1,1];return t.specularColor=new XA().setRGB(n[0],n[1],n[2],si),e.specularColorTexture!==void 0&&i.push(this.parser.assignTexture(t,"specularColorMap",e.specularColorTexture,Rt)),Promise.all(i)}}class EX{constructor(A){this.parser=A,this.name=bt.EXT_MATERIALS_BUMP}getMaterialType(A){return Ge(this.parser,A,this.name)!==null?ds:null}extendMaterialParams(A,t){const e=Ge(this.parser,A,this.name);if(e===null)return Promise.resolve();const i=[];return t.bumpScale=e.bumpFactor!==void 0?e.bumpFactor:1,e.bumpTexture!==void 0&&i.push(this.parser.assignTexture(t,"bumpMap",e.bumpTexture)),Promise.all(i)}}class cX{constructor(A){this.parser=A,this.name=bt.KHR_MATERIALS_ANISOTROPY}getMaterialType(A){return Ge(this.parser,A,this.name)!==null?ds:null}extendMaterialParams(A,t){const e=Ge(this.parser,A,this.name);if(e===null)return Promise.resolve();const i=[];return e.anisotropyStrength!==void 0&&(t.anisotropy=e.anisotropyStrength),e.anisotropyRotation!==void 0&&(t.anisotropyRotation=e.anisotropyRotation),e.anisotropyTexture!==void 0&&i.push(this.parser.assignTexture(t,"anisotropyMap",e.anisotropyTexture)),Promise.all(i)}}class QX{constructor(A){this.parser=A,this.name=bt.KHR_TEXTURE_BASISU}loadTexture(A){const t=this.parser,e=t.json,i=e.textures[A];if(!i.extensions||!i.extensions[this.name])return null;const n=i.extensions[this.name],o=t.options.ktx2Loader;if(!o){if(e.extensionsRequired&&e.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(A,n.source,o)}}class dX{constructor(A){this.parser=A,this.name=bt.EXT_TEXTURE_WEBP}loadTexture(A){const t=this.name,e=this.parser,i=e.json,n=i.textures[A];if(!n.extensions||!n.extensions[t])return null;const o=n.extensions[t],g=i.images[o.source];let a=e.textureLoader;if(g.uri){const r=e.options.manager.getHandler(g.uri);r!==null&&(a=r)}return e.loadTextureImage(A,o.source,a)}}class fX{constructor(A){this.parser=A,this.name=bt.EXT_TEXTURE_AVIF}loadTexture(A){const t=this.name,e=this.parser,i=e.json,n=i.textures[A];if(!n.extensions||!n.extensions[t])return null;const o=n.extensions[t],g=i.images[o.source];let a=e.textureLoader;if(g.uri){const r=e.options.manager.getHandler(g.uri);r!==null&&(a=r)}return e.loadTextureImage(A,o.source,a)}}class Pm{constructor(A,t){this.name=t,this.parser=A}loadBufferView(A){const t=this.parser.json,e=t.bufferViews[A];if(e.extensions&&e.extensions[this.name]){const i=e.extensions[this.name],n=this.parser.getDependency("buffer",i.buffer),o=this.parser.options.meshoptDecoder;if(!o||!o.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return n.then(function(g){const a=i.byteOffset||0,r=i.byteLength||0,I=i.count,l=i.byteStride,h=new Uint8Array(g,a,r);return o.decodeGltfBufferAsync?o.decodeGltfBufferAsync(I,l,h,i.mode,i.filter).then(function(B){return B.buffer}):o.ready.then(function(){const B=new ArrayBuffer(I*l);return o.decodeGltfBuffer(new Uint8Array(B),I,l,h,i.mode,i.filter),B})})}else return null}}class MX{constructor(A){this.name=bt.EXT_MESH_GPU_INSTANCING,this.parser=A}createNodeMesh(A){const t=this.parser.json,e=t.nodes[A];if(!e.extensions||!e.extensions[this.name]||e.mesh===void 0)return null;const i=t.meshes[e.mesh];for(const r of i.primitives)if(r.mode!==ps.TRIANGLES&&r.mode!==ps.TRIANGLE_STRIP&&r.mode!==ps.TRIANGLE_FAN&&r.mode!==void 0)return null;const o=e.extensions[this.name].attributes,g=[],a={};for(const r in o)g.push(this.parser.getDependency("accessor",o[r]).then(I=>(a[r]=I,a[r])));return g.length<1?null:(g.push(this.parser.createNodeMesh(A)),Promise.all(g).then(r=>{const I=r.pop(),l=I.isGroup?I.children:[I],h=r[0].count,B=[];for(const E of l){const c=new RA,Q=new S,C=new wt,d=new S(1,1,1),M=new ct(E.geometry,E.material,h);for(let w=0;w<h;w++)a.TRANSLATION&&Q.fromBufferAttribute(a.TRANSLATION,w),a.ROTATION&&C.fromBufferAttribute(a.ROTATION,w),a.SCALE&&d.fromBufferAttribute(a.SCALE,w),M.setMatrixAt(w,c.compose(Q,C,d));let y=null;for(const w in a)if(w==="_COLOR_0"){const D=a[w];M.instanceColor=new Un(D.array,D.itemSize,D.normalized)}else if(w!=="TRANSLATION"&&w!=="ROTATION"&&w!=="SCALE"){if(y===null){const p=M.geometry;y=new et,y.name=p.name;for(const f in p.attributes)y.setAttribute(f,p.attributes[f]);for(const f in p.morphAttributes)y.morphAttributes[f]=p.morphAttributes[f];p.index!==null&&y.setIndex(p.index),y.morphTargetsRelative=p.morphTargetsRelative;for(const f of p.groups)y.addGroup(f.start,f.count,f.materialIndex);p.boundingBox!==null&&(y.boundingBox=p.boundingBox.clone()),p.boundingSphere!==null&&(y.boundingSphere=p.boundingSphere.clone()),y.drawRange.start=p.drawRange.start,y.drawRange.count=p.drawRange.count,y.userData=Object.assign({},p.userData),M.geometry=y}const D=a[w];y.setAttribute(w,new Un(D.array,D.itemSize,D.normalized))}Et.prototype.copy.call(M,E),this.parser.assignFinalMaterial(M),B.push(M)}return I.isGroup?(I.clear(),I.add(...B),I):B[0]}))}}const Sm="glTF",cl=12,Ym={JSON:1313821514,BIN:5130562};class yX{constructor(A){this.name=bt.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(A,0,cl),e=new TextDecoder;if(this.header={magic:e.decode(new Uint8Array(A.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==Sm)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");const i=this.header.length-cl,n=new DataView(A,cl);let o=0;for(;o<i;){const g=n.getUint32(o,!0);o+=4;const a=n.getUint32(o,!0);if(o+=4,a===Ym.JSON){const r=new Uint8Array(A,cl+o,g);this.content=e.decode(r)}else if(a===Ym.BIN){const r=cl+o;this.body=A.slice(r,r+g)}o+=g}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class pX{constructor(A,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=bt.KHR_DRACO_MESH_COMPRESSION,this.json=A,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(A,t){const e=this.json,i=this.dracoLoader,n=A.extensions[this.name].bufferView,o=A.extensions[this.name].attributes,g={},a={},r={};for(const I in o){const l=R0[I]||I.toLowerCase();g[l]=o[I]}for(const I in A.attributes){const l=R0[I]||I.toLowerCase();if(o[I]!==void 0){const h=e.accessors[A.attributes[I]],B=Dr[h.componentType];r[l]=B.name,a[l]=h.normalized===!0}}return t.getDependency("bufferView",n).then(function(I){return new Promise(function(l,h){i.decodeDracoFile(I,function(B){for(const E in B.attributes){const c=B.attributes[E],Q=a[E];Q!==void 0&&(c.normalized=Q)}l(B)},g,r,si,h)})})}}class DX{constructor(){this.name=bt.KHR_TEXTURE_TRANSFORM}extendTexture(A,t){if((t.texCoord===void 0||t.texCoord===A.channel)&&t.offset===void 0&&t.rotation===void 0&&t.scale===void 0)return A;if(A=A.clone(),t.texCoord!==void 0&&(A.channel=t.texCoord),t.offset!==void 0&&A.offset.fromArray(t.offset),t.rotation!==void 0&&(A.rotation=t.rotation),t.scale!==void 0&&A.repeat.fromArray(t.scale),t.rotation!==void 0){const e=Math.cos(A.rotation),i=Math.sin(A.rotation);A.matrix.set(A.repeat.x*e,A.repeat.y*i,A.offset.x,-A.repeat.x*i,A.repeat.y*e,A.offset.y,0,0,1),A.matrixAutoUpdate=!1}return A.needsUpdate=!0,A}}class wX{constructor(){this.name=bt.KHR_MESH_QUANTIZATION}}class Fm extends pg{constructor(A,t,e,i){super(A,t,e,i)}copySampleValue_(A){const t=this.resultBuffer,e=this.sampleValues,i=this.valueSize,n=A*i*3+i;for(let o=0;o!==i;o++)t[o]=e[n+o];return t}interpolate_(A,t,e,i){const n=this.resultBuffer,o=this.sampleValues,g=this.valueSize,a=g*2,r=g*3,I=i-t,l=(e-t)/I,h=l*l,B=h*l,E=A*r,c=E-r,Q=-2*B+3*h,C=B-h,d=1-Q,M=C-h+l;for(let y=0;y!==g;y++){const w=o[c+y+g],D=o[c+y+a]*I,p=o[E+y+g],f=o[E+y]*I;n[y]=d*w+M*D+Q*p+C*f}return n}}const uX=new wt;class mX extends Fm{interpolate_(A,t,e,i){const n=super.interpolate_(A,t,e,i);return uX.fromArray(n).normalize().toArray(n),n}}const ps={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},Dr={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},bm={9728:xt,9729:Yt,9984:BI,9985:Sa,9986:ng,9987:Oi},Wm={33071:Gi,33648:Pa,10497:Ue},j0={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},R0={POSITION:"position",NORMAL:"normal",TANGENT:"tangent",TEXCOORD_0:"uv",TEXCOORD_1:"uv1",TEXCOORD_2:"uv2",TEXCOORD_3:"uv3",COLOR_0:"color",WEIGHTS_0:"skinWeight",JOINTS_0:"skinIndex"},bo={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},PX={CUBICSPLINE:void 0,LINEAR:ja,STEP:Ka},Z0={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function SX(s){return s.DefaultMaterial===void 0&&(s.DefaultMaterial=new mo({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:es})),s.DefaultMaterial}function Gg(s,A,t){for(const e in t.extensions)s[e]===void 0&&(A.userData.gltfExtensions=A.userData.gltfExtensions||{},A.userData.gltfExtensions[e]=t.extensions[e])}function hn(s,A){A.extras!==void 0&&(typeof A.extras=="object"?Object.assign(s.userData,A.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+A.extras))}function YX(s,A,t){let e=!1,i=!1,n=!1;for(let r=0,I=A.length;r<I;r++){const l=A[r];if(l.POSITION!==void 0&&(e=!0),l.NORMAL!==void 0&&(i=!0),l.COLOR_0!==void 0&&(n=!0),e&&i&&n)break}if(!e&&!i&&!n)return Promise.resolve(s);const o=[],g=[],a=[];for(let r=0,I=A.length;r<I;r++){const l=A[r];if(e){const h=l.POSITION!==void 0?t.getDependency("accessor",l.POSITION):s.attributes.position;o.push(h)}if(i){const h=l.NORMAL!==void 0?t.getDependency("accessor",l.NORMAL):s.attributes.normal;g.push(h)}if(n){const h=l.COLOR_0!==void 0?t.getDependency("accessor",l.COLOR_0):s.attributes.color;a.push(h)}}return Promise.all([Promise.all(o),Promise.all(g),Promise.all(a)]).then(function(r){const I=r[0],l=r[1],h=r[2];return e&&(s.morphAttributes.position=I),i&&(s.morphAttributes.normal=l),n&&(s.morphAttributes.color=h),s.morphTargetsRelative=!0,s})}function FX(s,A){if(s.updateMorphTargets(),A.weights!==void 0)for(let t=0,e=A.weights.length;t<e;t++)s.morphTargetInfluences[t]=A.weights[t];if(A.extras&&Array.isArray(A.extras.targetNames)){const t=A.extras.targetNames;if(s.morphTargetInfluences.length===t.length){s.morphTargetDictionary={};for(let e=0,i=t.length;e<i;e++)s.morphTargetDictionary[t[e]]=e}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function bX(s){let A;const t=s.extensions&&s.extensions[bt.KHR_DRACO_MESH_COMPRESSION];if(t?A="draco:"+t.bufferView+":"+t.indices+":"+N0(t.attributes):A=s.indices+":"+N0(s.attributes)+":"+s.mode,s.targets!==void 0)for(let e=0,i=s.targets.length;e<i;e++)A+=":"+N0(s.targets[e]);return A}function N0(s){let A="";const t=Object.keys(s).sort();for(let e=0,i=t.length;e<i;e++)A+=t[e]+":"+s[t[e]]+";";return A}function U0(s){switch(s){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type.")}}function WX(s){return s.search(/\.jpe?g($|\?)/i)>0||s.search(/^data\:image\/jpeg/)===0?"image/jpeg":s.search(/\.webp($|\?)/i)>0||s.search(/^data\:image\/webp/)===0?"image/webp":s.search(/\.ktx2($|\?)/i)>0||s.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}const GX=new RA;class TX{constructor(A={},t={}){this.json=A,this.extensions={},this.plugins={},this.options=t,this.cache=new iX,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let e=!1,i=-1,n=!1,o=-1;if(typeof navigator<"u"&&typeof navigator.userAgent<"u"){const g=navigator.userAgent;e=/^((?!chrome|android).)*safari/i.test(g)===!0;const a=g.match(/Version\/(\d+)/);i=e&&a?parseInt(a[1],10):-1,n=g.indexOf("Firefox")>-1,o=n?g.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||e&&i<17||n&&o<98?this.textureLoader=new kn(this.options.manager):this.textureLoader=new Qu(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new mi(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(A){this.extensions=A}setPlugins(A){this.plugins=A}parse(A,t){const e=this,i=this.json,n=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(o){return o._markDefs&&o._markDefs()}),Promise.all(this._invokeAll(function(o){return o.beforeRoot&&o.beforeRoot()})).then(function(){return Promise.all([e.getDependencies("scene"),e.getDependencies("animation"),e.getDependencies("camera")])}).then(function(o){const g={scene:o[0][i.scene||0],scenes:o[0],animations:o[1],cameras:o[2],asset:i.asset,parser:e,userData:{}};return Gg(n,g,i),hn(g,i),Promise.all(e._invokeAll(function(a){return a.afterRoot&&a.afterRoot(g)})).then(function(){for(const a of g.scenes)a.updateMatrixWorld();A(g)})}).catch(t)}_markDefs(){const A=this.json.nodes||[],t=this.json.skins||[],e=this.json.meshes||[];for(let i=0,n=t.length;i<n;i++){const o=t[i].joints;for(let g=0,a=o.length;g<a;g++)A[o[g]].isBone=!0}for(let i=0,n=A.length;i<n;i++){const o=A[i];o.mesh!==void 0&&(this._addNodeRef(this.meshCache,o.mesh),o.skin!==void 0&&(e[o.mesh].isSkinnedMesh=!0)),o.camera!==void 0&&this._addNodeRef(this.cameraCache,o.camera)}}_addNodeRef(A,t){t!==void 0&&(A.refs[t]===void 0&&(A.refs[t]=A.uses[t]=0),A.refs[t]++)}_getNodeRef(A,t,e){if(A.refs[t]<=1)return e;const i=e.clone(),n=(o,g)=>{const a=this.associations.get(o);a!=null&&this.associations.set(g,a);for(const[r,I]of o.children.entries())n(I,g.children[r])};return n(e,i),i.name+="_instance_"+A.uses[t]++,i}_invokeOne(A){const t=Object.values(this.plugins);t.push(this);for(let e=0;e<t.length;e++){const i=A(t[e]);if(i)return i}return null}_invokeAll(A){const t=Object.values(this.plugins);t.unshift(this);const e=[];for(let i=0;i<t.length;i++){const n=A(t[i]);n&&e.push(n)}return e}getDependency(A,t){const e=A+":"+t;let i=this.cache.get(e);if(!i){switch(A){case"scene":i=this.loadScene(t);break;case"node":i=this._invokeOne(function(n){return n.loadNode&&n.loadNode(t)});break;case"mesh":i=this._invokeOne(function(n){return n.loadMesh&&n.loadMesh(t)});break;case"accessor":i=this.loadAccessor(t);break;case"bufferView":i=this._invokeOne(function(n){return n.loadBufferView&&n.loadBufferView(t)});break;case"buffer":i=this.loadBuffer(t);break;case"material":i=this._invokeOne(function(n){return n.loadMaterial&&n.loadMaterial(t)});break;case"texture":i=this._invokeOne(function(n){return n.loadTexture&&n.loadTexture(t)});break;case"skin":i=this.loadSkin(t);break;case"animation":i=this._invokeOne(function(n){return n.loadAnimation&&n.loadAnimation(t)});break;case"camera":i=this.loadCamera(t);break;default:if(i=this._invokeOne(function(n){return n!=this&&n.getDependency&&n.getDependency(A,t)}),!i)throw new Error("Unknown type: "+A);break}this.cache.add(e,i)}return i}getDependencies(A){let t=this.cache.get(A);if(!t){const e=this,i=this.json[A+(A==="mesh"?"es":"s")]||[];t=Promise.all(i.map(function(n,o){return e.getDependency(A,o)})),this.cache.add(A,t)}return t}loadBuffer(A){const t=this.json.buffers[A],e=this.fileLoader;if(t.type&&t.type!=="arraybuffer")throw new Error("THREE.GLTFLoader: "+t.type+" buffer type is not supported.");if(t.uri===void 0&&A===0)return Promise.resolve(this.extensions[bt.KHR_BINARY_GLTF].body);const i=this.options;return new Promise(function(n,o){e.load(Ns.resolveURL(t.uri,i.path),n,void 0,function(){o(new Error('THREE.GLTFLoader: Failed to load buffer "'+t.uri+'".'))})})}loadBufferView(A){const t=this.json.bufferViews[A];return this.getDependency("buffer",t.buffer).then(function(e){const i=t.byteLength||0,n=t.byteOffset||0;return e.slice(n,n+i)})}loadAccessor(A){const t=this,e=this.json,i=this.json.accessors[A];if(i.bufferView===void 0&&i.sparse===void 0){const o=j0[i.type],g=Dr[i.componentType],a=i.normalized===!0,r=new g(i.count*o);return Promise.resolve(new yt(r,o,a))}const n=[];return i.bufferView!==void 0?n.push(this.getDependency("bufferView",i.bufferView)):n.push(null),i.sparse!==void 0&&(n.push(this.getDependency("bufferView",i.sparse.indices.bufferView)),n.push(this.getDependency("bufferView",i.sparse.values.bufferView))),Promise.all(n).then(function(o){const g=o[0],a=j0[i.type],r=Dr[i.componentType],I=r.BYTES_PER_ELEMENT,l=I*a,h=i.byteOffset||0,B=i.bufferView!==void 0?e.bufferViews[i.bufferView].byteStride:void 0,E=i.normalized===!0;let c,Q;if(B&&B!==l){const C=Math.floor(h/B),d="InterleavedBuffer:"+i.bufferView+":"+i.componentType+":"+C+":"+i.count;let M=t.cache.get(d);M||(c=new r(g,C*B,i.count*B/I),M=new va(c,B/I),t.cache.add(d,M)),Q=new ji(M,a,h%B/I,E)}else g===null?c=new r(i.count*a):c=new r(g,h,i.count*a),Q=new yt(c,a,E);if(i.sparse!==void 0){const C=j0.SCALAR,d=Dr[i.sparse.indices.componentType],M=i.sparse.indices.byteOffset||0,y=i.sparse.values.byteOffset||0,w=new d(o[1],M,i.sparse.count*C),D=new r(o[2],y,i.sparse.count*a);g!==null&&(Q=new yt(Q.array.slice(),Q.itemSize,Q.normalized)),Q.normalized=!1;for(let p=0,f=w.length;p<f;p++){const u=w[p];if(Q.setX(u,D[p*a]),a>=2&&Q.setY(u,D[p*a+1]),a>=3&&Q.setZ(u,D[p*a+2]),a>=4&&Q.setW(u,D[p*a+3]),a>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}Q.normalized=E}return Q})}loadTexture(A){const t=this.json,e=this.options,n=t.textures[A].source,o=t.images[n];let g=this.textureLoader;if(o.uri){const a=e.manager.getHandler(o.uri);a!==null&&(g=a)}return this.loadTextureImage(A,n,g)}loadTextureImage(A,t,e){const i=this,n=this.json,o=n.textures[A],g=n.images[t],a=(g.uri||g.bufferView)+":"+o.sampler;if(this.textureCache[a])return this.textureCache[a];const r=this.loadImageSource(t,e).then(function(I){I.flipY=!1,I.name=o.name||g.name||"",I.name===""&&typeof g.uri=="string"&&g.uri.startsWith("data:image/")===!1&&(I.name=g.uri);const h=(n.samplers||{})[o.sampler]||{};return I.magFilter=bm[h.magFilter]||Yt,I.minFilter=bm[h.minFilter]||Oi,I.wrapS=Wm[h.wrapS]||Ue,I.wrapT=Wm[h.wrapT]||Ue,I.generateMipmaps=!I.isCompressedTexture&&I.minFilter!==xt&&I.minFilter!==Yt,i.associations.set(I,{textures:A}),I}).catch(function(){return null});return this.textureCache[a]=r,r}loadImageSource(A,t){const e=this,i=this.json,n=this.options;if(this.sourceCache[A]!==void 0)return this.sourceCache[A].then(l=>l.clone());const o=i.images[A],g=self.URL||self.webkitURL;let a=o.uri||"",r=!1;if(o.bufferView!==void 0)a=e.getDependency("bufferView",o.bufferView).then(function(l){r=!0;const h=new Blob([l],{type:o.mimeType});return a=g.createObjectURL(h),a});else if(o.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+A+" is missing URI and bufferView");const I=Promise.resolve(a).then(function(l){return new Promise(function(h,B){let E=h;t.isImageBitmapLoader===!0&&(E=function(c){const Q=new Ft(c);Q.needsUpdate=!0,h(Q)}),t.load(Ns.resolveURL(l,n.path),E,void 0,B)})}).then(function(l){return r===!0&&g.revokeObjectURL(a),hn(l,o),l.userData.mimeType=o.mimeType||WX(o.uri),l}).catch(function(l){throw console.error("THREE.GLTFLoader: Couldn't load texture",a),l});return this.sourceCache[A]=I,I}assignTexture(A,t,e,i){const n=this;return this.getDependency("texture",e.index).then(function(o){if(!o)return null;if(e.texCoord!==void 0&&e.texCoord>0&&(o=o.clone(),o.channel=e.texCoord),n.extensions[bt.KHR_TEXTURE_TRANSFORM]){const g=e.extensions!==void 0?e.extensions[bt.KHR_TEXTURE_TRANSFORM]:void 0;if(g){const a=n.associations.get(o);o=n.extensions[bt.KHR_TEXTURE_TRANSFORM].extendTexture(o,g),n.associations.set(o,a)}}return i!==void 0&&(o.colorSpace=i),A[t]=o,o})}assignFinalMaterial(A){const t=A.geometry;let e=A.material;const i=t.attributes.tangent===void 0,n=t.attributes.color!==void 0,o=t.attributes.normal===void 0;if(A.isPoints){const g="PointsMaterial:"+e.uuid;let a=this.cache.get(g);a||(a=new QC,Ie.prototype.copy.call(a,e),a.color.copy(e.color),a.map=e.map,a.sizeAttenuation=!1,this.cache.add(g,a)),e=a}else if(A.isLine){const g="LineBasicMaterial:"+e.uuid;let a=this.cache.get(g);a||(a=new se,Ie.prototype.copy.call(a,e),a.color.copy(e.color),a.map=e.map,this.cache.add(g,a)),e=a}if(i||n||o){let g="ClonedMaterial:"+e.uuid+":";i&&(g+="derivative-tangents:"),n&&(g+="vertex-colors:"),o&&(g+="flat-shading:");let a=this.cache.get(g);a||(a=e.clone(),n&&(a.vertexColors=!0),o&&(a.flatShading=!0),i&&(a.normalScale&&(a.normalScale.y*=-1),a.clearcoatNormalScale&&(a.clearcoatNormalScale.y*=-1)),this.cache.add(g,a),this.associations.set(a,this.associations.get(e))),e=a}A.material=e}getMaterialType(){return mo}loadMaterial(A){const t=this,e=this.json,i=this.extensions,n=e.materials[A];let o;const g={},a=n.extensions||{},r=[];if(a[bt.KHR_MATERIALS_UNLIT]){const l=i[bt.KHR_MATERIALS_UNLIT];o=l.getMaterialType(),r.push(l.extendParams(g,n,t))}else{const l=n.pbrMetallicRoughness||{};if(g.color=new XA(1,1,1),g.opacity=1,Array.isArray(l.baseColorFactor)){const h=l.baseColorFactor;g.color.setRGB(h[0],h[1],h[2],si),g.opacity=h[3]}l.baseColorTexture!==void 0&&r.push(t.assignTexture(g,"map",l.baseColorTexture,Rt)),g.metalness=l.metallicFactor!==void 0?l.metallicFactor:1,g.roughness=l.roughnessFactor!==void 0?l.roughnessFactor:1,l.metallicRoughnessTexture!==void 0&&(r.push(t.assignTexture(g,"metalnessMap",l.metallicRoughnessTexture)),r.push(t.assignTexture(g,"roughnessMap",l.metallicRoughnessTexture))),o=this._invokeOne(function(h){return h.getMaterialType&&h.getMaterialType(A)}),r.push(Promise.all(this._invokeAll(function(h){return h.extendMaterialParams&&h.extendMaterialParams(A,g)})))}n.doubleSided===!0&&(g.side=Tt);const I=n.alphaMode||Z0.OPAQUE;if(I===Z0.BLEND?(g.transparent=!0,g.depthWrite=!1):(g.transparent=!1,I===Z0.MASK&&(g.alphaTest=n.alphaCutoff!==void 0?n.alphaCutoff:.5)),n.normalTexture!==void 0&&o!==Kt&&(r.push(t.assignTexture(g,"normalMap",n.normalTexture)),g.normalScale=new MA(1,1),n.normalTexture.scale!==void 0)){const l=n.normalTexture.scale;g.normalScale.set(l,l)}if(n.occlusionTexture!==void 0&&o!==Kt&&(r.push(t.assignTexture(g,"aoMap",n.occlusionTexture)),n.occlusionTexture.strength!==void 0&&(g.aoMapIntensity=n.occlusionTexture.strength)),n.emissiveFactor!==void 0&&o!==Kt){const l=n.emissiveFactor;g.emissive=new XA().setRGB(l[0],l[1],l[2],si)}return n.emissiveTexture!==void 0&&o!==Kt&&r.push(t.assignTexture(g,"emissiveMap",n.emissiveTexture,Rt)),Promise.all(r).then(function(){const l=new o(g);return n.name&&(l.name=n.name),hn(l,n),t.associations.set(l,{materials:A}),n.extensions&&Gg(i,l,n),l})}createUniqueName(A){const t=jt.sanitizeNodeName(A||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(A){const t=this,e=this.extensions,i=this.primitiveCache;function n(g){return e[bt.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(g,t).then(function(a){return Gm(a,g,t)})}const o=[];for(let g=0,a=A.length;g<a;g++){const r=A[g],I=bX(r),l=i[I];if(l)o.push(l.promise);else{let h;r.extensions&&r.extensions[bt.KHR_DRACO_MESH_COMPRESSION]?h=n(r):h=Gm(new et,r,t),r.mode===ps.TRIANGLE_STRIP?h=h.then(B=>um(B,LQ)):r.mode===ps.TRIANGLE_FAN&&(h=h.then(B=>um(B,Yh))),i[I]={primitive:r,promise:h},o.push(h)}}return Promise.all(o)}loadMesh(A){const t=this,e=this.json,i=this.extensions,n=e.meshes[A],o=n.primitives,g=[];for(let a=0,r=o.length;a<r;a++){const I=o[a].material===void 0?SX(this.cache):this.getDependency("material",o[a].material);g.push(I)}return g.push(t.loadGeometries(o)),Promise.all(g).then(async function(a){const r=a.slice(0,a.length-1),I=a[a.length-1],l=[];for(let B=0,E=I.length;B<E;B++){const c=I[B],Q=o[B];let C;const d=r[B];if(Q.mode===ps.TRIANGLES||Q.mode===ps.TRIANGLE_STRIP||Q.mode===ps.TRIANGLE_FAN||Q.mode===void 0){const M=n.isSkinnedMesh===!0,y=c.hasAttribute("skinIndex")&&c.hasAttribute("skinWeight");M&&y===!1&&console.warn("THREE.GLTFLoader: Missing skinIndex or skinWeight attributes. Skinning disabled."),C=M&&y?new pd(c,d):new bA(c,d),C.isSkinnedMesh===!0&&C.normalizeSkinWeights()}else if(Q.mode===ps.LINES)C=new Bi(c,d);else if(Q.mode===ps.LINE_STRIP)C=new he(c,d);else if(Q.mode===ps.LINE_LOOP)C=new er(c,d);else if(Q.mode===ps.POINTS)C=new ir(c,d);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+Q.mode);Object.keys(C.geometry.morphAttributes).length>0&&FX(C,n),C.name=t.createUniqueName(n.name||"mesh_"+A),hn(C,n),Q.extensions&&Gg(i,C,Q),t.assignFinalMaterial(C),l.push(C)}for(let B=0,E=l.length;B<E;B++)t.associations.set(l[B],{meshes:A,primitives:B});if(l.length===1)return n.extensions&&Gg(i,l[0],n),l[0];const h=new Ot;n.extensions&&Gg(i,h,n),t.associations.set(h,{meshes:A});for(let B=0,E=l.length;B<E;B++)h.add(l[B]);return h})}loadCamera(A){let t;const e=this.json.cameras[A],i=e[e.type];if(!i){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}return e.type==="perspective"?t=new Ce(rt.radToDeg(i.yfov),i.aspectRatio||1,i.znear||1,i.zfar||2e6):e.type==="orthographic"&&(t=new ze(-i.xmag,i.xmag,i.ymag,-i.ymag,i.znear,i.zfar)),e.name&&(t.name=this.createUniqueName(e.name)),hn(t,e),Promise.resolve(t)}loadSkin(A){const t=this.json.skins[A],e=[];for(let i=0,n=t.joints.length;i<n;i++)e.push(this._loadNodeShallow(t.joints[i]));return t.inverseBindMatrices!==void 0?e.push(this.getDependency("accessor",t.inverseBindMatrices)):e.push(null),Promise.all(e).then(function(i){const n=i.pop(),o=i,g=[],a=[];for(let r=0,I=o.length;r<I;r++){const l=o[r];if(l){g.push(l);const h=new RA;n!==null&&h.fromArray(n.array,r*16),a.push(h)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[r])}return new kI(g,a)})}loadAnimation(A){const t=this.json,e=this,i=t.animations[A],n=i.name?i.name:"animation_"+A,o=[],g=[],a=[],r=[],I=[];for(let l=0,h=i.channels.length;l<h;l++){const B=i.channels[l],E=i.samplers[B.sampler],c=B.target,Q=c.node,C=i.parameters!==void 0?i.parameters[E.input]:E.input,d=i.parameters!==void 0?i.parameters[E.output]:E.output;c.node!==void 0&&(o.push(this.getDependency("node",Q)),g.push(this.getDependency("accessor",C)),a.push(this.getDependency("accessor",d)),r.push(E),I.push(c))}return Promise.all([Promise.all(o),Promise.all(g),Promise.all(a),Promise.all(r),Promise.all(I)]).then(function(l){const h=l[0],B=l[1],E=l[2],c=l[3],Q=l[4],C=[];for(let M=0,y=h.length;M<y;M++){const w=h[M],D=B[M],p=E[M],f=c[M],u=Q[M];if(w===void 0)continue;w.updateMatrix&&w.updateMatrix();const Y=e._createAnimationTracks(w,D,p,f,u);if(Y)for(let b=0;b<Y.length;b++)C.push(Y[b])}const d=new lr(n,void 0,C);return hn(d,i),d})}createNodeMesh(A){const t=this.json,e=this,i=t.nodes[A];return i.mesh===void 0?null:e.getDependency("mesh",i.mesh).then(function(n){const o=e._getNodeRef(e.meshCache,i.mesh,n);return i.weights!==void 0&&o.traverse(function(g){if(g.isMesh)for(let a=0,r=i.weights.length;a<r;a++)g.morphTargetInfluences[a]=i.weights[a]}),o})}loadNode(A){const t=this.json,e=this,i=t.nodes[A],n=e._loadNodeShallow(A),o=[],g=i.children||[];for(let r=0,I=g.length;r<I;r++)o.push(e.getDependency("node",g[r]));const a=i.skin===void 0?Promise.resolve(null):e.getDependency("skin",i.skin);return Promise.all([n,Promise.all(o),a]).then(function(r){const I=r[0],l=r[1],h=r[2];h!==null&&I.traverse(function(B){B.isSkinnedMesh&&B.bind(h,GX)});for(let B=0,E=l.length;B<E;B++)I.add(l[B]);if(I.userData.pivot!==void 0&&l.length>0){const B=I.userData.pivot,E=l[0];I.pivot=new S().fromArray(B),I.position.x-=B[0],I.position.y-=B[1],I.position.z-=B[2],E.position.set(0,0,0),delete I.userData.pivot}return I})}_loadNodeShallow(A){const t=this.json,e=this.extensions,i=this;if(this.nodeCache[A]!==void 0)return this.nodeCache[A];const n=t.nodes[A],o=n.name?i.createUniqueName(n.name):"",g=[],a=i._invokeOne(function(r){return r.createNodeMesh&&r.createNodeMesh(A)});return a&&g.push(a),n.camera!==void 0&&g.push(i.getDependency("camera",n.camera).then(function(r){return i._getNodeRef(i.cameraCache,n.camera,r)})),i._invokeAll(function(r){return r.createNodeAttachment&&r.createNodeAttachment(A)}).forEach(function(r){g.push(r)}),this.nodeCache[A]=Promise.all(g).then(function(r){let I;if(n.isBone===!0?I=new gC:r.length>1?I=new Ot:r.length===1?I=r[0]:I=new Et,I!==r[0])for(let l=0,h=r.length;l<h;l++)I.add(r[l]);if(n.name&&(I.userData.name=n.name,I.name=o),hn(I,n),n.extensions&&Gg(e,I,n),n.matrix!==void 0){const l=new RA;l.fromArray(n.matrix),I.applyMatrix4(l)}else n.translation!==void 0&&I.position.fromArray(n.translation),n.rotation!==void 0&&I.quaternion.fromArray(n.rotation),n.scale!==void 0&&I.scale.fromArray(n.scale);if(!i.associations.has(I))i.associations.set(I,{});else if(n.mesh!==void 0&&i.meshCache.refs[n.mesh]>1){const l=i.associations.get(I);i.associations.set(I,{...l})}return i.associations.get(I).nodes=A,I}),this.nodeCache[A]}loadScene(A){const t=this.extensions,e=this.json.scenes[A],i=this,n=new Ot;e.name&&(n.name=i.createUniqueName(e.name)),hn(n,e),e.extensions&&Gg(t,n,e);const o=e.nodes||[],g=[];for(let a=0,r=o.length;a<r;a++)g.push(i.getDependency("node",o[a]));return Promise.all(g).then(function(a){for(let I=0,l=a.length;I<l;I++){const h=a[I];h.parent!==null?n.add(eX(h)):n.add(h)}const r=I=>{const l=new Map;for(const[h,B]of i.associations)(h instanceof Ie||h instanceof Ft)&&l.set(h,B);return I.traverse(h=>{const B=i.associations.get(h);B!=null&&l.set(h,B)}),l};return i.associations=r(n),n})}_createAnimationTracks(A,t,e,i,n){const o=[],g=A.name?A.name:A.uuid,a=[];function r(B){B.morphTargetInfluences&&a.push(B.name?B.name:B.uuid)}bo[n.path]===bo.weights?(r(A),A.isGroup&&A.children.forEach(r)):a.push(g);let I;switch(bo[n.path]){case bo.weights:I=rr;break;case bo.rotation:I=Ir;break;case bo.translation:case bo.scale:I=gl;break;default:switch(e.itemSize){case 1:I=rr;break;case 2:case 3:default:I=gl;break}break}const l=i.interpolation!==void 0?PX[i.interpolation]:ja,h=this._getArrayFromAccessor(e);for(let B=0,E=a.length;B<E;B++){const c=new I(a[B]+"."+bo[n.path],t.array,h,l);i.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(c),o.push(c)}return o}_getArrayFromAccessor(A){let t=A.array;if(A.normalized){const e=U0(t.constructor),i=new Float32Array(t.length);for(let n=0,o=t.length;n<o;n++)i[n]=t[n]*e;t=i}return t}_createCubicSplineTrackInterpolant(A){A.createInterpolant=function(e){const i=this instanceof Ir?mX:Fm;return new i(this.times,this.values,this.getValueSize()/3,e)},A.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function KX(s,A,t){const e=A.attributes,i=new vA;if(e.POSITION!==void 0){const g=t.json.accessors[e.POSITION],a=g.min,r=g.max;if(a!==void 0&&r!==void 0){if(i.set(new S(a[0],a[1],a[2]),new S(r[0],r[1],r[2])),g.normalized){const I=U0(Dr[g.componentType]);i.min.multiplyScalar(I),i.max.multiplyScalar(I)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;const n=A.targets;if(n!==void 0){const g=new S,a=new S;for(let r=0,I=n.length;r<I;r++){const l=n[r];if(l.POSITION!==void 0){const h=t.json.accessors[l.POSITION],B=h.min,E=h.max;if(B!==void 0&&E!==void 0){if(a.setX(Math.max(Math.abs(B[0]),Math.abs(E[0]))),a.setY(Math.max(Math.abs(B[1]),Math.abs(E[1]))),a.setZ(Math.max(Math.abs(B[2]),Math.abs(E[2]))),h.normalized){const c=U0(Dr[h.componentType]);a.multiplyScalar(c)}g.max(a)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}i.expandByVector(g)}s.boundingBox=i;const o=new be;i.getCenter(o.center),o.radius=i.min.distanceTo(i.max)/2,s.boundingSphere=o}function Gm(s,A,t){const e=A.attributes,i=[];function n(o,g){return t.getDependency("accessor",o).then(function(a){s.setAttribute(g,a)})}for(const o in e){const g=R0[o]||o.toLowerCase();g in s.attributes||i.push(n(e[o],g))}if(A.indices!==void 0&&!s.index){const o=t.getDependency("accessor",A.indices).then(function(g){s.setIndex(g)});i.push(o)}return ft.workingColorSpace!==si&&"COLOR_0"in e&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${ft.workingColorSpace}" not supported.`),hn(s,A),KX(s,A,t),Promise.all(i).then(function(){return A.targets!==void 0?YX(s,A.targets,t):s})}const X0="__BIM_ENGINE_SDK_ASSET_BASE__",J0="__BIM_ENGINE_SDK_ASSET_FILE_MAP__",x0="__BIM_ENGINE_SDK_ASSET_FILE_URLS__",k0="__BIM_ENGINE_SDK_ASSET_FILE_SESSION__",jX="https://unpkg.com/iflow-engine-base-3d@3.12.21/dist/",V0="https://__bim_engine_sdk_asset__/",RX=["assets/","fonts/","draco/","basis/","texture/","prompt/"];let H0=null;async function ZX(){return H0||(H0=Promise.resolve().then(()=>Hx).then(s=>s.default??s)),H0}function Tg(){return typeof globalThis<"u"?globalThis:null}function Ql(s){return s.endsWith("/")?s:`${s}/`}function Kg(s){return String(s).replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+/g,"/")}function Tm(s){return/^(?:[a-z][a-z\d+\-.]*:)?\/\//i.test(s)||/^(?:data|blob):/i.test(s)}function NX(s){return s.startsWith("./")||s.startsWith("../")}function nE(s,A){try{return A?new URL(s,A).toString():new URL(s).toString()}catch{return null}}function UX(s){return/\.zip$/i.test(s.name)}function XX(){return`${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function JX(s){return s.startsWith(V0)}function O0(){const A=Tg()?.[k0];return typeof A=="string"&&A?`${V0}${A}/`:null}function xX(s){return`${O0()??V0}${Kg(s)}`}function Km(){const A=Tg()?.[J0];return A instanceof Map?A:null}function kX(){const A=Tg()?.[x0];return Array.isArray(A)?A:[]}function jm(){const s=Tg();s&&(kX().forEach(A=>URL.revokeObjectURL(A)),delete s[J0],delete s[x0],delete s[k0])}function VX(s,A){const t=Tg();t&&(jm(),t[J0]=s,t[x0]=A,t[k0]=XX())}function HX(s,A,t){const e=Kg(A),i=new Set([e]),n=e.indexOf("dist/");n>=0&&i.add(e.slice(n+5));const o=e.indexOf("public/");o>=0&&i.add(e.slice(o+7));for(const g of RX){const a=e.indexOf(g);a>=0&&i.add(e.slice(a))}i.forEach(g=>{g&&(s.set(g,t),s.set(g.toLowerCase(),t))})}function Rm(s){const A=Km();if(!A)return null;const t=Kg(s);return A.get(t)??A.get(t.toLowerCase())??null}function Zm(s){const A=Km();if(!A)return!1;const t=Kg(s).replace(/\/?$/,"/").toLowerCase();for(const e of A.keys())if(e.toLowerCase().startsWith(t))return!0;return!1}function OX(s){if(!JX(s))return null;const A=O0();if(!A||!s.startsWith(A))return null;const t=s.slice(A.length);return Rm(t)}qd.setURLModifier(s=>OX(s)??s);async function LX(s){const A=[];for(const t of s){const e=Kg(t.webkitRelativePath||t.name);if(UX(t)){const n=await(await ZX()).loadAsync(t),o=Object.values(n.files);for(const g of o)g.dir||A.push({path:Kg(g.name),blob:await g.async("blob")});continue}A.push({path:e,blob:t})}return A}function Nm(){return typeof document<"u"&&document.baseURI?document.baseURI:typeof location<"u"&&location.href?location.href:null}function zX(s,A){const t=Ql(s);if(Tm(t))return t;const e=oE(A)||vX()||Nm();return nE(t,e||void 0)||t}function oE(s){if(!s)return null;try{const A=Nm(),t=nE(s,A||void 0)||s,e=new URL(".",t),i=e.pathname.replace(/\\/g,"/");return i.endsWith("/chunks/")?new URL("../",e).toString():A&&/\/src\//.test(i)?Ql(A):e.toString()}catch{return null}}function vX(){if(typeof document>"u")return null;const s=document.currentScript;if(s?.src)return oE(s.src);const A=document.getElementsByTagName("script");for(let t=A.length-1;t>=0;t-=1){const e=A[t]?.src;if(e&&/(?:bim-engine-sdk|iflow-engine-base|dwg-preview|gaussian)\.(?:es|umd)\.js(?:[?#].*)?$/.test(e))return oE(e)}return null}function _X(s){const A=Tg();if(A){if(!s){delete A[X0];return}A[X0]=Ql(s)}}async function L0(s){if(!s||s.length===0){jm();return}const A=Array.from(s),t=await LX(A),e=new Map,i=[];t.forEach(n=>{const o=URL.createObjectURL(n.blob);i.push(o),HX(e,n.path,o)}),VX(e,i)}async function qX(s){await L0(s?[s]:null)}function Um(s){const A=O0();if(A)return A;const e=Tg()?.[X0];return typeof e=="string"&&e.length>0?zX(e,s):Ql(jX)}function vt(s,A){if(Tm(s))return s;const t=Kg(s),e=Rm(t);if(e&&!s.endsWith("/"))return e;if(s.endsWith("/")||Zm(t)){const n=xX(t);if(Zm(t))return s.endsWith("/")?Ql(n):n}if(NX(s)){const n=nE(s,oE(A)||void 0);if(n)return n}const i=Um(A);return nE(t,i)||t}const $X=vt("/assets/worker_walk.glb",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ZA&&ZA.tagName.toUpperCase()==="SCRIPT"&&ZA.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href),AJ=Math.PI,tJ={16:"ShiftLeft",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",65:"KeyA",68:"KeyD",69:"KeyE",81:"KeyQ",32:"Space",83:"KeyS",87:"KeyW"},Ci={forward:["KeyW","ArrowUp"],backward:["KeyS","ArrowDown"],left:["KeyA","ArrowLeft"],right:["KeyD","ArrowRight"],up:["KeyQ"],down:["KeyE"],jump:["Space"],boost:["ShiftLeft","ShiftRight"]};class Xm extends os{constructor(A,t,e,i={}){super(),this._Engine=A,this.camera=t,this.object=t,this.domElement=e,this._isEnabled=!1,this.target=new S,this.auto=!1,this.applyGravity=i.applyGravity??!0,this.gravityMinHeight=!0,this.applyCollision=i.applyCollision??!0,this.positionEasing=!0,this.lookflag=1,this.lookHorizontalFlag=1,this.lookSpeed=i.lookSpeed??.003,this.moveSpeed=i.moveSpeed??.02,this.playerHeight=i.playerHeight??1.6,this.playerRadius=i.playerRadius??.3,this.cameraDistance=i.cameraDistance??2,this.cameraHeight=i.cameraHeight??0,this.targetHeight=i.targetHeight??this.playerHeight,this.cameraCollisionTargetHeight=i.cameraCollisionTargetHeight??this.playerHeight+.1,this.cameraCollisionInterval=Math.max(1,Math.floor(i.cameraCollisionInterval??20)),this.cameraCollisionPadding=i.cameraCollisionPadding??.15,this.minCameraCollisionDistance=i.minCameraCollisionDistance??.35,this.jumpSpeed=i.jumpSpeed??.24,this.jumpGravity=i.jumpGravity??.012,this.maxRotateX=i.maxPitch??Math.PI*.45,this.minPitch=i.minPitch??-Math.PI*.38,this.g=9.8,this._moveInput=new S,this._moveDirection=new S,this._rayCaster=new De,this._cameraRayCaster=new De,this._cameraCollisionFrame=0,this._lastCameraSafeDistance=null,this._fallingTime=0,this._isMouseInElement=!1,this._prevMouseX=0,this._prevMouseY=0,this._dragRotateThreshold=i.dragRotateThreshold??2,this._pointerLookActive=!1,this._externalLookActive=!1,this._scriptedMotionActive=!1,this._interactionActive=!1,this._yaw=0,this._pitch=i.initialPitch??0,this._pressedKeys=new Set,this._verticalVelocity=0,this._isJumping=!1,this._isJumpKeyDown=!1,this._jumpStartHeight=0,this.avatarRoot=new Ot,this.avatarRoot.name="ThirdPersonAvatarRoot",this.avatarRoot.visible=i.visible??!0,this.avatarMixer=null,this.avatarWalkAction=null,this._isWalkActionPlaying=!1,this._avatarAnimationTimer=new rl,this._avatarAnimationTimer.connect(document),this._avatarLoadRequestId=0,this.defaultAvatarUrl=i.avatarUrl??$X,this._ownsAvatarResources=!i.avatar,this.avatar=i.avatar||this.createDefaultAvatar(),this.avatar.name=this.avatar.name||"ThirdPersonAvatar",this.avatarRoot.add(this.avatar),!i.avatar&&this.defaultAvatarUrl&&this.loadAvatarModel(this.defaultAvatarUrl,i.avatarOptions);const n=this.isPcDevice();this.bindmousedown=n?this.onMouseDown.bind(this):this.onTouchStart.bind(this),this.bindmouseup=n?this.onMouseUp.bind(this):this.onTouchEnd.bind(this),this.bindmousemove=n?this.onMouseMove.bind(this):this.onTouchMove.bind(this),this.bindonKeyDown=this.onKeyDown.bind(this),this.bindonKeyUp=this.onKeyUp.bind(this),this.bindWindowBlur=this.onWindowBlur.bind(this),this.bindVisibilityChange=this.onVisibilityChange.bind(this),this.bindMouseEnter=this.onMouseEnter.bind(this),this.bindMouseLeave=this.onMouseLeave.bind(this),this.initAvatarPoseFromCamera()}set enabled(A){this._isEnabled!==A&&(this._isEnabled=A,A?(this.ensureAvatarInScene(),this.syncRotationStateFromCamera(),this._avatarAnimationTimer.reset(),this.addEvents(),this.updateCameraFromAvatar()):(this.removeEvents(),this.setPointerLookActive(!1),this.setExternalLookActive(!1),this.setScriptedMotionActive(!1),this.resetMovementState(),this.avatarRoot.visible=!1))}get enabled(){return this._isEnabled}setPointerLookActive(A){this._pointerLookActive=A===!0,this.syncInteractionState()}setExternalLookActive(A){this._externalLookActive=A===!0,this.syncInteractionState()}setScriptedMotionActive(A){this._scriptedMotionActive=A===!0,this.syncInteractionState()}syncInteractionState(){const A=this._pointerLookActive||this._externalLookActive||this._scriptedMotionActive||this.hasMoveInput()||this._isJumping;this._interactionActive!==A&&(this._interactionActive=A,this.dispatchEvent({type:A?"start":"end"}))}isPcDevice(){const A=this._Engine?.DeviceType??this._Engine?.deviceType;return A==="PC"||!A}createDefaultAvatar(){const A=new Ot;return A.name="ThirdPersonEmptyAvatar",A.visible=!1,A}setAvatarModel(A,t={}){if(A){if(this.clearAvatarAnimation(),this.avatar&&(this.avatarRoot.remove(this.avatar),this._ownsAvatarResources&&this.disposeObjectResources(this.avatar)),this.avatar=A,this._ownsAvatarResources=t.ownsResources===!0,A.rotation.y+=t.yawOffset??0,t.alignToFeet!==!1){const e=new vA().setFromObject(A),i=e.max.y-e.min.y;if(t.fitToPlayerHeight!==!1&&Number.isFinite(i)&&i>1e-6){const o=(t.targetHeight??this.playerHeight)/i;A.scale.multiplyScalar(o),e.setFromObject(A)}Number.isFinite(e.min.y)&&(A.position.y-=e.min.y)}A.traverse(e=>{(e.isMesh||e.isSkinnedMesh)&&(e.castShadow=!0,e.receiveShadow=!0,e.frustumCulled=!1)}),this.avatarRoot.add(A)}}loadAvatarModel(A,t={}){const e=++this._avatarLoadRequestId;new K0().load(A,n=>{if(e!==this._avatarLoadRequestId||!n?.scene)return;const o=n.scene;o.name="ThirdPersonWorkerAvatar",this.setAvatarModel(o,{alignToFeet:!0,fitToPlayerHeight:!0,ownsResources:!0,yawOffset:AJ,...t}),this.setupAvatarAnimation(o,n.animations||[])},void 0,n=>{console.warn("[ThirdPersonCameraControl] failed to load avatar model",A,n)})}setupAvatarAnimation(A,t){if(!t.length)return;this.avatarMixer=new I0(A);const e=t.find(i=>/walk|run|move/i.test(i.name))||t[0];this.avatarWalkAction=this.avatarMixer.clipAction(e),this.avatarWalkAction.enabled=!0,this.avatarWalkAction.clampWhenFinished=!1,this.avatarWalkAction.setEffectiveWeight(1),this.avatarWalkAction.paused=!0,this.avatarWalkAction.play(),this._avatarAnimationTimer.reset()}clearAvatarAnimation(){this.avatarMixer&&(this.avatarMixer.stopAllAction(),this.avatarMixer.uncacheRoot(this.avatar)),this.avatarMixer=null,this.avatarWalkAction=null,this._isWalkActionPlaying=!1}ensureAvatarInScene(){this._Engine?.scene&&(this.avatarRoot.parent||this._Engine.scene.add(this.avatarRoot),this.avatarRoot.visible=!0)}initAvatarPoseFromCamera(){if(!this.camera)return;const A=new S;this.camera.getWorldDirection(A),A.y=0,A.lengthSq()<1e-6&&A.set(0,0,-1),A.normalize(),this.setViewYaw(Math.atan2(A.x,-A.z));const t=this.targetHeight+this.cameraHeight+Math.sin(this._pitch)*this.cameraDistance,e=this.camera.position.clone().addScaledVector(A,this.cameraDistance).add(new S(0,-t,0)),i=this.getMinHeight();i!==void 0&&e.y<i&&(e.y=i),this.avatarRoot.position.copy(e),this.setViewYaw(this._yaw)}addEvents(){this.isPcDevice()?(this.domElement.addEventListener("mousedown",this.bindmousedown,!1),this.domElement.addEventListener("mouseup",this.bindmouseup,!1)):(this.domElement.addEventListener("touchstart",this.bindmousedown,!1),this.domElement.addEventListener("touchend",this.bindmouseup,!1)),this.domElement.addEventListener("mouseenter",this.bindMouseEnter,!1),this.domElement.addEventListener("mouseleave",this.bindMouseLeave,!1),window.addEventListener("keydown",this.bindonKeyDown,!1),window.addEventListener("keyup",this.bindonKeyUp,!1),window.addEventListener("blur",this.bindWindowBlur,!1),document.addEventListener("visibilitychange",this.bindVisibilityChange,!1)}removeEvents(){this.domElement.removeEventListener("touchstart",this.bindmousedown),this.domElement.removeEventListener("touchend",this.bindmouseup),this.domElement.removeEventListener("touchmove",this.bindmousemove),this.domElement.removeEventListener("mousedown",this.bindmousedown),this.domElement.removeEventListener("mouseup",this.bindmouseup),this.domElement.removeEventListener("mousemove",this.bindmousemove),this.domElement.removeEventListener("mouseenter",this.bindMouseEnter),this.domElement.removeEventListener("mouseleave",this.bindMouseLeave),window.removeEventListener("keydown",this.bindonKeyDown),window.removeEventListener("keyup",this.bindonKeyUp),window.removeEventListener("blur",this.bindWindowBlur),document.removeEventListener("visibilitychange",this.bindVisibilityChange)}onMouseEnter(){this._isMouseInElement=!0}onMouseLeave(){this._isMouseInElement=!1,this.setPointerLookActive(!1),this.setExternalLookActive(!1),this.resetMovementState()}onWindowBlur(){this.setPointerLookActive(!1),this.setExternalLookActive(!1),this.resetMovementState()}onVisibilityChange(){document.hidden&&(this.setPointerLookActive(!1),this.setExternalLookActive(!1),this.resetMovementState())}onMouseDown(A){this._isMouseInElement=!0,this.domElement.addEventListener("mousemove",this.bindmousemove,!1),this.setPointerLookActive(!0),A.preventDefault?.(),this._prevMouseX=A.screenX,this._prevMouseY=A.screenY}onMouseMove(A){if(!this._isEnabled)return;const t=A.screenX-this._prevMouseX,e=A.screenY-this._prevMouseY;Math.abs(t)+Math.abs(e)<this._dragRotateThreshold||(this.rotateByPointerDelta(t,e),this._prevMouseX=A.screenX,this._prevMouseY=A.screenY)}onMouseUp(){this.updateEngineMovingFlag(),this.setPointerLookActive(!1),this.domElement.removeEventListener("mousemove",this.bindmousemove)}onTouchStart(A){const t=A.targetTouches?.[0];t&&(this._isMouseInElement=!0,this.domElement.addEventListener("touchmove",this.bindmousemove,!1),this.setPointerLookActive(!0),A.preventDefault?.(),this._prevMouseX=t.clientX,this._prevMouseY=t.clientY)}onTouchMove(A){if(!this._isEnabled)return;const t=A.targetTouches?.[0];if(!t)return;const e=t.clientX-this._prevMouseX,i=t.clientY-this._prevMouseY;Math.abs(e)+Math.abs(i)<this._dragRotateThreshold||(this.rotateByPointerDelta(e,i),this._prevMouseX=t.clientX,this._prevMouseY=t.clientY)}onTouchEnd(){this.updateEngineMovingFlag(),this.setPointerLookActive(!1),this.domElement.removeEventListener("touchmove",this.bindmousemove)}setViewYaw(A){this._yaw=A,this.updateAvatarFacing()}getAvatarFacingYaw(){const A=-this._yaw,t=Math.sign(this._moveInput.x);return t!==0?A-t*Math.PI*.5:this._moveInput.z<0?A+Math.PI:A}updateAvatarFacing(){this.avatarRoot.rotation.y=this.getAvatarFacingYaw()}setViewPitch(A){this._pitch=rt.clamp(A,this.minPitch,this.maxRotateX)}rotateByPointerDelta(A,t){this.setViewYaw(this._yaw+A*this.lookHorizontalFlag*this.lookSpeed),this.setViewPitch(this._pitch+t*this.lookflag*this.lookSpeed),this.updateCameraFromAvatar(),this.dispatchCameraChange()}onKeyDown(A){if(!this._isEnabled||!this._isMouseInElement)return;const t=this.getEventCode(A);if(this.isManagedKey(t)){if(A.preventDefault?.(),this.hasCodeInGroup(t,Ci.jump)){A.stopPropagation?.(),this._isJumpKeyDown||(this._isJumpKeyDown=!0,this.jump());return}this._pressedKeys.add(t),this.updateEngineMovingFlag(),this.dispatchCameraChange()}}onKeyUp(A){const t=this.getEventCode(A);if(this.isManagedKey(t)){if(A.preventDefault?.(),this.hasCodeInGroup(t,Ci.jump)){A.stopPropagation?.(),this._isJumpKeyDown=!1;return}this._pressedKeys.delete(t),this.updateEngineMovingFlag()}}getEventCode(A){return A.code||tJ[A.keyCode]||A.key||""}hasPressed(A){return A.some(t=>this._pressedKeys.has(t))}isManagedKey(A){return this.hasCodeInGroup(A,Ci.forward)||this.hasCodeInGroup(A,Ci.backward)||this.hasCodeInGroup(A,Ci.left)||this.hasCodeInGroup(A,Ci.right)||this.hasCodeInGroup(A,Ci.up)||this.hasCodeInGroup(A,Ci.down)||this.hasCodeInGroup(A,Ci.jump)||this.hasCodeInGroup(A,Ci.boost)}hasCodeInGroup(A,t){return t.includes(A)}updateMoveInputFromKeys(){const A=(this.hasPressed(Ci.right)?1:0)-(this.hasPressed(Ci.left)?1:0),t=(this.hasPressed(Ci.forward)?1:0)-(this.hasPressed(Ci.backward)?1:0),e=this.applyGravity?0:(this.hasPressed(Ci.up)?1:0)-(this.hasPressed(Ci.down)?1:0);return this._moveInput.set(A,e,t),this._moveInput}hasMoveInput(){return this.updateMoveInputFromKeys().lengthSq()>0}updateEngineMovingFlag(){const A=this.hasMoveInput();this.updateAvatarFacing(),this._Engine&&(this._Engine.movefirst=A),this.syncInteractionState()}rotateX(A){this.setViewYaw(this._yaw-A*this.lookHorizontalFlag*this.lookSpeed),this.updateCameraFromAvatar()}rotateY(A){this.setViewPitch(this._pitch+A*this.lookflag*.5*this.lookSpeed),this.updateCameraFromAvatar()}setLookDirection({horizontal:A,vertical:t}={}){(A===1||A===-1)&&(this.lookHorizontalFlag=A),(t===1||t===-1)&&(this.lookflag=t)}update(){this._isEnabled&&(this.auto||(this.updateAvatarAnimation(),this.updateMoveInputFromKeys(),this.updateJump(),this.applyGravity&&!this._isJumping&&this.gravityTest(),this.moveAvatar(),this.updateCameraFromAvatar()))}moveAvatar(){this._moveDirection.set(0,0,0);const A=this.getFlatForward(),t=new S(-A.z,0,A.x).normalize();if(this._moveInput.z!==0&&this._moveDirection.addScaledVector(A,this._moveInput.z),this._moveInput.x!==0&&this._moveDirection.addScaledVector(t,this._moveInput.x),!this.applyGravity&&this._moveInput.y!==0&&(this._moveDirection.y+=this._moveInput.y),this._moveDirection.lengthSq()<=0){this.setAvatarWalking(!1),this.updateAvatarFacing(),this.updateEngineMovingFlag();return}this._moveDirection.normalize();const e=this.moveSpeed*(this.hasPressed(Ci.boost)?2:1);if(this.applyCollision&&this.isBlocked(this._moveDirection,e)){this.setAvatarWalking(!1),this.updateAvatarFacing(),this.updateEngineMovingFlag();return}this.avatarRoot.position.addScaledVector(this._moveDirection,e),this.updateAvatarFacing(),this.setAvatarWalking(this._moveInput.x!==0||this._moveInput.z!==0),this._Engine&&(this._Engine.movefirst=!0)}jump(){this._isJumping||(this._jumpStartHeight=this.avatarRoot.position.y,this._verticalVelocity=this.jumpSpeed,this._isJumping=!0,this.syncInteractionState())}updateJump(){if(!this._isJumping)return;this.avatarRoot.position.y+=this._verticalVelocity,this._verticalVelocity-=this.jumpGravity;const A=this.getJumpFloorHeight();this._verticalVelocity<=0&&this.avatarRoot.position.y<=A&&(this.setAvatarHeight(A),this._verticalVelocity=0,this._isJumping=!1,this._fallingTime=0,this.syncInteractionState())}getJumpFloorHeight(){const A=this.hitTest(new S(0,-1,0),this.playerHeight+3);if(A?.point)return A.point.y;const t=this.getMinHeight();return Math.max(this._jumpStartHeight,t??-1/0)}setAvatarWalking(A){!this.avatarWalkAction||this._isWalkActionPlaying===A||(this._isWalkActionPlaying=A,this.avatarWalkAction.paused=!1,A?this.avatarWalkAction.reset().fadeIn(.12).play():this.avatarWalkAction.fadeOut(.16))}updateAvatarAnimation(){this.avatarMixer&&(this._avatarAnimationTimer.update(),this.avatarMixer.update(this._avatarAnimationTimer.getDelta()))}getFlatForward(){return new S(Math.sin(this._yaw),0,-Math.cos(this._yaw)).normalize()}updateCameraFromAvatar(){if(!this.camera)return;const A=this.avatarRoot.position.clone().add(new S(0,this.targetHeight,0)),t=Math.cos(this._pitch)*this.cameraDistance,e=new S(-Math.sin(this._yaw)*t,this.cameraHeight+Math.sin(this._pitch)*this.cameraDistance,Math.cos(this._yaw)*t),i=A.clone().add(e);this.camera.position.copy(this.resolveCameraPosition(i)),this.camera.up.set(0,1,0),this.camera.lookAt(A),this.camera.updateMatrixWorld(!0),this.target.copy(A),this.syncSharedTargetFromAvatar(),this.dispatchEvent({type:"change"})}resolveCameraPosition(A){const t=this.getCameraCollisionTarget(),e=A.clone().sub(t),i=e.length();if(i<=1e-6)return A;const n=e.normalize();if(!this.shouldDetectCameraCollision()&&Number.isFinite(this._lastCameraSafeDistance))return t.clone().addScaledVector(n,Math.min(this._lastCameraSafeDistance,i));const o=this.hitCameraObstacle(t,n,i);if(!o)return this._lastCameraSafeDistance=i,A;const g=Math.max(o.distance-this.cameraCollisionPadding,this.minCameraCollisionDistance);return this._lastCameraSafeDistance=Math.min(g,i),t.clone().addScaledVector(n,this._lastCameraSafeDistance)}getCameraCollisionTarget(){return this.avatarRoot.position.clone().add(new S(0,this.cameraCollisionTargetHeight,0))}shouldDetectCameraCollision(){return this._cameraCollisionFrame+=1,Number.isFinite(this._lastCameraSafeDistance)?this._cameraCollisionFrame%this.cameraCollisionInterval===0:!0}getControlPosition(){return this.avatarRoot.position.clone()}setAvatarXZ(A,t,e={}){return!Number.isFinite(A)||!Number.isFinite(t)?!1:(this.avatarRoot.position.x=A,this.avatarRoot.position.z=t,e.updateCamera!==!1&&this.updateCameraFromAvatar(),this.dispatchCameraChange(),!0)}placeAvatarAtPoint(A,t={}){return A instanceof S?(this.avatarRoot.position.copy(A),this.setAvatarHeight(this.avatarRoot.position.y),this.syncRotationStateFromCamera(),this.setViewYaw(this._yaw),t.updateCamera!==!1&&(this.updateCameraFromAvatar(),this.dispatchCameraChange()),!0):!1}rotateYaw(A){return Number.isFinite(A)?(this.setViewYaw(this._yaw+A),this.updateCameraFromAvatar(),this.dispatchCameraChange(),!0):!1}syncAvatarFromCameraTarget(A=this.target,t={}){if(!this.camera||!(A instanceof S))return!1;this.target.copy(A),this.avatarRoot.position.set(A.x,A.y-this.targetHeight,A.z);const e=this.camera.position.clone().sub(A),i=Math.hypot(e.x,e.z);if(i>1e-6&&this.setViewYaw(Math.atan2(-e.x,e.z)),t.preserveCameraDistance!==!1){const n=e.y-this.cameraHeight,o=Math.hypot(i,n);Number.isFinite(o)&&o>1e-6&&(this.cameraDistance=o,this._pitch=rt.clamp(Math.atan2(n,i),this.minPitch,this.maxRotateX))}else this.syncRotationStateFromCamera();return this.syncSharedTargetFromAvatar(),this.dispatchEvent({type:"change"}),!0}flyToPoint(A,t={}){if(!(A instanceof S))return!1;const e=t.duration??500,i=this.avatarRoot.position.clone(),n=this.resolveAvatarFlightTarget(A),o=performance.now();this.resetMovementState(),this.setScriptedMotionActive(!0);const g=()=>{const a=performance.now()-o,r=Math.min(a/e,1),I=r<.5?2*r*r:1-Math.pow(-2*r+2,2)/2;this.avatarRoot.position.lerpVectors(i,n,I),this.updateCameraFromAvatar(),r<1?requestAnimationFrame(g):(this.setAvatarHeight(n.y),this.updateCameraFromAvatar(),this.setScriptedMotionActive(!1))};return requestAnimationFrame(g),!0}resolveAvatarFlightTarget(A){const t=A.clone(),e=A.clone().sub(this.avatarRoot.position);e.y=0,e.lengthSq()>1e-6&&(e.normalize(),t.addScaledVector(e,-(this.playerRadius+.2)));const i=this.getMinHeight();return this.gravityMinHeight&&i!==void 0&&t.y<i&&(t.y=i),t}syncRotationStateFromCamera(){if(!this.camera)return;const A=new S;this.camera.getWorldDirection(A);const t=A.clone();t.y=0,t.lengthSq()>1e-6&&(t.normalize(),this.setViewYaw(Math.atan2(t.x,-t.z))),this.setViewPitch(-Math.asin(A.y)),this.setViewYaw(this._yaw)}syncSharedTargetFromAvatar(){const A=[],t=e=>{!e?.target||A.includes(e)||A.push(e)};t(this),t(this._Engine?.controls),t(this._Engine?.controlModule?.orbitControls);for(const e of A)e.target.copy(this.target)}setScreenUp(A){return!A||!this.camera?!1:(this.camera.up.copy(A).normalize(),this.updateCameraFromAvatar(),!0)}gravityTest(){if(!this.applyGravity){this.setAvatarHeight(this.avatarRoot.position.y);return}let A=!0;this._fallingTime+=.01;const t=this.hitTest(new S(0,-1,0),this.playerHeight+2);if(!t)return;const e=t.point.y;if(this.positionEasing){if(e>=this.avatarRoot.position.y||e-this.avatarRoot.position.y<.2){this.setAvatarHeight(this.avatarRoot.position.y+(e-this.avatarRoot.position.y)*.08),this._fallingTime=0,A=!1;return}}else t.distance<this.playerHeight&&(this.setAvatarHeight(e),this._fallingTime=0,A=!1);A&&this.setAvatarHeight(this.avatarRoot.position.y-this.g*Math.pow(this._fallingTime,2))}setAvatarHeight(A){const t=this.getMinHeight();this.gravityMinHeight&&t!==void 0&&A<t?this.avatarRoot.position.y=t:this.avatarRoot.position.y=A}getMinHeight(){const A=this._Engine?.ToolUntils?this._Engine.ToolUntils.GetBoundingBox(this._Engine):null;return A?A.min.y:void 0}isBlocked(A,t){const e=this.hitTest(A,this.playerRadius+t+.05);return!!(e&&e.distance<this.playerRadius+t+.05)}hitCameraObstacle(A,t,e){if(!this._Engine?.handelBehaved?.handle_catch)return null;this._cameraRayCaster.ray.origin.copy(A),this._cameraRayCaster.ray.direction.copy(t).normalize(),this._cameraRayCaster.far=e;const i={},n=this._Engine.handelBehaved.handle_catch(this._cameraRayCaster,i,!1);return this._cameraRayCaster.far=1/0,!n||n.distance>=e?null:n}hitTest(A,t=1/0){const e=this.avatarRoot.position.clone().add(new S(0,this.playerHeight*.5,0));this._rayCaster.ray.origin.copy(e),this._rayCaster.ray.direction.copy(A).normalize(),this._rayCaster.far=t;const i={},n=this._Engine?.handelBehaved?.handle_catch?.(this._rayCaster,i,!1);if(this._rayCaster.far=1/0,n==null)return null;const o=n.object?.name,g=n.object?.url,a=this._Engine?.models?.find?.(r=>r.url===g);if(a&&o){const I=a.nodesMap?.get?.(o)?.infos?.[0]?.name;if(I&&(I.includes("门")||I.includes("門")||I.toLowerCase().includes("door")))return null}return n}dispatchCameraChange(){const A=new CustomEvent("bimengine:camerachange",{detail:""});window.dispatchEvent(A),this.dispatchEvent({type:"change"})}resetMovementState(){this._pressedKeys.clear(),this._moveInput.set(0,0,0),this._verticalVelocity=0,this._isJumping=!1,this._isJumpKeyDown=!1,this.updateAvatarFacing(),this.setAvatarWalking(!1),this._Engine&&(this._Engine.movefirst=!1),this.syncInteractionState()}dispose(){this.enabled=!1,this._avatarAnimationTimer.dispose(),this.avatarRoot?.parent&&this.avatarRoot.parent.remove(this.avatarRoot),this._avatarLoadRequestId++,this.clearAvatarAnimation(),this._ownsAvatarResources&&this.avatar&&this.disposeObjectResources(this.avatar)}disposeObjectResources(A){A.traverse(t=>{t.geometry&&t.geometry.dispose?.(),t.material&&(Array.isArray(t.material)?t.material.forEach(e=>e.dispose?.()):t.material.dispose?.())})}}const z0="__isModelUrlGroup",gE="__modelDepthBias",Jm=4;function xm(s){return s.__modelGroupMap instanceof Map||(s.__modelGroupMap=new Map),s.__modelGroupMap}function km(s){return s.__modelObjectIndexMap instanceof Map||(s.__modelObjectIndexMap=new Map),s.__modelObjectIndexMap}function v0(s,A){s.url=A,s.name=A,s.userData=s.userData??{},s.userData[z0]=!0}function _0(s,A){return s instanceof Ot?A==null?s.userData?.[z0]===!0:s.userData?.[z0]===!0&&s.url===A:!1}function q0(s,A){return s?.models?.find?.(t=>t?.url===A)}function dl(s,A,t){if(typeof t!="string"||t.length===0)return;const e=q0(s,A);e!=null&&(Array.isArray(e.urls)||(e.urls=[]),e.urls.includes(t)||e.urls.push(t))}function Wo(s,A){const t=xm(s),e=t.get(A);if(e&&e.parent!=null)return e;const i=q0(s,A);if(i?.group instanceof Ot&&i.group.parent!=null)return v0(i.group,A),t.set(A,i.group),i.group;const n=s?.scene?.children?.find?.(o=>o instanceof Ot?_0(o,A)?!0:o.name===A&&o.url===A:!1);return n!=null?(v0(n,A),t.set(A,n),i!=null&&(i.group=n),n):null}function Is(s,A){const t=Wo(s,A);return t==null?new RA:(t.updateWorldMatrix(!0,!1),t.matrixWorld.clone())}function jg(s,A){const t=Wo(s,A);if(t!=null)return t;const e=new Ot;v0(e,A),s.scene.add(e),xm(s).set(A,e);const n=q0(s,A);return n!=null&&(n.group=e),e}function eJ(s){const A=[],t=new Set;return(Array.isArray(s?.models)?s.models:[]).forEach(i=>{if(i?.url==null)return;const n=Wo(s,i.url);n==null||t.has(n.uuid)||(t.add(n.uuid),A.push(n))}),s?.scene?.children?.forEach?.(i=>{!_0(i)||t.has(i.uuid)||(t.add(i.uuid),A.push(i))}),A}function fl(s,A){const t=[],e=new Set;return eJ(s).forEach(n=>{n.traverse(o=>{o===n||e.has(o.uuid)||A(o)&&(e.add(o.uuid),t.push(o))})}),s?.scene?.children?.forEach?.(n=>{if(n.name=="highlightModel")e.add(n.uuid),t.push(n);else{if(e.has(n.uuid)||_0(n)||n.url==null)return;A(n)&&(e.add(n.uuid),t.push(n))}}),t}function $0(s){return fl(s,A=>A instanceof bA&&!(A instanceof ct))}function iJ(s){if(typeof s.__modelObjectIndexSeed=="number")return;let A=-1;s?.scene?.traverse?.(t=>{typeof t?.index=="number"&&Number.isFinite(t.index)&&(A=Math.max(A,t.index))}),s.__modelObjectIndexSeed=A+1}function sJ(s){iJ(s);const A=s.__modelObjectIndexSeed;return s.__modelObjectIndexSeed+=1,A}function Af(s,A,t){const e=typeof t=="number"?t:sJ(s);return A.index=e,km(s).set(e,A),e}function Vm(s){return Array.isArray(s)?s:s!=null?[s]:[]}function nJ(s){return 1+(Number.isFinite(s)?Math.abs(Math.floor(s)):0)%16*.125}function tf(s,A){const t=typeof A=="number"?A:s?.index,e=nJ(t);Vm(s?.material).forEach(i=>{i.userData=i.userData??{};const n=i.userData[gE]??{};i.userData[gE]={...n,enabled:!0,factor:1,units:e},i.polygonOffset=!0,i.polygonOffsetFactor=1,i.polygonOffsetUnits=e+(n.edgeActive?Jm:0),i.needsUpdate=!0})}function Hm(s,A){Vm(s?.material).forEach(t=>{t.userData=t.userData??{};const e=t.userData[gE]??{},i=e.enabled?e.units:t.polygonOffsetUnits??0,n=e.enabled?e.factor:t.polygonOffsetFactor??1;t.userData[gE]={...e,edgeActive:A},e.enabled||A?(t.polygonOffset=!1,t.polygonOffsetFactor=n,t.polygonOffsetUnits=i+(A?Jm:0)):t.polygonOffset=!1,t.needsUpdate=!0})}function Ds(s,A){if(!Number.isFinite(A))return;const t=km(s),e=t.get(A);if(e&&e.parent!=null)return e;e&&e.parent==null&&t.delete(A);const i=fl(s,n=>n.index===A)[0];return i!=null?(t.set(A,i),i):s?.scene?.children?.find?.(n=>n?.index===A)}class oJ{constructor(A){this.engine=A}snapModelCache=new Map;applySnapPreview(A,t,e){const i=this.engine,n=A.object.url,o=A.object.name;let g=i.modelEdge.getModelEdge(n,o);g||(g=[0,0,[]]);const a=Is(i,n),r=this.getModelSnapCache(n,o,g);i.camera.updateMatrixWorld(!0);const I=new RA().multiplyMatrices(i.camera.projectionMatrix,i.camera.matrixWorldInverse),l=i.renderer.domElement.clientWidth,h=i.renderer.domElement.clientHeight,B=new MA(t.offsetX,t.offsetY),E=new Ct,c=new S,Q=new S,C=new MA,d=new MA,M=new S;let y="face",w=null,D=null,p=100;if(e!=null){const f=A.point.clone(),u=A.normal||(A.face?A.face.normal:null);if(u&&A.object?.matrixWorld?.elements){const Y=u.clone().transformDirection(A.object.matrixWorld).normalize(),m=new S().subVectors(e,f).dot(Y),T=e.clone().sub(Y.clone().multiplyScalar(m)),F=this.projectWorldPointToScreen(T,I,l,h,C,E);if(F!=null){const j=this.getDistanceSq(F.x,F.y,B.x,B.y);j<p*4&&(p=j,w={point:T,distanceSq:j,pointxy:F.clone(),style:"vertical"},y="point")}}}for(let f=0;f<r.localPoints.length;f+=3){if(c.set(r.localPoints[f],r.localPoints[f+1],r.localPoints[f+2]).applyMatrix4(a),i.clipping&&!i.clipping.isPointInClippingRange(c))continue;const u=this.projectWorldPointToScreen(c,I,l,h,C,E);if(u==null)continue;const Y=this.getDistanceSq(u.x,u.y,B.x,B.y);Y<p&&(p=Y,w={point:c.clone(),distanceSq:Y,pointxy:u.clone(),style:"rect"})}for(let f=0;f<r.localCenters.length;f+=3){if(c.set(r.localCenters[f],r.localCenters[f+1],r.localCenters[f+2]).applyMatrix4(a),i.clipping&&!i.clipping.isPointInClippingRange(c))continue;const u=this.projectWorldPointToScreen(c,I,l,h,C,E);if(u==null)continue;const Y=this.getDistanceSq(u.x,u.y,B.x,B.y);Y<p&&(p=Y,w={point:c.clone(),distanceSq:Y,pointxy:u.clone(),style:"default"})}if(w!=null)y="point";else{for(let f=0;f<r.localLines.length;f+=6){c.set(r.localLines[f],r.localLines[f+1],r.localLines[f+2]).applyMatrix4(a),Q.set(r.localLines[f+3],r.localLines[f+4],r.localLines[f+5]).applyMatrix4(a);const u=this.projectWorldPointToScreen(c,I,l,h,C,E),Y=this.projectWorldPointToScreen(Q,I,l,h,d,E);if(u==null||Y==null)continue;const b=this.pointToLineProjection(B,u,Y),m=this.pointToLineDistanceSq(B,u,Y);if(m<p){const T=this.pointToLineProjection3D(b,c,Q,I,M);if(i.clipping&&!i.clipping.isPointInClippingRange(T))continue;D={distanceSq:m,point:T.clone(),pointxy:this.projectWorldPointToScreen(T,I,l,h,C,E)?.clone()??u.clone(),start:u.clone(),end:Y.clone(),style:"funnel"},p=m}}D!=null&&(y="line")}return y==="point"&&w!=null?(this.renderPointCandidate(w),A.point=w.point,A):y==="line"&&D!=null?(this.renderLineCandidate(D),A.point=D.point,A):(this.renderFaceCandidate(A),A)}getModelSnapCache(A,t,e){const i=`${A}::${t}`,n=Array.isArray(e?.[2])?e[2]:[],o=this.snapModelCache.get(i);if(o&&o.source===n)return o;const g=new Float32Array(n.length*3),a=new Float32Array(n.length*3),r=new Float32Array(n.length*6);let I=0,l=0,h=0;n.forEach(E=>{if(E?.[0]==null||E?.[1]==null)return;const c=E[0],Q=E[1];g[I++]=c.X,g[I++]=c.Z,g[I++]=-c.Y,a[l++]=(c.X+Q.X)*.5,a[l++]=(c.Z+Q.Z)*.5,a[l++]=(-c.Y-Q.Y)*.5,r[h++]=c.X,r[h++]=c.Z,r[h++]=-c.Y,r[h++]=Q.X,r[h++]=Q.Z,r[h++]=-Q.Y});const B={source:n,localPoints:g.subarray(0,I),localCenters:a.subarray(0,l),localLines:r.subarray(0,h)};return this.snapModelCache.set(i,B),B}projectWorldPointToScreen(A,t,e,i,n,o){if(o.set(A.x,A.y,A.z,1).applyMatrix4(t),Math.abs(o.w)<1e-10)return null;const g=1/o.w,a=o.x*g,r=o.y*g;return!Number.isFinite(a)||!Number.isFinite(r)?null:(n.set(a*e*.5+e*.5,-r*i*.5+i*.5),n)}getDistanceSq(A,t,e,i){const n=A-e,o=t-i;return n*n+o*o}pointToLineDistanceSq(A,t,e){const i=this.pointToLineProjection(A,t,e),n=t.x+(e.x-t.x)*i,o=t.y+(e.y-t.y)*i;return this.getDistanceSq(A.x,A.y,n,o)}pointToLineProjection(A,t,e){const i=new MA().subVectors(e,t),n=i.lengthSq();if(n<1e-10)return 0;const o=new MA().subVectors(A,t);return rt.clamp(o.dot(i)/n,0,1)}pointToLineProjection3D(A,t,e,i,n){const o=rt.clamp(A,0,1);if(!this.engine.camera.isPerspectiveCamera)return n.lerpVectors(t,e,o);const g=new Ct(t.x,t.y,t.z,1).applyMatrix4(i),r=new Ct(e.x,e.y,e.z,1).applyMatrix4(i).w*(1-o)+o*g.w,I=Math.abs(r)>1e-10?o*g.w/r:o;return n.lerpVectors(t,e,rt.clamp(I,0,1))}renderPointCandidate(A){const t=this.engine,e=A.pointxy;t.catchSvg.innerHTML="";const i=e.x+t.reactBoundingClientRect.left,n=e.y+t.reactBoundingClientRect.top,o=document.createElementNS("http://www.w3.org/2000/svg","polygon");switch(o.setAttribute("class","catchPoint"),A.style){case"default":o.setAttribute("points",`${i},${n-8} ${i-7},${n+4} ${i+7},${n+4}`);break;case"funnel":o.setAttribute("points",`${i-7},${n-10} ${i+7},${n-10} ${i+1},${n-1} ${i},${n} ${i+7},${n+10} ${i-7},${n+10} ${i-1},${n}`);break;case"vertical":o.setAttribute("points",`${i-12},${n} ${i},${n} ${i},${n-12}`),o.setAttribute("fill","none");break;case"rect":o.setAttribute("points",`${i-8},${n-8} ${i+8},${n-8} ${i+8},${n+8} ${i-8},${n+8}`);break}o.setAttribute("stroke","rgb(8, 223, 215)"),o.setAttribute("fill","transparent"),t.catchSvg.appendChild(o)}renderLineCandidate(A){const t=this.engine,e=A.pointxy,i=A.start,n=A.end;t.catchSvg.innerHTML="";const o=document.createElementNS("http://www.w3.org/2000/svg","line");o.setAttribute("class","catchLine"),o.setAttribute("x1",(i.x+t.reactBoundingClientRect.left).toString()),o.setAttribute("y1",(i.y+t.reactBoundingClientRect.top).toString()),o.setAttribute("x2",(n.x+t.reactBoundingClientRect.left).toString()),o.setAttribute("y2",(n.y+t.reactBoundingClientRect.top).toString()),o.setAttribute("stroke","rgb(8, 223, 215)"),o.setAttribute("stroke-width","2"),t.catchSvg.appendChild(o);const g=e.x+t.reactBoundingClientRect.left,a=e.y+t.reactBoundingClientRect.top,r=document.createElementNS("http://www.w3.org/2000/svg","polygon");r.setAttribute("class","catchPoint"),r.setAttribute("points",`${g-7},${a-10} ${g+7},${a-10} ${g+1},${a-1} ${g},${a} ${g+7},${a+10} ${g-7},${a+10} ${g-1},${a}`),r.setAttribute("stroke","rgb(8, 223, 215)"),r.setAttribute("fill","transparent"),t.catchSvg.appendChild(r)}renderFaceCandidate(A){const t=this.engine,e=A.point.clone(),i=A.normal||(A.face?A.face.normal:null),n=(i?i.clone():new S(0,0,1)).normalize(),o=Math.abs(n.y)<.9?new S(0,1,0):new S(1,0,0),g=new S().crossVectors(n,o).normalize(),a=new S().crossVectors(n,g).normalize(),r=20,I=new gi(t.camera,t.renderer,t.scene),l=I.worldToScreen(e),h=I.worldToScreen(new S().copy(e).add(g)),B=Math.sqrt((h.x-l.x)**2+(h.y-l.y)**2),E=B>0?r/B:.2,C=[new S().copy(g).add(a).multiplyScalar(E),new S().copy(g).sub(a).multiplyScalar(E),new S().copy(g).multiplyScalar(-1).sub(a).multiplyScalar(E),new S().copy(g).multiplyScalar(-1).add(a).multiplyScalar(E)].map(M=>new S().copy(e).add(M)).map(M=>I.worldToScreen(M));t.catchSvg.innerHTML="";const d=document.createElementNS("http://www.w3.org/2000/svg","polygon");d.setAttribute("class","catchFace"),d.setAttribute("points",C.map(M=>`${M.x+t.reactBoundingClientRect.left},${M.y+t.reactBoundingClientRect.top}`).join(" ")),d.setAttribute("fill","rgba(1, 238, 255, 0.2)"),d.setAttribute("stroke","rgb(0, 255, 247)"),d.setAttribute("stroke-width","1"),t.catchSvg.appendChild(d)}}function ef(s){const A={self:null,options:null,mouseDownTime:0,mouseDownPosition:null,lastClickTime:0,touchLongPressTimer:null,touchLongPressActive:!1,touchLatestEvent:null,touchStartPosition:null,touchMagnifierCanvas:null,touchMagnifierContext:null,touchInputMode:null,touchPointerId:null,touchControlsSnapshot:null,mouseMoveFrame:null,latestMouseMoveEvent:null},t=800,e=28,i=132,n=44,o=168,g=new oJ(s);A.handle_catch=function(_,G,x=!0,U=!0){const J=A.options;A.options={...J??{},showCatch:x};try{return BA(_,G,!0,U)}finally{A.options=J}},A.init=function(_,G){A.self!=null&&A.self.disActive!=null&&A.self.type!=_.type&&A.self.disActive(),A.self=_,G==null&&(G={showCatch:!1}),C(),A.clearLastPoint(),A.options=G,A.isClickSimpleModel=!0},A.render=function(){A.self&&A.self.render!=null&&A.self.render()};function a(){A.mouseMoveFrame!=null&&(cancelAnimationFrame(A.mouseMoveFrame),A.mouseMoveFrame=null),A.latestMouseMoveEvent=null}A.active=function(){s.renderer.domElement.addEventListener("mousedown",T),s.renderer.domElement.addEventListener("mouseup",j),s.renderer.domElement.addEventListener("mousemove",F),s.renderer.domElement.addEventListener("touchstart",H,{capture:!0,passive:!1}),s.renderer.domElement.addEventListener("touchend",nA,{capture:!0,passive:!1}),s.renderer.domElement.addEventListener("touchcancel",nA,{capture:!0,passive:!1}),s.renderer.domElement.addEventListener("touchmove",eA,{capture:!0,passive:!1}),s.renderer.domElement.addEventListener("pointerdown",lA,!0),s.renderer.domElement.addEventListener("pointermove",oA,!0),s.renderer.domElement.addEventListener("pointerup",dA,!0),s.renderer.domElement.addEventListener("pointercancel",dA,!0),window.addEventListener("keydown",r),window.addEventListener("keyup",I)},A.disActive=function(){C(),a(),u(),s.renderer.domElement.removeEventListener("mousedown",T),s.renderer.domElement.removeEventListener("mouseup",j),s.renderer.domElement.removeEventListener("mousemove",F),s.renderer.domElement.removeEventListener("touchstart",H,!0),s.renderer.domElement.removeEventListener("touchend",nA,!0),s.renderer.domElement.removeEventListener("touchcancel",nA,!0),s.renderer.domElement.removeEventListener("touchmove",eA,!0),s.renderer.domElement.removeEventListener("pointerdown",lA,!0),s.renderer.domElement.removeEventListener("pointermove",oA,!0),s.renderer.domElement.removeEventListener("pointerup",dA,!0),s.renderer.domElement.removeEventListener("pointercancel",dA,!0),window.removeEventListener("keydown",r),window.removeEventListener("keyup",I)};function r(_){(_.keyCode===8||_.keyCode===46)&&A.self&&A.self.handelKeyDeleteDown!=null&&A.self.handelKeyDeleteDown(),_.keyCode===27&&A.self&&A.self.handelKeyEscDown!=null&&A.self.handelKeyEscDown(),_.keyCode===13&&A.self&&A.self.handelKeyEnterDown!=null&&A.self.handelKeyEnterDown(),_.keyCode===32&&A.self&&A.self.handelKeySpaceDown!=null&&A.self.handelKeySpaceDown(_),_.key==="Tab"&&A.self&&A.self.handelKeyTabDown!=null&&A.self.handelKeyTabDown(_),_.key==="Control"&&A.self&&A.self.handelKeyCtrlDown!=null&&A.self.handelKeyCtrlDown(),_.key==="Delete"&&A.self&&A.self.handelKeyDeleteDown!=null&&A.self.handelKeyDeleteDown(),_.key==="Shift"&&A.self&&A.self.handelKeyShiftDown!=null&&A.self.handelKeyShiftDown(),_.key==="Meta"&&A.self&&A.self.handelKeyMetaDown!=null&&A.self.handelKeyMetaDown()}function I(_){_.key==="Alt"&&A.self&&A.self.handelKeyAltUp!=null&&A.self.handelKeyAltUp(),_.key==="Tab"&&A.self&&A.self.handelKeyTabUp!=null&&A.self.handelKeyTabUp(),_.key==="Control"&&A.self&&A.self.handelKeyCtrlUp!=null&&A.self.handelKeyCtrlUp(),_.key==="Shift"&&A.self&&A.self.handelKeyShiftUp!=null&&A.self.handelKeyShiftUp(),_.key==="Meta"&&A.self&&A.self.handelKeyMetaUp!=null&&A.self.handelKeyMetaUp(),_.key==="Command"&&A.self&&A.self.handelKeyCommandUp!=null&&A.self.handelKeyCommandUp(),_.key==="Windows"&&A.self&&A.self.handelKeyWindowsUp!=null&&A.self.handelKeyWindowsUp()}function l(_){const G=new MA,x=s.renderer.domElement.clientWidth,U=s.renderer.domElement.clientHeight;return G.x=_.offsetX/x*2-1,G.y=-(_.offsetY/U)*2+1,G}function h(_){const G=new De,x=l(_);return G.setFromCamera(x,s.camera),G}function B(){return s?.deviceModule?.isMobile?.()===!0||s?.deviceType==="mobile"}function E(){return B()&&A.options?.showCatch===!0}function c(_){const G=typeof TouchEvent<"u"&&_?.originalEvent instanceof TouchEvent;return E()&&!G}function Q(){A.touchLongPressTimer!=null&&(clearTimeout(A.touchLongPressTimer),A.touchLongPressTimer=null)}function C(){Q(),f(),y(),A.touchLongPressActive=!1,A.touchLatestEvent=null,A.touchStartPosition=null,A.touchInputMode=null,A.touchPointerId=null}function d(_){_?.preventDefault?.(),_?.stopPropagation?.(),_?.stopImmediatePropagation?.()}function M(){const _=s?.controls;!_||A.touchControlsSnapshot||(A.touchControlsSnapshot={controls:_,enabled:_.enabled!==!1},_.enabled=!1)}function y(){const _=A.touchControlsSnapshot;_&&(_.controls&&(w(_.controls),_.controls.enabled=_.enabled),A.touchControlsSnapshot=null)}function w(_){_?._pointers?.clear?.(),typeof _?.state=="number"&&(_.state=-1),_._isInteracting=!1,_._touchDistance=0,A.touchPointerId!=null&&_.domElement?.releasePointerCapture?.(A.touchPointerId)}function D(_){const G=_.touches[0]||_.changedTouches[0];return G?new MA(G.clientX,G.clientY):null}function p(){if(A.touchMagnifierCanvas)return A.touchMagnifierCanvas;const _=document.createElement("canvas"),G=Math.max(1,window.devicePixelRatio||1);return _.width=i*G,_.height=i*G,_.style.position="fixed",_.style.width=`${i}px`,_.style.height=`${i}px`,_.style.borderRadius="50%",_.style.border="2px solid rgba(0, 255, 247, 0.95)",_.style.boxShadow="0 8px 22px rgba(0, 0, 0, 0.32)",_.style.pointerEvents="none",_.style.zIndex="1002",_.style.display="none",_.style.background="#111",document.body.appendChild(_),A.touchMagnifierCanvas=_,A.touchMagnifierContext=_.getContext("2d"),_}function f(){const _=A.touchMagnifierCanvas;_&&(_.style.display="none")}function u(){A.touchMagnifierCanvas?.remove?.(),A.touchMagnifierCanvas=null,A.touchMagnifierContext=null}function Y(_,G,x,U,J,W){const P=s?.catchSvg;if(!P?.childElementCount)return;const R=s?.reactBoundingClientRect??G.getBoundingClientRect(),q=L=>{const[O,tA]=L.split(",").map(Number);return Number.isFinite(O)&&Number.isFinite(tA)?[(O-R.left-x)/J*i*W,(tA-R.top-U)/J*i*W]:null};Array.from(P.children).forEach(L=>{const O=L.tagName.toLowerCase(),gA=(O==="line"?[`${L.getAttribute("x1")},${L.getAttribute("y1")}`,`${L.getAttribute("x2")},${L.getAttribute("y2")}`].map(q):(L.getAttribute("points")||"").trim().split(/\s+/).map(q)).filter(Boolean);gA.length<2||(_.beginPath(),_.strokeStyle=L.getAttribute("stroke")||"rgb(8, 223, 215)",_.fillStyle=L.getAttribute("fill")||"transparent",_.lineWidth=Number(L.getAttribute("stroke-width")||2)*W,_.moveTo(gA[0][0],gA[0][1]),gA.slice(1).forEach(([hA,rA])=>_.lineTo(hA,rA)),O==="polygon"&&(_.closePath(),["none","transparent"].includes(String(_.fillStyle))||_.fill()),_.stroke())})}function b(_){const G=s?.renderer?.domElement,x=p(),U=A.touchMagnifierContext;if(!G||!x||!U)return;const J=_?.catch?.point,W=J&&(s?.worldToScreen??new gi(s.camera,s.renderer,s.scene)),P=W?.worldToScreenIfVisible?.(J)??W?.worldToScreen?.(J);if(!P||!Number.isFinite(P.x)||!Number.isFinite(P.y)||P.x<0||P.y<0||P.x>G.clientWidth||P.y>G.clientHeight){f();return}const R=x.width/i,q=Math.min(window.innerWidth-i/2-8,Math.max(i/2+8,_.clientX)),L=Math.min(window.innerHeight-i-8,Math.max(8,_.clientY-o));x.style.left=`${q-i/2}px`,x.style.top=`${L}px`,x.style.display="block";const O=G.width/Math.max(1,G.clientWidth),tA=G.height/Math.max(1,G.clientHeight),gA=n,hA=Math.max(0,Math.min(G.clientWidth-gA,P.x-gA/2)),rA=Math.max(0,Math.min(G.clientHeight-gA,P.y-gA/2));U.save(),U.clearRect(0,0,x.width,x.height),U.beginPath(),U.arc(x.width/2,x.height/2,x.width/2,0,Math.PI*2),U.clip(),U.fillStyle=window.getComputedStyle(G.parentElement??document.body).backgroundColor||"#dfe8f2",U.fillRect(0,0,x.width,x.height);try{U.drawImage(G,hA*O,rA*tA,gA*O,gA*tA,0,0,x.width,x.height),Y(U,G,hA,rA,gA,R)}catch{f(),U.restore();return}U.strokeStyle="rgba(0, 255, 247, 0.9)",U.lineWidth=1.5*R,U.beginPath(),U.moveTo(x.width/2-10*R,x.height/2),U.lineTo(x.width/2+10*R,x.height/2),U.moveTo(x.width/2,x.height/2-10*R),U.lineTo(x.width/2,x.height/2+10*R),U.stroke(),U.restore()}function m(_,G=!1,x=!1,U=!0){const J=h(_);if(_.raycaster=J,G){const W=BA(J,_,x,U);_.catch=W}}function T(_){c(_)||(A.mouseDownTime=Date.now(),A.mouseDownPosition=new S(_.offsetX,_.offsetY,0),A.self&&A.self.handleMouseDown!=null&&_.button==0&&(m(_,!0,!0),_.catch!=null&&(s.engineStatus.highlightModels==null||s.engineStatus.highlightModels.length==0)&&(s.engineStatus?.suppressNextOrbitOriginPick===!0?s.engineStatus.suppressNextOrbitOriginPick=!1:s.controlModule.orbitControls.origin.set(_.catch.point.x,_.catch.point.y,_.catch.point.z)),A.self.handleMouseDown(_)))}function F(_){c(_)||A.self&&A.self.handleMouseMove!=null&&(A.latestMouseMoveEvent=_,A.mouseMoveFrame==null&&(A.mouseMoveFrame=requestAnimationFrame(()=>{const G=A.latestMouseMoveEvent;A.latestMouseMoveEvent=null,A.mouseMoveFrame=null,G&&(s.engineStatus.isFree&&m(G,!0,!0,A.isClickSimpleModel),A.self.handleMouseMove(G))})))}function j(_){if(c(_))return;const G=Date.now(),x=G-A.mouseDownTime,U=new S(_.offsetX,_.offsetY,0);A.self&&A.self.handleMouseUp!=null&&_.button==0&&(m(_,!1,!1,!1),A.self.handleMouseUp(_));const J=U.distanceTo(A.mouseDownPosition);(x<100||J==0)&&A.self&&A.self.handleMouseClick!=null&&(m(_,!0,!0,!1),G-A.lastClickTime<200?A.self.handleMouseDoubleClick!=null&&_.button==0&&A.self.handleMouseDoubleClick(_):A.self.handleMouseClick!=null&&_.button==0?A.self.handleMouseClick(_):A.self.handleRightMouseClick!=null&&_.button==2&&A.self.handleRightMouseClick(_),A.lastClickTime=Date.now())}function X(_){const G=_.touches[0]||_.changedTouches[0];if(!G)return null;const U=s.renderer.domElement.getBoundingClientRect(),J=G.clientX-U.left,W=G.clientY-U.top;return{offsetX:J,offsetY:W,button:0,clientX:G.clientX,clientY:G.clientY,preventDefault:()=>_.preventDefault(),stopPropagation:()=>_.stopPropagation(),originalEvent:_}}function v(_){const x=s.renderer.domElement.getBoundingClientRect();return{offsetX:_.clientX-x.left,offsetY:_.clientY-x.top,button:_.button??0,clientX:_.clientX,clientY:_.clientY,preventDefault:()=>_.preventDefault(),stopPropagation:()=>_.stopPropagation(),originalEvent:_}}function k(_,G,x,U=null){C(),A.touchInputMode=x,A.touchPointerId=U,A.touchLatestEvent=_,A.touchStartPosition=G,A.touchLongPressTimer=window.setTimeout(()=>{const J=A.touchLatestEvent;J&&(A.touchLongPressActive=!0,M(),A.mouseDownTime=Date.now(),A.mouseDownPosition=new S(J.offsetX,J.offsetY,0),A.self?.handleMouseMove!=null&&(m(J,!0,!0,A.isClickSimpleModel),A.self.handleMouseMove(J)),b(J))},t)}function K(_,G){A.touchLatestEvent=_;const x=A.touchStartPosition;!A.touchLongPressActive&&x&&G&&x.distanceTo(G)>e&&Q(),A.touchLongPressActive&&(A.self?.handleMouseMove!=null&&(m(_,!0,!0,A.isClickSimpleModel),A.self.handleMouseMove(_)),b(_))}function z(_){Q(),A.touchLongPressActive&&(m(_,!0,!0,A.isClickSimpleModel),A.self?.handleMouseClick!=null&&A.self.handleMouseClick(_),A.self?.handleMouseUp!=null&&A.self.handleMouseUp(_)),C()}function H(_){if(_.preventDefault(),_.touches.length!==1){C();return}const G=X(_);if(G){if(E()){k(G,D(_)??new MA(G.clientX,G.clientY),"touch");return}T(G)}}function eA(_){if(_.preventDefault(),_.touches.length!==1){C();return}const G=X(_);if(G){if(E()){A.touchLongPressActive&&d(_),K(G,D(_));return}F(G)}}function nA(_){_.preventDefault();const G=X(_);if(G){if(E()){A.touchLongPressActive&&d(_),z(G);return}j(G)}}function lA(_){if(_.pointerType!=="touch"||!E()||_.isPrimary===!1)return;const G=v(_);k(G,new MA(_.clientX,_.clientY),"pointer",_.pointerId)}function oA(_){_.pointerType!=="touch"||!E()||(A.touchLongPressActive&&d(_),A.touchInputMode==="pointer"&&(A.touchPointerId!=null&&_.pointerId!==A.touchPointerId||K(v(_),new MA(_.clientX,_.clientY))))}function dA(_){_.pointerType!=="touch"||!E()||(A.touchLongPressActive&&d(_),A.touchInputMode==="pointer"&&(A.touchPointerId!=null&&_.pointerId!==A.touchPointerId||z(v(_))))}function BA(_,G,x=!1,U=!0){if(!s.engineStatus.isFree&&x==!1){s.hoverHighLight.clearHighlight();return}if(s.engineStatus.editorMode=="simple")return;s.catchSvg.innerHTML="";let J=s.octreeBox.rayInterationModel(_,x,U);if(J=s.clipping?.filterIntersectionsByClipping(J)??J,J.length!==0)return A.options.showCatch?g.applySnapPreview(J[0],G,A.lastPoint):J[0]}return A.setLastPoint=function(_){A.lastPoint=_},A.clearLastPoint=function(){A.lastPoint=null},A}class gJ{engine;orbitControls;firstPersonControls;thirdPersonControls;isActive=!0;originDiv=null;mobileRoamControlsEl=null;mobileMovePointerId=null;mobileMoveActiveKeys=new Set;mobileMoveIntensity=0;mobileMoveSpeedBase=new WeakMap;mobileLookPointerId=null;mobileLookOffset={x:0,y:0};handelBehaved;pendingThirdPersonOptions=null;prevContainerCursor=null;roamLookDirection={horizontal:1,vertical:1};isDragging=!1;isDown=!1;containerOffset={left:0,top:0};constructor(A){this.engine=A,this.init(),this.handelBehaved=ef(this.engine),this.handelBehaved.init(this,null),this.handelBehaved.active()}init(){this.orbitControls=new pm(this.engine,this.engine.camera,this.engine.renderer.domElement),this.orbitControls.showOriginIcon=!0,this.firstPersonControls=new Dm(this.engine,this.engine.camera,this.engine.renderer.domElement),this.thirdPersonControls=new Xm(this.engine,this.engine.camera,this.engine.renderer.domElement),this.applyRoamLookDirection(this.firstPersonControls),this.applyRoamLookDirection(this.thirdPersonControls);const A=document.createElement("div");this.originDiv=A,A.className="originDiv",A.style.position="absolute",A.style.top="0px",A.style.left="0px",A.style.width="30px",A.style.height="30px",A.style.borderRadius="50%",A.style.pointerEvents="none",A.style.backgroundImage=`url(${vt("/assets/svg/rotate-orbit.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ZA&&ZA.tagName.toUpperCase()==="SCRIPT"&&ZA.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href)})`,this.engine.container.appendChild(this.originDiv)}active(){this.isActive=!0,this.orbitControls.enabled=!0}disActive(){this.isActive=!1,this.orbitControls.enabled=!1}setEngineControls(A){this.engine.controls=A,this.engine.bindControlEvents?.(A)}setMoveSpeed(A){const t=A*.1;this.firstPersonControls&&(this.firstPersonControls.moveSpeed=t,this.setMobileMoveBaseSpeed(this.firstPersonControls,t)),this.thirdPersonControls&&(this.thirdPersonControls.moveSpeed=t,this.setMobileMoveBaseSpeed(this.thirdPersonControls,t))}getMoveSpeed(){const A=this.getActiveRoamControl()||this.firstPersonControls||this.thirdPersonControls;return this.getMobileMoveBaseSpeed(A)*10}setApplyCollision(A){this.firstPersonControls&&(this.firstPersonControls.applyCollision=A),this.thirdPersonControls&&(this.thirdPersonControls.applyCollision=A)}getApplyCollision(){return(this.getActiveRoamControl()||this.firstPersonControls||this.thirdPersonControls)?.applyCollision}setApplyGravity(A){this.firstPersonControls&&(this.firstPersonControls.applyGravity=A),this.thirdPersonControls&&(this.thirdPersonControls.applyGravity=A),this.updateMobileVerticalControlsVisibility()}getApplyGravity(){return(this.getActiveRoamControl()||this.firstPersonControls||this.thirdPersonControls)?.applyGravity}setRoamLookDirection(A){(A?.horizontal===1||A?.horizontal===-1)&&(this.roamLookDirection.horizontal=A.horizontal),(A?.vertical===1||A?.vertical===-1)&&(this.roamLookDirection.vertical=A.vertical),this.applyRoamLookDirection(this.firstPersonControls),this.applyRoamLookDirection(this.thirdPersonControls)}getRoamLookDirection(){return{...this.roamLookDirection}}applyRoamLookDirection(A){A?.setLookDirection?.(this.roamLookDirection)}toggleMinMap(){this.engine.minMap.toggle()}switchFirstPersonMode(){this.engine.cameraModule.switchToPerspectiveCamera(),this.firstPersonControls&&(this.firstPersonControls.sanitizeCameraOrientation?.(),this.firstPersonControls.enabled=!1),this.thirdPersonControls&&(this.thirdPersonControls.enabled=!1),this.firstPersonControls=new Dm(this.engine,this.engine.camera,this.engine.renderer.domElement,[]),this.applyRoamLookDirection(this.firstPersonControls),this.orbitControls.enabled=!1,this.firstPersonControls.sanitizeCameraOrientation?.(),this.firstPersonControls.enabled=!0,this.firstPersonControls.isActive=!0,this.firstPersonControls.syncRotationStateFromCamera?.(),this.firstPersonControls.syncSharedTargetFromCamera?.(),this.setEngineControls(this.firstPersonControls),this.engine.worldToScreen=new gi(this.engine.camera,this.engine.renderer,this.engine.scene),this.ensureMobileRoamControls()}switchThirdPersonMode(A){this.firstPersonControls&&(this.firstPersonControls.sanitizeCameraOrientation?.(),this.firstPersonControls.enabled=!1),this.thirdPersonControls&&(this.thirdPersonControls.enabled=!1),this.beginThirdPersonPlacement(A)}createThirdPersonControl(A){const t=this.thirdPersonControls,e={moveSpeed:t?.moveSpeed,applyCollision:t?.applyCollision,applyGravity:t?.applyGravity};return t?.dispose?.(),this.thirdPersonControls=new Xm(this.engine,this.engine.camera,this.engine.renderer.domElement,{...e,...A}),this.applyRoamLookDirection(this.thirdPersonControls),this.thirdPersonControls}beginThirdPersonPlacement(A){this.pendingThirdPersonOptions=A||{},this.orbitControls.enabled=!0,this.setEngineControls(this.orbitControls),this.engine.worldToScreen=new gi(this.engine.camera,this.engine.renderer,this.engine.scene),this.removeMobileRoamControls(),this.engine.container&&(this.prevContainerCursor=this.engine.container.style.cursor||"",this.engine.container.style.cursor="crosshair")}isWaitingThirdPersonPlacement(){return this.pendingThirdPersonOptions!=null}applyThirdPersonPlacement(A){if(!this.pendingThirdPersonOptions||!(A instanceof S))return!1;const t=this.pendingThirdPersonOptions;this.pendingThirdPersonOptions=null,this.engine.container&&this.prevContainerCursor!=null&&(this.engine.container.style.cursor=this.prevContainerCursor),this.prevContainerCursor=null,this.engine.cameraModule.switchToPerspectiveCamera();const e=this.createThirdPersonControl(t);return e.placeAvatarAtPoint?.(A,{updateCamera:!1}),this.orbitControls.enabled=!1,e.enabled=!0,e.isActive=!0,e.placeAvatarAtPoint?.(A),this.setEngineControls(e),this.engine.minMap?.show?.(),this.engine.worldToScreen=new gi(this.engine.camera,this.engine.renderer,this.engine.scene),this.ensureMobileRoamControls(),!0}setThirdPersonAvatar(A,t){this.thirdPersonControls?.setAvatarModel?.(A,t)}setThirdPersonMoveSpeed(A){this.thirdPersonControls&&(this.thirdPersonControls.moveSpeed=A*.1,this.setMobileMoveBaseSpeed(this.thirdPersonControls,this.thirdPersonControls.moveSpeed))}setThirdPersonApplyCollision(A){this.thirdPersonControls&&(this.thirdPersonControls.applyCollision=A)}setThirdPersonApplyGravity(A){this.thirdPersonControls&&(this.thirdPersonControls.applyGravity=A),this.updateMobileVerticalControlsVisibility()}getOrbitTargetFromCamera(A=10){const t=this.engine.camera,e=new S;return t.getWorldDirection(e),e.lengthSq()<=1e-8&&e.set(0,0,-1),t.position.clone().add(e.normalize().multiplyScalar(A))}switchDefaultMode(A){const t=A?.preserveCameraPose===!0;this.pendingThirdPersonOptions=null,this.engine.container&&this.prevContainerCursor!=null&&(this.engine.container.style.cursor=this.prevContainerCursor),this.prevContainerCursor=null,this.firstPersonControls&&(t||this.firstPersonControls.sanitizeCameraOrientation?.(),this.firstPersonControls.enabled=!1),this.thirdPersonControls&&(this.thirdPersonControls.enabled=!1);const e=this.engine.camera,i=t?this.orbitControls.target.clone():this.getOrbitTargetFromCamera(10),n=t&&this.orbitControls.origin?.clone?this.orbitControls.origin.clone():i.clone(),o=t&&this.orbitControls._referenceUp?.clone?this.orbitControls._referenceUp.clone():void 0,g=t&&this.orbitControls._viewRight?.clone?this.orbitControls._viewRight.clone():void 0;this.orbitControls.object=e,this.orbitControls.target.copy(i),this.orbitControls.syncStateFromCamera?.(e,i,{origin:n,referenceUp:o,viewRight:g}),this.orbitControls.enabled=!0,this.setEngineControls(this.orbitControls),this.orbitControls.update(!0),this.engine.worldToScreen=new gi(this.engine.camera,this.engine.renderer,this.engine.scene),this.removeMobileRoamControls()}handleMouseUp(A){this.isDragging=!1,this.isDown=!1}handleMouseMove(A){this.isDown?this.isDragging=!0:this.isDragging=!1}handleMouseDown(A){this.isDown=!0}handleMouseClick(A){this.isDragging=!1,this.isDown=!1}isMobileDevice(){return this.engine?.deviceModule?.isMobile?.()===!0||this.engine?.deviceType==="mobile"}getActiveRoamControl(){return this.firstPersonControls?.enabled?this.firstPersonControls:this.thirdPersonControls?.enabled?this.thirdPersonControls:null}getMobileMoveBaseSpeed(A){return!A||typeof A.moveSpeed!="number"?0:(this.mobileMoveSpeedBase.has(A)||this.mobileMoveSpeedBase.set(A,A.moveSpeed),this.mobileMoveSpeedBase.get(A)??A.moveSpeed)}setMobileMoveBaseSpeed(A,t){!A||typeof t!="number"||this.mobileMoveSpeedBase.set(A,t)}restoreMobileMoveSpeed(){[this.firstPersonControls,this.thirdPersonControls].forEach(A=>{A&&typeof A.moveSpeed=="number"&&this.mobileMoveSpeedBase.has(A)&&(A.moveSpeed=this.mobileMoveSpeedBase.get(A)??A.moveSpeed)})}updateMobileMoveSpeed(){const A=this.getActiveRoamControl();if(!A||typeof A.moveSpeed!="number")return;const t=this.getMobileMoveBaseSpeed(A);if(this.mobileMovePointerId==null||this.mobileMoveActiveKeys.size===0||this.mobileMoveIntensity<=0){A.moveSpeed=t;return}const e=.25;A.moveSpeed=t*(e+(1-e)*this.mobileMoveIntensity)}createVirtualKeyEvent(A,t){const i={w:{keyCode:87,code:"KeyW",key:"w"},a:{keyCode:65,code:"KeyA",key:"a"},s:{keyCode:83,code:"KeyS",key:"s"},d:{keyCode:68,code:"KeyD",key:"d"},q:{keyCode:81,code:"KeyQ",key:"q"},e:{keyCode:69,code:"KeyE",key:"e"}}[A];return{key:i.key,code:i.code,keyCode:i.keyCode,type:t?"keydown":"keyup",preventDefault(){},stopPropagation(){}}}setVirtualKey(A,t){const e=this.getActiveRoamControl();if(!e||!A)return;e._isMouseInElement=!0;const i=this.createVirtualKeyEvent(A,t);t?e.onKeyDown?.(i):e.onKeyUp?.(i)}updateMobileMoveKeys(A){const t=new Set(A);this.mobileMoveActiveKeys.forEach(e=>{t.has(e)||this.setVirtualKey(e,!1)}),t.forEach(e=>{this.mobileMoveActiveKeys.has(e)||this.setVirtualKey(e,!0)}),this.mobileMoveActiveKeys=t}releaseMobileMoveKeys(){this.mobileMoveIntensity=0,this.updateMobileMoveKeys([]),this.restoreMobileMoveSpeed()}bindVirtualButton(A,t){let e=!1,i=null;const n=()=>{e&&(e=!1,i=null,A.classList.remove("is-active"),this.setVirtualKey(t,!1))},o=a=>{a.preventDefault(),a.stopPropagation(),!e&&(e=!0,i=a.pointerId,A.classList.add("is-active"),A.setPointerCapture?.(a.pointerId),this.setVirtualKey(t,!0))},g=a=>{a.preventDefault(),a.stopPropagation(),!(!e||i!==a.pointerId)&&(A.releasePointerCapture?.(a.pointerId),n())};A.addEventListener("pointerdown",o),A.addEventListener("pointerup",g),A.addEventListener("pointercancel",g),A.addEventListener("lostpointercapture",n)}createMobileRoamButton(A,t,e=""){const i=document.createElement("button");return i.type="button",i.className=`bim-mobile-roam-button ${e}`.trim(),i.innerHTML=A,i.setAttribute("aria-label",t==="q"?"Move up":t==="e"?"Move down":A),this.bindVirtualButton(i,t),i}bindMovePad(A){const t=A.querySelector(".bim-mobile-roam-move-knob"),e=n=>{const o=A.getBoundingClientRect(),g=Math.min(o.width,o.height)*.5,a=g*.48,r=g*.22,I=n.clientX-o.left-g,l=n.clientY-o.top-g,h=Math.hypot(I,l),B=Math.min(h,a),E=h>a?a/h:1,c=I*E,Q=l*E;t&&(t.style.transform=`translate(${c}px, ${Q}px)`);const C=[];l<-r?C.push("w"):l>r&&C.push("s"),I<-r?C.push("a"):I>r&&C.push("d"),this.mobileMoveIntensity=C.length===0?0:Math.max(0,Math.min(1,(B-r)/(a-r))),this.updateMobileMoveKeys(C)};A.addEventListener("pointerdown",n=>{n.preventDefault(),n.stopPropagation(),this.mobileMovePointerId=n.pointerId,A.classList.add("is-active"),A.setPointerCapture?.(n.pointerId),e(n)}),A.addEventListener("pointermove",n=>{this.mobileMovePointerId===n.pointerId&&(n.preventDefault(),n.stopPropagation(),e(n))});const i=n=>{this.mobileMovePointerId===n.pointerId&&(n.preventDefault(),n.stopPropagation(),A.classList.remove("is-active"),A.releasePointerCapture?.(n.pointerId),this.mobileMovePointerId=null,t&&(t.style.transform=""),this.releaseMobileMoveKeys())};A.addEventListener("pointerup",i),A.addEventListener("pointercancel",i)}rotateActiveRoamView(A,t){const e=this.getActiveRoamControl();e&&(typeof e.rotateByPointerDelta=="function"?e.rotateByPointerDelta(A,t):(e.rotateX?.(A),e.rotateY?.(t*2),e.dispatchEvent?.({type:"change"}),window.dispatchEvent(new CustomEvent("bimengine:camerachange",{detail:""}))))}updateMobileLookRotation(){if(this.mobileLookPointerId==null||this.mobileLookOffset.x===0&&this.mobileLookOffset.y===0)return;const A=2.8;this.rotateActiveRoamView(this.mobileLookOffset.x*A,this.mobileLookOffset.y*A)}updateMobileVerticalControlsVisibility(){const A=this.mobileRoamControlsEl?.querySelector(".bim-mobile-roam-vertical-pad");A&&(A.style.display=this.getActiveRoamControl()?.applyGravity?"none":"flex")}ensureMobileRoamControls(){if(!this.isMobileDevice()){this.removeMobileRoamControls();return}if(this.mobileRoamControlsEl){this.mobileMovePointerId=null,this.releaseMobileMoveKeys(),this.mobileLookPointerId=null,this.mobileLookOffset={x:0,y:0},this.getActiveRoamControl()?.setExternalLookActive?.(!1),this.mobileRoamControlsEl.querySelectorAll(".is-active").forEach(n=>n.classList.remove("is-active")),this.mobileRoamControlsEl.querySelectorAll(".bim-mobile-roam-look-knob, .bim-mobile-roam-move-knob").forEach(n=>n.style.transform=""),this.firstPersonControls?.resetMovementState?.(),this.thirdPersonControls?.resetMovementState?.(),this.mobileRoamControlsEl.style.display="flex",this.updateMobileVerticalControlsVisibility();return}const A=document.createElement("div");A.className="bim-mobile-roam-controls",A.addEventListener("contextmenu",n=>n.preventDefault());const t=document.createElement("div");t.className="bim-mobile-roam-pad bim-mobile-roam-move-pad";const e=document.createElement("span");e.className="bim-mobile-roam-move-knob",t.appendChild(e),this.bindMovePad(t);const i=document.createElement("div");i.className="bim-mobile-roam-vertical-pad",i.appendChild(this.createMobileRoamButton("↑","q","is-round")),i.appendChild(this.createMobileRoamButton("↓","e","is-round")),A.appendChild(t),A.appendChild(i),this.engine.container.appendChild(A),this.mobileRoamControlsEl=A,this.updateMobileVerticalControlsVisibility()}removeMobileRoamControls(){this.mobileMovePointerId=null,this.releaseMobileMoveKeys(),this.mobileLookPointerId=null,this.mobileLookOffset={x:0,y:0},this.getActiveRoamControl()?.setExternalLookActive?.(!1),this.mobileRoamControlsEl&&(this.mobileRoamControlsEl.remove(),this.mobileRoamControlsEl=null),this.firstPersonControls?.resetMovementState?.(),this.thirdPersonControls?.resetMovementState?.()}update(){if(this.updateMobileMoveSpeed(),this.updateMobileLookRotation(),this.firstPersonControls.enabled&&this.firstPersonControls.update(),this.thirdPersonControls?.enabled&&this.thirdPersonControls.update(),this.orbitControls.enabled){const A=this.engine.controlModule.orbitControls.origin,e=this.engine.worldToScreen.worldToScreen(A);this.originDiv&&this.isDragging?(this.originDiv.style.left=e.x-15+this.engine.reactBoundingClientRect.left+"px",this.originDiv.style.top=e.y-15+this.engine.reactBoundingClientRect.top+"px",this.originDiv.style.display="block"):this.originDiv&&(this.originDiv.style.display="none")}}dispose(){this.isActive=!1,this.handelBehaved?.disActive?.(),this.orbitControls?.dispose?.(),this.firstPersonControls?.dispose?.(),this.thirdPersonControls?.dispose?.(),this.removeMobileRoamControls(),this.originDiv?.remove(),this.originDiv=null,this.orbitControls=null,this.firstPersonControls=null,this.thirdPersonControls=null,this.handelBehaved=null}}const Rg={name:"CopyShader",uniforms:{tDiffuse:{value:null},opacity:{value:1}},vertexShader:`
|
|
4220
|
+
}`;class TU{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(A,t){if(this.texture===null){const e=new Sd(A.texture);(A.depthNear!==t.depthNear||A.depthFar!==t.depthFar)&&(this.depthNear=A.depthNear,this.depthFar=A.depthFar),this.texture=e}}getMesh(A){if(this.texture!==null&&this.mesh===null){const t=A.cameras[0].viewport,e=new $t({vertexShader:WU,fragmentShader:GU,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new bA(new gn(20,20),e)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class KU extends os{constructor(A,t){super();const e=this;let i=null,n=1,o=null,g="local-floor",a=1,r=null,I=null,l=null,h=null,B=null,E=null;const c=typeof XRWebGLBinding<"u",Q=new TU,C={},d=t.getContextAttributes();let M=null,y=null;const w=[],D=[],p=new MA;let f=null,u=null;const Y=new Ce;Y.viewport=new Ct;const b=new Ce;b.viewport=new Ct;const m=[Y,b],T=new yu;let F=null,j=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(BA){let _=w[BA];return _===void 0&&(_=new Zh,w[BA]=_),_.getTargetRaySpace()},this.getControllerGrip=function(BA){let _=w[BA];return _===void 0&&(_=new Zh,w[BA]=_),_.getGripSpace()},this.getHand=function(BA){let _=w[BA];return _===void 0&&(_=new Zh,w[BA]=_),_.getHandSpace()};function X(BA){const _=D.indexOf(BA.inputSource);if(_===-1)return;const G=w[_];G!==void 0&&(G.update(BA.inputSource,BA.frame,r||o),G.dispatchEvent({type:BA.type,data:BA.inputSource}))}function v(){i.removeEventListener("select",X),i.removeEventListener("selectstart",X),i.removeEventListener("selectend",X),i.removeEventListener("squeeze",X),i.removeEventListener("squeezestart",X),i.removeEventListener("squeezeend",X),i.removeEventListener("end",v),i.removeEventListener("inputsourceschange",k);for(let BA=0;BA<w.length;BA++){const _=D[BA];_!==null&&(D[BA]=null,w[BA].disconnect(_))}F=null,j=null,Q.reset();for(const BA in C)delete C[BA];if(A.setRenderTarget(M),B=null,h=null,l=null,i=null,y=null,dA.stop(),e.isPresenting=!1,A.setPixelRatio(f),A.setSize(p.width,p.height,!1),u!==null){const BA=u.camera;BA.fov=u.fov,BA.zoom=u.zoom,BA.updateProjectionMatrix(),u=null}e.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(BA){n=BA,e.isPresenting===!0&&_A("WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(BA){g=BA,e.isPresenting===!0&&_A("WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return r||o},this.setReferenceSpace=function(BA){r=BA},this.getBaseLayer=function(){return h!==null?h:B},this.getBinding=function(){return l===null&&c&&(l=new XRWebGLBinding(i,t)),l},this.getFrame=function(){return E},this.getSession=function(){return i},this.setSession=async function(BA){if(i=BA,i!==null){if(M=A.getRenderTarget(),i.addEventListener("select",X),i.addEventListener("selectstart",X),i.addEventListener("selectend",X),i.addEventListener("squeeze",X),i.addEventListener("squeezestart",X),i.addEventListener("squeezeend",X),i.addEventListener("end",v),i.addEventListener("inputsourceschange",k),d.xrCompatible!==!0&&await t.makeXRCompatible(),f=A.getPixelRatio(),A.getSize(p),c&&"createProjectionLayer"in XRWebGLBinding.prototype){let G=null,x=null,U=null;d.depth&&(U=d.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,G=d.stencil?nn:sn,x=d.stencil?ho:Es);const J={colorFormat:t.RGBA8,depthFormat:U,scaleFactor:n};l=this.getBinding(),h=l.createProjectionLayer(J),i.updateRenderState({layers:[h]}),A.setPixelRatio(1),A.setSize(h.textureWidth,h.textureHeight,!1),y=new pe(h.textureWidth,h.textureHeight,{format:re,type:Bt,depthTexture:new wo(h.textureWidth,h.textureHeight,x,void 0,void 0,void 0,void 0,void 0,void 0,G),stencilBuffer:d.stencil,colorSpace:A.outputColorSpace,samples:d.antialias?4:0,resolveDepthBuffer:h.ignoreDepthValues===!1,resolveStencilBuffer:h.ignoreDepthValues===!1,storeMultisampledDepthBuffer:h.ignoreDepthValues===!1,storeMultisampledStencilBuffer:h.ignoreDepthValues===!1})}else{const G={antialias:d.antialias,alpha:!0,depth:d.depth,stencil:d.stencil,framebufferScaleFactor:n};B=new XRWebGLLayer(i,t,G),i.updateRenderState({baseLayer:B}),A.setPixelRatio(1),A.setSize(B.framebufferWidth,B.framebufferHeight,!1),y=new pe(B.framebufferWidth,B.framebufferHeight,{format:re,type:Bt,colorSpace:A.outputColorSpace,stencilBuffer:d.stencil,resolveDepthBuffer:B.ignoreDepthValues===!1,resolveStencilBuffer:B.ignoreDepthValues===!1,storeMultisampledDepthBuffer:B.ignoreDepthValues===!1,storeMultisampledStencilBuffer:B.ignoreDepthValues===!1})}y.isXRRenderTarget=!0,this.setFoveation(a),r=null,o=await i.requestReferenceSpace(g),dA.setContext(i),dA.start(),e.isPresenting=!0,e.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(i!==null)return i.environmentBlendMode},this.getDepthTexture=function(){return Q.getDepthTexture()};function k(BA){for(let _=0;_<BA.removed.length;_++){const G=BA.removed[_],x=D.indexOf(G);x>=0&&(D[x]=null,w[x].disconnect(G))}for(let _=0;_<BA.added.length;_++){const G=BA.added[_];let x=D.indexOf(G);if(x===-1){for(let J=0;J<w.length;J++)if(J>=D.length){D.push(G),x=J;break}else if(D[J]===null){D[J]=G,x=J;break}if(x===-1)break}const U=w[x];U&&U.connect(G)}}const K=new S,z=new S;function H(BA,_,G){K.setFromMatrixPosition(_.matrixWorld),z.setFromMatrixPosition(G.matrixWorld);const x=K.distanceTo(z),U=_.projectionMatrix.elements,J=G.projectionMatrix.elements,W=U[14]/(U[10]-1),P=U[14]/(U[10]+1),R=(U[9]+1)/U[5],q=(U[9]-1)/U[5],L=(U[8]-1)/U[0],O=(J[8]+1)/J[0],tA=W*L,gA=W*O,hA=x/(-L+O),rA=hA*-L;if(_.matrixWorld.decompose(BA.position,BA.quaternion,BA.scale),BA.translateX(rA),BA.translateZ(hA),BA.matrixWorld.compose(BA.position,BA.quaternion,BA.scale),BA.matrixWorldInverse.copy(BA.matrixWorld).invert(),U[10]===-1)BA.projectionMatrix.copy(_.projectionMatrix),BA.projectionMatrixInverse.copy(_.projectionMatrixInverse);else{const sA=W+hA,GA=P+hA,uA=tA-rA,iA=gA+(x-rA),Z=R*P/GA*sA,IA=q*P/GA*sA;BA.projectionMatrix.makePerspective(uA,iA,Z,IA,sA,GA),BA.projectionMatrixInverse.copy(BA.projectionMatrix).invert()}}function eA(BA,_){_===null?BA.matrixWorld.copy(BA.matrix):BA.matrixWorld.multiplyMatrices(_.matrixWorld,BA.matrix),BA.matrixWorldInverse.copy(BA.matrixWorld).invert()}this.updateCamera=function(BA){if(i===null)return;let _=BA.near,G=BA.far;Q.texture!==null&&(Q.depthNear>0&&(_=Q.depthNear),Q.depthFar>0&&(G=Q.depthFar)),T.near=b.near=Y.near=_,T.far=b.far=Y.far=G,(F!==T.near||j!==T.far)&&(i.updateRenderState({depthNear:T.near,depthFar:T.far}),F=T.near,j=T.far),T.layers.mask=BA.layers.mask|6,Y.layers.mask=T.layers.mask&-5,b.layers.mask=T.layers.mask&-3;const x=BA.parent,U=T.cameras;eA(T,x);for(let J=0;J<U.length;J++)eA(U[J],x);U.length===2?H(T,Y,b):T.projectionMatrix.copy(Y.projectionMatrix),u===null&&BA.isPerspectiveCamera&&(u={camera:BA,fov:BA.fov,zoom:BA.zoom}),nA(BA,T,x)};function nA(BA,_,G){G===null?BA.matrix.copy(_.matrixWorld):(BA.matrix.copy(G.matrixWorld),BA.matrix.invert(),BA.matrix.multiply(_.matrixWorld)),BA.matrix.decompose(BA.position,BA.quaternion,BA.scale),BA.updateMatrixWorld(!0),BA.projectionMatrix.copy(_.projectionMatrix),BA.projectionMatrixInverse.copy(_.projectionMatrixInverse),BA.isPerspectiveCamera&&(BA.fov=Za*2*Math.atan(1/BA.projectionMatrix.elements[5]),BA.zoom=1)}this.getCamera=function(){return T},this.getFoveation=function(){if(!(h===null&&B===null))return a},this.setFoveation=function(BA){a=BA,h!==null&&(h.fixedFoveation=BA),B!==null&&B.fixedFoveation!==void 0&&(B.fixedFoveation=BA)},this.hasDepthSensing=function(){return Q.texture!==null},this.getDepthSensingMesh=function(){return Q.getMesh(T)},this.getCameraTexture=function(BA){return C[BA]};let lA=null;function oA(BA,_){if(I=_.getViewerPose(r||o),E=_,I!==null){const G=I.views;B!==null&&(A.setRenderTargetFramebuffer(y,B.framebuffer),A.setRenderTarget(y));let x=!1;G.length!==T.cameras.length&&(T.cameras.length=0,x=!0);for(let P=0;P<G.length;P++){const R=G[P];let q=null;if(B!==null)q=B.getViewport(R);else{const O=l.getViewSubImage(h,R);q=O.viewport,P===0&&(A.setRenderTargetTextures(y,O.colorTexture,O.depthStencilTexture),A.setRenderTarget(y))}let L=m[P];L===void 0&&(L=new Ce,L.layers.enable(P),L.viewport=new Ct,m[P]=L),L.matrix.fromArray(R.transform.matrix),L.matrix.decompose(L.position,L.quaternion,L.scale),L.projectionMatrix.fromArray(R.projectionMatrix),L.projectionMatrixInverse.copy(L.projectionMatrix).invert(),L.viewport.set(q.x,q.y,q.width,q.height),P===0&&(T.matrix.copy(L.matrix),T.matrix.decompose(T.position,T.quaternion,T.scale)),x===!0&&T.cameras.push(L)}const U=i.enabledFeatures;if(U&&U.includes("depth-sensing")&&i.depthUsage=="gpu-optimized"&&c){l=e.getBinding();const P=l.getDepthInformation(G[0]);P&&P.isValid&&P.texture&&Q.init(P,i.renderState)}if(U&&U.includes("camera-access")&&c){A.state.unbindTexture(),l=e.getBinding();for(let P=0;P<G.length;P++){const R=G[P].camera;if(R){let q=C[R];q||(q=new Sd,C[R]=q);const L=l.getCameraImage(R);q.sourceTexture=L}}}}for(let G=0;G<w.length;G++){const x=D[G],U=w[G];x!==null&&U!==void 0&&U.update(x,_,r||o)}lA&&lA(BA,_),_.detectedPlanes&&e.dispatchEvent({type:"planesdetected",data:_}),E=null}const dA=new Nu;dA.setAnimationLoop(oA),this.setAnimationLoop=function(BA){lA=BA},this.dispose=function(){}}}const jU=new RA,hm=new ht;hm.set(-1,0,0,0,1,0,0,0,1);function RU(s,A){function t(Q,C){Q.matrixAutoUpdate===!0&&Q.updateMatrix(),C.value.copy(Q.matrix)}function e(Q,C){C.color.getRGB(Q.fogColor.value,kw(s)),C.isFog?(Q.fogNear.value=C.near,Q.fogFar.value=C.far):C.isFogExp2&&(Q.fogDensity.value=C.density)}function i(Q,C,d,M,y){C.isNodeMaterial?C.uniformsNeedUpdate=!1:C.isMeshBasicMaterial?n(Q,C):C.isMeshLambertMaterial?(n(Q,C),C.envMap&&(Q.envMapIntensity.value=C.envMapIntensity)):C.isMeshToonMaterial?(n(Q,C),l(Q,C)):C.isMeshPhongMaterial?(n(Q,C),I(Q,C),C.envMap&&(Q.envMapIntensity.value=C.envMapIntensity)):C.isMeshStandardMaterial?(n(Q,C),h(Q,C),C.isMeshPhysicalMaterial&&B(Q,C,y)):C.isMeshMatcapMaterial?(n(Q,C),E(Q,C)):C.isMeshDepthMaterial?n(Q,C):C.isMeshDistanceMaterial?(n(Q,C),c(Q,C)):C.isMeshNormalMaterial?n(Q,C):C.isLineBasicMaterial?(o(Q,C),C.isLineDashedMaterial&&g(Q,C)):C.isPointsMaterial?a(Q,C,d,M):C.isSpriteMaterial?r(Q,C):C.isShadowMaterial?(Q.color.value.copy(C.color),Q.opacity.value=C.opacity):C.isShaderMaterial&&(C.uniformsNeedUpdate=!1)}function n(Q,C){Q.opacity.value=C.opacity,C.color&&Q.diffuse.value.copy(C.color),C.emissive&&Q.emissive.value.copy(C.emissive).multiplyScalar(C.emissiveIntensity),C.map&&(Q.map.value=C.map,t(C.map,Q.mapTransform)),C.alphaMap&&(Q.alphaMap.value=C.alphaMap,t(C.alphaMap,Q.alphaMapTransform)),C.bumpMap&&(Q.bumpMap.value=C.bumpMap,t(C.bumpMap,Q.bumpMapTransform),Q.bumpScale.value=C.bumpScale,C.side===Ne&&(Q.bumpScale.value*=-1)),C.normalMap&&(Q.normalMap.value=C.normalMap,t(C.normalMap,Q.normalMapTransform),Q.normalScale.value.copy(C.normalScale),C.side===Ne&&Q.normalScale.value.negate()),C.displacementMap&&(Q.displacementMap.value=C.displacementMap,t(C.displacementMap,Q.displacementMapTransform),Q.displacementScale.value=C.displacementScale,Q.displacementBias.value=C.displacementBias),C.emissiveMap&&(Q.emissiveMap.value=C.emissiveMap,t(C.emissiveMap,Q.emissiveMapTransform)),C.specularMap&&(Q.specularMap.value=C.specularMap,t(C.specularMap,Q.specularMapTransform)),C.alphaTest>0&&(Q.alphaTest.value=C.alphaTest);const d=A.get(C),M=d.envMap,y=d.envMapRotation;M&&(Q.envMap.value=M,Q.envMapRotation.value.setFromMatrix4(jU.makeRotationFromEuler(y)).transpose(),M.isCubeTexture&&M.isRenderTargetTexture===!1&&Q.envMapRotation.value.premultiply(hm),Q.reflectivity.value=C.reflectivity,Q.ior.value=C.ior,Q.refractionRatio.value=C.refractionRatio),C.lightMap&&(Q.lightMap.value=C.lightMap,Q.lightMapIntensity.value=C.lightMapIntensity,t(C.lightMap,Q.lightMapTransform)),C.aoMap&&(Q.aoMap.value=C.aoMap,Q.aoMapIntensity.value=C.aoMapIntensity,t(C.aoMap,Q.aoMapTransform))}function o(Q,C){Q.diffuse.value.copy(C.color),Q.opacity.value=C.opacity,C.map&&(Q.map.value=C.map,t(C.map,Q.mapTransform))}function g(Q,C){Q.dashSize.value=C.dashSize,Q.totalSize.value=C.dashSize+C.gapSize,Q.scale.value=C.scale}function a(Q,C,d,M){Q.diffuse.value.copy(C.color),Q.opacity.value=C.opacity,Q.size.value=C.size*d,Q.scale.value=M*.5,C.map&&(Q.map.value=C.map,t(C.map,Q.uvTransform)),C.alphaMap&&(Q.alphaMap.value=C.alphaMap,t(C.alphaMap,Q.alphaMapTransform)),C.alphaTest>0&&(Q.alphaTest.value=C.alphaTest)}function r(Q,C){Q.diffuse.value.copy(C.color),Q.opacity.value=C.opacity,Q.rotation.value=C.rotation,C.map&&(Q.map.value=C.map,t(C.map,Q.mapTransform)),C.alphaMap&&(Q.alphaMap.value=C.alphaMap,t(C.alphaMap,Q.alphaMapTransform)),C.alphaTest>0&&(Q.alphaTest.value=C.alphaTest)}function I(Q,C){Q.specular.value.copy(C.specular),Q.shininess.value=Math.max(C.shininess,1e-4)}function l(Q,C){C.gradientMap&&(Q.gradientMap.value=C.gradientMap)}function h(Q,C){Q.metalness.value=C.metalness,C.metalnessMap&&(Q.metalnessMap.value=C.metalnessMap,t(C.metalnessMap,Q.metalnessMapTransform)),Q.roughness.value=C.roughness,C.roughnessMap&&(Q.roughnessMap.value=C.roughnessMap,t(C.roughnessMap,Q.roughnessMapTransform)),C.envMap&&(Q.envMapIntensity.value=C.envMapIntensity)}function B(Q,C,d){Q.ior.value=C.ior,C.sheen>0&&(Q.sheenColor.value.copy(C.sheenColor).multiplyScalar(C.sheen),Q.sheenRoughness.value=C.sheenRoughness,C.sheenColorMap&&(Q.sheenColorMap.value=C.sheenColorMap,t(C.sheenColorMap,Q.sheenColorMapTransform)),C.sheenRoughnessMap&&(Q.sheenRoughnessMap.value=C.sheenRoughnessMap,t(C.sheenRoughnessMap,Q.sheenRoughnessMapTransform))),C.clearcoat>0&&(Q.clearcoat.value=C.clearcoat,Q.clearcoatRoughness.value=C.clearcoatRoughness,C.clearcoatMap&&(Q.clearcoatMap.value=C.clearcoatMap,t(C.clearcoatMap,Q.clearcoatMapTransform)),C.clearcoatRoughnessMap&&(Q.clearcoatRoughnessMap.value=C.clearcoatRoughnessMap,t(C.clearcoatRoughnessMap,Q.clearcoatRoughnessMapTransform)),C.clearcoatNormalMap&&(Q.clearcoatNormalMap.value=C.clearcoatNormalMap,t(C.clearcoatNormalMap,Q.clearcoatNormalMapTransform),Q.clearcoatNormalScale.value.copy(C.clearcoatNormalScale),C.side===Ne&&Q.clearcoatNormalScale.value.negate())),C.dispersion>0&&(Q.dispersion.value=C.dispersion),C.retroreflectivity>0&&(Q.retroreflectivity.value=C.retroreflectivity),C.iridescence>0&&(Q.iridescence.value=C.iridescence,Q.iridescenceIOR.value=C.iridescenceIOR,Q.iridescenceThicknessMinimum.value=C.iridescenceThicknessRange[0],Q.iridescenceThicknessMaximum.value=C.iridescenceThicknessRange[1],C.iridescenceMap&&(Q.iridescenceMap.value=C.iridescenceMap,t(C.iridescenceMap,Q.iridescenceMapTransform)),C.iridescenceThicknessMap&&(Q.iridescenceThicknessMap.value=C.iridescenceThicknessMap,t(C.iridescenceThicknessMap,Q.iridescenceThicknessMapTransform))),C.transmission>0&&(Q.transmission.value=C.transmission,Q.transmissionSamplerMap.value=d.texture,Q.transmissionSamplerSize.value.set(d.width,d.height),C.transmissionMap&&(Q.transmissionMap.value=C.transmissionMap,t(C.transmissionMap,Q.transmissionMapTransform)),Q.thickness.value=C.thickness,C.thicknessMap&&(Q.thicknessMap.value=C.thicknessMap,t(C.thicknessMap,Q.thicknessMapTransform)),Q.attenuationDistance.value=C.attenuationDistance,Q.attenuationColor.value.copy(C.attenuationColor)),C.anisotropy>0&&(Q.anisotropyVector.value.set(C.anisotropy*Math.cos(C.anisotropyRotation),C.anisotropy*Math.sin(C.anisotropyRotation)),C.anisotropyMap&&(Q.anisotropyMap.value=C.anisotropyMap,t(C.anisotropyMap,Q.anisotropyMapTransform))),Q.specularIntensity.value=C.specularIntensity,Q.specularColor.value.copy(C.specularColor),C.specularColorMap&&(Q.specularColorMap.value=C.specularColorMap,t(C.specularColorMap,Q.specularColorMapTransform)),C.specularIntensityMap&&(Q.specularIntensityMap.value=C.specularIntensityMap,t(C.specularIntensityMap,Q.specularIntensityMapTransform))}function E(Q,C){C.matcap&&(Q.matcap.value=C.matcap)}function c(Q,C){const d=A.get(C).light;Q.referencePosition.value.setFromMatrixPosition(d.matrixWorld),Q.nearDistance.value=d.shadow.camera.near,Q.farDistance.value=d.shadow.camera.far}return{refreshFogUniforms:e,refreshMaterialUniforms:i}}function ZU(s,A,t,e){let i={},n={},o=[];const g=s.getParameter(s.MAX_UNIFORM_BUFFER_BINDINGS);function a(y,w){const D=w.program;e.uniformBlockBinding(y,D)}function r(y,w){let D=i[y.id];D===void 0&&(Q(y),D=I(y),i[y.id]=D,y.addEventListener("dispose",d));const p=w.program;e.updateUBOMapping(y,p);const f=A.render.frame;n[y.id]!==f&&(h(y),n[y.id]=f)}function I(y){const w=l();y.__bindingPointIndex=w;const D=s.createBuffer(),p=y.__size,f=y.usage;return s.bindBuffer(s.UNIFORM_BUFFER,D),s.bufferData(s.UNIFORM_BUFFER,p,f),s.bindBuffer(s.UNIFORM_BUFFER,null),s.bindBufferBase(s.UNIFORM_BUFFER,w,D),D}function l(){for(let y=0;y<g;y++)if(o.indexOf(y)===-1)return o.push(y),y;return gt("WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function h(y){const w=i[y.id],D=y.uniforms,p=y.__cache;s.bindBuffer(s.UNIFORM_BUFFER,w);for(let f=0,u=D.length;f<u;f++){const Y=D[f];if(Array.isArray(Y))for(let b=0,m=Y.length;b<m;b++)B(Y[b],f,b,p);else B(Y,f,0,p)}s.bindBuffer(s.UNIFORM_BUFFER,null)}function B(y,w,D,p){if(c(y,w,D,p)===!0){const f=y.__offset,u=y.value;if(Array.isArray(u)){let Y=0;for(let b=0;b<u.length;b++){const m=u[b],T=C(m);E(m,y.__data,Y),typeof m!="number"&&typeof m!="boolean"&&!m.isMatrix3&&!ArrayBuffer.isView(m)&&(Y+=T.storage/Float32Array.BYTES_PER_ELEMENT)}}else E(u,y.__data,0);s.bufferSubData(s.UNIFORM_BUFFER,f,y.__data)}}function E(y,w,D){typeof y=="number"||typeof y=="boolean"?w[0]=y:y.isMatrix3?(w[0]=y.elements[0],w[1]=y.elements[1],w[2]=y.elements[2],w[3]=0,w[4]=y.elements[3],w[5]=y.elements[4],w[6]=y.elements[5],w[7]=0,w[8]=y.elements[6],w[9]=y.elements[7],w[10]=y.elements[8],w[11]=0):ArrayBuffer.isView(y)?w.set(new y.constructor(y.buffer,y.byteOffset,w.length)):y.toArray(w,D)}function c(y,w,D,p){const f=y.value,u=w+"_"+D;if(p[u]===void 0)return typeof f=="number"||typeof f=="boolean"?p[u]=f:ArrayBuffer.isView(f)?p[u]=f.slice():p[u]=f.clone(),!0;{const Y=p[u];if(typeof f=="number"||typeof f=="boolean"){if(Y!==f)return p[u]=f,!0}else{if(ArrayBuffer.isView(f))return!0;if(Y.equals(f)===!1)return Y.copy(f),!0}}return!1}function Q(y){const w=y.uniforms;let D=0;const p=16;for(let u=0,Y=w.length;u<Y;u++){const b=Array.isArray(w[u])?w[u]:[w[u]];for(let m=0,T=b.length;m<T;m++){const F=b[m],j=Array.isArray(F.value)?F.value:[F.value];for(let X=0,v=j.length;X<v;X++){const k=j[X],K=C(k),z=D%p,H=z%K.boundary,eA=z+H;D+=H,eA!==0&&p-eA<K.storage&&(D+=p-eA),F.__data=new Float32Array(K.storage/Float32Array.BYTES_PER_ELEMENT),F.__offset=D,D+=K.storage}}}const f=D%p;return f>0&&(D+=p-f),y.__size=D,y.__cache={},this}function C(y){const w={boundary:0,storage:0};return typeof y=="number"||typeof y=="boolean"?(w.boundary=4,w.storage=4):y.isVector2?(w.boundary=8,w.storage=8):y.isVector3||y.isColor?(w.boundary=16,w.storage=12):y.isVector4?(w.boundary=16,w.storage=16):y.isMatrix3?(w.boundary=48,w.storage=48):y.isMatrix4?(w.boundary=64,w.storage=64):y.isTexture?_A("WebGLRenderer: Texture samplers can not be part of an uniforms group."):ArrayBuffer.isView(y)?(w.boundary=16,w.storage=y.byteLength):_A("WebGLRenderer: Unsupported uniform value type.",y),w}function d(y){const w=y.target;w.removeEventListener("dispose",d);const D=o.indexOf(w.__bindingPointIndex);o.splice(D,1),s.deleteBuffer(i[w.id]),delete i[w.id],delete n[w.id]}function M(){for(const y in i)s.deleteBuffer(i[y]);o=[],i={},n={}}return{bind:a,update:r,dispose:M}}const NU=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]);let ln=null;function UU(){return ln===null&&(ln=new wi(NU,16,16,ss,qt),ln.name="DFG_LUT",ln.minFilter=Yt,ln.magFilter=Yt,ln.wrapS=Gi,ln.wrapT=Gi,ln.generateMipmaps=!1,ln.needsUpdate=!0),ln}class AE{constructor(A={}){const{canvas:t=RD(),context:e=null,depth:i=!0,stencil:n=!1,alpha:o=!1,antialias:g=!1,premultipliedAlpha:a=!0,preserveDrawingBuffer:r=!1,powerPreference:I="default",failIfMajorPerformanceCaveat:l=!1,reversedDepthBuffer:h=!1,outputBufferType:B=Bt}=A;this.isWebGLRenderer=!0;let E;if(e!==null){if(typeof WebGLRenderingContext<"u"&&e instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");E=e.getContextAttributes().alpha}else E=o;const c=B,Q=new Set([Bh,lh,EI]),C=new Set([Bt,Es,Bo,ho,rh,Ih]),d=new Uint32Array(4),M=new Int32Array(4),y=new S;let w=null,D=null;const p=[],f=[];let u=null;this.domElement=t,this.debug={checkShaderErrors:!0,diagnostics:{keywords:!1},onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=li,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const Y=this;let b=!1,m=null,T=null,F=null,j=null;this._outputColorSpace=Rt;let X=0,v=0,k=null,K=-1,z=null;const H=new Ct,eA=new Ct;let nA=null;const lA=new XA(0);let oA=0,dA=t.width,BA=t.height,_=1,G=null,x=null;const U=new Ct(0,0,dA,BA),J=new Ct(0,0,dA,BA);let W=!1;const P=new Do;let R=!1,q=!1;const L=new RA,O=new S,tA=new Ct,gA={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let hA=!1;function rA(){return k===null?_:1}let sA=e;function GA($,EA){return t.getContext($,EA)}let uA,iA,Z,IA,cA,yA,jA,NA,fA,YA,JA,OA,xA,kA,At,st,ot,CA,HA,TA,zA,VA,KA;try{const $={alpha:!0,depth:i,stencil:n,antialias:g,premultipliedAlpha:a,preserveDrawingBuffer:r,powerPreference:I,failIfMajorPerformanceCaveat:l};if("setAttribute"in t&&t.setAttribute("data-engine",`three.js r${fa}`),t.addEventListener("webglcontextlost",Qt,!1),t.addEventListener("webglcontextrestored",lt,!1),t.addEventListener("webglcontextcreationerror",Jt,!1),sA===null){const EA="webgl2";if(sA=GA(EA,$),sA===null)throw GA(EA)?new Error("THREE.WebGLRenderer: Error creating WebGL context with your selected attributes."):new Error("THREE.WebGLRenderer: Error creating WebGL context.")}tt()}catch($){throw t.removeEventListener("webglcontextlost",Qt,!1),t.removeEventListener("webglcontextrestored",lt,!1),t.removeEventListener("webglcontextcreationerror",Jt,!1),gt("WebGLRenderer: "+$.message),$}function tt(){uA=new XZ(sA),uA.init(),zA=new Bm(sA,uA),iA=new bZ(sA,uA,A,zA),Z=new FU(sA,uA),iA.reversedDepthBuffer&&h&&Z.buffers.depth.setReversed(!0),T=sA.createFramebuffer(),F=sA.createFramebuffer(),j=sA.createFramebuffer(),IA=new kZ(sA),cA=new cU,yA=new bU(sA,uA,Z,cA,iA,zA,IA),jA=new UZ(Y),NA=new mR(sA),VA=new YZ(sA,NA),fA=new JZ(sA,NA,IA,VA),YA=new HZ(sA,fA,NA,VA,IA),CA=new VZ(sA,iA,yA),At=new WZ(cA),JA=new EU(Y,jA,uA,iA,VA,At),OA=new RU(Y,cA),xA=new dU,kA=new wU(uA),ot=new SZ(Y,jA,Z,YA,E,a),st=new YU(Y,YA,iA),KA=new ZU(sA,IA,iA,Z),HA=new FZ(sA,uA,IA),TA=new xZ(sA,uA,IA),IA.programs=JA.programs,Y.capabilities=iA,Y.extensions=uA,Y.properties=cA,Y.renderLists=xA,Y.shadowMap=st,Y.state=Z,Y.info=IA}c!==Bt&&(u=new LZ(c,t.width,t.height,g,i,n));const qA=new KU(Y,sA);this.xr=qA,this.getContext=function(){return sA},this.getContextAttributes=function(){return sA.getContextAttributes()},this.forceContextLoss=function(){const $=uA.get("WEBGL_lose_context");$&&$.loseContext()},this.forceContextRestore=function(){const $=uA.get("WEBGL_lose_context");$&&$.restoreContext()},this.getPixelRatio=function(){return _},this.setPixelRatio=function($){$!==void 0&&(_=$,this.setSize(dA,BA,!1))},this.getSize=function($){return $.set(dA,BA)},this.setSize=function($,EA,mA=!0){if(qA.isPresenting){_A("WebGLRenderer: Can't change size while VR device is presenting.");return}dA=$,BA=EA,t.width=Math.floor($*_),t.height=Math.floor(EA*_),mA===!0&&(t.style.width=$+"px",t.style.height=EA+"px"),u!==null&&u.setSize(t.width,t.height),this.setViewport(0,0,$,EA)},this.getDrawingBufferSize=function($){return $.set(dA*_,BA*_).floor()},this.setDrawingBufferSize=function($,EA,mA){dA=$,BA=EA,_=mA,t.width=Math.floor($*mA),t.height=Math.floor(EA*mA),this.setViewport(0,0,$,EA)},this.setEffects=function($){if(c===Bt){gt("WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.");return}if($){for(let EA=0;EA<$.length;EA++)if($[EA].isOutputPass===!0){_A("WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.");break}}u.setEffects($||[])},this.getCurrentViewport=function($){return $.copy(H)},this.getViewport=function($){return $.copy(U)},this.setViewport=function($,EA,mA,DA){$.isVector4?U.set($.x,$.y,$.z,$.w):U.set($,EA,mA,DA),Z.viewport(H.copy(U).multiplyScalar(_).round())},this.getScissor=function($){return $.copy(J)},this.setScissor=function($,EA,mA,DA){$.isVector4?J.set($.x,$.y,$.z,$.w):J.set($,EA,mA,DA),Z.scissor(eA.copy(J).multiplyScalar(_).round())},this.getScissorTest=function(){return W},this.setScissorTest=function($){Z.setScissorTest(W=$)},this.setOpaqueSort=function($){G=$},this.setTransparentSort=function($){x=$},this.getClearColor=function($){return $.copy(ot.getClearColor())},this.setClearColor=function(){ot.setClearColor(...arguments)},this.getClearAlpha=function(){return ot.getClearAlpha()},this.setClearAlpha=function(){ot.setClearAlpha(...arguments)},this.clear=function($=!0,EA=!0,mA=!0){let DA=0;if($){let wA=!1;if(k!==null){const N=k.texture.format;wA=Q.has(N)}if(wA){const N=k.texture.type,V=C.has(N),AA=ot.getClearColor(),aA=ot.getClearAlpha(),pA=AA.r,FA=AA.g,UA=AA.b;V?(d[0]=pA,d[1]=FA,d[2]=UA,d[3]=aA,sA.clearBufferuiv(sA.COLOR,0,d)):(M[0]=pA,M[1]=FA,M[2]=UA,M[3]=aA,sA.clearBufferiv(sA.COLOR,0,M))}else DA|=sA.COLOR_BUFFER_BIT}EA&&(DA|=sA.DEPTH_BUFFER_BIT,this.state.buffers.depth.setMask(!0)),mA&&(DA|=sA.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),DA!==0&&sA.clear(DA)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.setNodesHandler=function($){$.setRenderer(this),m=$},this.dispose=function(){t.removeEventListener("webglcontextlost",Qt,!1),t.removeEventListener("webglcontextrestored",lt,!1),t.removeEventListener("webglcontextcreationerror",Jt,!1),ot.dispose(),xA.dispose(),kA.dispose(),cA.dispose(),jA.dispose(),YA.dispose(),VA.dispose(),KA.dispose(),JA.dispose(),qA.dispose(),qA.removeEventListener("sessionstart",Fe),qA.removeEventListener("sessionend",Re),ne.stop()};function Qt($){$.preventDefault(),YI("WebGLRenderer: Context Lost."),b=!0}function lt(){YI("WebGLRenderer: Context Restored."),b=!1;const $=IA.autoReset,EA=st.enabled,mA=st.autoUpdate,DA=st.needsUpdate,wA=st.type;tt(),IA.autoReset=$,st.enabled=EA,st.autoUpdate=mA,st.needsUpdate=DA,st.type=wA}function Jt($){gt("WebGLRenderer: A WebGL context could not be created. Reason: ",$.statusMessage)}function Ht($){const EA=$.target;EA.removeEventListener("dispose",Ht),He(EA)}function He($){Oe($),cA.remove($)}function Oe($){const EA=cA.get($).programs;EA!==void 0&&(EA.forEach(function(mA){JA.releaseProgram(mA)}),$.isShaderMaterial&&JA.releaseShaderCache($))}this.renderBufferDirect=function($,EA,mA,DA,wA,N){EA===null&&(EA=gA);const V=wA.isMesh&&wA.matrixWorld.determinantAffine()<0,AA=Vp($,EA,mA,DA,wA);Z.setMaterial(DA,V);let aA=mA.index,pA=1;if(DA.wireframe===!0){if(aA=fA.getWireframeAttribute(mA),aA===void 0)return;pA=2}const FA=mA.drawRange,UA=mA.attributes.position;let WA=FA.start*pA,at=(FA.start+FA.count)*pA;N!==null&&(WA=Math.max(WA,N.start*pA),at=Math.min(at,(N.start+N.count)*pA)),aA!==null?(WA=Math.max(WA,0),at=Math.min(at,aA.count)):UA!=null&&(WA=Math.max(WA,0),at=Math.min(at,UA.count));const St=at-WA;if(St<0||St===1/0)return;VA.setup(wA,DA,AA,mA,aA);let Gt,mt=HA;if(aA!==null&&(Gt=NA.get(aA),mt=TA,mt.setIndex(Gt)),wA.isMesh)DA.wireframe===!0?(Z.setLineWidth(DA.wireframeLinewidth*rA()),mt.setMode(sA.LINES)):mt.setMode(sA.TRIANGLES);else if(wA.isLine){let oe=DA.linewidth;oe===void 0&&(oe=1),Z.setLineWidth(oe*rA()),wA.isLineSegments?mt.setMode(sA.LINES):wA.isLineLoop?mt.setMode(sA.LINE_LOOP):mt.setMode(sA.LINE_STRIP)}else wA.isPoints?mt.setMode(sA.POINTS):wA.isSprite&&mt.setMode(sA.TRIANGLES);if(wA.isBatchedMesh)if(uA.get("WEBGL_multi_draw"))mt.renderMultiDraw(wA._multiDrawStarts,wA._multiDrawCounts,wA._multiDrawCount);else{const oe=wA._multiDrawStarts,it=wA._multiDrawCounts,ie=wA._multiDrawCount,dt=aA?NA.get(aA).bytesPerElement:1,Mi=cA.get(DA).currentProgram.getUniforms();for(let ii=0;ii<ie;ii++)Mi.setValue(sA,"_gl_DrawID",ii),mt.render(oe[ii]/dt,it[ii])}else if(wA.isInstancedMesh)mt.renderInstances(WA,St,wA.count);else if(mA.isInstancedBufferGeometry){const oe=mA._maxInstanceCount!==void 0?mA._maxInstanceCount:1/0,it=Math.min(mA.instanceCount,oe);mt.renderInstances(WA,St,it)}else mt.render(WA,St)};function je($,EA,mA,DA){m!==null&&$.isNodeMaterial&&m.setObject(DA,$),R===!0&&At.setState($,mA,!1),$.transparent===!0&&$.side===Tt&&$.forceSinglePass===!1?($.side=Ne,$.needsUpdate=!0,nI($,EA,DA),$.side=es,$.needsUpdate=!0,nI($,EA,DA),$.side=Tt):nI($,EA,DA)}this.compile=function($,EA,mA=null){mA===null&&(mA=$),m!==null&&m.renderStart($,EA,mA),D=kA.get(mA),D.init(EA),f.push(D),mA.traverseVisible(function(wA){wA.isLight&&wA.layers.test(EA.layers)&&(D.pushLight(wA),wA.castShadow&&D.pushShadow(wA))}),$!==mA&&$.traverseVisible(function(wA){wA.isLight&&wA.layers.test(EA.layers)&&(D.pushLight(wA),wA.castShadow&&D.pushShadow(wA))}),D.setupLights(),m!==null&&m.updateLights(D.state.lightsArray),q=this.localClippingEnabled,R=At.init(this.clippingPlanes,q),R===!0&&At.setGlobalState(this.clippingPlanes,EA),m!==null&&st.render(D.state.shadowsArray,mA,EA);const DA=new Set;return $.traverse(function(wA){if(!(wA.isMesh||wA.isPoints||wA.isLine||wA.isSprite))return;const N=wA.material;if(N)if(Array.isArray(N))for(let V=0;V<N.length;V++){const AA=N[V];je(AA,mA,EA,wA),DA.add(AA)}else je(N,mA,EA,wA),DA.add(N)}),D=f.pop(),m!==null&&m.renderEnd(),DA},this.compileAsync=function($,EA,mA=null){const DA=this.compile($,EA,mA);return new Promise(wA=>{function N(){if(DA.forEach(function(V){const aA=cA.get(V).currentProgram;(aA===void 0||aA.isReady())&&DA.delete(V)}),DA.size===0){wA($);return}setTimeout(N,10)}uA.get("KHR_parallel_shader_compile")!==null?N():setTimeout(N,10)})};let Ye=null;function de($){Ye&&Ye($)}function Fe(){ne.stop()}function Re(){ne.start()}const ne=new Nu;ne.setAnimationLoop(de),typeof self<"u"&&ne.setContext(self),this.setAnimationLoop=function($){Ye=$,qA.setAnimationLoop($),$===null?ne.stop():ne.start()},qA.addEventListener("sessionstart",Fe),qA.addEventListener("sessionend",Re),this.render=function($,EA){if(EA!==void 0&&EA.isCamera!==!0){gt("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(b===!0)return;m!==null&&m.renderStart($,EA);const mA=qA.enabled===!0&&qA.isPresenting===!0,DA=u!==null&&(k===null||mA)&&u.begin(Y,k);if($.matrixWorldAutoUpdate===!0&&$.updateMatrixWorld(),EA.parent===null&&EA.matrixWorldAutoUpdate===!0&&EA.updateMatrixWorld(),qA.enabled===!0&&qA.isPresenting===!0&&(u===null||u.isCompositing()===!1)&&(qA.cameraAutoUpdate===!0&&qA.updateCamera(EA),EA=qA.getCamera()),$.isScene===!0&&$.onBeforeRender(Y,$,EA,k),D=kA.get($,f.length),D.init(EA),D.state.textureUnits=yA.getTextureUnits(),f.push(D),L.multiplyMatrices(EA.projectionMatrix,EA.matrixWorldInverse),P.setFromProjectionMatrix(L,ns,EA.reversedDepth),q=this.localClippingEnabled,R=At.init(this.clippingPlanes,q),w=xA.get($,p.length),w.init(),p.push(w),qA.enabled===!0&&qA.isPresenting===!0){const V=Y.xr.getDepthSensingMesh();V!==null&&VB(V,EA,-1/0,Y.sortObjects)}VB($,EA,0,Y.sortObjects),w.finish(),m!==null&&m.updateLights(D.state.lightsArray),Y.sortObjects===!0&&w.sort(G,x),hA=qA.enabled===!1||qA.isPresenting===!1||qA.hasDepthSensing()===!1,hA&&ot.addToRenderList(w,$),this.info.render.frame++,this.info.autoReset===!0&&this.info.reset(),R===!0&&At.beginShadows();const wA=D.state.shadowsArray;if(st.render(wA,$,EA),R===!0&&At.endShadows(),(DA&&u.hasRenderPass())===!1){const V=w.opaque,AA=w.transmissive;if(D.setupLights(),EA.isArrayCamera){const aA=EA.cameras;if(AA.length>0)for(let pA=0,FA=aA.length;pA<FA;pA++){const UA=aA[pA];PQ(V,AA,$,UA)}hA&&ot.render($);for(let pA=0,FA=aA.length;pA<FA;pA++){const UA=aA[pA];mQ(w,$,UA,UA.viewport)}}else AA.length>0&&PQ(V,AA,$,EA),hA&&ot.render($),mQ(w,$,EA)}k!==null&&v===0&&(yA.updateMultisampleRenderTarget(k),yA.updateRenderTargetMipmap(k)),DA&&u.end(Y),$.isScene===!0&&$.onAfterRender(Y,$,EA),VA.resetDefaultState(),K=-1,z=null,f.pop(),f.length>0?(D=f[f.length-1],yA.setTextureUnits(D.state.textureUnits),R===!0&&At.setGlobalState(Y.clippingPlanes,D.state.camera)):D=null,p.pop(),p.length>0?w=p[p.length-1]:w=null,m!==null&&m.renderEnd()};function VB($,EA,mA,DA){if($.visible===!1)return;if($.layers.test(EA.layers)){if($.isGroup)mA=$.renderOrder;else if($.isLOD)$.autoUpdate===!0&&$.update(EA);else if($.isLightProbeGrid)D.pushLightProbeGrid($);else if($.isLight)D.pushLight($),$.castShadow&&D.pushShadow($);else if($.isSprite){if(!$.frustumCulled||$.intersectsFrustum(P)){DA&&tA.setFromMatrixPosition($.matrixWorld).applyMatrix4(L);const V=YA.update($),AA=$.material;AA.visible&&w.push($,V,AA,mA,tA.z,null,EA)}}else if(($.isMesh||$.isLine||$.isPoints)&&(!$.frustumCulled||$.intersectsFrustum(P))){const V=YA.update($),AA=$.material;if(DA&&($.boundingSphere!==void 0?($.boundingSphere===null&&$.computeBoundingSphere(),tA.copy($.boundingSphere.center)):(V.boundingSphere===null&&V.computeBoundingSphere(),tA.copy(V.boundingSphere.center)),tA.applyMatrix4($.matrixWorld).applyMatrix4(L)),Array.isArray(AA)){const aA=V.groups;for(let pA=0,FA=aA.length;pA<FA;pA++){const UA=aA[pA],WA=AA[UA.materialIndex];WA&&WA.visible&&w.push($,V,WA,mA,tA.z,UA,EA)}}else AA.visible&&w.push($,V,AA,mA,tA.z,null,EA)}}const N=$.children;for(let V=0,AA=N.length;V<AA;V++)VB(N[V],EA,mA,DA)}function mQ($,EA,mA,DA){const{opaque:wA,transmissive:N,transparent:V}=$;D.setupLightsView(mA),R===!0&&At.setGlobalState(Y.clippingPlanes,mA),DA&&Z.viewport(H.copy(DA)),wA.length>0&&tn(wA,EA,mA),N.length>0&&tn(N,EA,mA),V.length>0&&tn(V,EA,mA),Z.buffers.depth.setTest(!0),Z.buffers.depth.setMask(!0),Z.buffers.color.setMask(!0),Z.setPolygonOffset(!1)}function PQ($,EA,mA,DA){if((mA.isScene===!0?mA.overrideMaterial:null)!==null)return;if(D.state.transmissionRenderTarget[DA.id]===void 0){const WA=uA.has("EXT_color_buffer_half_float")||uA.has("EXT_color_buffer_float");D.state.transmissionRenderTarget[DA.id]=new pe(1,1,{generateMipmaps:!0,type:WA?qt:Bt,minFilter:Oi,samples:Math.max(4,iA.samples),stencilBuffer:n,resolveDepthBuffer:!1,resolveStencilBuffer:!1,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!1,colorSpace:ft.workingColorSpace})}const N=D.state.transmissionRenderTarget[DA.id],V=DA.viewport||H;N.setSize(V.z*Y.transmissionResolutionScale,V.w*Y.transmissionResolutionScale);const AA=Y.getRenderTarget(),aA=Y.getActiveCubeFace(),pA=Y.getActiveMipmapLevel();Y.setRenderTarget(N),Y.getClearColor(lA),oA=Y.getClearAlpha(),oA<1&&Y.setClearColor(16777215,.5),Y.clear(),hA&&ot.render(mA);const FA=Y.toneMapping;Y.toneMapping=li;const UA=DA.viewport;if(DA.viewport!==void 0&&(DA.viewport=void 0),D.setupLightsView(DA),R===!0&&At.setGlobalState(Y.clippingPlanes,DA),tn($,mA,DA),yA.updateMultisampleRenderTarget(N),yA.updateRenderTargetMipmap(N),uA.has("WEBGL_multisampled_render_to_texture")===!1){let WA=!1;for(let at=0,St=EA.length;at<St;at++){const Gt=EA[at],{object:mt,geometry:oe,material:it,group:ie}=Gt;if(it.side===Tt&&mt.layers.test(DA.layers)){const dt=it.side;it.side=Ne,it.needsUpdate=!0,SQ(mt,mA,DA,oe,it,ie),it.side=dt,it.needsUpdate=!0,WA=!0}}WA===!0&&(yA.updateMultisampleRenderTarget(N),yA.updateRenderTargetMipmap(N))}Y.setRenderTarget(AA,aA,pA),Y.setClearColor(lA,oA),UA!==void 0&&(DA.viewport=UA),Y.toneMapping=FA}function tn($,EA,mA){const DA=EA.isScene===!0?EA.overrideMaterial:null;for(let wA=0,N=$.length;wA<N;wA++){const V=$[wA],{object:AA,geometry:aA,group:pA}=V;let FA=V.material;FA.allowOverride===!0&&DA!==null&&(FA=DA),AA.layers.test(mA.layers)&&SQ(AA,EA,mA,aA,FA,pA)}}function SQ($,EA,mA,DA,wA,N){m!==null&&wA.isNodeMaterial&&m.setObject($,wA),$.onBeforeRender(Y,EA,mA,DA,wA,N),$.modelViewMatrix.multiplyMatrices(mA.matrixWorldInverse,$.matrixWorld),$.normalMatrix.getNormalMatrix($.modelViewMatrix),wA.onBeforeRender(Y,EA,mA,DA,$,N),wA.transparent===!0&&wA.side===Tt&&wA.forceSinglePass===!1?(wA.side=Ne,wA.needsUpdate=!0,Y.renderBufferDirect(mA,EA,DA,wA,$,N),wA.side=es,wA.needsUpdate=!0,Y.renderBufferDirect(mA,EA,DA,wA,$,N),wA.side=Tt):Y.renderBufferDirect(mA,EA,DA,wA,$,N),$.onAfterRender(Y,EA,mA,DA,wA,N)}function nI($,EA,mA){EA.isScene!==!0&&(EA=gA);const DA=cA.get($),wA=D.state.lights,N=D.state.shadowsArray,V=wA.state.version,AA=JA.getParameters($,wA.state,N,EA,mA,D.state.lightProbeGridArray),aA=JA.getProgramCacheKey(AA);let pA=DA.programs;DA.environment=$.isMeshStandardMaterial||$.isMeshLambertMaterial||$.isMeshPhongMaterial?EA.environment:null,DA.fog=EA.fog;const FA=$.isMeshStandardMaterial||$.isMeshLambertMaterial&&!$.envMap||$.isMeshPhongMaterial&&!$.envMap;DA.envMap=jA.get($.envMap||DA.environment,FA),DA.envMapRotation=DA.environment!==null&&$.envMap===null?EA.environmentRotation:$.envMapRotation,pA===void 0&&($.addEventListener("dispose",Ht),pA=new Map,DA.programs=pA);let UA=pA.get(aA);if(UA!==void 0){if(DA.currentProgram===UA&&DA.lightsStateVersion===V)return FQ($,AA),UA}else AA.uniforms=JA.getUniforms($),m!==null&&$.isNodeMaterial&&m.build($,mA,AA),$.onBeforeCompile(AA,Y),UA=JA.acquireProgram(AA,aA),pA.set(aA,UA),DA.uniforms=AA.uniforms;const WA=DA.uniforms;return(!$.isShaderMaterial&&!$.isRawShaderMaterial||$.clipping===!0)&&(WA.clippingPlanes=At.uniform),FQ($,AA),DA.needsLights=Op($),DA.lightsStateVersion=V,DA.needsLights&&(WA.ambientLightColor.value=wA.state.ambient,WA.lightProbe.value=wA.state.probe,WA.sunLights.value=wA.state.sun,WA.sunLightShadows.value=wA.state.sunShadow,WA.directionalLights.value=wA.state.directional,WA.directionalLightShadows.value=wA.state.directionalShadow,WA.spotLights.value=wA.state.spot,WA.spotLightShadows.value=wA.state.spotShadow,WA.rectAreaLights.value=wA.state.rectArea,WA.ltc_1.value=wA.state.rectAreaLTC1,WA.ltc_2.value=wA.state.rectAreaLTC2,WA.pointLights.value=wA.state.point,WA.pointLightShadows.value=wA.state.pointShadow,WA.hemisphereLights.value=wA.state.hemi,WA.sunShadowMatrix.value=wA.state.sunShadowMatrix,WA.sunShadowCascade.value=wA.state.sunShadowCascade,WA.directionalShadowMatrix.value=wA.state.directionalShadowMatrix,WA.spotLightMatrix.value=wA.state.spotLightMatrix,WA.spotLightMap.value=wA.state.spotLightMap,WA.pointShadowMatrix.value=wA.state.pointShadowMatrix),DA.lightProbeGrid=D.state.lightProbeGridArray.length>0,DA.currentProgram=UA,DA.uniformsList=null,UA}function YQ($){if($.uniformsList===null){const EA=$.currentProgram.getUniforms();$.uniformsList=qC.seqWithValue(EA.seq,$.uniforms)}return $.uniformsList}function FQ($,EA){const mA=cA.get($);mA.outputColorSpace=EA.outputColorSpace,mA.batching=EA.batching,mA.batchingColor=EA.batchingColor,mA.instancing=EA.instancing,mA.instancingColor=EA.instancingColor,mA.instancingMorph=EA.instancingMorph,mA.skinning=EA.skinning,mA.morphTargets=EA.morphTargets,mA.morphNormals=EA.morphNormals,mA.morphColors=EA.morphColors,mA.morphTargetsCount=EA.morphTargetsCount,mA.numClippingPlanes=EA.numClippingPlanes,mA.numIntersection=EA.numClipIntersection,mA.vertexAlphas=EA.vertexAlphas,mA.vertexTangents=EA.vertexTangents,mA.toneMapping=EA.toneMapping}function kp($,EA){if($.length===0)return null;if($.length===1)return $[0].texture!==null?$[0]:null;y.setFromMatrixPosition(EA.matrixWorld);for(let mA=0,DA=$.length;mA<DA;mA++){const wA=$[mA];if(wA.texture!==null&&wA.boundingBox.containsPoint(y))return wA}return null}function Vp($,EA,mA,DA,wA){EA.isScene!==!0&&(EA=gA),yA.resetTextureUnits();const N=EA.fog,V=DA.isMeshStandardMaterial||DA.isMeshLambertMaterial||DA.isMeshPhongMaterial?EA.environment:null,AA=k===null?Y.outputColorSpace:k.isXRRenderTarget===!0?k.texture.colorSpace:ft.workingColorSpace,aA=DA.isMeshStandardMaterial||DA.isMeshLambertMaterial&&!DA.envMap||DA.isMeshPhongMaterial&&!DA.envMap,pA=jA.get(DA.envMap||V,aA),FA=DA.vertexColors===!0&&!!mA.attributes.color&&mA.attributes.color.itemSize===4,UA=!!mA.attributes.tangent&&(!!DA.normalMap||DA.anisotropy>0),WA=!!mA.morphAttributes.position,at=!!mA.morphAttributes.normal,St=!!mA.morphAttributes.color;let Gt=li;DA.toneMapped&&(k===null||k.isXRRenderTarget===!0)&&(Gt=Y.toneMapping);const mt=mA.morphAttributes.position||mA.morphAttributes.normal||mA.morphAttributes.color,oe=mt!==void 0?mt.length:0,it=cA.get(DA),ie=D.state.lights;if(R===!0&&(q===!0||$!==z)){const ge=$===z&&DA.id===K;At.setState(DA,$,ge)}let dt=!1;DA.version===it.__version?(it.needsLights&&it.lightsStateVersion!==ie.state.version||it.outputColorSpace!==AA||wA.isBatchedMesh&&it.batching===!1||!wA.isBatchedMesh&&it.batching===!0||wA.isBatchedMesh&&it.batchingColor===!0&&wA._colorsTexture===null||wA.isBatchedMesh&&it.batchingColor===!1&&wA._colorsTexture!==null||wA.isInstancedMesh&&it.instancing===!1||!wA.isInstancedMesh&&it.instancing===!0||wA.isSkinnedMesh&&it.skinning===!1||!wA.isSkinnedMesh&&it.skinning===!0||wA.isInstancedMesh&&it.instancingColor===!0&&wA.instanceColor===null||wA.isInstancedMesh&&it.instancingColor===!1&&wA.instanceColor!==null||wA.isInstancedMesh&&it.instancingMorph===!0&&wA.morphTexture===null||wA.isInstancedMesh&&it.instancingMorph===!1&&wA.morphTexture!==null||it.envMap!==pA||DA.fog===!0&&it.fog!==N||it.numClippingPlanes!==void 0&&(it.numClippingPlanes!==At.numPlanes||it.numIntersection!==At.numIntersection)||it.vertexAlphas!==FA||it.vertexTangents!==UA||it.morphTargets!==WA||it.morphNormals!==at||it.morphColors!==St||it.toneMapping!==Gt||it.morphTargetsCount!==oe||!!it.lightProbeGrid!=D.state.lightProbeGridArray.length>0)&&(dt=!0):(dt=!0,it.__version=DA.version);let Mi=it.currentProgram;dt===!0&&(Mi=nI(DA,EA,wA),m&&DA.isNodeMaterial&&m.onUpdateProgram(DA,Mi,it));let ii=!1,bs=!1,oI=!1;const _t=Mi.getUniforms(),Ze=it.uniforms;if(Z.useProgram(Mi.program)&&(ii=!0,bs=!0,oI=!0),DA.id!==K&&(K=DA.id,bs=!0),it.needsLights){const ge=kp(D.state.lightProbeGridArray,wA);it.lightProbeGrid!==ge&&(it.lightProbeGrid=ge,bs=!0)}if(ii||z!==$){Z.buffers.depth.getReversed()&&$.reversedDepth!==!0&&($._reversedDepth=!0,$.updateProjectionMatrix()),_t.setValue(sA,"projectionMatrix",$.projectionMatrix),_t.setValue(sA,"viewMatrix",$.matrixWorldInverse);const eg=_t.map.cameraPosition;eg!==void 0&&eg.setValue(sA,O.setFromMatrixPosition($.matrixWorld)),iA.logarithmicDepthBuffer&&_t.setValue(sA,"logDepthBufFC",2/(Math.log($.far+1)/Math.LN2)),(DA.isMeshPhongMaterial||DA.isMeshToonMaterial||DA.isMeshLambertMaterial||DA.isMeshBasicMaterial||DA.isMeshStandardMaterial||DA.isShaderMaterial)&&_t.setValue(sA,"isOrthographic",$.isOrthographicCamera===!0),z!==$&&(z=$,bs=!0,oI=!0)}if(it.needsLights&&(ie.state.sunShadowMap.length>0&&_t.setValue(sA,"sunShadowMap",ie.state.sunShadowMap,yA),ie.state.directionalShadowMap.length>0&&_t.setValue(sA,"directionalShadowMap",ie.state.directionalShadowMap,yA),ie.state.spotShadowMap.length>0&&_t.setValue(sA,"spotShadowMap",ie.state.spotShadowMap,yA),ie.state.pointShadowMap.length>0&&_t.setValue(sA,"pointShadowMap",ie.state.pointShadowMap,yA)),wA.isSkinnedMesh){_t.setOptional(sA,wA,"bindMatrix"),_t.setOptional(sA,wA,"bindMatrixInverse");const ge=wA.skeleton;ge&&(ge.boneTexture===null&&ge.computeBoneTexture(),_t.setValue(sA,"boneTexture",ge.boneTexture,yA))}wA.isBatchedMesh&&(_t.setOptional(sA,wA,"batchingTexture"),_t.setValue(sA,"batchingTexture",wA._matricesTexture,yA),_t.setOptional(sA,wA,"batchingIdTexture"),_t.setValue(sA,"batchingIdTexture",wA._indirectTexture,yA),_t.setOptional(sA,wA,"batchingColorTexture"),wA._colorsTexture!==null&&_t.setValue(sA,"batchingColorTexture",wA._colorsTexture,yA));const tg=mA.morphAttributes;if((tg.position!==void 0||tg.normal!==void 0||tg.color!==void 0)&&CA.update(wA,mA,Mi),(bs||it.receiveShadow!==wA.receiveShadow)&&(it.receiveShadow=wA.receiveShadow,_t.setValue(sA,"receiveShadow",wA.receiveShadow)),(DA.isMeshStandardMaterial||DA.isMeshLambertMaterial||DA.isMeshPhongMaterial)&&DA.envMap===null&&EA.environment!==null&&(Ze.envMapIntensity.value=EA.environmentIntensity),Ze.dfgLUT!==void 0&&(Ze.dfgLUT.value=UU()),bs){if(_t.setValue(sA,"toneMappingExposure",Y.toneMappingExposure),it.needsLights&&Hp(Ze,oI),N&&DA.fog===!0&&OA.refreshFogUniforms(Ze,N),OA.refreshMaterialUniforms(Ze,DA,_,BA,D.state.transmissionRenderTarget[$.id]),it.needsLights&&it.lightProbeGrid){const ge=it.lightProbeGrid;Ze.probesSH.value=ge.texture,Ze.probesMin.value.copy(ge.boundingBox.min),Ze.probesMax.value.copy(ge.boundingBox.max),Ze.probesResolution.value.copy(ge.resolution)}qC.upload(sA,YQ(it),Ze,yA)}if(DA.isShaderMaterial&&DA.uniformsNeedUpdate===!0&&(qC.upload(sA,YQ(it),Ze,yA),DA.uniformsNeedUpdate=!1),DA.isSpriteMaterial&&_t.setValue(sA,"center",wA.center),_t.setValue(sA,"modelViewMatrix",wA.modelViewMatrix),_t.setValue(sA,"normalMatrix",wA.normalMatrix),_t.setValue(sA,"modelMatrix",wA.matrixWorld),DA.uniformsGroups!==void 0){const ge=DA.uniformsGroups;for(let eg=0,gI=ge.length;eg<gI;eg++){const TG=ge[eg];KA.update(TG,Mi),KA.bind(TG,Mi)}}return Mi}function Hp($,EA){$.ambientLightColor.needsUpdate=EA,$.lightProbe.needsUpdate=EA,$.sunLights.needsUpdate=EA,$.sunLightShadows.needsUpdate=EA,$.directionalLights.needsUpdate=EA,$.directionalLightShadows.needsUpdate=EA,$.pointLights.needsUpdate=EA,$.pointLightShadows.needsUpdate=EA,$.spotLights.needsUpdate=EA,$.spotLightShadows.needsUpdate=EA,$.rectAreaLights.needsUpdate=EA,$.hemisphereLights.needsUpdate=EA}function Op($){return $.isMeshLambertMaterial||$.isMeshToonMaterial||$.isMeshPhongMaterial||$.isMeshStandardMaterial||$.isShadowMaterial||$.isShaderMaterial&&$.lights===!0}this.getActiveCubeFace=function(){return X},this.getActiveMipmapLevel=function(){return v},this.getRenderTarget=function(){return k},this.setRenderTargetTextures=function($,EA,mA){const DA=cA.get($);DA.__autoAllocateDepthBuffer=$.resolveDepthBuffer===!1,DA.__autoAllocateDepthBuffer===!1&&(DA.__useRenderToTexture=!1),cA.get($.texture).__webglTexture=EA,cA.get($.depthTexture).__webglTexture=DA.__autoAllocateDepthBuffer?void 0:mA,DA.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function($,EA){const mA=cA.get($);mA.__webglFramebuffer=EA,mA.__useDefaultFramebuffer=EA===void 0},this.setRenderTarget=function($,EA=0,mA=0){k=$,X=EA,v=mA;let DA=null,wA=!1,N=!1;if($){const AA=cA.get($);if(AA.__useDefaultFramebuffer!==void 0){Z.bindFramebuffer(sA.FRAMEBUFFER,AA.__webglFramebuffer),H.copy($.viewport),eA.copy($.scissor),nA=$.scissorTest,Z.viewport(H),Z.scissor(eA),Z.setScissorTest(nA),K=-1;return}else if(AA.__webglFramebuffer===void 0)yA.setupRenderTarget($);else if(AA.__hasExternalTextures)yA.rebindTextures($,cA.get($.texture).__webglTexture,cA.get($.depthTexture).__webglTexture);else if($.depthBuffer){const FA=$.depthTexture;if(AA.__boundDepthTexture!==FA){if(FA!==null&&cA.has(FA)&&($.width!==FA.image.width||$.height!==FA.image.height))throw new Error("THREE.WebGLRenderer: Attached DepthTexture is initialized to the incorrect size.");yA.setupDepthRenderbuffer($)}}const aA=$.texture;(aA.isData3DTexture||aA.isDataArrayTexture||aA.isCompressedArrayTexture)&&(N=!0);const pA=cA.get($).__webglFramebuffer;$.isWebGLCubeRenderTarget?(Array.isArray(pA[EA])?DA=pA[EA][mA]:DA=pA[EA],wA=!0):$.samples>0&&yA.useMultisampledRTT($)===!1?DA=cA.get($).__webglMultisampledFramebuffer:Array.isArray(pA)?DA=pA[mA]:DA=pA,H.copy($.viewport),eA.copy($.scissor),nA=$.scissorTest}else H.copy(U).multiplyScalar(_).floor(),eA.copy(J).multiplyScalar(_).floor(),nA=W;if(mA!==0&&(DA=T),Z.bindFramebuffer(sA.FRAMEBUFFER,DA)&&Z.drawBuffers($,DA),Z.viewport(H),Z.scissor(eA),Z.setScissorTest(nA),wA){const AA=cA.get($.texture);sA.framebufferTexture2D(sA.FRAMEBUFFER,sA.COLOR_ATTACHMENT0,sA.TEXTURE_CUBE_MAP_POSITIVE_X+EA,AA.__webglTexture,mA)}else if(N){const AA=EA;for(let aA=0;aA<$.textures.length;aA++){const pA=cA.get($.textures[aA]);sA.framebufferTextureLayer(sA.FRAMEBUFFER,sA.COLOR_ATTACHMENT0+aA,pA.__webglTexture,mA,AA)}}else if($!==null&&mA!==0){const AA=cA.get($.texture);sA.framebufferTexture2D(sA.FRAMEBUFFER,sA.COLOR_ATTACHMENT0,sA.TEXTURE_2D,AA.__webglTexture,mA)}K=-1};function bQ($){const EA=cA.get($);return(EA.__readFormat!==$.format||EA.__readType!==$.type)&&(EA.__readFormat=$.format,EA.__readType=$.type,EA.__formatReadable=iA.textureFormatReadable($.format),EA.__typeReadable=iA.textureTypeReadable($.type)),EA}this.readRenderTargetPixels=function($,EA,mA,DA,wA,N,V,AA=0){if(!($&&$.isWebGLRenderTarget)){gt("WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let aA=cA.get($).__webglFramebuffer;if($.isWebGLCubeRenderTarget&&V!==void 0&&(aA=aA[V]),aA){Z.bindFramebuffer(sA.FRAMEBUFFER,aA);try{const pA=$.textures[AA],FA=pA.format,UA=pA.type;$.textures.length>1&&sA.readBuffer(sA.COLOR_ATTACHMENT0+AA);const WA=bQ(pA);if(WA.__formatReadable===!1){gt("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(WA.__typeReadable===!1){gt("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}EA>=0&&EA<=$.width-DA&&mA>=0&&mA<=$.height-wA&&sA.readPixels(EA,mA,DA,wA,zA.convert(FA),zA.convert(UA),N)}finally{const pA=k!==null?cA.get(k).__webglFramebuffer:null;Z.bindFramebuffer(sA.FRAMEBUFFER,pA)}}},this.readRenderTargetPixelsAsync=async function($,EA,mA,DA,wA,N,V,AA=0){if(!($&&$.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let aA=cA.get($).__webglFramebuffer;if($.isWebGLCubeRenderTarget&&V!==void 0&&(aA=aA[V]),aA)if(EA>=0&&EA<=$.width-DA&&mA>=0&&mA<=$.height-wA){Z.bindFramebuffer(sA.FRAMEBUFFER,aA);const pA=$.textures[AA],FA=pA.format,UA=pA.type;$.textures.length>1&&sA.readBuffer(sA.COLOR_ATTACHMENT0+AA);const WA=bQ(pA);if(WA.__formatReadable===!1)throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(WA.__typeReadable===!1)throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const at=sA.createBuffer();sA.bindBuffer(sA.PIXEL_PACK_BUFFER,at),sA.bufferData(sA.PIXEL_PACK_BUFFER,N.byteLength,sA.STREAM_READ),sA.readPixels(EA,mA,DA,wA,zA.convert(FA),zA.convert(UA),0),sA.bindBuffer(sA.PIXEL_PACK_BUFFER,null);const St=k!==null?cA.get(k).__webglFramebuffer:null;Z.bindFramebuffer(sA.FRAMEBUFFER,St);const Gt=sA.fenceSync(sA.SYNC_GPU_COMMANDS_COMPLETE,0);return sA.flush(),await TT(sA,Gt,4),sA.bindBuffer(sA.PIXEL_PACK_BUFFER,at),sA.getBufferSubData(sA.PIXEL_PACK_BUFFER,0,N),sA.bindBuffer(sA.PIXEL_PACK_BUFFER,null),sA.deleteBuffer(at),sA.deleteSync(Gt),N}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function($,EA=null,mA=0){const DA=Math.pow(2,-mA),wA=Math.floor($.image.width*DA),N=Math.floor($.image.height*DA),V=EA!==null?EA.x:0,AA=EA!==null?EA.y:0;yA.setTexture2D($,0),sA.copyTexSubImage2D(sA.TEXTURE_2D,mA,0,0,V,AA,wA,N),Z.unbindTexture()},this.copyTextureToTexture=function($,EA,mA=null,DA=null,wA=0,N=0){let V,AA,aA,pA,FA,UA,WA,at,St;const Gt=$.isCompressedTexture?$.mipmaps[N]:$.image;if(mA!==null)V=mA.max.x-mA.min.x,AA=mA.max.y-mA.min.y,aA=mA.isBox3?mA.max.z-mA.min.z:1,pA=mA.min.x,FA=mA.min.y,UA=mA.isBox3?mA.min.z:0;else{const Ze=Math.pow(2,-wA);V=Math.floor(Gt.width*Ze),AA=Math.floor(Gt.height*Ze),$.isDataArrayTexture?aA=Gt.depth:$.isData3DTexture?aA=Math.floor(Gt.depth*Ze):aA=1,pA=0,FA=0,UA=0}DA!==null?(WA=DA.x,at=DA.y,St=DA.z):(WA=0,at=0,St=0);const mt=zA.convert(EA.format),oe=zA.convert(EA.type);let it;EA.isData3DTexture?(yA.setTexture3D(EA,0),it=sA.TEXTURE_3D):EA.isDataArrayTexture||EA.isCompressedArrayTexture?(yA.setTexture2DArray(EA,0),it=sA.TEXTURE_2D_ARRAY):(yA.setTexture2D(EA,0),it=sA.TEXTURE_2D),Z.activeTexture(sA.TEXTURE0),Z.pixelStorei(sA.UNPACK_FLIP_Y_WEBGL,EA.flipY),Z.pixelStorei(sA.UNPACK_PREMULTIPLY_ALPHA_WEBGL,EA.premultiplyAlpha),Z.pixelStorei(sA.UNPACK_ALIGNMENT,EA.unpackAlignment);const ie=Z.getParameter(sA.UNPACK_ROW_LENGTH),dt=Z.getParameter(sA.UNPACK_IMAGE_HEIGHT),Mi=Z.getParameter(sA.UNPACK_SKIP_PIXELS),ii=Z.getParameter(sA.UNPACK_SKIP_ROWS),bs=Z.getParameter(sA.UNPACK_SKIP_IMAGES);Z.pixelStorei(sA.UNPACK_ROW_LENGTH,Gt.width),Z.pixelStorei(sA.UNPACK_IMAGE_HEIGHT,Gt.height),Z.pixelStorei(sA.UNPACK_SKIP_PIXELS,pA),Z.pixelStorei(sA.UNPACK_SKIP_ROWS,FA),Z.pixelStorei(sA.UNPACK_SKIP_IMAGES,UA);const oI=$.isDataArrayTexture||$.isData3DTexture,_t=EA.isDataArrayTexture||EA.isData3DTexture;if($.isDepthTexture){const Ze=cA.get($),tg=cA.get(EA),ge=cA.get(Ze.__renderTarget),eg=cA.get(tg.__renderTarget);Z.bindFramebuffer(sA.READ_FRAMEBUFFER,ge.__webglFramebuffer),Z.bindFramebuffer(sA.DRAW_FRAMEBUFFER,eg.__webglFramebuffer);for(let gI=0;gI<aA;gI++)oI&&(sA.framebufferTextureLayer(sA.READ_FRAMEBUFFER,sA.COLOR_ATTACHMENT0,cA.get($).__webglTexture,wA,UA+gI),sA.framebufferTextureLayer(sA.DRAW_FRAMEBUFFER,sA.COLOR_ATTACHMENT0,cA.get(EA).__webglTexture,N,St+gI)),sA.blitFramebuffer(pA,FA,V,AA,WA,at,V,AA,sA.DEPTH_BUFFER_BIT,sA.NEAREST);Z.bindFramebuffer(sA.READ_FRAMEBUFFER,null),Z.bindFramebuffer(sA.DRAW_FRAMEBUFFER,null)}else if(wA!==0||$.isRenderTargetTexture||cA.has($)){const Ze=cA.get($),tg=cA.get(EA);Z.bindFramebuffer(sA.READ_FRAMEBUFFER,F),Z.bindFramebuffer(sA.DRAW_FRAMEBUFFER,j);for(let ge=0;ge<aA;ge++)oI?sA.framebufferTextureLayer(sA.READ_FRAMEBUFFER,sA.COLOR_ATTACHMENT0,Ze.__webglTexture,wA,UA+ge):sA.framebufferTexture2D(sA.READ_FRAMEBUFFER,sA.COLOR_ATTACHMENT0,sA.TEXTURE_2D,Ze.__webglTexture,wA),_t?sA.framebufferTextureLayer(sA.DRAW_FRAMEBUFFER,sA.COLOR_ATTACHMENT0,tg.__webglTexture,N,St+ge):sA.framebufferTexture2D(sA.DRAW_FRAMEBUFFER,sA.COLOR_ATTACHMENT0,sA.TEXTURE_2D,tg.__webglTexture,N),wA!==0?sA.blitFramebuffer(pA,FA,V,AA,WA,at,V,AA,sA.COLOR_BUFFER_BIT,sA.NEAREST):_t?sA.copyTexSubImage3D(it,N,WA,at,St+ge,pA,FA,V,AA):sA.copyTexSubImage2D(it,N,WA,at,pA,FA,V,AA);Z.bindFramebuffer(sA.READ_FRAMEBUFFER,null),Z.bindFramebuffer(sA.DRAW_FRAMEBUFFER,null)}else _t?$.isDataTexture||$.isData3DTexture?sA.texSubImage3D(it,N,WA,at,St,V,AA,aA,mt,oe,Gt.data):EA.isCompressedArrayTexture?sA.compressedTexSubImage3D(it,N,WA,at,St,V,AA,aA,mt,Gt.data):sA.texSubImage3D(it,N,WA,at,St,V,AA,aA,mt,oe,Gt):$.isDataTexture?sA.texSubImage2D(sA.TEXTURE_2D,N,WA,at,V,AA,mt,oe,Gt.data):$.isCompressedTexture?sA.compressedTexSubImage2D(sA.TEXTURE_2D,N,WA,at,Gt.width,Gt.height,mt,Gt.data):sA.texSubImage2D(sA.TEXTURE_2D,N,WA,at,V,AA,mt,oe,Gt);Z.pixelStorei(sA.UNPACK_ROW_LENGTH,ie),Z.pixelStorei(sA.UNPACK_IMAGE_HEIGHT,dt),Z.pixelStorei(sA.UNPACK_SKIP_PIXELS,Mi),Z.pixelStorei(sA.UNPACK_SKIP_ROWS,ii),Z.pixelStorei(sA.UNPACK_SKIP_IMAGES,bs),N===0&&EA.generateMipmaps&&sA.generateMipmap(it),Z.unbindTexture()},this.initRenderTarget=function($){cA.get($).__webglFramebuffer===void 0&&yA.setupRenderTarget($)},this.initTexture=function($){$.isCubeTexture?yA.setTextureCube($,0):$.isData3DTexture?yA.setTexture3D($,0):$.isDataArrayTexture||$.isCompressedArrayTexture?yA.setTexture2DArray($,0):yA.setTexture2D($,0),Z.unbindTexture()},this.resetState=function(){X=0,v=0,k=null,Z.reset(),VA.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return ns}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(A){this._outputColorSpace=A;const t=this.getContext();t.drawingBufferColorSpace=ft._getDrawingBufferColorSpace(A),t.unpackColorSpace=ft._getUnpackColorSpace()}}const Cm=Object.freeze(Object.defineProperty({__proto__:null,ACESFilmicToneMapping:wa,AddEquation:is,AddOperation:DD,AdditiveAnimationBlendMode:OQ,AdditiveBlending:OB,AgXToneMapping:oh,AlphaFormat:xQ,AlwaysCompare:KD,AlwaysDepth:vB,AlwaysStencilFunc:YD,AmbientLight:hr,AnimationAction:uu,AnimationClip:lr,AnimationLoader:uj,AnimationMixer:I0,AnimationObjectGroup:vj,AnimationUtils:fj,ArcCurve:Sw,ArrayCamera:yu,ArrowHelper:dR,AttachedBindMode:UQ,Audio:pu,AudioAnalyser:Uj,AudioContext:o0,AudioListener:Rj,AudioLoader:Gj,AxesHelper:fR,BackSide:Ne,BasicDepthPacking:PD,BasicShadowMap:xG,BatchedMesh:ud,BezierInterpolant:Au,Bone:gC,BooleanKeyframeTrack:Dg,Box2:Fu,Box3:vA,Box3Helper:cR,BoxGeometry:zt,BoxHelper:ER,BufferAttribute:yt,BufferGeometry:et,BufferGeometryLoader:Cu,ByteType:XQ,Cache:rn,Camera:NC,CameraHelper:CR,CanvasTexture:mw,CapsuleGeometry:MC,CatmullRomCurve3:Kd,CineonToneMapping:sh,CircleGeometry:yC,ClampToEdgeWrapping:Gi,Clock:eR,Color:XA,ColorKeyframeTrack:vd,ColorManagement:ft,Compatibility:ST,CompressedArrayTexture:ww,CompressedCubeTexture:uw,CompressedTexture:sr,CompressedTextureLoader:mj,ConeGeometry:vI,ConstantAlphaFactor:MD,ConstantColorFactor:dD,Controls:Q0,CubeCamera:Mu,CubeDepthTexture:Pw,CubeReflectionMapping:en,CubeRefractionMapping:lo,CubeTexture:zI,CubeTextureLoader:Pj,CubeUVReflectionMapping:ma,CubicBezierCurve:jd,CubicBezierCurve3:Ww,CubicInterpolant:qw,CullFaceBack:KQ,CullFaceFront:oD,CullFaceFrontBack:JG,CullFaceNone:nD,Curve:Ks,CurvePath:Jd,CustomBlending:LB,CustomToneMapping:nh,CylinderGeometry:Je,Cylindrical:iR,Data3DTexture:bI,DataArrayTexture:Th,DataTexture:wi,DataTextureLoader:nu,DataUtils:jI,DecrementStencilOp:nT,DecrementWrapStencilOp:gT,DefaultLoadingManager:qd,DepthFormat:sn,DepthStencilFormat:nn,DepthTexture:wo,DetachedBindMode:wD,DirectionalLight:Zs,DirectionalLightHelper:hR,DiscreteInterpolant:$w,DodecahedronGeometry:pC,DoubleSide:Tt,DstAlphaFactor:aI,DstColorFactor:rI,DynamicCopyUsage:pT,DynamicDrawUsage:cT,DynamicReadUsage:fT,EdgesGeometry:Fd,EllipseCurve:mC,EqualCompare:WD,EqualDepth:qB,EqualStencilFunc:lT,EquirectangularReflectionMapping:ua,EquirectangularRefractionMapping:lI,Euler:Le,EventDispatcher:os,ExternalTexture:Sd,ExtrudeGeometry:or,FileLoader:mi,Float16BufferAttribute:dK,Float32BufferAttribute:$A,FloatType:fe,Fog:Xh,FogExp2:Uh,FramebufferTexture:ZK,FrontSide:es,Frustum:Do,FrustumArray:IC,GLBufferAttribute:tR,GLSL1:wT,GLSL3:zQ,GreaterCompare:GD,GreaterDepth:Ah,GreaterEqualCompare:Wh,GreaterEqualDepth:$B,GreaterEqualStencilFunc:ET,GreaterStencilFunc:hT,GridHelper:lR,Group:Ot,HTMLTexture:NK,HalfFloatType:qt,HemisphereLight:ou,HemisphereLightHelper:IR,IcosahedronGeometry:FC,ImageBitmapLoader:Qu,ImageLoader:al,ImageUtils:kD,IncrementStencilOp:sT,IncrementWrapStencilOp:oT,InstancedBufferAttribute:Un,InstancedBufferGeometry:i0,InstancedInterleavedBuffer:JC,InstancedMesh:ct,Int16BufferAttribute:cK,Int32BufferAttribute:QK,Int8BufferAttribute:hK,IntType:ah,InterleavedBuffer:va,InterleavedBufferAttribute:ji,Interpolant:pg,InterpolateBezier:HQ,InterpolateDiscrete:Ka,InterpolateLinear:ja,InterpolateSmooth:Ph,InterpolationSamplingMode:PT,InterpolationSamplingType:mT,InvertStencilOp:aT,KeepStencilOp:Fh,KeyframeTrack:fs,LOD:sw,LatheGeometry:bC,Layers:jh,LessCompare:bD,LessDepth:_B,LessEqualCompare:bh,LessEqualDepth:Da,LessEqualStencilFunc:BT,LessStencilFunc:IT,Light:Vn,LightProbe:Bu,LightShadow:jC,Line:he,Line3:vi,LineBasicMaterial:se,LineCurve:Rd,LineCurve3:Zd,LineDashedMaterial:zw,LineLoop:er,LineSegments:Bi,LinearFilter:Yt,LinearInterpolant:zd,LinearMipMapLinearFilter:LG,LinearMipMapNearestFilter:OG,LinearMipmapLinearFilter:Oi,LinearMipmapNearestFilter:Sa,LinearSRGBColorSpace:si,LinearToneMapping:eh,LinearTransfer:PI,Loader:hi,LoaderUtils:Ns,LoadingManager:_d,LoopOnce:kQ,LoopPingPong:uD,LoopRepeat:VQ,MOUSE:ig,Material:Ie,MaterialBlending:kG,MaterialLoader:UC,MathUtils:rt,Matrix2:h0,Matrix3:ht,Matrix4:RA,MaxEquation:lD,Mesh:bA,MeshBasicMaterial:Kt,MeshDepthMaterial:Hd,MeshDistanceMaterial:Od,MeshLambertMaterial:Ow,MeshMatcapMaterial:Lw,MeshNormalMaterial:KC,MeshPhongMaterial:Vw,MeshPhysicalMaterial:ds,MeshStandardMaterial:mo,MeshToonMaterial:Hw,MinEquation:ID,MirroredRepeatWrapping:Pa,MixOperation:pD,MultiplyBlending:RQ,MultiplyOperation:II,NearestFilter:xt,NearestMipMapLinearFilter:HG,NearestMipMapNearestFilter:VG,NearestMipmapLinearFilter:ng,NearestMipmapNearestFilter:BI,NeutralToneMapping:sg,NeverCompare:FD,NeverDepth:zB,NeverStencilFunc:rT,NoBlending:ae,NoColorSpace:cs,NoNormalPacking:$G,NoToneMapping:li,NormalAnimationBlendMode:Sh,NormalBlending:pa,NormalGAPacking:tT,NormalRGPacking:AT,NotEqualCompare:TD,NotEqualDepth:th,NotEqualStencilFunc:CT,NumberKeyframeTrack:rr,Object3D:Et,ObjectLoader:bj,ObjectSpaceNormalMap:SD,OctahedronGeometry:Xn,OneFactor:BD,OneMinusConstantAlphaFactor:yD,OneMinusConstantColorFactor:fD,OneMinusDstAlphaFactor:ED,OneMinusDstColorFactor:cD,OneMinusSrcAlphaFactor:NQ,OneMinusSrcColorFactor:CD,OrthographicCamera:ze,PCFShadowMap:Ma,PCFSoftShadowMap:gD,PMREMGenerator:ll,Path:$I,PerspectiveCamera:Ce,Plane:pt,PlaneGeometry:gn,PlaneHelper:QR,PointLight:t0,PointLightHelper:aR,Points:ir,PointsMaterial:QC,PolarGridHelper:BR,PolyhedronGeometry:uo,PositionalAudio:Nj,PropertyBinding:jt,PropertyMixer:wu,QuadraticBezierCurve:Nd,QuadraticBezierCurve3:Ud,Quaternion:wt,QuaternionKeyframeTrack:Ir,QuaternionLinearInterpolant:iu,R11_EAC_Format:fI,RED_GREEN_RGTC2_Format:Ta,RED_RGTC1_Format:DI,REVISION:fa,RG11_EAC_Format:Ga,RGBADepthPacking:vG,RGBAFormat:re,RGBAIntegerFormat:Bh,RGBA_ASTC_10x10_Format:Dh,RGBA_ASTC_10x5_Format:Mh,RGBA_ASTC_10x6_Format:yh,RGBA_ASTC_10x8_Format:ph,RGBA_ASTC_12x10_Format:wh,RGBA_ASTC_12x12_Format:uh,RGBA_ASTC_4x4_Format:co,RGBA_ASTC_5x4_Format:Ch,RGBA_ASTC_5x5_Format:Eh,RGBA_ASTC_6x5_Format:ch,RGBA_ASTC_6x6_Format:ag,RGBA_ASTC_8x5_Format:Qh,RGBA_ASTC_8x6_Format:dh,RGBA_ASTC_8x8_Format:fh,RGBA_BPTC_Format:rg,RGBA_ETC2_EAC_Format:Wa,RGBA_PVRTC_2BPPV1_Format:Fa,RGBA_PVRTC_4BPPV1_Format:gg,RGBA_S3TC_DXT1_Format:Co,RGBA_S3TC_DXT3_Format:cI,RGBA_S3TC_DXT5_Format:Eo,RGBDepthPacking:_G,RGBFormat:Ya,RGBIntegerFormat:zG,RGB_BPTC_SIGNED_Format:mh,RGB_BPTC_UNSIGNED_Format:pI,RGB_ETC1_Format:dI,RGB_ETC2_Format:ba,RGB_PVRTC_2BPPV1_Format:hh,RGB_PVRTC_4BPPV1_Format:QI,RGB_S3TC_DXT1_Format:og,RGDepthPacking:qG,RGFormat:ss,RGIntegerFormat:lh,RawShaderMaterial:TC,Ray:Nn,Raycaster:De,RectAreaLight:lu,RedFormat:on,RedIntegerFormat:EI,ReinhardToneMapping:ih,RenderObjectRefreshType:YT,RenderTarget:td,RenderTarget3D:qj,RepeatWrapping:Ue,ReplaceStencilOp:iT,ReverseSubtractEquation:rD,RingGeometry:gr,SIGNED_R11_EAC_Format:MI,SIGNED_RED_GREEN_RGTC2_Format:uI,SIGNED_RED_RGTC1_Format:wI,SIGNED_RG11_EAC_Format:yI,SRGBColorSpace:Rt,SRGBTransfer:Xt,Scene:GI,ShaderChunk:ut,ShaderLib:Zi,ShaderMaterial:$t,ShadowMaterial:Jw,Shape:Mg,ShapeGeometry:sl,ShapePath:MR,ShapeUtils:js,ShortType:JQ,Skeleton:kI,SkeletonHelper:gR,SkinnedMesh:pd,Source:AK,Sphere:be,SphereGeometry:an,Spherical:Su,SphericalHarmonics3:e0,SplineCurve:Xd,SpotLight:A0,SpotLightHelper:oR,Sprite:JI,SpriteMaterial:Hh,SrcAlphaFactor:ZQ,SrcAlphaSaturateFactor:QD,SrcColorFactor:hD,StaticCopyUsage:yT,StaticDrawUsage:Gh,StaticReadUsage:dT,StereoCamera:Tj,StreamCopyUsage:DT,StreamDrawUsage:QT,StreamReadUsage:MT,StringKeyframeTrack:wg,SubtractEquation:aD,SubtractiveBlending:jQ,TOUCH:XG,TangentSpaceNormalMap:Yn,TetrahedronGeometry:WC,Texture:Ft,TextureLoader:kn,TextureSource:Wn,TextureUtils:uR,Timer:rl,TimestampQuery:uT,TorusGeometry:Jn,TorusKnotGeometry:GC,Triangle:Lt,TriangleFanDrawMode:Yh,TriangleStripDrawMode:LQ,TrianglesDrawMode:mD,TubeGeometry:nl,UVMapping:gh,Uint16BufferAttribute:Bd,Uint32BufferAttribute:hd,Uint8BufferAttribute:CK,Uint8ClampedBufferAttribute:EK,Uniform:l0,UniformsGroup:AR,UniformsLib:LA,UniformsUtils:oi,UnsignedByteType:Bt,UnsignedInt101111Type:CI,UnsignedInt248Type:ho,UnsignedInt5999Type:hI,UnsignedIntType:Es,UnsignedShort4444Type:rh,UnsignedShort5551Type:Ih,UnsignedShortType:Bo,VSMShadowMap:ya,Vector2:MA,Vector3:S,Vector4:Ct,VectorKeyframeTrack:gl,VideoFrameTexture:RK,VideoTexture:Dw,WebGL3DRenderTarget:iK,WebGLArrayRenderTarget:eK,WebGLCoordinateSystem:ns,WebGLCubeRenderTarget:D0,WebGLRenderTarget:pe,WebGLRenderer:AE,WebGLUtils:Bm,WebGPUCoordinateSystem:Bg,WebXRController:Zh,WireframeGeometry:Vd,WrapAroundEnding:mI,ZeroCurvatureEnding:Ig,ZeroFactor:Io,ZeroSlopeEnding:lg,ZeroStencilOp:eT,createCanvasElement:RD,error:gt,getConsoleFunction:GT,log:YI,setConsoleFunction:WT,warn:_A,warnOnce:Fn},Symbol.toStringTag,{value:"Module"}));class XU{engine;scene;constructor(A){this.engine=A,this.scene=new GI;let t=new Ot;t.name="groupEdge",this.scene.add(t)}}var yr=Object.freeze({Linear:Object.freeze({None:function(s){return s},In:function(s){return s},Out:function(s){return s},InOut:function(s){return s}}),Quadratic:Object.freeze({In:function(s){return s*s},Out:function(s){return s*(2-s)},InOut:function(s){return(s*=2)<1?.5*s*s:-.5*(--s*(s-2)-1)}}),Cubic:Object.freeze({In:function(s){return s*s*s},Out:function(s){return--s*s*s+1},InOut:function(s){return(s*=2)<1?.5*s*s*s:.5*((s-=2)*s*s+2)}}),Quartic:Object.freeze({In:function(s){return s*s*s*s},Out:function(s){return 1- --s*s*s*s},InOut:function(s){return(s*=2)<1?.5*s*s*s*s:-.5*((s-=2)*s*s*s-2)}}),Quintic:Object.freeze({In:function(s){return s*s*s*s*s},Out:function(s){return--s*s*s*s*s+1},InOut:function(s){return(s*=2)<1?.5*s*s*s*s*s:.5*((s-=2)*s*s*s*s+2)}}),Sinusoidal:Object.freeze({In:function(s){return 1-Math.sin((1-s)*Math.PI/2)},Out:function(s){return Math.sin(s*Math.PI/2)},InOut:function(s){return .5*(1-Math.sin(Math.PI*(.5-s)))}}),Exponential:Object.freeze({In:function(s){return s===0?0:Math.pow(1024,s-1)},Out:function(s){return s===1?1:1-Math.pow(2,-10*s)},InOut:function(s){return s===0?0:s===1?1:(s*=2)<1?.5*Math.pow(1024,s-1):.5*(-Math.pow(2,-10*(s-1))+2)}}),Circular:Object.freeze({In:function(s){return 1-Math.sqrt(1-s*s)},Out:function(s){return Math.sqrt(1- --s*s)},InOut:function(s){return(s*=2)<1?-.5*(Math.sqrt(1-s*s)-1):.5*(Math.sqrt(1-(s-=2)*s)+1)}}),Elastic:Object.freeze({In:function(s){return s===0?0:s===1?1:-Math.pow(2,10*(s-1))*Math.sin((s-1.1)*5*Math.PI)},Out:function(s){return s===0?0:s===1?1:Math.pow(2,-10*s)*Math.sin((s-.1)*5*Math.PI)+1},InOut:function(s){return s===0?0:s===1?1:(s*=2,s<1?-.5*Math.pow(2,10*(s-1))*Math.sin((s-1.1)*5*Math.PI):.5*Math.pow(2,-10*(s-1))*Math.sin((s-1.1)*5*Math.PI)+1)}}),Back:Object.freeze({In:function(s){var A=1.70158;return s===1?1:s*s*((A+1)*s-A)},Out:function(s){var A=1.70158;return s===0?0:--s*s*((A+1)*s+A)+1},InOut:function(s){var A=2.5949095;return(s*=2)<1?.5*(s*s*((A+1)*s-A)):.5*((s-=2)*s*((A+1)*s+A)+2)}}),Bounce:Object.freeze({In:function(s){return 1-yr.Bounce.Out(1-s)},Out:function(s){return s<1/2.75?7.5625*s*s:s<2/2.75?7.5625*(s-=1.5/2.75)*s+.75:s<2.5/2.75?7.5625*(s-=2.25/2.75)*s+.9375:7.5625*(s-=2.625/2.75)*s+.984375},InOut:function(s){return s<.5?yr.Bounce.In(s*2)*.5:yr.Bounce.Out(s*2-1)*.5+.5}}),generatePow:function(s){return s===void 0&&(s=4),s=s<Number.EPSILON?Number.EPSILON:s,s=s>1e4?1e4:s,{In:function(A){return Math.pow(A,s)},Out:function(A){return 1-Math.pow(1-A,s)},InOut:function(A){return A<.5?Math.pow(A*2,s)/2:(1-Math.pow(2-A*2,s))/2+.5}}}}),Cl=function(){return performance.now()},JU=(function(){function s(){this._tweens={},this._tweensAddedDuringUpdate={}}return s.prototype.getAll=function(){var A=this;return Object.keys(this._tweens).map(function(t){return A._tweens[t]})},s.prototype.removeAll=function(){this._tweens={}},s.prototype.add=function(A){this._tweens[A.getId()]=A,this._tweensAddedDuringUpdate[A.getId()]=A},s.prototype.remove=function(A){delete this._tweens[A.getId()],delete this._tweensAddedDuringUpdate[A.getId()]},s.prototype.update=function(A,t){A===void 0&&(A=Cl()),t===void 0&&(t=!1);var e=Object.keys(this._tweens);if(e.length===0)return!1;for(;e.length>0;){this._tweensAddedDuringUpdate={};for(var i=0;i<e.length;i++){var n=this._tweens[e[i]],o=!t;n&&n.update(A,o)===!1&&!t&&delete this._tweens[e[i]]}e=Object.keys(this._tweensAddedDuringUpdate)}return!0},s})(),S0={Linear:function(s,A){var t=s.length-1,e=t*A,i=Math.floor(e),n=S0.Utils.Linear;return A<0?n(s[0],s[1],e):A>1?n(s[t],s[t-1],t-e):n(s[i],s[i+1>t?t:i+1],e-i)},Utils:{Linear:function(s,A,t){return(A-s)*t+s}}},Em=(function(){function s(){}return s.nextId=function(){return s._nextId++},s._nextId=0,s})(),Y0=new JU,xU=(function(){function s(A,t){t===void 0&&(t=Y0),this._object=A,this._group=t,this._isPaused=!1,this._pauseStart=0,this._valuesStart={},this._valuesEnd={},this._valuesStartRepeat={},this._duration=1e3,this._isDynamic=!1,this._initialRepeat=0,this._repeat=0,this._yoyo=!1,this._isPlaying=!1,this._reversed=!1,this._delayTime=0,this._startTime=0,this._easingFunction=yr.Linear.None,this._interpolationFunction=S0.Linear,this._chainedTweens=[],this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._id=Em.nextId(),this._isChainStopped=!1,this._propertiesAreSetUp=!1,this._goToEnd=!1}return s.prototype.getId=function(){return this._id},s.prototype.isPlaying=function(){return this._isPlaying},s.prototype.isPaused=function(){return this._isPaused},s.prototype.getDuration=function(){return this._duration},s.prototype.to=function(A,t){if(t===void 0&&(t=1e3),this._isPlaying)throw new Error("Can not call Tween.to() while Tween is already started or paused. Stop the Tween first.");return this._valuesEnd=A,this._propertiesAreSetUp=!1,this._duration=t<0?0:t,this},s.prototype.duration=function(A){return A===void 0&&(A=1e3),this._duration=A<0?0:A,this},s.prototype.dynamic=function(A){return A===void 0&&(A=!1),this._isDynamic=A,this},s.prototype.start=function(A,t){if(A===void 0&&(A=Cl()),t===void 0&&(t=!1),this._isPlaying)return this;if(this._group&&this._group.add(this),this._repeat=this._initialRepeat,this._reversed){this._reversed=!1;for(var e in this._valuesStartRepeat)this._swapEndStartRepeatValues(e),this._valuesStart[e]=this._valuesStartRepeat[e]}if(this._isPlaying=!0,this._isPaused=!1,this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._isChainStopped=!1,this._startTime=A,this._startTime+=this._delayTime,!this._propertiesAreSetUp||t){if(this._propertiesAreSetUp=!0,!this._isDynamic){var i={};for(var n in this._valuesEnd)i[n]=this._valuesEnd[n];this._valuesEnd=i}this._setupProperties(this._object,this._valuesStart,this._valuesEnd,this._valuesStartRepeat,t)}return this},s.prototype.startFromCurrentValues=function(A){return this.start(A,!0)},s.prototype._setupProperties=function(A,t,e,i,n){for(var o in e){var g=A[o],a=Array.isArray(g),r=a?"array":typeof g,I=!a&&Array.isArray(e[o]);if(!(r==="undefined"||r==="function")){if(I){var l=e[o];if(l.length===0)continue;for(var h=[g],B=0,E=l.length;B<E;B+=1){var c=this._handleRelativeValue(g,l[B]);if(isNaN(c)){I=!1,console.warn("Found invalid interpolation list. Skipping.");break}h.push(c)}I&&(e[o]=h)}if((r==="object"||a)&&g&&!I){t[o]=a?[]:{};var Q=g;for(var C in Q)t[o][C]=Q[C];i[o]=a?[]:{};var l=e[o];if(!this._isDynamic){var d={};for(var C in l)d[C]=l[C];e[o]=l=d}this._setupProperties(Q,t[o],l,i[o],n)}else(typeof t[o]>"u"||n)&&(t[o]=g),a||(t[o]*=1),I?i[o]=e[o].slice().reverse():i[o]=t[o]||0}}},s.prototype.stop=function(){return this._isChainStopped||(this._isChainStopped=!0,this.stopChainedTweens()),this._isPlaying?(this._group&&this._group.remove(this),this._isPlaying=!1,this._isPaused=!1,this._onStopCallback&&this._onStopCallback(this._object),this):this},s.prototype.end=function(){return this._goToEnd=!0,this.update(1/0),this},s.prototype.pause=function(A){return A===void 0&&(A=Cl()),this._isPaused||!this._isPlaying?this:(this._isPaused=!0,this._pauseStart=A,this._group&&this._group.remove(this),this)},s.prototype.resume=function(A){return A===void 0&&(A=Cl()),!this._isPaused||!this._isPlaying?this:(this._isPaused=!1,this._startTime+=A-this._pauseStart,this._pauseStart=0,this._group&&this._group.add(this),this)},s.prototype.stopChainedTweens=function(){for(var A=0,t=this._chainedTweens.length;A<t;A++)this._chainedTweens[A].stop();return this},s.prototype.group=function(A){return A===void 0&&(A=Y0),this._group=A,this},s.prototype.delay=function(A){return A===void 0&&(A=0),this._delayTime=A,this},s.prototype.repeat=function(A){return A===void 0&&(A=0),this._initialRepeat=A,this._repeat=A,this},s.prototype.repeatDelay=function(A){return this._repeatDelayTime=A,this},s.prototype.yoyo=function(A){return A===void 0&&(A=!1),this._yoyo=A,this},s.prototype.easing=function(A){return A===void 0&&(A=yr.Linear.None),this._easingFunction=A,this},s.prototype.interpolation=function(A){return A===void 0&&(A=S0.Linear),this._interpolationFunction=A,this},s.prototype.chain=function(){for(var A=[],t=0;t<arguments.length;t++)A[t]=arguments[t];return this._chainedTweens=A,this},s.prototype.onStart=function(A){return this._onStartCallback=A,this},s.prototype.onEveryStart=function(A){return this._onEveryStartCallback=A,this},s.prototype.onUpdate=function(A){return this._onUpdateCallback=A,this},s.prototype.onRepeat=function(A){return this._onRepeatCallback=A,this},s.prototype.onComplete=function(A){return this._onCompleteCallback=A,this},s.prototype.onStop=function(A){return this._onStopCallback=A,this},s.prototype.update=function(A,t){var e=this,i;if(A===void 0&&(A=Cl()),t===void 0&&(t=!0),this._isPaused)return!0;var n,o=this._startTime+this._duration;if(!this._goToEnd&&!this._isPlaying){if(A>o)return!1;t&&this.start(A,!0)}if(this._goToEnd=!1,A<this._startTime)return!0;this._onStartCallbackFired===!1&&(this._onStartCallback&&this._onStartCallback(this._object),this._onStartCallbackFired=!0),this._onEveryStartCallbackFired===!1&&(this._onEveryStartCallback&&this._onEveryStartCallback(this._object),this._onEveryStartCallbackFired=!0);var g=A-this._startTime,a=this._duration+((i=this._repeatDelayTime)!==null&&i!==void 0?i:this._delayTime),r=this._duration+this._repeat*a,I=function(){if(e._duration===0||g>r)return 1;var Q=Math.trunc(g/a),C=g-Q*a,d=Math.min(C/e._duration,1);return d===0&&g===e._duration?1:d},l=I(),h=this._easingFunction(l);if(this._updateProperties(this._object,this._valuesStart,this._valuesEnd,h),this._onUpdateCallback&&this._onUpdateCallback(this._object,l),this._duration===0||g>=this._duration)if(this._repeat>0){var B=Math.min(Math.trunc((g-this._duration)/a)+1,this._repeat);isFinite(this._repeat)&&(this._repeat-=B);for(n in this._valuesStartRepeat)!this._yoyo&&typeof this._valuesEnd[n]=="string"&&(this._valuesStartRepeat[n]=this._valuesStartRepeat[n]+parseFloat(this._valuesEnd[n])),this._yoyo&&this._swapEndStartRepeatValues(n),this._valuesStart[n]=this._valuesStartRepeat[n];return this._yoyo&&(this._reversed=!this._reversed),this._startTime+=a*B,this._onRepeatCallback&&this._onRepeatCallback(this._object),this._onEveryStartCallbackFired=!1,!0}else{this._onCompleteCallback&&this._onCompleteCallback(this._object);for(var E=0,c=this._chainedTweens.length;E<c;E++)this._chainedTweens[E].start(this._startTime+this._duration,!1);return this._isPlaying=!1,!1}return!0},s.prototype._updateProperties=function(A,t,e,i){for(var n in e)if(t[n]!==void 0){var o=t[n]||0,g=e[n],a=Array.isArray(A[n]),r=Array.isArray(g),I=!a&&r;I?A[n]=this._interpolationFunction(g,i):typeof g=="object"&&g?this._updateProperties(A[n],o,g,i):(g=this._handleRelativeValue(o,g),typeof g=="number"&&(A[n]=o+(g-o)*i))}},s.prototype._handleRelativeValue=function(A,t){return typeof t!="string"?t:t.charAt(0)==="+"||t.charAt(0)==="-"?A+parseFloat(t):parseFloat(t)},s.prototype._swapEndStartRepeatValues=function(A){var t=this._valuesStartRepeat[A],e=this._valuesEnd[A];typeof e=="string"?this._valuesStartRepeat[A]=this._valuesStartRepeat[A]+parseFloat(e):this._valuesStartRepeat[A]=this._valuesEnd[A],this._valuesEnd[A]=t},s})();Em.nextId;var Bn=Y0;Bn.getAll.bind(Bn),Bn.removeAll.bind(Bn),Bn.add.bind(Bn),Bn.remove.bind(Bn),Bn.update.bind(Bn);var Wg={Easing:yr,Tween:xU};class gi{constructor(A,t,e){this.camera=A,this.renderer=t,this.scene=e,this.raycaster=new De}raycaster;worldToScreenNormalized(A){const t=A.clone();return t.project(this.camera),new MA(t.x,t.y)}worldToScreen(A){const t=new S;return t.copy(A).project(this.camera),t.x=t.x*this.renderer.domElement.clientWidth*.5,t.y=-t.y*this.renderer.domElement.clientHeight*.5,t.z=(t.z+1)*.5,t.x+=this.renderer.domElement.clientWidth*.5,t.y+=this.renderer.domElement.clientHeight*.5,new MA(t.x,t.y)}worldToScreenIfVisible(A){if(this.camera.updateMatrixWorld(!0),this.camera instanceof Ce&&A.clone().applyMatrix4(this.camera.matrixWorldInverse).z>=0)return null;const t=A.clone().project(this.camera);if(!Number.isFinite(t.x)||!Number.isFinite(t.y)||!Number.isFinite(t.z)||t.z<-1||t.z>1)return null;const e=this.renderer.domElement.clientWidth,i=this.renderer.domElement.clientHeight;return new MA(t.x*e*.5+e*.5,-t.y*i*.5+i*.5)}screenToNormalized(A,t){const e=this.renderer.domElement.clientWidth,i=this.renderer.domElement.clientHeight,n=A/e*2-1,o=-(t/i*2-1);return new MA(n,o)}screenToWorld(A,t,e){if(!this.scene&&!e)return console.warn("WorldToScreen: 需要提供 scene 或 objects 参数才能进行屏幕坐标转世界坐标"),null;const i=this.screenToNormalized(A,t);this.raycaster.setFromCamera(i,this.camera);const n=e||this.scene.children,o=this.raycaster.intersectObjects(n,!0);return o.length>0?o[0].point:null}screenToWorldWithDepth(A,t,e=0){const i=this.screenToNormalized(A,t);this.raycaster.setFromCamera(i,this.camera);const n=new S;return this.raycaster.ray.at(e,n),n}updateCamera(A){this.camera=A}updateRenderer(A){this.renderer=A}updateScene(A){this.scene=A}}var Yo=(s=>(s.PERSPECTIVE="perspective",s.ORTHOGRAPHIC="orthographic",s))(Yo||{});class Ee{static MIN_VISIBLE_HEIGHT=1e-4;static MIN_CAMERA_DISTANCE=1e-4;static CAMERA_ANIMATION_IDLE_EXEMPT_REASON="camera-module-animation";engine;perspectiveCamera;orthographicCamera;cameraAnimationFrame=null;constructor(A){this.engine=A,this.perspectiveCamera=new Ce(45,this.engine.container.clientWidth/this.engine.container.clientHeight,.1,1e3),this.perspectiveCamera.position.set(2,2,2),this.perspectiveCamera.lookAt(0,0,0);const t=50,e=this.engine.container.clientWidth/this.engine.container.clientHeight;this.orthographicCamera=new ze(t*e/-2,t*e/2,t/2,t/-2,.1,1e3)}exitDrawingPinView(){this.engine.drawingPin?.exitViewMode?.()}getCameraAspect(A){const t=A?.width??this.engine.container?.clientWidth??1,e=A?.height??this.engine.container?.clientHeight??1;return e>0?t/e:1}getPerspectiveVisibleHeight(A,t){const e=Math.max(A.position.distanceTo(t),Ee.MIN_CAMERA_DISTANCE),i=rt.degToRad(A.getEffectiveFOV()*.5);return Math.max(2*e*Math.tan(i),Ee.MIN_VISIBLE_HEIGHT)}getOrthographicVisibleHeight(A=this.orthographicCamera){return Math.max((A.top-A.bottom)/A.zoom,Ee.MIN_VISIBLE_HEIGHT)}setOrthographicVisibleHeight(A,t=this.orthographicCamera,e){const i=Math.max(A,Ee.MIN_VISIBLE_HEIGHT),n=Number.isFinite(e)&&e>0?e:this.getCameraAspect(),o=Math.max(t.zoom||1,Ee.MIN_CAMERA_DISTANCE),g=i*o*.5,a=g*n;t.left=-a,t.right=a,t.top=g,t.bottom=-g}getViewDirection(A,t,e){const i=new S().subVectors(A,t);return i.lengthSq()>Ee.MIN_CAMERA_DISTANCE?i.normalize():new S(0,0,1).applyQuaternion(e).normalize()}getStableCameraUp(A){const t=A.clone().normalize();if(t.lengthSq()<=Ee.MIN_CAMERA_DISTANCE)return new S(0,1,0);const e=[new S(0,1,0),new S(0,0,1),new S(1,0,0)];for(const i of e){const n=i.clone().sub(t.clone().multiplyScalar(i.dot(t)));if(n.lengthSq()>Ee.MIN_CAMERA_DISTANCE)return n.normalize()}return new S(0,1,0)}updateComposerCamera(){if(!this.engine.composerModule?.composer)return;const A=this.engine.camera,t=this.engine.composerModule.composer;if(t.passes)for(const e of t.passes)e.camera!==void 0&&(e.camera=A)}applySwitchedCamera(A,t){this.engine.camera=A,this.engine.scene.camera=A,this.engine.controls?.target&&this.engine.controls.target.copy(t),this.engine.controls&&(this.engine.controls.object=A),this.engine.controlModule.orbitControls.object=A,this.engine.controlModule.firstPersonControls.camera=A,this.engine.controlModule.firstPersonControls.object=A,this.engine.controlModule.firstPersonControls.syncRotationStateFromCamera?.(),this.engine.controlModule.firstPersonControls.syncSharedTargetFromCamera?.(),this.engine.controlModule.thirdPersonControls&&(this.engine.controlModule.thirdPersonControls.camera=A,this.engine.controlModule.thirdPersonControls.object=A,this.engine.controlModule.thirdPersonControls.syncRotationStateFromCamera?.(),this.engine.controlModule.thirdPersonControls.syncSharedTargetFromAvatar?.()),A.updateProjectionMatrix?.(),A.updateMatrixWorld(),this.updateComposerCamera(),this.engine.controls?.update&&this.engine.controls.update(),this.engine.worldToScreen=new gi(this.engine.camera,this.engine.renderer,this.engine.scene)}resolvePoseReferenceUp(A,t){if(A.referenceUp){const a=new S(A.referenceUp.x,A.referenceUp.y,A.referenceUp.z);if(a.lengthSq()>Ee.MIN_CAMERA_DISTANCE)return a.normalize()}if(!A.up||!t)return;const e=new S(A.up.x,A.up.y,A.up.z);if(e.lengthSq()<=Ee.MIN_CAMERA_DISTANCE)return;const i=t.clone().sub(this.engine.camera.position);if(i.lengthSq()<=Ee.MIN_CAMERA_DISTANCE)return;i.normalize(),e.normalize();const n=[new S(0,1,0),new S(0,-1,0),new S(0,0,1),new S(0,0,-1),new S(1,0,0),new S(-1,0,0)];let o,g=-1/0;for(const a of n){const r=a.clone().sub(i.clone().multiplyScalar(a.dot(i)));if(r.lengthSq()<=Ee.MIN_CAMERA_DISTANCE)continue;const I=r.normalize().dot(e);I>g&&(g=I,o=a.clone())}return o}syncControlsAfterPoseRestore(A,t,e,i){const n=this.engine.camera;if(!n)return;A&&this.engine.controls?.target&&this.engine.controls.target.copy(A);const o=this.engine.controlModule?.orbitControls;o&&(A&&typeof o.syncStateFromCamera=="function"?o.syncStateFromCamera(n,A,{origin:t??"target",referenceUp:e,viewRight:i}):(o.object=n,A&&o.target&&o.target.copy(A),t&&o.origin?o.origin.copy(t):A&&o.origin&&o.origin.copy(A),e&&o._referenceUp?.copy&&o._referenceUp.copy(e).normalize(),i&&o._viewRight?.copy&&o._viewRight.copy(i).normalize(),o._rotateVelocity?.set?.(0,0),o._panVelocity?.set?.(0,0),typeof o._zoomVelocity=="number"&&(o._zoomVelocity=0),o._lastPosition?.copy?.(n.position),o._lastTarget?.copy?.(o.target),o._lastUp?.copy?.(n.up),o._lastQuaternion?.copy?.(n.quaternion),o._lastZoom=n.zoom,o.saveState?.()));const g=this.engine.controlModule?.firstPersonControls;g&&(g.camera=n,g.object=n,g.syncRotationStateFromCamera?.(),g.syncSharedTargetFromCamera?.());const a=this.engine.controlModule?.thirdPersonControls;a&&(a.camera=n,a.object=n,a.syncRotationStateFromCamera?.(),a.syncSharedTargetFromAvatar?.()),this.engine.worldToScreen=new gi(this.engine.camera,this.engine.renderer,this.engine.scene)}inferTargetFromRestoredCamera(A){const t=new S;A.getWorldDirection(t),t.lengthSq()<=Ee.MIN_CAMERA_DISTANCE&&t.set(0,0,-1);const i=this.engine.controls?.target?.distanceTo?.(A.position),n=this.engine.octreeBox?.getBoundingBox?.(),o=n?.min&&n?.max?n.max.distanceTo(n.min)*.8:0;let g=10;return typeof i=="number"&&Number.isFinite(i)&&i>Ee.MIN_CAMERA_DISTANCE?g=i:o>Ee.MIN_CAMERA_DISTANCE&&(g=o),A.position.clone().add(t.normalize().multiplyScalar(g))}switchCurrentCamera(){this.engine.camera===this.perspectiveCamera?this.switchToOrthographicCamera():this.switchToPerspectiveCamera()}setPerspectiveFov(A,t){const e=this.perspectiveCamera,i=e.fov,n=Math.max(1,Math.min(120,A));if(t?.adjustDistance!==!1&&this.engine.camera===e&&this.engine.controls?.target){const g=this.engine.controls.target.clone(),a=e.position.clone(),r=a.distanceTo(g);if(r>1e-6){const I=rt.degToRad(i*.5),l=rt.degToRad(n*.5),h=Math.tan(I)/Math.tan(l),B=r*h,E=new S().subVectors(a,g).normalize();e.position.copy(g).add(E.multiplyScalar(B))}}e.fov=n,e.updateProjectionMatrix()}switchToPerspectiveCamera(){if(this.exitDrawingPinView(),!this.engine.controls)return;const A=this.engine.camera;if(!A)return;const t=A.position.clone(),e=this.engine.controls.target.clone(),i=A.quaternion.clone(),n=A.up.clone(),o=this.perspectiveCamera,g=this.getViewDirection(t,e,i),a=A instanceof ze?this.getOrthographicVisibleHeight(A):this.getPerspectiveVisibleHeight(A,e),r=rt.degToRad(o.getEffectiveFOV()*.5),I=Math.max(a/(2*Math.tan(r)),Ee.MIN_CAMERA_DISTANCE);o.near=A.near,o.far=A.far,o.aspect=this.getCameraAspect(),o.up.copy(n),o.position.copy(e).add(g.multiplyScalar(I)),o.lookAt(e),this.engine.camera=o,this.applySwitchedCamera(o,e)}switchToOrthographicCamera(){if(this.exitDrawingPinView(),!this.engine.controls)return;const A=this.engine.camera;if(!A)return;const t=A.position.clone(),e=this.engine.controls.target.clone(),i=A.quaternion.clone(),n=A.up.clone(),o=this.orthographicCamera,g=this.getViewDirection(t,e,i),a=A instanceof Ce?this.getPerspectiveVisibleHeight(A,e):this.getOrthographicVisibleHeight(A),r=rt.degToRad(A.getEffectiveFOV()*.5),I=Math.max(a/(2*Math.tan(r)),Ee.MIN_CAMERA_DISTANCE);o.near=A.near,o.far=A.far,o.zoom=1,this.setOrthographicVisibleHeight(a,o),o.up.copy(n);const l=this.engine.octreeBox?.getBoundingBox?.(),h=l?l.max.distanceTo(l.min)*.8:I,B=Math.max(h,Ee.MIN_CAMERA_DISTANCE);o.position.copy(e).add(g.clone().multiplyScalar(B)),o.quaternion.copy(i),this.engine.camera=o,this.applySwitchedCamera(o,e)}getCameraType(){return this.engine.camera===this.perspectiveCamera?"perspective":this.engine.camera===this.orthographicCamera?"orthographic":"perspective"}getCameraPose(){const A=this.engine.camera,t=this.getCameraType(),e={type:t,position:{x:A.position.x,y:A.position.y,z:A.position.z},rotation:{x:A.rotation.x,y:A.rotation.y,z:A.rotation.z},quaternion:{x:A.quaternion.x,y:A.quaternion.y,z:A.quaternion.z,w:A.quaternion.w},up:{x:A.up.x,y:A.up.y,z:A.up.z}};this.engine.controls?.target&&(e.target={x:this.engine.controls.target.x,y:this.engine.controls.target.y,z:this.engine.controls.target.z});const i=this.engine.controlModule?.orbitControls;return i?.origin&&(e.origin={x:i.origin.x,y:i.origin.y,z:i.origin.z}),i?._referenceUp&&(e.referenceUp={x:i._referenceUp.x,y:i._referenceUp.y,z:i._referenceUp.z}),i?._viewRight&&(e.viewRight={x:i._viewRight.x,y:i._viewRight.y,z:i._viewRight.z}),t==="orthographic"&&(e.zoom=A.zoom,e.orthographicHeight=this.getOrthographicVisibleHeight(A)),e}restoreCameraPose(A){this.exitDrawingPinView(),this.getCameraType()!==A.type&&(A.type==="perspective"?this.switchToPerspectiveCamera():this.switchToOrthographicCamera());const e=this.engine.camera;e.position.set(A.position.x,A.position.y,A.position.z),A.up&&e.up.set(A.up.x,A.up.y,A.up.z),A.quaternion?e.quaternion.set(A.quaternion.x,A.quaternion.y,A.quaternion.z,A.quaternion.w):A.rotation&&e.rotation.set(A.rotation.x,A.rotation.y,A.rotation.z);let i;A.target&&(i=new S(A.target.x,A.target.y,A.target.z));const n=A.origin?new S(A.origin.x,A.origin.y,A.origin.z):i?.clone();if(A.type==="orthographic"){const a=e;A.zoom!==void 0&&(a.zoom=A.zoom),A.orthographicHeight!==void 0&&this.setOrthographicVisibleHeight(A.orthographicHeight,a),a.updateProjectionMatrix()}e.updateMatrix(),e.updateMatrixWorld(!0),i||(i=this.inferTargetFromRestoredCamera(e));const o=this.resolvePoseReferenceUp(A,i),g=A.viewRight?new S(A.viewRight.x,A.viewRight.y,A.viewRight.z):void 0;this.syncControlsAfterPoseRestore(i,n,o,g)}setViewFromOriginAndDirection(A,t,e=null,i,n=0,o){this.exitDrawingPinView();const g=new S(t.x,t.y,t.z).normalize(),a=new S(A.x,A.y,A.z);let r=i??null;if(r==null||r<=0){const h=this.engine.octreeBox?.getBoundingBox?.();if(h&&h.min&&h.max){const B=new S().subVectors(h.max,h.min);r=Math.max(B.x,B.y,B.z)*1.2}else r=50}const I=a.clone().add(g.clone().negate().multiplyScalar(r));if(this.engine.camera){if(e||(e=this.getStableCameraUp(g)),n>0){this.animateCameraToTarget(I,a,e,n,o);return}this.applyCameraPose(I,a,e),o?.()}}rotateToTarget(A,t=0,e){const i=this.engine.camera;if(!i)return;const n=new S(A.x,A.y,A.z);if(i.position.distanceToSquared(n)<=Ee.MIN_CAMERA_DISTANCE){e?.();return}const o=i.position.clone(),g=i.up.lengthSq()>Ee.MIN_CAMERA_DISTANCE?i.up.clone().normalize():this.getStableCameraUp(n.clone().sub(o));if(t>0){this.animateCameraToTarget(o,n,g,t,e);return}this.applyCameraPose(o,n,g),e?.()}applyCameraPose(A,t,e){const i=this.engine.camera;i&&(i.position.copy(A),i.up.copy(e),this.engine.controls?.target&&this.engine.controls.target.copy(t),typeof this.engine.controls?.setScreenUp=="function"?this.engine.controls.setScreenUp(e):i.lookAt(t),this.engine.controls?.update&&this.engine.controls.update(),i.updateMatrix(),i.updateMatrixWorld(!0))}animateCameraToTarget(A,t,e,i,n){const o=this.engine.camera,g=this.engine.controls;if(!o||!g?.target){this.applyCameraPose(A,t,e),n?.();return}const a=()=>{this.engine.renderer&&(this.engine.renderer.interactionActive=!0),this.engine.setIdleFrameRateExempt?.(Ee.CAMERA_ANIMATION_IDLE_EXEMPT_REASON,!0),this.engine.events?.trigger?.("engine-busy"),this.engine.requestComposerRender?.()},r=()=>{this.engine.renderer&&(this.engine.renderer.interactionActive=!1),this.engine.setIdleFrameRateExempt?.(Ee.CAMERA_ANIMATION_IDLE_EXEMPT_REASON,!1),this.engine.events?.trigger?.("engine-free")};this.cameraAnimationFrame!=null&&(cancelAnimationFrame(this.cameraAnimationFrame),this.cameraAnimationFrame=null,r());const I=new Wg.Tween({px:o.position.x,py:o.position.y,pz:o.position.z,tx:g.target.x,ty:g.target.y,tz:g.target.z,ux:o.up.x,uy:o.up.y,uz:o.up.z}).to({px:A.x,py:A.y,pz:A.z,tx:t.x,ty:t.y,tz:t.z,ux:e.x,uy:e.y,uz:e.z},i);I.easing(Wg.Easing.Cubic.InOut),I.onUpdate(h=>{o.position.set(h.px,h.py,h.pz),g.target.set(h.tx,h.ty,h.tz),o.up.set(h.ux,h.uy,h.uz).normalize(),typeof g.setScreenUp=="function"?g.setScreenUp(o.up.clone()):o.lookAt(g.target),g.auto=!0,g.update?.(),o.updateMatrix(),o.updateMatrixWorld(!0),this.engine.requestComposerRender?.()}),I.onComplete(()=>{g.auto=!1,this.cameraAnimationFrame=null,this.applyCameraPose(A,t,e),this.engine.requestComposerRender?.(),r(),n?.()});const l=()=>{I.update()&&(this.cameraAnimationFrame=requestAnimationFrame(l))};a(),I.start(),l()}}class kU{engine;deviceType;constructor(A){this.engine=A,this.deviceType=this.detectDeviceType()}detectDeviceType(){const A=[/Android/i,/webOS/i,/iPhone/i,/iPad/i,/iPod/i,/BlackBerry/i,/Windows Phone/i,/Mobile/i],t=navigator.userAgent||globalThis.opera,e=A.some(I=>I.test(t)),i="ontouchstart"in globalThis||navigator.maxTouchPoints>0||navigator.msMaxTouchPoints>0,n=globalThis.screen.width,o=globalThis.screen.height,g=n<=768||o<=768,r=(globalThis.devicePixelRatio||1)>=2;return e||i&&g||i&&r?"mobile":"PC"}getDeviceType(){return this.deviceType}isMobile(){return this.deviceType==="mobile"}isPC(){return this.deviceType==="PC"}redetectDeviceType(){return this.deviceType=this.detectDeviceType(),this.deviceType}getContainerSize(){return{width:this.engine.container.clientWidth,height:this.engine.container.clientHeight}}}const VU="iflowbim.cn",HU=512,OU=128,LU=150,zU=38,tE=290,F0=190;class vU{THREE;text;scene;camera;material;sprites=[];size;viewportWidth=0;viewportHeight=0;constructor(A,t=VU){this.THREE=A,this.text=t,this.scene=new A.Scene,this.camera=new A.OrthographicCamera(0,1,1,0,-10,10),this.material=new A.SpriteMaterial({map:new A.CanvasTexture(this.createTextTexture()),transparent:!0,opacity:.46,depthTest:!1,depthWrite:!1,toneMapped:!1}),this.size=new A.Vector2}render(A){}dispose(){this.material.map?.dispose?.(),this.material.dispose?.(),this.sprites.length=0}createTextTexture(){const A=document.createElement("canvas");A.width=HU,A.height=OU;const t=A.getContext("2d");return t&&(t.clearRect(0,0,A.width,A.height),t.textAlign="center",t.textBaseline="middle",t.font="600 54px Arial, Helvetica, sans-serif",t.lineWidth=3,t.strokeStyle="rgba(0, 0, 0, 0.20)",t.fillStyle="rgba(255, 255, 255, 0.24)",t.strokeText(this.text,A.width/2,A.height/2),t.fillText(this.text,A.width/2,A.height/2)),A}updateLayout(A,t){if(A===this.viewportWidth&&t===this.viewportHeight)return;this.viewportWidth=A,this.viewportHeight=t,this.camera.left=-A/2,this.camera.right=A/2,this.camera.top=t/2,this.camera.bottom=-t/2,this.camera.updateProjectionMatrix();const e=Math.ceil(A/tE)+2,i=Math.ceil(t/F0)+2,n=e*i;this.ensureSpriteCount(n);let o=0;const g=-A/2-tE/2,a=-t/2-F0/2;for(let r=0;r<i;r+=1)for(let I=0;I<e;I+=1){const l=this.sprites[o],h=g+I*tE+r%2*(tE/2),B=a+r*F0;l.position.set(h,B,0),l.visible=!0,o+=1}for(let r=o;r<this.sprites.length;r+=1)this.sprites[r].visible=!1}ensureSpriteCount(A){for(;this.sprites.length<A;){const t=new this.THREE.Sprite(this.material);t.scale.set(LU,zU,1),t.rotation.z=-.32,t.renderOrder=999999,this.scene.add(t),this.sprites.push(t)}}}const b0=1.1;function cm(s){return s?.deviceModule?.isMobile?.()===!0?1:window.devicePixelRatio||1}class _U{engine;renderer;watermark;constructor(A){this.engine=A,this.renderer=null,this.watermark=new vU(Cm)}createRenderer(){const{width:A,height:t}=this.engine.deviceModule.getContainerSize(),e=this.engine.deviceModule.isMobile();return ft.enabled=!0,this.renderer=new AE({antialias:e?!1:this.engine.options.antialias??!0,alpha:!0,premultipliedAlpha:!1,stencil:!0,preserveDrawingBuffer:!0}),this.renderer.setClearColor(0,0),this.renderer.setSize(A,t,!1),this.renderer.setPixelRatio(cm(this.engine)),this.renderer.domElement.style.width="100%",this.renderer.domElement.style.width="100%",this.renderer.domElement.style.height="100%",this.renderer.domElement.style.display="block",this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=Ma,this.renderer.localClippingEnabled=!0,this.renderer.outputColorSpace=Rt,this.renderer.toneMapping=sg,this.renderer.toneMappingExposure=b0,this.engine.container.appendChild(this.renderer.domElement),this.renderer}disposeRenderer(){this.watermark.dispose(),this.renderer?.dispose()}drawWatermark(){this.renderer&&this.watermark.render(this.renderer)}}const qU={type:"change"},Qm={type:"start"},dm={type:"end"},Nt=1e-6,W0=Math.PI*2,qe={NONE:-1,ROTATE:0,PAN:1,DOLLY:2,TOUCH_ROTATE:3,TOUCH_DOLLY_PAN:4},G0=new S(1,0,0),$U=new S(0,1,0),AX=new S(0,0,1),pr=new S,eE=new S,Ni=new S,Zt=new S,Ms=new S,ai=new S,ys=new S,tX=new S,iE=new wt,T0=new wt,fm=new Set(["KeyW","KeyA","KeyS","KeyD","KeyQ","KeyE","ArrowUp","ArrowLeft","ArrowDown","ArrowRight","ShiftLeft","ShiftRight"]);function sE(s,A,t){return Math.max(A,Math.min(t,s))}function Mm(s){return{width:Math.max(s?.clientWidth||1,1),height:Math.max(s?.clientHeight||1,1)}}function Fo(s){return s&&typeof s.x=="number"&&typeof s.y=="number"&&typeof s.z=="number"}function ym(s){const A=s?.tagName?.toLowerCase?.();return s?.isContentEditable===!0||A==="input"||A==="textarea"||A==="select"}class pm extends Q0{constructor(A,t,e=null){super(t,e),this.engine=A,this.target=new S,this.origin=new S,this.cursor=new S,this.showOriginIcon=!0,this.auto=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.enableRotate=!0,this.enablePan=!0,this.enableZoom=!0,this.enableDamping=!1,this.rotateSpeed=.51,this.panSpeed=1,this.zoomSpeed=1,this.touchZoomSpeed=1.35,this.dampingFactor=.08,this.keyRotateSpeed=1,this.keyPanSpeed=7,this.keyMoveSpeed=.5,this.keyMoveBoost=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:ig.ROTATE,MIDDLE:ig.DOLLY,RIGHT:ig.PAN},this.state=qe.NONE,this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this.up0=this.object.up.clone(),this.origin0=this.origin.clone(),this._lastZoom=this.object.zoom,this._lastPosition=this.object.position.clone(),this._lastTarget=this.target.clone(),this._lastUp=this.object.up.clone(),this._lastQuaternion=this.object.quaternion.clone(),this._referenceUp=this.object.up.clone().normalize(),this._viewRight=new S(1,0,0).applyQuaternion(this.object.quaternion).normalize(),this._rotateVelocity=new MA,this._panVelocity=new MA,this._zoomVelocity=0,this._mouseStart=new MA,this._touchCenter=new MA,this._touchDistance=0,this._pointers=new Map,this._pressedKeys=new Set,this._keyboardAnimationId=null,this._lastKeyboardMoveTime=0,this._isInteracting=!1,this._keyDomElement=null,this._touchAction="",this._onContextMenu=this._handleContextMenu.bind(this),this._onPointerDown=this._handlePointerDown.bind(this),this._onPointerMove=this._handlePointerMove.bind(this),this._onPointerUp=this._handlePointerUp.bind(this),this._onPointerCancel=this._handlePointerUp.bind(this),this._onWheel=this._handleWheel.bind(this),this._onKeyDown=this._handleKeyDown.bind(this),this._onKeyUp=this._handleKeyUp.bind(this),this.domElement&&this.connect(this.domElement),this.update(),this.saveState()}connect(A){A&&(this.disconnect(),this.domElement=A,this._touchAction=A.style.touchAction,A.style.touchAction="none",A.addEventListener("contextmenu",this._onContextMenu),A.addEventListener("pointerdown",this._onPointerDown),A.addEventListener("pointermove",this._onPointerMove),A.addEventListener("pointerup",this._onPointerUp),A.addEventListener("pointercancel",this._onPointerCancel),A.addEventListener("wheel",this._onWheel,{passive:!1}),this.listenToKeyEvents(window))}disconnect(){this.domElement&&(this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerCancel),this.domElement.removeEventListener("wheel",this._onWheel),this.domElement.style.touchAction=this._touchAction,this.stopListenToKeyEvents())}dispose(){this.disconnect(),this._pointers.clear(),this._pressedKeys.clear(),this._stopKeyboardMoveLoop(),this.state=qe.NONE}listenToKeyEvents(A){this.stopListenToKeyEvents(),this._keyDomElement=A,this._keyDomElement?.addEventListener("keydown",this._onKeyDown),this._keyDomElement?.addEventListener("keyup",this._onKeyUp)}stopListenToKeyEvents(){this._keyDomElement&&(this._keyDomElement.removeEventListener("keydown",this._onKeyDown),this._keyDomElement.removeEventListener("keyup",this._onKeyUp),this._keyDomElement=null,this._pressedKeys.clear(),this._stopKeyboardMoveLoop())}saveState(){this.target0.copy(this.target),this.position0.copy(this.object.position),this.zoom0=this.object.zoom,this.up0.copy(this.object.up),Fo(this.origin)&&this.origin0.copy(this.origin)}reset(){this.target.copy(this.target0),this.object.position.copy(this.position0),this.object.zoom=this.zoom0,this.object.up.copy(this.up0),Fo(this.origin)&&this.origin.copy(this.origin0),this._rotateVelocity.set(0,0),this._panVelocity.set(0,0),this._zoomVelocity=0,this.object.updateProjectionMatrix?.(),this.update(!0),this.state=qe.NONE}setScreenUp(A){return!Fo(A)||(ai.copy(this.target).sub(this.object.position),ai.lengthSq()<Nt)||(ai.normalize(),Ms.copy(A).normalize(),Zt.crossVectors(ai,Ms),Zt.lengthSq()<Nt)?!1:(this._viewRight.copy(Zt.normalize()),this.update(!0),!0)}syncStateFromCamera(A=this.object,t=this.target,e={}){if(!A)return!1;this.object=A,Fo(t)&&this.target.copy(t),e.origin==="target"?this.origin.copy(this.target):Fo(e.origin)&&this.origin.copy(e.origin);const i=this.target.clone().sub(A.position),n=Fo(e.referenceUp)?new S(e.referenceUp.x,e.referenceUp.y,e.referenceUp.z).normalize():A.up.clone().normalize();return n.lengthSq()>Nt&&this._referenceUp.copy(n),Fo(e.viewRight)?this._viewRight.copy(e.viewRight).normalize():i.lengthSq()>Nt&&(i.normalize(),Zt.crossVectors(i,this._referenceUp),Zt.lengthSq()>Nt?this._viewRight.copy(Zt.normalize()):this._viewRight.set(1,0,0).applyQuaternion(A.quaternion).normalize()),this._rotateVelocity.set(0,0),this._panVelocity.set(0,0),this._zoomVelocity=0,this._mouseStart.set(0,0),this._touchCenter.set(0,0),this._touchDistance=0,this._pointers.clear(),this._pressedKeys.clear(),this._isInteracting=!1,this.state=qe.NONE,this._lastPosition.copy(A.position),this._lastTarget.copy(this.target),this._lastUp.copy(A.up),this._lastQuaternion.copy(A.quaternion),this._lastZoom=A.zoom,this.saveState(),!0}update(A=null,t=!1){const e=typeof A=="number"?A:null,i=typeof A=="boolean"?A:!!t,n=this._applyPendingMotion(e);this._alignCamera();const o=i||n||this._hasCameraStateChanged();return o&&(this.dispatchEvent(qU),this._rememberState()),o}_applyPendingMotion(A){let t=!1;this.autoRotate&&this.state===qe.NONE&&this.auto===!1&&(this._rotateVelocity.x+=this._getAutoRotateAngle(A)),this._applyKeyboardMove(A)&&(t=!0);const e=this._consumeVector2(this._rotateVelocity);e.lengthSq()>Nt&&this.enableRotate&&(this._applyRotation(e.x,e.y),t=!0);const i=this._consumeVector2(this._panVelocity);i.lengthSq()>Nt&&this.enablePan&&(this._applyPan(i.x,i.y),t=!0);const n=this._consumeNumber("_zoomVelocity");return Math.abs(n)>Nt&&this.enableZoom&&(this._applyZoom(n),t=!0),t}_applyKeyboardMove(A){if(!this.enabled||!this.object?.isPerspectiveCamera||this._pressedKeys.size===0||(ys.set(0,0,0),(this._pressedKeys.has("KeyW")||this._pressedKeys.has("ArrowUp"))&&(ys.z+=1),(this._pressedKeys.has("KeyS")||this._pressedKeys.has("ArrowDown"))&&(ys.z-=1),(this._pressedKeys.has("KeyA")||this._pressedKeys.has("ArrowLeft"))&&(ys.x-=1),(this._pressedKeys.has("KeyD")||this._pressedKeys.has("ArrowRight"))&&(ys.x+=1),this._pressedKeys.has("KeyQ")&&(ys.y+=1),this._pressedKeys.has("KeyE")&&(ys.y-=1),ys.lengthSq()<=Nt)||(ys.normalize(),Zt.copy(G0).applyQuaternion(this.object.quaternion).normalize(),ai.set(0,0,-1).applyQuaternion(this.object.quaternion).normalize(),Ms.copy(this._referenceUp).normalize(),Ms.lengthSq()<=Nt&&Ms.copy(this.object.up).normalize(),Ni.set(0,0,0),Ni.addScaledVector(Zt,ys.x),Ni.addScaledVector(ai,ys.z),Ni.addScaledVector(Ms,ys.y),Ni.lengthSq()<=Nt))return!1;Ni.normalize();const t=Number.isFinite(A)&&A>0?A:1/60,e=Math.max(this.object.position.distanceTo(this.target),1),i=this._pressedKeys.has("ShiftLeft")||this._pressedKeys.has("ShiftRight")?this.keyMoveBoost:1,n=Math.max(e*.8,1)*this.keyMoveSpeed*t*i;return Ni.multiplyScalar(n),this.object.position.add(Ni),this.target.add(Ni),this.origin.add(Ni),!0}_startKeyboardMoveLoop(){if(this._keyboardAnimationId!=null)return;this._lastKeyboardMoveTime=performance.now();const A=t=>{if(this._keyboardAnimationId=null,!this.enabled||this._pressedKeys.size===0){this._lastKeyboardMoveTime=0;return}const e=Math.min(Math.max((t-this._lastKeyboardMoveTime)/1e3,0),.05);this._lastKeyboardMoveTime=t,this.update(e),this._keyboardAnimationId=requestAnimationFrame(A)};this._keyboardAnimationId=requestAnimationFrame(A)}_stopKeyboardMoveLoop(){this._keyboardAnimationId!=null&&(cancelAnimationFrame(this._keyboardAnimationId),this._keyboardAnimationId=null),this._lastKeyboardMoveTime=0}_consumeVector2(A){if(!this.enableDamping){const i=A.clone();return A.set(0,0),i}const t=sE(this.dampingFactor,0,1),e=A.clone().multiplyScalar(t);return A.sub(e),A.lengthSq()<Nt&&A.set(0,0),e}_consumeNumber(A){if(!this.enableDamping){const i=this[A];return this[A]=0,i}const t=sE(this.dampingFactor,0,1),e=this[A]*t;return this[A]-=e,Math.abs(this[A])<Nt&&(this[A]=0),e}_applyRotation(A,t){const e=this._getRotatePivot(),i=this.object.position;pr.copy(i).sub(e),pr.lengthSq()<Nt&&pr.set(0,0,Math.max(this.minDistance,1)),eE.copy(this.target).sub(e),ai.copy(this.target).sub(i).normalize(),Math.abs(A)>Nt&&(iE.setFromAxisAngle(this._referenceUp,-A),pr.applyQuaternion(iE),eE.applyQuaternion(iE),ai.applyQuaternion(iE).normalize()),Zt.copy(this._getStableRightAxis(ai)),Math.abs(t)>Nt&&Zt.lengthSq()>Nt&&(T0.setFromAxisAngle(Zt,-t),pr.applyQuaternion(T0),eE.applyQuaternion(T0)),i.copy(e).add(pr),this.target.copy(e).add(eE)}_applyPan(A,t){const{width:e,height:i}=Mm(this.domElement);Zt.copy(G0).applyQuaternion(this.object.quaternion).normalize(),Ms.copy($U).applyQuaternion(this.object.quaternion).normalize();let n=0,o=0;if(this.object.isPerspectiveCamera){const a=2*Math.max(this.object.position.distanceTo(this.target),Nt)*Math.tan(rt.degToRad(this.object.getEffectiveFOV()*.5)),r=a*this.object.aspect;n=A/e*r*this.panSpeed,o=t/i*a*this.panSpeed}else if(this.object.isOrthographicCamera){const g=(this.object.right-this.object.left)/this.object.zoom,a=(this.object.top-this.object.bottom)/this.object.zoom;n=A/e*g*this.panSpeed,o=t/i*a*this.panSpeed}else return;Ni.set(0,0,0),Ni.addScaledVector(Zt,-n),Ni.addScaledVector(Ms,o),this.object.position.add(Ni),this.target.add(Ni)}_applyZoom(A){const t=Math.pow(.95,this.zoomSpeed*A);if(this.object.isPerspectiveCamera){ai.copy(this.object.position).sub(this.target);const e=Math.max(ai.length(),Nt),i=sE(e/t,this.minDistance,this.maxDistance);ai.setLength(i),this.object.position.copy(this.target).add(ai);return}this.object.isOrthographicCamera&&(this.object.zoom=sE(this.object.zoom*t,this.minZoom,this.maxZoom),this.object.updateProjectionMatrix())}_alignCamera(){ai.copy(this.target).sub(this.object.position),!(ai.lengthSq()<Nt)&&(ai.normalize(),Zt.copy(this._getStableRightAxis(ai)),Ms.crossVectors(Zt,ai).normalize(),Ms.lengthSq()<Nt&&Ms.copy(this._referenceUp),this._viewRight.copy(Zt),this.object.up.copy(Ms),this.object.lookAt(this.target),this.object.updateMatrixWorld())}_getStableRightAxis(A){return Zt.crossVectors(A,this._referenceUp),Zt.lengthSq()<Nt&&(Zt.copy(this._viewRight),Zt.addScaledVector(A,-Zt.dot(A))),Zt.lengthSq()<Nt&&(Zt.copy(G0),Zt.addScaledVector(A,-Zt.dot(A))),Zt.lengthSq()<Nt&&(Zt.copy(AX),Zt.addScaledVector(A,-Zt.dot(A))),Zt.normalize(),this._viewRight.lengthSq()>Nt&&Zt.dot(this._viewRight)<0&&Zt.negate(),Zt}_getRotatePivot(){return Fo(this.origin)?this.origin.distanceToSquared(this.target)<Nt?this.target:tX.copy(this.origin):this.target}_hasCameraStateChanged(){const A=this.object.isOrthographicCamera&&Math.abs(this.object.zoom-this._lastZoom)>Nt;return this._lastPosition.distanceToSquared(this.object.position)>Nt||this._lastTarget.distanceToSquared(this.target)>Nt||this._lastUp.distanceToSquared(this.object.up)>Nt||8*(1-Math.abs(this._lastQuaternion.dot(this.object.quaternion)))>Nt||A}_rememberState(){this._lastPosition.copy(this.object.position),this._lastTarget.copy(this.target),this._lastUp.copy(this.object.up),this._lastQuaternion.copy(this.object.quaternion),this._lastZoom=this.object.zoom}_getAutoRotateAngle(A){return A!=null?W0/60*this.autoRotateSpeed*A:W0/3600*this.autoRotateSpeed}_beginInteraction(A){this._isInteracting||(this.dispatchEvent(Qm),this._isInteracting=!0),this.state=A}_endInteraction(){this._isInteracting&&(this._isInteracting=!1,this.state=qe.NONE,this.dispatchEvent(dm))}_handleContextMenu(A){A.preventDefault()}_handlePointerDown(A){if(!this.enabled||!this.domElement)return;if(this.domElement.setPointerCapture?.(A.pointerId),this._pointers.set(A.pointerId,{x:A.clientX,y:A.clientY,pointerType:A.pointerType,button:A.button}),A.pointerType==="touch"){this._handleTouchStart();return}const t=this._resolveMouseAction(A);t!=null&&(this._mouseStart.set(A.clientX,A.clientY),this._beginInteraction(t))}_handlePointerMove(A){const t=this._pointers.get(A.pointerId);if(!t)return;if(A.pointerType==="touch"){t.x=A.clientX,t.y=A.clientY,this._handleTouchMove();return}if(!this.enabled||this.state===qe.NONE)return;const e=A.clientX-this._mouseStart.x,i=A.clientY-this._mouseStart.y;this._mouseStart.set(A.clientX,A.clientY),this.state===qe.ROTATE?this._queueRotate(e,i):this.state===qe.PAN?this._queuePan(e,i):this.state===qe.DOLLY&&this._queueZoom(i*.01),this.update()}_handlePointerUp(A){if(this._pointers.has(A.pointerId)){if(this.domElement?.releasePointerCapture?.(A.pointerId),this._pointers.delete(A.pointerId),A.pointerType==="touch"){this._pointers.size>0?this._restartTouchGesture():this._endInteraction();return}this._endInteraction()}}_handleWheel(A){!this.enabled||!this.enableZoom||(A.preventDefault(),this.dispatchEvent(Qm),this._queueZoom(Math.sign(A.deltaY)),this.update(),this.dispatchEvent(dm))}_handleKeyDown(A){if(!this.enabled)return;const t=A.code||A.key;if(this.object?.isPerspectiveCamera&&fm.has(t)){ym(A.target)||(this._pressedKeys.add(t),this._startKeyboardMoveLoop(),A.preventDefault());return}let e=!1;switch(t){case this.keys.UP:A.ctrlKey||A.metaKey||A.shiftKey?this._queuePan(0,this.keyPanSpeed):this._queueRotate(0,this.keyRotateSpeed),e=!0;break;case this.keys.BOTTOM:A.ctrlKey||A.metaKey||A.shiftKey?this._queuePan(0,-this.keyPanSpeed):this._queueRotate(0,-this.keyRotateSpeed),e=!0;break;case this.keys.LEFT:A.ctrlKey||A.metaKey||A.shiftKey?this._queuePan(this.keyPanSpeed,0):this._queueRotate(this.keyRotateSpeed,0),e=!0;break;case this.keys.RIGHT:A.ctrlKey||A.metaKey||A.shiftKey?this._queuePan(-this.keyPanSpeed,0):this._queueRotate(-this.keyRotateSpeed,0),e=!0;break}e&&(A.preventDefault(),this.update())}_handleKeyUp(A){const t=A.code||A.key;fm.has(t)&&(this._pressedKeys.delete(t),this._pressedKeys.size===0&&this._stopKeyboardMoveLoop(),this.object?.isPerspectiveCamera&&!ym(A.target)&&A.preventDefault())}_handleTouchStart(){const A=Array.from(this._pointers.values());if(A.length===1){this._touchCenter.set(A[0].x,A[0].y),this._touchDistance=0,this._beginInteraction(qe.TOUCH_ROTATE);return}if(A.length>=2){const t=(A[0].x+A[1].x)*.5,e=(A[0].y+A[1].y)*.5,i=Math.hypot(A[0].x-A[1].x,A[0].y-A[1].y);this._touchCenter.set(t,e),this._touchDistance=i,this._beginInteraction(qe.TOUCH_DOLLY_PAN)}}_restartTouchGesture(){const A=Array.from(this._pointers.values());if(A.length===1){this.state=qe.TOUCH_ROTATE,this._touchCenter.set(A[0].x,A[0].y),this._touchDistance=0;return}A.length>=2&&(this.state=qe.TOUCH_DOLLY_PAN,this._touchCenter.set((A[0].x+A[1].x)*.5,(A[0].y+A[1].y)*.5),this._touchDistance=Math.hypot(A[0].x-A[1].x,A[0].y-A[1].y))}_handleTouchMove(){if(!this.enabled)return;const A=Array.from(this._pointers.values());if(A.length===1&&this.state===qe.TOUCH_ROTATE){const n=A[0].x-this._touchCenter.x,o=A[0].y-this._touchCenter.y;this._touchCenter.set(A[0].x,A[0].y),this._queueRotate(n,o),this.update();return}if(A.length<2||this.state!==qe.TOUCH_DOLLY_PAN)return;const t=(A[0].x+A[1].x)*.5,e=(A[0].y+A[1].y)*.5,i=Math.hypot(A[0].x-A[1].x,A[0].y-A[1].y);if(this._queuePan(t-this._touchCenter.x,e-this._touchCenter.y),this._touchCenter.set(t,e),this._touchDistance>0&&i>0){const n=i/this._touchDistance,o=Math.pow(n,Math.max(this.touchZoomSpeed||1,Nt));this._queueZoom(Math.log(o)/Math.log(.95))}this._touchDistance=i,this.update()}_resolveMouseAction(A){let t=null;return A.button===0?t=A.ctrlKey||A.metaKey||A.shiftKey?this.mouseButtons.RIGHT:this.mouseButtons.LEFT:A.button===1?t=this.mouseButtons.MIDDLE:A.button===2&&(t=this.mouseButtons.RIGHT),t===ig.ROTATE&&this.enableRotate?qe.ROTATE:t===ig.PAN&&this.enablePan?qe.PAN:t===ig.DOLLY&&this.enableZoom?qe.DOLLY:null}_queueRotate(A,t){if(!this.enableRotate||!this.domElement)return;const{height:e}=Mm(this.domElement),i=W0/e;this._rotateVelocity.x+=A*i*this.rotateSpeed,this._rotateVelocity.y+=t*i*this.rotateSpeed}_queuePan(A,t){this.enablePan&&(this._panVelocity.x+=A,this._panVelocity.y+=t)}_queueZoom(A){this.enableZoom&&(this._zoomVelocity+=A)}}class Dm extends os{constructor(A,t,e,i){super(),this._Engine=A,this.camera=t,this.object=t,this.domElement=e,this._isEnabled=!1,this._rayOriginOffset=new S(0,-1,0),this._camerLocalDirection=new S,this._tmpVector=new S,this._lookDirection=new S,this._rayCaster=new De,this._fallingTime=0,this._isMouseInElement=!1,this._euler=new Le(0,0,0,"YZX"),this._prevMouseX=0,this._prevMouseY=0,this._pointerLookActive=!1,this._externalLookActive=!1,this._interactionActive=!1,this._sharedTargetDistance=10,this.target=this.camera.position.clone().add(new S(0,0,-1).applyQuaternion(this.camera.quaternion).normalize().multiplyScalar(this._sharedTargetDistance)),this.applyGravity=!1,this.gravityMinHeight=!0,this.applyCollision=!0,this.positionEasing=!0,this.lookflag=1,this.lookHorizontalFlag=1,this.lookSpeed=.003,this.moveSpeed=.02,this.playerHeight=1.6,this.jumpSpeed=.24,this.jumpGravity=.012,this.maxRotateX=Math.PI*.5-.01,this.g=9.8,this.bindmousedown=this._Engine&&this._Engine.deviceType!=="PC"?this.onTouchStart.bind(this):this.onMouseDown.bind(this),this.bindmouseup=this._Engine&&this._Engine.deviceType!=="PC"?this.onTouchEnd.bind(this):this.onMouseUp.bind(this),this.bindmousemove=this._Engine&&this._Engine.deviceType!=="PC"?this.onTouchMove.bind(this):this.onMouseMove.bind(this),this.bindonKeyDown=this.onKeyDown.bind(this),this.bindonKeyUp=this.onKeyUp.bind(this),this.bindWindowBlur=this.onWindowBlur.bind(this),this.bindVisibilityChange=this.onVisibilityChange.bind(this),this.bindMousewheel=this.onMousewheel.bind(this),this.bindMouseEnter=this.onMouseEnter.bind(this),this.bindMouseLeave=this.onMouseLeave.bind(this),this.needMousewheel=!1,this.moveWheelRun=!0,this.moveWheelStop=!1,this.wheelClock,this.keydown=!1,this.shiftDown=!1,this._verticalVelocity=0,this._isJumping=!1,this._isJumpKeyDown=!1,this._jumpStartHeight=this.camera.position.y,this.gravityTestCount=5,this.catchTestCount=10,this.GetEngine=()=>A,this.syncRotationStateFromCamera(),this.sanitizeCameraOrientation(),this.syncSharedTargetFromCamera()}set colliders(A){this._rayCastObjects=A}set enabled(A){this._isEnabled!==A&&(this._isEnabled=A,A?(this.syncRotationStateFromCamera(),this.sanitizeCameraOrientation(),this.syncSharedTargetFromCamera(),this.addEvents()):(this.removeEvents(),this.setPointerLookActive(!1),this.setExternalLookActive(!1),this.resetMovementState?.(),this.syncRotationStateFromCamera(),this.syncSharedTargetFromCamera()))}get enabled(){return this._isEnabled}hasMoveInput(){return this._camerLocalDirection.lengthSq()>1e-8}setPointerLookActive(A){this._pointerLookActive=A===!0,this.syncInteractionState()}setExternalLookActive(A){this._externalLookActive=A===!0,this.syncInteractionState()}syncInteractionState(){const A=this._pointerLookActive||this._externalLookActive||this.hasMoveInput()||this._isJumping;this._interactionActive!==A&&(this._interactionActive=A,this.dispatchEvent({type:A?"start":"end"}))}dispatchCameraChange(){window.dispatchEvent(new CustomEvent("bimengine:camerachange",{detail:""})),this.dispatchEvent({type:"change"})}isPcDevice(){const A=this._Engine?.deviceModule?.getDeviceType?.()??this._Engine?.deviceType??this._Engine?.DeviceType;return A==="PC"||!A}addEvents(){this.isPcDevice()?(this.domElement.addEventListener("mousedown",this.bindmousedown,!1),this.domElement.addEventListener("mouseup",this.bindmouseup,!1)):(this.domElement.addEventListener("touchstart",this.bindmousedown,!1),this.domElement.addEventListener("touchend",this.bindmouseup,!1)),this.domElement.addEventListener("mouseenter",this.bindMouseEnter,!1),this.domElement.addEventListener("mouseleave",this.bindMouseLeave,!1),window.addEventListener("keydown",this.bindonKeyDown,!1),window.addEventListener("keyup",this.bindonKeyUp,!1),window.addEventListener("blur",this.bindWindowBlur,!1),document.addEventListener("visibilitychange",this.bindVisibilityChange,!1),this.needMousewheel&&(document.addEventListener&&document.addEventListener("DOMMouseScroll",this.bindMousewheel,!1),window.addEventListener("mousewheel",this.bindMousewheel,!1))}removeEvents(){this.isPcDevice()?(this.domElement.removeEventListener("mousedown",this.bindmousedown),this.domElement.removeEventListener("mouseup",this.bindmouseup),this.domElement.removeEventListener("mousemove",this.bindmousemove)):(this.domElement.removeEventListener("touchstart",this.bindmousedown),this.domElement.removeEventListener("touchend",this.bindmouseup),this.domElement.removeEventListener("touchmove",this.bindmousemove)),this.domElement.removeEventListener("mouseenter",this.bindMouseEnter),this.domElement.removeEventListener("mouseleave",this.bindMouseLeave),window.removeEventListener("keydown",this.bindonKeyDown),window.removeEventListener("keyup",this.bindonKeyUp),window.removeEventListener("blur",this.bindWindowBlur),document.removeEventListener("visibilitychange",this.bindVisibilityChange),this.needMousewheel&&(document.addEventListener&&document.removeEventListener("DOMMouseScroll",this.bindMousewheel),window.removeEventListener("mousewheel",this.bindMousewheel))}onMouseEnter(A){this._isMouseInElement=!0}onMouseLeave(A){this._isMouseInElement=!1,this.setPointerLookActive(!1),this.setExternalLookActive(!1),this.resetMovementState()}onWindowBlur(){this.setPointerLookActive(!1),this.setExternalLookActive(!1),this.resetMovementState()}onVisibilityChange(){document.hidden&&(this.setPointerLookActive(!1),this.setExternalLookActive(!1),this.resetMovementState())}onMousewheel(A){let t;switch(A.wheelDelta?(A.wheelDelta>0&&(t="up"),A.wheelDelta<0&&(t="down")):A.detail&&(A.detail<0&&(t="up"),A.detail>0&&(t="down")),t){case"up":this._camerLocalDirection.z=1;break;case"down":this._camerLocalDirection.z=-1;break}this.moveWheelRun==!0?(this.moveWheelRun=!1,this.moveWheelStop=!0,this.wheelClock=setTimeout(()=>{this.moveWheelStop==!0&&(this.moveWheelStop=!1,this.moveWheelRun=!0,this._camerLocalDirection.z=0,this.syncInteractionState())},200)):(clearTimeout(this.wheelClock),this.wheelClock=setTimeout(()=>{this.moveWheelStop==!0&&(this.moveWheelStop=!1,this.moveWheelRun=!0,this._camerLocalDirection.z=0,this.syncInteractionState())},150)),this.syncInteractionState()}onMouseDown(A){console.log("[FirstPersonCameraControl] onMouseDown",A),this.domElement.addEventListener("mousemove",this.bindmousemove,!1),this.syncRotationStateFromCamera(),this.setPointerLookActive(!0),this._prevMouseX=A.screenX,this._prevMouseY=A.screenY}onMouseMove(A){if(this._isEnabled==!1)return;let t=this._prevMouseX?A.screenX-this._prevMouseX:0,e=this._prevMouseY?A.screenY-this._prevMouseY:0,i=this._euler.x-e*this.lookflag*this.lookSpeed;i>=0?i<this.maxRotateX?this._euler.x=i:this._euler.x=this.maxRotateX:i>-this.maxRotateX?this._euler.x=i:this._euler.x=-this.maxRotateX,this._euler.y-=t*this.lookHorizontalFlag*this.lookSpeed,this.camera.quaternion.setFromEuler(this._euler),this.syncSharedTargetFromCamera(),this._prevMouseX=A.screenX,this._prevMouseY=A.screenY;let n=this.GetEngine();n.movefirst=!0,this.dispatchCameraChange()}onMouseUp(A){let t=this.GetEngine();t.movefirst=!1,this.setPointerLookActive(!1),this.domElement.removeEventListener("mousemove",this.bindmousemove)}onTouchStart(A){this.domElement.addEventListener("touchmove",this.bindmousemove,!1),this.syncRotationStateFromCamera(),this.setPointerLookActive(!0),this._prevMouseX=A.targetTouches[0].clientX,this._prevMouseY=A.targetTouches[0].clientY}onTouchMove(A){if(this._isEnabled==!1)return;let t=this._prevMouseX?this._prevMouseX-A.targetTouches[0].clientX:0,e=this._prevMouseY?this._prevMouseY-A.targetTouches[0].clientY:0,i=this._euler.x-e*this.lookflag*this.lookSpeed;i>=0?i<this.maxRotateX?this._euler.x=i:this._euler.x=this.maxRotateX:i>-this.maxRotateX?this._euler.x=i:this._euler.x=-this.maxRotateX,this._euler.y-=t*this.lookHorizontalFlag*this.lookSpeed,this.camera.quaternion.setFromEuler(this._euler),this.syncSharedTargetFromCamera(),this._prevMouseX=A.targetTouches[0].clientX,this._prevMouseY=A.targetTouches[0].clientY;let n=this.GetEngine();n.movefirst=!0,this.dispatchCameraChange()}onTouchEnd(A){let t=this.GetEngine();t.movefirst=!1,this.setPointerLookActive(!1),this.domElement.removeEventListener("touchmove",this.bindmousemove)}onKeyDown(A){if(!this._isMouseInElement)return;let t=this.GetEngine();switch(t.movefirst=!0,this.dispatchCameraChange(),A.keyCode){case 38:this._camerLocalDirection.z=1;break;case 81:if(this.applyGravity){this.keydown=!1,this._camerLocalDirection.y=0;break}this.keydown=!0,this._camerLocalDirection.y=1;break;case 69:if(this.applyGravity){this.keydown=!1,this._camerLocalDirection.y=0;break}this._camerLocalDirection.y=-1;break;case 87:this._camerLocalDirection.z=1;break;case 37:this._camerLocalDirection.x=-1;break;case 65:this._camerLocalDirection.x=-1;break;case 40:this._camerLocalDirection.z=-1;break;case 83:this._camerLocalDirection.z=-1;break;case 39:this._camerLocalDirection.x=1;break;case 68:this._camerLocalDirection.x=1;break;case 32:A.preventDefault?.(),A.stopPropagation?.(),this._isJumpKeyDown||(this._isJumpKeyDown=!0,this.jump());break;case 16:this.shiftDown=!0;break}this.syncInteractionState()}onKeyUp(A){let t=this.GetEngine();switch(A.keyCode){case 38:case 87:this._camerLocalDirection.z=0;break;case 37:case 65:this._camerLocalDirection.x=0;break;case 40:case 83:this._camerLocalDirection.z=0;break;case 39:case 68:this._camerLocalDirection.x=0;break;case 81:case 69:this.keydown=!1,this._camerLocalDirection.y=0;break;case 32:A.preventDefault?.(),A.stopPropagation?.(),this._isJumpKeyDown=!1;break;case 16:this.shiftDown=!1;break}t.movefirst=this._camerLocalDirection.x!==0||this._camerLocalDirection.y!==0||this._camerLocalDirection.z!==0,this.syncInteractionState()}rotateX(A){this.syncRotationStateFromCamera(),this._euler.y-=A*this.lookHorizontalFlag*this.lookSpeed,this.camera.quaternion.setFromEuler(this._euler),this.syncSharedTargetFromCamera(),this.dispatchCameraChange()}rotateY(A){this.syncRotationStateFromCamera();let t=this._euler.x-A*this.lookflag*.5*this.lookSpeed;t>=0?t<this.maxRotateX?this._euler.x=t:this._euler.x=this.maxRotateX:t>-this.maxRotateX?this._euler.x=t:this._euler.x=-this.maxRotateX,this.camera.quaternion.setFromEuler(this._euler),this.syncSharedTargetFromCamera(),this.dispatchCameraChange()}setLookDirection({horizontal:A,vertical:t}={}){(A===1||A===-1)&&(this.lookHorizontalFlag=A),(t===1||t===-1)&&(this.lookflag=t)}update(){const A=this.camera.position.clone(),t=this.camera.quaternion.clone();this.applyGravity&&(this.keydown=!1,this._camerLocalDirection.y=0),this.updateJump(),!this.keydown&&!this._isJumping&&this.gravityTest(),this.collisionTest(),this.syncSharedTargetFromCamera(),this.syncInteractionState(),(A.distanceToSquared(this.camera.position)>1e-12||1-Math.abs(t.dot(this.camera.quaternion))>1e-12)&&this.dispatchCameraChange()}syncRotationStateFromCamera(){this.camera&&(this.object=this.camera,this.camera.updateMatrixWorld?.(),this._euler.setFromQuaternion(this.camera.quaternion,"YZX"))}sanitizeCameraOrientation(){this.camera&&(this.syncRotationStateFromCamera(),this._euler.x=rt.clamp(this._euler.x,-this.maxRotateX,this.maxRotateX),this._euler.z=0,this.camera.up.set(0,1,0),this.camera.quaternion.setFromEuler(this._euler),this.camera.updateMatrixWorld?.(!0))}syncSharedTargetFromCamera(){if(!this.camera)return;this.object=this.camera;let A=this.GetEngine();const t=[],e=i=>{!i?.target||t.includes(i)||t.push(i)};if(e(this),e(A?.controls),e(A?.controlModule?.orbitControls),t.length!==0){this.camera.getWorldDirection(this._lookDirection);for(const i of t){const n=this.camera.position.distanceTo(i.target);Number.isFinite(n)&&n>.001&&(this._sharedTargetDistance=n),i.target.copy(this.camera.position).addScaledVector(this._lookDirection,this._sharedTargetDistance)}}}setScreenUp(A){return!A||typeof A.x!="number"||typeof A.y!="number"||typeof A.z!="number"||!this.camera?!1:(this.camera.up.copy(A).normalize(),this.target&&this.camera.lookAt(this.target),this.camera.updateMatrixWorld?.(!0),this.syncRotationStateFromCamera(),this.sanitizeCameraOrientation(),this.syncSharedTargetFromCamera(),!0)}resetMovementState(){this._camerLocalDirection.set(0,0,0),this.keydown=!1,this.shiftDown=!1,this._verticalVelocity=0,this._isJumping=!1,this._isJumpKeyDown=!1;let A=this.GetEngine();A&&(A.movefirst=!1),this.syncInteractionState()}resetMovementState(){this._camerLocalDirection.set(0,0,0),this.keydown=!1,this.shiftDown=!1,this._verticalVelocity=0,this._isJumping=!1,this._isJumpKeyDown=!1;let A=this.GetEngine();A&&(A.movefirst=!1),this.syncInteractionState()}jump(){this._isJumping||(this._jumpStartHeight=this.camera.position.y,this._verticalVelocity=this.jumpSpeed,this._isJumping=!0,this.syncInteractionState())}updateJump(){if(!this._isJumping)return;this.setCameraHeight(this.camera.position.y+this._verticalVelocity),this._verticalVelocity-=this.jumpGravity;const A=this.getJumpFloorCameraHeight();this._verticalVelocity<=0&&this.camera.position.y<=A&&(this.setCameraHeight(A),this._verticalVelocity=0,this._isJumping=!1,this._fallingTime=0,this.syncInteractionState())}getJumpFloorCameraHeight(){const A=this.hitTest(new S(0,-1,0),this.playerHeight+3);if(A?.point)return A.point.y+this.playerHeight;const t=this.getMinHeight();return Math.max(this._jumpStartHeight,t??-1/0)}gravityTest(){if(!(this._camerLocalDirection.y==0&&this._camerLocalDirection.z==0&&this._camerLocalDirection.x==0))if(this.applyGravity){let A=!0;this._fallingTime+=.01,this._tmpVector.set(0,-1,0);const t=this.hitTest(this._tmpVector,this.playerHeight+3);if(t==null)return;if(t){const e=t.point.add(new S(0,this.playerHeight,0));if(this.positionEasing){if(e.y>=this.camera.position.y||e.y-this.camera.position.y<.2){this.setCameraHeight(this.camera.position.y+(e.y-this.camera.position.y)*.08),this._fallingTime=0,A=!1;return}}else t.distance<this.playerHeight&&(this.setCameraHeight(e.y),this._fallingTime=0,A=!1)}A&&this.setCameraHeight(this.camera.position.y-this.g*Math.pow(this._fallingTime,2))}else this.setCameraHeight(this.camera.position.y)}collisionTest(){this._camerLocalDirection.x!==0&&this.collisionTestX(),this._camerLocalDirection.z!==0&&this.collisionTestZ(),!this.applyGravity&&this._camerLocalDirection.y!==0&&this.collisionTestY()}collisionTestX(){let A=this.GetEngine();if(A.movefirst=!0,this._tmpVector.setFromMatrixColumn(this.camera.matrix,0),this._tmpVector.multiplyScalar(this._camerLocalDirection.x),this._tmpVector.set(this._tmpVector.x,0,this._tmpVector.z),this._tmpVector=this._tmpVector.normalize(),this.applyCollision){const t=this.hitTest(this._tmpVector);if(t&&t.distance<.3)return}this.camera.position.addScaledVector(this._tmpVector,this.moveSpeed*(this.shiftDown?2:1))}collisionTestZ(){let A=this.GetEngine();if(A.movefirst=!0,this._tmpVector.setFromMatrixColumn(this.camera.matrix,0),this._tmpVector.crossVectors(this.camera.up,this._tmpVector),this._tmpVector.multiplyScalar(this._camerLocalDirection.z),this._tmpVector.set(this._tmpVector.x,0,this._tmpVector.z),this._tmpVector=this._tmpVector.normalize(),this.applyCollision){const t=this.hitTest(this._tmpVector);if(t&&t.distance<.3)return}this.camera.position.addScaledVector(this._tmpVector,this.moveSpeed*(this.shiftDown?2:1))}collisionTestY(){let A=this.GetEngine();if(A.movefirst=!0,this._tmpVector.setFromMatrixColumn(this.camera.matrix,0),this._tmpVector=new S(0,1,0),this._tmpVector.multiplyScalar(this._camerLocalDirection.y),this.applyCollision){const e=this.hitTest(this._tmpVector);if(e&&e.distance<.3)return}let t=this.camera.position.clone().addScaledVector(this._tmpVector,this.moveSpeed*(this.shiftDown?2:1));this.setCameraHeight(t.y)}setCameraHeight(A){let t=this.getMinHeight();this.gravityMinHeight&&t!==void 0&&A<t?this.camera.position.y=t:this.camera.position.y=A}getMinHeight(){let A,t=this.GetEngine(),e=t.ToolUntils?t.ToolUntils.GetBoundingBox(t):null;return t&&e&&(A=e.min.y),A}hitTest(A=this._tmpVector,t=1/0){const e=this.camera.position.clone().add(this._rayOriginOffset);this._rayCaster.ray.origin=e,this._rayCaster.ray.direction=A,this._rayCaster.far=t;let i=this.GetEngine();var n=i.scene.ground;n&&n.material.type;let o={},g=i.handelBehaved.handle_catch(this._rayCaster,o,!1);if(this._rayCaster.far=1/0,g==null)return null;let a=g.object.name,r=g.object.url,I=i.models.find(l=>l.url==r);if(I!=null){let l=I.nodesMap.get(a);if(l.infos!=null&&l.infos.length!=0&&l.infos[0].name&&(l.infos[0].name.includes("门")||l.infos[0].name.includes("門")||l.infos[0].name.includes("door")))return null}return g}}function El(s,A=!1){const t=s[0].index!==null,e=new Set(Object.keys(s[0].attributes)),i=new Set(Object.keys(s[0].morphAttributes)),n={},o={},g=s[0].morphTargetsRelative,a=new et;let r=0;for(let I=0;I<s.length;++I){const l=s[I];let h=0;if(t!==(l.index!==null))return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+I+". All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them."),null;for(const B in l.attributes){if(!e.has(B))return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+I+'. All geometries must have compatible attributes; make sure "'+B+'" attribute exists among all geometries, or in none of them.'),null;n[B]===void 0&&(n[B]=[]),n[B].push(l.attributes[B]),h++}if(h!==e.size)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+I+". Make sure all geometries have the same number of attributes."),null;if(g!==l.morphTargetsRelative)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+I+". .morphTargetsRelative must be consistent throughout all geometries."),null;for(const B in l.morphAttributes){if(!i.has(B))return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+I+". .morphAttributes must be consistent throughout all geometries."),null;o[B]===void 0&&(o[B]=[]),o[B].push(l.morphAttributes[B])}if(A){let B;if(t)B=l.index.count;else if(l.attributes.position!==void 0)B=l.attributes.position.count;else return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+I+". The geometry must have either an index or a position attribute"),null;a.addGroup(r,B,I),r+=B}}if(t){let I=0;const l=[];for(let h=0;h<s.length;++h){const B=s[h].index;for(let E=0;E<B.count;++E)l.push(B.getX(E)+I);I+=s[h].attributes.position.count}a.setIndex(l)}for(const I in n){const l=wm(n[I]);if(!l)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the "+I+" attribute."),null;a.setAttribute(I,l)}for(const I in o){const l=o[I][0].length;if(l!==0){a.morphAttributes=a.morphAttributes||{},a.morphAttributes[I]=[];for(let h=0;h<l;++h){const B=[];for(let c=0;c<o[I].length;++c)B.push(o[I][c][h]);const E=wm(B);if(!E)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the "+I+" morphAttribute."),null;a.morphAttributes[I].push(E)}}}return a}function wm(s){let A,t,e,i=-1,n=0;for(let r=0;r<s.length;++r){const I=s[r];if(A===void 0&&(A=I.array.constructor),A!==I.array.constructor)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.array must be of consistent array types across matching attributes."),null;if(t===void 0&&(t=I.itemSize),t!==I.itemSize)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.itemSize must be consistent across matching attributes."),null;if(e===void 0&&(e=I.normalized),e!==I.normalized)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.normalized must be consistent across matching attributes."),null;if(i===-1&&(i=I.gpuType),i!==I.gpuType)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.gpuType must be consistent across matching attributes."),null;n+=I.count*t}const o=new A(n),g=new yt(o,t,e);let a=0;for(let r=0;r<s.length;++r){const I=s[r];if(I.isInterleavedBufferAttribute){const l=a/t;for(let h=0,B=I.count;h<B;h++)for(let E=0;E<t;E++){const c=I.getComponent(h,E);g.setComponent(h+l,E,c)}}else o.set(I.array,a);a+=I.count*t}return i!==void 0&&(g.gpuType=i),g}function um(s,A){if(A===mD)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),s;if(A===Yh||A===LQ){let t=s.getIndex();if(t===null){const n=[],o=s.getAttribute("position");if(o!==void 0){for(let g=0;g<o.count;g++)n.push(g);s.setIndex(n),t=s.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),s}const e=t.count-2,i=[];if(A===Yh)for(let n=1;n<=e;n++)i.push(t.getX(0)),i.push(t.getX(n)),i.push(t.getX(n+1));else for(let n=0;n<e;n++)n%2===0?(i.push(t.getX(n)),i.push(t.getX(n+1)),i.push(t.getX(n+2))):(i.push(t.getX(n+2)),i.push(t.getX(n+1)),i.push(t.getX(n)));return i.length/3!==e&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles."),s.setIndex(i),s.clearGroups(),s}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",A),s}function eX(s){const A=new Map,t=new Map,e=s.clone();return mm(s,e,function(i,n){A.set(n,i),t.set(i,n)}),e.traverse(function(i){if(!i.isSkinnedMesh)return;const n=i,o=A.get(i),g=o.skeleton.bones;n.skeleton=o.skeleton.clone(),n.bindMatrix.copy(o.bindMatrix),n.skeleton.bones=g.map(function(a){return t.get(a)}),n.bind(n.skeleton,n.bindMatrix)}),e}function mm(s,A,t){t(s,A);for(let e=0;e<s.children.length;e++)mm(s.children[e],A.children[e],t)}class K0 extends hi{constructor(A){super(A),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new gX(t)}),this.register(function(t){return new aX(t)}),this.register(function(t){return new QX(t)}),this.register(function(t){return new dX(t)}),this.register(function(t){return new fX(t)}),this.register(function(t){return new IX(t)}),this.register(function(t){return new lX(t)}),this.register(function(t){return new BX(t)}),this.register(function(t){return new hX(t)}),this.register(function(t){return new oX(t)}),this.register(function(t){return new CX(t)}),this.register(function(t){return new rX(t)}),this.register(function(t){return new cX(t)}),this.register(function(t){return new EX(t)}),this.register(function(t){return new sX(t)}),this.register(function(t){return new Pm(t,bt.EXT_MESHOPT_COMPRESSION)}),this.register(function(t){return new Pm(t,bt.KHR_MESHOPT_COMPRESSION)}),this.register(function(t){return new MX(t)})}load(A,t,e,i){const n=this;let o;if(this.resourcePath!=="")o=this.resourcePath;else if(this.path!==""){const r=Ns.extractUrlBase(A);o=Ns.resolveURL(r,this.path)}else o=Ns.extractUrlBase(A);this.manager.itemStart(A);const g=function(r){i?i(r):console.error(r),n.manager.itemError(A),n.manager.itemEnd(A)},a=new mi(this.manager);a.setPath(this.path),a.setResponseType("arraybuffer"),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(A,function(r){try{n.parse(r,o,function(I){t(I),n.manager.itemEnd(A)},g)}catch(I){g(I)}},e,g)}setDRACOLoader(A){return this.dracoLoader=A,this}setKTX2Loader(A){return this.ktx2Loader=A,this}setMeshoptDecoder(A){return this.meshoptDecoder=A,this}register(A){return this.pluginCallbacks.indexOf(A)===-1&&this.pluginCallbacks.push(A),this}unregister(A){return this.pluginCallbacks.indexOf(A)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(A),1),this}parse(A,t,e,i){let n;const o={},g={},a=new TextDecoder;if(typeof A=="string")n=JSON.parse(A);else if(A instanceof ArrayBuffer)if(a.decode(new Uint8Array(A,0,4))===Sm){try{o[bt.KHR_BINARY_GLTF]=new yX(A)}catch(l){i&&i(l);return}n=JSON.parse(o[bt.KHR_BINARY_GLTF].content)}else n=JSON.parse(a.decode(A));else n=A;if(n.asset===void 0||n.asset.version[0]<2){i&&i(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}const r=new TX(n,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});r.fileLoader.setRequestHeader(this.requestHeader);for(let I=0;I<this.pluginCallbacks.length;I++){const l=this.pluginCallbacks[I](r);l.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),g[l.name]=l,o[l.name]=!0}if(n.extensionsUsed)for(let I=0;I<n.extensionsUsed.length;++I){const l=n.extensionsUsed[I],h=n.extensionsRequired||[];switch(l){case bt.KHR_MATERIALS_UNLIT:o[l]=new nX;break;case bt.KHR_DRACO_MESH_COMPRESSION:o[l]=new pX(n,this.dracoLoader);break;case bt.KHR_TEXTURE_TRANSFORM:o[l]=new DX;break;case bt.KHR_MESH_QUANTIZATION:o[l]=new wX;break;default:h.indexOf(l)>=0&&g[l]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+l+'".')}}r.setExtensions(o),r.setPlugins(g),r.parse(e,i)}parseAsync(A,t){const e=this;return new Promise(function(i,n){e.parse(A,t,i,n)})}}function iX(){let s={};return{get:function(A){return s[A]},add:function(A,t){s[A]=t},remove:function(A){delete s[A]},removeAll:function(){s={}}}}function Ge(s,A,t){const e=s.json.materials[A];return e.extensions&&e.extensions[t]?e.extensions[t]:null}const bt={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",KHR_MESHOPT_COMPRESSION:"KHR_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class sX{constructor(A){this.parser=A,this.name=bt.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const A=this.parser,t=this.parser.json.nodes||[];for(let e=0,i=t.length;e<i;e++){const n=t[e];n.extensions&&n.extensions[this.name]&&n.extensions[this.name].light!==void 0&&A._addNodeRef(this.cache,n.extensions[this.name].light)}}_loadLight(A){const t=this.parser,e="light:"+A;let i=t.cache.get(e);if(i)return i;const n=t.json,a=((n.extensions&&n.extensions[this.name]||{}).lights||[])[A];let r;const I=new XA(16777215);a.color!==void 0&&I.setRGB(a.color[0],a.color[1],a.color[2],si);const l=a.range!==void 0?a.range:0;switch(a.type){case"directional":r=new Zs(I),r.target.position.set(0,0,-1),r.add(r.target);break;case"point":r=new t0(I),r.distance=l;break;case"spot":r=new A0(I),r.distance=l,a.spot=a.spot||{},a.spot.innerConeAngle=a.spot.innerConeAngle!==void 0?a.spot.innerConeAngle:0,a.spot.outerConeAngle=a.spot.outerConeAngle!==void 0?a.spot.outerConeAngle:Math.PI/4,r.angle=a.spot.outerConeAngle,r.penumbra=1-a.spot.innerConeAngle/a.spot.outerConeAngle,r.target.position.set(0,0,-1),r.add(r.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+a.type)}return r.position.set(0,0,0),hn(r,a),a.intensity!==void 0&&(r.intensity=a.intensity),r.name=t.createUniqueName(a.name||"light_"+A),i=Promise.resolve(r),t.cache.add(e,i),i}getDependency(A,t){if(A==="light")return this._loadLight(t)}createNodeAttachment(A){const t=this,e=this.parser,n=e.json.nodes[A],g=(n.extensions&&n.extensions[this.name]||{}).light;return g===void 0?null:this._loadLight(g).then(function(a){return e._getNodeRef(t.cache,g,a)})}}class nX{constructor(){this.name=bt.KHR_MATERIALS_UNLIT}getMaterialType(){return Kt}extendParams(A,t,e){const i=[];A.color=new XA(1,1,1),A.opacity=1;const n=t.pbrMetallicRoughness;if(n){if(Array.isArray(n.baseColorFactor)){const o=n.baseColorFactor;A.color.setRGB(o[0],o[1],o[2],si),A.opacity=o[3]}n.baseColorTexture!==void 0&&i.push(e.assignTexture(A,"map",n.baseColorTexture,Rt))}return Promise.all(i)}}class oX{constructor(A){this.parser=A,this.name=bt.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(A,t){const e=Ge(this.parser,A,this.name);return e===null||e.emissiveStrength!==void 0&&(t.emissiveIntensity=e.emissiveStrength),Promise.resolve()}}class gX{constructor(A){this.parser=A,this.name=bt.KHR_MATERIALS_CLEARCOAT}getMaterialType(A){return Ge(this.parser,A,this.name)!==null?ds:null}extendMaterialParams(A,t){const e=Ge(this.parser,A,this.name);if(e===null)return Promise.resolve();const i=[];if(e.clearcoatFactor!==void 0&&(t.clearcoat=e.clearcoatFactor),e.clearcoatTexture!==void 0&&i.push(this.parser.assignTexture(t,"clearcoatMap",e.clearcoatTexture)),e.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=e.clearcoatRoughnessFactor),e.clearcoatRoughnessTexture!==void 0&&i.push(this.parser.assignTexture(t,"clearcoatRoughnessMap",e.clearcoatRoughnessTexture)),e.clearcoatNormalTexture!==void 0&&(i.push(this.parser.assignTexture(t,"clearcoatNormalMap",e.clearcoatNormalTexture)),e.clearcoatNormalTexture.scale!==void 0)){const n=e.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new MA(n,n)}return Promise.all(i)}}class aX{constructor(A){this.parser=A,this.name=bt.KHR_MATERIALS_DISPERSION}getMaterialType(A){return Ge(this.parser,A,this.name)!==null?ds:null}extendMaterialParams(A,t){const e=Ge(this.parser,A,this.name);return e===null||(t.dispersion=e.dispersion!==void 0?e.dispersion:0),Promise.resolve()}}class rX{constructor(A){this.parser=A,this.name=bt.KHR_MATERIALS_IRIDESCENCE}getMaterialType(A){return Ge(this.parser,A,this.name)!==null?ds:null}extendMaterialParams(A,t){const e=Ge(this.parser,A,this.name);if(e===null)return Promise.resolve();const i=[];return e.iridescenceFactor!==void 0&&(t.iridescence=e.iridescenceFactor),e.iridescenceTexture!==void 0&&i.push(this.parser.assignTexture(t,"iridescenceMap",e.iridescenceTexture)),e.iridescenceIor!==void 0&&(t.iridescenceIOR=e.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),e.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=e.iridescenceThicknessMinimum),e.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=e.iridescenceThicknessMaximum),e.iridescenceThicknessTexture!==void 0&&i.push(this.parser.assignTexture(t,"iridescenceThicknessMap",e.iridescenceThicknessTexture)),Promise.all(i)}}class IX{constructor(A){this.parser=A,this.name=bt.KHR_MATERIALS_SHEEN}getMaterialType(A){return Ge(this.parser,A,this.name)!==null?ds:null}extendMaterialParams(A,t){const e=Ge(this.parser,A,this.name);if(e===null)return Promise.resolve();const i=[];if(t.sheenColor=new XA(0,0,0),t.sheenRoughness=0,t.sheen=1,e.sheenColorFactor!==void 0){const n=e.sheenColorFactor;t.sheenColor.setRGB(n[0],n[1],n[2],si)}return e.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=e.sheenRoughnessFactor),e.sheenColorTexture!==void 0&&i.push(this.parser.assignTexture(t,"sheenColorMap",e.sheenColorTexture,Rt)),e.sheenRoughnessTexture!==void 0&&i.push(this.parser.assignTexture(t,"sheenRoughnessMap",e.sheenRoughnessTexture)),Promise.all(i)}}class lX{constructor(A){this.parser=A,this.name=bt.KHR_MATERIALS_TRANSMISSION}getMaterialType(A){return Ge(this.parser,A,this.name)!==null?ds:null}extendMaterialParams(A,t){const e=Ge(this.parser,A,this.name);if(e===null)return Promise.resolve();const i=[];return e.transmissionFactor!==void 0&&(t.transmission=e.transmissionFactor),e.transmissionTexture!==void 0&&i.push(this.parser.assignTexture(t,"transmissionMap",e.transmissionTexture)),Promise.all(i)}}class BX{constructor(A){this.parser=A,this.name=bt.KHR_MATERIALS_VOLUME}getMaterialType(A){return Ge(this.parser,A,this.name)!==null?ds:null}extendMaterialParams(A,t){const e=Ge(this.parser,A,this.name);if(e===null)return Promise.resolve();const i=[];t.thickness=e.thicknessFactor!==void 0?e.thicknessFactor:0,e.thicknessTexture!==void 0&&i.push(this.parser.assignTexture(t,"thicknessMap",e.thicknessTexture)),t.attenuationDistance=e.attenuationDistance||1/0;const n=e.attenuationColor||[1,1,1];return t.attenuationColor=new XA().setRGB(n[0],n[1],n[2],si),Promise.all(i)}}class hX{constructor(A){this.parser=A,this.name=bt.KHR_MATERIALS_IOR}getMaterialType(A){return Ge(this.parser,A,this.name)!==null?ds:null}extendMaterialParams(A,t){const e=Ge(this.parser,A,this.name);return e===null||(t.ior=e.ior!==void 0?e.ior:1.5,t.ior===0&&(t.ior=1e3)),Promise.resolve()}}class CX{constructor(A){this.parser=A,this.name=bt.KHR_MATERIALS_SPECULAR}getMaterialType(A){return Ge(this.parser,A,this.name)!==null?ds:null}extendMaterialParams(A,t){const e=Ge(this.parser,A,this.name);if(e===null)return Promise.resolve();const i=[];t.specularIntensity=e.specularFactor!==void 0?e.specularFactor:1,e.specularTexture!==void 0&&i.push(this.parser.assignTexture(t,"specularIntensityMap",e.specularTexture));const n=e.specularColorFactor||[1,1,1];return t.specularColor=new XA().setRGB(n[0],n[1],n[2],si),e.specularColorTexture!==void 0&&i.push(this.parser.assignTexture(t,"specularColorMap",e.specularColorTexture,Rt)),Promise.all(i)}}class EX{constructor(A){this.parser=A,this.name=bt.EXT_MATERIALS_BUMP}getMaterialType(A){return Ge(this.parser,A,this.name)!==null?ds:null}extendMaterialParams(A,t){const e=Ge(this.parser,A,this.name);if(e===null)return Promise.resolve();const i=[];return t.bumpScale=e.bumpFactor!==void 0?e.bumpFactor:1,e.bumpTexture!==void 0&&i.push(this.parser.assignTexture(t,"bumpMap",e.bumpTexture)),Promise.all(i)}}class cX{constructor(A){this.parser=A,this.name=bt.KHR_MATERIALS_ANISOTROPY}getMaterialType(A){return Ge(this.parser,A,this.name)!==null?ds:null}extendMaterialParams(A,t){const e=Ge(this.parser,A,this.name);if(e===null)return Promise.resolve();const i=[];return e.anisotropyStrength!==void 0&&(t.anisotropy=e.anisotropyStrength),e.anisotropyRotation!==void 0&&(t.anisotropyRotation=e.anisotropyRotation),e.anisotropyTexture!==void 0&&i.push(this.parser.assignTexture(t,"anisotropyMap",e.anisotropyTexture)),Promise.all(i)}}class QX{constructor(A){this.parser=A,this.name=bt.KHR_TEXTURE_BASISU}loadTexture(A){const t=this.parser,e=t.json,i=e.textures[A];if(!i.extensions||!i.extensions[this.name])return null;const n=i.extensions[this.name],o=t.options.ktx2Loader;if(!o){if(e.extensionsRequired&&e.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(A,n.source,o)}}class dX{constructor(A){this.parser=A,this.name=bt.EXT_TEXTURE_WEBP}loadTexture(A){const t=this.name,e=this.parser,i=e.json,n=i.textures[A];if(!n.extensions||!n.extensions[t])return null;const o=n.extensions[t],g=i.images[o.source];let a=e.textureLoader;if(g.uri){const r=e.options.manager.getHandler(g.uri);r!==null&&(a=r)}return e.loadTextureImage(A,o.source,a)}}class fX{constructor(A){this.parser=A,this.name=bt.EXT_TEXTURE_AVIF}loadTexture(A){const t=this.name,e=this.parser,i=e.json,n=i.textures[A];if(!n.extensions||!n.extensions[t])return null;const o=n.extensions[t],g=i.images[o.source];let a=e.textureLoader;if(g.uri){const r=e.options.manager.getHandler(g.uri);r!==null&&(a=r)}return e.loadTextureImage(A,o.source,a)}}class Pm{constructor(A,t){this.name=t,this.parser=A}loadBufferView(A){const t=this.parser.json,e=t.bufferViews[A];if(e.extensions&&e.extensions[this.name]){const i=e.extensions[this.name],n=this.parser.getDependency("buffer",i.buffer),o=this.parser.options.meshoptDecoder;if(!o||!o.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return n.then(function(g){const a=i.byteOffset||0,r=i.byteLength||0,I=i.count,l=i.byteStride,h=new Uint8Array(g,a,r);return o.decodeGltfBufferAsync?o.decodeGltfBufferAsync(I,l,h,i.mode,i.filter).then(function(B){return B.buffer}):o.ready.then(function(){const B=new ArrayBuffer(I*l);return o.decodeGltfBuffer(new Uint8Array(B),I,l,h,i.mode,i.filter),B})})}else return null}}class MX{constructor(A){this.name=bt.EXT_MESH_GPU_INSTANCING,this.parser=A}createNodeMesh(A){const t=this.parser.json,e=t.nodes[A];if(!e.extensions||!e.extensions[this.name]||e.mesh===void 0)return null;const i=t.meshes[e.mesh];for(const r of i.primitives)if(r.mode!==ps.TRIANGLES&&r.mode!==ps.TRIANGLE_STRIP&&r.mode!==ps.TRIANGLE_FAN&&r.mode!==void 0)return null;const o=e.extensions[this.name].attributes,g=[],a={};for(const r in o)g.push(this.parser.getDependency("accessor",o[r]).then(I=>(a[r]=I,a[r])));return g.length<1?null:(g.push(this.parser.createNodeMesh(A)),Promise.all(g).then(r=>{const I=r.pop(),l=I.isGroup?I.children:[I],h=r[0].count,B=[];for(const E of l){const c=new RA,Q=new S,C=new wt,d=new S(1,1,1),M=new ct(E.geometry,E.material,h);for(let w=0;w<h;w++)a.TRANSLATION&&Q.fromBufferAttribute(a.TRANSLATION,w),a.ROTATION&&C.fromBufferAttribute(a.ROTATION,w),a.SCALE&&d.fromBufferAttribute(a.SCALE,w),M.setMatrixAt(w,c.compose(Q,C,d));let y=null;for(const w in a)if(w==="_COLOR_0"){const D=a[w];M.instanceColor=new Un(D.array,D.itemSize,D.normalized)}else if(w!=="TRANSLATION"&&w!=="ROTATION"&&w!=="SCALE"){if(y===null){const p=M.geometry;y=new et,y.name=p.name;for(const f in p.attributes)y.setAttribute(f,p.attributes[f]);for(const f in p.morphAttributes)y.morphAttributes[f]=p.morphAttributes[f];p.index!==null&&y.setIndex(p.index),y.morphTargetsRelative=p.morphTargetsRelative;for(const f of p.groups)y.addGroup(f.start,f.count,f.materialIndex);p.boundingBox!==null&&(y.boundingBox=p.boundingBox.clone()),p.boundingSphere!==null&&(y.boundingSphere=p.boundingSphere.clone()),y.drawRange.start=p.drawRange.start,y.drawRange.count=p.drawRange.count,y.userData=Object.assign({},p.userData),M.geometry=y}const D=a[w];y.setAttribute(w,new Un(D.array,D.itemSize,D.normalized))}Et.prototype.copy.call(M,E),this.parser.assignFinalMaterial(M),B.push(M)}return I.isGroup?(I.clear(),I.add(...B),I):B[0]}))}}const Sm="glTF",cl=12,Ym={JSON:1313821514,BIN:5130562};class yX{constructor(A){this.name=bt.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(A,0,cl),e=new TextDecoder;if(this.header={magic:e.decode(new Uint8Array(A.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==Sm)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");const i=this.header.length-cl,n=new DataView(A,cl);let o=0;for(;o<i;){const g=n.getUint32(o,!0);o+=4;const a=n.getUint32(o,!0);if(o+=4,a===Ym.JSON){const r=new Uint8Array(A,cl+o,g);this.content=e.decode(r)}else if(a===Ym.BIN){const r=cl+o;this.body=A.slice(r,r+g)}o+=g}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class pX{constructor(A,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=bt.KHR_DRACO_MESH_COMPRESSION,this.json=A,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(A,t){const e=this.json,i=this.dracoLoader,n=A.extensions[this.name].bufferView,o=A.extensions[this.name].attributes,g={},a={},r={};for(const I in o){const l=R0[I]||I.toLowerCase();g[l]=o[I]}for(const I in A.attributes){const l=R0[I]||I.toLowerCase();if(o[I]!==void 0){const h=e.accessors[A.attributes[I]],B=Dr[h.componentType];r[l]=B.name,a[l]=h.normalized===!0}}return t.getDependency("bufferView",n).then(function(I){return new Promise(function(l,h){i.decodeDracoFile(I,function(B){for(const E in B.attributes){const c=B.attributes[E],Q=a[E];Q!==void 0&&(c.normalized=Q)}l(B)},g,r,si,h)})})}}class DX{constructor(){this.name=bt.KHR_TEXTURE_TRANSFORM}extendTexture(A,t){if((t.texCoord===void 0||t.texCoord===A.channel)&&t.offset===void 0&&t.rotation===void 0&&t.scale===void 0)return A;if(A=A.clone(),t.texCoord!==void 0&&(A.channel=t.texCoord),t.offset!==void 0&&A.offset.fromArray(t.offset),t.rotation!==void 0&&(A.rotation=t.rotation),t.scale!==void 0&&A.repeat.fromArray(t.scale),t.rotation!==void 0){const e=Math.cos(A.rotation),i=Math.sin(A.rotation);A.matrix.set(A.repeat.x*e,A.repeat.y*i,A.offset.x,-A.repeat.x*i,A.repeat.y*e,A.offset.y,0,0,1),A.matrixAutoUpdate=!1}return A.needsUpdate=!0,A}}class wX{constructor(){this.name=bt.KHR_MESH_QUANTIZATION}}class Fm extends pg{constructor(A,t,e,i){super(A,t,e,i)}copySampleValue_(A){const t=this.resultBuffer,e=this.sampleValues,i=this.valueSize,n=A*i*3+i;for(let o=0;o!==i;o++)t[o]=e[n+o];return t}interpolate_(A,t,e,i){const n=this.resultBuffer,o=this.sampleValues,g=this.valueSize,a=g*2,r=g*3,I=i-t,l=(e-t)/I,h=l*l,B=h*l,E=A*r,c=E-r,Q=-2*B+3*h,C=B-h,d=1-Q,M=C-h+l;for(let y=0;y!==g;y++){const w=o[c+y+g],D=o[c+y+a]*I,p=o[E+y+g],f=o[E+y]*I;n[y]=d*w+M*D+Q*p+C*f}return n}}const uX=new wt;class mX extends Fm{interpolate_(A,t,e,i){const n=super.interpolate_(A,t,e,i);return uX.fromArray(n).normalize().toArray(n),n}}const ps={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},Dr={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},bm={9728:xt,9729:Yt,9984:BI,9985:Sa,9986:ng,9987:Oi},Wm={33071:Gi,33648:Pa,10497:Ue},j0={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},R0={POSITION:"position",NORMAL:"normal",TANGENT:"tangent",TEXCOORD_0:"uv",TEXCOORD_1:"uv1",TEXCOORD_2:"uv2",TEXCOORD_3:"uv3",COLOR_0:"color",WEIGHTS_0:"skinWeight",JOINTS_0:"skinIndex"},bo={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},PX={CUBICSPLINE:void 0,LINEAR:ja,STEP:Ka},Z0={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function SX(s){return s.DefaultMaterial===void 0&&(s.DefaultMaterial=new mo({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:es})),s.DefaultMaterial}function Gg(s,A,t){for(const e in t.extensions)s[e]===void 0&&(A.userData.gltfExtensions=A.userData.gltfExtensions||{},A.userData.gltfExtensions[e]=t.extensions[e])}function hn(s,A){A.extras!==void 0&&(typeof A.extras=="object"?Object.assign(s.userData,A.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+A.extras))}function YX(s,A,t){let e=!1,i=!1,n=!1;for(let r=0,I=A.length;r<I;r++){const l=A[r];if(l.POSITION!==void 0&&(e=!0),l.NORMAL!==void 0&&(i=!0),l.COLOR_0!==void 0&&(n=!0),e&&i&&n)break}if(!e&&!i&&!n)return Promise.resolve(s);const o=[],g=[],a=[];for(let r=0,I=A.length;r<I;r++){const l=A[r];if(e){const h=l.POSITION!==void 0?t.getDependency("accessor",l.POSITION):s.attributes.position;o.push(h)}if(i){const h=l.NORMAL!==void 0?t.getDependency("accessor",l.NORMAL):s.attributes.normal;g.push(h)}if(n){const h=l.COLOR_0!==void 0?t.getDependency("accessor",l.COLOR_0):s.attributes.color;a.push(h)}}return Promise.all([Promise.all(o),Promise.all(g),Promise.all(a)]).then(function(r){const I=r[0],l=r[1],h=r[2];return e&&(s.morphAttributes.position=I),i&&(s.morphAttributes.normal=l),n&&(s.morphAttributes.color=h),s.morphTargetsRelative=!0,s})}function FX(s,A){if(s.updateMorphTargets(),A.weights!==void 0)for(let t=0,e=A.weights.length;t<e;t++)s.morphTargetInfluences[t]=A.weights[t];if(A.extras&&Array.isArray(A.extras.targetNames)){const t=A.extras.targetNames;if(s.morphTargetInfluences.length===t.length){s.morphTargetDictionary={};for(let e=0,i=t.length;e<i;e++)s.morphTargetDictionary[t[e]]=e}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function bX(s){let A;const t=s.extensions&&s.extensions[bt.KHR_DRACO_MESH_COMPRESSION];if(t?A="draco:"+t.bufferView+":"+t.indices+":"+N0(t.attributes):A=s.indices+":"+N0(s.attributes)+":"+s.mode,s.targets!==void 0)for(let e=0,i=s.targets.length;e<i;e++)A+=":"+N0(s.targets[e]);return A}function N0(s){let A="";const t=Object.keys(s).sort();for(let e=0,i=t.length;e<i;e++)A+=t[e]+":"+s[t[e]]+";";return A}function U0(s){switch(s){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type.")}}function WX(s){return s.search(/\.jpe?g($|\?)/i)>0||s.search(/^data\:image\/jpeg/)===0?"image/jpeg":s.search(/\.webp($|\?)/i)>0||s.search(/^data\:image\/webp/)===0?"image/webp":s.search(/\.ktx2($|\?)/i)>0||s.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}const GX=new RA;class TX{constructor(A={},t={}){this.json=A,this.extensions={},this.plugins={},this.options=t,this.cache=new iX,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let e=!1,i=-1,n=!1,o=-1;if(typeof navigator<"u"&&typeof navigator.userAgent<"u"){const g=navigator.userAgent;e=/^((?!chrome|android).)*safari/i.test(g)===!0;const a=g.match(/Version\/(\d+)/);i=e&&a?parseInt(a[1],10):-1,n=g.indexOf("Firefox")>-1,o=n?g.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||e&&i<17||n&&o<98?this.textureLoader=new kn(this.options.manager):this.textureLoader=new Qu(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new mi(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(A){this.extensions=A}setPlugins(A){this.plugins=A}parse(A,t){const e=this,i=this.json,n=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(o){return o._markDefs&&o._markDefs()}),Promise.all(this._invokeAll(function(o){return o.beforeRoot&&o.beforeRoot()})).then(function(){return Promise.all([e.getDependencies("scene"),e.getDependencies("animation"),e.getDependencies("camera")])}).then(function(o){const g={scene:o[0][i.scene||0],scenes:o[0],animations:o[1],cameras:o[2],asset:i.asset,parser:e,userData:{}};return Gg(n,g,i),hn(g,i),Promise.all(e._invokeAll(function(a){return a.afterRoot&&a.afterRoot(g)})).then(function(){for(const a of g.scenes)a.updateMatrixWorld();A(g)})}).catch(t)}_markDefs(){const A=this.json.nodes||[],t=this.json.skins||[],e=this.json.meshes||[];for(let i=0,n=t.length;i<n;i++){const o=t[i].joints;for(let g=0,a=o.length;g<a;g++)A[o[g]].isBone=!0}for(let i=0,n=A.length;i<n;i++){const o=A[i];o.mesh!==void 0&&(this._addNodeRef(this.meshCache,o.mesh),o.skin!==void 0&&(e[o.mesh].isSkinnedMesh=!0)),o.camera!==void 0&&this._addNodeRef(this.cameraCache,o.camera)}}_addNodeRef(A,t){t!==void 0&&(A.refs[t]===void 0&&(A.refs[t]=A.uses[t]=0),A.refs[t]++)}_getNodeRef(A,t,e){if(A.refs[t]<=1)return e;const i=e.clone(),n=(o,g)=>{const a=this.associations.get(o);a!=null&&this.associations.set(g,a);for(const[r,I]of o.children.entries())n(I,g.children[r])};return n(e,i),i.name+="_instance_"+A.uses[t]++,i}_invokeOne(A){const t=Object.values(this.plugins);t.push(this);for(let e=0;e<t.length;e++){const i=A(t[e]);if(i)return i}return null}_invokeAll(A){const t=Object.values(this.plugins);t.unshift(this);const e=[];for(let i=0;i<t.length;i++){const n=A(t[i]);n&&e.push(n)}return e}getDependency(A,t){const e=A+":"+t;let i=this.cache.get(e);if(!i){switch(A){case"scene":i=this.loadScene(t);break;case"node":i=this._invokeOne(function(n){return n.loadNode&&n.loadNode(t)});break;case"mesh":i=this._invokeOne(function(n){return n.loadMesh&&n.loadMesh(t)});break;case"accessor":i=this.loadAccessor(t);break;case"bufferView":i=this._invokeOne(function(n){return n.loadBufferView&&n.loadBufferView(t)});break;case"buffer":i=this.loadBuffer(t);break;case"material":i=this._invokeOne(function(n){return n.loadMaterial&&n.loadMaterial(t)});break;case"texture":i=this._invokeOne(function(n){return n.loadTexture&&n.loadTexture(t)});break;case"skin":i=this.loadSkin(t);break;case"animation":i=this._invokeOne(function(n){return n.loadAnimation&&n.loadAnimation(t)});break;case"camera":i=this.loadCamera(t);break;default:if(i=this._invokeOne(function(n){return n!=this&&n.getDependency&&n.getDependency(A,t)}),!i)throw new Error("Unknown type: "+A);break}this.cache.add(e,i)}return i}getDependencies(A){let t=this.cache.get(A);if(!t){const e=this,i=this.json[A+(A==="mesh"?"es":"s")]||[];t=Promise.all(i.map(function(n,o){return e.getDependency(A,o)})),this.cache.add(A,t)}return t}loadBuffer(A){const t=this.json.buffers[A],e=this.fileLoader;if(t.type&&t.type!=="arraybuffer")throw new Error("THREE.GLTFLoader: "+t.type+" buffer type is not supported.");if(t.uri===void 0&&A===0)return Promise.resolve(this.extensions[bt.KHR_BINARY_GLTF].body);const i=this.options;return new Promise(function(n,o){e.load(Ns.resolveURL(t.uri,i.path),n,void 0,function(){o(new Error('THREE.GLTFLoader: Failed to load buffer "'+t.uri+'".'))})})}loadBufferView(A){const t=this.json.bufferViews[A];return this.getDependency("buffer",t.buffer).then(function(e){const i=t.byteLength||0,n=t.byteOffset||0;return e.slice(n,n+i)})}loadAccessor(A){const t=this,e=this.json,i=this.json.accessors[A];if(i.bufferView===void 0&&i.sparse===void 0){const o=j0[i.type],g=Dr[i.componentType],a=i.normalized===!0,r=new g(i.count*o);return Promise.resolve(new yt(r,o,a))}const n=[];return i.bufferView!==void 0?n.push(this.getDependency("bufferView",i.bufferView)):n.push(null),i.sparse!==void 0&&(n.push(this.getDependency("bufferView",i.sparse.indices.bufferView)),n.push(this.getDependency("bufferView",i.sparse.values.bufferView))),Promise.all(n).then(function(o){const g=o[0],a=j0[i.type],r=Dr[i.componentType],I=r.BYTES_PER_ELEMENT,l=I*a,h=i.byteOffset||0,B=i.bufferView!==void 0?e.bufferViews[i.bufferView].byteStride:void 0,E=i.normalized===!0;let c,Q;if(B&&B!==l){const C=Math.floor(h/B),d="InterleavedBuffer:"+i.bufferView+":"+i.componentType+":"+C+":"+i.count;let M=t.cache.get(d);M||(c=new r(g,C*B,i.count*B/I),M=new va(c,B/I),t.cache.add(d,M)),Q=new ji(M,a,h%B/I,E)}else g===null?c=new r(i.count*a):c=new r(g,h,i.count*a),Q=new yt(c,a,E);if(i.sparse!==void 0){const C=j0.SCALAR,d=Dr[i.sparse.indices.componentType],M=i.sparse.indices.byteOffset||0,y=i.sparse.values.byteOffset||0,w=new d(o[1],M,i.sparse.count*C),D=new r(o[2],y,i.sparse.count*a);g!==null&&(Q=new yt(Q.array.slice(),Q.itemSize,Q.normalized)),Q.normalized=!1;for(let p=0,f=w.length;p<f;p++){const u=w[p];if(Q.setX(u,D[p*a]),a>=2&&Q.setY(u,D[p*a+1]),a>=3&&Q.setZ(u,D[p*a+2]),a>=4&&Q.setW(u,D[p*a+3]),a>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}Q.normalized=E}return Q})}loadTexture(A){const t=this.json,e=this.options,n=t.textures[A].source,o=t.images[n];let g=this.textureLoader;if(o.uri){const a=e.manager.getHandler(o.uri);a!==null&&(g=a)}return this.loadTextureImage(A,n,g)}loadTextureImage(A,t,e){const i=this,n=this.json,o=n.textures[A],g=n.images[t],a=(g.uri||g.bufferView)+":"+o.sampler;if(this.textureCache[a])return this.textureCache[a];const r=this.loadImageSource(t,e).then(function(I){I.flipY=!1,I.name=o.name||g.name||"",I.name===""&&typeof g.uri=="string"&&g.uri.startsWith("data:image/")===!1&&(I.name=g.uri);const h=(n.samplers||{})[o.sampler]||{};return I.magFilter=bm[h.magFilter]||Yt,I.minFilter=bm[h.minFilter]||Oi,I.wrapS=Wm[h.wrapS]||Ue,I.wrapT=Wm[h.wrapT]||Ue,I.generateMipmaps=!I.isCompressedTexture&&I.minFilter!==xt&&I.minFilter!==Yt,i.associations.set(I,{textures:A}),I}).catch(function(){return null});return this.textureCache[a]=r,r}loadImageSource(A,t){const e=this,i=this.json,n=this.options;if(this.sourceCache[A]!==void 0)return this.sourceCache[A].then(l=>l.clone());const o=i.images[A],g=self.URL||self.webkitURL;let a=o.uri||"",r=!1;if(o.bufferView!==void 0)a=e.getDependency("bufferView",o.bufferView).then(function(l){r=!0;const h=new Blob([l],{type:o.mimeType});return a=g.createObjectURL(h),a});else if(o.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+A+" is missing URI and bufferView");const I=Promise.resolve(a).then(function(l){return new Promise(function(h,B){let E=h;t.isImageBitmapLoader===!0&&(E=function(c){const Q=new Ft(c);Q.needsUpdate=!0,h(Q)}),t.load(Ns.resolveURL(l,n.path),E,void 0,B)})}).then(function(l){return r===!0&&g.revokeObjectURL(a),hn(l,o),l.userData.mimeType=o.mimeType||WX(o.uri),l}).catch(function(l){throw console.error("THREE.GLTFLoader: Couldn't load texture",a),l});return this.sourceCache[A]=I,I}assignTexture(A,t,e,i){const n=this;return this.getDependency("texture",e.index).then(function(o){if(!o)return null;if(e.texCoord!==void 0&&e.texCoord>0&&(o=o.clone(),o.channel=e.texCoord),n.extensions[bt.KHR_TEXTURE_TRANSFORM]){const g=e.extensions!==void 0?e.extensions[bt.KHR_TEXTURE_TRANSFORM]:void 0;if(g){const a=n.associations.get(o);o=n.extensions[bt.KHR_TEXTURE_TRANSFORM].extendTexture(o,g),n.associations.set(o,a)}}return i!==void 0&&(o.colorSpace=i),A[t]=o,o})}assignFinalMaterial(A){const t=A.geometry;let e=A.material;const i=t.attributes.tangent===void 0,n=t.attributes.color!==void 0,o=t.attributes.normal===void 0;if(A.isPoints){const g="PointsMaterial:"+e.uuid;let a=this.cache.get(g);a||(a=new QC,Ie.prototype.copy.call(a,e),a.color.copy(e.color),a.map=e.map,a.sizeAttenuation=!1,this.cache.add(g,a)),e=a}else if(A.isLine){const g="LineBasicMaterial:"+e.uuid;let a=this.cache.get(g);a||(a=new se,Ie.prototype.copy.call(a,e),a.color.copy(e.color),a.map=e.map,this.cache.add(g,a)),e=a}if(i||n||o){let g="ClonedMaterial:"+e.uuid+":";i&&(g+="derivative-tangents:"),n&&(g+="vertex-colors:"),o&&(g+="flat-shading:");let a=this.cache.get(g);a||(a=e.clone(),n&&(a.vertexColors=!0),o&&(a.flatShading=!0),i&&(a.normalScale&&(a.normalScale.y*=-1),a.clearcoatNormalScale&&(a.clearcoatNormalScale.y*=-1)),this.cache.add(g,a),this.associations.set(a,this.associations.get(e))),e=a}A.material=e}getMaterialType(){return mo}loadMaterial(A){const t=this,e=this.json,i=this.extensions,n=e.materials[A];let o;const g={},a=n.extensions||{},r=[];if(a[bt.KHR_MATERIALS_UNLIT]){const l=i[bt.KHR_MATERIALS_UNLIT];o=l.getMaterialType(),r.push(l.extendParams(g,n,t))}else{const l=n.pbrMetallicRoughness||{};if(g.color=new XA(1,1,1),g.opacity=1,Array.isArray(l.baseColorFactor)){const h=l.baseColorFactor;g.color.setRGB(h[0],h[1],h[2],si),g.opacity=h[3]}l.baseColorTexture!==void 0&&r.push(t.assignTexture(g,"map",l.baseColorTexture,Rt)),g.metalness=l.metallicFactor!==void 0?l.metallicFactor:1,g.roughness=l.roughnessFactor!==void 0?l.roughnessFactor:1,l.metallicRoughnessTexture!==void 0&&(r.push(t.assignTexture(g,"metalnessMap",l.metallicRoughnessTexture)),r.push(t.assignTexture(g,"roughnessMap",l.metallicRoughnessTexture))),o=this._invokeOne(function(h){return h.getMaterialType&&h.getMaterialType(A)}),r.push(Promise.all(this._invokeAll(function(h){return h.extendMaterialParams&&h.extendMaterialParams(A,g)})))}n.doubleSided===!0&&(g.side=Tt);const I=n.alphaMode||Z0.OPAQUE;if(I===Z0.BLEND?(g.transparent=!0,g.depthWrite=!1):(g.transparent=!1,I===Z0.MASK&&(g.alphaTest=n.alphaCutoff!==void 0?n.alphaCutoff:.5)),n.normalTexture!==void 0&&o!==Kt&&(r.push(t.assignTexture(g,"normalMap",n.normalTexture)),g.normalScale=new MA(1,1),n.normalTexture.scale!==void 0)){const l=n.normalTexture.scale;g.normalScale.set(l,l)}if(n.occlusionTexture!==void 0&&o!==Kt&&(r.push(t.assignTexture(g,"aoMap",n.occlusionTexture)),n.occlusionTexture.strength!==void 0&&(g.aoMapIntensity=n.occlusionTexture.strength)),n.emissiveFactor!==void 0&&o!==Kt){const l=n.emissiveFactor;g.emissive=new XA().setRGB(l[0],l[1],l[2],si)}return n.emissiveTexture!==void 0&&o!==Kt&&r.push(t.assignTexture(g,"emissiveMap",n.emissiveTexture,Rt)),Promise.all(r).then(function(){const l=new o(g);return n.name&&(l.name=n.name),hn(l,n),t.associations.set(l,{materials:A}),n.extensions&&Gg(i,l,n),l})}createUniqueName(A){const t=jt.sanitizeNodeName(A||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(A){const t=this,e=this.extensions,i=this.primitiveCache;function n(g){return e[bt.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(g,t).then(function(a){return Gm(a,g,t)})}const o=[];for(let g=0,a=A.length;g<a;g++){const r=A[g],I=bX(r),l=i[I];if(l)o.push(l.promise);else{let h;r.extensions&&r.extensions[bt.KHR_DRACO_MESH_COMPRESSION]?h=n(r):h=Gm(new et,r,t),r.mode===ps.TRIANGLE_STRIP?h=h.then(B=>um(B,LQ)):r.mode===ps.TRIANGLE_FAN&&(h=h.then(B=>um(B,Yh))),i[I]={primitive:r,promise:h},o.push(h)}}return Promise.all(o)}loadMesh(A){const t=this,e=this.json,i=this.extensions,n=e.meshes[A],o=n.primitives,g=[];for(let a=0,r=o.length;a<r;a++){const I=o[a].material===void 0?SX(this.cache):this.getDependency("material",o[a].material);g.push(I)}return g.push(t.loadGeometries(o)),Promise.all(g).then(async function(a){const r=a.slice(0,a.length-1),I=a[a.length-1],l=[];for(let B=0,E=I.length;B<E;B++){const c=I[B],Q=o[B];let C;const d=r[B];if(Q.mode===ps.TRIANGLES||Q.mode===ps.TRIANGLE_STRIP||Q.mode===ps.TRIANGLE_FAN||Q.mode===void 0){const M=n.isSkinnedMesh===!0,y=c.hasAttribute("skinIndex")&&c.hasAttribute("skinWeight");M&&y===!1&&console.warn("THREE.GLTFLoader: Missing skinIndex or skinWeight attributes. Skinning disabled."),C=M&&y?new pd(c,d):new bA(c,d),C.isSkinnedMesh===!0&&C.normalizeSkinWeights()}else if(Q.mode===ps.LINES)C=new Bi(c,d);else if(Q.mode===ps.LINE_STRIP)C=new he(c,d);else if(Q.mode===ps.LINE_LOOP)C=new er(c,d);else if(Q.mode===ps.POINTS)C=new ir(c,d);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+Q.mode);Object.keys(C.geometry.morphAttributes).length>0&&FX(C,n),C.name=t.createUniqueName(n.name||"mesh_"+A),hn(C,n),Q.extensions&&Gg(i,C,Q),t.assignFinalMaterial(C),l.push(C)}for(let B=0,E=l.length;B<E;B++)t.associations.set(l[B],{meshes:A,primitives:B});if(l.length===1)return n.extensions&&Gg(i,l[0],n),l[0];const h=new Ot;n.extensions&&Gg(i,h,n),t.associations.set(h,{meshes:A});for(let B=0,E=l.length;B<E;B++)h.add(l[B]);return h})}loadCamera(A){let t;const e=this.json.cameras[A],i=e[e.type];if(!i){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}return e.type==="perspective"?t=new Ce(rt.radToDeg(i.yfov),i.aspectRatio||1,i.znear||1,i.zfar||2e6):e.type==="orthographic"&&(t=new ze(-i.xmag,i.xmag,i.ymag,-i.ymag,i.znear,i.zfar)),e.name&&(t.name=this.createUniqueName(e.name)),hn(t,e),Promise.resolve(t)}loadSkin(A){const t=this.json.skins[A],e=[];for(let i=0,n=t.joints.length;i<n;i++)e.push(this._loadNodeShallow(t.joints[i]));return t.inverseBindMatrices!==void 0?e.push(this.getDependency("accessor",t.inverseBindMatrices)):e.push(null),Promise.all(e).then(function(i){const n=i.pop(),o=i,g=[],a=[];for(let r=0,I=o.length;r<I;r++){const l=o[r];if(l){g.push(l);const h=new RA;n!==null&&h.fromArray(n.array,r*16),a.push(h)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[r])}return new kI(g,a)})}loadAnimation(A){const t=this.json,e=this,i=t.animations[A],n=i.name?i.name:"animation_"+A,o=[],g=[],a=[],r=[],I=[];for(let l=0,h=i.channels.length;l<h;l++){const B=i.channels[l],E=i.samplers[B.sampler],c=B.target,Q=c.node,C=i.parameters!==void 0?i.parameters[E.input]:E.input,d=i.parameters!==void 0?i.parameters[E.output]:E.output;c.node!==void 0&&(o.push(this.getDependency("node",Q)),g.push(this.getDependency("accessor",C)),a.push(this.getDependency("accessor",d)),r.push(E),I.push(c))}return Promise.all([Promise.all(o),Promise.all(g),Promise.all(a),Promise.all(r),Promise.all(I)]).then(function(l){const h=l[0],B=l[1],E=l[2],c=l[3],Q=l[4],C=[];for(let M=0,y=h.length;M<y;M++){const w=h[M],D=B[M],p=E[M],f=c[M],u=Q[M];if(w===void 0)continue;w.updateMatrix&&w.updateMatrix();const Y=e._createAnimationTracks(w,D,p,f,u);if(Y)for(let b=0;b<Y.length;b++)C.push(Y[b])}const d=new lr(n,void 0,C);return hn(d,i),d})}createNodeMesh(A){const t=this.json,e=this,i=t.nodes[A];return i.mesh===void 0?null:e.getDependency("mesh",i.mesh).then(function(n){const o=e._getNodeRef(e.meshCache,i.mesh,n);return i.weights!==void 0&&o.traverse(function(g){if(g.isMesh)for(let a=0,r=i.weights.length;a<r;a++)g.morphTargetInfluences[a]=i.weights[a]}),o})}loadNode(A){const t=this.json,e=this,i=t.nodes[A],n=e._loadNodeShallow(A),o=[],g=i.children||[];for(let r=0,I=g.length;r<I;r++)o.push(e.getDependency("node",g[r]));const a=i.skin===void 0?Promise.resolve(null):e.getDependency("skin",i.skin);return Promise.all([n,Promise.all(o),a]).then(function(r){const I=r[0],l=r[1],h=r[2];h!==null&&I.traverse(function(B){B.isSkinnedMesh&&B.bind(h,GX)});for(let B=0,E=l.length;B<E;B++)I.add(l[B]);if(I.userData.pivot!==void 0&&l.length>0){const B=I.userData.pivot,E=l[0];I.pivot=new S().fromArray(B),I.position.x-=B[0],I.position.y-=B[1],I.position.z-=B[2],E.position.set(0,0,0),delete I.userData.pivot}return I})}_loadNodeShallow(A){const t=this.json,e=this.extensions,i=this;if(this.nodeCache[A]!==void 0)return this.nodeCache[A];const n=t.nodes[A],o=n.name?i.createUniqueName(n.name):"",g=[],a=i._invokeOne(function(r){return r.createNodeMesh&&r.createNodeMesh(A)});return a&&g.push(a),n.camera!==void 0&&g.push(i.getDependency("camera",n.camera).then(function(r){return i._getNodeRef(i.cameraCache,n.camera,r)})),i._invokeAll(function(r){return r.createNodeAttachment&&r.createNodeAttachment(A)}).forEach(function(r){g.push(r)}),this.nodeCache[A]=Promise.all(g).then(function(r){let I;if(n.isBone===!0?I=new gC:r.length>1?I=new Ot:r.length===1?I=r[0]:I=new Et,I!==r[0])for(let l=0,h=r.length;l<h;l++)I.add(r[l]);if(n.name&&(I.userData.name=n.name,I.name=o),hn(I,n),n.extensions&&Gg(e,I,n),n.matrix!==void 0){const l=new RA;l.fromArray(n.matrix),I.applyMatrix4(l)}else n.translation!==void 0&&I.position.fromArray(n.translation),n.rotation!==void 0&&I.quaternion.fromArray(n.rotation),n.scale!==void 0&&I.scale.fromArray(n.scale);if(!i.associations.has(I))i.associations.set(I,{});else if(n.mesh!==void 0&&i.meshCache.refs[n.mesh]>1){const l=i.associations.get(I);i.associations.set(I,{...l})}return i.associations.get(I).nodes=A,I}),this.nodeCache[A]}loadScene(A){const t=this.extensions,e=this.json.scenes[A],i=this,n=new Ot;e.name&&(n.name=i.createUniqueName(e.name)),hn(n,e),e.extensions&&Gg(t,n,e);const o=e.nodes||[],g=[];for(let a=0,r=o.length;a<r;a++)g.push(i.getDependency("node",o[a]));return Promise.all(g).then(function(a){for(let I=0,l=a.length;I<l;I++){const h=a[I];h.parent!==null?n.add(eX(h)):n.add(h)}const r=I=>{const l=new Map;for(const[h,B]of i.associations)(h instanceof Ie||h instanceof Ft)&&l.set(h,B);return I.traverse(h=>{const B=i.associations.get(h);B!=null&&l.set(h,B)}),l};return i.associations=r(n),n})}_createAnimationTracks(A,t,e,i,n){const o=[],g=A.name?A.name:A.uuid,a=[];function r(B){B.morphTargetInfluences&&a.push(B.name?B.name:B.uuid)}bo[n.path]===bo.weights?(r(A),A.isGroup&&A.children.forEach(r)):a.push(g);let I;switch(bo[n.path]){case bo.weights:I=rr;break;case bo.rotation:I=Ir;break;case bo.translation:case bo.scale:I=gl;break;default:switch(e.itemSize){case 1:I=rr;break;case 2:case 3:default:I=gl;break}break}const l=i.interpolation!==void 0?PX[i.interpolation]:ja,h=this._getArrayFromAccessor(e);for(let B=0,E=a.length;B<E;B++){const c=new I(a[B]+"."+bo[n.path],t.array,h,l);i.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(c),o.push(c)}return o}_getArrayFromAccessor(A){let t=A.array;if(A.normalized){const e=U0(t.constructor),i=new Float32Array(t.length);for(let n=0,o=t.length;n<o;n++)i[n]=t[n]*e;t=i}return t}_createCubicSplineTrackInterpolant(A){A.createInterpolant=function(e){const i=this instanceof Ir?mX:Fm;return new i(this.times,this.values,this.getValueSize()/3,e)},A.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function KX(s,A,t){const e=A.attributes,i=new vA;if(e.POSITION!==void 0){const g=t.json.accessors[e.POSITION],a=g.min,r=g.max;if(a!==void 0&&r!==void 0){if(i.set(new S(a[0],a[1],a[2]),new S(r[0],r[1],r[2])),g.normalized){const I=U0(Dr[g.componentType]);i.min.multiplyScalar(I),i.max.multiplyScalar(I)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;const n=A.targets;if(n!==void 0){const g=new S,a=new S;for(let r=0,I=n.length;r<I;r++){const l=n[r];if(l.POSITION!==void 0){const h=t.json.accessors[l.POSITION],B=h.min,E=h.max;if(B!==void 0&&E!==void 0){if(a.setX(Math.max(Math.abs(B[0]),Math.abs(E[0]))),a.setY(Math.max(Math.abs(B[1]),Math.abs(E[1]))),a.setZ(Math.max(Math.abs(B[2]),Math.abs(E[2]))),h.normalized){const c=U0(Dr[h.componentType]);a.multiplyScalar(c)}g.max(a)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}i.expandByVector(g)}s.boundingBox=i;const o=new be;i.getCenter(o.center),o.radius=i.min.distanceTo(i.max)/2,s.boundingSphere=o}function Gm(s,A,t){const e=A.attributes,i=[];function n(o,g){return t.getDependency("accessor",o).then(function(a){s.setAttribute(g,a)})}for(const o in e){const g=R0[o]||o.toLowerCase();g in s.attributes||i.push(n(e[o],g))}if(A.indices!==void 0&&!s.index){const o=t.getDependency("accessor",A.indices).then(function(g){s.setIndex(g)});i.push(o)}return ft.workingColorSpace!==si&&"COLOR_0"in e&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${ft.workingColorSpace}" not supported.`),hn(s,A),KX(s,A,t),Promise.all(i).then(function(){return A.targets!==void 0?YX(s,A.targets,t):s})}const X0="__BIM_ENGINE_SDK_ASSET_BASE__",J0="__BIM_ENGINE_SDK_ASSET_FILE_MAP__",x0="__BIM_ENGINE_SDK_ASSET_FILE_URLS__",k0="__BIM_ENGINE_SDK_ASSET_FILE_SESSION__",jX="https://unpkg.com/iflow-engine-base-3d@3.12.21/dist/",V0="https://__bim_engine_sdk_asset__/",RX=["assets/","fonts/","draco/","basis/","texture/","prompt/"];let H0=null;async function ZX(){return H0||(H0=Promise.resolve().then(()=>Hx).then(s=>s.default??s)),H0}function Tg(){return typeof globalThis<"u"?globalThis:null}function Ql(s){return s.endsWith("/")?s:`${s}/`}function Kg(s){return String(s).replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+/g,"/")}function Tm(s){return/^(?:[a-z][a-z\d+\-.]*:)?\/\//i.test(s)||/^(?:data|blob):/i.test(s)}function NX(s){return s.startsWith("./")||s.startsWith("../")}function nE(s,A){try{return A?new URL(s,A).toString():new URL(s).toString()}catch{return null}}function UX(s){return/\.zip$/i.test(s.name)}function XX(){return`${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function JX(s){return s.startsWith(V0)}function O0(){const A=Tg()?.[k0];return typeof A=="string"&&A?`${V0}${A}/`:null}function xX(s){return`${O0()??V0}${Kg(s)}`}function Km(){const A=Tg()?.[J0];return A instanceof Map?A:null}function kX(){const A=Tg()?.[x0];return Array.isArray(A)?A:[]}function jm(){const s=Tg();s&&(kX().forEach(A=>URL.revokeObjectURL(A)),delete s[J0],delete s[x0],delete s[k0])}function VX(s,A){const t=Tg();t&&(jm(),t[J0]=s,t[x0]=A,t[k0]=XX())}function HX(s,A,t){const e=Kg(A),i=new Set([e]),n=e.indexOf("dist/");n>=0&&i.add(e.slice(n+5));const o=e.indexOf("public/");o>=0&&i.add(e.slice(o+7));for(const g of RX){const a=e.indexOf(g);a>=0&&i.add(e.slice(a))}i.forEach(g=>{g&&(s.set(g,t),s.set(g.toLowerCase(),t))})}function Rm(s){const A=Km();if(!A)return null;const t=Kg(s);return A.get(t)??A.get(t.toLowerCase())??null}function Zm(s){const A=Km();if(!A)return!1;const t=Kg(s).replace(/\/?$/,"/").toLowerCase();for(const e of A.keys())if(e.toLowerCase().startsWith(t))return!0;return!1}function OX(s){if(!JX(s))return null;const A=O0();if(!A||!s.startsWith(A))return null;const t=s.slice(A.length);return Rm(t)}qd.setURLModifier(s=>OX(s)??s);async function LX(s){const A=[];for(const t of s){const e=Kg(t.webkitRelativePath||t.name);if(UX(t)){const n=await(await ZX()).loadAsync(t),o=Object.values(n.files);for(const g of o)g.dir||A.push({path:Kg(g.name),blob:await g.async("blob")});continue}A.push({path:e,blob:t})}return A}function Nm(){return typeof document<"u"&&document.baseURI?document.baseURI:typeof location<"u"&&location.href?location.href:null}function zX(s,A){const t=Ql(s);if(Tm(t))return t;const e=oE(A)||vX()||Nm();return nE(t,e||void 0)||t}function oE(s){if(!s)return null;try{const A=Nm(),t=nE(s,A||void 0)||s,e=new URL(".",t),i=e.pathname.replace(/\\/g,"/");return i.endsWith("/chunks/")?new URL("../",e).toString():A&&/\/src\//.test(i)?Ql(A):e.toString()}catch{return null}}function vX(){if(typeof document>"u")return null;const s=document.currentScript;if(s?.src)return oE(s.src);const A=document.getElementsByTagName("script");for(let t=A.length-1;t>=0;t-=1){const e=A[t]?.src;if(e&&/(?:bim-engine-sdk|iflow-engine-base|dwg-preview|gaussian)\.(?:es|umd)\.js(?:[?#].*)?$/.test(e))return oE(e)}return null}function _X(s){const A=Tg();if(A){if(!s){delete A[X0];return}A[X0]=Ql(s)}}async function L0(s){if(!s||s.length===0){jm();return}const A=Array.from(s),t=await LX(A),e=new Map,i=[];t.forEach(n=>{const o=URL.createObjectURL(n.blob);i.push(o),HX(e,n.path,o)}),VX(e,i)}async function qX(s){await L0(s?[s]:null)}function Um(s){const A=O0();if(A)return A;const e=Tg()?.[X0];return typeof e=="string"&&e.length>0?zX(e,s):Ql(jX)}function vt(s,A){if(Tm(s))return s;const t=Kg(s),e=Rm(t);if(e&&!s.endsWith("/"))return e;if(s.endsWith("/")||Zm(t)){const n=xX(t);if(Zm(t))return s.endsWith("/")?Ql(n):n}if(NX(s)){const n=nE(s,oE(A)||void 0);if(n)return n}const i=Um(A);return nE(t,i)||t}const $X=vt("/assets/worker_walk.glb",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ZA&&ZA.tagName.toUpperCase()==="SCRIPT"&&ZA.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href),AJ=Math.PI,tJ={16:"ShiftLeft",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",65:"KeyA",68:"KeyD",69:"KeyE",81:"KeyQ",32:"Space",83:"KeyS",87:"KeyW"},Ci={forward:["KeyW","ArrowUp"],backward:["KeyS","ArrowDown"],left:["KeyA","ArrowLeft"],right:["KeyD","ArrowRight"],up:["KeyQ"],down:["KeyE"],jump:["Space"],boost:["ShiftLeft","ShiftRight"]};class Xm extends os{constructor(A,t,e,i={}){super(),this._Engine=A,this.camera=t,this.object=t,this.domElement=e,this._isEnabled=!1,this.target=new S,this.auto=!1,this.applyGravity=i.applyGravity??!0,this.gravityMinHeight=!0,this.applyCollision=i.applyCollision??!0,this.positionEasing=!0,this.lookflag=1,this.lookHorizontalFlag=1,this.lookSpeed=i.lookSpeed??.003,this.moveSpeed=i.moveSpeed??.02,this.playerHeight=i.playerHeight??1.6,this.playerRadius=i.playerRadius??.3,this.cameraDistance=i.cameraDistance??2,this.cameraHeight=i.cameraHeight??0,this.targetHeight=i.targetHeight??this.playerHeight,this.cameraCollisionTargetHeight=i.cameraCollisionTargetHeight??this.playerHeight+.1,this.cameraCollisionInterval=Math.max(1,Math.floor(i.cameraCollisionInterval??20)),this.cameraCollisionPadding=i.cameraCollisionPadding??.15,this.minCameraCollisionDistance=i.minCameraCollisionDistance??.35,this.jumpSpeed=i.jumpSpeed??.24,this.jumpGravity=i.jumpGravity??.012,this.maxRotateX=i.maxPitch??Math.PI*.45,this.minPitch=i.minPitch??-Math.PI*.38,this.g=9.8,this._moveInput=new S,this._moveDirection=new S,this._rayCaster=new De,this._cameraRayCaster=new De,this._cameraCollisionFrame=0,this._lastCameraSafeDistance=null,this._fallingTime=0,this._isMouseInElement=!1,this._prevMouseX=0,this._prevMouseY=0,this._dragRotateThreshold=i.dragRotateThreshold??2,this._pointerLookActive=!1,this._externalLookActive=!1,this._scriptedMotionActive=!1,this._interactionActive=!1,this._yaw=0,this._pitch=i.initialPitch??0,this._pressedKeys=new Set,this._verticalVelocity=0,this._isJumping=!1,this._isJumpKeyDown=!1,this._jumpStartHeight=0,this.avatarRoot=new Ot,this.avatarRoot.name="ThirdPersonAvatarRoot",this.avatarRoot.visible=i.visible??!0,this.avatarMixer=null,this.avatarWalkAction=null,this._isWalkActionPlaying=!1,this._avatarAnimationTimer=new rl,this._avatarAnimationTimer.connect(document),this._avatarLoadRequestId=0,this.defaultAvatarUrl=i.avatarUrl??$X,this._ownsAvatarResources=!i.avatar,this.avatar=i.avatar||this.createDefaultAvatar(),this.avatar.name=this.avatar.name||"ThirdPersonAvatar",this.avatarRoot.add(this.avatar),!i.avatar&&this.defaultAvatarUrl&&this.loadAvatarModel(this.defaultAvatarUrl,i.avatarOptions);const n=this.isPcDevice();this.bindmousedown=n?this.onMouseDown.bind(this):this.onTouchStart.bind(this),this.bindmouseup=n?this.onMouseUp.bind(this):this.onTouchEnd.bind(this),this.bindmousemove=n?this.onMouseMove.bind(this):this.onTouchMove.bind(this),this.bindonKeyDown=this.onKeyDown.bind(this),this.bindonKeyUp=this.onKeyUp.bind(this),this.bindWindowBlur=this.onWindowBlur.bind(this),this.bindVisibilityChange=this.onVisibilityChange.bind(this),this.bindMouseEnter=this.onMouseEnter.bind(this),this.bindMouseLeave=this.onMouseLeave.bind(this),this.initAvatarPoseFromCamera()}set enabled(A){this._isEnabled!==A&&(this._isEnabled=A,A?(this.ensureAvatarInScene(),this.syncRotationStateFromCamera(),this._avatarAnimationTimer.reset(),this.addEvents(),this.updateCameraFromAvatar()):(this.removeEvents(),this.setPointerLookActive(!1),this.setExternalLookActive(!1),this.setScriptedMotionActive(!1),this.resetMovementState(),this.avatarRoot.visible=!1))}get enabled(){return this._isEnabled}setPointerLookActive(A){this._pointerLookActive=A===!0,this.syncInteractionState()}setExternalLookActive(A){this._externalLookActive=A===!0,this.syncInteractionState()}setScriptedMotionActive(A){this._scriptedMotionActive=A===!0,this.syncInteractionState()}syncInteractionState(){const A=this._pointerLookActive||this._externalLookActive||this._scriptedMotionActive||this.hasMoveInput()||this._isJumping;this._interactionActive!==A&&(this._interactionActive=A,this.dispatchEvent({type:A?"start":"end"}))}isPcDevice(){const A=this._Engine?.DeviceType??this._Engine?.deviceType;return A==="PC"||!A}createDefaultAvatar(){const A=new Ot;return A.name="ThirdPersonEmptyAvatar",A.visible=!1,A}setAvatarModel(A,t={}){if(A){if(this.clearAvatarAnimation(),this.avatar&&(this.avatarRoot.remove(this.avatar),this._ownsAvatarResources&&this.disposeObjectResources(this.avatar)),this.avatar=A,this._ownsAvatarResources=t.ownsResources===!0,A.rotation.y+=t.yawOffset??0,t.alignToFeet!==!1){const e=new vA().setFromObject(A),i=e.max.y-e.min.y;if(t.fitToPlayerHeight!==!1&&Number.isFinite(i)&&i>1e-6){const o=(t.targetHeight??this.playerHeight)/i;A.scale.multiplyScalar(o),e.setFromObject(A)}Number.isFinite(e.min.y)&&(A.position.y-=e.min.y)}A.traverse(e=>{(e.isMesh||e.isSkinnedMesh)&&(e.castShadow=!0,e.receiveShadow=!0,e.frustumCulled=!1)}),this.avatarRoot.add(A)}}loadAvatarModel(A,t={}){const e=++this._avatarLoadRequestId;new K0().load(A,n=>{if(e!==this._avatarLoadRequestId||!n?.scene)return;const o=n.scene;o.name="ThirdPersonWorkerAvatar",this.setAvatarModel(o,{alignToFeet:!0,fitToPlayerHeight:!0,ownsResources:!0,yawOffset:AJ,...t}),this.setupAvatarAnimation(o,n.animations||[])},void 0,n=>{console.warn("[ThirdPersonCameraControl] failed to load avatar model",A,n)})}setupAvatarAnimation(A,t){if(!t.length)return;this.avatarMixer=new I0(A);const e=t.find(i=>/walk|run|move/i.test(i.name))||t[0];this.avatarWalkAction=this.avatarMixer.clipAction(e),this.avatarWalkAction.enabled=!0,this.avatarWalkAction.clampWhenFinished=!1,this.avatarWalkAction.setEffectiveWeight(1),this.avatarWalkAction.paused=!0,this.avatarWalkAction.play(),this._avatarAnimationTimer.reset()}clearAvatarAnimation(){this.avatarMixer&&(this.avatarMixer.stopAllAction(),this.avatarMixer.uncacheRoot(this.avatar)),this.avatarMixer=null,this.avatarWalkAction=null,this._isWalkActionPlaying=!1}ensureAvatarInScene(){this._Engine?.scene&&(this.avatarRoot.parent||this._Engine.scene.add(this.avatarRoot),this.avatarRoot.visible=!0)}initAvatarPoseFromCamera(){if(!this.camera)return;const A=new S;this.camera.getWorldDirection(A),A.y=0,A.lengthSq()<1e-6&&A.set(0,0,-1),A.normalize(),this.setViewYaw(Math.atan2(A.x,-A.z));const t=this.targetHeight+this.cameraHeight+Math.sin(this._pitch)*this.cameraDistance,e=this.camera.position.clone().addScaledVector(A,this.cameraDistance).add(new S(0,-t,0)),i=this.getMinHeight();i!==void 0&&e.y<i&&(e.y=i),this.avatarRoot.position.copy(e),this.setViewYaw(this._yaw)}addEvents(){this.isPcDevice()?(this.domElement.addEventListener("mousedown",this.bindmousedown,!1),this.domElement.addEventListener("mouseup",this.bindmouseup,!1)):(this.domElement.addEventListener("touchstart",this.bindmousedown,!1),this.domElement.addEventListener("touchend",this.bindmouseup,!1)),this.domElement.addEventListener("mouseenter",this.bindMouseEnter,!1),this.domElement.addEventListener("mouseleave",this.bindMouseLeave,!1),window.addEventListener("keydown",this.bindonKeyDown,!1),window.addEventListener("keyup",this.bindonKeyUp,!1),window.addEventListener("blur",this.bindWindowBlur,!1),document.addEventListener("visibilitychange",this.bindVisibilityChange,!1)}removeEvents(){this.domElement.removeEventListener("touchstart",this.bindmousedown),this.domElement.removeEventListener("touchend",this.bindmouseup),this.domElement.removeEventListener("touchmove",this.bindmousemove),this.domElement.removeEventListener("mousedown",this.bindmousedown),this.domElement.removeEventListener("mouseup",this.bindmouseup),this.domElement.removeEventListener("mousemove",this.bindmousemove),this.domElement.removeEventListener("mouseenter",this.bindMouseEnter),this.domElement.removeEventListener("mouseleave",this.bindMouseLeave),window.removeEventListener("keydown",this.bindonKeyDown),window.removeEventListener("keyup",this.bindonKeyUp),window.removeEventListener("blur",this.bindWindowBlur),document.removeEventListener("visibilitychange",this.bindVisibilityChange)}onMouseEnter(){this._isMouseInElement=!0}onMouseLeave(){this._isMouseInElement=!1,this.setPointerLookActive(!1),this.setExternalLookActive(!1),this.resetMovementState()}onWindowBlur(){this.setPointerLookActive(!1),this.setExternalLookActive(!1),this.resetMovementState()}onVisibilityChange(){document.hidden&&(this.setPointerLookActive(!1),this.setExternalLookActive(!1),this.resetMovementState())}onMouseDown(A){this._isMouseInElement=!0,this.domElement.addEventListener("mousemove",this.bindmousemove,!1),this.setPointerLookActive(!0),A.preventDefault?.(),this._prevMouseX=A.screenX,this._prevMouseY=A.screenY}onMouseMove(A){if(!this._isEnabled)return;const t=A.screenX-this._prevMouseX,e=A.screenY-this._prevMouseY;Math.abs(t)+Math.abs(e)<this._dragRotateThreshold||(this.rotateByPointerDelta(t,e),this._prevMouseX=A.screenX,this._prevMouseY=A.screenY)}onMouseUp(){this.updateEngineMovingFlag(),this.setPointerLookActive(!1),this.domElement.removeEventListener("mousemove",this.bindmousemove)}onTouchStart(A){const t=A.targetTouches?.[0];t&&(this._isMouseInElement=!0,this.domElement.addEventListener("touchmove",this.bindmousemove,!1),this.setPointerLookActive(!0),A.preventDefault?.(),this._prevMouseX=t.clientX,this._prevMouseY=t.clientY)}onTouchMove(A){if(!this._isEnabled)return;const t=A.targetTouches?.[0];if(!t)return;const e=t.clientX-this._prevMouseX,i=t.clientY-this._prevMouseY;Math.abs(e)+Math.abs(i)<this._dragRotateThreshold||(this.rotateByPointerDelta(e,i),this._prevMouseX=t.clientX,this._prevMouseY=t.clientY)}onTouchEnd(){this.updateEngineMovingFlag(),this.setPointerLookActive(!1),this.domElement.removeEventListener("touchmove",this.bindmousemove)}setViewYaw(A){this._yaw=A,this.updateAvatarFacing()}getAvatarFacingYaw(){const A=-this._yaw,t=Math.sign(this._moveInput.x);return t!==0?A-t*Math.PI*.5:this._moveInput.z<0?A+Math.PI:A}updateAvatarFacing(){this.avatarRoot.rotation.y=this.getAvatarFacingYaw()}setViewPitch(A){this._pitch=rt.clamp(A,this.minPitch,this.maxRotateX)}rotateByPointerDelta(A,t){this.setViewYaw(this._yaw+A*this.lookHorizontalFlag*this.lookSpeed),this.setViewPitch(this._pitch+t*this.lookflag*this.lookSpeed),this.updateCameraFromAvatar(),this.dispatchCameraChange()}onKeyDown(A){if(!this._isEnabled||!this._isMouseInElement)return;const t=this.getEventCode(A);if(this.isManagedKey(t)){if(A.preventDefault?.(),this.hasCodeInGroup(t,Ci.jump)){A.stopPropagation?.(),this._isJumpKeyDown||(this._isJumpKeyDown=!0,this.jump());return}this._pressedKeys.add(t),this.updateEngineMovingFlag(),this.dispatchCameraChange()}}onKeyUp(A){const t=this.getEventCode(A);if(this.isManagedKey(t)){if(A.preventDefault?.(),this.hasCodeInGroup(t,Ci.jump)){A.stopPropagation?.(),this._isJumpKeyDown=!1;return}this._pressedKeys.delete(t),this.updateEngineMovingFlag()}}getEventCode(A){return A.code||tJ[A.keyCode]||A.key||""}hasPressed(A){return A.some(t=>this._pressedKeys.has(t))}isManagedKey(A){return this.hasCodeInGroup(A,Ci.forward)||this.hasCodeInGroup(A,Ci.backward)||this.hasCodeInGroup(A,Ci.left)||this.hasCodeInGroup(A,Ci.right)||this.hasCodeInGroup(A,Ci.up)||this.hasCodeInGroup(A,Ci.down)||this.hasCodeInGroup(A,Ci.jump)||this.hasCodeInGroup(A,Ci.boost)}hasCodeInGroup(A,t){return t.includes(A)}updateMoveInputFromKeys(){const A=(this.hasPressed(Ci.right)?1:0)-(this.hasPressed(Ci.left)?1:0),t=(this.hasPressed(Ci.forward)?1:0)-(this.hasPressed(Ci.backward)?1:0),e=this.applyGravity?0:(this.hasPressed(Ci.up)?1:0)-(this.hasPressed(Ci.down)?1:0);return this._moveInput.set(A,e,t),this._moveInput}hasMoveInput(){return this.updateMoveInputFromKeys().lengthSq()>0}updateEngineMovingFlag(){const A=this.hasMoveInput();this.updateAvatarFacing(),this._Engine&&(this._Engine.movefirst=A),this.syncInteractionState()}rotateX(A){this.setViewYaw(this._yaw-A*this.lookHorizontalFlag*this.lookSpeed),this.updateCameraFromAvatar()}rotateY(A){this.setViewPitch(this._pitch+A*this.lookflag*.5*this.lookSpeed),this.updateCameraFromAvatar()}setLookDirection({horizontal:A,vertical:t}={}){(A===1||A===-1)&&(this.lookHorizontalFlag=A),(t===1||t===-1)&&(this.lookflag=t)}update(){this._isEnabled&&(this.auto||(this.updateAvatarAnimation(),this.updateMoveInputFromKeys(),this.updateJump(),this.applyGravity&&!this._isJumping&&this.gravityTest(),this.moveAvatar(),this.updateCameraFromAvatar()))}moveAvatar(){this._moveDirection.set(0,0,0);const A=this.getFlatForward(),t=new S(-A.z,0,A.x).normalize();if(this._moveInput.z!==0&&this._moveDirection.addScaledVector(A,this._moveInput.z),this._moveInput.x!==0&&this._moveDirection.addScaledVector(t,this._moveInput.x),!this.applyGravity&&this._moveInput.y!==0&&(this._moveDirection.y+=this._moveInput.y),this._moveDirection.lengthSq()<=0){this.setAvatarWalking(!1),this.updateAvatarFacing(),this.updateEngineMovingFlag();return}this._moveDirection.normalize();const e=this.moveSpeed*(this.hasPressed(Ci.boost)?2:1);if(this.applyCollision&&this.isBlocked(this._moveDirection,e)){this.setAvatarWalking(!1),this.updateAvatarFacing(),this.updateEngineMovingFlag();return}this.avatarRoot.position.addScaledVector(this._moveDirection,e),this.updateAvatarFacing(),this.setAvatarWalking(this._moveInput.x!==0||this._moveInput.z!==0),this._Engine&&(this._Engine.movefirst=!0)}jump(){this._isJumping||(this._jumpStartHeight=this.avatarRoot.position.y,this._verticalVelocity=this.jumpSpeed,this._isJumping=!0,this.syncInteractionState())}updateJump(){if(!this._isJumping)return;this.avatarRoot.position.y+=this._verticalVelocity,this._verticalVelocity-=this.jumpGravity;const A=this.getJumpFloorHeight();this._verticalVelocity<=0&&this.avatarRoot.position.y<=A&&(this.setAvatarHeight(A),this._verticalVelocity=0,this._isJumping=!1,this._fallingTime=0,this.syncInteractionState())}getJumpFloorHeight(){const A=this.hitTest(new S(0,-1,0),this.playerHeight+3);if(A?.point)return A.point.y;const t=this.getMinHeight();return Math.max(this._jumpStartHeight,t??-1/0)}setAvatarWalking(A){!this.avatarWalkAction||this._isWalkActionPlaying===A||(this._isWalkActionPlaying=A,this.avatarWalkAction.paused=!1,A?this.avatarWalkAction.reset().fadeIn(.12).play():this.avatarWalkAction.fadeOut(.16))}updateAvatarAnimation(){this.avatarMixer&&(this._avatarAnimationTimer.update(),this.avatarMixer.update(this._avatarAnimationTimer.getDelta()))}getFlatForward(){return new S(Math.sin(this._yaw),0,-Math.cos(this._yaw)).normalize()}updateCameraFromAvatar(){if(!this.camera)return;const A=this.avatarRoot.position.clone().add(new S(0,this.targetHeight,0)),t=Math.cos(this._pitch)*this.cameraDistance,e=new S(-Math.sin(this._yaw)*t,this.cameraHeight+Math.sin(this._pitch)*this.cameraDistance,Math.cos(this._yaw)*t),i=A.clone().add(e);this.camera.position.copy(this.resolveCameraPosition(i)),this.camera.up.set(0,1,0),this.camera.lookAt(A),this.camera.updateMatrixWorld(!0),this.target.copy(A),this.syncSharedTargetFromAvatar(),this.dispatchEvent({type:"change"})}resolveCameraPosition(A){const t=this.getCameraCollisionTarget(),e=A.clone().sub(t),i=e.length();if(i<=1e-6)return A;const n=e.normalize();if(!this.shouldDetectCameraCollision()&&Number.isFinite(this._lastCameraSafeDistance))return t.clone().addScaledVector(n,Math.min(this._lastCameraSafeDistance,i));const o=this.hitCameraObstacle(t,n,i);if(!o)return this._lastCameraSafeDistance=i,A;const g=Math.max(o.distance-this.cameraCollisionPadding,this.minCameraCollisionDistance);return this._lastCameraSafeDistance=Math.min(g,i),t.clone().addScaledVector(n,this._lastCameraSafeDistance)}getCameraCollisionTarget(){return this.avatarRoot.position.clone().add(new S(0,this.cameraCollisionTargetHeight,0))}shouldDetectCameraCollision(){return this._cameraCollisionFrame+=1,Number.isFinite(this._lastCameraSafeDistance)?this._cameraCollisionFrame%this.cameraCollisionInterval===0:!0}getControlPosition(){return this.avatarRoot.position.clone()}setAvatarXZ(A,t,e={}){return!Number.isFinite(A)||!Number.isFinite(t)?!1:(this.avatarRoot.position.x=A,this.avatarRoot.position.z=t,e.updateCamera!==!1&&this.updateCameraFromAvatar(),this.dispatchCameraChange(),!0)}placeAvatarAtPoint(A,t={}){return A instanceof S?(this.avatarRoot.position.copy(A),this.setAvatarHeight(this.avatarRoot.position.y),this.syncRotationStateFromCamera(),this.setViewYaw(this._yaw),t.updateCamera!==!1&&(this.updateCameraFromAvatar(),this.dispatchCameraChange()),!0):!1}rotateYaw(A){return Number.isFinite(A)?(this.setViewYaw(this._yaw+A),this.updateCameraFromAvatar(),this.dispatchCameraChange(),!0):!1}syncAvatarFromCameraTarget(A=this.target,t={}){if(!this.camera||!(A instanceof S))return!1;this.target.copy(A),this.avatarRoot.position.set(A.x,A.y-this.targetHeight,A.z);const e=this.camera.position.clone().sub(A),i=Math.hypot(e.x,e.z);if(i>1e-6&&this.setViewYaw(Math.atan2(-e.x,e.z)),t.preserveCameraDistance!==!1){const n=e.y-this.cameraHeight,o=Math.hypot(i,n);Number.isFinite(o)&&o>1e-6&&(this.cameraDistance=o,this._pitch=rt.clamp(Math.atan2(n,i),this.minPitch,this.maxRotateX))}else this.syncRotationStateFromCamera();return this.syncSharedTargetFromAvatar(),this.dispatchEvent({type:"change"}),!0}flyToPoint(A,t={}){if(!(A instanceof S))return!1;const e=t.duration??500,i=this.avatarRoot.position.clone(),n=this.resolveAvatarFlightTarget(A),o=performance.now();this.resetMovementState(),this.setScriptedMotionActive(!0);const g=()=>{const a=performance.now()-o,r=Math.min(a/e,1),I=r<.5?2*r*r:1-Math.pow(-2*r+2,2)/2;this.avatarRoot.position.lerpVectors(i,n,I),this.updateCameraFromAvatar(),r<1?requestAnimationFrame(g):(this.setAvatarHeight(n.y),this.updateCameraFromAvatar(),this.setScriptedMotionActive(!1))};return requestAnimationFrame(g),!0}resolveAvatarFlightTarget(A){const t=A.clone(),e=A.clone().sub(this.avatarRoot.position);e.y=0,e.lengthSq()>1e-6&&(e.normalize(),t.addScaledVector(e,-(this.playerRadius+.2)));const i=this.getMinHeight();return this.gravityMinHeight&&i!==void 0&&t.y<i&&(t.y=i),t}syncRotationStateFromCamera(){if(!this.camera)return;const A=new S;this.camera.getWorldDirection(A);const t=A.clone();t.y=0,t.lengthSq()>1e-6&&(t.normalize(),this.setViewYaw(Math.atan2(t.x,-t.z))),this.setViewPitch(-Math.asin(A.y)),this.setViewYaw(this._yaw)}syncSharedTargetFromAvatar(){const A=[],t=e=>{!e?.target||A.includes(e)||A.push(e)};t(this),t(this._Engine?.controls),t(this._Engine?.controlModule?.orbitControls);for(const e of A)e.target.copy(this.target)}setScreenUp(A){return!A||!this.camera?!1:(this.camera.up.copy(A).normalize(),this.updateCameraFromAvatar(),!0)}gravityTest(){if(!this.applyGravity){this.setAvatarHeight(this.avatarRoot.position.y);return}let A=!0;this._fallingTime+=.01;const t=this.hitTest(new S(0,-1,0),this.playerHeight+2);if(!t)return;const e=t.point.y;if(this.positionEasing){if(e>=this.avatarRoot.position.y||e-this.avatarRoot.position.y<.2){this.setAvatarHeight(this.avatarRoot.position.y+(e-this.avatarRoot.position.y)*.08),this._fallingTime=0,A=!1;return}}else t.distance<this.playerHeight&&(this.setAvatarHeight(e),this._fallingTime=0,A=!1);A&&this.setAvatarHeight(this.avatarRoot.position.y-this.g*Math.pow(this._fallingTime,2))}setAvatarHeight(A){const t=this.getMinHeight();this.gravityMinHeight&&t!==void 0&&A<t?this.avatarRoot.position.y=t:this.avatarRoot.position.y=A}getMinHeight(){const A=this._Engine?.ToolUntils?this._Engine.ToolUntils.GetBoundingBox(this._Engine):null;return A?A.min.y:void 0}isBlocked(A,t){const e=this.hitTest(A,this.playerRadius+t+.05);return!!(e&&e.distance<this.playerRadius+t+.05)}hitCameraObstacle(A,t,e){if(!this._Engine?.handelBehaved?.handle_catch)return null;this._cameraRayCaster.ray.origin.copy(A),this._cameraRayCaster.ray.direction.copy(t).normalize(),this._cameraRayCaster.far=e;const i={},n=this._Engine.handelBehaved.handle_catch(this._cameraRayCaster,i,!1);return this._cameraRayCaster.far=1/0,!n||n.distance>=e?null:n}hitTest(A,t=1/0){const e=this.avatarRoot.position.clone().add(new S(0,this.playerHeight*.5,0));this._rayCaster.ray.origin.copy(e),this._rayCaster.ray.direction.copy(A).normalize(),this._rayCaster.far=t;const i={},n=this._Engine?.handelBehaved?.handle_catch?.(this._rayCaster,i,!1);if(this._rayCaster.far=1/0,n==null)return null;const o=n.object?.name,g=n.object?.url,a=this._Engine?.models?.find?.(r=>r.url===g);if(a&&o){const I=a.nodesMap?.get?.(o)?.infos?.[0]?.name;if(I&&(I.includes("门")||I.includes("門")||I.toLowerCase().includes("door")))return null}return n}dispatchCameraChange(){const A=new CustomEvent("bimengine:camerachange",{detail:""});window.dispatchEvent(A),this.dispatchEvent({type:"change"})}resetMovementState(){this._pressedKeys.clear(),this._moveInput.set(0,0,0),this._verticalVelocity=0,this._isJumping=!1,this._isJumpKeyDown=!1,this.updateAvatarFacing(),this.setAvatarWalking(!1),this._Engine&&(this._Engine.movefirst=!1),this.syncInteractionState()}dispose(){this.enabled=!1,this._avatarAnimationTimer.dispose(),this.avatarRoot?.parent&&this.avatarRoot.parent.remove(this.avatarRoot),this._avatarLoadRequestId++,this.clearAvatarAnimation(),this._ownsAvatarResources&&this.avatar&&this.disposeObjectResources(this.avatar)}disposeObjectResources(A){A.traverse(t=>{t.geometry&&t.geometry.dispose?.(),t.material&&(Array.isArray(t.material)?t.material.forEach(e=>e.dispose?.()):t.material.dispose?.())})}}const z0="__isModelUrlGroup",gE="__modelDepthBias",Jm=4;function xm(s){return s.__modelGroupMap instanceof Map||(s.__modelGroupMap=new Map),s.__modelGroupMap}function km(s){return s.__modelObjectIndexMap instanceof Map||(s.__modelObjectIndexMap=new Map),s.__modelObjectIndexMap}function v0(s,A){s.url=A,s.name=A,s.userData=s.userData??{},s.userData[z0]=!0}function _0(s,A){return s instanceof Ot?A==null?s.userData?.[z0]===!0:s.userData?.[z0]===!0&&s.url===A:!1}function q0(s,A){return s?.models?.find?.(t=>t?.url===A)}function dl(s,A,t){if(typeof t!="string"||t.length===0)return;const e=q0(s,A);e!=null&&(Array.isArray(e.urls)||(e.urls=[]),e.urls.includes(t)||e.urls.push(t))}function Wo(s,A){const t=xm(s),e=t.get(A);if(e&&e.parent!=null)return e;const i=q0(s,A);if(i?.group instanceof Ot&&i.group.parent!=null)return v0(i.group,A),t.set(A,i.group),i.group;const n=s?.scene?.children?.find?.(o=>o instanceof Ot?_0(o,A)?!0:o.name===A&&o.url===A:!1);return n!=null?(v0(n,A),t.set(A,n),i!=null&&(i.group=n),n):null}function Is(s,A){const t=Wo(s,A);return t==null?new RA:(t.updateWorldMatrix(!0,!1),t.matrixWorld.clone())}function jg(s,A){const t=Wo(s,A);if(t!=null)return t;const e=new Ot;v0(e,A),s.scene.add(e),xm(s).set(A,e);const n=q0(s,A);return n!=null&&(n.group=e),e}function eJ(s){const A=[],t=new Set;return(Array.isArray(s?.models)?s.models:[]).forEach(i=>{if(i?.url==null)return;const n=Wo(s,i.url);n==null||t.has(n.uuid)||(t.add(n.uuid),A.push(n))}),s?.scene?.children?.forEach?.(i=>{!_0(i)||t.has(i.uuid)||(t.add(i.uuid),A.push(i))}),A}function fl(s,A){const t=[],e=new Set;return eJ(s).forEach(n=>{n.traverse(o=>{o===n||e.has(o.uuid)||A(o)&&(e.add(o.uuid),t.push(o))})}),s?.scene?.children?.forEach?.(n=>{if(n.name=="highlightModel")e.add(n.uuid),t.push(n);else{if(e.has(n.uuid)||_0(n)||n.url==null)return;A(n)&&(e.add(n.uuid),t.push(n))}}),t}function $0(s){return fl(s,A=>A instanceof bA&&!(A instanceof ct))}function iJ(s){if(typeof s.__modelObjectIndexSeed=="number")return;let A=-1;s?.scene?.traverse?.(t=>{typeof t?.index=="number"&&Number.isFinite(t.index)&&(A=Math.max(A,t.index))}),s.__modelObjectIndexSeed=A+1}function sJ(s){iJ(s);const A=s.__modelObjectIndexSeed;return s.__modelObjectIndexSeed+=1,A}function Af(s,A,t){const e=typeof t=="number"?t:sJ(s);return A.index=e,km(s).set(e,A),e}function Vm(s){return Array.isArray(s)?s:s!=null?[s]:[]}function nJ(s){return 1+(Number.isFinite(s)?Math.abs(Math.floor(s)):0)%16*.125}function tf(s,A){const t=typeof A=="number"?A:s?.index,e=nJ(t);Vm(s?.material).forEach(i=>{i.userData=i.userData??{};const n=i.userData[gE]??{};i.userData[gE]={...n,enabled:!0,factor:1,units:e},i.polygonOffset=!0,i.polygonOffsetFactor=1,i.polygonOffsetUnits=e+(n.edgeActive?Jm:0),i.needsUpdate=!0})}function Hm(s,A){Vm(s?.material).forEach(t=>{t.userData=t.userData??{};const e=t.userData[gE]??{},i=e.enabled?e.units:t.polygonOffsetUnits??0,n=e.enabled?e.factor:t.polygonOffsetFactor??1;t.userData[gE]={...e,edgeActive:A},e.enabled||A?(t.polygonOffset=!1,t.polygonOffsetFactor=n,t.polygonOffsetUnits=i+(A?Jm:0)):t.polygonOffset=!1,t.needsUpdate=!0})}function Ds(s,A){if(!Number.isFinite(A))return;const t=km(s),e=t.get(A);if(e&&e.parent!=null)return e;e&&e.parent==null&&t.delete(A);const i=fl(s,n=>n.index===A)[0];return i!=null?(t.set(A,i),i):s?.scene?.children?.find?.(n=>n?.index===A)}class oJ{constructor(A){this.engine=A}snapModelCache=new Map;applySnapPreview(A,t,e){const i=this.engine,n=A.object.url,o=A.object.name;let g=i.modelEdge.getModelEdge(n,o);g||(g=[0,0,[]]);const a=Is(i,n),r=this.getModelSnapCache(n,o,g);i.camera.updateMatrixWorld(!0);const I=new RA().multiplyMatrices(i.camera.projectionMatrix,i.camera.matrixWorldInverse),l=i.renderer.domElement.clientWidth,h=i.renderer.domElement.clientHeight,B=new MA(t.offsetX,t.offsetY),E=new Ct,c=new S,Q=new S,C=new MA,d=new MA,M=new S;let y="face",w=null,D=null,p=100;if(e!=null){const f=A.point.clone(),u=A.normal||(A.face?A.face.normal:null);if(u&&A.object?.matrixWorld?.elements){const Y=u.clone().transformDirection(A.object.matrixWorld).normalize(),m=new S().subVectors(e,f).dot(Y),T=e.clone().sub(Y.clone().multiplyScalar(m)),F=this.projectWorldPointToScreen(T,I,l,h,C,E);if(F!=null){const j=this.getDistanceSq(F.x,F.y,B.x,B.y);j<p*4&&(p=j,w={point:T,distanceSq:j,pointxy:F.clone(),style:"vertical"},y="point")}}}for(let f=0;f<r.localPoints.length;f+=3){if(c.set(r.localPoints[f],r.localPoints[f+1],r.localPoints[f+2]).applyMatrix4(a),i.clipping&&!i.clipping.isPointInClippingRange(c))continue;const u=this.projectWorldPointToScreen(c,I,l,h,C,E);if(u==null)continue;const Y=this.getDistanceSq(u.x,u.y,B.x,B.y);Y<p&&(p=Y,w={point:c.clone(),distanceSq:Y,pointxy:u.clone(),style:"rect"})}for(let f=0;f<r.localCenters.length;f+=3){if(c.set(r.localCenters[f],r.localCenters[f+1],r.localCenters[f+2]).applyMatrix4(a),i.clipping&&!i.clipping.isPointInClippingRange(c))continue;const u=this.projectWorldPointToScreen(c,I,l,h,C,E);if(u==null)continue;const Y=this.getDistanceSq(u.x,u.y,B.x,B.y);Y<p&&(p=Y,w={point:c.clone(),distanceSq:Y,pointxy:u.clone(),style:"default"})}if(w!=null)y="point";else{for(let f=0;f<r.localLines.length;f+=6){c.set(r.localLines[f],r.localLines[f+1],r.localLines[f+2]).applyMatrix4(a),Q.set(r.localLines[f+3],r.localLines[f+4],r.localLines[f+5]).applyMatrix4(a);const u=this.projectWorldPointToScreen(c,I,l,h,C,E),Y=this.projectWorldPointToScreen(Q,I,l,h,d,E);if(u==null||Y==null)continue;const b=this.pointToLineProjection(B,u,Y),m=this.pointToLineDistanceSq(B,u,Y);if(m<p){const T=this.pointToLineProjection3D(b,c,Q,I,M);if(i.clipping&&!i.clipping.isPointInClippingRange(T))continue;D={distanceSq:m,point:T.clone(),pointxy:this.projectWorldPointToScreen(T,I,l,h,C,E)?.clone()??u.clone(),start:u.clone(),end:Y.clone(),style:"funnel"},p=m}}D!=null&&(y="line")}return y==="point"&&w!=null?(this.renderPointCandidate(w),A.point=w.point,A):y==="line"&&D!=null?(this.renderLineCandidate(D),A.point=D.point,A):(this.renderFaceCandidate(A),A)}getModelSnapCache(A,t,e){const i=`${A}::${t}`,n=Array.isArray(e?.[2])?e[2]:[],o=this.snapModelCache.get(i);if(o&&o.source===n)return o;const g=new Float32Array(n.length*3),a=new Float32Array(n.length*3),r=new Float32Array(n.length*6);let I=0,l=0,h=0;n.forEach(E=>{if(E?.[0]==null||E?.[1]==null)return;const c=E[0],Q=E[1];g[I++]=c.X,g[I++]=c.Z,g[I++]=-c.Y,a[l++]=(c.X+Q.X)*.5,a[l++]=(c.Z+Q.Z)*.5,a[l++]=(-c.Y-Q.Y)*.5,r[h++]=c.X,r[h++]=c.Z,r[h++]=-c.Y,r[h++]=Q.X,r[h++]=Q.Z,r[h++]=-Q.Y});const B={source:n,localPoints:g.subarray(0,I),localCenters:a.subarray(0,l),localLines:r.subarray(0,h)};return this.snapModelCache.set(i,B),B}projectWorldPointToScreen(A,t,e,i,n,o){if(o.set(A.x,A.y,A.z,1).applyMatrix4(t),Math.abs(o.w)<1e-10)return null;const g=1/o.w,a=o.x*g,r=o.y*g;return!Number.isFinite(a)||!Number.isFinite(r)?null:(n.set(a*e*.5+e*.5,-r*i*.5+i*.5),n)}getDistanceSq(A,t,e,i){const n=A-e,o=t-i;return n*n+o*o}pointToLineDistanceSq(A,t,e){const i=this.pointToLineProjection(A,t,e),n=t.x+(e.x-t.x)*i,o=t.y+(e.y-t.y)*i;return this.getDistanceSq(A.x,A.y,n,o)}pointToLineProjection(A,t,e){const i=new MA().subVectors(e,t),n=i.lengthSq();if(n<1e-10)return 0;const o=new MA().subVectors(A,t);return rt.clamp(o.dot(i)/n,0,1)}pointToLineProjection3D(A,t,e,i,n){const o=rt.clamp(A,0,1);if(!this.engine.camera.isPerspectiveCamera)return n.lerpVectors(t,e,o);const g=new Ct(t.x,t.y,t.z,1).applyMatrix4(i),r=new Ct(e.x,e.y,e.z,1).applyMatrix4(i).w*(1-o)+o*g.w,I=Math.abs(r)>1e-10?o*g.w/r:o;return n.lerpVectors(t,e,rt.clamp(I,0,1))}renderPointCandidate(A){const t=this.engine,e=A.pointxy;t.catchSvg.innerHTML="";const i=e.x+t.reactBoundingClientRect.left,n=e.y+t.reactBoundingClientRect.top,o=document.createElementNS("http://www.w3.org/2000/svg","polygon");switch(o.setAttribute("class","catchPoint"),A.style){case"default":o.setAttribute("points",`${i},${n-8} ${i-7},${n+4} ${i+7},${n+4}`);break;case"funnel":o.setAttribute("points",`${i-7},${n-10} ${i+7},${n-10} ${i+1},${n-1} ${i},${n} ${i+7},${n+10} ${i-7},${n+10} ${i-1},${n}`);break;case"vertical":o.setAttribute("points",`${i-12},${n} ${i},${n} ${i},${n-12}`),o.setAttribute("fill","none");break;case"rect":o.setAttribute("points",`${i-8},${n-8} ${i+8},${n-8} ${i+8},${n+8} ${i-8},${n+8}`);break}o.setAttribute("stroke","rgb(8, 223, 215)"),o.setAttribute("fill","transparent"),t.catchSvg.appendChild(o)}renderLineCandidate(A){const t=this.engine,e=A.pointxy,i=A.start,n=A.end;t.catchSvg.innerHTML="";const o=document.createElementNS("http://www.w3.org/2000/svg","line");o.setAttribute("class","catchLine"),o.setAttribute("x1",(i.x+t.reactBoundingClientRect.left).toString()),o.setAttribute("y1",(i.y+t.reactBoundingClientRect.top).toString()),o.setAttribute("x2",(n.x+t.reactBoundingClientRect.left).toString()),o.setAttribute("y2",(n.y+t.reactBoundingClientRect.top).toString()),o.setAttribute("stroke","rgb(8, 223, 215)"),o.setAttribute("stroke-width","2"),t.catchSvg.appendChild(o);const g=e.x+t.reactBoundingClientRect.left,a=e.y+t.reactBoundingClientRect.top,r=document.createElementNS("http://www.w3.org/2000/svg","polygon");r.setAttribute("class","catchPoint"),r.setAttribute("points",`${g-7},${a-10} ${g+7},${a-10} ${g+1},${a-1} ${g},${a} ${g+7},${a+10} ${g-7},${a+10} ${g-1},${a}`),r.setAttribute("stroke","rgb(8, 223, 215)"),r.setAttribute("fill","transparent"),t.catchSvg.appendChild(r)}renderFaceCandidate(A){const t=this.engine,e=A.point.clone(),i=A.normal||(A.face?A.face.normal:null),n=(i?i.clone():new S(0,0,1)).normalize(),o=Math.abs(n.y)<.9?new S(0,1,0):new S(1,0,0),g=new S().crossVectors(n,o).normalize(),a=new S().crossVectors(n,g).normalize(),r=20,I=new gi(t.camera,t.renderer,t.scene),l=I.worldToScreen(e),h=I.worldToScreen(new S().copy(e).add(g)),B=Math.sqrt((h.x-l.x)**2+(h.y-l.y)**2),E=B>0?r/B:.2,C=[new S().copy(g).add(a).multiplyScalar(E),new S().copy(g).sub(a).multiplyScalar(E),new S().copy(g).multiplyScalar(-1).sub(a).multiplyScalar(E),new S().copy(g).multiplyScalar(-1).add(a).multiplyScalar(E)].map(M=>new S().copy(e).add(M)).map(M=>I.worldToScreen(M));t.catchSvg.innerHTML="";const d=document.createElementNS("http://www.w3.org/2000/svg","polygon");d.setAttribute("class","catchFace"),d.setAttribute("points",C.map(M=>`${M.x+t.reactBoundingClientRect.left},${M.y+t.reactBoundingClientRect.top}`).join(" ")),d.setAttribute("fill","rgba(1, 238, 255, 0.2)"),d.setAttribute("stroke","rgb(0, 255, 247)"),d.setAttribute("stroke-width","1"),t.catchSvg.appendChild(d)}}function ef(s){const A={self:null,options:null,mouseDownTime:0,mouseDownPosition:null,lastClickTime:0,touchLongPressTimer:null,touchLongPressActive:!1,touchLatestEvent:null,touchStartPosition:null,touchMagnifierCanvas:null,touchMagnifierContext:null,touchInputMode:null,touchPointerId:null,touchControlsSnapshot:null,mouseMoveFrame:null,latestMouseMoveEvent:null},t=800,e=28,i=132,n=44,o=168,g=new oJ(s);A.handle_catch=function(_,G,x=!0,U=!0){const J=A.options;A.options={...J??{},showCatch:x};try{return BA(_,G,!0,U)}finally{A.options=J}},A.init=function(_,G){A.self!=null&&A.self.disActive!=null&&A.self.type!=_.type&&A.self.disActive(),A.self=_,G==null&&(G={showCatch:!1}),C(),A.clearLastPoint(),A.options=G,A.isClickSimpleModel=!0},A.render=function(){A.self&&A.self.render!=null&&A.self.render()};function a(){A.mouseMoveFrame!=null&&(cancelAnimationFrame(A.mouseMoveFrame),A.mouseMoveFrame=null),A.latestMouseMoveEvent=null}A.active=function(){s.renderer.domElement.addEventListener("mousedown",T),s.renderer.domElement.addEventListener("mouseup",j),s.renderer.domElement.addEventListener("mousemove",F),s.renderer.domElement.addEventListener("touchstart",H,{capture:!0,passive:!1}),s.renderer.domElement.addEventListener("touchend",nA,{capture:!0,passive:!1}),s.renderer.domElement.addEventListener("touchcancel",nA,{capture:!0,passive:!1}),s.renderer.domElement.addEventListener("touchmove",eA,{capture:!0,passive:!1}),s.renderer.domElement.addEventListener("pointerdown",lA,!0),s.renderer.domElement.addEventListener("pointermove",oA,!0),s.renderer.domElement.addEventListener("pointerup",dA,!0),s.renderer.domElement.addEventListener("pointercancel",dA,!0),window.addEventListener("keydown",r),window.addEventListener("keyup",I)},A.disActive=function(){C(),a(),u(),s.renderer.domElement.removeEventListener("mousedown",T),s.renderer.domElement.removeEventListener("mouseup",j),s.renderer.domElement.removeEventListener("mousemove",F),s.renderer.domElement.removeEventListener("touchstart",H,!0),s.renderer.domElement.removeEventListener("touchend",nA,!0),s.renderer.domElement.removeEventListener("touchcancel",nA,!0),s.renderer.domElement.removeEventListener("touchmove",eA,!0),s.renderer.domElement.removeEventListener("pointerdown",lA,!0),s.renderer.domElement.removeEventListener("pointermove",oA,!0),s.renderer.domElement.removeEventListener("pointerup",dA,!0),s.renderer.domElement.removeEventListener("pointercancel",dA,!0),window.removeEventListener("keydown",r),window.removeEventListener("keyup",I)};function r(_){(_.keyCode===8||_.keyCode===46)&&A.self&&A.self.handelKeyDeleteDown!=null&&A.self.handelKeyDeleteDown(),_.keyCode===27&&A.self&&A.self.handelKeyEscDown!=null&&A.self.handelKeyEscDown(),_.keyCode===13&&A.self&&A.self.handelKeyEnterDown!=null&&A.self.handelKeyEnterDown(),_.keyCode===32&&A.self&&A.self.handelKeySpaceDown!=null&&A.self.handelKeySpaceDown(_),_.key==="Tab"&&A.self&&A.self.handelKeyTabDown!=null&&A.self.handelKeyTabDown(_),_.key==="Control"&&A.self&&A.self.handelKeyCtrlDown!=null&&A.self.handelKeyCtrlDown(),_.key==="Delete"&&A.self&&A.self.handelKeyDeleteDown!=null&&A.self.handelKeyDeleteDown(),_.key==="Shift"&&A.self&&A.self.handelKeyShiftDown!=null&&A.self.handelKeyShiftDown(),_.key==="Meta"&&A.self&&A.self.handelKeyMetaDown!=null&&A.self.handelKeyMetaDown()}function I(_){_.key==="Alt"&&A.self&&A.self.handelKeyAltUp!=null&&A.self.handelKeyAltUp(),_.key==="Tab"&&A.self&&A.self.handelKeyTabUp!=null&&A.self.handelKeyTabUp(),_.key==="Control"&&A.self&&A.self.handelKeyCtrlUp!=null&&A.self.handelKeyCtrlUp(),_.key==="Shift"&&A.self&&A.self.handelKeyShiftUp!=null&&A.self.handelKeyShiftUp(),_.key==="Meta"&&A.self&&A.self.handelKeyMetaUp!=null&&A.self.handelKeyMetaUp(),_.key==="Command"&&A.self&&A.self.handelKeyCommandUp!=null&&A.self.handelKeyCommandUp(),_.key==="Windows"&&A.self&&A.self.handelKeyWindowsUp!=null&&A.self.handelKeyWindowsUp()}function l(_){const G=new MA,x=s.renderer.domElement.clientWidth,U=s.renderer.domElement.clientHeight;return G.x=_.offsetX/x*2-1,G.y=-(_.offsetY/U)*2+1,G}function h(_){const G=new De,x=l(_);return G.setFromCamera(x,s.camera),G}function B(){return s?.deviceModule?.isMobile?.()===!0||s?.deviceType==="mobile"}function E(){return B()&&A.options?.showCatch===!0}function c(_){const G=typeof TouchEvent<"u"&&_?.originalEvent instanceof TouchEvent;return E()&&!G}function Q(){A.touchLongPressTimer!=null&&(clearTimeout(A.touchLongPressTimer),A.touchLongPressTimer=null)}function C(){Q(),f(),y(),A.touchLongPressActive=!1,A.touchLatestEvent=null,A.touchStartPosition=null,A.touchInputMode=null,A.touchPointerId=null}function d(_){_?.preventDefault?.(),_?.stopPropagation?.(),_?.stopImmediatePropagation?.()}function M(){const _=s?.controls;!_||A.touchControlsSnapshot||(A.touchControlsSnapshot={controls:_,enabled:_.enabled!==!1},_.enabled=!1)}function y(){const _=A.touchControlsSnapshot;_&&(_.controls&&(w(_.controls),_.controls.enabled=_.enabled),A.touchControlsSnapshot=null)}function w(_){_?._pointers?.clear?.(),typeof _?.state=="number"&&(_.state=-1),_._isInteracting=!1,_._touchDistance=0,A.touchPointerId!=null&&_.domElement?.releasePointerCapture?.(A.touchPointerId)}function D(_){const G=_.touches[0]||_.changedTouches[0];return G?new MA(G.clientX,G.clientY):null}function p(){if(A.touchMagnifierCanvas)return A.touchMagnifierCanvas;const _=document.createElement("canvas"),G=Math.max(1,window.devicePixelRatio||1);return _.width=i*G,_.height=i*G,_.style.position="fixed",_.style.width=`${i}px`,_.style.height=`${i}px`,_.style.borderRadius="50%",_.style.border="2px solid rgba(0, 255, 247, 0.95)",_.style.boxShadow="0 8px 22px rgba(0, 0, 0, 0.32)",_.style.pointerEvents="none",_.style.zIndex="1002",_.style.display="none",_.style.background="#111",document.body.appendChild(_),A.touchMagnifierCanvas=_,A.touchMagnifierContext=_.getContext("2d"),_}function f(){const _=A.touchMagnifierCanvas;_&&(_.style.display="none")}function u(){A.touchMagnifierCanvas?.remove?.(),A.touchMagnifierCanvas=null,A.touchMagnifierContext=null}function Y(_,G,x,U,J,W){const P=s?.catchSvg;if(!P?.childElementCount)return;const R=s?.reactBoundingClientRect??G.getBoundingClientRect(),q=L=>{const[O,tA]=L.split(",").map(Number);return Number.isFinite(O)&&Number.isFinite(tA)?[(O-R.left-x)/J*i*W,(tA-R.top-U)/J*i*W]:null};Array.from(P.children).forEach(L=>{const O=L.tagName.toLowerCase(),gA=(O==="line"?[`${L.getAttribute("x1")},${L.getAttribute("y1")}`,`${L.getAttribute("x2")},${L.getAttribute("y2")}`].map(q):(L.getAttribute("points")||"").trim().split(/\s+/).map(q)).filter(Boolean);gA.length<2||(_.beginPath(),_.strokeStyle=L.getAttribute("stroke")||"rgb(8, 223, 215)",_.fillStyle=L.getAttribute("fill")||"transparent",_.lineWidth=Number(L.getAttribute("stroke-width")||2)*W,_.moveTo(gA[0][0],gA[0][1]),gA.slice(1).forEach(([hA,rA])=>_.lineTo(hA,rA)),O==="polygon"&&(_.closePath(),["none","transparent"].includes(String(_.fillStyle))||_.fill()),_.stroke())})}function b(_){const G=s?.renderer?.domElement,x=p(),U=A.touchMagnifierContext;if(!G||!x||!U)return;const J=_?.catch?.point,W=J&&(s?.worldToScreen??new gi(s.camera,s.renderer,s.scene)),P=W?.worldToScreenIfVisible?.(J)??W?.worldToScreen?.(J);if(!P||!Number.isFinite(P.x)||!Number.isFinite(P.y)||P.x<0||P.y<0||P.x>G.clientWidth||P.y>G.clientHeight){f();return}const R=x.width/i,q=Math.min(window.innerWidth-i/2-8,Math.max(i/2+8,_.clientX)),L=Math.min(window.innerHeight-i-8,Math.max(8,_.clientY-o));x.style.left=`${q-i/2}px`,x.style.top=`${L}px`,x.style.display="block";const O=G.width/Math.max(1,G.clientWidth),tA=G.height/Math.max(1,G.clientHeight),gA=n,hA=Math.max(0,Math.min(G.clientWidth-gA,P.x-gA/2)),rA=Math.max(0,Math.min(G.clientHeight-gA,P.y-gA/2));U.save(),U.clearRect(0,0,x.width,x.height),U.beginPath(),U.arc(x.width/2,x.height/2,x.width/2,0,Math.PI*2),U.clip(),U.fillStyle=window.getComputedStyle(G.parentElement??document.body).backgroundColor||"#dfe8f2",U.fillRect(0,0,x.width,x.height);try{U.drawImage(G,hA*O,rA*tA,gA*O,gA*tA,0,0,x.width,x.height),Y(U,G,hA,rA,gA,R)}catch{f(),U.restore();return}U.strokeStyle="rgba(0, 255, 247, 0.9)",U.lineWidth=1.5*R,U.beginPath(),U.moveTo(x.width/2-10*R,x.height/2),U.lineTo(x.width/2+10*R,x.height/2),U.moveTo(x.width/2,x.height/2-10*R),U.lineTo(x.width/2,x.height/2+10*R),U.stroke(),U.restore()}function m(_,G=!1,x=!1,U=!0){const J=h(_);if(_.raycaster=J,G){const W=BA(J,_,x,U);_.catch=W}}function T(_){c(_)||(A.mouseDownTime=Date.now(),A.mouseDownPosition=new S(_.offsetX,_.offsetY,0),A.self&&A.self.handleMouseDown!=null&&_.button==0&&(m(_,!0,!0),_.catch!=null&&(s.engineStatus.highlightModels==null||s.engineStatus.highlightModels.length==0)&&(s.engineStatus?.suppressNextOrbitOriginPick===!0?s.engineStatus.suppressNextOrbitOriginPick=!1:s.controlModule.orbitControls.origin.set(_.catch.point.x,_.catch.point.y,_.catch.point.z)),A.self.handleMouseDown(_)))}function F(_){c(_)||A.self&&A.self.handleMouseMove!=null&&(A.latestMouseMoveEvent=_,A.mouseMoveFrame==null&&(A.mouseMoveFrame=requestAnimationFrame(()=>{const G=A.latestMouseMoveEvent;A.latestMouseMoveEvent=null,A.mouseMoveFrame=null,G&&(s.engineStatus.isFree&&m(G,!0,!0,A.isClickSimpleModel),A.self.handleMouseMove(G))})))}function j(_){if(c(_))return;const G=Date.now(),x=G-A.mouseDownTime,U=new S(_.offsetX,_.offsetY,0);A.self&&A.self.handleMouseUp!=null&&_.button==0&&(m(_,!1,!1,!1),A.self.handleMouseUp(_));const J=U.distanceTo(A.mouseDownPosition);(x<100||J==0)&&A.self&&A.self.handleMouseClick!=null&&(m(_,!0,!0,!1),G-A.lastClickTime<200?A.self.handleMouseDoubleClick!=null&&_.button==0&&A.self.handleMouseDoubleClick(_):A.self.handleMouseClick!=null&&_.button==0?A.self.handleMouseClick(_):A.self.handleRightMouseClick!=null&&_.button==2&&A.self.handleRightMouseClick(_),A.lastClickTime=Date.now())}function X(_){const G=_.touches[0]||_.changedTouches[0];if(!G)return null;const U=s.renderer.domElement.getBoundingClientRect(),J=G.clientX-U.left,W=G.clientY-U.top;return{offsetX:J,offsetY:W,button:0,clientX:G.clientX,clientY:G.clientY,preventDefault:()=>_.preventDefault(),stopPropagation:()=>_.stopPropagation(),originalEvent:_}}function v(_){const x=s.renderer.domElement.getBoundingClientRect();return{offsetX:_.clientX-x.left,offsetY:_.clientY-x.top,button:_.button??0,clientX:_.clientX,clientY:_.clientY,preventDefault:()=>_.preventDefault(),stopPropagation:()=>_.stopPropagation(),originalEvent:_}}function k(_,G,x,U=null){C(),A.touchInputMode=x,A.touchPointerId=U,A.touchLatestEvent=_,A.touchStartPosition=G,A.touchLongPressTimer=window.setTimeout(()=>{const J=A.touchLatestEvent;J&&(A.touchLongPressActive=!0,M(),A.mouseDownTime=Date.now(),A.mouseDownPosition=new S(J.offsetX,J.offsetY,0),A.self?.handleMouseMove!=null&&(m(J,!0,!0,A.isClickSimpleModel),A.self.handleMouseMove(J)),b(J))},t)}function K(_,G){A.touchLatestEvent=_;const x=A.touchStartPosition;!A.touchLongPressActive&&x&&G&&x.distanceTo(G)>e&&Q(),A.touchLongPressActive&&(A.self?.handleMouseMove!=null&&(m(_,!0,!0,A.isClickSimpleModel),A.self.handleMouseMove(_)),b(_))}function z(_){Q(),A.touchLongPressActive&&(m(_,!0,!0,A.isClickSimpleModel),A.self?.handleMouseClick!=null&&A.self.handleMouseClick(_),A.self?.handleMouseUp!=null&&A.self.handleMouseUp(_)),C()}function H(_){if(_.preventDefault(),_.touches.length!==1){C();return}const G=X(_);if(G){if(E()){k(G,D(_)??new MA(G.clientX,G.clientY),"touch");return}T(G)}}function eA(_){if(_.preventDefault(),_.touches.length!==1){C();return}const G=X(_);if(G){if(E()){A.touchLongPressActive&&d(_),K(G,D(_));return}F(G)}}function nA(_){_.preventDefault();const G=X(_);if(G){if(E()){A.touchLongPressActive&&d(_),z(G);return}j(G)}}function lA(_){if(_.pointerType!=="touch"||!E()||_.isPrimary===!1)return;const G=v(_);k(G,new MA(_.clientX,_.clientY),"pointer",_.pointerId)}function oA(_){_.pointerType!=="touch"||!E()||(A.touchLongPressActive&&d(_),A.touchInputMode==="pointer"&&(A.touchPointerId!=null&&_.pointerId!==A.touchPointerId||K(v(_),new MA(_.clientX,_.clientY))))}function dA(_){_.pointerType!=="touch"||!E()||(A.touchLongPressActive&&d(_),A.touchInputMode==="pointer"&&(A.touchPointerId!=null&&_.pointerId!==A.touchPointerId||z(v(_))))}function BA(_,G,x=!1,U=!0){if(!s.engineStatus.isFree&&x==!1){s.hoverHighLight.clearHighlight();return}if(s.engineStatus.editorMode=="simple")return;s.catchSvg.innerHTML="";let J=s.octreeBox.rayInterationModel(_,x,U);if(J=s.clipping?.filterIntersectionsByClipping(J)??J,J.length!==0)return A.options.showCatch?g.applySnapPreview(J[0],G,A.lastPoint):J[0]}return A.setLastPoint=function(_){A.lastPoint=_},A.clearLastPoint=function(){A.lastPoint=null},A}class gJ{engine;orbitControls;firstPersonControls;thirdPersonControls;isActive=!0;originDiv=null;mobileRoamControlsEl=null;mobileMovePointerId=null;mobileMoveActiveKeys=new Set;mobileMoveIntensity=0;mobileMoveSpeedBase=new WeakMap;mobileLookPointerId=null;mobileLookOffset={x:0,y:0};handelBehaved;pendingThirdPersonOptions=null;prevContainerCursor=null;roamLookDirection={horizontal:1,vertical:1};isDragging=!1;isDown=!1;containerOffset={left:0,top:0};constructor(A){this.engine=A,this.init(),this.handelBehaved=ef(this.engine),this.handelBehaved.init(this,null),this.handelBehaved.active()}init(){this.orbitControls=new pm(this.engine,this.engine.camera,this.engine.renderer.domElement),this.orbitControls.showOriginIcon=!0,this.firstPersonControls=new Dm(this.engine,this.engine.camera,this.engine.renderer.domElement),this.thirdPersonControls=new Xm(this.engine,this.engine.camera,this.engine.renderer.domElement),this.applyRoamLookDirection(this.firstPersonControls),this.applyRoamLookDirection(this.thirdPersonControls);const A=document.createElement("div");this.originDiv=A,A.className="originDiv",A.style.position="absolute",A.style.top="0px",A.style.left="0px",A.style.width="30px",A.style.height="30px",A.style.borderRadius="50%",A.style.pointerEvents="none",A.style.backgroundImage=`url(${vt("/assets/svg/rotate-orbit.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ZA&&ZA.tagName.toUpperCase()==="SCRIPT"&&ZA.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href)})`,this.engine.container.appendChild(this.originDiv)}active(){this.isActive=!0,this.orbitControls.enabled=!0}disActive(){this.isActive=!1,this.orbitControls.enabled=!1}setEngineControls(A){this.engine.controls=A,this.engine.bindControlEvents?.(A)}setMoveSpeed(A){const t=A*.1;this.firstPersonControls&&(this.firstPersonControls.moveSpeed=t,this.setMobileMoveBaseSpeed(this.firstPersonControls,t)),this.thirdPersonControls&&(this.thirdPersonControls.moveSpeed=t,this.setMobileMoveBaseSpeed(this.thirdPersonControls,t))}getMoveSpeed(){const A=this.getActiveRoamControl()||this.firstPersonControls||this.thirdPersonControls;return this.getMobileMoveBaseSpeed(A)*10}setApplyCollision(A){this.firstPersonControls&&(this.firstPersonControls.applyCollision=A),this.thirdPersonControls&&(this.thirdPersonControls.applyCollision=A)}getApplyCollision(){return(this.getActiveRoamControl()||this.firstPersonControls||this.thirdPersonControls)?.applyCollision}setApplyGravity(A){this.firstPersonControls&&(this.firstPersonControls.applyGravity=A),this.thirdPersonControls&&(this.thirdPersonControls.applyGravity=A),this.updateMobileVerticalControlsVisibility()}getApplyGravity(){return(this.getActiveRoamControl()||this.firstPersonControls||this.thirdPersonControls)?.applyGravity}setRoamLookDirection(A){(A?.horizontal===1||A?.horizontal===-1)&&(this.roamLookDirection.horizontal=A.horizontal),(A?.vertical===1||A?.vertical===-1)&&(this.roamLookDirection.vertical=A.vertical),this.applyRoamLookDirection(this.firstPersonControls),this.applyRoamLookDirection(this.thirdPersonControls)}getRoamLookDirection(){return{...this.roamLookDirection}}applyRoamLookDirection(A){A?.setLookDirection?.(this.roamLookDirection)}toggleMinMap(){this.engine.minMap.toggle()}switchFirstPersonMode(){this.engine.cameraModule.switchToPerspectiveCamera(),this.firstPersonControls&&(this.firstPersonControls.sanitizeCameraOrientation?.(),this.firstPersonControls.enabled=!1),this.thirdPersonControls&&(this.thirdPersonControls.enabled=!1),this.firstPersonControls=new Dm(this.engine,this.engine.camera,this.engine.renderer.domElement,[]),this.applyRoamLookDirection(this.firstPersonControls),this.orbitControls.enabled=!1,this.firstPersonControls.sanitizeCameraOrientation?.(),this.firstPersonControls.enabled=!0,this.firstPersonControls.isActive=!0,this.firstPersonControls.syncRotationStateFromCamera?.(),this.firstPersonControls.syncSharedTargetFromCamera?.(),this.setEngineControls(this.firstPersonControls),this.engine.worldToScreen=new gi(this.engine.camera,this.engine.renderer,this.engine.scene),this.ensureMobileRoamControls()}switchThirdPersonMode(A){this.firstPersonControls&&(this.firstPersonControls.sanitizeCameraOrientation?.(),this.firstPersonControls.enabled=!1),this.thirdPersonControls&&(this.thirdPersonControls.enabled=!1),this.beginThirdPersonPlacement(A)}createThirdPersonControl(A){const t=this.thirdPersonControls,e={moveSpeed:t?.moveSpeed,applyCollision:t?.applyCollision,applyGravity:t?.applyGravity};return t?.dispose?.(),this.thirdPersonControls=new Xm(this.engine,this.engine.camera,this.engine.renderer.domElement,{...e,...A}),this.applyRoamLookDirection(this.thirdPersonControls),this.thirdPersonControls}beginThirdPersonPlacement(A){this.pendingThirdPersonOptions=A||{},this.orbitControls.enabled=!0,this.setEngineControls(this.orbitControls),this.engine.worldToScreen=new gi(this.engine.camera,this.engine.renderer,this.engine.scene),this.removeMobileRoamControls(),this.engine.container&&(this.prevContainerCursor=this.engine.container.style.cursor||"",this.engine.container.style.cursor="crosshair")}isWaitingThirdPersonPlacement(){return this.pendingThirdPersonOptions!=null}applyThirdPersonPlacement(A){if(!this.pendingThirdPersonOptions||!(A instanceof S))return!1;const t=this.pendingThirdPersonOptions;this.pendingThirdPersonOptions=null,this.engine.container&&this.prevContainerCursor!=null&&(this.engine.container.style.cursor=this.prevContainerCursor),this.prevContainerCursor=null,this.engine.cameraModule.switchToPerspectiveCamera();const e=this.createThirdPersonControl(t);return e.placeAvatarAtPoint?.(A,{updateCamera:!1}),this.orbitControls.enabled=!1,e.enabled=!0,e.isActive=!0,e.placeAvatarAtPoint?.(A),this.setEngineControls(e),this.engine.minMap?.show?.(),this.engine.worldToScreen=new gi(this.engine.camera,this.engine.renderer,this.engine.scene),this.ensureMobileRoamControls(),!0}setThirdPersonAvatar(A,t){this.thirdPersonControls?.setAvatarModel?.(A,t)}setThirdPersonMoveSpeed(A){this.thirdPersonControls&&(this.thirdPersonControls.moveSpeed=A*.1,this.setMobileMoveBaseSpeed(this.thirdPersonControls,this.thirdPersonControls.moveSpeed))}setThirdPersonApplyCollision(A){this.thirdPersonControls&&(this.thirdPersonControls.applyCollision=A)}setThirdPersonApplyGravity(A){this.thirdPersonControls&&(this.thirdPersonControls.applyGravity=A),this.updateMobileVerticalControlsVisibility()}getOrbitTargetFromCamera(A=10){const t=this.engine.camera,e=new S;return t.getWorldDirection(e),e.lengthSq()<=1e-8&&e.set(0,0,-1),t.position.clone().add(e.normalize().multiplyScalar(A))}switchDefaultMode(A){const t=A?.preserveCameraPose===!0;this.pendingThirdPersonOptions=null,this.engine.container&&this.prevContainerCursor!=null&&(this.engine.container.style.cursor=this.prevContainerCursor),this.prevContainerCursor=null,this.firstPersonControls&&(t||this.firstPersonControls.sanitizeCameraOrientation?.(),this.firstPersonControls.enabled=!1),this.thirdPersonControls&&(this.thirdPersonControls.enabled=!1);const e=this.engine.camera,i=t?this.orbitControls.target.clone():this.getOrbitTargetFromCamera(10),n=t&&this.orbitControls.origin?.clone?this.orbitControls.origin.clone():i.clone(),o=t&&this.orbitControls._referenceUp?.clone?this.orbitControls._referenceUp.clone():void 0,g=t&&this.orbitControls._viewRight?.clone?this.orbitControls._viewRight.clone():void 0;this.orbitControls.object=e,this.orbitControls.target.copy(i),this.orbitControls.syncStateFromCamera?.(e,i,{origin:n,referenceUp:o,viewRight:g}),this.orbitControls.enabled=!0,this.setEngineControls(this.orbitControls),this.orbitControls.update(!0),this.engine.worldToScreen=new gi(this.engine.camera,this.engine.renderer,this.engine.scene),this.removeMobileRoamControls()}handleMouseUp(A){this.isDragging=!1,this.isDown=!1}handleMouseMove(A){this.isDown?this.isDragging=!0:this.isDragging=!1}handleMouseDown(A){this.isDown=!0}handleMouseClick(A){this.isDragging=!1,this.isDown=!1}isMobileDevice(){return this.engine?.deviceModule?.isMobile?.()===!0||this.engine?.deviceType==="mobile"}getActiveRoamControl(){return this.firstPersonControls?.enabled?this.firstPersonControls:this.thirdPersonControls?.enabled?this.thirdPersonControls:null}getMobileMoveBaseSpeed(A){return!A||typeof A.moveSpeed!="number"?0:(this.mobileMoveSpeedBase.has(A)||this.mobileMoveSpeedBase.set(A,A.moveSpeed),this.mobileMoveSpeedBase.get(A)??A.moveSpeed)}setMobileMoveBaseSpeed(A,t){!A||typeof t!="number"||this.mobileMoveSpeedBase.set(A,t)}restoreMobileMoveSpeed(){[this.firstPersonControls,this.thirdPersonControls].forEach(A=>{A&&typeof A.moveSpeed=="number"&&this.mobileMoveSpeedBase.has(A)&&(A.moveSpeed=this.mobileMoveSpeedBase.get(A)??A.moveSpeed)})}updateMobileMoveSpeed(){const A=this.getActiveRoamControl();if(!A||typeof A.moveSpeed!="number")return;const t=this.getMobileMoveBaseSpeed(A);if(this.mobileMovePointerId==null||this.mobileMoveActiveKeys.size===0||this.mobileMoveIntensity<=0){A.moveSpeed=t;return}const e=.25;A.moveSpeed=t*(e+(1-e)*this.mobileMoveIntensity)}createVirtualKeyEvent(A,t){const i={w:{keyCode:87,code:"KeyW",key:"w"},a:{keyCode:65,code:"KeyA",key:"a"},s:{keyCode:83,code:"KeyS",key:"s"},d:{keyCode:68,code:"KeyD",key:"d"},q:{keyCode:81,code:"KeyQ",key:"q"},e:{keyCode:69,code:"KeyE",key:"e"}}[A];return{key:i.key,code:i.code,keyCode:i.keyCode,type:t?"keydown":"keyup",preventDefault(){},stopPropagation(){}}}setVirtualKey(A,t){const e=this.getActiveRoamControl();if(!e||!A)return;e._isMouseInElement=!0;const i=this.createVirtualKeyEvent(A,t);t?e.onKeyDown?.(i):e.onKeyUp?.(i)}updateMobileMoveKeys(A){const t=new Set(A);this.mobileMoveActiveKeys.forEach(e=>{t.has(e)||this.setVirtualKey(e,!1)}),t.forEach(e=>{this.mobileMoveActiveKeys.has(e)||this.setVirtualKey(e,!0)}),this.mobileMoveActiveKeys=t}releaseMobileMoveKeys(){this.mobileMoveIntensity=0,this.updateMobileMoveKeys([]),this.restoreMobileMoveSpeed()}bindVirtualButton(A,t){let e=!1,i=null;const n=()=>{e&&(e=!1,i=null,A.classList.remove("is-active"),this.setVirtualKey(t,!1))},o=a=>{a.preventDefault(),a.stopPropagation(),!e&&(e=!0,i=a.pointerId,A.classList.add("is-active"),A.setPointerCapture?.(a.pointerId),this.setVirtualKey(t,!0))},g=a=>{a.preventDefault(),a.stopPropagation(),!(!e||i!==a.pointerId)&&(A.releasePointerCapture?.(a.pointerId),n())};A.addEventListener("pointerdown",o),A.addEventListener("pointerup",g),A.addEventListener("pointercancel",g),A.addEventListener("lostpointercapture",n)}createMobileRoamButton(A,t,e=""){const i=document.createElement("button");return i.type="button",i.className=`bim-mobile-roam-button ${e}`.trim(),i.innerHTML=A,i.setAttribute("aria-label",t==="q"?"Move up":t==="e"?"Move down":A),this.bindVirtualButton(i,t),i}bindMovePad(A){const t=A.querySelector(".bim-mobile-roam-move-knob"),e=n=>{const o=A.getBoundingClientRect(),g=Math.min(o.width,o.height)*.5,a=g*.48,r=g*.22,I=n.clientX-o.left-g,l=n.clientY-o.top-g,h=Math.hypot(I,l),B=Math.min(h,a),E=h>a?a/h:1,c=I*E,Q=l*E;t&&(t.style.transform=`translate(${c}px, ${Q}px)`);const C=[];l<-r?C.push("w"):l>r&&C.push("s"),I<-r?C.push("a"):I>r&&C.push("d"),this.mobileMoveIntensity=C.length===0?0:Math.max(0,Math.min(1,(B-r)/(a-r))),this.updateMobileMoveKeys(C)};A.addEventListener("pointerdown",n=>{n.preventDefault(),n.stopPropagation(),this.mobileMovePointerId=n.pointerId,A.classList.add("is-active"),A.setPointerCapture?.(n.pointerId),e(n)}),A.addEventListener("pointermove",n=>{this.mobileMovePointerId===n.pointerId&&(n.preventDefault(),n.stopPropagation(),e(n))});const i=n=>{this.mobileMovePointerId===n.pointerId&&(n.preventDefault(),n.stopPropagation(),A.classList.remove("is-active"),A.releasePointerCapture?.(n.pointerId),this.mobileMovePointerId=null,t&&(t.style.transform=""),this.releaseMobileMoveKeys())};A.addEventListener("pointerup",i),A.addEventListener("pointercancel",i)}rotateActiveRoamView(A,t){const e=this.getActiveRoamControl();e&&(typeof e.rotateByPointerDelta=="function"?e.rotateByPointerDelta(A,t):(e.rotateX?.(A),e.rotateY?.(t*2),e.dispatchEvent?.({type:"change"}),window.dispatchEvent(new CustomEvent("bimengine:camerachange",{detail:""}))))}updateMobileLookRotation(){if(this.mobileLookPointerId==null||this.mobileLookOffset.x===0&&this.mobileLookOffset.y===0)return;const A=2.8;this.rotateActiveRoamView(this.mobileLookOffset.x*A,this.mobileLookOffset.y*A)}updateMobileVerticalControlsVisibility(){const A=this.mobileRoamControlsEl?.querySelector(".bim-mobile-roam-vertical-pad");A&&(A.style.display=this.getActiveRoamControl()?.applyGravity?"none":"flex")}ensureMobileRoamControls(){if(!this.isMobileDevice()){this.removeMobileRoamControls();return}if(this.mobileRoamControlsEl){this.mobileMovePointerId=null,this.releaseMobileMoveKeys(),this.mobileLookPointerId=null,this.mobileLookOffset={x:0,y:0},this.getActiveRoamControl()?.setExternalLookActive?.(!1),this.mobileRoamControlsEl.querySelectorAll(".is-active").forEach(n=>n.classList.remove("is-active")),this.mobileRoamControlsEl.querySelectorAll(".bim-mobile-roam-look-knob, .bim-mobile-roam-move-knob").forEach(n=>n.style.transform=""),this.firstPersonControls?.resetMovementState?.(),this.thirdPersonControls?.resetMovementState?.(),this.mobileRoamControlsEl.style.display="flex",this.updateMobileVerticalControlsVisibility();return}const A=document.createElement("div");A.className="bim-mobile-roam-controls",A.addEventListener("contextmenu",n=>n.preventDefault());const t=document.createElement("div");t.className="bim-mobile-roam-pad bim-mobile-roam-move-pad";const e=document.createElement("span");e.className="bim-mobile-roam-move-knob",t.appendChild(e),this.bindMovePad(t);const i=document.createElement("div");i.className="bim-mobile-roam-vertical-pad",i.appendChild(this.createMobileRoamButton("↑","q","is-round")),i.appendChild(this.createMobileRoamButton("↓","e","is-round")),A.appendChild(t),A.appendChild(i),this.engine.container.appendChild(A),this.mobileRoamControlsEl=A,this.updateMobileVerticalControlsVisibility()}removeMobileRoamControls(){this.mobileMovePointerId=null,this.releaseMobileMoveKeys(),this.mobileLookPointerId=null,this.mobileLookOffset={x:0,y:0},this.getActiveRoamControl()?.setExternalLookActive?.(!1),this.mobileRoamControlsEl&&(this.mobileRoamControlsEl.remove(),this.mobileRoamControlsEl=null),this.firstPersonControls?.resetMovementState?.(),this.thirdPersonControls?.resetMovementState?.()}update(){if(this.updateMobileMoveSpeed(),this.updateMobileLookRotation(),this.firstPersonControls.enabled&&this.firstPersonControls.update(),this.thirdPersonControls?.enabled&&this.thirdPersonControls.update(),this.orbitControls.enabled){const A=this.engine.controlModule.orbitControls.origin,e=this.engine.worldToScreen.worldToScreen(A);this.originDiv&&this.isDragging?(this.originDiv.style.left=e.x-15+this.engine.reactBoundingClientRect.left+"px",this.originDiv.style.top=e.y-15+this.engine.reactBoundingClientRect.top+"px",this.originDiv.style.display="block"):this.originDiv&&(this.originDiv.style.display="none")}}dispose(){this.isActive=!1,this.handelBehaved?.disActive?.(),this.orbitControls?.dispose?.(),this.firstPersonControls?.dispose?.(),this.thirdPersonControls?.dispose?.(),this.removeMobileRoamControls(),this.originDiv?.remove(),this.originDiv=null,this.orbitControls=null,this.firstPersonControls=null,this.thirdPersonControls=null,this.handelBehaved=null}}const Rg={name:"CopyShader",uniforms:{tDiffuse:{value:null},opacity:{value:1}},vertexShader:`
|
|
4221
4221
|
|
|
4222
4222
|
varying vec2 vUv;
|
|
4223
4223
|
|
|
@@ -6597,7 +6597,7 @@ void main() {
|
|
|
6597
6597
|
#include <premultiplied_alpha_fragment>
|
|
6598
6598
|
|
|
6599
6599
|
}
|
|
6600
|
-
`};class Zy extends $t{constructor(A){super({type:"LineMaterial",uniforms:oi.clone(Zi.line.uniforms),vertexShader:Zi.line.vertexShader,fragmentShader:Zi.line.fragmentShader,clipping:!0}),this.isLineMaterial=!0,this.setValues(A)}get color(){return this.uniforms.diffuse.value}set color(A){this.uniforms.diffuse.value=A}get worldUnits(){return"WORLD_UNITS"in this.defines}set worldUnits(A){A===!0!==this.worldUnits&&(this.needsUpdate=!0),A===!0?this.defines.WORLD_UNITS="":delete this.defines.WORLD_UNITS}get linewidth(){return this.uniforms.linewidth.value}set linewidth(A){this.uniforms.linewidth&&(this.uniforms.linewidth.value=A)}get dashed(){return"USE_DASH"in this.defines}set dashed(A){A===!0!==this.dashed&&(this.needsUpdate=!0),A===!0?this.defines.USE_DASH="":delete this.defines.USE_DASH}get dashScale(){return this.uniforms.dashScale.value}set dashScale(A){this.uniforms.dashScale.value=A}get dashSize(){return this.uniforms.dashSize.value}set dashSize(A){this.uniforms.dashSize.value=A}get dashOffset(){return this.uniforms.dashOffset.value}set dashOffset(A){this.uniforms.dashOffset.value=A}get gapSize(){return this.uniforms.gapSize.value}set gapSize(A){this.uniforms.gapSize.value=A}get opacity(){return this.uniforms.opacity.value}set opacity(A){this.uniforms&&(this.uniforms.opacity.value=A)}get resolution(){return this.uniforms.resolution.value}set resolution(A){this.uniforms.resolution.value.copy(A)}get alphaToCoverage(){return"USE_ALPHA_TO_COVERAGE"in this.defines}set alphaToCoverage(A){this.defines&&(A===!0!==this.alphaToCoverage&&(this.needsUpdate=!0),A===!0?this.defines.USE_ALPHA_TO_COVERAGE="":delete this.defines.USE_ALPHA_TO_COVERAGE)}}const Ny=new Ct,wW=new S,uW=new S,Qi=new Ct,di=new Ct,wn=new Ct,Uy=new S,Xy=new RA,fi=new vi,mW=new S,hQ=new vA,CQ=new be,un=new Ct;let mn,ca;function PW(s,A,t){return un.set(0,0,-A,1).applyMatrix4(s.projectionMatrix),un.multiplyScalar(1/un.w),un.x=ca/t.width,un.y=ca/t.height,un.applyMatrix4(s.projectionMatrixInverse),un.multiplyScalar(1/un.w),Math.abs(Math.max(un.x,un.y))}function U8(s,A){const t=s.matrixWorld,e=s.geometry,i=e.attributes.instanceStart,n=e.attributes.instanceEnd,o=Math.min(e.instanceCount,i.count);for(let g=0,a=o;g<a;g++){fi.start.fromBufferAttribute(i,g),fi.end.fromBufferAttribute(n,g),fi.applyMatrix4(t);const r=new S,I=new S;mn.distanceSqToSegment(fi.start,fi.end,I,r),I.distanceTo(r)<ca*.5&&A.push({point:I,pointOnLine:r,distance:mn.origin.distanceTo(I),object:s,face:null,faceIndex:g,uv:null,uv1:null})}}function X8(s,A,t){const e=A.projectionMatrix,n=s.material.resolution,o=s.matrixWorld,g=s.geometry,a=g.attributes.instanceStart,r=g.attributes.instanceEnd,I=Math.min(g.instanceCount,a.count),l=-A.near;mn.at(1,wn),wn.w=1,wn.applyMatrix4(A.matrixWorldInverse),wn.applyMatrix4(e),wn.multiplyScalar(1/wn.w),wn.x*=n.x/2,wn.y*=n.y/2,wn.z=0,Uy.copy(wn),Xy.multiplyMatrices(A.matrixWorldInverse,o);for(let h=0,B=I;h<B;h++){if(Qi.fromBufferAttribute(a,h),di.fromBufferAttribute(r,h),Qi.w=1,di.w=1,Qi.applyMatrix4(Xy),di.applyMatrix4(Xy),Qi.z>l&&di.z>l)continue;if(Qi.z>l){const M=Qi.z-di.z,y=(Qi.z-l)/M;Qi.lerp(di,y)}else if(di.z>l){const M=di.z-Qi.z,y=(di.z-l)/M;di.lerp(Qi,y)}Qi.applyMatrix4(e),di.applyMatrix4(e),Qi.multiplyScalar(1/Qi.w),di.multiplyScalar(1/di.w),Qi.x*=n.x/2,Qi.y*=n.y/2,di.x*=n.x/2,di.y*=n.y/2,fi.start.copy(Qi),fi.start.z=0,fi.end.copy(di),fi.end.z=0;const c=fi.closestPointToPointParameter(Uy,!0);fi.at(c,mW);const Q=rt.lerp(Qi.z,di.z,c),C=Q>=-1&&Q<=1,d=Uy.distanceTo(mW)<ca*.5;if(C&&d){fi.start.fromBufferAttribute(a,h),fi.end.fromBufferAttribute(r,h),fi.start.applyMatrix4(o),fi.end.applyMatrix4(o);const M=new S,y=new S;mn.distanceSqToSegment(fi.start,fi.end,y,M),t.push({point:y,pointOnLine:M,distance:mn.origin.distanceTo(y),object:s,face:null,faceIndex:h,uv:null,uv1:null})}}}class J8 extends bA{constructor(A=new DW,t=new Zy({color:Math.random()*16777215})){super(A,t),this.isLineSegments2=!0,this.type="LineSegments2"}computeLineDistances(){const A=this.geometry,t=A.attributes.instanceStart,e=A.attributes.instanceEnd,i=new Float32Array(2*t.count);for(let o=0,g=0,a=t.count;o<a;o++,g+=2)wW.fromBufferAttribute(t,o),uW.fromBufferAttribute(e,o),i[g]=g===0?0:i[g-1],i[g+1]=i[g]+wW.distanceTo(uW);const n=new JC(i,2,1);return A.setAttribute("instanceDistanceStart",new ji(n,1,0)),A.setAttribute("instanceDistanceEnd",new ji(n,1,1)),this}raycast(A,t){const e=this.material.worldUnits,i=A.camera;if(i===null&&!e&&console.error('LineSegments2: "Raycaster.camera" needs to be set in order to raycast against LineSegments2 while worldUnits is set to false.'),e===!1&&(this.material.resolution.x===0||this.material.resolution.y===0))return;const n=A.params.Line2!==void 0&&A.params.Line2.threshold||0;mn=A.ray;const o=this.matrixWorld,g=this.geometry,a=this.material;ca=a.linewidth+n,g.boundingSphere===null&&g.computeBoundingSphere(),CQ.copy(g.boundingSphere).applyMatrix4(o);let r;if(e)r=ca*.5;else{const l=Math.max(i.near,CQ.distanceToPoint(mn.origin));r=PW(i,l,a.resolution)}if(CQ.radius+=r,mn.intersectsSphere(CQ)===!1)return;g.boundingBox===null&&g.computeBoundingBox(),hQ.copy(g.boundingBox).applyMatrix4(o);let I;if(e)I=ca*.5;else{const l=Math.max(i.near,hQ.distanceToPoint(mn.origin));I=PW(i,l,a.resolution)}hQ.expandByScalar(I),mn.intersectsBox(hQ)!==!1&&(e?U8(this,t):X8(this,i,t))}onBeforeRender(A){const t=this.material.uniforms;t&&t.resolution&&(A.getViewport(Ny),this.material.uniforms.resolution.value.set(Ny.z,Ny.w))}}class SW extends DW{constructor(){super(),this.isLineGeometry=!0,this.type="LineGeometry"}setPositions(A){const t=A.length-3,e=new Float32Array(2*t);for(let i=0;i<t;i+=3)e[2*i]=A[i],e[2*i+1]=A[i+1],e[2*i+2]=A[i+2],e[2*i+3]=A[i+3],e[2*i+4]=A[i+4],e[2*i+5]=A[i+5];return super.setPositions(e),this}setColors(A){const t=A.length-3,e=new Float32Array(2*t);for(let i=0;i<t;i+=3)e[2*i]=A[i],e[2*i+1]=A[i+1],e[2*i+2]=A[i+2],e[2*i+3]=A[i+3],e[2*i+4]=A[i+4],e[2*i+5]=A[i+5];return super.setColors(e),this}setFromPoints(A){const t=A.length-1,e=new Float32Array(6*t);for(let i=0;i<t;i++)e[6*i]=A[i].x,e[6*i+1]=A[i].y,e[6*i+2]=A[i].z||0,e[6*i+3]=A[i+1].x,e[6*i+4]=A[i+1].y,e[6*i+5]=A[i+1].z||0;return super.setPositions(e),this}fromLine(A){const t=A.geometry;return this.setPositions(t.attributes.position.array),this}}class x8 extends J8{constructor(A=new SW,t=new Zy({color:Math.random()*16777215})){super(A,t),this.isLine2=!0,this.type="Line2"}}const EQ={lineType:"bezier",lineColor:"#22c55e",previewColor:"#f59e0b",pointColor:"#ffffff",selectedPointColor:"#f59e0b",pointSize:.34,lineWidth:4,sampleCount:64,roundedRadius:1,historyLimit:100},k8={bezier:"贝塞尔曲线",straight:"直线",rounded:"圆角直线"},V8={bezier:"∿",straight:"╱",rounded:"⌁"};class H8{type="path-draw";engine;root=new Ot;pointsGroup=new Ot;points=[];history=[];options={...EQ};lineType=EQ.lineType;roundedRadius=EQ.roundedRadius;line=null;previewLine=null;previewMarker=null;transformControl=null;transformHelper=null;selectedPointId=null;panel=null;pointsList=null;statusElement=null;addButton=null;completeButton=null;radiusInput=null;mode="editing";active=!1;closing=!1;transformDragging=!1;suppressNextCanvasClick=!1;controlsEnabledBeforeDrag=!0;pointSequence=0;pathId="";onKeyDown;constructor(A){this.engine=A,this.root.name="PathDrawRoot",this.pointsGroup.name="PathDrawPoints",this.root.add(this.pointsGroup),this.onKeyDown=this.handleKeyDown.bind(this)}open(A={}){this.active&&this.close(),this.options={...EQ,...A},this.pathId=A.id??`path-${Date.now()}`,this.lineType=this.options.lineType,this.roundedRadius=Math.max(0,this.options.roundedRadius),this.active=!0,this.mode="editing",this.engine.scene?.add(this.root),this.ensureTransformControl(),this.createPanel(),this.activateBehavior(),window.addEventListener("keydown",this.onKeyDown,!0),this.refreshAll()}startAddPoint(){return!this.active||this.transformDragging?!1:(this.mode="picking",this.clearSelection(),this.setStatus("请在模型上拾取位置"),this.addButton&&(this.addButton.dataset.active="true"),!0)}setLineType(A){!this.active||this.lineType===A||(this.saveHistory(),this.lineType=A,this.refreshAll(),this.emitChange())}undo(){const A=this.history.pop();return A?(this.restoreSnapshot(A),this.mode="editing",this.clearPreview(),this.refreshAll(),this.emitChange(),!0):!1}clear(){this.points.length!==0&&(this.saveHistory(),this.clearPointRecords(),this.mode="editing",this.clearPreview(),this.refreshAll(),this.emitChange())}getPathData(){if(this.points.length<2)return null;const A=this.buildSamplePoints(this.points.map(t=>t.position));return{version:1,id:this.pathId,lineType:this.lineType,coordinateSystem:"world",closed:!1,roundedRadius:this.roundedRadius,points:this.points.map((t,e)=>({id:t.id,order:e,role:this.getPointRole(e),position:this.toPlainVector(t.position)})),samples:A.map(t=>this.toPlainVector(t)),length:this.calculateLength(A)}}complete(){const A=this.getPathData();if(!A)return null;try{this.options.onComplete?.(A)}finally{this.close()}return A}isActive(){return this.active}close(){this.closeInternal(!0)}closeInternal(A){!this.active&&!this.panel||this.closing||(this.closing=!0,this.active=!1,window.removeEventListener("keydown",this.onKeyDown,!0),this.clearPreview(),this.clearPointRecords(),this.disposeLine("line"),this.detachTransformControl(),this.panel?.remove(),this.panel=null,this.pointsList=null,this.statusElement=null,this.addButton=null,this.completeButton=null,this.radiusInput=null,this.history.length=0,this.selectedPointId=null,this.root.parent?.remove(this.root),A&&this.restoreDefaultBehavior(),this.closing=!1)}dispose(){this.closeInternal(!1),this.transformControl?.dispose(),this.transformControl=null,this.transformHelper=null}update(){!this.active||!this.engine.camera||(this.transformControl&&this.transformControl.camera!==this.engine.camera&&(this.transformControl.camera=this.engine.camera),this.syncLineResolution(this.line),this.syncLineResolution(this.previewLine))}disActive(){this.closing||this.closeInternal(!1)}handleMouseMove(A){if(!this.active||this.mode!=="picking")return;const t=this.getCatchPoint(A?.catch);if(!t){this.clearPreview();return}this.updatePreview(t)}handleMouseClick(A){if(!this.active)return;if(this.suppressNextCanvasClick){this.suppressNextCanvasClick=!1;return}if(this.mode==="picking"){const e=this.getCatchPoint(A?.catch);if(!e)return;this.saveHistory();const i=this.createPointRecord(e);this.points.push(i),this.pointsGroup.add(i.mesh),this.mode="editing",this.clearPreview(),this.selectPoint(i.id),this.refreshAll(),this.emitChange();return}const t=this.pickPointMesh(A);t?this.selectPoint(t.userData.pathDrawPointId):this.clearSelection()}handelKeyEscDown(){if(this.mode==="picking"){this.mode="editing",this.clearPreview(),this.refreshPanel();return}this.clearSelection()}activateBehavior(){const A=this.engine.handelBehaved;A?.init?.(this,{showCatch:!0}),A?.active?.()}restoreDefaultBehavior(){const A=this.engine.handelBehaved;A?.self===this&&(A.disActive?.(),this.engine.interactionModule?.init?.(),this.engine.interactionModule?.active?.(),this.engine.catchSvg&&(this.engine.catchSvg.innerHTML=""))}ensureTransformControl(){if(this.transformControl){this.transformHelper&&!this.transformHelper.parent&&this.engine.scene?.add(this.transformHelper);return}!this.engine.camera||!this.engine.renderer||!this.engine.scene||(this.transformControl=new ql(this.engine.camera,this.engine.renderer.domElement),this.transformControl.setMode("translate"),this.transformControl.size=.72,this.transformControl.addEventListener("dragging-changed",A=>{if(this.transformDragging=!!A.value,this.transformDragging){this.saveHistory(),this.controlsEnabledBeforeDrag=this.engine.controls?.enabled!==!1,this.engine.controls&&(this.engine.controls.enabled=!1);return}this.engine.controls&&(this.engine.controls.enabled=this.controlsEnabledBeforeDrag),this.suppressNextCanvasClick=!0,requestAnimationFrame(()=>{this.suppressNextCanvasClick=!1}),this.refreshAll(),this.emitChange()}),this.transformControl.addEventListener("objectChange",()=>{const A=this.getSelectedPoint();A&&(A.position.copy(A.mesh.position),this.refreshLine(),this.refreshPanel(),this.emitChange())}),this.transformHelper=this.transformControl.getHelper(),this.transformHelper.visible=!1,this.engine.scene.add(this.transformHelper))}detachTransformControl(){this.transformControl?.detach(),this.transformHelper&&(this.transformHelper.visible=!1,this.transformHelper.parent?.remove(this.transformHelper))}createPointRecord(A,t){const e=new an(this.options.pointSize,18,12),i=new Kt({color:this.options.pointColor,depthTest:!1,depthWrite:!1}),n=new bA(e,i),o=t??`path-point-${++this.pointSequence}`;return n.name=o,n.position.copy(A),n.renderOrder=1002,n.userData.pathDrawPointId=o,{id:o,position:A.clone(),mesh:n}}selectPoint(A){const t=this.points.find(e=>e.id===A);!t||!this.transformControl||!this.transformHelper||(this.selectedPointId=A,this.points.forEach(e=>e.mesh.material.color.set(e.id===A?this.options.selectedPointColor:this.options.pointColor)),this.transformControl.attach(t.mesh),this.transformHelper.visible=!0,this.refreshPanel())}clearSelection(){this.selectedPointId=null,this.points.forEach(A=>A.mesh.material.color.set(this.options.pointColor)),this.transformControl?.detach(),this.transformHelper&&(this.transformHelper.visible=!1),this.refreshPanel()}getSelectedPoint(){return this.points.find(A=>A.id===this.selectedPointId)??null}getCatchPoint(A){return A?.point instanceof S?A.point.clone():null}pickPointMesh(A){if(!this.engine.camera||!this.engine.renderer)return null;const t=this.engine.renderer.domElement.clientWidth,e=this.engine.renderer.domElement.clientHeight;if(!t||!e)return null;const i=new MA(A.offsetX/t*2-1,-(A.offsetY/e)*2+1),n=new De;return n.setFromCamera(i,this.engine.camera),n.intersectObjects(this.pointsGroup.children,!1)[0]?.object??null}updatePreview(A){this.previewMarker||(this.previewMarker=new bA(new an(this.options.pointSize*.72,14,10),new Kt({color:this.options.previewColor,depthTest:!1,depthWrite:!1})),this.previewMarker.renderOrder=1003,this.root.add(this.previewMarker)),this.previewMarker.position.copy(A),this.previewMarker.visible=!0;const t=[...this.points.map(i=>i.position),A];if(t.length<2){this.disposeLine("previewLine");return}const e=this.buildSamplePoints(t);this.previewLine=this.updateLineObject(this.previewLine,e,!0)}clearPreview(){this.disposeLine("previewLine"),this.previewMarker&&(this.previewMarker.geometry.dispose(),this.previewMarker.material.dispose(),this.previewMarker.parent?.remove(this.previewMarker),this.previewMarker=null)}refreshAll(){this.refreshLine(),this.refreshPanel(),this.requestRender()}refreshLine(){if(this.points.length<2){this.disposeLine("line");return}const A=this.buildSamplePoints(this.points.map(t=>t.position));this.line=this.updateLineObject(this.line,A,!1)}updateLineObject(A,t,e){const i=new SW;if(i.setPositions(t.flatMap(g=>[g.x,g.y,g.z])),A)return A.geometry.dispose(),A.geometry=i,A.computeLineDistances(),this.syncLineResolution(A),this.requestRender(),A;const n=new Zy({color:e?this.options.previewColor:this.options.lineColor,linewidth:this.options.lineWidth,dashed:e,dashSize:.32,gapSize:.2,depthTest:!1,transparent:e,opacity:e?.82:1}),o=new x8(i,n);return o.name=e?"PathDrawPreviewLine":"PathDrawLine",o.renderOrder=e?1001:1e3,o.computeLineDistances(),this.syncLineResolution(o),this.root.add(o),this.requestRender(),o}syncLineResolution(A){const t=A?.material,e=this.engine.renderer?.domElement;!t||!e||t.resolution.set(e.clientWidth,e.clientHeight)}disposeLine(A){const t=this[A];if(!t)return;t.parent?.remove(t),t.geometry.dispose(),(Array.isArray(t.material)?t.material:[t.material]).forEach(i=>i.dispose()),this[A]=null}buildSamplePoints(A){return A.length<2?A.map(t=>t.clone()):this.lineType==="straight"?A.map(t=>t.clone()):this.lineType==="rounded"?this.sampleRoundedPolyline(A):this.sampleBezier(A)}sampleBezier(A){const t=Math.max(2,this.options.sampleCount);return Array.from({length:t+1},(e,i)=>{const n=A.map(g=>g.clone()),o=i/t;for(let g=n.length-1;g>0;g-=1)for(let a=0;a<g;a+=1)n[a].lerp(n[a+1],o);return n[0]})}sampleRoundedPolyline(A){if(A.length<3||this.roundedRadius<=0)return A.map(i=>i.clone());const t=[A[0].clone()],e=Math.max(4,Math.round(this.options.sampleCount/Math.max(1,A.length-2)));for(let i=1;i<A.length-1;i+=1){const n=A[i-1],o=A[i],g=A[i+1],a=n.distanceTo(o),r=o.distanceTo(g);if(a<1e-8||r<1e-8){t.push(o.clone());continue}const I=Math.min(this.roundedRadius,a*.5,r*.5),l=o.clone().lerp(n,I/a),h=o.clone().lerp(g,I/r);t.push(l);for(let B=1;B<=e;B+=1){const E=B/e,c=1-E;t.push(new S().addScaledVector(l,c*c).addScaledVector(o,2*c*E).addScaledVector(h,E*E))}}return t.push(A[A.length-1].clone()),t}calculateLength(A){let t=0;for(let e=1;e<A.length;e+=1)t+=A[e-1].distanceTo(A[e]);return t}getPointRole(A){return A===0?"start":A===this.points.length-1?"end":"control"}getRoleLabel(A){const t=this.getPointRole(A);return t==="start"?"起点":t==="end"?"终点":`控制点 ${A}`}saveHistory(){this.history.push(this.createSnapshot()),this.history.length>this.options.historyLimit&&this.history.shift()}createSnapshot(){return{lineType:this.lineType,roundedRadius:this.roundedRadius,points:this.points.map(A=>({id:A.id,position:A.position.toArray()}))}}restoreSnapshot(A){this.clearPointRecords(),this.lineType=A.lineType,this.roundedRadius=A.roundedRadius,A.points.forEach(t=>{const e=this.createPointRecord(new S(...t.position),t.id);this.points.push(e),this.pointsGroup.add(e.mesh)})}clearPointRecords(){this.clearSelection(),this.points.forEach(A=>{A.mesh.parent?.remove(A.mesh),A.mesh.geometry.dispose(),A.mesh.material.dispose()}),this.points.length=0}removePoint(A){const t=this.points.findIndex(i=>i.id===A);if(t<0)return;this.saveHistory();const[e]=this.points.splice(t,1);e.mesh.parent?.remove(e.mesh),e.mesh.geometry.dispose(),e.mesh.material.dispose(),this.selectedPointId===A&&this.clearSelection(),this.refreshAll(),this.emitChange()}updatePointCoordinate(A,t,e){const i=this.points.find(n=>n.id===A);!i||!Number.isFinite(e)||i.position[t]===e||(this.saveHistory(),i.position[t]=e,i.mesh.position[t]=e,this.refreshAll(),this.emitChange())}createPanel(){const A=document.createElement("div");A.dataset.pathDrawPanel="true",Object.assign(A.style,{position:"absolute",top:"56px",right:"16px",width:"310px",maxHeight:"calc(100% - 72px)",display:"flex",flexDirection:"column",background:"rgba(255, 255, 255, 0.98)",color:"#111827",border:"1px solid #d1d5db",borderRadius:"6px",boxShadow:"0 12px 28px rgba(15,23,42,0.18)",fontFamily:"Arial, sans-serif",fontSize:"12px",zIndex:"1200",overflow:"hidden"});const t=document.createElement("div");Object.assign(t.style,{display:"flex",alignItems:"center",minHeight:"40px",padding:"0 8px 0 12px",borderBottom:"1px solid #e5e7eb"});const e=document.createElement("strong");e.textContent="路径绘制",e.style.flex="1";const i=document.createElement("span");Object.assign(i.style,{color:"#64748b",marginRight:"8px"});const n=this.createIconButton("×","关闭路径绘制",()=>this.close());t.append(e,i,n),A.appendChild(t),this.statusElement=i;const o=document.createElement("div");Object.assign(o.style,{display:"grid",gridTemplateColumns:"repeat(3, 1fr)",gap:"4px",padding:"8px"}),["bezier","straight","rounded"].forEach(Q=>{const C=this.createIconButton(V8[Q],k8[Q],()=>this.setLineType(Q));C.dataset.lineType=Q,C.style.width="100%",C.style.fontSize="18px",o.appendChild(C)}),A.appendChild(o);const g=document.createElement("label");g.dataset.radiusRow="true",Object.assign(g.style,{display:"none",alignItems:"center",gap:"8px",padding:"0 10px 8px",color:"#475569"});const a=document.createElement("span");a.textContent="圆角";const r=document.createElement("input");r.type="number",r.min="0",r.step="0.1",Object.assign(r.style,{flex:"1",minWidth:"0",height:"26px",padding:"0 7px",color:"#111827",background:"#ffffff",border:"1px solid #cbd5e1",borderRadius:"4px"}),r.addEventListener("change",()=>{const Q=Number(r.value);if(!Number.isFinite(Q)||Q<0||Q===this.roundedRadius){r.value=String(this.roundedRadius);return}this.saveHistory(),this.roundedRadius=Q,this.refreshAll(),this.emitChange()}),g.append(a,r),A.appendChild(g),this.radiusInput=r;const I=document.createElement("div");Object.assign(I.style,{flex:"1",minHeight:"72px",maxHeight:"200px",overflowY:"auto",overflowX:"hidden",borderTop:"1px solid #e5e7eb"}),A.appendChild(I),this.pointsList=I;const l=document.createElement("div");Object.assign(l.style,{display:"grid",gridTemplateColumns:"1fr auto auto auto",gap:"6px",padding:"8px",borderTop:"1px solid #e5e7eb"});const h=this.createIconButton("+","添加点",()=>this.startAddPoint());h.style.width="100%";const B=this.createIconButton("↶","撤销 Ctrl+Z",()=>this.undo());B.dataset.undoButton="true";const E=this.createIconButton("⌫","清空路径",()=>this.clear());E.dataset.clearButton="true";const c=this.createIconButton("✓","完成并返回路径",()=>this.complete());c.dataset.primary="true",l.append(h,B,E,c),A.appendChild(l),this.addButton=h,this.completeButton=c,this.engine.container?.appendChild(A),this.panel=A}createIconButton(A,t,e){const i=document.createElement("button");return i.type="button",i.textContent=A,i.title=t,i.setAttribute("aria-label",t),Object.assign(i.style,{width:"32px",height:"30px",display:"inline-flex",alignItems:"center",justifyContent:"center",padding:"0",border:"1px solid #d1d5db",borderRadius:"4px",background:"#f8fafc",color:"#334155",cursor:"pointer",fontSize:"15px"}),i.addEventListener("click",e),i}refreshPanel(){if(!this.panel||!this.pointsList)return;this.setStatus(this.mode==="picking"?"拾取中":`${this.points.length} 个点`),this.addButton&&(this.addButton.dataset.active=String(this.mode==="picking"),this.addButton.style.background=this.mode==="picking"?"#ffedd5":"#f8fafc",this.addButton.style.borderColor=this.mode==="picking"?"#f97316":"#d1d5db",this.addButton.style.color=this.mode==="picking"?"#9a3412":"#334155"),this.panel.querySelectorAll("[data-line-type]").forEach(i=>{const n=i.dataset.lineType===this.lineType;i.style.background=n?"#dcfce7":"#f8fafc",i.style.borderColor=n?"#22c55e":"#d1d5db",i.style.color=n?"#166534":"#334155"});const A=this.panel.querySelector("[data-radius-row]");A&&(A.style.display=this.lineType==="rounded"?"flex":"none"),this.radiusInput&&(this.radiusInput.value=String(this.roundedRadius));const t=this.panel.querySelector("[data-undo-button]"),e=this.panel.querySelector("[data-clear-button]");this.setButtonDisabled(t,this.history.length===0),this.setButtonDisabled(e,this.points.length===0),this.setButtonDisabled(this.completeButton,this.points.length<2),this.renderPointRows()}renderPointRows(){if(this.pointsList){if(this.pointsList.innerHTML="",this.points.length===0){const A=document.createElement("div");A.textContent="暂无点位",Object.assign(A.style,{padding:"24px 12px",textAlign:"center",color:"#94a3b8"}),this.pointsList.appendChild(A);return}this.points.forEach((A,t)=>{const e=document.createElement("div");Object.assign(e.style,{display:"grid",gridTemplateColumns:"64px repeat(3, minmax(0, 1fr)) 28px",gap:"4px",alignItems:"center",height:"40px",boxSizing:"border-box",padding:"5px 8px",cursor:"pointer",background:A.id===this.selectedPointId?"#fef3c7":"#ffffff",borderBottom:"1px solid #eef2f7"}),e.addEventListener("click",()=>this.selectPoint(A.id));const i=document.createElement("span");i.textContent=this.getRoleLabel(t),i.title=i.textContent,Object.assign(i.style,{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"#334155"}),e.appendChild(i),["x","y","z"].forEach(o=>{const g=document.createElement("input");g.type="number",g.step="0.001",g.value=A.position[o].toFixed(3),g.title=o.toUpperCase(),Object.assign(g.style,{width:"100%",minWidth:"0",height:"25px",padding:"0 4px",boxSizing:"border-box",color:"#1f2937",background:"#ffffff",border:"1px solid #cbd5e1",borderRadius:"3px",fontSize:"11px"}),g.addEventListener("click",a=>a.stopPropagation()),g.addEventListener("change",()=>this.updatePointCoordinate(A.id,o,Number(g.value))),e.appendChild(g)});const n=this.createIconButton("×",`删除${this.getRoleLabel(t)}`,()=>this.removePoint(A.id));n.style.width="28px",n.style.height="25px",n.addEventListener("click",o=>o.stopPropagation()),e.appendChild(n),this.pointsList?.appendChild(e)})}}setButtonDisabled(A,t){A&&(A.disabled=t,A.style.opacity=t?"0.4":"1",A.style.cursor=t?"not-allowed":"pointer",A.dataset.primary==="true"&&(A.style.background=t?"#f1f5f9":"#16a34a",A.style.color=t?"#94a3b8":"#ffffff",A.style.borderColor=t?"#d1d5db":"#15803d"))}setStatus(A){this.statusElement&&(this.statusElement.textContent=A)}handleKeyDown(A){if(!(!this.active||this.isTextInputTarget(A))){if((A.ctrlKey||A.metaKey)&&!A.shiftKey&&!A.altKey&&A.key.toLowerCase()==="z"){if(this.history.length===0)return;A.preventDefault(),A.stopImmediatePropagation(),this.undo();return}A.key==="Escape"&&this.handelKeyEscDown()}}isTextInputTarget(A){const t=A.target;return!!(t?.isContentEditable||["INPUT","TEXTAREA","SELECT"].includes(t?.tagName??""))}emitChange(){this.options.onChange?.(this.getPathData()),this.requestRender()}requestRender(){this.engine.requestComposerRender?.()}toPlainVector(A){return{x:A.x,y:A.y,z:A.z}}}class O8{engine;continusIds=new Map;constructor(A){this.engine=A}buildContinueIds(A){const e=this.engine?.engineStatus?.models?.find(n=>n.url===A)?.properties?.models;if(e==null||typeof e!="object"){this.continusIds.set(A,new Set);return}const i=new Set;Object.keys(e).forEach(n=>{const o=Number(n);Number.isFinite(o)&&this.shouldFilterId(A,n,e[n])&&i.add(o)}),this.continusIds.set(A,i)}setContinueIds(A,t){const e=new Set;t.forEach(i=>{const n=Number(i);Number.isFinite(n)&&e.add(n)}),this.continusIds.set(A,e)}getContinueIds(A){return Array.from(this.continusIds.get(A)??[])}getContinueIdSet(A){return this.continusIds.get(A)??new Set}hasContinueId(A,t){const e=Number(t);return Number.isFinite(e)?this.getContinueIdSet(A).has(e):!1}clear(A){if(typeof A=="string"){this.continusIds.delete(A);return}this.continusIds.clear()}shouldFilterId(A,t,e){const n=this.engine?.engineStatus?.models?.find(I=>I.url===A)?.properties,o=Array.isArray(e)?e:n?.models?.[t];if(n==null||!Array.isArray(o)||o.length===0)return!1;const g=n.categorys??{},a=n.names??{},r=n.values??{};return o.some(I=>{if(!Array.isArray(I)||I.length<3)return!1;const l=String(g[I[0]]??""),h=String(a[I[1]]??""),B=String(r[I[2]]??"");return l.includes("图层信息")&&h.includes("父类别")&&(B.includes("注释")||B.includes("视口范围")||B.includes("剖面"))})}}const UB={version:"4.0.1"}.version;function Jy(){const s=globalThis.crypto?.subtle;if(!s)throw new Error("[BimEngine] Web Crypto API is required for secure sdkAuth credentials mode");return s}function XB(s){return new TextEncoder().encode(s)}function JB(s){return s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength)}function YW(s){let A="";return s.forEach(t=>{A+=String.fromCharCode(t)}),btoa(A)}function L8(s){const A=s.getUTCFullYear(),t=String(s.getUTCMonth()+1).padStart(2,"0"),e=String(s.getUTCDate()).padStart(2,"0");return`${A}${t}${e}`}async function z8(s){const A=await Jy().digest("SHA-256",JB(XB(s)));return Array.from(new Uint8Array(A)).map(t=>t.toString(16).padStart(2,"0")).join("")}async function v8(s,A){const t=Jy(),e=await t.importKey("raw",JB(s),{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return t.sign("HMAC",e,JB(XB(A)))}function _8(s){return XB([s.appId,s.engineType,s.requestDate,String(s.timestamp),s.nonce].join("|"))}async function q8(s){const A=Jy(),t=new Date,e=t.getTime(),i=L8(t),n=globalThis.crypto.randomUUID(),o=globalThis.crypto.getRandomValues(new Uint8Array(12)),g=await z8(s.appSecret),a=await v8(XB(g),i),r=await A.importKey("raw",a,"AES-GCM",!1,["encrypt"]),I=JSON.stringify({appKey:s.appKey,appSecret:s.appSecret}),l=await A.encrypt({name:"AES-GCM",iv:o,additionalData:JB(_8({appId:s.appId,engineType:s.engineType,requestDate:i,timestamp:e,nonce:n})),tagLength:128},r,JB(XB(I)));return{appId:s.appId,engineType:s.engineType,requestDate:i,timestamp:e,nonce:n,iv:YW(o),cipherText:YW(new Uint8Array(l)),sdkVersion:s.sdkVersion,origin:s.origin,product:s.product}}const xy=new Map;function cQ(s){return s.replace(/\/+$/,"")}function QQ(s){if(s)return s;if(typeof window<"u"&&typeof window.location?.origin=="string")return window.location.origin}function $8(s,A){return JSON.stringify({endpoint:cQ(s.endpoint),token:s.token??"",appId:s.appId??"",appKey:s.appKey??"",appSecret:s.appSecret??"",origin:QQ(s.origin)??"",product:s.product??"",engineType:A,sdkVersion:UB})}async function ky(s,A,t){const e=typeof AbortController<"u"?new AbortController:void 0,i=e?setTimeout(()=>e.abort(),t):void 0;try{const n=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(A),signal:e?.signal}),o=await n.json().catch(()=>({}));if(!n.ok){const g=o?.error?.message??o?.message??`SDK authentication failed with status ${n.status}`;throw new Error(g)}return o}finally{i!=null&&clearTimeout(i)}}async function A3(s,A){const t=await ky(`${cQ(s.endpoint)}/oauth/sdk-verify`,{sdkToken:s.token,engineType:A,sdkVersion:UB,origin:QQ(s.origin),product:s.product},s.timeoutMs??8e3);return t.sdkToken=s.token,t}async function t3(s,A){const t=await q8({appId:s.appId,appKey:s.appKey,appSecret:s.appSecret,engineType:A,sdkVersion:UB,origin:QQ(s.origin),product:s.product}),e=await ky(`${cQ(s.endpoint)}/oauth/sdk-token/secure`,t,s.timeoutMs??8e3),i=await ky(`${cQ(s.endpoint)}/oauth/sdk-verify`,{sdkToken:e.sdkToken,engineType:A,sdkVersion:UB,origin:QQ(s.origin),product:s.product},s.timeoutMs??8e3);return i.sdkToken=e.sdkToken,i}async function e3(s,A){const t=s?.sdkAuth;if(!t)return null;if(!t.endpoint)throw new Error("[BimEngine] sdkAuth.endpoint is required");if(!t.token&&!(t.appId&&t.appKey&&t.appSecret))return null;const e=$8(t,A),i=xy.get(e);if(i){const o=await i;return s&&(s.__sdkAuthSession=o),o}const n=(t.token?A3(t,A):t3(t,A)).then(o=>{if(o.authorized!==!0)throw new Error("[BimEngine] SDK authorization rejected");return s&&(s.__sdkAuthSession=o),o}).catch(o=>{throw xy.delete(e),o});return xy.set(e,n),n}var Vy,FW;function Pt(){return FW||(FW=1,Vy={options:{usePureJavaScript:!1}}),Vy}var Hy={exports:{}},Oy,bW;function i3(){if(bW)return Oy;bW=1;var s={};Oy=s;var A={};s.encode=function(e,i,n){if(typeof i!="string")throw new TypeError('"alphabet" must be a string.');if(n!==void 0&&typeof n!="number")throw new TypeError('"maxline" must be a number.');var o="";if(!(e instanceof Uint8Array))o=t(e,i);else{var g=0,a=i.length,r=i.charAt(0),I=[0];for(g=0;g<e.length;++g){for(var l=0,h=e[g];l<I.length;++l)h+=I[l]<<8,I[l]=h%a,h=h/a|0;for(;h>0;)I.push(h%a),h=h/a|0}for(g=0;e[g]===0&&g<e.length-1;++g)o+=r;for(g=I.length-1;g>=0;--g)o+=i[I[g]]}if(n){var B=new RegExp(".{1,"+n+"}","g");o=o.match(B).join(`\r
|
|
6600
|
+
`};class Zy extends $t{constructor(A){super({type:"LineMaterial",uniforms:oi.clone(Zi.line.uniforms),vertexShader:Zi.line.vertexShader,fragmentShader:Zi.line.fragmentShader,clipping:!0}),this.isLineMaterial=!0,this.setValues(A)}get color(){return this.uniforms.diffuse.value}set color(A){this.uniforms.diffuse.value=A}get worldUnits(){return"WORLD_UNITS"in this.defines}set worldUnits(A){A===!0!==this.worldUnits&&(this.needsUpdate=!0),A===!0?this.defines.WORLD_UNITS="":delete this.defines.WORLD_UNITS}get linewidth(){return this.uniforms.linewidth.value}set linewidth(A){this.uniforms.linewidth&&(this.uniforms.linewidth.value=A)}get dashed(){return"USE_DASH"in this.defines}set dashed(A){A===!0!==this.dashed&&(this.needsUpdate=!0),A===!0?this.defines.USE_DASH="":delete this.defines.USE_DASH}get dashScale(){return this.uniforms.dashScale.value}set dashScale(A){this.uniforms.dashScale.value=A}get dashSize(){return this.uniforms.dashSize.value}set dashSize(A){this.uniforms.dashSize.value=A}get dashOffset(){return this.uniforms.dashOffset.value}set dashOffset(A){this.uniforms.dashOffset.value=A}get gapSize(){return this.uniforms.gapSize.value}set gapSize(A){this.uniforms.gapSize.value=A}get opacity(){return this.uniforms.opacity.value}set opacity(A){this.uniforms&&(this.uniforms.opacity.value=A)}get resolution(){return this.uniforms.resolution.value}set resolution(A){this.uniforms.resolution.value.copy(A)}get alphaToCoverage(){return"USE_ALPHA_TO_COVERAGE"in this.defines}set alphaToCoverage(A){this.defines&&(A===!0!==this.alphaToCoverage&&(this.needsUpdate=!0),A===!0?this.defines.USE_ALPHA_TO_COVERAGE="":delete this.defines.USE_ALPHA_TO_COVERAGE)}}const Ny=new Ct,wW=new S,uW=new S,Qi=new Ct,di=new Ct,wn=new Ct,Uy=new S,Xy=new RA,fi=new vi,mW=new S,hQ=new vA,CQ=new be,un=new Ct;let mn,ca;function PW(s,A,t){return un.set(0,0,-A,1).applyMatrix4(s.projectionMatrix),un.multiplyScalar(1/un.w),un.x=ca/t.width,un.y=ca/t.height,un.applyMatrix4(s.projectionMatrixInverse),un.multiplyScalar(1/un.w),Math.abs(Math.max(un.x,un.y))}function U8(s,A){const t=s.matrixWorld,e=s.geometry,i=e.attributes.instanceStart,n=e.attributes.instanceEnd,o=Math.min(e.instanceCount,i.count);for(let g=0,a=o;g<a;g++){fi.start.fromBufferAttribute(i,g),fi.end.fromBufferAttribute(n,g),fi.applyMatrix4(t);const r=new S,I=new S;mn.distanceSqToSegment(fi.start,fi.end,I,r),I.distanceTo(r)<ca*.5&&A.push({point:I,pointOnLine:r,distance:mn.origin.distanceTo(I),object:s,face:null,faceIndex:g,uv:null,uv1:null})}}function X8(s,A,t){const e=A.projectionMatrix,n=s.material.resolution,o=s.matrixWorld,g=s.geometry,a=g.attributes.instanceStart,r=g.attributes.instanceEnd,I=Math.min(g.instanceCount,a.count),l=-A.near;mn.at(1,wn),wn.w=1,wn.applyMatrix4(A.matrixWorldInverse),wn.applyMatrix4(e),wn.multiplyScalar(1/wn.w),wn.x*=n.x/2,wn.y*=n.y/2,wn.z=0,Uy.copy(wn),Xy.multiplyMatrices(A.matrixWorldInverse,o);for(let h=0,B=I;h<B;h++){if(Qi.fromBufferAttribute(a,h),di.fromBufferAttribute(r,h),Qi.w=1,di.w=1,Qi.applyMatrix4(Xy),di.applyMatrix4(Xy),Qi.z>l&&di.z>l)continue;if(Qi.z>l){const M=Qi.z-di.z,y=(Qi.z-l)/M;Qi.lerp(di,y)}else if(di.z>l){const M=di.z-Qi.z,y=(di.z-l)/M;di.lerp(Qi,y)}Qi.applyMatrix4(e),di.applyMatrix4(e),Qi.multiplyScalar(1/Qi.w),di.multiplyScalar(1/di.w),Qi.x*=n.x/2,Qi.y*=n.y/2,di.x*=n.x/2,di.y*=n.y/2,fi.start.copy(Qi),fi.start.z=0,fi.end.copy(di),fi.end.z=0;const c=fi.closestPointToPointParameter(Uy,!0);fi.at(c,mW);const Q=rt.lerp(Qi.z,di.z,c),C=Q>=-1&&Q<=1,d=Uy.distanceTo(mW)<ca*.5;if(C&&d){fi.start.fromBufferAttribute(a,h),fi.end.fromBufferAttribute(r,h),fi.start.applyMatrix4(o),fi.end.applyMatrix4(o);const M=new S,y=new S;mn.distanceSqToSegment(fi.start,fi.end,y,M),t.push({point:y,pointOnLine:M,distance:mn.origin.distanceTo(y),object:s,face:null,faceIndex:h,uv:null,uv1:null})}}}class J8 extends bA{constructor(A=new DW,t=new Zy({color:Math.random()*16777215})){super(A,t),this.isLineSegments2=!0,this.type="LineSegments2"}computeLineDistances(){const A=this.geometry,t=A.attributes.instanceStart,e=A.attributes.instanceEnd,i=new Float32Array(2*t.count);for(let o=0,g=0,a=t.count;o<a;o++,g+=2)wW.fromBufferAttribute(t,o),uW.fromBufferAttribute(e,o),i[g]=g===0?0:i[g-1],i[g+1]=i[g]+wW.distanceTo(uW);const n=new JC(i,2,1);return A.setAttribute("instanceDistanceStart",new ji(n,1,0)),A.setAttribute("instanceDistanceEnd",new ji(n,1,1)),this}raycast(A,t){const e=this.material.worldUnits,i=A.camera;if(i===null&&!e&&console.error('LineSegments2: "Raycaster.camera" needs to be set in order to raycast against LineSegments2 while worldUnits is set to false.'),e===!1&&(this.material.resolution.x===0||this.material.resolution.y===0))return;const n=A.params.Line2!==void 0&&A.params.Line2.threshold||0;mn=A.ray;const o=this.matrixWorld,g=this.geometry,a=this.material;ca=a.linewidth+n,g.boundingSphere===null&&g.computeBoundingSphere(),CQ.copy(g.boundingSphere).applyMatrix4(o);let r;if(e)r=ca*.5;else{const l=Math.max(i.near,CQ.distanceToPoint(mn.origin));r=PW(i,l,a.resolution)}if(CQ.radius+=r,mn.intersectsSphere(CQ)===!1)return;g.boundingBox===null&&g.computeBoundingBox(),hQ.copy(g.boundingBox).applyMatrix4(o);let I;if(e)I=ca*.5;else{const l=Math.max(i.near,hQ.distanceToPoint(mn.origin));I=PW(i,l,a.resolution)}hQ.expandByScalar(I),mn.intersectsBox(hQ)!==!1&&(e?U8(this,t):X8(this,i,t))}onBeforeRender(A){const t=this.material.uniforms;t&&t.resolution&&(A.getViewport(Ny),this.material.uniforms.resolution.value.set(Ny.z,Ny.w))}}class SW extends DW{constructor(){super(),this.isLineGeometry=!0,this.type="LineGeometry"}setPositions(A){const t=A.length-3,e=new Float32Array(2*t);for(let i=0;i<t;i+=3)e[2*i]=A[i],e[2*i+1]=A[i+1],e[2*i+2]=A[i+2],e[2*i+3]=A[i+3],e[2*i+4]=A[i+4],e[2*i+5]=A[i+5];return super.setPositions(e),this}setColors(A){const t=A.length-3,e=new Float32Array(2*t);for(let i=0;i<t;i+=3)e[2*i]=A[i],e[2*i+1]=A[i+1],e[2*i+2]=A[i+2],e[2*i+3]=A[i+3],e[2*i+4]=A[i+4],e[2*i+5]=A[i+5];return super.setColors(e),this}setFromPoints(A){const t=A.length-1,e=new Float32Array(6*t);for(let i=0;i<t;i++)e[6*i]=A[i].x,e[6*i+1]=A[i].y,e[6*i+2]=A[i].z||0,e[6*i+3]=A[i+1].x,e[6*i+4]=A[i+1].y,e[6*i+5]=A[i+1].z||0;return super.setPositions(e),this}fromLine(A){const t=A.geometry;return this.setPositions(t.attributes.position.array),this}}class x8 extends J8{constructor(A=new SW,t=new Zy({color:Math.random()*16777215})){super(A,t),this.isLine2=!0,this.type="Line2"}}const EQ={lineType:"bezier",lineColor:"#22c55e",previewColor:"#f59e0b",pointColor:"#ffffff",selectedPointColor:"#f59e0b",pointSize:.34,lineWidth:4,sampleCount:64,roundedRadius:1,historyLimit:100},k8={bezier:"贝塞尔曲线",straight:"直线",rounded:"圆角直线"},V8={bezier:"∿",straight:"╱",rounded:"⌁"};class H8{type="path-draw";engine;root=new Ot;pointsGroup=new Ot;points=[];history=[];options={...EQ};lineType=EQ.lineType;roundedRadius=EQ.roundedRadius;line=null;previewLine=null;previewMarker=null;transformControl=null;transformHelper=null;selectedPointId=null;panel=null;pointsList=null;statusElement=null;addButton=null;completeButton=null;radiusInput=null;mode="editing";active=!1;closing=!1;transformDragging=!1;suppressNextCanvasClick=!1;controlsEnabledBeforeDrag=!0;pointSequence=0;pathId="";onKeyDown;constructor(A){this.engine=A,this.root.name="PathDrawRoot",this.pointsGroup.name="PathDrawPoints",this.root.add(this.pointsGroup),this.onKeyDown=this.handleKeyDown.bind(this)}open(A={}){this.active&&this.close(),this.options={...EQ,...A},this.pathId=A.id??`path-${Date.now()}`,this.lineType=this.options.lineType,this.roundedRadius=Math.max(0,this.options.roundedRadius),this.active=!0,this.mode="editing",this.engine.scene?.add(this.root),this.ensureTransformControl(),this.createPanel(),this.activateBehavior(),window.addEventListener("keydown",this.onKeyDown,!0),this.refreshAll()}startAddPoint(){return!this.active||this.transformDragging?!1:(this.mode="picking",this.clearSelection(),this.setStatus("请在模型上拾取位置"),this.addButton&&(this.addButton.dataset.active="true"),!0)}setLineType(A){!this.active||this.lineType===A||(this.saveHistory(),this.lineType=A,this.refreshAll(),this.emitChange())}undo(){const A=this.history.pop();return A?(this.restoreSnapshot(A),this.mode="editing",this.clearPreview(),this.refreshAll(),this.emitChange(),!0):!1}clear(){this.points.length!==0&&(this.saveHistory(),this.clearPointRecords(),this.mode="editing",this.clearPreview(),this.refreshAll(),this.emitChange())}getPathData(){if(this.points.length<2)return null;const A=this.buildSamplePoints(this.points.map(t=>t.position));return{version:1,id:this.pathId,lineType:this.lineType,coordinateSystem:"world",closed:!1,roundedRadius:this.roundedRadius,points:this.points.map((t,e)=>({id:t.id,order:e,role:this.getPointRole(e),position:this.toPlainVector(t.position)})),samples:A.map(t=>this.toPlainVector(t)),length:this.calculateLength(A)}}complete(){const A=this.getPathData();if(!A)return null;try{this.options.onComplete?.(A)}finally{this.close()}return A}isActive(){return this.active}close(){this.closeInternal(!0)}closeInternal(A){!this.active&&!this.panel||this.closing||(this.closing=!0,this.active=!1,window.removeEventListener("keydown",this.onKeyDown,!0),this.clearPreview(),this.clearPointRecords(),this.disposeLine("line"),this.detachTransformControl(),this.panel?.remove(),this.panel=null,this.pointsList=null,this.statusElement=null,this.addButton=null,this.completeButton=null,this.radiusInput=null,this.history.length=0,this.selectedPointId=null,this.root.parent?.remove(this.root),A&&this.restoreDefaultBehavior(),this.closing=!1)}dispose(){this.closeInternal(!1),this.transformControl?.dispose(),this.transformControl=null,this.transformHelper=null}update(){!this.active||!this.engine.camera||(this.transformControl&&this.transformControl.camera!==this.engine.camera&&(this.transformControl.camera=this.engine.camera),this.syncLineResolution(this.line),this.syncLineResolution(this.previewLine))}disActive(){this.closing||this.closeInternal(!1)}handleMouseMove(A){if(!this.active||this.mode!=="picking")return;const t=this.getCatchPoint(A?.catch);if(!t){this.clearPreview();return}this.updatePreview(t)}handleMouseClick(A){if(!this.active)return;if(this.suppressNextCanvasClick){this.suppressNextCanvasClick=!1;return}if(this.mode==="picking"){const e=this.getCatchPoint(A?.catch);if(!e)return;this.saveHistory();const i=this.createPointRecord(e);this.points.push(i),this.pointsGroup.add(i.mesh),this.mode="editing",this.clearPreview(),this.selectPoint(i.id),this.refreshAll(),this.emitChange();return}const t=this.pickPointMesh(A);t?this.selectPoint(t.userData.pathDrawPointId):this.clearSelection()}handelKeyEscDown(){if(this.mode==="picking"){this.mode="editing",this.clearPreview(),this.refreshPanel();return}this.clearSelection()}activateBehavior(){const A=this.engine.handelBehaved;A?.init?.(this,{showCatch:!0}),A?.active?.()}restoreDefaultBehavior(){const A=this.engine.handelBehaved;A?.self===this&&(A.disActive?.(),this.engine.interactionModule?.init?.(),this.engine.interactionModule?.active?.(),this.engine.catchSvg&&(this.engine.catchSvg.innerHTML=""))}ensureTransformControl(){if(this.transformControl){this.transformHelper&&!this.transformHelper.parent&&this.engine.scene?.add(this.transformHelper);return}!this.engine.camera||!this.engine.renderer||!this.engine.scene||(this.transformControl=new ql(this.engine.camera,this.engine.renderer.domElement),this.transformControl.setMode("translate"),this.transformControl.size=.72,this.transformControl.addEventListener("dragging-changed",A=>{if(this.transformDragging=!!A.value,this.transformDragging){this.saveHistory(),this.controlsEnabledBeforeDrag=this.engine.controls?.enabled!==!1,this.engine.controls&&(this.engine.controls.enabled=!1);return}this.engine.controls&&(this.engine.controls.enabled=this.controlsEnabledBeforeDrag),this.suppressNextCanvasClick=!0,requestAnimationFrame(()=>{this.suppressNextCanvasClick=!1}),this.refreshAll(),this.emitChange()}),this.transformControl.addEventListener("objectChange",()=>{const A=this.getSelectedPoint();A&&(A.position.copy(A.mesh.position),this.refreshLine(),this.refreshPanel(),this.emitChange())}),this.transformHelper=this.transformControl.getHelper(),this.transformHelper.visible=!1,this.engine.scene.add(this.transformHelper))}detachTransformControl(){this.transformControl?.detach(),this.transformHelper&&(this.transformHelper.visible=!1,this.transformHelper.parent?.remove(this.transformHelper))}createPointRecord(A,t){const e=new an(this.options.pointSize,18,12),i=new Kt({color:this.options.pointColor,depthTest:!1,depthWrite:!1}),n=new bA(e,i),o=t??`path-point-${++this.pointSequence}`;return n.name=o,n.position.copy(A),n.renderOrder=1002,n.userData.pathDrawPointId=o,{id:o,position:A.clone(),mesh:n}}selectPoint(A){const t=this.points.find(e=>e.id===A);!t||!this.transformControl||!this.transformHelper||(this.selectedPointId=A,this.points.forEach(e=>e.mesh.material.color.set(e.id===A?this.options.selectedPointColor:this.options.pointColor)),this.transformControl.attach(t.mesh),this.transformHelper.visible=!0,this.refreshPanel())}clearSelection(){this.selectedPointId=null,this.points.forEach(A=>A.mesh.material.color.set(this.options.pointColor)),this.transformControl?.detach(),this.transformHelper&&(this.transformHelper.visible=!1),this.refreshPanel()}getSelectedPoint(){return this.points.find(A=>A.id===this.selectedPointId)??null}getCatchPoint(A){return A?.point instanceof S?A.point.clone():null}pickPointMesh(A){if(!this.engine.camera||!this.engine.renderer)return null;const t=this.engine.renderer.domElement.clientWidth,e=this.engine.renderer.domElement.clientHeight;if(!t||!e)return null;const i=new MA(A.offsetX/t*2-1,-(A.offsetY/e)*2+1),n=new De;return n.setFromCamera(i,this.engine.camera),n.intersectObjects(this.pointsGroup.children,!1)[0]?.object??null}updatePreview(A){this.previewMarker||(this.previewMarker=new bA(new an(this.options.pointSize*.72,14,10),new Kt({color:this.options.previewColor,depthTest:!1,depthWrite:!1})),this.previewMarker.renderOrder=1003,this.root.add(this.previewMarker)),this.previewMarker.position.copy(A),this.previewMarker.visible=!0;const t=[...this.points.map(i=>i.position),A];if(t.length<2){this.disposeLine("previewLine");return}const e=this.buildSamplePoints(t);this.previewLine=this.updateLineObject(this.previewLine,e,!0)}clearPreview(){this.disposeLine("previewLine"),this.previewMarker&&(this.previewMarker.geometry.dispose(),this.previewMarker.material.dispose(),this.previewMarker.parent?.remove(this.previewMarker),this.previewMarker=null)}refreshAll(){this.refreshLine(),this.refreshPanel(),this.requestRender()}refreshLine(){if(this.points.length<2){this.disposeLine("line");return}const A=this.buildSamplePoints(this.points.map(t=>t.position));this.line=this.updateLineObject(this.line,A,!1)}updateLineObject(A,t,e){const i=new SW;if(i.setPositions(t.flatMap(g=>[g.x,g.y,g.z])),A)return A.geometry.dispose(),A.geometry=i,A.computeLineDistances(),this.syncLineResolution(A),this.requestRender(),A;const n=new Zy({color:e?this.options.previewColor:this.options.lineColor,linewidth:this.options.lineWidth,dashed:e,dashSize:.32,gapSize:.2,depthTest:!1,transparent:e,opacity:e?.82:1}),o=new x8(i,n);return o.name=e?"PathDrawPreviewLine":"PathDrawLine",o.renderOrder=e?1001:1e3,o.computeLineDistances(),this.syncLineResolution(o),this.root.add(o),this.requestRender(),o}syncLineResolution(A){const t=A?.material,e=this.engine.renderer?.domElement;!t||!e||t.resolution.set(e.clientWidth,e.clientHeight)}disposeLine(A){const t=this[A];if(!t)return;t.parent?.remove(t),t.geometry.dispose(),(Array.isArray(t.material)?t.material:[t.material]).forEach(i=>i.dispose()),this[A]=null}buildSamplePoints(A){return A.length<2?A.map(t=>t.clone()):this.lineType==="straight"?A.map(t=>t.clone()):this.lineType==="rounded"?this.sampleRoundedPolyline(A):this.sampleBezier(A)}sampleBezier(A){const t=Math.max(2,this.options.sampleCount);return Array.from({length:t+1},(e,i)=>{const n=A.map(g=>g.clone()),o=i/t;for(let g=n.length-1;g>0;g-=1)for(let a=0;a<g;a+=1)n[a].lerp(n[a+1],o);return n[0]})}sampleRoundedPolyline(A){if(A.length<3||this.roundedRadius<=0)return A.map(i=>i.clone());const t=[A[0].clone()],e=Math.max(4,Math.round(this.options.sampleCount/Math.max(1,A.length-2)));for(let i=1;i<A.length-1;i+=1){const n=A[i-1],o=A[i],g=A[i+1],a=n.distanceTo(o),r=o.distanceTo(g);if(a<1e-8||r<1e-8){t.push(o.clone());continue}const I=Math.min(this.roundedRadius,a*.5,r*.5),l=o.clone().lerp(n,I/a),h=o.clone().lerp(g,I/r);t.push(l);for(let B=1;B<=e;B+=1){const E=B/e,c=1-E;t.push(new S().addScaledVector(l,c*c).addScaledVector(o,2*c*E).addScaledVector(h,E*E))}}return t.push(A[A.length-1].clone()),t}calculateLength(A){let t=0;for(let e=1;e<A.length;e+=1)t+=A[e-1].distanceTo(A[e]);return t}getPointRole(A){return A===0?"start":A===this.points.length-1?"end":"control"}getRoleLabel(A){const t=this.getPointRole(A);return t==="start"?"起点":t==="end"?"终点":`控制点 ${A}`}saveHistory(){this.history.push(this.createSnapshot()),this.history.length>this.options.historyLimit&&this.history.shift()}createSnapshot(){return{lineType:this.lineType,roundedRadius:this.roundedRadius,points:this.points.map(A=>({id:A.id,position:A.position.toArray()}))}}restoreSnapshot(A){this.clearPointRecords(),this.lineType=A.lineType,this.roundedRadius=A.roundedRadius,A.points.forEach(t=>{const e=this.createPointRecord(new S(...t.position),t.id);this.points.push(e),this.pointsGroup.add(e.mesh)})}clearPointRecords(){this.clearSelection(),this.points.forEach(A=>{A.mesh.parent?.remove(A.mesh),A.mesh.geometry.dispose(),A.mesh.material.dispose()}),this.points.length=0}removePoint(A){const t=this.points.findIndex(i=>i.id===A);if(t<0)return;this.saveHistory();const[e]=this.points.splice(t,1);e.mesh.parent?.remove(e.mesh),e.mesh.geometry.dispose(),e.mesh.material.dispose(),this.selectedPointId===A&&this.clearSelection(),this.refreshAll(),this.emitChange()}updatePointCoordinate(A,t,e){const i=this.points.find(n=>n.id===A);!i||!Number.isFinite(e)||i.position[t]===e||(this.saveHistory(),i.position[t]=e,i.mesh.position[t]=e,this.refreshAll(),this.emitChange())}createPanel(){const A=document.createElement("div");A.dataset.pathDrawPanel="true",Object.assign(A.style,{position:"absolute",top:"56px",right:"16px",width:"310px",maxHeight:"calc(100% - 72px)",display:"flex",flexDirection:"column",background:"rgba(255, 255, 255, 0.98)",color:"#111827",border:"1px solid #d1d5db",borderRadius:"6px",boxShadow:"0 12px 28px rgba(15,23,42,0.18)",fontFamily:"Arial, sans-serif",fontSize:"12px",zIndex:"1200",overflow:"hidden"});const t=document.createElement("div");Object.assign(t.style,{display:"flex",alignItems:"center",minHeight:"40px",padding:"0 8px 0 12px",borderBottom:"1px solid #e5e7eb"});const e=document.createElement("strong");e.textContent="路径绘制",e.style.flex="1";const i=document.createElement("span");Object.assign(i.style,{color:"#64748b",marginRight:"8px"});const n=this.createIconButton("×","关闭路径绘制",()=>this.close());t.append(e,i,n),A.appendChild(t),this.statusElement=i;const o=document.createElement("div");Object.assign(o.style,{display:"grid",gridTemplateColumns:"repeat(3, 1fr)",gap:"4px",padding:"8px"}),["bezier","straight","rounded"].forEach(Q=>{const C=this.createIconButton(V8[Q],k8[Q],()=>this.setLineType(Q));C.dataset.lineType=Q,C.style.width="100%",C.style.fontSize="18px",o.appendChild(C)}),A.appendChild(o);const g=document.createElement("label");g.dataset.radiusRow="true",Object.assign(g.style,{display:"none",alignItems:"center",gap:"8px",padding:"0 10px 8px",color:"#475569"});const a=document.createElement("span");a.textContent="圆角";const r=document.createElement("input");r.type="number",r.min="0",r.step="0.1",Object.assign(r.style,{flex:"1",minWidth:"0",height:"26px",padding:"0 7px",color:"#111827",background:"#ffffff",border:"1px solid #cbd5e1",borderRadius:"4px"}),r.addEventListener("change",()=>{const Q=Number(r.value);if(!Number.isFinite(Q)||Q<0||Q===this.roundedRadius){r.value=String(this.roundedRadius);return}this.saveHistory(),this.roundedRadius=Q,this.refreshAll(),this.emitChange()}),g.append(a,r),A.appendChild(g),this.radiusInput=r;const I=document.createElement("div");Object.assign(I.style,{flex:"1",minHeight:"72px",maxHeight:"200px",overflowY:"auto",overflowX:"hidden",borderTop:"1px solid #e5e7eb"}),A.appendChild(I),this.pointsList=I;const l=document.createElement("div");Object.assign(l.style,{display:"grid",gridTemplateColumns:"1fr auto auto auto",gap:"6px",padding:"8px",borderTop:"1px solid #e5e7eb"});const h=this.createIconButton("+","添加点",()=>this.startAddPoint());h.style.width="100%";const B=this.createIconButton("↶","撤销 Ctrl+Z",()=>this.undo());B.dataset.undoButton="true";const E=this.createIconButton("⌫","清空路径",()=>this.clear());E.dataset.clearButton="true";const c=this.createIconButton("✓","完成并返回路径",()=>this.complete());c.dataset.primary="true",l.append(h,B,E,c),A.appendChild(l),this.addButton=h,this.completeButton=c,this.engine.container?.appendChild(A),this.panel=A}createIconButton(A,t,e){const i=document.createElement("button");return i.type="button",i.textContent=A,i.title=t,i.setAttribute("aria-label",t),Object.assign(i.style,{width:"32px",height:"30px",display:"inline-flex",alignItems:"center",justifyContent:"center",padding:"0",border:"1px solid #d1d5db",borderRadius:"4px",background:"#f8fafc",color:"#334155",cursor:"pointer",fontSize:"15px"}),i.addEventListener("click",e),i}refreshPanel(){if(!this.panel||!this.pointsList)return;this.setStatus(this.mode==="picking"?"拾取中":`${this.points.length} 个点`),this.addButton&&(this.addButton.dataset.active=String(this.mode==="picking"),this.addButton.style.background=this.mode==="picking"?"#ffedd5":"#f8fafc",this.addButton.style.borderColor=this.mode==="picking"?"#f97316":"#d1d5db",this.addButton.style.color=this.mode==="picking"?"#9a3412":"#334155"),this.panel.querySelectorAll("[data-line-type]").forEach(i=>{const n=i.dataset.lineType===this.lineType;i.style.background=n?"#dcfce7":"#f8fafc",i.style.borderColor=n?"#22c55e":"#d1d5db",i.style.color=n?"#166534":"#334155"});const A=this.panel.querySelector("[data-radius-row]");A&&(A.style.display=this.lineType==="rounded"?"flex":"none"),this.radiusInput&&(this.radiusInput.value=String(this.roundedRadius));const t=this.panel.querySelector("[data-undo-button]"),e=this.panel.querySelector("[data-clear-button]");this.setButtonDisabled(t,this.history.length===0),this.setButtonDisabled(e,this.points.length===0),this.setButtonDisabled(this.completeButton,this.points.length<2),this.renderPointRows()}renderPointRows(){if(this.pointsList){if(this.pointsList.innerHTML="",this.points.length===0){const A=document.createElement("div");A.textContent="暂无点位",Object.assign(A.style,{padding:"24px 12px",textAlign:"center",color:"#94a3b8"}),this.pointsList.appendChild(A);return}this.points.forEach((A,t)=>{const e=document.createElement("div");Object.assign(e.style,{display:"grid",gridTemplateColumns:"64px repeat(3, minmax(0, 1fr)) 28px",gap:"4px",alignItems:"center",height:"40px",boxSizing:"border-box",padding:"5px 8px",cursor:"pointer",background:A.id===this.selectedPointId?"#fef3c7":"#ffffff",borderBottom:"1px solid #eef2f7"}),e.addEventListener("click",()=>this.selectPoint(A.id));const i=document.createElement("span");i.textContent=this.getRoleLabel(t),i.title=i.textContent,Object.assign(i.style,{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"#334155"}),e.appendChild(i),["x","y","z"].forEach(o=>{const g=document.createElement("input");g.type="number",g.step="0.001",g.value=A.position[o].toFixed(3),g.title=o.toUpperCase(),Object.assign(g.style,{width:"100%",minWidth:"0",height:"25px",padding:"0 4px",boxSizing:"border-box",color:"#1f2937",background:"#ffffff",border:"1px solid #cbd5e1",borderRadius:"3px",fontSize:"11px"}),g.addEventListener("click",a=>a.stopPropagation()),g.addEventListener("change",()=>this.updatePointCoordinate(A.id,o,Number(g.value))),e.appendChild(g)});const n=this.createIconButton("×",`删除${this.getRoleLabel(t)}`,()=>this.removePoint(A.id));n.style.width="28px",n.style.height="25px",n.addEventListener("click",o=>o.stopPropagation()),e.appendChild(n),this.pointsList?.appendChild(e)})}}setButtonDisabled(A,t){A&&(A.disabled=t,A.style.opacity=t?"0.4":"1",A.style.cursor=t?"not-allowed":"pointer",A.dataset.primary==="true"&&(A.style.background=t?"#f1f5f9":"#16a34a",A.style.color=t?"#94a3b8":"#ffffff",A.style.borderColor=t?"#d1d5db":"#15803d"))}setStatus(A){this.statusElement&&(this.statusElement.textContent=A)}handleKeyDown(A){if(!(!this.active||this.isTextInputTarget(A))){if((A.ctrlKey||A.metaKey)&&!A.shiftKey&&!A.altKey&&A.key.toLowerCase()==="z"){if(this.history.length===0)return;A.preventDefault(),A.stopImmediatePropagation(),this.undo();return}A.key==="Escape"&&this.handelKeyEscDown()}}isTextInputTarget(A){const t=A.target;return!!(t?.isContentEditable||["INPUT","TEXTAREA","SELECT"].includes(t?.tagName??""))}emitChange(){this.options.onChange?.(this.getPathData()),this.requestRender()}requestRender(){this.engine.requestComposerRender?.()}toPlainVector(A){return{x:A.x,y:A.y,z:A.z}}}class O8{engine;continusIds=new Map;constructor(A){this.engine=A}buildContinueIds(A){const e=this.engine?.engineStatus?.models?.find(n=>n.url===A)?.properties?.models;if(e==null||typeof e!="object"){this.continusIds.set(A,new Set);return}const i=new Set;Object.keys(e).forEach(n=>{const o=Number(n);Number.isFinite(o)&&this.shouldFilterId(A,n,e[n])&&i.add(o)}),this.continusIds.set(A,i)}setContinueIds(A,t){const e=new Set;t.forEach(i=>{const n=Number(i);Number.isFinite(n)&&e.add(n)}),this.continusIds.set(A,e)}getContinueIds(A){return Array.from(this.continusIds.get(A)??[])}getContinueIdSet(A){return this.continusIds.get(A)??new Set}hasContinueId(A,t){const e=Number(t);return Number.isFinite(e)?this.getContinueIdSet(A).has(e):!1}clear(A){if(typeof A=="string"){this.continusIds.delete(A);return}this.continusIds.clear()}shouldFilterId(A,t,e){const n=this.engine?.engineStatus?.models?.find(I=>I.url===A)?.properties,o=Array.isArray(e)?e:n?.models?.[t];if(n==null||!Array.isArray(o)||o.length===0)return!1;const g=n.categorys??{},a=n.names??{},r=n.values??{};return o.some(I=>{if(!Array.isArray(I)||I.length<3)return!1;const l=String(g[I[0]]??""),h=String(a[I[1]]??""),B=String(r[I[2]]??"");return l.includes("图层信息")&&h.includes("父类别")&&(B.includes("注释")||B.includes("视口范围")||B.includes("剖面"))})}}const UB={version:"4.0.2"}.version;function Jy(){const s=globalThis.crypto?.subtle;if(!s)throw new Error("[BimEngine] Web Crypto API is required for secure sdkAuth credentials mode");return s}function XB(s){return new TextEncoder().encode(s)}function JB(s){return s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength)}function YW(s){let A="";return s.forEach(t=>{A+=String.fromCharCode(t)}),btoa(A)}function L8(s){const A=s.getUTCFullYear(),t=String(s.getUTCMonth()+1).padStart(2,"0"),e=String(s.getUTCDate()).padStart(2,"0");return`${A}${t}${e}`}async function z8(s){const A=await Jy().digest("SHA-256",JB(XB(s)));return Array.from(new Uint8Array(A)).map(t=>t.toString(16).padStart(2,"0")).join("")}async function v8(s,A){const t=Jy(),e=await t.importKey("raw",JB(s),{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return t.sign("HMAC",e,JB(XB(A)))}function _8(s){return XB([s.appId,s.engineType,s.requestDate,String(s.timestamp),s.nonce].join("|"))}async function q8(s){const A=Jy(),t=new Date,e=t.getTime(),i=L8(t),n=globalThis.crypto.randomUUID(),o=globalThis.crypto.getRandomValues(new Uint8Array(12)),g=await z8(s.appSecret),a=await v8(XB(g),i),r=await A.importKey("raw",a,"AES-GCM",!1,["encrypt"]),I=JSON.stringify({appKey:s.appKey,appSecret:s.appSecret}),l=await A.encrypt({name:"AES-GCM",iv:o,additionalData:JB(_8({appId:s.appId,engineType:s.engineType,requestDate:i,timestamp:e,nonce:n})),tagLength:128},r,JB(XB(I)));return{appId:s.appId,engineType:s.engineType,requestDate:i,timestamp:e,nonce:n,iv:YW(o),cipherText:YW(new Uint8Array(l)),sdkVersion:s.sdkVersion,origin:s.origin,product:s.product}}const xy=new Map;function cQ(s){return s.replace(/\/+$/,"")}function QQ(s){if(s)return s;if(typeof window<"u"&&typeof window.location?.origin=="string")return window.location.origin}function $8(s,A){return JSON.stringify({endpoint:cQ(s.endpoint),token:s.token??"",appId:s.appId??"",appKey:s.appKey??"",appSecret:s.appSecret??"",origin:QQ(s.origin)??"",product:s.product??"",engineType:A,sdkVersion:UB})}async function ky(s,A,t){const e=typeof AbortController<"u"?new AbortController:void 0,i=e?setTimeout(()=>e.abort(),t):void 0;try{const n=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(A),signal:e?.signal}),o=await n.json().catch(()=>({}));if(!n.ok){const g=o?.error?.message??o?.message??`SDK authentication failed with status ${n.status}`;throw new Error(g)}return o}finally{i!=null&&clearTimeout(i)}}async function A3(s,A){const t=await ky(`${cQ(s.endpoint)}/oauth/sdk-verify`,{sdkToken:s.token,engineType:A,sdkVersion:UB,origin:QQ(s.origin),product:s.product},s.timeoutMs??8e3);return t.sdkToken=s.token,t}async function t3(s,A){const t=await q8({appId:s.appId,appKey:s.appKey,appSecret:s.appSecret,engineType:A,sdkVersion:UB,origin:QQ(s.origin),product:s.product}),e=await ky(`${cQ(s.endpoint)}/oauth/sdk-token/secure`,t,s.timeoutMs??8e3),i=await ky(`${cQ(s.endpoint)}/oauth/sdk-verify`,{sdkToken:e.sdkToken,engineType:A,sdkVersion:UB,origin:QQ(s.origin),product:s.product},s.timeoutMs??8e3);return i.sdkToken=e.sdkToken,i}async function e3(s,A){const t=s?.sdkAuth;if(!t)return null;if(!t.endpoint)throw new Error("[BimEngine] sdkAuth.endpoint is required");if(!t.token&&!(t.appId&&t.appKey&&t.appSecret))return null;const e=$8(t,A),i=xy.get(e);if(i){const o=await i;return s&&(s.__sdkAuthSession=o),o}const n=(t.token?A3(t,A):t3(t,A)).then(o=>{if(o.authorized!==!0)throw new Error("[BimEngine] SDK authorization rejected");return s&&(s.__sdkAuthSession=o),o}).catch(o=>{throw xy.delete(e),o});return xy.set(e,n),n}var Vy,FW;function Pt(){return FW||(FW=1,Vy={options:{usePureJavaScript:!1}}),Vy}var Hy={exports:{}},Oy,bW;function i3(){if(bW)return Oy;bW=1;var s={};Oy=s;var A={};s.encode=function(e,i,n){if(typeof i!="string")throw new TypeError('"alphabet" must be a string.');if(n!==void 0&&typeof n!="number")throw new TypeError('"maxline" must be a number.');var o="";if(!(e instanceof Uint8Array))o=t(e,i);else{var g=0,a=i.length,r=i.charAt(0),I=[0];for(g=0;g<e.length;++g){for(var l=0,h=e[g];l<I.length;++l)h+=I[l]<<8,I[l]=h%a,h=h/a|0;for(;h>0;)I.push(h%a),h=h/a|0}for(g=0;e[g]===0&&g<e.length-1;++g)o+=r;for(g=I.length-1;g>=0;--g)o+=i[I[g]]}if(n){var B=new RegExp(".{1,"+n+"}","g");o=o.match(B).join(`\r
|
|
6601
6601
|
`)}return o},s.decode=function(e,i){if(typeof e!="string")throw new TypeError('"input" must be a string.');if(typeof i!="string")throw new TypeError('"alphabet" must be a string.');var n=A[i];if(!n){n=A[i]=[];for(var o=0;o<i.length;++o)n[i.charCodeAt(o)]=o}e=e.replace(/\s/g,"");for(var g=i.length,a=i.charAt(0),r=[0],o=0;o<e.length;o++){var I=n[e.charCodeAt(o)];if(I===void 0)return;for(var l=0,h=I;l<r.length;++l)h+=r[l]*g,r[l]=h&255,h>>=8;for(;h>0;)r.push(h&255),h>>=8}for(var B=0;e[B]===a&&B<e.length-1;++B)r.push(0);return typeof Buffer<"u"?Buffer.from(r.reverse()):new Uint8Array(r.reverse())};function t(e,i){var n=0,o=i.length,g=i.charAt(0),a=[0];for(n=0;n<e.length();++n){for(var r=0,I=e.at(n);r<a.length;++r)I+=a[r]<<8,a[r]=I%o,I=I/o|0;for(;I>0;)a.push(I%o),I=I/o|0}var l="";for(n=0;e.at(n)===0&&n<e.length()-1;++n)l+=g;for(n=a.length-1;n>=0;--n)l+=i[a[n]];return l}return Oy}var WW;function Ut(){if(WW)return Hy.exports;WW=1;var s=Pt(),A=i3(),t=Hy.exports=s.util=s.util||{};(function(){if(typeof process<"u"&&process.nextTick&&!process.browser){t.nextTick=process.nextTick,typeof setImmediate=="function"?t.setImmediate=setImmediate:t.setImmediate=t.nextTick;return}if(typeof setImmediate=="function"){t.setImmediate=function(){return setImmediate.apply(void 0,arguments)},t.nextTick=function(p){return setImmediate(p)};return}if(t.setImmediate=function(p){setTimeout(p,0)},typeof window<"u"&&typeof window.postMessage=="function"){let p=function(f){if(f.source===window&&f.data===C){f.stopPropagation();var u=d.slice();d.length=0,u.forEach(function(Y){Y()})}};var C="forge.setImmediate",d=[];t.setImmediate=function(f){d.push(f),d.length===1&&window.postMessage(C,"*")},window.addEventListener("message",p,!0)}if(typeof MutationObserver<"u"){var M=Date.now(),y=!0,w=document.createElement("div"),d=[];new MutationObserver(function(){var f=d.slice();d.length=0,f.forEach(function(u){u()})}).observe(w,{attributes:!0});var D=t.setImmediate;t.setImmediate=function(f){Date.now()-M>15?(M=Date.now(),D(f)):(d.push(f),d.length===1&&w.setAttribute("a",y=!y))}}t.nextTick=t.setImmediate})(),t.isNodejs=typeof process<"u"&&process.versions&&process.versions.node,t.globalScope=(function(){return t.isNodejs?ul:typeof self>"u"?window:self})(),t.isArray=Array.isArray||function(C){return Object.prototype.toString.call(C)==="[object Array]"},t.isArrayBuffer=function(C){return typeof ArrayBuffer<"u"&&C instanceof ArrayBuffer},t.isArrayBufferView=function(C){return C&&t.isArrayBuffer(C.buffer)&&C.byteLength!==void 0};function e(C){if(!(C===8||C===16||C===24||C===32))throw new Error("Only 8, 16, 24, or 32 bits supported: "+C)}t.ByteBuffer=i;function i(C){if(this.data="",this.read=0,typeof C=="string")this.data=C;else if(t.isArrayBuffer(C)||t.isArrayBufferView(C))if(typeof Buffer<"u"&&C instanceof Buffer)this.data=C.toString("binary");else{var d=new Uint8Array(C);try{this.data=String.fromCharCode.apply(null,d)}catch{for(var M=0;M<d.length;++M)this.putByte(d[M])}}else(C instanceof i||typeof C=="object"&&typeof C.data=="string"&&typeof C.read=="number")&&(this.data=C.data,this.read=C.read);this._constructedStringLength=0}t.ByteStringBuffer=i;var n=4096;t.ByteStringBuffer.prototype._optimizeConstructedString=function(C){this._constructedStringLength+=C,this._constructedStringLength>n&&(this.data.substr(0,1),this._constructedStringLength=0)},t.ByteStringBuffer.prototype.length=function(){return this.data.length-this.read},t.ByteStringBuffer.prototype.isEmpty=function(){return this.length()<=0},t.ByteStringBuffer.prototype.putByte=function(C){return this.putBytes(String.fromCharCode(C))},t.ByteStringBuffer.prototype.fillWithByte=function(C,d){C=String.fromCharCode(C);for(var M=this.data;d>0;)d&1&&(M+=C),d>>>=1,d>0&&(C+=C);return this.data=M,this._optimizeConstructedString(d),this},t.ByteStringBuffer.prototype.putBytes=function(C){return this.data+=C,this._optimizeConstructedString(C.length),this},t.ByteStringBuffer.prototype.putString=function(C){return this.putBytes(t.encodeUtf8(C))},t.ByteStringBuffer.prototype.putInt16=function(C){return this.putBytes(String.fromCharCode(C>>8&255)+String.fromCharCode(C&255))},t.ByteStringBuffer.prototype.putInt24=function(C){return this.putBytes(String.fromCharCode(C>>16&255)+String.fromCharCode(C>>8&255)+String.fromCharCode(C&255))},t.ByteStringBuffer.prototype.putInt32=function(C){return this.putBytes(String.fromCharCode(C>>24&255)+String.fromCharCode(C>>16&255)+String.fromCharCode(C>>8&255)+String.fromCharCode(C&255))},t.ByteStringBuffer.prototype.putInt16Le=function(C){return this.putBytes(String.fromCharCode(C&255)+String.fromCharCode(C>>8&255))},t.ByteStringBuffer.prototype.putInt24Le=function(C){return this.putBytes(String.fromCharCode(C&255)+String.fromCharCode(C>>8&255)+String.fromCharCode(C>>16&255))},t.ByteStringBuffer.prototype.putInt32Le=function(C){return this.putBytes(String.fromCharCode(C&255)+String.fromCharCode(C>>8&255)+String.fromCharCode(C>>16&255)+String.fromCharCode(C>>24&255))},t.ByteStringBuffer.prototype.putInt=function(C,d){e(d);var M="";do d-=8,M+=String.fromCharCode(C>>d&255);while(d>0);return this.putBytes(M)},t.ByteStringBuffer.prototype.putSignedInt=function(C,d){return C<0&&(C+=2<<d-1),this.putInt(C,d)},t.ByteStringBuffer.prototype.putBuffer=function(C){return this.putBytes(C.getBytes())},t.ByteStringBuffer.prototype.getByte=function(){return this.data.charCodeAt(this.read++)},t.ByteStringBuffer.prototype.getInt16=function(){var C=this.data.charCodeAt(this.read)<<8^this.data.charCodeAt(this.read+1);return this.read+=2,C},t.ByteStringBuffer.prototype.getInt24=function(){var C=this.data.charCodeAt(this.read)<<16^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2);return this.read+=3,C},t.ByteStringBuffer.prototype.getInt32=function(){var C=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,C},t.ByteStringBuffer.prototype.getInt16Le=function(){var C=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8;return this.read+=2,C},t.ByteStringBuffer.prototype.getInt24Le=function(){var C=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2)<<16;return this.read+=3,C},t.ByteStringBuffer.prototype.getInt32Le=function(){var C=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,C},t.ByteStringBuffer.prototype.getInt=function(C){e(C);var d=0;do d=(d<<8)+this.data.charCodeAt(this.read++),C-=8;while(C>0);return d},t.ByteStringBuffer.prototype.getSignedInt=function(C){var d=this.getInt(C),M=2<<C-2;return d>=M&&(d-=M<<1),d},t.ByteStringBuffer.prototype.getBytes=function(C){var d;return C?(C=Math.min(this.length(),C),d=this.data.slice(this.read,this.read+C),this.read+=C):C===0?d="":(d=this.read===0?this.data:this.data.slice(this.read),this.clear()),d},t.ByteStringBuffer.prototype.bytes=function(C){return typeof C>"u"?this.data.slice(this.read):this.data.slice(this.read,this.read+C)},t.ByteStringBuffer.prototype.at=function(C){return this.data.charCodeAt(this.read+C)},t.ByteStringBuffer.prototype.setAt=function(C,d){return this.data=this.data.substr(0,this.read+C)+String.fromCharCode(d)+this.data.substr(this.read+C+1),this},t.ByteStringBuffer.prototype.last=function(){return this.data.charCodeAt(this.data.length-1)},t.ByteStringBuffer.prototype.copy=function(){var C=t.createBuffer(this.data);return C.read=this.read,C},t.ByteStringBuffer.prototype.compact=function(){return this.read>0&&(this.data=this.data.slice(this.read),this.read=0),this},t.ByteStringBuffer.prototype.clear=function(){return this.data="",this.read=0,this},t.ByteStringBuffer.prototype.truncate=function(C){var d=Math.max(0,this.length()-C);return this.data=this.data.substr(this.read,d),this.read=0,this},t.ByteStringBuffer.prototype.toHex=function(){for(var C="",d=this.read;d<this.data.length;++d){var M=this.data.charCodeAt(d);M<16&&(C+="0"),C+=M.toString(16)}return C},t.ByteStringBuffer.prototype.toString=function(){return t.decodeUtf8(this.bytes())};function o(C,d){d=d||{},this.read=d.readOffset||0,this.growSize=d.growSize||1024;var M=t.isArrayBuffer(C),y=t.isArrayBufferView(C);if(M||y){M?this.data=new DataView(C):this.data=new DataView(C.buffer,C.byteOffset,C.byteLength),this.write="writeOffset"in d?d.writeOffset:this.data.byteLength;return}this.data=new DataView(new ArrayBuffer(0)),this.write=0,C!=null&&this.putBytes(C),"writeOffset"in d&&(this.write=d.writeOffset)}t.DataBuffer=o,t.DataBuffer.prototype.length=function(){return this.write-this.read},t.DataBuffer.prototype.isEmpty=function(){return this.length()<=0},t.DataBuffer.prototype.accommodate=function(C,d){if(this.length()>=C)return this;d=Math.max(d||this.growSize,C);var M=new Uint8Array(this.data.buffer,this.data.byteOffset,this.data.byteLength),y=new Uint8Array(this.length()+d);return y.set(M),this.data=new DataView(y.buffer),this},t.DataBuffer.prototype.putByte=function(C){return this.accommodate(1),this.data.setUint8(this.write++,C),this},t.DataBuffer.prototype.fillWithByte=function(C,d){this.accommodate(d);for(var M=0;M<d;++M)this.data.setUint8(C);return this},t.DataBuffer.prototype.putBytes=function(C,d){if(t.isArrayBufferView(C)){var M=new Uint8Array(C.buffer,C.byteOffset,C.byteLength),y=M.byteLength-M.byteOffset;this.accommodate(y);var w=new Uint8Array(this.data.buffer,this.write);return w.set(M),this.write+=y,this}if(t.isArrayBuffer(C)){var M=new Uint8Array(C);this.accommodate(M.byteLength);var w=new Uint8Array(this.data.buffer);return w.set(M,this.write),this.write+=M.byteLength,this}if(C instanceof t.DataBuffer||typeof C=="object"&&typeof C.read=="number"&&typeof C.write=="number"&&t.isArrayBufferView(C.data)){var M=new Uint8Array(C.data.byteLength,C.read,C.length());this.accommodate(M.byteLength);var w=new Uint8Array(C.data.byteLength,this.write);return w.set(M),this.write+=M.byteLength,this}if(C instanceof t.ByteStringBuffer&&(C=C.data,d="binary"),d=d||"binary",typeof C=="string"){var D;if(d==="hex")return this.accommodate(Math.ceil(C.length/2)),D=new Uint8Array(this.data.buffer,this.write),this.write+=t.binary.hex.decode(C,D,this.write),this;if(d==="base64")return this.accommodate(Math.ceil(C.length/4)*3),D=new Uint8Array(this.data.buffer,this.write),this.write+=t.binary.base64.decode(C,D,this.write),this;if(d==="utf8"&&(C=t.encodeUtf8(C),d="binary"),d==="binary"||d==="raw")return this.accommodate(C.length),D=new Uint8Array(this.data.buffer,this.write),this.write+=t.binary.raw.decode(D),this;if(d==="utf16")return this.accommodate(C.length*2),D=new Uint16Array(this.data.buffer,this.write),this.write+=t.text.utf16.encode(D),this;throw new Error("Invalid encoding: "+d)}throw Error("Invalid parameter: "+C)},t.DataBuffer.prototype.putBuffer=function(C){return this.putBytes(C),C.clear(),this},t.DataBuffer.prototype.putString=function(C){return this.putBytes(C,"utf16")},t.DataBuffer.prototype.putInt16=function(C){return this.accommodate(2),this.data.setInt16(this.write,C),this.write+=2,this},t.DataBuffer.prototype.putInt24=function(C){return this.accommodate(3),this.data.setInt16(this.write,C>>8&65535),this.data.setInt8(this.write,C>>16&255),this.write+=3,this},t.DataBuffer.prototype.putInt32=function(C){return this.accommodate(4),this.data.setInt32(this.write,C),this.write+=4,this},t.DataBuffer.prototype.putInt16Le=function(C){return this.accommodate(2),this.data.setInt16(this.write,C,!0),this.write+=2,this},t.DataBuffer.prototype.putInt24Le=function(C){return this.accommodate(3),this.data.setInt8(this.write,C>>16&255),this.data.setInt16(this.write,C>>8&65535,!0),this.write+=3,this},t.DataBuffer.prototype.putInt32Le=function(C){return this.accommodate(4),this.data.setInt32(this.write,C,!0),this.write+=4,this},t.DataBuffer.prototype.putInt=function(C,d){e(d),this.accommodate(d/8);do d-=8,this.data.setInt8(this.write++,C>>d&255);while(d>0);return this},t.DataBuffer.prototype.putSignedInt=function(C,d){return e(d),this.accommodate(d/8),C<0&&(C+=2<<d-1),this.putInt(C,d)},t.DataBuffer.prototype.getByte=function(){return this.data.getInt8(this.read++)},t.DataBuffer.prototype.getInt16=function(){var C=this.data.getInt16(this.read);return this.read+=2,C},t.DataBuffer.prototype.getInt24=function(){var C=this.data.getInt16(this.read)<<8^this.data.getInt8(this.read+2);return this.read+=3,C},t.DataBuffer.prototype.getInt32=function(){var C=this.data.getInt32(this.read);return this.read+=4,C},t.DataBuffer.prototype.getInt16Le=function(){var C=this.data.getInt16(this.read,!0);return this.read+=2,C},t.DataBuffer.prototype.getInt24Le=function(){var C=this.data.getInt8(this.read)^this.data.getInt16(this.read+1,!0)<<8;return this.read+=3,C},t.DataBuffer.prototype.getInt32Le=function(){var C=this.data.getInt32(this.read,!0);return this.read+=4,C},t.DataBuffer.prototype.getInt=function(C){e(C);var d=0;do d=(d<<8)+this.data.getInt8(this.read++),C-=8;while(C>0);return d},t.DataBuffer.prototype.getSignedInt=function(C){var d=this.getInt(C),M=2<<C-2;return d>=M&&(d-=M<<1),d},t.DataBuffer.prototype.getBytes=function(C){var d;return C?(C=Math.min(this.length(),C),d=this.data.slice(this.read,this.read+C),this.read+=C):C===0?d="":(d=this.read===0?this.data:this.data.slice(this.read),this.clear()),d},t.DataBuffer.prototype.bytes=function(C){return typeof C>"u"?this.data.slice(this.read):this.data.slice(this.read,this.read+C)},t.DataBuffer.prototype.at=function(C){return this.data.getUint8(this.read+C)},t.DataBuffer.prototype.setAt=function(C,d){return this.data.setUint8(C,d),this},t.DataBuffer.prototype.last=function(){return this.data.getUint8(this.write-1)},t.DataBuffer.prototype.copy=function(){return new t.DataBuffer(this)},t.DataBuffer.prototype.compact=function(){if(this.read>0){var C=new Uint8Array(this.data.buffer,this.read),d=new Uint8Array(C.byteLength);d.set(C),this.data=new DataView(d),this.write-=this.read,this.read=0}return this},t.DataBuffer.prototype.clear=function(){return this.data=new DataView(new ArrayBuffer(0)),this.read=this.write=0,this},t.DataBuffer.prototype.truncate=function(C){return this.write=Math.max(0,this.length()-C),this.read=Math.min(this.read,this.write),this},t.DataBuffer.prototype.toHex=function(){for(var C="",d=this.read;d<this.data.byteLength;++d){var M=this.data.getUint8(d);M<16&&(C+="0"),C+=M.toString(16)}return C},t.DataBuffer.prototype.toString=function(C){var d=new Uint8Array(this.data,this.read,this.length());if(C=C||"utf8",C==="binary"||C==="raw")return t.binary.raw.encode(d);if(C==="hex")return t.binary.hex.encode(d);if(C==="base64")return t.binary.base64.encode(d);if(C==="utf8")return t.text.utf8.decode(d);if(C==="utf16")return t.text.utf16.decode(d);throw new Error("Invalid encoding: "+C)},t.createBuffer=function(C,d){return d=d||"raw",C!==void 0&&d==="utf8"&&(C=t.encodeUtf8(C)),new t.ByteBuffer(C)},t.fillString=function(C,d){for(var M="";d>0;)d&1&&(M+=C),d>>>=1,d>0&&(C+=C);return M},t.xorBytes=function(C,d,M){for(var y="",w="",D="",p=0,f=0;M>0;--M,++p)w=C.charCodeAt(p)^d.charCodeAt(p),f>=10&&(y+=D,D="",f=0),D+=String.fromCharCode(w),++f;return y+=D,y},t.hexToBytes=function(C){var d="",M=0;for(C.length&!0&&(M=1,d+=String.fromCharCode(parseInt(C[0],16)));M<C.length;M+=2)d+=String.fromCharCode(parseInt(C.substr(M,2),16));return d},t.bytesToHex=function(C){return t.createBuffer(C).toHex()},t.int32ToBytes=function(C){return String.fromCharCode(C>>24&255)+String.fromCharCode(C>>16&255)+String.fromCharCode(C>>8&255)+String.fromCharCode(C&255)};var g="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",a=[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],r="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";t.encode64=function(C,d){for(var M="",y="",w,D,p,f=0;f<C.length;)w=C.charCodeAt(f++),D=C.charCodeAt(f++),p=C.charCodeAt(f++),M+=g.charAt(w>>2),M+=g.charAt((w&3)<<4|D>>4),isNaN(D)?M+="==":(M+=g.charAt((D&15)<<2|p>>6),M+=isNaN(p)?"=":g.charAt(p&63)),d&&M.length>d&&(y+=M.substr(0,d)+`\r
|
|
6602
6602
|
`,M=M.substr(d));return y+=M,y},t.decode64=function(C){C=C.replace(/[^A-Za-z0-9\+\/\=]/g,"");for(var d="",M,y,w,D,p=0;p<C.length;)M=a[C.charCodeAt(p++)-43],y=a[C.charCodeAt(p++)-43],w=a[C.charCodeAt(p++)-43],D=a[C.charCodeAt(p++)-43],d+=String.fromCharCode(M<<2|y>>4),w!==64&&(d+=String.fromCharCode((y&15)<<4|w>>2),D!==64&&(d+=String.fromCharCode((w&3)<<6|D)));return d},t.encodeUtf8=function(C){return unescape(encodeURIComponent(C))},t.decodeUtf8=function(C){return decodeURIComponent(escape(C))},t.binary={raw:{},hex:{},base64:{},base58:{},baseN:{encode:A.encode,decode:A.decode}},t.binary.raw.encode=function(C){return String.fromCharCode.apply(null,C)},t.binary.raw.decode=function(C,d,M){var y=d;y||(y=new Uint8Array(C.length)),M=M||0;for(var w=M,D=0;D<C.length;++D)y[w++]=C.charCodeAt(D);return d?w-M:y},t.binary.hex.encode=t.bytesToHex,t.binary.hex.decode=function(C,d,M){var y=d;y||(y=new Uint8Array(Math.ceil(C.length/2))),M=M||0;var w=0,D=M;for(C.length&1&&(w=1,y[D++]=parseInt(C[0],16));w<C.length;w+=2)y[D++]=parseInt(C.substr(w,2),16);return d?D-M:y},t.binary.base64.encode=function(C,d){for(var M="",y="",w,D,p,f=0;f<C.byteLength;)w=C[f++],D=C[f++],p=C[f++],M+=g.charAt(w>>2),M+=g.charAt((w&3)<<4|D>>4),isNaN(D)?M+="==":(M+=g.charAt((D&15)<<2|p>>6),M+=isNaN(p)?"=":g.charAt(p&63)),d&&M.length>d&&(y+=M.substr(0,d)+`\r
|
|
6603
6603
|
`,M=M.substr(d));return y+=M,y},t.binary.base64.decode=function(C,d,M){var y=d;y||(y=new Uint8Array(Math.ceil(C.length/4)*3)),C=C.replace(/[^A-Za-z0-9\+\/\=]/g,""),M=M||0;for(var w,D,p,f,u=0,Y=M;u<C.length;)w=a[C.charCodeAt(u++)-43],D=a[C.charCodeAt(u++)-43],p=a[C.charCodeAt(u++)-43],f=a[C.charCodeAt(u++)-43],y[Y++]=w<<2|D>>4,p!==64&&(y[Y++]=(D&15)<<4|p>>2,f!==64&&(y[Y++]=(p&3)<<6|f));return d?Y-M:y.subarray(0,Y)},t.binary.base58.encode=function(C,d){return t.binary.baseN.encode(C,r,d)},t.binary.base58.decode=function(C,d){return t.binary.baseN.decode(C,r,d)},t.text={utf8:{},utf16:{}},t.text.utf8.encode=function(C,d,M){C=t.encodeUtf8(C);var y=d;y||(y=new Uint8Array(C.length)),M=M||0;for(var w=M,D=0;D<C.length;++D)y[w++]=C.charCodeAt(D);return d?w-M:y},t.text.utf8.decode=function(C){return t.decodeUtf8(String.fromCharCode.apply(null,C))},t.text.utf16.encode=function(C,d,M){var y=d;y||(y=new Uint8Array(C.length*2));var w=new Uint16Array(y.buffer);M=M||0;for(var D=M,p=M,f=0;f<C.length;++f)w[p++]=C.charCodeAt(f),D+=2;return d?D-M:y},t.text.utf16.decode=function(C){return String.fromCharCode.apply(null,new Uint16Array(C.buffer))},t.deflate=function(C,d,M){if(d=t.decode64(C.deflate(t.encode64(d)).rval),M){var y=2,w=d.charCodeAt(1);w&32&&(y=6),d=d.substring(y,d.length-4)}return d},t.inflate=function(C,d,M){var y=C.inflate(t.encode64(d)).rval;return y===null?null:t.decode64(y)};var I=function(C,d,M){if(!C)throw new Error("WebStorage not available.");var y;if(M===null?y=C.removeItem(d):(M=t.encode64(JSON.stringify(M)),y=C.setItem(d,M)),typeof y<"u"&&y.rval!==!0){var w=new Error(y.error.message);throw w.id=y.error.id,w.name=y.error.name,w}},l=function(C,d){if(!C)throw new Error("WebStorage not available.");var M=C.getItem(d);if(C.init)if(M.rval===null){if(M.error){var y=new Error(M.error.message);throw y.id=M.error.id,y.name=M.error.name,y}M=null}else M=M.rval;return M!==null&&(M=JSON.parse(t.decode64(M))),M},h=function(C,d,M,y){var w=l(C,d);w===null&&(w={}),w[M]=y,I(C,d,w)},B=function(C,d,M){var y=l(C,d);return y!==null&&(y=M in y?y[M]:null),y},E=function(C,d,M){var y=l(C,d);if(y!==null&&M in y){delete y[M];var w=!0;for(var D in y){w=!1;break}w&&(y=null),I(C,d,y)}},c=function(C,d){I(C,d,null)},Q=function(C,d,M){var y=null;typeof M>"u"&&(M=["web","flash"]);var w,D=!1,p=null;for(var f in M){w=M[f];try{if(w==="flash"||w==="both"){if(d[0]===null)throw new Error("Flash local storage not available.");y=C.apply(this,d),D=w==="flash"}(w==="web"||w==="both")&&(d[0]=localStorage,y=C.apply(this,d),D=!0)}catch(u){p=u}if(D)break}if(!D)throw p;return y};return t.setItem=function(C,d,M,y,w){Q(h,arguments,w)},t.getItem=function(C,d,M,y){return Q(B,arguments,y)},t.removeItem=function(C,d,M,y){Q(E,arguments,y)},t.clearItems=function(C,d,M){Q(c,arguments,M)},t.isEmpty=function(C){for(var d in C)if(C.hasOwnProperty(d))return!1;return!0},t.format=function(C){for(var d=/%./g,M,y,w=0,D=[],p=0;M=d.exec(C);){y=C.substring(p,d.lastIndex-2),y.length>0&&D.push(y),p=d.lastIndex;var f=M[0][1];switch(f){case"s":case"o":w<arguments.length?D.push(arguments[w+++1]):D.push("<?>");break;case"%":D.push("%");break;default:D.push("<%"+f+"?>")}}return D.push(C.substring(p)),D.join("")},t.formatNumber=function(C,d,M,y){var w=C,D=isNaN(d=Math.abs(d))?2:d,p=M===void 0?",":M,f=y===void 0?".":y,u=w<0?"-":"",Y=parseInt(w=Math.abs(+w||0).toFixed(D),10)+"",b=Y.length>3?Y.length%3:0;return u+(b?Y.substr(0,b)+f:"")+Y.substr(b).replace(/(\d{3})(?=\d)/g,"$1"+f)+(D?p+Math.abs(w-Y).toFixed(D).slice(2):"")},t.formatSize=function(C){return C>=1073741824?C=t.formatNumber(C/1073741824,2,".","")+" GiB":C>=1048576?C=t.formatNumber(C/1048576,2,".","")+" MiB":C>=1024?C=t.formatNumber(C/1024,0)+" KiB":C=t.formatNumber(C,0)+" bytes",C},t.bytesFromIP=function(C){return C.indexOf(".")!==-1?t.bytesFromIPv4(C):C.indexOf(":")!==-1?t.bytesFromIPv6(C):null},t.bytesFromIPv4=function(C){if(C=C.split("."),C.length!==4)return null;for(var d=t.createBuffer(),M=0;M<C.length;++M){var y=parseInt(C[M],10);if(isNaN(y))return null;d.putByte(y)}return d.getBytes()},t.bytesFromIPv6=function(C){var d=0;C=C.split(":").filter(function(p){return p.length===0&&++d,!0});for(var M=(8-C.length+d)*2,y=t.createBuffer(),w=0;w<8;++w){if(!C[w]||C[w].length===0){y.fillWithByte(0,M),M=0;continue}var D=t.hexToBytes(C[w]);D.length<2&&y.putByte(0),y.putBytes(D)}return y.getBytes()},t.bytesToIP=function(C){return C.length===4?t.bytesToIPv4(C):C.length===16?t.bytesToIPv6(C):null},t.bytesToIPv4=function(C){if(C.length!==4)return null;for(var d=[],M=0;M<C.length;++M)d.push(C.charCodeAt(M));return d.join(".")},t.bytesToIPv6=function(C){if(C.length!==16)return null;for(var d=[],M=[],y=0,w=0;w<C.length;w+=2){for(var D=t.bytesToHex(C[w]+C[w+1]);D[0]==="0"&&D!=="0";)D=D.substr(1);if(D==="0"){var p=M[M.length-1],f=d.length;!p||f!==p.end+1?M.push({start:f,end:f}):(p.end=f,p.end-p.start>M[y].end-M[y].start&&(y=M.length-1))}d.push(D)}if(M.length>0){var u=M[y];u.end-u.start>0&&(d.splice(u.start,u.end-u.start+1,""),u.start===0&&d.unshift(""),u.end===7&&d.push(""))}return d.join(":")},t.estimateCores=function(C,d){if(typeof C=="function"&&(d=C,C={}),C=C||{},"cores"in t&&!C.update)return d(null,t.cores);if(typeof navigator<"u"&&"hardwareConcurrency"in navigator&&navigator.hardwareConcurrency>0)return t.cores=navigator.hardwareConcurrency,d(null,t.cores);if(typeof Worker>"u")return t.cores=1,d(null,t.cores);if(typeof Blob>"u")return t.cores=2,d(null,t.cores);var M=URL.createObjectURL(new Blob(["(",(function(){self.addEventListener("message",function(p){var f=Date.now(),u=f+4;self.postMessage({st:f,et:u})})}).toString(),")()"],{type:"application/javascript"}));y([],5,16);function y(p,f,u){if(f===0){var Y=Math.floor(p.reduce(function(b,m){return b+m},0)/p.length);return t.cores=Math.max(1,Y),URL.revokeObjectURL(M),d(null,t.cores)}w(u,function(b,m){p.push(D(u,m)),y(p,f-1,u)})}function w(p,f){for(var u=[],Y=[],b=0;b<p;++b){var m=new Worker(M);m.addEventListener("message",function(T){if(Y.push(T.data),Y.length===p){for(var F=0;F<p;++F)u[F].terminate();f(null,Y)}}),u.push(m)}for(var b=0;b<p;++b)u[b].postMessage(b)}function D(p,f){for(var u=[],Y=0;Y<p;++Y)for(var b=f[Y],m=u[Y]=[],T=0;T<p;++T)if(Y!==T){var F=f[T];(b.st>F.st&&b.st<F.et||F.st>b.st&&F.st<b.et)&&m.push(T)}return u.reduce(function(j,X){return Math.max(j,X.length)},0)}},Hy.exports}var Ly,GW;function zy(){if(GW)return Ly;GW=1;var s=Pt();Ut(),Ly=s.cipher=s.cipher||{},s.cipher.algorithms=s.cipher.algorithms||{},s.cipher.createCipher=function(t,e){var i=t;if(typeof i=="string"&&(i=s.cipher.getAlgorithm(i),i&&(i=i())),!i)throw new Error("Unsupported algorithm: "+t);return new s.cipher.BlockCipher({algorithm:i,key:e,decrypt:!1})},s.cipher.createDecipher=function(t,e){var i=t;if(typeof i=="string"&&(i=s.cipher.getAlgorithm(i),i&&(i=i())),!i)throw new Error("Unsupported algorithm: "+t);return new s.cipher.BlockCipher({algorithm:i,key:e,decrypt:!0})},s.cipher.registerAlgorithm=function(t,e){t=t.toUpperCase(),s.cipher.algorithms[t]=e},s.cipher.getAlgorithm=function(t){return t=t.toUpperCase(),t in s.cipher.algorithms?s.cipher.algorithms[t]:null};var A=s.cipher.BlockCipher=function(t){this.algorithm=t.algorithm,this.mode=this.algorithm.mode,this.blockSize=this.mode.blockSize,this._finish=!1,this._input=null,this.output=null,this._op=t.decrypt?this.mode.decrypt:this.mode.encrypt,this._decrypt=t.decrypt,this.algorithm.initialize(t)};return A.prototype.start=function(t){t=t||{};var e={};for(var i in t)e[i]=t[i];e.decrypt=this._decrypt,this._finish=!1,this._input=s.util.createBuffer(),this.output=t.output||s.util.createBuffer(),this.mode.start(e)},A.prototype.update=function(t){for(t&&this._input.putBuffer(t);!this._op.call(this.mode,this._input,this.output,this._finish)&&!this._finish;);this._input.compact()},A.prototype.finish=function(t){t&&(this.mode.name==="ECB"||this.mode.name==="CBC")&&(this.mode.pad=function(i){return t(this.blockSize,i,!1)},this.mode.unpad=function(i){return t(this.blockSize,i,!0)});var e={};return e.decrypt=this._decrypt,e.overflow=this._input.length()%this.blockSize,!(!this._decrypt&&this.mode.pad&&!this.mode.pad(this._input,e)||(this._finish=!0,this.update(),this._decrypt&&this.mode.unpad&&!this.mode.unpad(this.output,e))||this.mode.afterFinish&&!this.mode.afterFinish(this.output,e))},Ly}var vy={exports:{}},TW;function KW(){if(TW)return vy.exports;TW=1;var s=Pt();Ut(),s.cipher=s.cipher||{};var A=vy.exports=s.cipher.modes=s.cipher.modes||{};A.ecb=function(n){n=n||{},this.name="ECB",this.cipher=n.cipher,this.blockSize=n.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints)},A.ecb.prototype.start=function(n){},A.ecb.prototype.encrypt=function(n,o,g){if(n.length()<this.blockSize&&!(g&&n.length()>0))return!0;for(var a=0;a<this._ints;++a)this._inBlock[a]=n.getInt32();this.cipher.encrypt(this._inBlock,this._outBlock);for(var a=0;a<this._ints;++a)o.putInt32(this._outBlock[a])},A.ecb.prototype.decrypt=function(n,o,g){if(n.length()<this.blockSize&&!(g&&n.length()>0))return!0;for(var a=0;a<this._ints;++a)this._inBlock[a]=n.getInt32();this.cipher.decrypt(this._inBlock,this._outBlock);for(var a=0;a<this._ints;++a)o.putInt32(this._outBlock[a])},A.ecb.prototype.pad=function(n,o){var g=n.length()===this.blockSize?this.blockSize:this.blockSize-n.length();return n.fillWithByte(g,g),!0},A.ecb.prototype.unpad=function(n,o){if(o.overflow>0)return!1;var g=n.length(),a=n.at(g-1);return a>this.blockSize<<2?!1:(n.truncate(a),!0)},A.cbc=function(n){n=n||{},this.name="CBC",this.cipher=n.cipher,this.blockSize=n.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints)},A.cbc.prototype.start=function(n){if(n.iv===null){if(!this._prev)throw new Error("Invalid IV parameter.");this._iv=this._prev.slice(0)}else if("iv"in n)this._iv=t(n.iv,this.blockSize),this._prev=this._iv.slice(0);else throw new Error("Invalid IV parameter.")},A.cbc.prototype.encrypt=function(n,o,g){if(n.length()<this.blockSize&&!(g&&n.length()>0))return!0;for(var a=0;a<this._ints;++a)this._inBlock[a]=this._prev[a]^n.getInt32();this.cipher.encrypt(this._inBlock,this._outBlock);for(var a=0;a<this._ints;++a)o.putInt32(this._outBlock[a]);this._prev=this._outBlock},A.cbc.prototype.decrypt=function(n,o,g){if(n.length()<this.blockSize&&!(g&&n.length()>0))return!0;for(var a=0;a<this._ints;++a)this._inBlock[a]=n.getInt32();this.cipher.decrypt(this._inBlock,this._outBlock);for(var a=0;a<this._ints;++a)o.putInt32(this._prev[a]^this._outBlock[a]);this._prev=this._inBlock.slice(0)},A.cbc.prototype.pad=function(n,o){var g=n.length()===this.blockSize?this.blockSize:this.blockSize-n.length();return n.fillWithByte(g,g),!0},A.cbc.prototype.unpad=function(n,o){if(o.overflow>0)return!1;var g=n.length(),a=n.at(g-1);return a>this.blockSize<<2?!1:(n.truncate(a),!0)},A.cfb=function(n){n=n||{},this.name="CFB",this.cipher=n.cipher,this.blockSize=n.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialBlock=new Array(this._ints),this._partialOutput=s.util.createBuffer(),this._partialBytes=0},A.cfb.prototype.start=function(n){if(!("iv"in n))throw new Error("Invalid IV parameter.");this._iv=t(n.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},A.cfb.prototype.encrypt=function(n,o,g){var a=n.length();if(a===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&a>=this.blockSize){for(var r=0;r<this._ints;++r)this._inBlock[r]=n.getInt32()^this._outBlock[r],o.putInt32(this._inBlock[r]);return}var I=(this.blockSize-a)%this.blockSize;I>0&&(I=this.blockSize-I),this._partialOutput.clear();for(var r=0;r<this._ints;++r)this._partialBlock[r]=n.getInt32()^this._outBlock[r],this._partialOutput.putInt32(this._partialBlock[r]);if(I>0)n.read-=this.blockSize;else for(var r=0;r<this._ints;++r)this._inBlock[r]=this._partialBlock[r];if(this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),I>0&&!g)return o.putBytes(this._partialOutput.getBytes(I-this._partialBytes)),this._partialBytes=I,!0;o.putBytes(this._partialOutput.getBytes(a-this._partialBytes)),this._partialBytes=0},A.cfb.prototype.decrypt=function(n,o,g){var a=n.length();if(a===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&a>=this.blockSize){for(var r=0;r<this._ints;++r)this._inBlock[r]=n.getInt32(),o.putInt32(this._inBlock[r]^this._outBlock[r]);return}var I=(this.blockSize-a)%this.blockSize;I>0&&(I=this.blockSize-I),this._partialOutput.clear();for(var r=0;r<this._ints;++r)this._partialBlock[r]=n.getInt32(),this._partialOutput.putInt32(this._partialBlock[r]^this._outBlock[r]);if(I>0)n.read-=this.blockSize;else for(var r=0;r<this._ints;++r)this._inBlock[r]=this._partialBlock[r];if(this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),I>0&&!g)return o.putBytes(this._partialOutput.getBytes(I-this._partialBytes)),this._partialBytes=I,!0;o.putBytes(this._partialOutput.getBytes(a-this._partialBytes)),this._partialBytes=0},A.ofb=function(n){n=n||{},this.name="OFB",this.cipher=n.cipher,this.blockSize=n.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialOutput=s.util.createBuffer(),this._partialBytes=0},A.ofb.prototype.start=function(n){if(!("iv"in n))throw new Error("Invalid IV parameter.");this._iv=t(n.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},A.ofb.prototype.encrypt=function(n,o,g){var a=n.length();if(n.length()===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&a>=this.blockSize){for(var r=0;r<this._ints;++r)o.putInt32(n.getInt32()^this._outBlock[r]),this._inBlock[r]=this._outBlock[r];return}var I=(this.blockSize-a)%this.blockSize;I>0&&(I=this.blockSize-I),this._partialOutput.clear();for(var r=0;r<this._ints;++r)this._partialOutput.putInt32(n.getInt32()^this._outBlock[r]);if(I>0)n.read-=this.blockSize;else for(var r=0;r<this._ints;++r)this._inBlock[r]=this._outBlock[r];if(this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),I>0&&!g)return o.putBytes(this._partialOutput.getBytes(I-this._partialBytes)),this._partialBytes=I,!0;o.putBytes(this._partialOutput.getBytes(a-this._partialBytes)),this._partialBytes=0},A.ofb.prototype.decrypt=A.ofb.prototype.encrypt,A.ctr=function(n){n=n||{},this.name="CTR",this.cipher=n.cipher,this.blockSize=n.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialOutput=s.util.createBuffer(),this._partialBytes=0},A.ctr.prototype.start=function(n){if(!("iv"in n))throw new Error("Invalid IV parameter.");this._iv=t(n.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},A.ctr.prototype.encrypt=function(n,o,g){var a=n.length();if(a===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&a>=this.blockSize)for(var r=0;r<this._ints;++r)o.putInt32(n.getInt32()^this._outBlock[r]);else{var I=(this.blockSize-a)%this.blockSize;I>0&&(I=this.blockSize-I),this._partialOutput.clear();for(var r=0;r<this._ints;++r)this._partialOutput.putInt32(n.getInt32()^this._outBlock[r]);if(I>0&&(n.read-=this.blockSize),this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),I>0&&!g)return o.putBytes(this._partialOutput.getBytes(I-this._partialBytes)),this._partialBytes=I,!0;o.putBytes(this._partialOutput.getBytes(a-this._partialBytes)),this._partialBytes=0}e(this._inBlock)},A.ctr.prototype.decrypt=A.ctr.prototype.encrypt,A.gcm=function(n){n=n||{},this.name="GCM",this.cipher=n.cipher,this.blockSize=n.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints),this._partialOutput=s.util.createBuffer(),this._partialBytes=0,this._R=3774873600},A.gcm.prototype.start=function(n){if(!("iv"in n))throw new Error("Invalid IV parameter.");var o=s.util.createBuffer(n.iv);this._cipherLength=0;var g;if("additionalData"in n?g=s.util.createBuffer(n.additionalData):g=s.util.createBuffer(),"tagLength"in n?this._tagLength=n.tagLength:this._tagLength=128,this._tag=null,n.decrypt&&(this._tag=s.util.createBuffer(n.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 a=o.length();if(a===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(i(a*8)))}this._inBlock=this._j0.slice(0),e(this._inBlock),this._partialBytes=0,g=s.util.createBuffer(g),this._aDataLength=i(g.length()*8);var r=g.length()%this.blockSize;for(r&&g.fillWithByte(0,this.blockSize-r),this._s=[0,0,0,0];g.length()>0;)this._s=this.ghash(this._hashSubkey,this._s,[g.getInt32(),g.getInt32(),g.getInt32(),g.getInt32()])},A.gcm.prototype.encrypt=function(n,o,g){var a=n.length();if(a===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&a>=this.blockSize){for(var r=0;r<this._ints;++r)o.putInt32(this._outBlock[r]^=n.getInt32());this._cipherLength+=this.blockSize}else{var I=(this.blockSize-a)%this.blockSize;I>0&&(I=this.blockSize-I),this._partialOutput.clear();for(var r=0;r<this._ints;++r)this._partialOutput.putInt32(n.getInt32()^this._outBlock[r]);if(I<=0||g){if(g){var l=a%this.blockSize;this._cipherLength+=l,this._partialOutput.truncate(this.blockSize-l)}else this._cipherLength+=this.blockSize;for(var r=0;r<this._ints;++r)this._outBlock[r]=this._partialOutput.getInt32();this._partialOutput.read-=this.blockSize}if(this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),I>0&&!g)return n.read-=this.blockSize,o.putBytes(this._partialOutput.getBytes(I-this._partialBytes)),this._partialBytes=I,!0;o.putBytes(this._partialOutput.getBytes(a-this._partialBytes)),this._partialBytes=0}this._s=this.ghash(this._hashSubkey,this._s,this._outBlock),e(this._inBlock)},A.gcm.prototype.decrypt=function(n,o,g){var a=n.length();if(a<this.blockSize&&!(g&&a>0))return!0;this.cipher.encrypt(this._inBlock,this._outBlock),e(this._inBlock),this._hashBlock[0]=n.getInt32(),this._hashBlock[1]=n.getInt32(),this._hashBlock[2]=n.getInt32(),this._hashBlock[3]=n.getInt32(),this._s=this.ghash(this._hashSubkey,this._s,this._hashBlock);for(var r=0;r<this._ints;++r)o.putInt32(this._outBlock[r]^this._hashBlock[r]);a<this.blockSize?this._cipherLength+=a%this.blockSize:this._cipherLength+=this.blockSize},A.gcm.prototype.afterFinish=function(n,o){var g=!0;o.decrypt&&o.overflow&&n.truncate(this.blockSize-o.overflow),this.tag=s.util.createBuffer();var a=this._aDataLength.concat(i(this._cipherLength*8));this._s=this.ghash(this._hashSubkey,this._s,a);var r=[];this.cipher.encrypt(this._j0,r);for(var I=0;I<this._ints;++I)this.tag.putInt32(this._s[I]^r[I]);return this.tag.truncate(this.tag.length()%(this._tagLength/8)),o.decrypt&&this.tag.bytes()!==this._tag&&(g=!1),g},A.gcm.prototype.multiply=function(n,o){for(var g=[0,0,0,0],a=o.slice(0),r=0;r<128;++r){var I=n[r/32|0]&1<<31-r%32;I&&(g[0]^=a[0],g[1]^=a[1],g[2]^=a[2],g[3]^=a[3]),this.pow(a,a)}return g},A.gcm.prototype.pow=function(n,o){for(var g=n[3]&1,a=3;a>0;--a)o[a]=n[a]>>>1|(n[a-1]&1)<<31;o[0]=n[0]>>>1,g&&(o[0]^=this._R)},A.gcm.prototype.tableMultiply=function(n){for(var o=[0,0,0,0],g=0;g<32;++g){var a=g/8|0,r=n[a]>>>(7-g%8)*4&15,I=this._m[g][r];o[0]^=I[0],o[1]^=I[1],o[2]^=I[2],o[3]^=I[3]}return o},A.gcm.prototype.ghash=function(n,o,g){return o[0]^=g[0],o[1]^=g[1],o[2]^=g[2],o[3]^=g[3],this.tableMultiply(o)},A.gcm.prototype.generateHashTable=function(n,o){for(var g=8/o,a=4*g,r=16*g,I=new Array(r),l=0;l<r;++l){var h=[0,0,0,0],B=l/a|0,E=(a-1-l%a)*o;h[B]=1<<o-1<<E,I[l]=this.generateSubHashTable(this.multiply(h,n),o)}return I},A.gcm.prototype.generateSubHashTable=function(n,o){var g=1<<o,a=g>>>1,r=new Array(g);r[a]=n.slice(0);for(var I=a>>>1;I>0;)this.pow(r[2*I],r[I]=[]),I>>=1;for(I=2;I<a;){for(var l=1;l<I;++l){var h=r[I],B=r[l];r[I+l]=[h[0]^B[0],h[1]^B[1],h[2]^B[2],h[3]^B[3]]}I*=2}for(r[0]=[0,0,0,0],I=a+1;I<g;++I){var E=r[I^a];r[I]=[n[0]^E[0],n[1]^E[1],n[2]^E[2],n[3]^E[3]]}return r};function t(n,o){if(typeof n=="string"&&(n=s.util.createBuffer(n)),s.util.isArray(n)&&n.length>4){var g=n;n=s.util.createBuffer();for(var a=0;a<g.length;++a)n.putByte(g[a])}if(n.length()<o)throw new Error("Invalid IV length; got "+n.length()+" bytes and expected "+o+" bytes.");if(!s.util.isArray(n)){for(var r=[],I=o/4,a=0;a<I;++a)r.push(n.getInt32());n=r}return n}function e(n){n[n.length-1]=n[n.length-1]+1&4294967295}function i(n){return[n/4294967296|0,n&4294967295]}return vy.exports}var _y,jW;function Qa(){if(jW)return _y;jW=1;var s=Pt();zy(),KW(),Ut(),_y=s.aes=s.aes||{},s.aes.startEncrypting=function(B,E,c,Q){var C=h({key:B,output:c,decrypt:!1,mode:Q});return C.start(E),C},s.aes.createEncryptionCipher=function(B,E){return h({key:B,output:null,decrypt:!1,mode:E})},s.aes.startDecrypting=function(B,E,c,Q){var C=h({key:B,output:c,decrypt:!0,mode:Q});return C.start(E),C},s.aes.createDecryptionCipher=function(B,E){return h({key:B,output:null,decrypt:!0,mode:E})},s.aes.Algorithm=function(B,E){t||r();var c=this;c.name=B,c.mode=new E({blockSize:16,cipher:{encrypt:function(Q,C){return l(c._w,Q,C,!1)},decrypt:function(Q,C){return l(c._w,Q,C,!0)}}}),c._init=!1},s.aes.Algorithm.prototype.initialize=function(B){if(!this._init){var E=B.key,c;if(typeof E=="string"&&(E.length===16||E.length===24||E.length===32))E=s.util.createBuffer(E);else if(s.util.isArray(E)&&(E.length===16||E.length===24||E.length===32)){c=E,E=s.util.createBuffer();for(var Q=0;Q<c.length;++Q)E.putByte(c[Q])}if(!s.util.isArray(E)){c=E,E=[];var C=c.length();if(C===16||C===24||C===32){C=C>>>2;for(var Q=0;Q<C;++Q)E.push(c.getInt32())}}if(!s.util.isArray(E)||!(E.length===4||E.length===6||E.length===8))throw new Error("Invalid key parameter.");var d=this.mode.name,M=["CFB","OFB","CTR","GCM"].indexOf(d)!==-1;this._w=I(E,B.decrypt&&!M),this._init=!0}},s.aes._expandKey=function(B,E){return t||r(),I(B,E)},s.aes._updateBlock=l,A("AES-ECB",s.cipher.modes.ecb),A("AES-CBC",s.cipher.modes.cbc),A("AES-CFB",s.cipher.modes.cfb),A("AES-OFB",s.cipher.modes.ofb),A("AES-CTR",s.cipher.modes.ctr),A("AES-GCM",s.cipher.modes.gcm);function A(B,E){var c=function(){return new s.aes.Algorithm(B,E)};s.cipher.registerAlgorithm(B,c)}var t=!1,e=4,i,n,o,g,a;function r(){t=!0,o=[0,1,2,4,8,16,32,64,128,27,54];for(var B=new Array(256),E=0;E<128;++E)B[E]=E<<1,B[E+128]=E+128<<1^283;i=new Array(256),n=new Array(256),g=new Array(4),a=new Array(4);for(var E=0;E<4;++E)g[E]=new Array(256),a[E]=new Array(256);for(var c=0,Q=0,C,d,M,y,w,D,p,E=0;E<256;++E){y=Q^Q<<1^Q<<2^Q<<3^Q<<4,y=y>>8^y&255^99,i[c]=y,n[y]=c,w=B[y],C=B[c],d=B[C],M=B[d],D=w<<24^y<<16^y<<8^(y^w),p=(C^d^M)<<24^(c^M)<<16^(c^d^M)<<8^(c^C^M);for(var f=0;f<4;++f)g[f][c]=D,a[f][y]=p,D=D<<24|D>>>8,p=p<<24|p>>>8;c===0?c=Q=1:(c=C^B[B[B[C^M]]],Q^=B[B[Q]])}}function I(B,E){for(var c=B.slice(0),Q,C=1,d=c.length,M=d+6+1,y=e*M,w=d;w<y;++w)Q=c[w-1],w%d===0?(Q=i[Q>>>16&255]<<24^i[Q>>>8&255]<<16^i[Q&255]<<8^i[Q>>>24]^o[C]<<24,C++):d>6&&w%d===4&&(Q=i[Q>>>24]<<24^i[Q>>>16&255]<<16^i[Q>>>8&255]<<8^i[Q&255]),c[w]=c[w-d]^Q;if(E){var D,p=a[0],f=a[1],u=a[2],Y=a[3],b=c.slice(0);y=c.length;for(var w=0,m=y-e;w<y;w+=e,m-=e)if(w===0||w===y-e)b[w]=c[m],b[w+1]=c[m+3],b[w+2]=c[m+2],b[w+3]=c[m+1];else for(var T=0;T<e;++T)D=c[m+T],b[w+(3&-T)]=p[i[D>>>24]]^f[i[D>>>16&255]]^u[i[D>>>8&255]]^Y[i[D&255]];c=b}return c}function l(B,E,c,Q){var C=B.length/4-1,d,M,y,w,D;Q?(d=a[0],M=a[1],y=a[2],w=a[3],D=n):(d=g[0],M=g[1],y=g[2],w=g[3],D=i);var p,f,u,Y,b,m,T;p=E[0]^B[0],f=E[Q?3:1]^B[1],u=E[2]^B[2],Y=E[Q?1:3]^B[3];for(var F=3,j=1;j<C;++j)b=d[p>>>24]^M[f>>>16&255]^y[u>>>8&255]^w[Y&255]^B[++F],m=d[f>>>24]^M[u>>>16&255]^y[Y>>>8&255]^w[p&255]^B[++F],T=d[u>>>24]^M[Y>>>16&255]^y[p>>>8&255]^w[f&255]^B[++F],Y=d[Y>>>24]^M[p>>>16&255]^y[f>>>8&255]^w[u&255]^B[++F],p=b,f=m,u=T;c[0]=D[p>>>24]<<24^D[f>>>16&255]<<16^D[u>>>8&255]<<8^D[Y&255]^B[++F],c[Q?3:1]=D[f>>>24]<<24^D[u>>>16&255]<<16^D[Y>>>8&255]<<8^D[p&255]^B[++F],c[2]=D[u>>>24]<<24^D[Y>>>16&255]<<16^D[p>>>8&255]<<8^D[f&255]^B[++F],c[Q?1:3]=D[Y>>>24]<<24^D[p>>>16&255]<<16^D[f>>>8&255]<<8^D[u&255]^B[++F]}function h(B){B=B||{};var E=(B.mode||"CBC").toUpperCase(),c="AES-"+E,Q;B.decrypt?Q=s.cipher.createDecipher(c,B.key):Q=s.cipher.createCipher(c,B.key);var C=Q.start;return Q.start=function(d,M){var y=null;M instanceof s.util.ByteBuffer&&(y=M,M={}),M=M||{},M.output=y,M.iv=d,C.call(Q,M)},Q}return _y}var qy={exports:{}},$y={exports:{}},Ap={exports:{}},RW;function da(){if(RW)return Ap.exports;RW=1;var s=Pt();s.pki=s.pki||{};var A=Ap.exports=s.pki.oids=s.oids=s.oids||{};function t(i,n){A[i]=n,A[n]=i}function e(i,n){A[i]=n}return t("1.2.840.113549.1.1.1","rsaEncryption"),t("1.2.840.113549.1.1.4","md5WithRSAEncryption"),t("1.2.840.113549.1.1.5","sha1WithRSAEncryption"),t("1.2.840.113549.1.1.7","RSAES-OAEP"),t("1.2.840.113549.1.1.8","mgf1"),t("1.2.840.113549.1.1.9","pSpecified"),t("1.2.840.113549.1.1.10","RSASSA-PSS"),t("1.2.840.113549.1.1.11","sha256WithRSAEncryption"),t("1.2.840.113549.1.1.12","sha384WithRSAEncryption"),t("1.2.840.113549.1.1.13","sha512WithRSAEncryption"),t("1.3.101.112","EdDSA25519"),t("1.2.840.10040.4.3","dsa-with-sha1"),t("1.3.14.3.2.7","desCBC"),t("1.3.14.3.2.26","sha1"),t("1.3.14.3.2.29","sha1WithRSASignature"),t("2.16.840.1.101.3.4.2.1","sha256"),t("2.16.840.1.101.3.4.2.2","sha384"),t("2.16.840.1.101.3.4.2.3","sha512"),t("2.16.840.1.101.3.4.2.4","sha224"),t("2.16.840.1.101.3.4.2.5","sha512-224"),t("2.16.840.1.101.3.4.2.6","sha512-256"),t("1.2.840.113549.2.2","md2"),t("1.2.840.113549.2.5","md5"),t("1.2.840.113549.1.7.1","data"),t("1.2.840.113549.1.7.2","signedData"),t("1.2.840.113549.1.7.3","envelopedData"),t("1.2.840.113549.1.7.4","signedAndEnvelopedData"),t("1.2.840.113549.1.7.5","digestedData"),t("1.2.840.113549.1.7.6","encryptedData"),t("1.2.840.113549.1.9.1","emailAddress"),t("1.2.840.113549.1.9.2","unstructuredName"),t("1.2.840.113549.1.9.3","contentType"),t("1.2.840.113549.1.9.4","messageDigest"),t("1.2.840.113549.1.9.5","signingTime"),t("1.2.840.113549.1.9.6","counterSignature"),t("1.2.840.113549.1.9.7","challengePassword"),t("1.2.840.113549.1.9.8","unstructuredAddress"),t("1.2.840.113549.1.9.14","extensionRequest"),t("1.2.840.113549.1.9.20","friendlyName"),t("1.2.840.113549.1.9.21","localKeyId"),t("1.2.840.113549.1.9.22.1","x509Certificate"),t("1.2.840.113549.1.12.10.1.1","keyBag"),t("1.2.840.113549.1.12.10.1.2","pkcs8ShroudedKeyBag"),t("1.2.840.113549.1.12.10.1.3","certBag"),t("1.2.840.113549.1.12.10.1.4","crlBag"),t("1.2.840.113549.1.12.10.1.5","secretBag"),t("1.2.840.113549.1.12.10.1.6","safeContentsBag"),t("1.2.840.113549.1.5.13","pkcs5PBES2"),t("1.2.840.113549.1.5.12","pkcs5PBKDF2"),t("1.2.840.113549.1.12.1.1","pbeWithSHAAnd128BitRC4"),t("1.2.840.113549.1.12.1.2","pbeWithSHAAnd40BitRC4"),t("1.2.840.113549.1.12.1.3","pbeWithSHAAnd3-KeyTripleDES-CBC"),t("1.2.840.113549.1.12.1.4","pbeWithSHAAnd2-KeyTripleDES-CBC"),t("1.2.840.113549.1.12.1.5","pbeWithSHAAnd128BitRC2-CBC"),t("1.2.840.113549.1.12.1.6","pbewithSHAAnd40BitRC2-CBC"),t("1.2.840.113549.2.7","hmacWithSHA1"),t("1.2.840.113549.2.8","hmacWithSHA224"),t("1.2.840.113549.2.9","hmacWithSHA256"),t("1.2.840.113549.2.10","hmacWithSHA384"),t("1.2.840.113549.2.11","hmacWithSHA512"),t("1.2.840.113549.3.7","des-EDE3-CBC"),t("2.16.840.1.101.3.4.1.2","aes128-CBC"),t("2.16.840.1.101.3.4.1.22","aes192-CBC"),t("2.16.840.1.101.3.4.1.42","aes256-CBC"),t("2.5.4.3","commonName"),t("2.5.4.4","surname"),t("2.5.4.5","serialNumber"),t("2.5.4.6","countryName"),t("2.5.4.7","localityName"),t("2.5.4.8","stateOrProvinceName"),t("2.5.4.9","streetAddress"),t("2.5.4.10","organizationName"),t("2.5.4.11","organizationalUnitName"),t("2.5.4.12","title"),t("2.5.4.13","description"),t("2.5.4.15","businessCategory"),t("2.5.4.17","postalCode"),t("2.5.4.42","givenName"),t("2.5.4.65","pseudonym"),t("1.3.6.1.4.1.311.60.2.1.2","jurisdictionOfIncorporationStateOrProvinceName"),t("1.3.6.1.4.1.311.60.2.1.3","jurisdictionOfIncorporationCountryName"),t("2.16.840.1.113730.1.1","nsCertType"),t("2.16.840.1.113730.1.13","nsComment"),e("2.5.29.1","authorityKeyIdentifier"),e("2.5.29.2","keyAttributes"),e("2.5.29.3","certificatePolicies"),e("2.5.29.4","keyUsageRestriction"),e("2.5.29.5","policyMapping"),e("2.5.29.6","subtreesConstraint"),e("2.5.29.7","subjectAltName"),e("2.5.29.8","issuerAltName"),e("2.5.29.9","subjectDirectoryAttributes"),e("2.5.29.10","basicConstraints"),e("2.5.29.11","nameConstraints"),e("2.5.29.12","policyConstraints"),e("2.5.29.13","basicConstraints"),t("2.5.29.14","subjectKeyIdentifier"),t("2.5.29.15","keyUsage"),e("2.5.29.16","privateKeyUsagePeriod"),t("2.5.29.17","subjectAltName"),t("2.5.29.18","issuerAltName"),t("2.5.29.19","basicConstraints"),e("2.5.29.20","cRLNumber"),e("2.5.29.21","cRLReason"),e("2.5.29.22","expirationDate"),e("2.5.29.23","instructionCode"),e("2.5.29.24","invalidityDate"),e("2.5.29.25","cRLDistributionPoints"),e("2.5.29.26","issuingDistributionPoint"),e("2.5.29.27","deltaCRLIndicator"),e("2.5.29.28","issuingDistributionPoint"),e("2.5.29.29","certificateIssuer"),e("2.5.29.30","nameConstraints"),t("2.5.29.31","cRLDistributionPoints"),t("2.5.29.32","certificatePolicies"),e("2.5.29.33","policyMappings"),e("2.5.29.34","policyConstraints"),t("2.5.29.35","authorityKeyIdentifier"),e("2.5.29.36","policyConstraints"),t("2.5.29.37","extKeyUsage"),e("2.5.29.46","freshestCRL"),e("2.5.29.54","inhibitAnyPolicy"),t("1.3.6.1.4.1.11129.2.4.2","timestampList"),t("1.3.6.1.5.5.7.1.1","authorityInfoAccess"),t("1.3.6.1.5.5.7.3.1","serverAuth"),t("1.3.6.1.5.5.7.3.2","clientAuth"),t("1.3.6.1.5.5.7.3.3","codeSigning"),t("1.3.6.1.5.5.7.3.4","emailProtection"),t("1.3.6.1.5.5.7.3.8","timeStamping"),Ap.exports}var ZW;function Pn(){if(ZW)return $y.exports;ZW=1;var s=Pt();Ut(),da();var A=$y.exports=s.asn1=s.asn1||{};A.Class={UNIVERSAL:0,APPLICATION:64,CONTEXT_SPECIFIC:128,PRIVATE:192},A.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},A.maxDepth=256,A.create=function(o,g,a,r,I){if(s.util.isArray(r)){for(var l=[],h=0;h<r.length;++h)r[h]!==void 0&&l.push(r[h]);r=l}var B={tagClass:o,type:g,constructed:a,composed:a||s.util.isArray(r),value:r};return I&&"bitStringContents"in I&&(B.bitStringContents=I.bitStringContents,B.original=A.copy(B)),B},A.copy=function(o,g){var a;if(s.util.isArray(o)){a=[];for(var r=0;r<o.length;++r)a.push(A.copy(o[r],g));return a}return typeof o=="string"?o:(a={tagClass:o.tagClass,type:o.type,constructed:o.constructed,composed:o.composed,value:A.copy(o.value,g)},g&&!g.excludeBitStringContents&&(a.bitStringContents=o.bitStringContents),a)},A.equals=function(o,g,a){if(s.util.isArray(o)){if(!s.util.isArray(g)||o.length!==g.length)return!1;for(var r=0;r<o.length;++r)if(!A.equals(o[r],g[r]))return!1;return!0}if(typeof o!=typeof g)return!1;if(typeof o=="string")return o===g;var I=o.tagClass===g.tagClass&&o.type===g.type&&o.constructed===g.constructed&&o.composed===g.composed&&A.equals(o.value,g.value);return a&&a.includeBitStringContents&&(I=I&&o.bitStringContents===g.bitStringContents),I},A.getBerValueLength=function(o){var g=o.getByte();if(g!==128){var a,r=g&128;return r?a=o.getInt((g&127)<<3):a=g,a}};function t(o,g,a){if(a>g){var r=new Error("Too few bytes to parse DER.");throw r.available=o.length(),r.remaining=g,r.requested=a,r}}var e=function(o,g){var a=o.getByte();if(g--,a!==128){var r,I=a&128;if(!I)r=a;else{var l=a&127;t(o,g,l),r=o.getInt(l<<3)}if(r<0)throw new Error("Negative length: "+r);return r}};A.fromDer=function(o,g){g===void 0&&(g={strict:!0,parseAllBytes:!0,decodeBitStrings:!0}),typeof g=="boolean"&&(g={strict:g,parseAllBytes:!0,decodeBitStrings:!0}),"strict"in g||(g.strict=!0),"parseAllBytes"in g||(g.parseAllBytes=!0),"decodeBitStrings"in g||(g.decodeBitStrings=!0),"maxDepth"in g||(g.maxDepth=A.maxDepth),typeof o=="string"&&(o=s.util.createBuffer(o));var a=o.length(),r=i(o,o.length(),0,g);if(g.parseAllBytes&&o.length()!==0){var I=new Error("Unparsed DER bytes remain after ASN.1 parsing.");throw I.byteCount=a,I.remaining=o.length(),I}return r};function i(o,g,a,r){if(a>=r.maxDepth)throw new Error("ASN.1 parsing error: Max depth exceeded.");var I;t(o,g,2);var l=o.getByte();g--;var h=l&192,B=l&31;I=o.length();var E=e(o,g);if(g-=I-o.length(),E!==void 0&&E>g){if(r.strict){var c=new Error("Too few bytes to read ASN.1 value.");throw c.available=o.length(),c.remaining=g,c.requested=E,c}E=g}var Q,C,d=(l&32)===32;if(d)if(Q=[],E===void 0)for(;;){if(t(o,g,2),o.bytes(2)==="\0\0"){o.getBytes(2),g-=2;break}I=o.length(),Q.push(i(o,g,a+1,r)),g-=I-o.length()}else for(;E>0;)I=o.length(),Q.push(i(o,E,a+1,r)),g-=I-o.length(),E-=I-o.length();if(Q===void 0&&h===A.Class.UNIVERSAL&&B===A.Type.BITSTRING&&(C=o.bytes(E)),Q===void 0&&r.decodeBitStrings&&h===A.Class.UNIVERSAL&&B===A.Type.BITSTRING&&E>1){var M=o.read,y=g,w=0;if(B===A.Type.BITSTRING&&(t(o,g,1),w=o.getByte(),g--),w===0)try{I=o.length();var D={strict:!0,decodeBitStrings:!0},p=i(o,g,a+1,D),f=I-o.length();g-=f,B==A.Type.BITSTRING&&f++;var u=p.tagClass;f===E&&(u===A.Class.UNIVERSAL||u===A.Class.CONTEXT_SPECIFIC)&&(Q=[p])}catch{}Q===void 0&&(o.read=M,g=y)}if(Q===void 0){if(E===void 0){if(r.strict)throw new Error("Non-constructed ASN.1 object of indefinite length.");E=g}if(B===A.Type.BMPSTRING)for(Q="";E>0;E-=2)t(o,g,2),Q+=String.fromCharCode(o.getInt16()),g-=2;else Q=o.getBytes(E),g-=E}var Y=C===void 0?null:{bitStringContents:C};return A.create(h,B,d,Q,Y)}A.toDer=function(o){var g=s.util.createBuffer(),a=o.tagClass|o.type,r=s.util.createBuffer(),I=!1;if("bitStringContents"in o&&(I=!0,o.original&&(I=A.equals(o,o.original))),I)r.putBytes(o.bitStringContents);else if(o.composed){o.constructed?a|=32:r.putByte(0);for(var l=0;l<o.value.length;++l)o.value[l]!==void 0&&r.putBuffer(A.toDer(o.value[l]))}else if(o.type===A.Type.BMPSTRING)for(var l=0;l<o.value.length;++l)r.putInt16(o.value.charCodeAt(l));else o.type===A.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)?r.putBytes(o.value.substr(1)):r.putBytes(o.value);if(g.putByte(a),r.length()<=127)g.putByte(r.length()&127);else{var h=r.length(),B="";do B+=String.fromCharCode(h&255),h=h>>>8;while(h>0);g.putByte(B.length|128);for(var l=B.length-1;l>=0;--l)g.putByte(B.charCodeAt(l))}return g.putBuffer(r),g},A.oidToDer=function(o){var g=o.split("."),a=s.util.createBuffer();a.putByte(40*parseInt(g[0],10)+parseInt(g[1],10));for(var r,I,l,h,B=2;B<g.length;++B){if(r=!0,I=[],l=parseInt(g[B],10),l>4294967295)throw new Error("OID value too large; max is 32-bits.");do h=l&127,l=l>>>7,r||(h|=128),I.push(h),r=!1;while(l>0);for(var E=I.length-1;E>=0;--E)a.putByte(I[E])}return a},A.derToOid=function(o){var g;typeof o=="string"&&(o=s.util.createBuffer(o));var a=o.getByte();g=Math.floor(a/40)+"."+a%40;for(var r=0;o.length()>0;){if(r>70368744177663)throw new Error("OID value too large; max is 53-bits.");a=o.getByte(),r=r*128,a&128?r+=a&127:(g+="."+(r+a),r=0)}return g},A.utcTimeToDate=function(o){var g=new Date,a=parseInt(o.substr(0,2),10);a=a>=50?1900+a:2e3+a;var r=parseInt(o.substr(2,2),10)-1,I=parseInt(o.substr(4,2),10),l=parseInt(o.substr(6,2),10),h=parseInt(o.substr(8,2),10),B=0;if(o.length>11){var E=o.charAt(10),c=10;E!=="+"&&E!=="-"&&(B=parseInt(o.substr(10,2),10),c+=2)}if(g.setUTCFullYear(a,r,I),g.setUTCHours(l,h,B,0),c&&(E=o.charAt(c),E==="+"||E==="-")){var Q=parseInt(o.substr(c+1,2),10),C=parseInt(o.substr(c+4,2),10),d=Q*60+C;d*=6e4,E==="+"?g.setTime(+g-d):g.setTime(+g+d)}return g},A.generalizedTimeToDate=function(o){var g=new Date,a=parseInt(o.substr(0,4),10),r=parseInt(o.substr(4,2),10)-1,I=parseInt(o.substr(6,2),10),l=parseInt(o.substr(8,2),10),h=parseInt(o.substr(10,2),10),B=parseInt(o.substr(12,2),10),E=0,c=0,Q=!1;o.charAt(o.length-1)==="Z"&&(Q=!0);var C=o.length-5,d=o.charAt(C);if(d==="+"||d==="-"){var M=parseInt(o.substr(C+1,2),10),y=parseInt(o.substr(C+4,2),10);c=M*60+y,c*=6e4,d==="+"&&(c*=-1),Q=!0}return o.charAt(14)==="."&&(E=parseFloat(o.substr(14),10)*1e3),Q?(g.setUTCFullYear(a,r,I),g.setUTCHours(l,h,B,E),g.setTime(+g+c)):(g.setFullYear(a,r,I),g.setHours(l,h,B,E)),g},A.dateToUtcTime=function(o){if(typeof o=="string")return o;var g="",a=[];a.push((""+o.getUTCFullYear()).substr(2)),a.push(""+(o.getUTCMonth()+1)),a.push(""+o.getUTCDate()),a.push(""+o.getUTCHours()),a.push(""+o.getUTCMinutes()),a.push(""+o.getUTCSeconds());for(var r=0;r<a.length;++r)a[r].length<2&&(g+="0"),g+=a[r];return g+="Z",g},A.dateToGeneralizedTime=function(o){if(typeof o=="string")return o;var g="",a=[];a.push(""+o.getUTCFullYear()),a.push(""+(o.getUTCMonth()+1)),a.push(""+o.getUTCDate()),a.push(""+o.getUTCHours()),a.push(""+o.getUTCMinutes()),a.push(""+o.getUTCSeconds());for(var r=0;r<a.length;++r)a[r].length<2&&(g+="0"),g+=a[r];return g+="Z",g},A.integerToDer=function(o){var g=s.util.createBuffer();if(o>=-128&&o<128)return g.putSignedInt(o,8);if(o>=-32768&&o<32768)return g.putSignedInt(o,16);if(o>=-8388608&&o<8388608)return g.putSignedInt(o,24);if(o>=-2147483648&&o<2147483648)return g.putSignedInt(o,32);var a=new Error("Integer too large; max is 32-bits.");throw a.integer=o,a},A.derToInteger=function(o){typeof o=="string"&&(o=s.util.createBuffer(o));var g=o.length()*8;if(g>32)throw new Error("Integer too large; max is 32-bits.");return o.getSignedInt(g)},A.validate=function(o,g,a,r){var I=!1;if((o.tagClass===g.tagClass||typeof g.tagClass>"u")&&(o.type===g.type||typeof g.type>"u"))if(o.constructed===g.constructed||typeof g.constructed>"u"){if(I=!0,g.value&&s.util.isArray(g.value))for(var l=0,h=0;I&&h<g.value.length;++h){var B=g.value[h];I=!!B.optional;var E=o.value[l];if(!E){B.optional||(I=!1,r&&r.push("["+g.name+'] Missing required element. Expected tag class "'+B.tagClass+'", type "'+B.type+'"'));continue}var c=typeof B.tagClass<"u"&&typeof B.type<"u";if(c&&(E.tagClass!==B.tagClass||E.type!==B.type))if(B.optional){I=!0;continue}else{I=!1,r&&r.push("["+g.name+"] Tag mismatch. Expected ("+B.tagClass+","+B.type+"), got ("+E.tagClass+","+E.type+")");break}var Q=A.validate(E,B,a,r);if(Q)++l,I=!0;else if(B.optional)I=!0;else{I=!1;break}}if(I&&a&&(g.capture&&(a[g.capture]=o.value),g.captureAsn1&&(a[g.captureAsn1]=o),g.captureBitStringContents&&"bitStringContents"in o&&(a[g.captureBitStringContents]=o.bitStringContents),g.captureBitStringValue&&"bitStringContents"in o))if(o.bitStringContents.length<2)a[g.captureBitStringValue]="";else{var C=o.bitStringContents.charCodeAt(0);if(C!==0)throw new Error("captureBitStringValue only supported for zero unused bits");a[g.captureBitStringValue]=o.bitStringContents.slice(1)}}else r&&r.push("["+g.name+'] Expected constructed "'+g.constructed+'", got "'+o.constructed+'"');else r&&(o.tagClass!==g.tagClass&&r.push("["+g.name+'] Expected tag class "'+g.tagClass+'", got "'+o.tagClass+'"'),o.type!==g.type&&r.push("["+g.name+'] Expected type "'+g.type+'", got "'+o.type+'"'));return I};var n=/[^\\u0000-\\u00ff]/;return A.prettyPrint=function(o,g,a){var r="";g=g||0,a=a||2,g>0&&(r+=`
|
|
@@ -6618,4 +6618,4 @@ void main() {
|
|
|
6618
6618
|
Private-Lines: `+B+`\r
|
|
6619
6619
|
`,I+=c;var w=i("putty-private-key-file-mac-key",o),D=s.util.createBuffer();e(D,a),e(D,r),e(D,g),D.putInt32(l.length()),D.putBuffer(l),D.putInt32(E.length()),D.putBuffer(E);var p=s.hmac.create();return p.start("sha1",w),p.update(D.bytes()),I+=`\r
|
|
6620
6620
|
Private-MAC: `+p.digest().toHex()+`\r
|
|
6621
|
-
`,I},A.publicKeyToOpenSSH=function(n,o){var g="ssh-rsa";o=o||"";var a=s.util.createBuffer();return e(a,g),t(a,n.e),t(a,n.n),g+" "+s.util.encode64(a.bytes())+" "+o},A.privateKeyToOpenSSH=function(n,o){return o?s.pki.encryptRsaPrivateKey(n,o,{legacy:!0,algorithm:"aes128"}):s.pki.privateKeyToPem(n)},A.getPublicKeyFingerprint=function(n,o){o=o||{};var g=o.md||s.md.md5.create(),a="ssh-rsa",r=s.util.createBuffer();e(r,a),t(r,n.e),t(r,n.n),g.start(),g.update(r.getBytes());var I=g.digest();if(o.encoding==="hex"){var l=I.toHex();return o.delimiter?l.match(/.{2}/g).join(o.delimiter):l}else{if(o.encoding==="binary")return I.getBytes();if(o.encoding)throw new Error('Unknown encoding "'+o.encoding+'".')}return I};function t(n,o){var g=o.toString(16);g[0]>="8"&&(g="00"+g);var a=s.util.hexToBytes(g);n.putInt32(a.length),n.putBytes(a)}function e(n,o){n.putInt32(o.length),n.putString(o)}function i(){for(var n=s.md.sha1.create(),o=arguments.length,g=0;g<o;++g)n.update(arguments[g]);return n.digest()}return Tp.exports}var Kp,FG;function h3(){return FG||(FG=1,Kp=Pt(),Qa(),n3(),Pn(),zy(),dQ(),g3(),xB(),a3(),r3(),I3(),IG(),Ip(),sI(),tG(),EG(),l3(),QG(),iG(),LW(),up(),An(),_W(),B3(),fG(),Ut()),Kp}var jp=h3();const C3="evtrsa1",Rp=new Map;function bG(s){return s.replace(/\/+$/,"")}function E3(s){return new TextEncoder().encode(s)}function wQ(s){let A="";return s.forEach(t=>{A+=String.fromCharCode(t)}),btoa(A).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function c3(s,A){const t=typeof AbortController<"u"?new AbortController:void 0,e=t?setTimeout(()=>t.abort(),A):void 0;try{const i=await fetch(s,{method:"GET",headers:{Accept:"application/json"},signal:t?.signal}),n=await i.json().catch(()=>({}));if(!i.ok){const o=n?.error?.message??n?.message??`ViewToken public key request failed with status ${i.status}`;throw new Error(o)}return n}finally{e!=null&&clearTimeout(e)}}function Zp(s){const A=globalThis.crypto;if(!A?.getRandomValues)throw new Error("[BimEngine] crypto.getRandomValues is required to encrypt viewToken");return A.getRandomValues(new Uint8Array(s))}function Q3(s){let A="";return s.forEach(t=>{A+=String.fromCharCode(t)}),A}function d3(s){const A=new Uint8Array(s.length);for(let t=0;t<s.length;t+=1)A[t]=s.charCodeAt(t)&255;return A}async function f3(s,A){const t=`${bG(s)}/models/view-token/public-key`,e=await c3(t,A);if(e.algorithm!=="RSA-OAEP-256"||!e.publicKey)throw new Error("[BimEngine] OpenAPI returned an invalid viewToken public key");return jp.pki.publicKeyFromPem(e.publicKey)}function M3(s,A){const t=bG(s),e=Rp.get(t);if(e)return e;const i=f3(s,A).catch(n=>{throw Rp.delete(t),n});return Rp.set(t,i),i}async function y3(s,A,t){const e=await M3(s,t),i=Zp(32),n=Zp(12),o=Zp(16),g=JSON.stringify({viewToken:A,timestamp:Date.now(),nonce:wQ(o)}),a=e.encrypt(Q3(i),"RSA-OAEP",{md:jp.md.sha256.create(),mgf1:{md:jp.md.sha256.create()}}),r=GE(i,n).encrypt(E3(g));return[C3,wQ(d3(a)),wQ(n),wQ(r)].join(".")}function p3(s){return s.replace(/\/+$/,"")}async function D3(s,A,t){const e=typeof AbortController<"u"?new AbortController:void 0,i=e?setTimeout(()=>e.abort(),t):void 0;try{const n=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(A),signal:e?.signal}),o=await n.json().catch(()=>({}));if(!n.ok){const g=o?.error?.message??o?.message??`ViewToken resolve failed with status ${n.status}`;throw new Error(g)}return o}finally{i!=null&&clearTimeout(i)}}function w3(s){switch(s){case"2d":return"cad_model";case"720":return"panorama";case"gis":return"gis_scene";case"gaussian":return"gaussian_model";case"3d":default:return"model"}}function u3(s){return{models:[{modelType:s.toLowerCase().endsWith(".json")?"3dtiles":"glb",url:s}]}}function m3(s,A){return{applicationId:0,engineType:A,assetCategory:w3(A),url:s,urls:[s],info:A==="gis"?u3(s):void 0}}async function P3(s,A,t){const e=s?.sdkAuth;if(!e?.endpoint)return m3(A,t);let i;(e.token||e.appId&&e.appKey&&e.appSecret)&&(i=(await e3(s,t))?.sdkToken);const o={viewToken:await y3(e.endpoint,A,e.timeoutMs??8e3),engineType:t};return i&&(o.sdkToken=i),D3(`${p3(e.endpoint)}/models/view-token/resolve`,o,e.timeoutMs??8e3)}const S3=Object.freeze({maxTextureSize:1024,samples:0,restrictTextureSize:!0}),Y3=Object.freeze({maxTextureSize:2048,samples:4,restrictTextureSize:!0}),F3=Object.freeze({maxTextureSize:4096,samples:6,restrictTextureSize:!0}),b3=Object.freeze({maxTextureSize:4096,samples:6,restrictTextureSize:!1});function W3(s){return typeof s!="number"||!Number.isFinite(s)||s<=4?S3:s<=6?Y3:s<8?F3:b3}class WG{options;mobileMemoryProfile;deviceType;animationId=null;isDisposed=!1;isRenderingPaused=!1;suppressComposerRenderWhenFree=!1;pendingComposerRender=!0;controlsEnabledBeforePause=!0;boundControl=null;controlEventHandlers=null;animate;onWindowResize;_fpsFrameCount=0;_fpsLastCheck=0;_fpsLastSwitch=0;_lowFpsCount=0;_highFpsCount=0;frameLockEnabled=!0;_idleFrameInterval=1e3/1;_lastIdleFrameTime=0;_idleFrameRateExemptionReasons=new Set;_fpsCheckInterval=100;_fpsSwitchCooldown=100;_fpsThreshold=30;_fpsUpgradeThreshold=60;_lowFpsRequired=5;_highFpsRequired=.1;isMouseDown=!1;isWheeling=!1;scene;camera;renderer;sceneModule;cameraModule;deviceModule;renderModule;controlModule;composerModule;loaderModule;engineStatus;events;lightModule;interactionModule;modelToolModule;worldToScreen;handelBehaved;octreeBox;controls;stats;catchSvg;engineModelModule;viewTree;merge2d;viewCube;rangeScale;setting;measure;clipping;modelTree;engineInfo;modelProperties;search;modelMapperBatch;modelEdge;nodeBox;pathRoaming;hoverHighLight;minMap;grid;level;issueReport;text;hdr;ground;skyManager;linkElement2d3d;linkView2d3d;oneClickEncoding;fabricDraw;drawingPin;modelLink3d;label;annotation3d;calibration;modelPlace;modelComparison;modelExplode;materialTool;pathDraw;rxQuotaListMapper;filterLoaderModel;models=[];reactBoundingClientRect={left:0,top:0};version=UB;versionEl=null;container;constructor(A){if(window.THREE=Cm,O9(),this.options=A,this.mobileMemoryProfile=W3(A.limit_memory),this.container=document.getElementById(A.containerId),!this.container)throw new Error(`Container ${A.containerId} not found`);if(this.rxQuotaListMapper=new N8(this),this.filterLoaderModel=new O8(this),this.engineModelModule=new uV(this),this.engineModelModule.init(),this.deviceModule=new kU(this),this.deviceType=this.deviceModule.getDeviceType(),this.cameraModule=new Ee(this),this.sceneModule=new XU(this),this.scene=this.sceneModule.scene,this.renderModule=new _U(this),this.renderer=this.renderModule.createRenderer(),this.camera=this.cameraModule.perspectiveCamera,this.scene.camera=this.camera,this.renderer){const o=this.renderer;o.interactionCullingEnabled=!0,o.interactionActive=!1,o.interactionRenderScene=this.scene,o.interactionFrameBudgetMs=this.options.interactionFrameBudgetMs??6,o.interactionSkipShadows=this.options.interactionSkipShadows??!0}this.controlModule=new gJ(this),this.controlModule.switchDefaultMode(),this.controls=this.controlModule.orbitControls,this.clipping=new EO(this),this.clipping.init(),this.composerModule=new MJ(this),this.composerModule.init(),this.events=new $4;const t=this.events.trigger.bind(this.events);this.events.trigger=((o,g)=>{t(o,g),String(o)!==String(ce.EngineBusy)&&this.requestComposerRender()}),this.engineStatus=new q4(this),this.engineStatus.init(),this.loaderModule=new ci(this),this.lightModule=new fV(this),this.lightModule.init(),this.viewCube=new JV(this),this.viewCube.init(),this.options.showViewCube==!1&&this.viewCube.hide(),this.octreeBox=xV(this),this.rangeScale=new kV(this),this.rangeScale.init(),this.setting=new BH(this),this.engineModelModule.init(),this.handelBehaved=ef(this),this.modelMapperBatch=new pO(this),this.measure=new yH(this),this.modelToolModule=new yV(this),this.modelLink3d=new xv(this,this.options.linkOptions??{}),this.modelLink3d.init(),this.modelProperties=new dO(this),this.search=new yO(this),this.interactionModule=new MV(this),this.interactionModule.init(),this.interactionModule.active(),this.hoverHighLight=new ic(this),this.modelEdge=new IH(this),this.nodeBox=new uO(this),this.modelTree=new cO(this),this.viewTree=new TM(this),this.merge2d=new OO(this),this.engineInfo=new QO(this),this.pathRoaming=new YO(this),this.pathRoaming.init(),this.oneClickEncoding=new KO(this),this.minMap=new FO(this),this.linkElement2d3d=new GO(this),this.linkView2d3d=new TO(this),this.grid=new OV(this),this.level=new AH(this),this.issueReport=new bO(this),this.fabricDraw=new Uv(this),this.drawingPin=new Xv(this),this.label=new Vv(this),this.annotation3d=new P8(this),this.calibration=new iI(this),this.modelPlace=new b8(this),this.modelComparison=new W8(this),this.modelExplode=new G8(this),this.materialTool=new yW(this,this.options.materialEditorOptions??{}),this.materialTool.init(),this.pathDraw=new H8(this),this.text=new WO(this),this.hdr=new _V(this),this.ground=new hM(this),this.ground.init(),this.skyManager=new lH(this),this.setting.init(),this.worldToScreen=new gi(this.camera,this.renderer,this.scene),this.options.showStats&&(this.stats=new YV,this.stats.showPanel(0),this.stats.dom.style.position="absolute",this.stats.dom.style.top="0px",this.stats.dom.style.left="0px",this.stats.dom.style.zIndex="1000",this.container.appendChild(this.stats.dom));let e=document.createElement("div");e.className="versionText",this.versionEl=e,this.updateVersionDisplay(),this.container.appendChild(e);let i=document.createElementNS("http://www.w3.org/2000/svg","svg");window.getComputedStyle(this.container).position==="static"&&(this.container.style.position="relative",this.container.style.position="relative",this.container.style.position="relative"),i.style.position="absolute",i.style.zIndex="1000",i.style.left="0px",i.style.top="0px",i.style.width="0px",i.style.height="0px",i.style.overflow="hidden",i.style.display="block",i.style.pointerEvents="none",this.container.appendChild(i),this.catchSvg=i,this.syncCatchSvgViewport(),this.onWindowResize=()=>{this.handleWindowResize()},window.addEventListener("resize",this.onWindowResize);let n=this;this.bindControlEvents(this.controls),this.events.on(ce.LoadingCompleted,()=>{n.modelEdge.active(),n.modelToolModule.addPickBoxByNames(["门店编号"])}),this.events.on(ce.EngineBusy,()=>{n.requestComposerRender()}),this.events.on(ce.EngineFree,()=>{n.requestComposerRender()}),this.animate=()=>{if(this.isRenderingPaused=!1,!this.isRenderingPaused)this.animationId=requestAnimationFrame(this.animate);else{this.animationId=null;return}const o=performance.now(),g=this.engineStatus?.isFree===!0;if(this.frameLockEnabled&&g&&this._idleFrameRateExemptionReasons.size===0&&!this.pendingComposerRender){if(o-this._lastIdleFrameTime<this._idleFrameInterval)return;this._lastIdleFrameTime=o}else this._lastIdleFrameTime=o;if(this.stats&&this.stats.begin(),this.modelEdge?.update?.(),this.composerModule&&(!this.suppressComposerRenderWhenFree||this.pendingComposerRender)&&(this.composerModule.render(),this.renderModule?.drawWatermark(),this.pendingComposerRender=!1),this.viewCube&&this.viewCube.cubeTool.RenderScene(),this.measure.update(),this.ground.update(),this.skyManager.update(),this.hoverHighLight.update(),this.controlModule.update(),this.modelPlace?.update?.(),this.pathDraw?.update?.(),this.minMap.update(),this.grid.update(),this.level.update(),this.text&&this.text.update(),this.label&&this.label.update(),this.annotation3d&&this.annotation3d.updateFrame(1/60),this.modelExplode?.update?.(),this.stats&&this.stats.end(),g)this._fpsFrameCount=0,this._fpsLastCheck=o,this._lowFpsCount=0,this._highFpsCount=0;else if(this._fpsFrameCount++,o-this._fpsLastCheck>=this._fpsCheckInterval){const a=o-this._fpsLastCheck,r=this._fpsFrameCount/a*1e3;this._fpsFrameCount=0,this._fpsLastCheck=o,r<this._fpsThreshold?(this._lowFpsCount++,this._highFpsCount=0,this._lowFpsCount>=this._lowFpsRequired&&o-this._fpsLastSwitch>this._fpsSwitchCooldown&&(this._adaptiveRenderingDowngrade(),this._fpsLastSwitch=o,this._lowFpsCount=0)):(this._lowFpsCount=0,this._highFpsCount=0)}if(this.scene){let a=this.scene?.dirLight;a&&this.camera&&this.updateLightPosition(this.camera,a),this.camera&&this.lightModule?.updateDirectionalShadow(this.camera)}},this.animate()}changeHandelBehavedMode(A){this.engineStatus.editorMode=A}getHandelBehavedMode(){return this.engineStatus.editorMode}updateVersionDisplay(){if(!this.versionEl)return;const A={simple:"simple",balance:"balance",advanced:"advanced"},t=this.engineModelModule?.getCurrentMode()??"",e=A[t]??t;this.versionEl.innerHTML=`v${this.version} | ${e}`}bindControlEvents(A){if(this.boundControl===A||(this.boundControl?.removeEventListener&&this.controlEventHandlers&&(this.boundControl.removeEventListener("start",this.controlEventHandlers.start),this.boundControl.removeEventListener("end",this.controlEventHandlers.end),this.boundControl.removeEventListener("change",this.controlEventHandlers.change)),this.boundControl=A,this.controlEventHandlers=null,!A?.addEventListener))return;const t=()=>{this.renderer&&(this.renderer.interactionActive=!0),this.events.trigger(ce.EngineBusy),this.container&&(this.container.style.cursor="none")},e=()=>{this.renderer&&(this.renderer.interactionActive=!1),this.events.trigger(ce.EngineFree),this.container&&(this.container.style.cursor="default")},i=()=>{if(this.requestComposerRender(),!this.camera)return;const n=new S;this.camera.getWorldDirection(n);const o=Math.atan2(n.x,-n.z);window.dispatchEvent(new CustomEvent("D3ViewUpdate",{detail:{position:this.camera.position,rotation:o,type:this.camera.type}}))};A.addEventListener("start",t),A.addEventListener("end",e),A.addEventListener("change",i),this.controlEventHandlers={start:t,end:e,change:i}}requestComposerRender(){this.pendingComposerRender=!0}setFrameLock(A){this.frameLockEnabled!==A&&(this.frameLockEnabled=A,this._lastIdleFrameTime=0,this.requestComposerRender())}isFrameLockEnabled(){return this.frameLockEnabled}setIdleFrameRateExempt(A,t){if(A){if(t){this._idleFrameRateExemptionReasons.add(A),this.requestComposerRender();return}this._idleFrameRateExemptionReasons.delete(A)}}async loadModelByViewToken(A,t){const e=await P3(this.options,A,"3d"),i=Array.isArray(e.urls)&&e.urls.length>0?e.urls:[e.url];await this.loaderModule.loadModels(i,t)}applyCalibration(A){return this.calibration.apply(A)}alignCalibrationBySegments(A){return this.calibration.alignBySegments(A)}startPointCalibration(A){return this.calibration.startPointCalibration(A)}updateLightPosition(A,t,e=!0){const i=new S;A.getWorldDirection(i);const n=100,o=new S().copy(i).multiplyScalar(-n),g=new S(0,1,0),a=new S().crossVectors(i,g).normalize();o.addScaledVector(g,n*.5),o.addScaledVector(a,n*.3),t.position.copy(A.position).add(o);const r=new S().copy(A.position).add(i.multiplyScalar(20));t.target.position.copy(r),t.target.updateMatrixWorld()}_adaptiveRenderingDowngrade(){const A=["simple","balance","advanced"],t=this.engineModelModule.getCurrentMode(),e=A.indexOf(t);if(e>0){const i=A[e-1];console.log(`[AdaptiveRendering] FPS低于${this._fpsThreshold},自动降级: ${t} → ${i}`),this.engineModelModule.autoSwitch(i)}}_adaptiveRenderingUpgrade(){const A=["simple","balance","advanced"],t=this.engineModelModule.getCurrentMode(),e=A.indexOf(t);if(e<A.length-1){const i=A[e+1];console.log(`[AdaptiveRendering] FPS高于${this._fpsUpgradeThreshold},自动升级: ${t} → ${i}`),this.engineModelModule.autoSwitch(i)}}pauseRendering(){if(this.isRenderingPaused){console.warn("[BimEngine] Rendering is already paused");return}this.isRenderingPaused=!0,this.controls&&(this.controlsEnabledBeforePause=this.controls.enabled,this.controls.enabled=!1)}resumeRendering(){if(!this.isRenderingPaused){console.warn("[BimEngine] Rendering is not paused");return}this.isRenderingPaused=!1,this.controls&&(this.controls.enabled=this.controlsEnabledBeforePause),this.animationId===null&&this.animate()}isRenderingPausedState(){return this.isRenderingPaused}getViewportSize(A,t){const e=this.container?.getBoundingClientRect(),i=Math.round(e?.width||0)||A||this.container?.clientWidth||this.renderer?.domElement.clientWidth||0,n=Math.round(e?.height||0)||t||this.container?.clientHeight||this.renderer?.domElement.clientHeight||0;return{width:Math.max(1,i),height:Math.max(1,n)}}syncCatchSvgViewport(A,t){if(!this.catchSvg||!this.renderer)return;const e=A??this.renderer.domElement.clientWidth,i=t??this.renderer.domElement.clientHeight;if(!e||!i)return;const n=Number.isFinite(this.reactBoundingClientRect?.left)?this.reactBoundingClientRect.left:0,o=Number.isFinite(this.reactBoundingClientRect?.top)?this.reactBoundingClientRect.top:0;this.catchSvg.style.width=`${e}px`,this.catchSvg.style.height=`${i}px`,this.catchSvg.setAttribute("width",`${e}`),this.catchSvg.setAttribute("height",`${i}`),this.catchSvg.setAttribute("viewBox",`${n} ${o} ${e} ${i}`),this.catchSvg.setAttribute("preserveAspectRatio","none")}handleWindowResize(A,t){if(!this.container||!this.renderer||!this.camera)return;const e=this.getViewportSize(A,t);A=e.width,t=e.height;const i=this.camera.position.clone(),n=this.camera.quaternion.clone(),o=this.camera.up.clone(),g=this.controls?.target?.clone?.(),a=this.controlModule?.orbitControls?.origin?.clone?.();this.renderer.setPixelRatio(cm(this)),this.renderer.setSize(A,t,!1);const r=this.renderer.domElement.clientWidth||A,I=this.renderer.domElement.clientHeight||t;if(!r||!I)return;const l=r/I;if(this.camera===this.cameraModule.perspectiveCamera)this.cameraModule.perspectiveCamera.aspect=l,this.cameraModule.perspectiveCamera.updateProjectionMatrix(),this.camera=this.cameraModule.perspectiveCamera;else if(this.camera===this.cameraModule.orthographicCamera){const h=this.cameraModule.orthographicCamera,B=this.cameraModule.getOrthographicVisibleHeight(h);this.cameraModule.setOrthographicVisibleHeight(B,h,l),h.updateProjectionMatrix()}if(this.composerModule&&(typeof this.composerModule.resize=="function"?this.composerModule.resize(r,I):this.composerModule.composer&&this.composerModule.composer.setSize(r,I)),this.catchSvg&&this.catchSvg.setAttribute("viewBox",`0 0 ${r} ${I}`),this.syncCatchSvgViewport(r,I),this.fabricDraw&&this.fabricDraw.resize(r,I),this.camera.position.copy(i),this.camera.quaternion.copy(n),this.camera.up.copy(o),this.camera.updateMatrix(),this.camera.updateMatrixWorld(!0),g&&this.controls?.target&&this.controls.target.copy(g),a&&this.controlModule?.orbitControls?.origin&&this.controlModule.orbitControls.origin.copy(a),this.controlModule?.orbitControls){const h=this.controlModule.orbitControls;h._lastPosition?.copy?.(this.camera.position),h._lastTarget?.copy?.(h.target),h._lastUp?.copy?.(this.camera.up),h._lastQuaternion?.copy?.(this.camera.quaternion),h._lastZoom=this.camera.zoom}this.controlModule?.firstPersonControls?.syncRotationStateFromCamera?.(),this.controlModule?.firstPersonControls?.syncSharedTargetFromCamera?.(),this.controlModule?.thirdPersonControls?.syncRotationStateFromCamera?.(),this.controlModule?.thirdPersonControls?.syncSharedTargetFromAvatar?.(),this.events&&this.events.trigger(ce.ViewportResize,{width:r,height:I})}dispose(){if(this.isDisposed)return;this.isDisposed=!0,console.log("[BimEngine] Starting engine disposal..."),this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null),this.isRenderingPaused=!0,this.onWindowResize&&window.removeEventListener("resize",this.onWindowResize);try{this.invokeIfExists(this.rangeScale,"dispose"),this.invokeIfExists(this.measure,"dispose"),this.invokeIfExists(this.clipping,"disActive"),this.invokeIfExists(this.interactionModule,"dispose"),this.invokeIfExists(this.pathRoaming,"dispose"),this.invokeIfExists(this.controlModule,"dispose"),this.invokeIfExists(this.hoverHighLight,"dispose"),this.invokeIfExists(this.linkElement2d3d,"dispose"),this.invokeIfExists(this.linkView2d3d,"dispose"),this.invokeIfExists(this.skyManager,"close",!0),this.invokeIfExists(this.hdr,"dispose"),this.invokeIfExists(this.minMap,"dispose"),this.invokeIfExists(this.grid,"dispose"),this.invokeIfExists(this.level,"dispose"),this.invokeIfExists(this.ground,"dispose"),this.invokeIfExists(this.text,"dispose"),this.invokeIfExists(this.issueReport,"dispose"),this.invokeIfExists(this.fabricDraw,"dispose"),this.invokeIfExists(this.modelLink3d,"dispose"),this.invokeIfExists(this.label,"dispose"),this.invokeIfExists(this.annotation3d,"dispose"),this.invokeIfExists(this.calibration,"dispose"),this.invokeIfExists(this.search,"dispose"),this.invokeIfExists(this.modelPlace,"dispose"),this.invokeIfExists(this.modelComparison,"dispose"),this.invokeIfExists(this.modelExplode,"dispose"),this.invokeIfExists(this.materialTool,"dispose"),this.invokeIfExists(this.pathDraw,"dispose"),this.invokeIfExists(this.nodeBox,"dispose"),this.invokeIfExists(this.viewCube?.cubeTool,"dispose"),this.invokeIfExists(this.handelBehaved,"disActive"),this.invokeIfExists(this.engineStatus,"dispose")}catch(t){console.warn("[BimEngine] Error disposing managers:",t)}try{this.controlModule&&(this.controlModule.originDiv&&this.controlModule.originDiv.remove(),this.controlModule.orbitControls&&typeof this.controlModule.orbitControls.dispose=="function"&&this.controlModule.orbitControls.dispose(),this.controlModule.firstPersonControls&&typeof this.controlModule.firstPersonControls.dispose=="function"&&this.controlModule.firstPersonControls.dispose(),this.controlModule.thirdPersonControls&&typeof this.controlModule.thirdPersonControls.dispose=="function"&&this.controlModule.thirdPersonControls.dispose())}catch(t){console.warn("[BimEngine] Error disposing controls:",t)}this.scene&&(this.disposeSceneAttachments(this.scene),this.clearScene(this.scene));try{this.composerModule&&this.composerModule.composer&&(this.composerModule.composer.passes&&this.composerModule.composer.passes.forEach(t=>{t?.dispose?.()}),this.composerModule.composer.renderTarget1&&this.composerModule.composer.renderTarget1.dispose(),this.composerModule.composer.renderTarget2&&this.composerModule.composer.renderTarget2.dispose(),this.composerModule.composer.dispose?.(),this.composerModule.composer.passes=[])}catch(t){console.warn("[BimEngine] Error disposing composer:",t)}try{this.renderModule?.disposeRenderer?.(),this.renderer&&(this.renderer.renderLists?.dispose?.(),this.renderer.domElement&&this.renderer.domElement.parentElement&&this.renderer.domElement.parentElement.removeChild(this.renderer.domElement),this.renderer.dispose(),this.renderer.forceContextLoss())}catch(t){console.warn("[BimEngine] Error disposing renderer:",t)}try{this.stats?.dom?.parentElement&&this.stats.dom.parentElement.removeChild(this.stats.dom),this.catchSvg?.parentElement&&this.catchSvg.parentElement.removeChild(this.catchSvg),this.versionEl?.parentElement&&this.versionEl.parentElement.removeChild(this.versionEl)}catch(t){console.warn("[BimEngine] Error disposing DOM elements:",t)}try{this.events&&this.events.listeners&&this.events.listeners.clear()}catch(t){console.warn("[BimEngine] Error clearing event listeners:",t)}const A=this;A.scene=null,A.camera=null,A.renderer=null,A.controls=null,A.models=[],A.container=null,A.catchSvg=null,A.stats=null,A.versionEl=null,A.worldToScreen=null,A.measure=null,A.clipping=null,A.interactionModule=null,A.controlModule=null,A.sceneModule=null,A.cameraModule=null,A.deviceModule=null,A.renderModule=null,A.composerModule=null,A.loaderModule=null,A.lightModule=null,A.engineStatus=null,A.hoverHighLight=null,A.pathRoaming=null,A.hdr=null,A.skyManager=null,A.viewCube=null,A.grid=null,A.level=null,A.ground=null,A.minMap=null,A.fabricDraw=null,A.modelLink3d=null,A.label=null,A.annotation3d=null,A.pathDraw=null,A.calibration=null,A.linkElement2d3d=null,A.linkView2d3d=null,A.rangeScale=null,A.text=null,A.issueReport=null,A.modelEdge=null,A.nodeBox=null,A.modelTree=null,A.modelProperties=null,A.search=null,A.modelMapperBatch=null,A.modelComparison=null,A.modelExplode=null,A.materialTool=null,A.engineInfo=null,A.ai=null,A.oneClickEncoding=null,A.drawingPin=null,A.events=null,console.log("[BimEngine] Engine disposal completed")}clearScene(A){if(!A)return;[...A.children].forEach(e=>{this.clearScene(e)}),A.parent&&A.parent.remove(A),A instanceof bA&&!(A instanceof ct)&&(A.geometry&&A.geometry.dispose(),A.material&&(Array.isArray(A.material)?A.material.forEach(e=>this.disposeMaterial(e)):this.disposeMaterial(A.material))),A instanceof he&&(A.geometry&&A.geometry.dispose(),A.material&&this.disposeMaterial(A.material)),A instanceof ir&&(A.geometry&&A.geometry.dispose(),A.material&&this.disposeMaterial(A.material)),A instanceof ct&&(A.geometry&&A.geometry.dispose(),A.material&&(Array.isArray(A.material)?A.material.forEach(e=>this.disposeMaterial(e)):this.disposeMaterial(A.material)),A.instanceMatrix&&(A.instanceMatrix=null),A.instanceColor&&(A.instanceColor=null)),A instanceof JI&&A.material&&this.disposeMaterial(A.material),A instanceof Vn&&A.shadow?.dispose?.()}invokeIfExists(A,t,...e){const i=A?.[t];typeof i=="function"&&i.apply(A,e)}disposeSceneAttachments(A){new Set([A.background,A.environment,A.overrideMaterial]).forEach(e=>{this.disposeSceneAttachment(e)}),A.background=null,A.environment=null,A.overrideMaterial=null,A.dirLight=null,A.camera=null}disposeSceneAttachment(A){A&&(A instanceof Ie||A instanceof Ft)&&A.dispose?.()}disposeMaterial(A){if(!A)return;["map","lightMap","bumpMap","normalMap","specularMap","envMap","alphaMap","aoMap","displacementMap","emissiveMap","gradientMap","metalnessMap","roughnessMap","clearcoatMap","clearcoatNormalMap","clearcoatRoughnessMap","transmissionMap","thicknessMap","sheenColorMap","sheenRoughnessMap","specularIntensityMap","specularColorMap","iridescenceMap","iridescenceThicknessMap"].forEach(e=>{const i=A[e];i&&i instanceof Ft&&i.dispose()}),A.dispose()}}async function G3(s){s?.assetFiles?await L0(s.assetFiles):s?.assetFile?await qX(s.assetFile):s?.assetBaseUrl&&await L0(null),s?.assetBaseUrl&&_X(s.assetBaseUrl)}async function GG(s){return await G3(s),new WG(s)}Sn.EngineKernelV2=WG,Sn.MaterialTool=yW,Sn.createEngine=GG,Sn.default=GG,Object.defineProperties(Sn,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
|
|
6621
|
+
`,I},A.publicKeyToOpenSSH=function(n,o){var g="ssh-rsa";o=o||"";var a=s.util.createBuffer();return e(a,g),t(a,n.e),t(a,n.n),g+" "+s.util.encode64(a.bytes())+" "+o},A.privateKeyToOpenSSH=function(n,o){return o?s.pki.encryptRsaPrivateKey(n,o,{legacy:!0,algorithm:"aes128"}):s.pki.privateKeyToPem(n)},A.getPublicKeyFingerprint=function(n,o){o=o||{};var g=o.md||s.md.md5.create(),a="ssh-rsa",r=s.util.createBuffer();e(r,a),t(r,n.e),t(r,n.n),g.start(),g.update(r.getBytes());var I=g.digest();if(o.encoding==="hex"){var l=I.toHex();return o.delimiter?l.match(/.{2}/g).join(o.delimiter):l}else{if(o.encoding==="binary")return I.getBytes();if(o.encoding)throw new Error('Unknown encoding "'+o.encoding+'".')}return I};function t(n,o){var g=o.toString(16);g[0]>="8"&&(g="00"+g);var a=s.util.hexToBytes(g);n.putInt32(a.length),n.putBytes(a)}function e(n,o){n.putInt32(o.length),n.putString(o)}function i(){for(var n=s.md.sha1.create(),o=arguments.length,g=0;g<o;++g)n.update(arguments[g]);return n.digest()}return Tp.exports}var Kp,FG;function h3(){return FG||(FG=1,Kp=Pt(),Qa(),n3(),Pn(),zy(),dQ(),g3(),xB(),a3(),r3(),I3(),IG(),Ip(),sI(),tG(),EG(),l3(),QG(),iG(),LW(),up(),An(),_W(),B3(),fG(),Ut()),Kp}var jp=h3();const C3="evtrsa1",Rp=new Map;function bG(s){return s.replace(/\/+$/,"")}function E3(s){return new TextEncoder().encode(s)}function wQ(s){let A="";return s.forEach(t=>{A+=String.fromCharCode(t)}),btoa(A).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function c3(s,A){const t=typeof AbortController<"u"?new AbortController:void 0,e=t?setTimeout(()=>t.abort(),A):void 0;try{const i=await fetch(s,{method:"GET",headers:{Accept:"application/json"},signal:t?.signal}),n=await i.json().catch(()=>({}));if(!i.ok){const o=n?.error?.message??n?.message??`ViewToken public key request failed with status ${i.status}`;throw new Error(o)}return n}finally{e!=null&&clearTimeout(e)}}function Zp(s){const A=globalThis.crypto;if(!A?.getRandomValues)throw new Error("[BimEngine] crypto.getRandomValues is required to encrypt viewToken");return A.getRandomValues(new Uint8Array(s))}function Q3(s){let A="";return s.forEach(t=>{A+=String.fromCharCode(t)}),A}function d3(s){const A=new Uint8Array(s.length);for(let t=0;t<s.length;t+=1)A[t]=s.charCodeAt(t)&255;return A}async function f3(s,A){const t=`${bG(s)}/models/view-token/public-key`,e=await c3(t,A);if(e.algorithm!=="RSA-OAEP-256"||!e.publicKey)throw new Error("[BimEngine] OpenAPI returned an invalid viewToken public key");return jp.pki.publicKeyFromPem(e.publicKey)}function M3(s,A){const t=bG(s),e=Rp.get(t);if(e)return e;const i=f3(s,A).catch(n=>{throw Rp.delete(t),n});return Rp.set(t,i),i}async function y3(s,A,t){const e=await M3(s,t),i=Zp(32),n=Zp(12),o=Zp(16),g=JSON.stringify({viewToken:A,timestamp:Date.now(),nonce:wQ(o)}),a=e.encrypt(Q3(i),"RSA-OAEP",{md:jp.md.sha256.create(),mgf1:{md:jp.md.sha256.create()}}),r=GE(i,n).encrypt(E3(g));return[C3,wQ(d3(a)),wQ(n),wQ(r)].join(".")}function p3(s){return s.replace(/\/+$/,"")}async function D3(s,A,t){const e=typeof AbortController<"u"?new AbortController:void 0,i=e?setTimeout(()=>e.abort(),t):void 0;try{const n=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(A),signal:e?.signal}),o=await n.json().catch(()=>({}));if(!n.ok){const g=o?.error?.message??o?.message??`ViewToken resolve failed with status ${n.status}`;throw new Error(g)}return o}finally{i!=null&&clearTimeout(i)}}function w3(s){switch(s){case"2d":return"cad_model";case"720":return"panorama";case"gis":return"gis_scene";case"gaussian":return"gaussian_model";case"3d":default:return"model"}}function u3(s){return{models:[{modelType:s.toLowerCase().endsWith(".json")?"3dtiles":"glb",url:s}]}}function m3(s,A){return{applicationId:0,engineType:A,assetCategory:w3(A),url:s,urls:[s],info:A==="gis"?u3(s):void 0}}async function P3(s,A,t){const e=s?.sdkAuth;if(!e?.endpoint)return m3(A,t);let i;(e.token||e.appId&&e.appKey&&e.appSecret)&&(i=(await e3(s,t))?.sdkToken);const o={viewToken:await y3(e.endpoint,A,e.timeoutMs??8e3),engineType:t};return i&&(o.sdkToken=i),D3(`${p3(e.endpoint)}/models/view-token/resolve`,o,e.timeoutMs??8e3)}const S3=Object.freeze({maxTextureSize:1024,samples:0,restrictTextureSize:!0}),Y3=Object.freeze({maxTextureSize:2048,samples:4,restrictTextureSize:!0}),F3=Object.freeze({maxTextureSize:4096,samples:4,restrictTextureSize:!0}),b3=Object.freeze({maxTextureSize:4096,samples:4,restrictTextureSize:!1});function W3(s){return typeof s!="number"||!Number.isFinite(s)||s<=4?S3:s<=6?Y3:s<8?F3:b3}class WG{options;mobileMemoryProfile;deviceType;animationId=null;isDisposed=!1;isRenderingPaused=!1;suppressComposerRenderWhenFree=!1;pendingComposerRender=!0;controlsEnabledBeforePause=!0;boundControl=null;controlEventHandlers=null;animate;onWindowResize;_fpsFrameCount=0;_fpsLastCheck=0;_fpsLastSwitch=0;_lowFpsCount=0;_highFpsCount=0;frameLockEnabled=!0;_idleFrameInterval=1e3/1;_lastIdleFrameTime=0;_idleFrameRateExemptionReasons=new Set;_fpsCheckInterval=100;_fpsSwitchCooldown=100;_fpsThreshold=30;_fpsUpgradeThreshold=60;_lowFpsRequired=5;_highFpsRequired=.1;isMouseDown=!1;isWheeling=!1;scene;camera;renderer;sceneModule;cameraModule;deviceModule;renderModule;controlModule;composerModule;loaderModule;engineStatus;events;lightModule;interactionModule;modelToolModule;worldToScreen;handelBehaved;octreeBox;controls;stats;catchSvg;engineModelModule;viewTree;merge2d;viewCube;rangeScale;setting;measure;clipping;modelTree;engineInfo;modelProperties;search;modelMapperBatch;modelEdge;nodeBox;pathRoaming;hoverHighLight;minMap;grid;level;issueReport;text;hdr;ground;skyManager;linkElement2d3d;linkView2d3d;oneClickEncoding;fabricDraw;drawingPin;modelLink3d;label;annotation3d;calibration;modelPlace;modelComparison;modelExplode;materialTool;pathDraw;rxQuotaListMapper;filterLoaderModel;models=[];reactBoundingClientRect={left:0,top:0};version=UB;versionEl=null;container;constructor(A){if(window.THREE=Cm,O9(),this.options=A,this.mobileMemoryProfile=W3(A.limit_memory),this.container=document.getElementById(A.containerId),!this.container)throw new Error(`Container ${A.containerId} not found`);if(this.rxQuotaListMapper=new N8(this),this.filterLoaderModel=new O8(this),this.engineModelModule=new uV(this),this.engineModelModule.init(),this.deviceModule=new kU(this),this.deviceType=this.deviceModule.getDeviceType(),this.cameraModule=new Ee(this),this.sceneModule=new XU(this),this.scene=this.sceneModule.scene,this.renderModule=new _U(this),this.renderer=this.renderModule.createRenderer(),this.camera=this.cameraModule.perspectiveCamera,this.scene.camera=this.camera,this.renderer){const o=this.renderer;o.interactionCullingEnabled=!0,o.interactionActive=!1,o.interactionRenderScene=this.scene,o.interactionFrameBudgetMs=this.options.interactionFrameBudgetMs??6,o.interactionSkipShadows=this.options.interactionSkipShadows??!0}this.controlModule=new gJ(this),this.controlModule.switchDefaultMode(),this.controls=this.controlModule.orbitControls,this.clipping=new EO(this),this.clipping.init(),this.composerModule=new MJ(this),this.composerModule.init(),this.events=new $4;const t=this.events.trigger.bind(this.events);this.events.trigger=((o,g)=>{t(o,g),String(o)!==String(ce.EngineBusy)&&this.requestComposerRender()}),this.engineStatus=new q4(this),this.engineStatus.init(),this.loaderModule=new ci(this),this.lightModule=new fV(this),this.lightModule.init(),this.viewCube=new JV(this),this.viewCube.init(),this.options.showViewCube==!1&&this.viewCube.hide(),this.octreeBox=xV(this),this.rangeScale=new kV(this),this.rangeScale.init(),this.setting=new BH(this),this.engineModelModule.init(),this.handelBehaved=ef(this),this.modelMapperBatch=new pO(this),this.measure=new yH(this),this.modelToolModule=new yV(this),this.modelLink3d=new xv(this,this.options.linkOptions??{}),this.modelLink3d.init(),this.modelProperties=new dO(this),this.search=new yO(this),this.interactionModule=new MV(this),this.interactionModule.init(),this.interactionModule.active(),this.hoverHighLight=new ic(this),this.modelEdge=new IH(this),this.nodeBox=new uO(this),this.modelTree=new cO(this),this.viewTree=new TM(this),this.merge2d=new OO(this),this.engineInfo=new QO(this),this.pathRoaming=new YO(this),this.pathRoaming.init(),this.oneClickEncoding=new KO(this),this.minMap=new FO(this),this.linkElement2d3d=new GO(this),this.linkView2d3d=new TO(this),this.grid=new OV(this),this.level=new AH(this),this.issueReport=new bO(this),this.fabricDraw=new Uv(this),this.drawingPin=new Xv(this),this.label=new Vv(this),this.annotation3d=new P8(this),this.calibration=new iI(this),this.modelPlace=new b8(this),this.modelComparison=new W8(this),this.modelExplode=new G8(this),this.materialTool=new yW(this,this.options.materialEditorOptions??{}),this.materialTool.init(),this.pathDraw=new H8(this),this.text=new WO(this),this.hdr=new _V(this),this.ground=new hM(this),this.ground.init(),this.skyManager=new lH(this),this.setting.init(),this.worldToScreen=new gi(this.camera,this.renderer,this.scene),this.options.showStats&&(this.stats=new YV,this.stats.showPanel(0),this.stats.dom.style.position="absolute",this.stats.dom.style.top="0px",this.stats.dom.style.left="0px",this.stats.dom.style.zIndex="1000",this.container.appendChild(this.stats.dom));let e=document.createElement("div");e.className="versionText",this.versionEl=e,this.updateVersionDisplay(),this.container.appendChild(e);let i=document.createElementNS("http://www.w3.org/2000/svg","svg");window.getComputedStyle(this.container).position==="static"&&(this.container.style.position="relative",this.container.style.position="relative",this.container.style.position="relative"),i.style.position="absolute",i.style.zIndex="1000",i.style.left="0px",i.style.top="0px",i.style.width="0px",i.style.height="0px",i.style.overflow="hidden",i.style.display="block",i.style.pointerEvents="none",this.container.appendChild(i),this.catchSvg=i,this.syncCatchSvgViewport(),this.onWindowResize=()=>{this.handleWindowResize()},window.addEventListener("resize",this.onWindowResize);let n=this;this.bindControlEvents(this.controls),this.events.on(ce.LoadingCompleted,()=>{n.modelEdge.active(),n.modelToolModule.addPickBoxByNames(["门店编号"])}),this.events.on(ce.EngineBusy,()=>{n.requestComposerRender()}),this.events.on(ce.EngineFree,()=>{n.requestComposerRender()}),this.animate=()=>{if(this.isRenderingPaused=!1,!this.isRenderingPaused)this.animationId=requestAnimationFrame(this.animate);else{this.animationId=null;return}const o=performance.now(),g=this.engineStatus?.isFree===!0;if(this.frameLockEnabled&&g&&this._idleFrameRateExemptionReasons.size===0&&!this.pendingComposerRender){if(o-this._lastIdleFrameTime<this._idleFrameInterval)return;this._lastIdleFrameTime=o}else this._lastIdleFrameTime=o;if(this.stats&&this.stats.begin(),this.modelEdge?.update?.(),this.composerModule&&(!this.suppressComposerRenderWhenFree||this.pendingComposerRender)&&(this.composerModule.render(),this.renderModule?.drawWatermark(),this.pendingComposerRender=!1),this.viewCube&&this.viewCube.cubeTool.RenderScene(),this.measure.update(),this.ground.update(),this.skyManager.update(),this.hoverHighLight.update(),this.controlModule.update(),this.modelPlace?.update?.(),this.pathDraw?.update?.(),this.minMap.update(),this.grid.update(),this.level.update(),this.text&&this.text.update(),this.label&&this.label.update(),this.annotation3d&&this.annotation3d.updateFrame(1/60),this.modelExplode?.update?.(),this.stats&&this.stats.end(),g)this._fpsFrameCount=0,this._fpsLastCheck=o,this._lowFpsCount=0,this._highFpsCount=0;else if(this._fpsFrameCount++,o-this._fpsLastCheck>=this._fpsCheckInterval){const a=o-this._fpsLastCheck,r=this._fpsFrameCount/a*1e3;this._fpsFrameCount=0,this._fpsLastCheck=o,r<this._fpsThreshold?(this._lowFpsCount++,this._highFpsCount=0,this._lowFpsCount>=this._lowFpsRequired&&o-this._fpsLastSwitch>this._fpsSwitchCooldown&&(this._adaptiveRenderingDowngrade(),this._fpsLastSwitch=o,this._lowFpsCount=0)):(this._lowFpsCount=0,this._highFpsCount=0)}if(this.scene){let a=this.scene?.dirLight;a&&this.camera&&this.updateLightPosition(this.camera,a),this.camera&&this.lightModule?.updateDirectionalShadow(this.camera)}},this.animate()}changeHandelBehavedMode(A){this.engineStatus.editorMode=A}getHandelBehavedMode(){return this.engineStatus.editorMode}updateVersionDisplay(){if(!this.versionEl)return;const A={simple:"simple",balance:"balance",advanced:"advanced"},t=this.engineModelModule?.getCurrentMode()??"",e=A[t]??t;this.versionEl.innerHTML=`v${this.version} | ${e}`}bindControlEvents(A){if(this.boundControl===A||(this.boundControl?.removeEventListener&&this.controlEventHandlers&&(this.boundControl.removeEventListener("start",this.controlEventHandlers.start),this.boundControl.removeEventListener("end",this.controlEventHandlers.end),this.boundControl.removeEventListener("change",this.controlEventHandlers.change)),this.boundControl=A,this.controlEventHandlers=null,!A?.addEventListener))return;const t=()=>{this.renderer&&(this.renderer.interactionActive=!0),this.events.trigger(ce.EngineBusy),this.container&&(this.container.style.cursor="none")},e=()=>{this.renderer&&(this.renderer.interactionActive=!1),this.events.trigger(ce.EngineFree),this.container&&(this.container.style.cursor="default")},i=()=>{if(this.requestComposerRender(),!this.camera)return;const n=new S;this.camera.getWorldDirection(n);const o=Math.atan2(n.x,-n.z);window.dispatchEvent(new CustomEvent("D3ViewUpdate",{detail:{position:this.camera.position,rotation:o,type:this.camera.type}}))};A.addEventListener("start",t),A.addEventListener("end",e),A.addEventListener("change",i),this.controlEventHandlers={start:t,end:e,change:i}}requestComposerRender(){this.pendingComposerRender=!0}setFrameLock(A){this.frameLockEnabled!==A&&(this.frameLockEnabled=A,this._lastIdleFrameTime=0,this.requestComposerRender())}isFrameLockEnabled(){return this.frameLockEnabled}setIdleFrameRateExempt(A,t){if(A){if(t){this._idleFrameRateExemptionReasons.add(A),this.requestComposerRender();return}this._idleFrameRateExemptionReasons.delete(A)}}async loadModelByViewToken(A,t){const e=await P3(this.options,A,"3d"),i=Array.isArray(e.urls)&&e.urls.length>0?e.urls:[e.url];await this.loaderModule.loadModels(i,t)}applyCalibration(A){return this.calibration.apply(A)}alignCalibrationBySegments(A){return this.calibration.alignBySegments(A)}startPointCalibration(A){return this.calibration.startPointCalibration(A)}updateLightPosition(A,t,e=!0){const i=new S;A.getWorldDirection(i);const n=100,o=new S().copy(i).multiplyScalar(-n),g=new S(0,1,0),a=new S().crossVectors(i,g).normalize();o.addScaledVector(g,n*.5),o.addScaledVector(a,n*.3),t.position.copy(A.position).add(o);const r=new S().copy(A.position).add(i.multiplyScalar(20));t.target.position.copy(r),t.target.updateMatrixWorld()}_adaptiveRenderingDowngrade(){const A=["simple","balance","advanced"],t=this.engineModelModule.getCurrentMode(),e=A.indexOf(t);if(e>0){const i=A[e-1];console.log(`[AdaptiveRendering] FPS低于${this._fpsThreshold},自动降级: ${t} → ${i}`),this.engineModelModule.autoSwitch(i)}}_adaptiveRenderingUpgrade(){const A=["simple","balance","advanced"],t=this.engineModelModule.getCurrentMode(),e=A.indexOf(t);if(e<A.length-1){const i=A[e+1];console.log(`[AdaptiveRendering] FPS高于${this._fpsUpgradeThreshold},自动升级: ${t} → ${i}`),this.engineModelModule.autoSwitch(i)}}pauseRendering(){if(this.isRenderingPaused){console.warn("[BimEngine] Rendering is already paused");return}this.isRenderingPaused=!0,this.controls&&(this.controlsEnabledBeforePause=this.controls.enabled,this.controls.enabled=!1)}resumeRendering(){if(!this.isRenderingPaused){console.warn("[BimEngine] Rendering is not paused");return}this.isRenderingPaused=!1,this.controls&&(this.controls.enabled=this.controlsEnabledBeforePause),this.animationId===null&&this.animate()}isRenderingPausedState(){return this.isRenderingPaused}getViewportSize(A,t){const e=this.container?.getBoundingClientRect(),i=Math.round(e?.width||0)||A||this.container?.clientWidth||this.renderer?.domElement.clientWidth||0,n=Math.round(e?.height||0)||t||this.container?.clientHeight||this.renderer?.domElement.clientHeight||0;return{width:Math.max(1,i),height:Math.max(1,n)}}syncCatchSvgViewport(A,t){if(!this.catchSvg||!this.renderer)return;const e=A??this.renderer.domElement.clientWidth,i=t??this.renderer.domElement.clientHeight;if(!e||!i)return;const n=Number.isFinite(this.reactBoundingClientRect?.left)?this.reactBoundingClientRect.left:0,o=Number.isFinite(this.reactBoundingClientRect?.top)?this.reactBoundingClientRect.top:0;this.catchSvg.style.width=`${e}px`,this.catchSvg.style.height=`${i}px`,this.catchSvg.setAttribute("width",`${e}`),this.catchSvg.setAttribute("height",`${i}`),this.catchSvg.setAttribute("viewBox",`${n} ${o} ${e} ${i}`),this.catchSvg.setAttribute("preserveAspectRatio","none")}handleWindowResize(A,t){if(!this.container||!this.renderer||!this.camera)return;const e=this.getViewportSize(A,t);A=e.width,t=e.height;const i=this.camera.position.clone(),n=this.camera.quaternion.clone(),o=this.camera.up.clone(),g=this.controls?.target?.clone?.(),a=this.controlModule?.orbitControls?.origin?.clone?.();this.renderer.setPixelRatio(cm(this)),this.renderer.setSize(A,t,!1);const r=this.renderer.domElement.clientWidth||A,I=this.renderer.domElement.clientHeight||t;if(!r||!I)return;const l=r/I;if(this.camera===this.cameraModule.perspectiveCamera)this.cameraModule.perspectiveCamera.aspect=l,this.cameraModule.perspectiveCamera.updateProjectionMatrix(),this.camera=this.cameraModule.perspectiveCamera;else if(this.camera===this.cameraModule.orthographicCamera){const h=this.cameraModule.orthographicCamera,B=this.cameraModule.getOrthographicVisibleHeight(h);this.cameraModule.setOrthographicVisibleHeight(B,h,l),h.updateProjectionMatrix()}if(this.composerModule&&(typeof this.composerModule.resize=="function"?this.composerModule.resize(r,I):this.composerModule.composer&&this.composerModule.composer.setSize(r,I)),this.catchSvg&&this.catchSvg.setAttribute("viewBox",`0 0 ${r} ${I}`),this.syncCatchSvgViewport(r,I),this.fabricDraw&&this.fabricDraw.resize(r,I),this.camera.position.copy(i),this.camera.quaternion.copy(n),this.camera.up.copy(o),this.camera.updateMatrix(),this.camera.updateMatrixWorld(!0),g&&this.controls?.target&&this.controls.target.copy(g),a&&this.controlModule?.orbitControls?.origin&&this.controlModule.orbitControls.origin.copy(a),this.controlModule?.orbitControls){const h=this.controlModule.orbitControls;h._lastPosition?.copy?.(this.camera.position),h._lastTarget?.copy?.(h.target),h._lastUp?.copy?.(this.camera.up),h._lastQuaternion?.copy?.(this.camera.quaternion),h._lastZoom=this.camera.zoom}this.controlModule?.firstPersonControls?.syncRotationStateFromCamera?.(),this.controlModule?.firstPersonControls?.syncSharedTargetFromCamera?.(),this.controlModule?.thirdPersonControls?.syncRotationStateFromCamera?.(),this.controlModule?.thirdPersonControls?.syncSharedTargetFromAvatar?.(),this.events&&this.events.trigger(ce.ViewportResize,{width:r,height:I})}dispose(){if(this.isDisposed)return;this.isDisposed=!0,console.log("[BimEngine] Starting engine disposal..."),this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null),this.isRenderingPaused=!0,this.onWindowResize&&window.removeEventListener("resize",this.onWindowResize);try{this.invokeIfExists(this.rangeScale,"dispose"),this.invokeIfExists(this.measure,"dispose"),this.invokeIfExists(this.clipping,"disActive"),this.invokeIfExists(this.interactionModule,"dispose"),this.invokeIfExists(this.pathRoaming,"dispose"),this.invokeIfExists(this.controlModule,"dispose"),this.invokeIfExists(this.hoverHighLight,"dispose"),this.invokeIfExists(this.linkElement2d3d,"dispose"),this.invokeIfExists(this.linkView2d3d,"dispose"),this.invokeIfExists(this.skyManager,"close",!0),this.invokeIfExists(this.hdr,"dispose"),this.invokeIfExists(this.minMap,"dispose"),this.invokeIfExists(this.grid,"dispose"),this.invokeIfExists(this.level,"dispose"),this.invokeIfExists(this.ground,"dispose"),this.invokeIfExists(this.text,"dispose"),this.invokeIfExists(this.issueReport,"dispose"),this.invokeIfExists(this.fabricDraw,"dispose"),this.invokeIfExists(this.modelLink3d,"dispose"),this.invokeIfExists(this.label,"dispose"),this.invokeIfExists(this.annotation3d,"dispose"),this.invokeIfExists(this.calibration,"dispose"),this.invokeIfExists(this.search,"dispose"),this.invokeIfExists(this.modelPlace,"dispose"),this.invokeIfExists(this.modelComparison,"dispose"),this.invokeIfExists(this.modelExplode,"dispose"),this.invokeIfExists(this.materialTool,"dispose"),this.invokeIfExists(this.pathDraw,"dispose"),this.invokeIfExists(this.nodeBox,"dispose"),this.invokeIfExists(this.viewCube?.cubeTool,"dispose"),this.invokeIfExists(this.handelBehaved,"disActive"),this.invokeIfExists(this.engineStatus,"dispose")}catch(t){console.warn("[BimEngine] Error disposing managers:",t)}try{this.controlModule&&(this.controlModule.originDiv&&this.controlModule.originDiv.remove(),this.controlModule.orbitControls&&typeof this.controlModule.orbitControls.dispose=="function"&&this.controlModule.orbitControls.dispose(),this.controlModule.firstPersonControls&&typeof this.controlModule.firstPersonControls.dispose=="function"&&this.controlModule.firstPersonControls.dispose(),this.controlModule.thirdPersonControls&&typeof this.controlModule.thirdPersonControls.dispose=="function"&&this.controlModule.thirdPersonControls.dispose())}catch(t){console.warn("[BimEngine] Error disposing controls:",t)}this.scene&&(this.disposeSceneAttachments(this.scene),this.clearScene(this.scene));try{this.composerModule&&this.composerModule.composer&&(this.composerModule.composer.passes&&this.composerModule.composer.passes.forEach(t=>{t?.dispose?.()}),this.composerModule.composer.renderTarget1&&this.composerModule.composer.renderTarget1.dispose(),this.composerModule.composer.renderTarget2&&this.composerModule.composer.renderTarget2.dispose(),this.composerModule.composer.dispose?.(),this.composerModule.composer.passes=[])}catch(t){console.warn("[BimEngine] Error disposing composer:",t)}try{this.renderModule?.disposeRenderer?.(),this.renderer&&(this.renderer.renderLists?.dispose?.(),this.renderer.domElement&&this.renderer.domElement.parentElement&&this.renderer.domElement.parentElement.removeChild(this.renderer.domElement),this.renderer.dispose(),this.renderer.forceContextLoss())}catch(t){console.warn("[BimEngine] Error disposing renderer:",t)}try{this.stats?.dom?.parentElement&&this.stats.dom.parentElement.removeChild(this.stats.dom),this.catchSvg?.parentElement&&this.catchSvg.parentElement.removeChild(this.catchSvg),this.versionEl?.parentElement&&this.versionEl.parentElement.removeChild(this.versionEl)}catch(t){console.warn("[BimEngine] Error disposing DOM elements:",t)}try{this.events&&this.events.listeners&&this.events.listeners.clear()}catch(t){console.warn("[BimEngine] Error clearing event listeners:",t)}const A=this;A.scene=null,A.camera=null,A.renderer=null,A.controls=null,A.models=[],A.container=null,A.catchSvg=null,A.stats=null,A.versionEl=null,A.worldToScreen=null,A.measure=null,A.clipping=null,A.interactionModule=null,A.controlModule=null,A.sceneModule=null,A.cameraModule=null,A.deviceModule=null,A.renderModule=null,A.composerModule=null,A.loaderModule=null,A.lightModule=null,A.engineStatus=null,A.hoverHighLight=null,A.pathRoaming=null,A.hdr=null,A.skyManager=null,A.viewCube=null,A.grid=null,A.level=null,A.ground=null,A.minMap=null,A.fabricDraw=null,A.modelLink3d=null,A.label=null,A.annotation3d=null,A.pathDraw=null,A.calibration=null,A.linkElement2d3d=null,A.linkView2d3d=null,A.rangeScale=null,A.text=null,A.issueReport=null,A.modelEdge=null,A.nodeBox=null,A.modelTree=null,A.modelProperties=null,A.search=null,A.modelMapperBatch=null,A.modelComparison=null,A.modelExplode=null,A.materialTool=null,A.engineInfo=null,A.ai=null,A.oneClickEncoding=null,A.drawingPin=null,A.events=null,console.log("[BimEngine] Engine disposal completed")}clearScene(A){if(!A)return;[...A.children].forEach(e=>{this.clearScene(e)}),A.parent&&A.parent.remove(A),A instanceof bA&&!(A instanceof ct)&&(A.geometry&&A.geometry.dispose(),A.material&&(Array.isArray(A.material)?A.material.forEach(e=>this.disposeMaterial(e)):this.disposeMaterial(A.material))),A instanceof he&&(A.geometry&&A.geometry.dispose(),A.material&&this.disposeMaterial(A.material)),A instanceof ir&&(A.geometry&&A.geometry.dispose(),A.material&&this.disposeMaterial(A.material)),A instanceof ct&&(A.geometry&&A.geometry.dispose(),A.material&&(Array.isArray(A.material)?A.material.forEach(e=>this.disposeMaterial(e)):this.disposeMaterial(A.material)),A.instanceMatrix&&(A.instanceMatrix=null),A.instanceColor&&(A.instanceColor=null)),A instanceof JI&&A.material&&this.disposeMaterial(A.material),A instanceof Vn&&A.shadow?.dispose?.()}invokeIfExists(A,t,...e){const i=A?.[t];typeof i=="function"&&i.apply(A,e)}disposeSceneAttachments(A){new Set([A.background,A.environment,A.overrideMaterial]).forEach(e=>{this.disposeSceneAttachment(e)}),A.background=null,A.environment=null,A.overrideMaterial=null,A.dirLight=null,A.camera=null}disposeSceneAttachment(A){A&&(A instanceof Ie||A instanceof Ft)&&A.dispose?.()}disposeMaterial(A){if(!A)return;["map","lightMap","bumpMap","normalMap","specularMap","envMap","alphaMap","aoMap","displacementMap","emissiveMap","gradientMap","metalnessMap","roughnessMap","clearcoatMap","clearcoatNormalMap","clearcoatRoughnessMap","transmissionMap","thicknessMap","sheenColorMap","sheenRoughnessMap","specularIntensityMap","specularColorMap","iridescenceMap","iridescenceThicknessMap"].forEach(e=>{const i=A[e];i&&i instanceof Ft&&i.dispose()}),A.dispose()}}async function G3(s){s?.assetFiles?await L0(s.assetFiles):s?.assetFile?await qX(s.assetFile):s?.assetBaseUrl&&await L0(null),s?.assetBaseUrl&&_X(s.assetBaseUrl)}async function GG(s){return await G3(s),new WG(s)}Sn.EngineKernelV2=WG,Sn.MaterialTool=yW,Sn.createEngine=GG,Sn.default=GG,Object.defineProperties(Sn,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
|