u-space 0.0.30 → 0.0.31

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.
Files changed (34) hide show
  1. package/dist/getTransferables-C97JPUVf.cjs +1 -0
  2. package/dist/getTransferables-DrzSmiCR.js +43 -0
  3. package/dist/index.cjs +3 -3
  4. package/dist/index.js +1549 -1026
  5. package/dist/modelDecodeProtocol-D1Apm9iG.cjs +1 -0
  6. package/dist/modelDecodeProtocol-wDB7ksYw.js +56 -0
  7. package/dist/src/loaders/ModelDecodeWorkerClient.d.ts +31 -0
  8. package/dist/src/loaders/ModelLoaderManager.d.ts +15 -2
  9. package/dist/src/loaders/buildDecodedGltfModel.d.ts +4 -0
  10. package/dist/src/loaders/index.d.ts +1 -0
  11. package/dist/src/objects/Model.d.ts +1 -0
  12. package/dist/src/worker/decodeGltfModel.d.ts +10 -0
  13. package/dist/src/worker/getTransferables.d.ts +1 -0
  14. package/dist/src/worker/index.d.ts +1 -0
  15. package/dist/src/worker/installWorkerImageLoader.d.ts +3 -0
  16. package/dist/src/worker/model-decoder.d.ts +13 -0
  17. package/dist/src/worker/modelDecodeProtocol.d.ts +205 -0
  18. package/dist/src/worker/workerImageUtils.d.ts +8 -0
  19. package/dist/worker/index.cjs +1 -1
  20. package/dist/worker/index.js +8 -6
  21. package/dist/worker/model-decoder.cjs +1 -0
  22. package/dist/worker/model-decoder.js +339 -0
  23. package/dist/worker/runtime.cjs +1 -1
  24. package/dist/worker/runtime.js +202 -208
  25. package/dist/workerImageUtils-lmOMyTQN.cjs +1 -0
  26. package/dist/workerImageUtils-mQD3TQ1N.js +105 -0
  27. package/docs/api-viewer.md +45 -1
  28. package/docs/changelog.md +15 -0
  29. package/docs/examples-guide.md +9 -3
  30. package/docs/getting-started.md +1 -1
  31. package/docs/index.md +1 -1
  32. package/docs/mcp.md +5 -3
  33. package/docs/release.md +5 -3
  34. package/package.json +9 -1
@@ -0,0 +1 @@
1
+ "use strict";function o(a){const r=new Set,e=new WeakSet,n=f=>{if(!(!f||typeof f!="object")){if(f instanceof ArrayBuffer){r.add(f);return}if(ArrayBuffer.isView(f)){f.buffer instanceof ArrayBuffer&&r.add(f.buffer);return}if(typeof ImageBitmap<"u"&&f instanceof ImageBitmap){r.add(f);return}if(typeof MessagePort<"u"&&f instanceof MessagePort){r.add(f);return}if(typeof OffscreenCanvas<"u"&&f instanceof OffscreenCanvas){r.add(f);return}if(!e.has(f)){if(e.add(f),f instanceof Map){f.forEach((s,t)=>{n(t),n(s)});return}if(f instanceof Set){f.forEach(n);return}Object.values(f).forEach(n)}}};return n(a),[...r]}exports.getTransferables=o;
@@ -0,0 +1,43 @@
1
+ function t(a) {
2
+ const n = /* @__PURE__ */ new Set(), e = /* @__PURE__ */ new WeakSet(), r = (f) => {
3
+ if (!(!f || typeof f != "object")) {
4
+ if (f instanceof ArrayBuffer) {
5
+ n.add(f);
6
+ return;
7
+ }
8
+ if (ArrayBuffer.isView(f)) {
9
+ f.buffer instanceof ArrayBuffer && n.add(f.buffer);
10
+ return;
11
+ }
12
+ if (typeof ImageBitmap < "u" && f instanceof ImageBitmap) {
13
+ n.add(f);
14
+ return;
15
+ }
16
+ if (typeof MessagePort < "u" && f instanceof MessagePort) {
17
+ n.add(f);
18
+ return;
19
+ }
20
+ if (typeof OffscreenCanvas < "u" && f instanceof OffscreenCanvas) {
21
+ n.add(f);
22
+ return;
23
+ }
24
+ if (!e.has(f)) {
25
+ if (e.add(f), f instanceof Map) {
26
+ f.forEach((s, o) => {
27
+ r(o), r(s);
28
+ });
29
+ return;
30
+ }
31
+ if (f instanceof Set) {
32
+ f.forEach(r);
33
+ return;
34
+ }
35
+ Object.values(f).forEach(r);
36
+ }
37
+ }
38
+ };
39
+ return r(a), [...n];
40
+ }
41
+ export {
42
+ t as g
43
+ };
package/dist/index.cjs CHANGED
@@ -1,11 +1,11 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const j=require("./Viewer-BKNV67Jj.cjs"),o=require("three/webgpu"),Ke=require("three/addons/loaders/GLTFLoader.js"),gt=require("three/addons/loaders/FBXLoader.js"),yt=require("three/addons/loaders/OBJLoader.js"),bt=require("three/addons/loaders/STLLoader.js"),xt=require("three/addons/loaders/DRACOLoader.js"),wt=require("three/addons/loaders/KTX2Loader.js"),ge=require("three/addons/libs/meshopt_decoder.module.js"),Mt=require("three/addons/loaders/HDRLoader.js"),pe=require("three/addons/utils/SkeletonUtils.js"),f=require("three/tsl"),St=require("three/addons/tsl/display/OutlineNode.js"),M=require("three/addons/libs/tween.module.js"),It=require("three/addons/utils/BufferGeometryUtils.js"),vt=require("three/addons/renderers/CSS2DRenderer.js"),qe=require("three/addons/renderers/CSS3DRenderer.js");class Et extends o.EventDispatcher{scene;camera;domElement;_container;_selected=new Set;_boxSelectionEnabled=!1;_isSelecting=!1;_startPoint=new o.Vector2;_endPoint=new o.Vector2;_selectionBox=null;_deep=!0;targetObjects=null;constructor(e,t,s){super(),this.domElement=e,this._container=e.parentElement??e,this.scene=t,this.camera=s}get selected(){return this._selected}get selectedArray(){return Array.from(this._selected)}select(e){const t=Array.isArray(e)?e:[e],s=[];for(const n of t)this._selected.has(n)||(this._selected.add(n),s.push(n));s.length>0&&(this.dispatchEvent({type:"select",objects:s}),this.dispatchEvent({type:"change",selected:this._selected}))}deselect(e){const t=Array.isArray(e)?e:[e],s=[];for(const n of t)this._selected.delete(n)&&s.push(n);s.length>0&&(this.dispatchEvent({type:"deselect",objects:s}),this.dispatchEvent({type:"change",selected:this._selected}))}toggle(e){this._selected.has(e)?this.deselect(e):this.select(e)}clear(){if(this._selected.size===0)return;const e=Array.from(this._selected);this._selected.clear(),this.dispatchEvent({type:"deselect",objects:e}),this.dispatchEvent({type:"change",selected:this._selected})}isSelected(e){return this._selected.has(e)}enableBoxSelection(e={}){this._boxSelectionEnabled||(this._boxSelectionEnabled=!0,this._deep=e.deep??!0,this._selectionBox=document.createElement("div"),this._selectionBox.style.cssText=`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const j=require("./Viewer-BKNV67Jj.cjs"),o=require("three/webgpu"),pe=require("three/addons/loaders/GLTFLoader.js"),Ee=require("three/addons/loaders/FBXLoader.js"),St=require("three/addons/loaders/OBJLoader.js"),Et=require("three/addons/loaders/STLLoader.js"),vt=require("three/addons/loaders/DRACOLoader.js"),It=require("three/addons/loaders/KTX2Loader.js"),de=require("three/addons/libs/meshopt_decoder.module.js"),ee=require("./modelDecodeProtocol-D1Apm9iG.cjs"),Ct=require("three/addons/loaders/HDRLoader.js"),Me=require("three/addons/utils/SkeletonUtils.js"),g=require("three/tsl"),Bt=require("three/addons/tsl/display/OutlineNode.js"),T=require("three/addons/libs/tween.module.js"),Ot=require("three/addons/utils/BufferGeometryUtils.js"),At=require("three/addons/renderers/CSS2DRenderer.js"),et=require("three/addons/renderers/CSS3DRenderer.js");class _t extends o.EventDispatcher{scene;camera;domElement;_container;_selected=new Set;_boxSelectionEnabled=!1;_isSelecting=!1;_startPoint=new o.Vector2;_endPoint=new o.Vector2;_selectionBox=null;_deep=!0;targetObjects=null;constructor(e,t,s){super(),this.domElement=e,this._container=e.parentElement??e,this.scene=t,this.camera=s}get selected(){return this._selected}get selectedArray(){return Array.from(this._selected)}select(e){const t=Array.isArray(e)?e:[e],s=[];for(const n of t)this._selected.has(n)||(this._selected.add(n),s.push(n));s.length>0&&(this.dispatchEvent({type:"select",objects:s}),this.dispatchEvent({type:"change",selected:this._selected}))}deselect(e){const t=Array.isArray(e)?e:[e],s=[];for(const n of t)this._selected.delete(n)&&s.push(n);s.length>0&&(this.dispatchEvent({type:"deselect",objects:s}),this.dispatchEvent({type:"change",selected:this._selected}))}toggle(e){this._selected.has(e)?this.deselect(e):this.select(e)}clear(){if(this._selected.size===0)return;const e=Array.from(this._selected);this._selected.clear(),this.dispatchEvent({type:"deselect",objects:e}),this.dispatchEvent({type:"change",selected:this._selected})}isSelected(e){return this._selected.has(e)}enableBoxSelection(e={}){this._boxSelectionEnabled||(this._boxSelectionEnabled=!0,this._deep=e.deep??!0,this._selectionBox=document.createElement("div"),this._selectionBox.style.cssText=`
2
2
  position: absolute;
3
3
  border: 1px dashed #55aaff;
4
4
  background: rgba(75, 160, 255, 0.15);
5
5
  pointer-events: none;
6
6
  display: none;
7
7
  z-index: 9999;
8
- `,e.className&&(this._selectionBox.className=e.className),this._container.style.position=this._container.style.position||"relative",this._container.appendChild(this._selectionBox),this.domElement.addEventListener("pointerdown",this._onBoxPointerDown),this.domElement.addEventListener("pointermove",this._onBoxPointerMove),this.domElement.addEventListener("pointerup",this._onBoxPointerUp))}disableBoxSelection(){this._boxSelectionEnabled&&(this._boxSelectionEnabled=!1,this.domElement.removeEventListener("pointerdown",this._onBoxPointerDown),this.domElement.removeEventListener("pointermove",this._onBoxPointerMove),this.domElement.removeEventListener("pointerup",this._onBoxPointerUp),this._selectionBox&&(this._selectionBox.remove(),this._selectionBox=null))}setCamera(e){this.camera=e}_onBoxPointerDown=e=>{if(e.button!==0)return;this._isSelecting=!0;const t=this._container.getBoundingClientRect();this._startPoint.set(e.clientX-t.left,e.clientY-t.top),this._endPoint.copy(this._startPoint),this._selectionBox&&(this._selectionBox.style.display="block",this._updateBoxElement())};_onBoxPointerMove=e=>{if(!this._isSelecting)return;const t=this._container.getBoundingClientRect();this._endPoint.set(e.clientX-t.left,e.clientY-t.top),this._updateBoxElement()};_onBoxPointerUp=()=>{if(!this._isSelecting)return;this._isSelecting=!1,this._selectionBox&&(this._selectionBox.style.display="none");const e=this._getObjectsInBox();this.clear(),e.length>0&&this.select(e)};_updateBoxElement(){if(!this._selectionBox)return;const e=Math.min(this._startPoint.x,this._endPoint.x),t=Math.min(this._startPoint.y,this._endPoint.y),s=Math.abs(this._endPoint.x-this._startPoint.x),n=Math.abs(this._endPoint.y-this._startPoint.y);this._selectionBox.style.left=`${e}px`,this._selectionBox.style.top=`${t}px`,this._selectionBox.style.width=`${s}px`,this._selectionBox.style.height=`${n}px`}_getObjectsInBox(){const e=this._container.getBoundingClientRect(),t=e.width,s=e.height,n=new o.Vector2(this._startPoint.x/t*2-1,-(this._startPoint.y/s)*2+1),r=new o.Vector2(this._endPoint.x/t*2-1,-(this._endPoint.y/s)*2+1),a=new o.Box2(new o.Vector2(Math.min(n.x,r.x),Math.min(n.y,r.y)),new o.Vector2(Math.max(n.x,r.x),Math.max(n.y,r.y))),c=this.targetObjects||this.scene.children,l=[],h=new o.Matrix4;h.multiplyMatrices(this.camera.projectionMatrix,this.camera.matrixWorldInverse);const u=d=>{if(!d.visible)return;const p=new o.Vector3;if(p.setFromMatrixPosition(d.matrixWorld),p.applyMatrix4(h),p.z>-1&&p.z<1&&a.containsPoint(new o.Vector2(p.x,p.y))&&l.push(d),this._deep)for(const m of d.children)u(m)};for(const d of c)u(d);return l}dispose(){this.disableBoxSelection(),this._selected.clear()}}class Bt{scenes=new Map;_activeSceneKey=null;add(e,t){this.scenes.set(e,t)}create(e,t={}){const s=new o.Scene;return t.background!==void 0&&(s.background=new o.Color(t.background)),this.scenes.set(e,s),s}get(e){return this.scenes.get(e)}remove(e){this.scenes.delete(e),this._activeSceneKey===e&&(this._activeSceneKey=null)}get activeKey(){return this._activeSceneKey}set activeKey(e){this._activeSceneKey=e}keys(){return Array.from(this.scenes.keys())}serialize(e){const t=this.scenes.get(e);if(!t)return null;let s=null;return t.background instanceof o.Color&&(s=`#${t.background.getHexString()}`),{name:t.name||e,background:s,environmentRotation:{x:t.environmentRotation?.x??0,y:t.environmentRotation?.y??0,z:t.environmentRotation?.z??0},children:t.children.map(n=>n.name||n.uuid)}}clear(){this.scenes.clear(),this._activeSceneKey=null}get size(){return this.scenes.size}}class Ct{scene;lights=new Map;helpers=new Map;constructor(e){this.scene=e}addAmbient(e,t={}){const{color:s=16777215,intensity:n=.5}=t,r=new o.AmbientLight(s,n);return r.name=e,this._register(e,r),r}addDirectional(e,t={}){const{color:s=16777215,intensity:n=1,position:r={x:5,y:10,z:5},castShadow:a=!1,shadowMapSize:c=1024}=t,l=new o.DirectionalLight(s,n);return l.position.set(r.x,r.y,r.z),l.castShadow=a,a&&l.shadow.mapSize.setScalar(c),l.name=e,this._register(e,l),l}addPoint(e,t={}){const{color:s=16777215,intensity:n=1,distance:r=0,decay:a=2,position:c={x:0,y:5,z:0},castShadow:l=!1}=t,h=new o.PointLight(s,n,r,a);return h.position.set(c.x,c.y,c.z),h.castShadow=l,h.name=e,this._register(e,h),h}addSpot(e,t={}){const{color:s=16777215,intensity:n=1,distance:r=0,angle:a=Math.PI/6,penumbra:c=.1,decay:l=2,position:h={x:0,y:10,z:0},target:u,castShadow:d=!1}=t,p=new o.SpotLight(s,n,r,a,c,l);return p.position.set(h.x,h.y,h.z),u&&p.target.position.set(u.x,u.y,u.z),p.castShadow=d,p.name=e,this._register(e,p),p}addHemisphere(e,t={}){const{skyColor:s=8900331,groundColor:n=3549447,intensity:r=.6}=t,a=new o.HemisphereLight(s,n,r);return a.name=e,this._register(e,a),a}applyPreset(e){switch(this.removeAll(),e){case"indoor":this.addAmbient("preset_ambient",{intensity:.4}),this.addPoint("preset_point1",{position:{x:0,y:3,z:0},intensity:1,castShadow:!0}),this.addPoint("preset_point2",{position:{x:3,y:2,z:-3},intensity:.5});break;case"outdoor":this.addHemisphere("preset_hemi",{skyColor:8900331,groundColor:3549447,intensity:.6}),this.addDirectional("preset_sun",{position:{x:10,y:20,z:10},intensity:1.5,castShadow:!0,shadowMapSize:2048});break;case"studio":this.addAmbient("preset_ambient",{intensity:.3}),this.addDirectional("preset_key",{position:{x:5,y:8,z:5},intensity:1.2,castShadow:!0}),this.addDirectional("preset_fill",{position:{x:-5,y:5,z:-2},intensity:.6}),this.addDirectional("preset_back",{position:{x:0,y:5,z:-8},intensity:.4});break;case"warehouse":this.addAmbient("preset_ambient",{intensity:.2}),this.addPoint("preset_light1",{position:{x:-5,y:6,z:-5},intensity:2,distance:20}),this.addPoint("preset_light2",{position:{x:5,y:6,z:-5},intensity:2,distance:20}),this.addPoint("preset_light3",{position:{x:-5,y:6,z:5},intensity:2,distance:20}),this.addPoint("preset_light4",{position:{x:5,y:6,z:5},intensity:2,distance:20});break}}get(e){return this.lights.get(e)}remove(e){const t=this.lights.get(e);t&&(this.scene.remove(t),this.lights.delete(e)),this.hideHelper(e)}removeAll(){const e=Array.from(this.lights.keys());for(const t of e)this.remove(t)}showHelper(e){if(this.helpers.has(e))return;const t=this.lights.get(e);if(!t)return;let s=null;t instanceof o.DirectionalLight?s=new o.DirectionalLightHelper(t,1):t instanceof o.PointLight?s=new o.PointLightHelper(t,.5):t instanceof o.SpotLight?s=new o.SpotLightHelper(t):t instanceof o.HemisphereLight&&(s=new o.HemisphereLightHelper(t,1)),s&&(this.scene.add(s),this.helpers.set(e,s))}hideHelper(e){const t=this.helpers.get(e);t&&(this.scene.remove(t),this.helpers.delete(e))}showAllHelpers(){for(const[e]of this.lights)this.showHelper(e)}hideAllHelpers(){const e=Array.from(this.helpers.keys());for(const t of e)this.hideHelper(t)}_register(e,t){this.lights.has(e)&&this.remove(e),this.lights.set(e,t),this.scene.add(t)}dispose(){this.removeAll(),this.hideAllHelpers()}}class Xe extends Ke.GLTFLoader{constructor(e){super(e)}parse(e,t,s,n){if(_t(e.slice(0,8))==="SBMG----"){const a=Ot(e.slice(8));return super.parse(a,t,s,n)}else return super.parse(e,t,s,n)}}function _t(i){return new TextDecoder().decode(new Uint8Array(i))}function Ot(i){const e=new DataView(i);for(let t=0;t<e.byteLength;t++){const s=e.getUint8(t),n=(s>>4&15)+(s<<4&240);e.setUint8(t,n)}return e.buffer}const At=8,Lt=130,ye=66,Tt="SBK-----",Nt="SBM-----",Qe=new TextDecoder,Pt=new TextEncoder;function Dt(i){let e=At;const t=new Uint8Array(i,0,e);if(Qe.decode(t)!==Tt)return i;e+=Lt;const n=new Uint8Array(i,0,e);if(n[40]===1){const a=Pt.encode(Nt),c=new Uint8Array([n[41]]),l=Rt(n),h=jt(l);let u=ye%h.length;const d=e+ye,p=new Uint8Array(i,d),m=new Uint8Array(p.length);for(let w=0;w<p.length;w++)m[w]=p[w]^h[u],u=(u+1)%h.length;const g=new Uint8Array(a.length+c.length+m.length);return g.set(a),g.set(c,a.length),g.set(m,a.length+c.length),g.buffer}}function Rt(i){const e=new Uint8Array(128);return e.set(i.slice(42,74),0),e.set(i.slice(74,138),32),e.set(i.slice(8,40),96),e}function jt(i){const e=new Uint8Array(64);return e.set(i.slice(0,8),0),e.set(i.slice(24,32),8),e.set(i.slice(40,56),16),e.set(i.slice(64,88),32),e.set(i.slice(96,104),56),e}const zt=(i,e,t)=>{const s=i.buffer.slice(t,t+e);let n=Qe.decode(s);return n=n.replace("\\","/"),n.startsWith("Maps/")||(n=`Maps/${n}`),n},Ut=(i,e,t)=>{const[s,n,r,a,c]=e,l=t||a<1;return new o.MeshStandardNodeMaterial({name:i,color:new o.Color(s,n,r),opacity:a,transparent:l,alphaTest:.01,side:c})},kt=i=>i?.toLowerCase().endsWith(".png")??!1;class Gt{data;options;textureLoader;littleEndian=!0;materials=new Map;constructor(e,t){this.data=e,this.options=t,this.textureLoader=new o.TextureLoader(t.manager),this.textureLoader.setCrossOrigin(t.crossOrigin),this.textureLoader.setRequestHeader(t.requestHeader)}parse(e,t){let s=this.data;const n=Dt(this.data);n&&(s=n);const r=new DataView(s);let a=8;const c=r.getUint8(a);a+=1,c===1?this._parseV2(r,a,e):c===2?this._parseV2(r,a,e):c===3?this._parseV3(r,a,e):t?.(new Error(`SBMLoader: Unsupported SBM version: ${c}`))}_parseV2(e,t,s){const n=new o.Group,r=e.getUint16(t,this.littleEndian);t+=2;const a=e.getUint16(t,this.littleEndian);t+=2;for(let c=0;c<r;++c){const l=e.getUint16(t,this.littleEndian).toString();t+=2,t+=4,t+=4,t+=4,t+=4;const h=e.getFloat32(t,this.littleEndian);t+=4;const u=e.getFloat32(t,this.littleEndian);t+=4;const d=e.getFloat32(t,this.littleEndian);t+=4;const p=e.getFloat32(t,this.littleEndian);t+=4,t+=4,t+=4,t+=4,t+=4;let m=e.getUint8(t);t+=1,m===0?m=o.FrontSide:m===1?m=o.BackSide:m===2&&(m=o.DoubleSide);const g=e.getUint16(t,this.littleEndian);t+=2;const w=g>0?zt(e,g,t):"";if(t+=g,!this.materials.has(l)){const S=Ut(l,[h,u,d,p,m],kt(w));this.materials.set(l,S),w&&this.options.path&&this.textureLoader.load(o.LoaderUtils.resolveURL(w,this.options.path),b=>{b.colorSpace=o.SRGBColorSpace,b.wrapS=o.RepeatWrapping,b.wrapT=o.RepeatWrapping,b.flipY=!1,b.anisotropy=16,S.map=b})}}for(let c=0;c<a;++c){const l=e.getUint16(t,this.littleEndian).toString();t+=2;const h=e.getUint16(t,this.littleEndian).toString();t+=2;const u=[],d=[],p=[],m=[],g=e.getUint16(t,this.littleEndian);if(t+=2,g>0)for(let x=0;x<g;x++){const O=new o.Vector3;O.setX(e.getFloat32(t,this.littleEndian)),t+=4,O.setY(e.getFloat32(t,this.littleEndian)),t+=4,O.setZ(e.getFloat32(t,this.littleEndian)),t+=4,u.push(O)}const w=e.getUint16(t,this.littleEndian);if(t+=2,w>0)for(let x=0;x<w;x++)t+=4,t+=4,t+=4;const E=e.getUint16(t,this.littleEndian);if(t+=2,E>0)for(let x=0;x<E;x++){const O=new o.Vector2;O.setX(e.getFloat32(t,this.littleEndian)),t+=4,O.setY(e.getFloat32(t,this.littleEndian)),t+=4,d.push(O)}const S=e.getUint16(t,this.littleEndian);if(t+=2,S>0)for(let x=0;x<S;x++){const O=e.getUint16(t,this.littleEndian);t+=2;const R=e.getUint16(t,this.littleEndian);t+=2;const T=e.getUint16(t,this.littleEndian);t+=2;const N=[O,R,T];p.push(N),d.length>0&&m.push([d[N[0]],d[N[1]],d[N[2]]])}const b=[],v=[];for(let x=0;x<p.length;x++){const O=p[x],R=u[O[0]],T=u[O[1]],N=u[O[2]];b.push(...R.toArray(),...T.toArray(),...N.toArray());let F=new o.Vector2,P=new o.Vector2,y=new o.Vector2;const _=m[x];_!==void 0&&(F=_[0],P=_[1],y=_[2]),v.push(...F.toArray(),...P.toArray(),...y.toArray())}const C=new Float32Array(b),A=new Float32Array(v),L=new o.BufferGeometry;if(C.length>0&&L.setAttribute("position",new o.BufferAttribute(C,3)),A.length>0&&L.setAttribute("uv",new o.BufferAttribute(A,2)),L.computeVertexNormals(),this.materials.has(h)){const x=new o.Mesh(L,this.materials.get(h));x.name=l,x.castShadow=!0,x.receiveShadow=!0,n.add(x)}}s(n)}_parseV3(e,t,s){const n=new o.Group;console.warn("SBMLoader: SBM version 3 is not supported yet."),s(n)}}class Ye extends o.Loader{load(e,t,s,n){let r;if(this.resourcePath!=="")r=this.resourcePath;else if(this.path!==""){const l=o.LoaderUtils.extractUrlBase(e);r=o.LoaderUtils.resolveURL(l,this.path)}else r=o.LoaderUtils.extractUrlBase(e);this.manager.itemStart(e);const a=l=>{n?n(l):console.error(l),this.manager.itemError(e),this.manager.itemEnd(e)},c=new o.FileLoader(this.manager);c.setPath(this.path),c.setResponseType("arraybuffer"),c.setRequestHeader(this.requestHeader),c.setWithCredentials(this.withCredentials),c.load(e,l=>{try{this.parse(l,r,h=>{t(h),this.manager.itemEnd(e)},a)}catch(h){a(h)}},s,a)}parse(e,t,s,n){const r=new TextDecoder().decode(e.slice(0,8));if(r!=="SBK-----"&&r!=="SBM-----"){n?.(new Error(`SBMLoader: Invalid SBM format: ${r}`));return}new Gt(e,{path:t,crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager}).parse(s,n)}parseAsync(e,t){return new Promise((s,n)=>{this.parse(e,t,r=>{s(r)},r=>{n(r)})})}}const Wt=["map","alphaMap","aoMap","bumpMap","clearcoatMap","clearcoatNormalMap","clearcoatRoughnessMap","displacementMap","emissiveMap","envMap","gradientMap","iridescenceMap","iridescenceThicknessMap","lightMap","matcap","metalnessMap","normalMap","roughnessMap","sheenColorMap","sheenRoughnessMap","specularColorMap","specularIntensityMap","specularMap","thicknessMap","transmissionMap"];function Q(i){return i.traverse(e=>{if(!(e instanceof o.Mesh))return;const t=Array.isArray(e.material)?e.material:[e.material];for(const s of t){if(!s)continue;let n=!1;for(const r of Wt){const a=s[r];a?.isTexture&&a.image==null&&(a.dispose(),s[r]=null,n=!0)}n&&(s.needsUpdate=!0)}}),i}class U{static CACHE_NAME="u-space-model-loader-cache";static fileLoader=new o.FileLoader().setResponseType("arraybuffer");static dracoLoader=new xt.DRACOLoader().setDecoderPath(`https://cdn.jsdelivr.net/npm/three@0.${o.REVISION}.0/examples/jsm/libs/draco/`);static ktx2Loader=new wt.KTX2Loader().setTranscoderPath(`https://cdn.jsdelivr.net/npm/three@0.${o.REVISION}.0/examples/jsm/libs/basis/`);static gltfLoader=new Ke.GLTFLoader().setDRACOLoader(U.dracoLoader).setKTX2Loader(U.ktx2Loader).setMeshoptDecoder(ge.MeshoptDecoder);static sbmxLoader=new Xe().setDRACOLoader(U.dracoLoader).setKTX2Loader(U.ktx2Loader).setMeshoptDecoder(ge.MeshoptDecoder);static sbmLoader=new Ye;static fbxLoader=new gt.FBXLoader;static objLoader=new yt.OBJLoader;static stlLoader=new bt.STLLoader;static setLoadingManager(e){this.fileLoader.manager=e,this.dracoLoader.manager=e,this.ktx2Loader.manager=e,this.gltfLoader.manager=e,this.sbmxLoader.manager=e,this.sbmLoader.manager=e,this.fbxLoader.manager=e,this.objLoader.manager=e,this.stlLoader.manager=e}static async setRenderer(e){await e.init(),this.ktx2Loader.detectSupport(e)}static setDracoPath(e){this.dracoLoader.setDecoderPath(e)}static setKTX2Path(e){this.ktx2Loader.setTranscoderPath(e)}static async loadAsync(e,t={persistent:!0}){const s=e.split(".").pop()?.split("?")[0].toLowerCase();let n;switch(t.persistent&&typeof caches<"u"?n=await this.getPersistentData(e):n=await this.fileLoader.loadAsync(e),s){case"gltf":case"glb":const r=await this.gltfLoader.parseAsync(n,o.LoaderUtils.extractUrlBase(e));return r.scene.animations=r.animations,Q(r.scene);case"sbmx":const a=await this.sbmxLoader.parseAsync(n,o.LoaderUtils.extractUrlBase(e));return a.scene.animations=a.animations,Q(a.scene);case"sbm":const c=await this.sbmLoader.parseAsync(n,o.LoaderUtils.extractUrlBase(e));return Q(c);case"fbx":const l=this.fbxLoader.parse(n,o.LoaderUtils.extractUrlBase(e));return Q(l);case"obj":const h=new TextDecoder().decode(n),u=this.objLoader.parse(h);return Q(u);case"stl":const d=this.stlLoader.parse(n);return new o.Mesh(d,new o.MeshStandardNodeMaterial);default:throw new Error(`Unsupported model format: ${s}`)}}static async getPersistentData(e){try{const t=await caches.open(this.CACHE_NAME),s=await t.match(e);if(s)return await s.arrayBuffer();const n=await this.fileLoader.loadAsync(e),r=new Response(n);return await t.put(e,r),n}catch(t){return console.warn(`[LoaderManager] Failed to use Cache API for ${e}:`,t),await this.fileLoader.loadAsync(e)}}}class Ft{static textureLoader=new o.TextureLoader;static hdrLoader=new Mt.HDRLoader;static cubeTextureLoader=new o.CubeTextureLoader;static setLoadingManager(e){this.textureLoader.manager=e,this.hdrLoader.manager=e,this.cubeTextureLoader.manager=e}static async loadAsyncTexture(e){return await this.textureLoader.loadAsync(e)}static async loadAsyncHDR(e){const t=await this.hdrLoader.loadAsync(e);return t.mapping=o.EquirectangularReflectionMapping,t}static async loadAsyncCubeTexture(e,t){return this.cubeTextureLoader.setPath(e),await this.cubeTextureLoader.loadAsync(t)}}class k extends o.Mesh{isBaseMesh=!0;type="BaseMesh";castShadow=!0;receiveShadow=!0;ignoreInvisibleWhenRaycast=!0;constructor(...e){super(...e)}raycast(e,t){return this.visible===!1&&this.ignoreInvisibleWhenRaycast===!0?!1:super.raycast(e,t)}}class K extends o.Group{isBaseGroup=!0;type="BaseGroup";ignoreInvisibleWhenRaycast=!0;constructor(...e){super(...e)}raycast(e,t){return this.visible===!1&&this.ignoreInvisibleWhenRaycast===!0?!1:super.raycast(e,t)}}class Je extends o.Sprite{isBaseSprite=!0;type="BaseSprite";ignoreInvisibleWhenRaycast=!0;constructor(...e){super(...e)}raycast(e,t){return this.visible===!1&&this.ignoreInvisibleWhenRaycast===!0?!1:super.raycast(e,t)}}class J extends K{isModel=!0;type="Model";static memoryCache=new Map;mixer=null;animations=[];actions=new Map;constructor(){super()}async loadAsync(e){const{url:t,cache:s=!0,persistent:n=!0}=e;try{let r;s?J.memoryCache.has(t)?r=J.memoryCache.get(t):(r=U.loadAsync(t,{persistent:n}),J.memoryCache.set(t,r)):r=U.loadAsync(t,{persistent:n});const a=await r,c=pe.clone(a);return this.add(c),c.animations&&c.animations.length>0&&(this.animations=c.animations,this.mixer=new o.AnimationMixer(c)),c}catch(r){return console.error(`[Model] Failed to load model from ${t}:`,r),null}}playAnimation(e,t={}){if(!this.mixer||this.animations.length===0)return null;const{loop:s=!0,repetitions:n=1/0,timeScale:r=1,clampWhenFinished:a=!1}=t;let c;if(e===void 0?c=this.animations[0]:typeof e=="number"?c=this.animations[e]:c=this.animations.find(h=>h.name===e),!c)return console.warn(`[Model] Animation not found: ${e}`),null;let l=this.actions.get(c.name);return l||(l=this.mixer.clipAction(c),this.actions.set(c.name,l)),l.setLoop(s?o.LoopRepeat:o.LoopOnce,n),l.clampWhenFinished=a,l.timeScale=r,l.reset().play(),l}playAllAnimations(e={}){return this.animations.map((t,s)=>this.playAnimation(s,e)).filter(t=>t!==null)}stopAnimation(e){if(!this.mixer)return;if(e===void 0){this.mixer.stopAllAction();return}let t;typeof e=="number"?t=this.animations[e]?.name:t=e,t&&this.actions.get(t)?.stop()}updateAnimation(e){this.mixer?.update(e)}getBoundingBox(){return new o.Box3().setFromObject(this)}getCenter(){const e=new o.Vector3;return this.getBoundingBox().getCenter(e),e}setMaterial(e){this.traverse(t=>{t instanceof o.Mesh&&(t.material=e)})}static clearMemoryCache(){this.memoryCache.clear()}static async clearPersistentCache(){typeof caches<"u"&&await caches.delete("u-space-loader-cache")}}class Ze extends k{isSphereMesh=!0;type="SphereMesh";constructor({geometryParameters:e,materialParameters:t}={}){super(),this.geometry=new o.SphereGeometry(e?.radius,e?.widthSegments,e?.heightSegments,e?.phiStart,e?.phiLength,e?.thetaStart,e?.thetaLength),this.material=new o.MeshStandardNodeMaterial(t)}}class le extends k{isTubeMesh=!0;type="TubeMesh";constructor({geometryParameters:e,materialParameters:t}={}){super(),this.geometry=new o.TubeGeometry(e?.path,e?.tubularSegments,e?.radius,e?.radialSegments,e?.closed),this.material=new o.MeshStandardNodeMaterial(t)}}class Ht extends K{isTopology=!0;type="Topology";parameters={nodeColor:255,nodeRadius:.5,edgeColor:65280,edgeRadius:.1,pathColor:16711935,pathRadius:.2};nodes=new Map;adjacencyMap=new Map;graphGroup=null;pathMeshes=[];constructor(e){super(),e&&Object.assign(this.parameters,e)}addNode(e,t){this.nodes.has(e)&&console.warn(`[Topology] Node ${e} already exists. Overwriting.`),this.nodes.set(e,t),this.adjacencyMap.has(e)||this.adjacencyMap.set(e,new Map)}removeNode(e){if(!this.nodes.has(e)){console.warn(`[Topology] Node ${e} does not exist.`);return}this.nodes.delete(e),this.adjacencyMap.delete(e)}addEdge(e,t,s,n=!0){const r=this.nodes.get(e),a=this.nodes.get(t);if(!r||!a){console.error(`[Topology] Cannot add edge. One or both nodes not found: ${e}, ${t}`);return}const c=s??r.distanceTo(a);this.getNeighbors(e)?.set(t,c),n&&this.getNeighbors(t)?.set(e,c)}removeEdge(e,t,s=!0){this.getNeighbors(e)?.delete(t),s&&this.getNeighbors(t)?.delete(e)}getShortestPath(e,t){if(!this.nodes.has(e)||!this.nodes.has(t))return console.warn("[Topology] Start or End node not found."),[];const s=new Map,n=new Map,r=new Set;for(const[l]of this.nodes)s.set(l,1/0),n.set(l,null),r.add(l);for(s.set(e,0);r.size>0;){let l=null,h=1/0;for(const d of r){const p=s.get(d);p<h&&(h=p,l=d)}if(l===null||l===t||h===1/0)break;r.delete(l);const u=this.adjacencyMap?.get(l);if(u)for(const[d,p]of u){if(!r.has(d))continue;const m=s.get(l)+p;m<s.get(d)&&(s.set(d,m),n.set(d,l))}}const a=[];let c=t;if(n.get(t)===null&&e!==t)return[];for(;c!==null;){const l=this.nodes.get(c);l&&a.unshift(l),c=n.get(c)||null}return a}renderGraph(){this.clearGraph(),this.graphGroup=new o.Group;const e=new Ze({geometryParameters:{radius:this.parameters.nodeRadius,widthSegments:16,heightSegments:16},materialParameters:{color:this.parameters.nodeColor}});this.nodes.forEach((s,n)=>{const r=e.clone();r.position.copy(s),Object.assign(r.userData,{id:n,type:"node"}),this.graphGroup.add(r)});const t=new Set;this.adjacencyMap.forEach((s,n)=>{s.forEach((r,a)=>{const c=[n,a].sort().join("-");if(t.has(c))return;t.add(c);const l=this.nodes.get(n),h=this.nodes.get(a);if(l&&h){const u=new o.LineCurve3(l,h),d=new le({geometryParameters:{path:u,tubularSegments:1,radius:this.parameters.edgeRadius,radialSegments:8,closed:!1},materialParameters:{color:this.parameters.edgeColor}});Object.assign(d.userData,{from:n,to:a,weight:r,type:"edge"}),this.graphGroup.add(d)}})}),this.add(this.graphGroup)}clearGraph(){this.graphGroup&&(this.remove(this.graphGroup),this.graphGroup.traverse(e=>{e instanceof o.Mesh&&(e.geometry.dispose(),e.material.dispose())}),this.graphGroup=null)}renderPath(e,t=this.parameters.pathColor){if(e.length<2)return;const s=new o.CatmullRomCurve3(e,!1,"catmullrom",0),n=new le({geometryParameters:{path:s,tubularSegments:e.length*10,radius:this.parameters.pathRadius,closed:!1},materialParameters:{color:t}});return this.add(n),this.pathMeshes.push(n),n}clearPaths(){this.pathMeshes.forEach(e=>{this.remove(e),e.geometry.dispose(),e.material.dispose()}),this.pathMeshes=[]}exportData(){const e={};this.nodes.forEach((n,r)=>{e[r]={x:n.x,y:n.y,z:n.z}});const t=[],s=new Set;return this.adjacencyMap.forEach((n,r)=>{n.forEach((a,c)=>{const l=[r,c].sort().join("-");s.has(l)||(s.add(l),t.push({from:r,to:c,weight:a}))})}),{nodes:e,edges:t}}importData(e){this.clearGraph(),this.clearPaths(),this.nodes.clear(),this.adjacencyMap.clear(),Object.entries(e.nodes).forEach(([t,s])=>{this.addNode(t,new o.Vector3(s.x,s.y,s.z))}),e.edges.forEach(({from:t,to:s,weight:n})=>{this.addEdge(t,s,n)}),this.renderGraph()}dispose(){this.clearGraph(),this.clearPaths()}getNeighbors(e){return this.adjacencyMap.get(e)}}class $t extends Je{isPoi=!0;type="Poi";parameters={img:"",text:"",fontSize:32,fontFamily:"Arial",color:"#ffffff",iconSize:64,padding:10,backgroundColor:"rgba(0, 0, 0, 0)",borderRadius:8,textPosition:"right",scaleFactor:.01};_canvas=document.createElement("canvas");_lastParametersJSON="";constructor(e={}){super(new o.SpriteNodeMaterial),Object.assign(this.parameters,e),this.updateAsync()}async updateAsync(e={}){Object.assign(this.parameters,e);const t=JSON.stringify(this.parameters);if(t===this._lastParametersJSON)return;this._lastParametersJSON=t;const s=this._canvas,n=s.getContext("2d");if(!n)return;n.font=`${this.parameters.fontSize}px ${this.parameters.fontFamily}`;let r=null;this.parameters.img&&(r=await this._loadImage(this.parameters.img));const{text:a,fontSize:c,color:l,iconSize:h,padding:u,backgroundColor:d,borderRadius:p,textPosition:m,scaleFactor:g}=this.parameters,w=n.measureText(a),E=a?w.width:0,S=a?c:0;let b=0,v=0,C=0,A=0,L=0,x=0;const O=!!r,R=!!a;if(O&&R)switch(m){case"top":b=Math.max(h,E),v=h+u+S,L=(b-E)/2,x=S/2,C=(b-h)/2,A=S+u;break;case"bottom":b=Math.max(h,E),v=h+u+S,C=(b-h)/2,A=0,L=(b-E)/2,x=h+u+S/2;break;case"left":b=h+u+E,v=Math.max(h,S),L=0,x=v/2,C=E+u,A=(v-h)/2;break;default:b=h+u+E,v=Math.max(h,S),C=0,A=(v-h)/2,L=h+u,x=v/2;break}else O?(b=h,v=h,C=0,A=0):R&&(b=E,v=S,L=0,x=S/2);const T=b+u*2,N=v+u*2;if(s.width=T,s.height=N,n.font=`${c}px ${this.parameters.fontFamily}`,d&&(n.fillStyle=d,this._drawRoundedRect(n,0,0,T,N,p),n.fill()),O&&n.drawImage(r,C+u,A+u,h,h),R){n.fillStyle=l;const y=n.measureText(a),_=y.actualBoundingBoxAscent+y.actualBoundingBoxDescent,I=y.actualBoundingBoxAscent-_/2;n.textBaseline="alphabetic",n.fillText(a,L+u,x+u+I)}const F=this.material.map,P=new o.CanvasTexture(s);P.colorSpace=o.SRGBColorSpace,this.material.map=P,F?.dispose(),this.scale.set(T*g,N*g,1)}_loadImage(e){return new Promise((t,s)=>{if(typeof e=="string"){const n=new Image;n.crossOrigin="Anonymous",n.onload=()=>t(n),n.onerror=()=>s(new Error(`Failed to load image: ${e}`)),n.src=e}else t(e)})}_drawRoundedRect(e,t,s,n,r,a){e.beginPath(),e.moveTo(t+a,s),e.lineTo(t+n-a,s),e.quadraticCurveTo(t+n,s,t+n,s+a),e.lineTo(t+n,s+r-a),e.quadraticCurveTo(t+n,s+r,t+n-a,s+r),e.lineTo(t+a,s+r),e.quadraticCurveTo(t,s+r,t,s+r-a),e.lineTo(t,s+a),e.quadraticCurveTo(t,s,t+a,s),e.closePath()}dispose(){this.material.map?.dispose(),this.material.dispose()}}class fe extends k{isShapeMesh=!0;type="ShapeMesh";constructor({geometryParameters:e,materialParameters:t}={}){super(),this.geometry=new o.ShapeGeometry(e?.shape,e?.curveSegments),this.material=new o.MeshStandardNodeMaterial(t),this.geometry.rotateX(-Math.PI/2)}static createFromPoints(e,t={}){return new fe({...t,geometryParameters:{...t.geometryParameters,shape:new o.Shape(e.map(s=>new o.Vector2(s.x,-s.z)))}})}}class me extends k{isExtrudeMesh=!0;type="ExtrudeMesh";constructor({geometryParameters:e,materialParameters:t}={}){super(),this.geometry=new o.ExtrudeGeometry(e?.shape,e?.options),this.material=new o.MeshStandardNodeMaterial(t),this.geometry.rotateX(-Math.PI/2)}static createFromPoints(e,t={}){return e&&e.length===0&&(e=void 0),new me({...t,geometryParameters:{...t.geometryParameters,shape:new o.Shape(e?.map(s=>new o.Vector2(s.x,-s.z)))}})}}class Vt extends k{isPlaneMesh=!0;type="PlaneMesh";constructor({geometryParameters:e,materialParameters:t}={}){super(),this.geometry=new o.PlaneGeometry(e?.width,e?.height,e?.widthSegments,e?.heightSegments),this.material=new o.MeshStandardNodeMaterial(t)}}class Kt extends k{isCircleMesh=!0;type="CircleMesh";constructor({geometryParameters:e,materialParameters:t}={}){super(new o.CircleGeometry(e?.radius,e?.segments,e?.thetaStart,e?.thetaLength),new o.MeshStandardNodeMaterial(t)),this.geometry.rotateX(-Math.PI/2)}}class G{static traverseMeshes(e,t){e.traverse(s=>{s instanceof o.Mesh&&t(s)})}}const qt=3,Xt=1,Qt=0,Yt=2,Jt=.001,be=new o.Vector3,H=new o.Vector3,Zt=new o.Quaternion;function xe(i){return i.isInstanceObject===!0}function we(i){let e=!1;return i.traverse(t=>{if(e)return;const s=t;e=s.isMesh===!0||s.isSprite===!0}),e}function es(i){let e=i;for(;e;){if(!e.visible)return!1;e=e.parent}return!0}function Me(i){return i===void 0||!Number.isFinite(i)||i<=0?Yt:i}class ts{static flow(e={}){const{baseColor:t=16777215,flowColor:s=65280,speed:n=1,scale:r=3,intensity:a=4}=e,c=f.color(new o.Color(t)),l=f.color(new o.Color(s)),h=f.uv().x.mul(r).sub(f.time.mul(n)),u=f.pow(f.sin(h).add(1).mul(.5),a);return f.mix(c,l,u)}static breathe(e={}){const{baseColor:t=16777215,breathColor:s=65280,speed:n=1,intensity:r=2}=e,a=f.color(new o.Color(t)),c=f.color(new o.Color(s)),l=f.sin(f.time.mul(n)).add(1).mul(.5),h=f.pow(l,r);return f.mix(a,c,h)}static fluid(e={}){const{baseColor:t=16777215,flowColor:s=255,speed:n=1,scale:r=1,intensity:a=1,distortion:c=.5}=e,l=f.color(new o.Color(t)),h=f.color(new o.Color(s)),u=f.uv().mul(r),d=f.time.mul(n),p=f.mx_noise_float(u.add(d),1,0),m=u.add(p.mul(c)),g=f.mx_noise_float(m,1,0).add(1).mul(.5),w=f.pow(g,a);return f.mix(l,h,w)}static outline(e={}){let t=[...e.selectedObjects??[]];const s=[],n=new Map,r=new o.Box3;let a=null,c=null,l=null,h=null,u=null,d=e.instanceBoundsProxy??!0,p=e.instanceBoundsPadding??0,m=e.instanceBoundsMinSize??Jt,g=Me(e.downSampleRatio);const w=f.uniform(e.edgeStrength??qt),E=f.uniform(e.edgeThickness??Xt),S=f.uniform(e.edgeGlow??Qt),b=f.uniform(new o.Color(e.visibleEdgeColor??16777215)),v=f.uniform(new o.Color(e.hiddenEdgeColor??5125686)),C=()=>(h??=new o.BoxGeometry(1,1,1),h),A=()=>(u||(u=new o.MeshBasicNodeMaterial({color:16777215}),u.colorWrite=!1,u.depthWrite=!1,u.name="u-space.outline.instanceBoundsProxy"),u),L=y=>{const{source:_,mesh:I}=y,B=_.getInstanceBoundingBox?.(r,!0);if(!B||B.isEmpty()||!es(_)){I.visible=!1;return}B.getCenter(be),B.getSize(H);const D=Math.max(0,p),X=Math.max(0,m);H.set(Math.max(H.x+D*2,X),Math.max(H.y+D*2,X),Math.max(H.z+D*2,X)),I.visible=!0,I.layers.mask=_.layers.mask,I.matrix.compose(be,Zt,H),I.matrixWorldNeedsUpdate=!0},x=y=>{y.unsubscribe?.(),y.mesh.removeFromParent()},O=(y,_)=>{let I=n.get(y);if(!I){const B=new o.Mesh(C(),A());B.name=`u-space.outline.instanceBoundsProxy:${y.uuid}`,B.matrixAutoUpdate=!1,B.castShadow=!1,B.receiveShadow=!1,B.frustumCulled=!1,B.raycast=()=>{},B.userData.instanceObject=y,I={source:y,mesh:B,unsubscribe:y.onInstanceRenderDirty?.(()=>L(I))??null},n.set(y,I)}return I.mesh.parent!==_&&(I.mesh.removeFromParent(),_.add(I.mesh)),L(I),I.mesh.visible?I.mesh:null},R=(y,_)=>{const I=y.getInstanceRenderObject?.();return I&&we(I)?I:we(y)?y:d&&y.getInstanceBoundingBox?O(y,_):null},T=y=>{const _=new Set,I=new Set;for(const B of t){const D=xe(B)?R(B,y):B;D&&(_.add(D),xe(B)&&n.get(B)?.mesh===D&&I.add(B))}n.forEach((B,D)=>{I.has(D)||(x(B),n.delete(D))}),s.length=0,_.forEach(B=>s.push(B))},N=()=>{a?.dispose(),a=null},F=(y,_)=>{if(a&&c===y&&l===_)return a.downSampleRatio=g,a;N(),c=y,l=_,a=St.outline(y,_,{selectedObjects:s,edgeThickness:E,edgeGlow:S,downSampleRatio:g});const I=a.updateBefore.bind(a);return a.updateBefore=B=>(T(y),I(B)),a},P=((y,_)=>{const I=y.scene,B=y.camera;T(I);const D=F(I,B),X=D.visibleEdge.mul(b).add(D.hiddenEdge.mul(v)).mul(w);return f.add(_,f.vec4(X,0))});return Object.defineProperties(P,{outlineNode:{get:()=>a},selectedObjects:{get:()=>t}}),P.setSelectedObjects=y=>(t=[...y],c&&T(c),P),P.update=y=>(y.edgeStrength!==void 0&&(w.value=y.edgeStrength),y.edgeThickness!==void 0&&(E.value=y.edgeThickness),y.edgeGlow!==void 0&&(S.value=y.edgeGlow),y.visibleEdgeColor!==void 0&&b.value.set(y.visibleEdgeColor),y.hiddenEdgeColor!==void 0&&v.value.set(y.hiddenEdgeColor),y.instanceBoundsProxy!==void 0&&(d=y.instanceBoundsProxy),y.instanceBoundsPadding!==void 0&&(p=y.instanceBoundsPadding),y.instanceBoundsMinSize!==void 0&&(m=y.instanceBoundsMinSize),y.downSampleRatio!==void 0&&(g=Me(y.downSampleRatio),a&&(a.downSampleRatio=g)),c&&T(c),P),P.dispose=()=>{N(),n.forEach(x),n.clear(),h?.dispose(),u?.dispose(),h=null,u=null,t=[],s.length=0,c=null,l=null},P}}function ss(i){}const q="uSpaceHighlight",ee=`${q}/enabled`,et=`${q}/opacity`,tt=`${q}/color`,st=`${q}/overwrite`,nt=`${q}/multiplyOpacity`,re=`${q}/instancedOriginalOpacity`,oe="uSpaceBreathe",ie=`${oe}/enabled`,rt=`${oe}/color`,it=`${oe}/speed`,at=`${oe}/intensity`,ae=new WeakMap,ns=f.Fn(()=>{const i=f.userData(ee,"uint"),e=f.userData(tt,"uint"),t=f.userData(st,"uint"),s=ve(e),n=f.materialColor.mul(s),r=f.select(t.greaterThan(0),s,n),a=f.select(i.greaterThan(0),r,f.materialColor),c=f.userData(ie,"uint"),l=f.userData(rt,"uint"),h=f.userData(it,"float"),u=f.userData(at,"float"),d=ve(l),p=f.sin(f.time.mul(h)).add(1).mul(.5),m=f.pow(p,u),g=f.mix(a,d,m);return f.select(c.greaterThan(0),g,a)})(),rs=f.Fn(()=>{const i=f.userData(ee,"uint"),e=f.userData(et,"float"),t=f.userData(nt,"uint"),s=f.select(t.greaterThan(0),f.materialOpacity.mul(e),e);return f.select(i.greaterThan(0),s,f.materialOpacity)})();function Z(i){return Array.isArray(i.material)?i.material:[i.material]}function Se(i){Z(i).forEach(t=>{if(!t)return;let s=ae.get(t);s||(s={colorNode:t.colorNode,opacityNode:t.opacityNode,transparent:t.transparent,depthWrite:t.depthWrite,activeMeshes:new Set},ae.set(t,s)),s.activeMeshes.add(i),t.transparent=!0,t.colorNode=ns,t.opacityNode=rs,t.needsUpdate=!0})}function Ie(i){const e=i.userData[ee],t=i.userData[ie];if(e||t)return;Z(i).forEach(n=>{if(!n)return;const r=ae.get(n);r&&(r.activeMeshes.delete(i),!(r.activeMeshes.size>0)&&(n.colorNode=r.colorNode,n.opacityNode=r.opacityNode,n.transparent=r.transparent,n.depthWrite=r.depthWrite,n.needsUpdate=!0,ae.delete(n)))})}function is(i,e,t,s){const n=i,r=n.setInstanceHighlight;if(r)return r.call(i,e,t,s),!0;const a=n.setInstanceColor,c=n.setInstanceOpacity,l=n.getInstanceOpacity,h=n.getInstanceColor,u=n.hasInstanceColor;return!a||!c?!1:(i.userData[re]===void 0&&(i.userData[re]={hasColor:u?.call(i)??!1,color:h?.call(i,new o.Color).getHex()??16777215,opacity:l?.call(i)??1}),a.call(i,e),c.call(i,t),!0)}function as(i){const e=i,t=e.clearInstanceHighlight;if(t)return t.call(i),!0;const s=e.resetInstanceColor,n=e.setInstanceColor,r=e.setInstanceOpacity;if(!s||!r)return!1;const a=i.userData[re];return a&&(a.hasColor&&n?n.call(i,a.color):s.call(i),r.call(i,a.opacity),Reflect.deleteProperty(i.userData,re)),!0}class W{static highlightColor(e,t={}){const s=Array.isArray(e)?e:[e],{opacity:n=.5,color:r=16711680,overwrite:a=!1,depthWrite:c,multiplyOpacity:l=!1}=t,h=new o.Color(r).getHex();for(const u of s)is(u,r,n,a)||G.traverseMeshes(u,d=>{d.userData[ee]=1,d.userData[et]=n,d.userData[tt]=h,d.userData[st]=a?1:0,d.userData[nt]=l?1:0,Se(d),c!==void 0&&Z(d).forEach(m=>{m&&(m.depthWrite=c)})})}static removeHighlightColor(e){const t=Array.isArray(e)?e:[e];for(const s of t)as(s)||G.traverseMeshes(s,n=>{n.userData[ee]=0,Ie(n)})}static breatheColor(e,t={}){const s=Array.isArray(e)?e:[e],n=Object.assign({color:65280,speed:1,intensity:2},t);n.color=new o.Color(n.color).getHex();for(const r of s)G.traverseMeshes(r,a=>{a.userData[ie]=1,a.userData[rt]=n.color,a.userData[it]=n.speed,a.userData[at]=n.intensity,Se(a)})}static removeBreatheColor(e){const t=Array.isArray(e)?e:[e];for(const s of t)G.traverseMeshes(s,n=>{n.userData[ie]=0,Ie(n)})}static wireframe(e,t=!0){const s=Array.isArray(e)?e:[e];for(const n of s)G.traverseMeshes(n,r=>{Z(r).forEach(a=>{if(!a)return;const c=a;c.wireframe=t,c.needsUpdate=!0})})}static removeWireframe(e){W.wireframe(e,!1)}static fadeIn(e,t={}){const{duration:s=500}=t;return W._fade(e,0,1,s)}static fadeOut(e,t={}){const{duration:s=500}=t;return W._fade(e,1,0,s)}static _fade(e,t,s,n){const r=Array.isArray(e)?e:[e],a=new Map;for(const c of r)G.traverseMeshes(c,l=>{Z(l).forEach(h=>{if(!h||a.has(h))return;const u=h.opacity,d=h.transparent,p=s>=1?u:s;a.set(h,{material:h,targetOpacity:p,originalOpacity:u,originalTransparent:d}),h.transparent=!0,h.opacity=t,h.needsUpdate=!0})});return a.size===0?Promise.resolve():new Promise(c=>{const l=performance.now();let h=0;const u=()=>{const d=performance.now()-l,p=Math.min(d/n,1);if(!r[0].parent){cancelAnimationFrame(h),c();return}for(const{material:g,targetOpacity:w}of a.values())g.opacity=t+(w-t)*p,g.needsUpdate=!0;if(p<1)h=requestAnimationFrame(u);else{if(s>=1)for(const{material:g,originalOpacity:w,originalTransparent:E}of a.values())g.opacity=w,g.transparent=E,g.needsUpdate=!0;c()}};h=requestAnimationFrame(u)})}}const ve=i=>{const e=i.shiftRight(16).bitAnd(255).toFloat().div(255),t=i.shiftRight(8).bitAnd(255).toFloat().div(255),s=i.bitAnd(255).toFloat().div(255);return f.vec3(e,t,s)};class ot extends M.Tween{viewer;constructor(e,t){super(t),this.viewer=e}_update=({time:e})=>{const t=this.update(e);this.viewer.invalidate(),t||this.viewer.removeEventListener("afterControlsUpdate",this._update)};easingByMode(e){const t=cs[e];return super.easing(t)}start(e,t){return this.viewer.addEventListener("afterControlsUpdate",this._update),super.start(e,t)}stop(){return this.viewer.removeEventListener("afterControlsUpdate",this._update),super.stop()}}function os(i,e,t,s={},n,r){return new Promise((a,c)=>{const{duration:l=1e3,delay:h=0,repeat:u=!1,mode:d="Linear.None",yoyo:p=!1}=s,m=new ot(i,e).to(t,l).easingByMode(d).delay(h).onUpdate(g=>{n?.(g,m)}).onComplete(()=>{a()}).onStop(()=>{c("animation stop")}).onStart(()=>{r?.(m)});typeof u=="number"?m.repeat(u):typeof u=="boolean"&&u&&m.repeat(1/0),p&&m.repeatDelay(20),m.yoyo(p),m.start()})}const cs={"Linear.None":M.Easing.Linear.None,"Quadratic.In":M.Easing.Quadratic.In,"Quadratic.Out":M.Easing.Quadratic.Out,"Quadratic.InOut":M.Easing.Quadratic.InOut,"Cubic.In":M.Easing.Cubic.In,"Cubic.Out":M.Easing.Cubic.Out,"Cubic.InOut":M.Easing.Cubic.InOut,"Quartic.In":M.Easing.Quartic.In,"Quartic.Out":M.Easing.Quartic.Out,"Quartic.InOut":M.Easing.Quartic.InOut,"Quintic.In":M.Easing.Quintic.In,"Quintic.Out":M.Easing.Quintic.Out,"Quintic.InOut":M.Easing.Quintic.InOut,"Sinusoidal.In":M.Easing.Sinusoidal.In,"Sinusoidal.Out":M.Easing.Sinusoidal.Out,"Sinusoidal.InOut":M.Easing.Sinusoidal.InOut,"Exponential.In":M.Easing.Exponential.In,"Exponential.Out":M.Easing.Exponential.Out,"Exponential.InOut":M.Easing.Exponential.InOut,"Circular.In":M.Easing.Circular.In,"Circular.Out":M.Easing.Circular.Out,"Circular.InOut":M.Easing.Circular.InOut,"Elastic.In":M.Easing.Elastic.In,"Elastic.Out":M.Easing.Elastic.Out,"Elastic.InOut":M.Easing.Elastic.InOut,"Back.In":M.Easing.Back.In,"Back.Out":M.Easing.Back.Out,"Back.InOut":M.Easing.Back.InOut,"Bounce.In":M.Easing.Bounce.In,"Bounce.Out":M.Easing.Bounce.Out,"Bounce.InOut":M.Easing.Bounce.InOut};class ls{scene;planes=new Map;helpers=new Map;group;constructor(e){this.scene=e,this.group=new o.ClippingGroup,this.group.name="__clippingToolGroup",this.scene.add(this.group)}attach(){const e=[...this.scene.children];for(const t of e)t!==this.group&&this.group.add(t)}detach(){const e=[...this.group.children];for(const t of e)this.helpers.has(t.name)||this.scene.add(t)}enable(){this.group.enabled=!0}disable(){this.group.enabled=!1}addPlane(e,t={}){const{normal:s={x:0,y:-1,z:0},constant:n=0,showHelper:r=!1,helperSize:a=5,helperColor:c=16711680}=t,l=new o.Plane(new o.Vector3(s.x,s.y,s.z),n);return this.planes.set(e,l),this._syncPlanes(),r&&this.showHelper(e,a,c),l}addBox(e,t,s={}){const{showHelpers:n=!1,helperColor:r=16711680}=s,a=t.min,c=t.max,l=[{suffix:"+x",normal:{x:-1,y:0,z:0},constant:c.x},{suffix:"-x",normal:{x:1,y:0,z:0},constant:-a.x},{suffix:"+y",normal:{x:0,y:-1,z:0},constant:c.y},{suffix:"-y",normal:{x:0,y:1,z:0},constant:-a.y},{suffix:"+z",normal:{x:0,y:0,z:-1},constant:c.z},{suffix:"-z",normal:{x:0,y:0,z:1},constant:-a.z}],h=[];for(const u of l){const d=`${e}_${u.suffix}`;this.addPlane(d,{normal:u.normal,constant:u.constant,showHelper:n,helperColor:r}),h.push(d)}return h}addBoxFromObject(e,t,s=0,n={}){const r=new o.Box3().setFromObject(t);return r.expandByScalar(s),this.addBox(e,r,n)}setPlaneConstant(e,t){const s=this.planes.get(e);s&&(s.constant=t)}removePlane(e){this.planes.delete(e),this.hideHelper(e),this._syncPlanes()}removeBox(e){const t=["+x","-x","+y","-y","+z","-z"];for(const s of t)this.removePlane(`${e}_${s}`)}removeAll(){const e=Array.from(this.helpers.keys());for(const t of e)this.hideHelper(t);this.planes.clear(),this._syncPlanes()}showHelper(e,t=5,s=16711680){this.hideHelper(e);const n=this.planes.get(e);if(!n)return;const r=new o.PlaneHelper(n,t,new o.Color(s).getHex());r.name=e,this.helpers.set(e,r),this.scene.add(r)}hideHelper(e){const t=this.helpers.get(e);t&&(this.scene.remove(t),t.dispose(),this.helpers.delete(e))}get(e){return this.planes.get(e)}_syncPlanes(){this.group.clippingPlanes=Array.from(this.planes.values())}dispose(){this.detach(),this.removeAll(),this.scene.remove(this.group)}}class hs{scene;measurements=new Map;_idCounter=0;constructor(e){this.scene=e}measureDistance(e,t,s={}){const{lineColor:n=16776960}=s,r=new o.Vector3(e.x,e.y,e.z),a=new o.Vector3(t.x,t.y,t.z),c=r.distanceTo(a),l=`measure_dist_${this._idCounter++}`,h=new o.Group;h.name=l;const u=new o.BufferGeometry().setFromPoints([r,a]),d=new o.LineBasicMaterial({color:n}),p=new o.Line(u,d);h.add(p),this.scene.add(h);const m={id:l,type:"distance",value:c,unit:"m",points:[r,a],object:h};return this.measurements.set(l,m),m}measureArea(e,t={}){const{lineColor:s=65280}=t;if(e.length<3)throw new Error("MeasureTool.measureArea requires at least 3 points");const n=e.map(m=>new o.Vector3(m.x,m.y,m.z)),r=this._calculatePolygonArea(n),a=`measure_area_${this._idCounter++}`,c=new o.Group;c.name=a;const l=[...n,n[0]],h=new o.BufferGeometry().setFromPoints(l),u=new o.LineBasicMaterial({color:s}),d=new o.Line(h,u);c.add(d),this.scene.add(c);const p={id:a,type:"area",value:r,unit:"m²",points:n,object:c};return this.measurements.set(a,p),p}measureAngle(e,t,s,n={}){const{lineColor:r=16746496}=n,a=new o.Vector3(e.x,e.y,e.z),c=new o.Vector3(t.x,t.y,t.z),l=new o.Vector3(s.x,s.y,s.z),h=a.clone().sub(c).normalize(),u=l.clone().sub(c).normalize(),p=Math.acos(Math.max(-1,Math.min(1,h.dot(u))))*180/Math.PI,m=`measure_angle_${this._idCounter++}`,g=new o.Group;g.name=m;const w=new o.BufferGeometry().setFromPoints([a,c,l]),E=new o.LineBasicMaterial({color:r}),S=new o.Line(w,E);g.add(S),this.scene.add(g);const b={id:m,type:"angle",value:p,unit:"°",points:[a,c,l],object:g};return this.measurements.set(m,b),b}get(e){return this.measurements.get(e)}remove(e){const t=this.measurements.get(e);t&&(this.scene.remove(t.object),t.object.traverse(s=>{s.geometry?.dispose(),s.material?.dispose()}),this.measurements.delete(e))}removeAll(){const e=Array.from(this.measurements.keys());for(const t of e)this.remove(t)}getAll(){return Array.from(this.measurements.values())}_calculatePolygonArea(e){const t=e.length,s=new o.Vector3;for(let r=0;r<t;r++){const a=e[r],c=e[(r+1)%t],l=new o.Vector3().crossVectors(a,c);s.add(l)}const n=new o.Vector3;if(t>=3){const r=e[1].clone().sub(e[0]),a=e[2].clone().sub(e[0]);n.crossVectors(r,a).normalize()}return Math.abs(s.dot(n))/2}dispose(){this.removeAll()}}class us{scene;annotations=new Map;_idCounter=0;_createCSSObject=null;constructor(e){this.scene=e}setCSSObjectFactory(e){this._createCSSObject=e}add(e,t){this.annotations.has(e)&&this.remove(e);const s=new o.Group;s.name=`annotation_${e}`;const n=new o.Vector3(t.position.x,t.position.y,t.position.z);s.position.copy(n);const r=document.createElement("div");if(r.innerHTML=t.content,r.style.cssText=`
8
+ `,e.className&&(this._selectionBox.className=e.className),this._container.style.position=this._container.style.position||"relative",this._container.appendChild(this._selectionBox),this.domElement.addEventListener("pointerdown",this._onBoxPointerDown),this.domElement.addEventListener("pointermove",this._onBoxPointerMove),this.domElement.addEventListener("pointerup",this._onBoxPointerUp))}disableBoxSelection(){this._boxSelectionEnabled&&(this._boxSelectionEnabled=!1,this.domElement.removeEventListener("pointerdown",this._onBoxPointerDown),this.domElement.removeEventListener("pointermove",this._onBoxPointerMove),this.domElement.removeEventListener("pointerup",this._onBoxPointerUp),this._selectionBox&&(this._selectionBox.remove(),this._selectionBox=null))}setCamera(e){this.camera=e}_onBoxPointerDown=e=>{if(e.button!==0)return;this._isSelecting=!0;const t=this._container.getBoundingClientRect();this._startPoint.set(e.clientX-t.left,e.clientY-t.top),this._endPoint.copy(this._startPoint),this._selectionBox&&(this._selectionBox.style.display="block",this._updateBoxElement())};_onBoxPointerMove=e=>{if(!this._isSelecting)return;const t=this._container.getBoundingClientRect();this._endPoint.set(e.clientX-t.left,e.clientY-t.top),this._updateBoxElement()};_onBoxPointerUp=()=>{if(!this._isSelecting)return;this._isSelecting=!1,this._selectionBox&&(this._selectionBox.style.display="none");const e=this._getObjectsInBox();this.clear(),e.length>0&&this.select(e)};_updateBoxElement(){if(!this._selectionBox)return;const e=Math.min(this._startPoint.x,this._endPoint.x),t=Math.min(this._startPoint.y,this._endPoint.y),s=Math.abs(this._endPoint.x-this._startPoint.x),n=Math.abs(this._endPoint.y-this._startPoint.y);this._selectionBox.style.left=`${e}px`,this._selectionBox.style.top=`${t}px`,this._selectionBox.style.width=`${s}px`,this._selectionBox.style.height=`${n}px`}_getObjectsInBox(){const e=this._container.getBoundingClientRect(),t=e.width,s=e.height,n=new o.Vector2(this._startPoint.x/t*2-1,-(this._startPoint.y/s)*2+1),r=new o.Vector2(this._endPoint.x/t*2-1,-(this._endPoint.y/s)*2+1),a=new o.Box2(new o.Vector2(Math.min(n.x,r.x),Math.min(n.y,r.y)),new o.Vector2(Math.max(n.x,r.x),Math.max(n.y,r.y))),c=this.targetObjects||this.scene.children,l=[],h=new o.Matrix4;h.multiplyMatrices(this.camera.projectionMatrix,this.camera.matrixWorldInverse);const d=u=>{if(!u.visible)return;const p=new o.Vector3;if(p.setFromMatrixPosition(u.matrixWorld),p.applyMatrix4(h),p.z>-1&&p.z<1&&a.containsPoint(new o.Vector2(p.x,p.y))&&l.push(u),this._deep)for(const f of u.children)d(f)};for(const u of c)d(u);return l}dispose(){this.disableBoxSelection(),this._selected.clear()}}class Lt{scenes=new Map;_activeSceneKey=null;add(e,t){this.scenes.set(e,t)}create(e,t={}){const s=new o.Scene;return t.background!==void 0&&(s.background=new o.Color(t.background)),this.scenes.set(e,s),s}get(e){return this.scenes.get(e)}remove(e){this.scenes.delete(e),this._activeSceneKey===e&&(this._activeSceneKey=null)}get activeKey(){return this._activeSceneKey}set activeKey(e){this._activeSceneKey=e}keys(){return Array.from(this.scenes.keys())}serialize(e){const t=this.scenes.get(e);if(!t)return null;let s=null;return t.background instanceof o.Color&&(s=`#${t.background.getHexString()}`),{name:t.name||e,background:s,environmentRotation:{x:t.environmentRotation?.x??0,y:t.environmentRotation?.y??0,z:t.environmentRotation?.z??0},children:t.children.map(n=>n.name||n.uuid)}}clear(){this.scenes.clear(),this._activeSceneKey=null}get size(){return this.scenes.size}}class Tt{scene;lights=new Map;helpers=new Map;constructor(e){this.scene=e}addAmbient(e,t={}){const{color:s=16777215,intensity:n=.5}=t,r=new o.AmbientLight(s,n);return r.name=e,this._register(e,r),r}addDirectional(e,t={}){const{color:s=16777215,intensity:n=1,position:r={x:5,y:10,z:5},castShadow:a=!1,shadowMapSize:c=1024}=t,l=new o.DirectionalLight(s,n);return l.position.set(r.x,r.y,r.z),l.castShadow=a,a&&l.shadow.mapSize.setScalar(c),l.name=e,this._register(e,l),l}addPoint(e,t={}){const{color:s=16777215,intensity:n=1,distance:r=0,decay:a=2,position:c={x:0,y:5,z:0},castShadow:l=!1}=t,h=new o.PointLight(s,n,r,a);return h.position.set(c.x,c.y,c.z),h.castShadow=l,h.name=e,this._register(e,h),h}addSpot(e,t={}){const{color:s=16777215,intensity:n=1,distance:r=0,angle:a=Math.PI/6,penumbra:c=.1,decay:l=2,position:h={x:0,y:10,z:0},target:d,castShadow:u=!1}=t,p=new o.SpotLight(s,n,r,a,c,l);return p.position.set(h.x,h.y,h.z),d&&p.target.position.set(d.x,d.y,d.z),p.castShadow=u,p.name=e,this._register(e,p),p}addHemisphere(e,t={}){const{skyColor:s=8900331,groundColor:n=3549447,intensity:r=.6}=t,a=new o.HemisphereLight(s,n,r);return a.name=e,this._register(e,a),a}applyPreset(e){switch(this.removeAll(),e){case"indoor":this.addAmbient("preset_ambient",{intensity:.4}),this.addPoint("preset_point1",{position:{x:0,y:3,z:0},intensity:1,castShadow:!0}),this.addPoint("preset_point2",{position:{x:3,y:2,z:-3},intensity:.5});break;case"outdoor":this.addHemisphere("preset_hemi",{skyColor:8900331,groundColor:3549447,intensity:.6}),this.addDirectional("preset_sun",{position:{x:10,y:20,z:10},intensity:1.5,castShadow:!0,shadowMapSize:2048});break;case"studio":this.addAmbient("preset_ambient",{intensity:.3}),this.addDirectional("preset_key",{position:{x:5,y:8,z:5},intensity:1.2,castShadow:!0}),this.addDirectional("preset_fill",{position:{x:-5,y:5,z:-2},intensity:.6}),this.addDirectional("preset_back",{position:{x:0,y:5,z:-8},intensity:.4});break;case"warehouse":this.addAmbient("preset_ambient",{intensity:.2}),this.addPoint("preset_light1",{position:{x:-5,y:6,z:-5},intensity:2,distance:20}),this.addPoint("preset_light2",{position:{x:5,y:6,z:-5},intensity:2,distance:20}),this.addPoint("preset_light3",{position:{x:-5,y:6,z:5},intensity:2,distance:20}),this.addPoint("preset_light4",{position:{x:5,y:6,z:5},intensity:2,distance:20});break}}get(e){return this.lights.get(e)}remove(e){const t=this.lights.get(e);t&&(this.scene.remove(t),this.lights.delete(e)),this.hideHelper(e)}removeAll(){const e=Array.from(this.lights.keys());for(const t of e)this.remove(t)}showHelper(e){if(this.helpers.has(e))return;const t=this.lights.get(e);if(!t)return;let s=null;t instanceof o.DirectionalLight?s=new o.DirectionalLightHelper(t,1):t instanceof o.PointLight?s=new o.PointLightHelper(t,.5):t instanceof o.SpotLight?s=new o.SpotLightHelper(t):t instanceof o.HemisphereLight&&(s=new o.HemisphereLightHelper(t,1)),s&&(this.scene.add(s),this.helpers.set(e,s))}hideHelper(e){const t=this.helpers.get(e);t&&(this.scene.remove(t),this.helpers.delete(e))}showAllHelpers(){for(const[e]of this.lights)this.showHelper(e)}hideAllHelpers(){const e=Array.from(this.helpers.keys());for(const t of e)this.hideHelper(t)}_register(e,t){this.lights.has(e)&&this.remove(e),this.lights.set(e,t),this.scene.add(t)}dispose(){this.removeAll(),this.hideAllHelpers()}}class fe extends pe.GLTFLoader{constructor(e){super(e)}parse(e,t,s,n){if(Dt(e.slice(0,8))==="SBMG----"){const a=Nt(e.slice(8));return super.parse(a,t,s,n)}else return super.parse(e,t,s,n)}}function Dt(i){return new TextDecoder().decode(new Uint8Array(i))}function Nt(i){const e=new DataView(i);for(let t=0;t<e.byteLength;t++){const s=e.getUint8(t),n=(s>>4&15)+(s<<4&240);e.setUint8(t,n)}return e.buffer}const Rt=8,Pt=130,ve=66,kt="SBK-----",jt="SBM-----",tt=new TextDecoder,Ut=new TextEncoder;function zt(i){let e=Rt;const t=new Uint8Array(i,0,e);if(tt.decode(t)!==kt)return i;e+=Pt;const n=new Uint8Array(i,0,e);if(n[40]===1){const a=Ut.encode(jt),c=new Uint8Array([n[41]]),l=Ft(n),h=Wt(l);let d=ve%h.length;const u=e+ve,p=new Uint8Array(i,u),f=new Uint8Array(p.length);for(let C=0;C<p.length;C++)f[C]=p[C]^h[d],d=(d+1)%h.length;const S=new Uint8Array(a.length+c.length+f.length);return S.set(a),S.set(c,a.length),S.set(f,a.length+c.length),S.buffer}}function Ft(i){const e=new Uint8Array(128);return e.set(i.slice(42,74),0),e.set(i.slice(74,138),32),e.set(i.slice(8,40),96),e}function Wt(i){const e=new Uint8Array(64);return e.set(i.slice(0,8),0),e.set(i.slice(24,32),8),e.set(i.slice(40,56),16),e.set(i.slice(64,88),32),e.set(i.slice(96,104),56),e}const Gt=(i,e,t)=>{const s=i.buffer.slice(t,t+e);let n=tt.decode(s);return n=n.replace("\\","/"),n.startsWith("Maps/")||(n=`Maps/${n}`),n},Ht=(i,e,t)=>{const[s,n,r,a,c]=e,l=t||a<1;return new o.MeshStandardNodeMaterial({name:i,color:new o.Color(s,n,r),opacity:a,transparent:l,alphaTest:.01,side:c})},$t=i=>i?.toLowerCase().endsWith(".png")??!1;class Vt{data;options;textureLoader;littleEndian=!0;materials=new Map;constructor(e,t){this.data=e,this.options=t,this.textureLoader=new o.TextureLoader(t.manager),this.textureLoader.setCrossOrigin(t.crossOrigin),this.textureLoader.setRequestHeader(t.requestHeader)}parse(e,t){let s=this.data;const n=zt(this.data);n&&(s=n);const r=new DataView(s);let a=8;const c=r.getUint8(a);a+=1,c===1?this._parseV2(r,a,e):c===2?this._parseV2(r,a,e):c===3?this._parseV3(r,a,e):t?.(new Error(`SBMLoader: Unsupported SBM version: ${c}`))}_parseV2(e,t,s){const n=new o.Group,r=e.getUint16(t,this.littleEndian);t+=2;const a=e.getUint16(t,this.littleEndian);t+=2;for(let c=0;c<r;++c){const l=e.getUint16(t,this.littleEndian).toString();t+=2,t+=4,t+=4,t+=4,t+=4;const h=e.getFloat32(t,this.littleEndian);t+=4;const d=e.getFloat32(t,this.littleEndian);t+=4;const u=e.getFloat32(t,this.littleEndian);t+=4;const p=e.getFloat32(t,this.littleEndian);t+=4,t+=4,t+=4,t+=4,t+=4;let f=e.getUint8(t);t+=1,f===0?f=o.FrontSide:f===1?f=o.BackSide:f===2&&(f=o.DoubleSide);const S=e.getUint16(t,this.littleEndian);t+=2;const C=S>0?Gt(e,S,t):"";if(t+=S,!this.materials.has(l)){const O=Ht(l,[h,d,u,p,f],$t(C));this.materials.set(l,O),C&&this.options.path&&this.textureLoader.load(o.LoaderUtils.resolveURL(C,this.options.path),w=>{w.colorSpace=o.SRGBColorSpace,w.wrapS=o.RepeatWrapping,w.wrapT=o.RepeatWrapping,w.flipY=!1,w.anisotropy=16,O.map=w})}}for(let c=0;c<a;++c){const l=e.getUint16(t,this.littleEndian).toString();t+=2;const h=e.getUint16(t,this.littleEndian).toString();t+=2;const d=[],u=[],p=[],f=[],S=e.getUint16(t,this.littleEndian);if(t+=2,S>0)for(let M=0;M<S;M++){const I=new o.Vector3;I.setX(e.getFloat32(t,this.littleEndian)),t+=4,I.setY(e.getFloat32(t,this.littleEndian)),t+=4,I.setZ(e.getFloat32(t,this.littleEndian)),t+=4,d.push(I)}const C=e.getUint16(t,this.littleEndian);if(t+=2,C>0)for(let M=0;M<C;M++)t+=4,t+=4,t+=4;const D=e.getUint16(t,this.littleEndian);if(t+=2,D>0)for(let M=0;M<D;M++){const I=new o.Vector2;I.setX(e.getFloat32(t,this.littleEndian)),t+=4,I.setY(e.getFloat32(t,this.littleEndian)),t+=4,u.push(I)}const O=e.getUint16(t,this.littleEndian);if(t+=2,O>0)for(let M=0;M<O;M++){const I=e.getUint16(t,this.littleEndian);t+=2;const A=e.getUint16(t,this.littleEndian);t+=2;const v=e.getUint16(t,this.littleEndian);t+=2;const B=[I,A,v];p.push(B),u.length>0&&f.push([u[B[0]],u[B[1]],u[B[2]]])}const w=[],x=[];for(let M=0;M<p.length;M++){const I=p[M],A=d[I[0]],v=d[I[1]],B=d[I[2]];w.push(...A.toArray(),...v.toArray(),...B.toArray());let P=new o.Vector2,R=new o.Vector2,m=new o.Vector2;const N=f[M];N!==void 0&&(P=N[0],R=N[1],m=N[2]),x.push(...P.toArray(),...R.toArray(),...m.toArray())}const b=new Float32Array(w),y=new Float32Array(x),E=new o.BufferGeometry;if(b.length>0&&E.setAttribute("position",new o.BufferAttribute(b,3)),y.length>0&&E.setAttribute("uv",new o.BufferAttribute(y,2)),E.computeVertexNormals(),this.materials.has(h)){const M=new o.Mesh(E,this.materials.get(h));M.name=l,M.castShadow=!0,M.receiveShadow=!0,n.add(M)}}s(n)}_parseV3(e,t,s){const n=new o.Group;console.warn("SBMLoader: SBM version 3 is not supported yet."),s(n)}}class me extends o.Loader{load(e,t,s,n){let r;if(this.resourcePath!=="")r=this.resourcePath;else if(this.path!==""){const l=o.LoaderUtils.extractUrlBase(e);r=o.LoaderUtils.resolveURL(l,this.path)}else r=o.LoaderUtils.extractUrlBase(e);this.manager.itemStart(e);const a=l=>{n?n(l):console.error(l),this.manager.itemError(e),this.manager.itemEnd(e)},c=new o.FileLoader(this.manager);c.setPath(this.path),c.setResponseType("arraybuffer"),c.setRequestHeader(this.requestHeader),c.setWithCredentials(this.withCredentials),c.load(e,l=>{try{this.parse(l,r,h=>{t(h),this.manager.itemEnd(e)},a)}catch(h){a(h)}},s,a)}parse(e,t,s,n){const r=new TextDecoder().decode(e.slice(0,8));if(r!=="SBK-----"&&r!=="SBM-----"){n?.(new Error(`SBMLoader: Invalid SBM format: ${r}`));return}new Vt(e,{path:t,crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager}).parse(s,n)}parseAsync(e,t){return new Promise((s,n)=>{this.parse(e,t,r=>{s(r)},r=>{n(r)})})}}const Kt={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},qt={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},Xt={POSITION:"position",NORMAL:"normal",TANGENT:"tangent",TEXCOORD_0:"uv",TEXCOORD_1:"uv1",TEXCOORD_2:"uv2",TEXCOORD_3:"uv3",COLOR_0:"color"};function Q(i,e){e&&typeof e=="object"&&!Array.isArray(e)&&Object.assign(i.userData,e)}function Yt(i){if(i.protocolVersion!==ee.MODEL_DECODE_PROTOCOL_VERSION)throw new Error(`Unsupported model decode protocol ${i.protocolVersion}; expected ${ee.MODEL_DECODE_PROTOCOL_VERSION}.`);const{document:e,buffers:t,images:s}=i;ee.validateDecodedGltfNodeGraph(e);const n=new Map,r=new Map,a=new Map,c=new Map,l=new Map,h=x=>{const b=n.get(x);if(b)return b;const y=e.accessors?.[x];if(!y||y.bufferView===void 0)throw new Error(`Decoded glTF references missing accessor ${x}.`);const E=e.bufferViews?.[y.bufferView];if(!E)throw new Error(`Decoded glTF references missing bufferView ${y.bufferView}.`);const M=t[E.buffer];if(!M)throw new Error(`Decoded glTF references missing buffer ${E.buffer}.`);const I=Kt[y.componentType],A=qt[y.type];if(!I||!A)throw new Error(`Unsupported decoded glTF accessor type ${y.componentType}/${y.type}.`);const v=I.BYTES_PER_ELEMENT,B=E.byteOffset??0,P=y.byteOffset??0;let R;const m=A*v;if(E.byteStride&&E.byteStride!==m){if(E.byteStride%v!==0||P%v!==0)throw new Error(`Decoded glTF accessor ${x} has an invalid interleaved alignment.`);const N=Math.floor(P/E.byteStride),_=[y.bufferView,y.componentType,N,y.count].join(":");let L=r.get(_);if(!L){const k=new I(M,B+N*E.byteStride,y.count*E.byteStride/v);L=new o.InterleavedBuffer(k,E.byteStride/v),r.set(_,L)}R=new o.InterleavedBufferAttribute(L,A,P%E.byteStride/v,y.normalized??!1)}else{const N=new I(M,B+P,y.count*A);R=new o.BufferAttribute(N,A,y.normalized??!1)}return R.name=y.name??"",n.set(x,R),R},d=(x,b,y)=>{const E=`${x}:${b}:${y}`,M=l.get(E);if(M)return M;const I=e.textures?.[x];if(!I||I.source===void 0)throw new Error(`Decoded glTF references missing texture ${x}.`);const A=s[I.source];if(!A)throw new Error(`Decoded glTF references missing image ${I.source}.`);const v=I.sampler===void 0?void 0:e.samplers?.[I.sampler],B=new o.Texture(A);return B.name=I.name??e.images?.[I.source]?.name??"",B.flipY=!1,B.colorSpace=b,B.channel=y,B.magFilter=v?.magFilter===9728?o.NearestFilter:o.LinearFilter,B.minFilter=(()=>{switch(v?.minFilter){case 9728:return o.NearestFilter;case 9729:return o.LinearFilter;case 9984:return o.NearestMipmapNearestFilter;case 9985:return o.LinearMipmapNearestFilter;case 9986:return o.NearestMipmapLinearFilter;default:return o.LinearMipmapLinearFilter}})(),B.wrapS=(()=>{switch(v?.wrapS){case 33071:return o.ClampToEdgeWrapping;case 33648:return o.MirroredRepeatWrapping;default:return o.RepeatWrapping}})(),B.wrapT=(()=>{switch(v?.wrapT){case 33071:return o.ClampToEdgeWrapping;case 33648:return o.MirroredRepeatWrapping;default:return o.RepeatWrapping}})(),B.needsUpdate=!0,l.set(E,B),B},u=(x,b,y,E)=>{y&&(x[b]=d(y.index,E,y.texCoord??0))},p=(x,b,y,E)=>{const M=[x??"default",b?"derivative-tangents":"",y?"vertex-colors":"",E?"flat-shading":""].join(":"),I=c.get(M);if(I)return I;const A=x===void 0?void 0:e.materials?.[x];if(x!==void 0&&!A)throw new Error(`Decoded glTF references missing material ${x}.`);const v=A??{},B=v.pbrMetallicRoughness??{},P=B.baseColorFactor??[1,1,1,1],R=v.alphaMode??"OPAQUE",m=new o.MeshStandardMaterial({color:new o.Color().setRGB(P[0]??1,P[1]??1,P[2]??1,o.LinearSRGBColorSpace),opacity:P[3]??1,metalness:B.metallicFactor??1,roughness:B.roughnessFactor??1,transparent:R==="BLEND",depthWrite:R!=="BLEND",alphaTest:R==="MASK"?v.alphaCutoff??.5:0});return v.doubleSided&&(m.side=o.DoubleSide),m.vertexColors=y,m.flatShading=E,m.name=v.name??"",u(m,"map",B.baseColorTexture,o.SRGBColorSpace),u(m,"metalnessMap",B.metallicRoughnessTexture,o.NoColorSpace),u(m,"roughnessMap",B.metallicRoughnessTexture,o.NoColorSpace),u(m,"normalMap",v.normalTexture,o.NoColorSpace),u(m,"aoMap",v.occlusionTexture,o.NoColorSpace),u(m,"emissiveMap",v.emissiveTexture,o.SRGBColorSpace),v.normalTexture?.scale!==void 0&&(m.normalScale=new o.Vector2(v.normalTexture.scale,v.normalTexture.scale)),b&&(m.normalScale.y*=-1),v.occlusionTexture?.strength!==void 0&&(m.aoMapIntensity=v.occlusionTexture.strength),v.emissiveFactor&&m.emissive.setRGB(v.emissiveFactor[0]??0,v.emissiveFactor[1]??0,v.emissiveFactor[2]??0,o.LinearSRGBColorSpace),Q(m,v.extras),c.set(M,m),m},f=(x,b)=>{const y=`${x}:${b}`,E=a.get(y);if(E)return E;const M=e.meshes?.[x]?.primitives[b];if(!M)throw new Error(`Decoded glTF references missing primitive ${y}.`);const I=new o.BufferGeometry;for(const[A,v]of Object.entries(M.attributes)){const B=Xt[A]??A.toLowerCase();I.setAttribute(B,h(v))}if(M.indices!==void 0){const A=h(M.indices);if(A instanceof o.InterleavedBufferAttribute)throw new Error(`Decoded glTF index accessor ${M.indices} cannot be interleaved.`);I.setIndex(A)}return a.set(y,I),I},S=x=>{const b=e.meshes?.[x];if(!b)throw new Error(`Decoded glTF references missing mesh ${x}.`);const y=b.primitives.map((M,I)=>{const A=new o.Mesh(f(x,I),p(M.material,M.attributes.TANGENT===void 0,M.attributes.COLOR_0!==void 0,M.attributes.NORMAL===void 0));return A.name=b.name??"",A});if(y.length===1)return Q(y[0],b.extras),y[0];const E=new o.Group;return E.name=b.name??"",E.add(...y),Q(E,b.extras),E},C=x=>{const b=e.nodes?.[x];if(!b)throw new Error(`Decoded glTF references missing node ${x}.`);const y=b.mesh===void 0?new o.Group:S(b.mesh);y.name=b.name??y.name,b.matrix?new o.Matrix4().fromArray(b.matrix).decompose(y.position,y.quaternion,y.scale):(b.translation&&y.position.fromArray(b.translation),b.rotation&&y.quaternion.fromArray(b.rotation),b.scale&&y.scale.fromArray(b.scale)),Q(y,b.extras);for(const E of b.children??[])y.add(C(E));return y},D=e.scene??0,O=e.scenes?.[D];if(!O)throw new Error(`Decoded glTF references missing scene ${D}.`);const w=new o.Group;w.name=O.name??"",Q(w,O.extras);for(const x of O.nodes??[])w.add(C(x));return w.animations=[],w}const Qt=256;function Jt(i){return i instanceof Error?{message:i.message,name:i.name,stack:i.stack}:{message:String(i)}}function Zt(i){const e=new Error(i.message);return e.name=i.name??"Error",e.stack=i.stack,e}class te extends Error{name="ModelDecodeWorkerUnavailableError";constructor(e,t){super(e,t)}}function st(i,e,t=Qt){if(i.images.length!==i.imageKeys.length)throw new Error("Decoded model image identities do not match its image payload.");const s=[];for(let n=0;n<i.images.length;n++){const r=i.imageKeys[n],a=i.images[n],c=e.get(r);if(c)e.delete(r),e.set(r,c),c!==a&&a.close(),i.images[n]=c;else for(e.set(r,a),s.push(r);e.size>Math.max(0,t);){const l=e.keys().next().value;if(l===void 0)break;e.delete(l)}}return s}class nt{worker;#s;#a=1;#t=new Map;#e=new Map;#r=!1;constructor(e,t={}){this.worker=e,this.#s=t.onFatal,e.addEventListener("message",this.#o),e.addEventListener("error",this.#l),e.addEventListener("messageerror",this.#d)}get disposed(){return this.#r}supports(e){const t=e.split(/[?#]/,1)[0].split(".").pop()?.toLowerCase();return t==="sbmx"||t==="gltf"||t==="glb"}async loadAsync(e,t={}){if(this.#r)throw new te("Model decode Worker is unavailable.");const s=this.#a++,{signal:n,loadingManager:r,...a}=t;if(n?.aborted)throw n.reason??new DOMException("Aborted","AbortError");const c=await new Promise((h,d)=>{const u={resolve:h,reject:d,manager:r,rootUrl:e,resources:new Map};if(r?.itemStart(e),n){const p=()=>{this.#t.delete(s),this.#h(u,n.reason??new DOMException("Aborted","AbortError")),d(n.reason??new DOMException("Aborted","AbortError"));try{this.#n({type:"cancel",id:s})}catch{}};u.cleanup=()=>n.removeEventListener("abort",p),n.addEventListener("abort",p,{once:!0})}this.#t.set(s,u);try{this.#n({type:"decode",id:s,url:e,options:a})}catch(p){this.#t.delete(s),u.cleanup?.();const f=p instanceof Error?p:new Error(String(p));this.#h(u,f),d(f)}}),l=[];try{return l.push(...st(c,this.#e)),Yt(c)}catch(h){const d=new Set;for(const u of l){const p=c.imageKeys.indexOf(u),f=this.#e.get(u)??c.images[p];this.#e.get(u)===f&&this.#e.delete(u),f&&!d.has(f)&&(f.close(),d.add(f))}throw h}finally{try{this.#n({type:"ack",id:s})}catch{}}}dispose(){if(!this.#r){this.#r=!0;try{this.#n({type:"dispose"})}catch{}this.#i(),this.worker.terminate(),this.#p(new te("Model decode Worker was disposed.")),this.#e.clear()}}#n(e){this.worker.postMessage(e)}#o=e=>{const t=e.data;if(t.type==="disposed")return;if(t.type==="resolve-resource"){this.#c(t.id,t.resourceId,t.url);return}if(t.type==="resource-complete"){const n=this.#t.get(t.id),r=n?.resources.get(t.resourceId);n&&r!==void 0&&(n.resources.delete(t.resourceId),t.ok||n.manager?.itemError(r),n.manager?.itemEnd(r));return}const s=this.#t.get(t.id);if(!s){if(t.type==="decoded"){t.packet.images.forEach(n=>n.close());try{this.#n({type:"ack",id:t.id})}catch{}}return}if(this.#t.delete(t.id),s.cleanup?.(),t.type==="decoded")this.#h(s),s.resolve(t.packet);else if(t.type==="unsupported")this.#h(s,void 0,!1),s.reject(new ee.UnsupportedModelDecodeError(t.reason));else{const n=Zt(t.error);this.#h(s,n),s.reject(n)}};#c(e,t,s){const n=this.#t.get(e);if(!n){try{this.#n({type:"resource-resolved",id:e,resourceId:t,error:{message:"The model decode request is no longer active.",name:"AbortError"}})}catch{}return}let r;try{r=n.manager?.resolveURL(s)??s,n.manager?.itemStart(r),n.manager&&n.resources.set(t,r),this.#n({type:"resource-resolved",id:e,resourceId:t,url:r})}catch(a){r!==void 0&&n.resources.delete(t)&&(n.manager?.itemError(r),n.manager?.itemEnd(r));try{this.#n({type:"resource-resolved",id:e,resourceId:t,error:Jt(a)})}catch(c){this.#u(c instanceof Error?c:new Error(String(c)))}}}#l=e=>{this.#u(e.error instanceof Error?e.error:new Error(e.message))};#d=()=>{this.#u(new Error("Failed to deserialize a model decode Worker response."))};#u(e){if(this.#r)return;this.#r=!0,this.#i(),this.worker.terminate();const t=new te(`Model decode Worker failed: ${e.message}`,{cause:e});this.#p(t),this.#e.clear(),this.#s?.(t)}#i(){this.worker.removeEventListener("message",this.#o),this.worker.removeEventListener("error",this.#l),this.worker.removeEventListener("messageerror",this.#d)}#h(e,t,s=t!==void 0){for(const n of e.resources.values())t&&e.manager?.itemError(n),e.manager?.itemEnd(n);e.resources.clear(),s&&e.manager?.itemError(e.rootUrl),e.manager?.itemEnd(e.rootUrl)}#p(e){for(const t of this.#t.values())t.cleanup?.(),this.#h(t,e),t.reject(e);this.#t.clear()}}const es=["map","alphaMap","aoMap","bumpMap","clearcoatMap","clearcoatNormalMap","clearcoatRoughnessMap","displacementMap","emissiveMap","envMap","gradientMap","iridescenceMap","iridescenceThicknessMap","lightMap","matcap","metalnessMap","normalMap","roughnessMap","sheenColorMap","sheenRoughnessMap","specularColorMap","specularIntensityMap","specularMap","thicknessMap","transmissionMap"];function J(i){return i.traverse(e=>{if(!(e instanceof o.Mesh))return;const t=Array.isArray(e.material)?e.material:[e.material];for(const s of t){if(!s)continue;let n=!1;for(const r of es){const a=s[r];a?.isTexture&&a.image==null&&(a.dispose(),s[r]=null,n=!0)}n&&(s.needsUpdate=!0)}}),i}class z{static CACHE_NAME="u-space-model-loader-cache";static fileLoader=new o.FileLoader().setResponseType("arraybuffer");static dracoLoader=new vt.DRACOLoader().setDecoderPath(`https://cdn.jsdelivr.net/npm/three@0.${o.REVISION}.0/examples/jsm/libs/draco/`);static ktx2Loader=new It.KTX2Loader().setTranscoderPath(`https://cdn.jsdelivr.net/npm/three@0.${o.REVISION}.0/examples/jsm/libs/basis/`);static gltfLoader=new pe.GLTFLoader().setDRACOLoader(z.dracoLoader).setKTX2Loader(z.ktx2Loader).setMeshoptDecoder(de.MeshoptDecoder);static sbmxLoader=new fe().setDRACOLoader(z.dracoLoader).setKTX2Loader(z.ktx2Loader).setMeshoptDecoder(de.MeshoptDecoder);static sbmLoader=new me;static fbxLoader=new Ee.FBXLoader;static objLoader=new St.OBJLoader;static stlLoader=new Et.STLLoader;static decodeWorkerClient=null;static setDecodeWorker(e){const t=this.decodeWorkerClient;if(this.decodeWorkerClient=null,t?.dispose(),!e)return()=>{};let s;return s=new nt(e,{onFatal:()=>{this.decodeWorkerClient===s&&(this.decodeWorkerClient=null)}}),this.decodeWorkerClient=s,()=>{this.decodeWorkerClient===s&&(this.decodeWorkerClient=null,s.dispose())}}static get decodeWorkerEnabled(){return this.decodeWorkerClient!==null&&!this.decodeWorkerClient.disposed}static setLoadingManager(e){this.fileLoader.manager=e,this.dracoLoader.manager=e,this.ktx2Loader.manager=e,this.gltfLoader.manager=e,this.sbmxLoader.manager=e,this.sbmLoader.manager=e,this.fbxLoader.manager=e,this.objLoader.manager=e,this.stlLoader.manager=e}static async setRenderer(e){await e.init(),this.ktx2Loader.detectSupport(e)}static setDracoPath(e){this.dracoLoader.setDecoderPath(e)}static setKTX2Path(e){this.ktx2Loader.setTranscoderPath(e)}static async loadAsync(e,t={persistent:!0}){const s=e.split(/[?#]/,1)[0].split(".").pop()?.toLowerCase(),n=t.persistent??!0,r=t.signal;this.throwIfAborted(r);const a=this.decodeWorkerClient;if(a?.supports(e)){const d=this.fileLoader.manager.resolveURL(e),u=typeof location>"u"?e:new URL(e,location.href).href,p=typeof location>"u"?d:new URL(d,location.href).href;try{return await a.loadAsync(p,{persistent:n,headers:this.fileLoader.requestHeader,credentials:this.fileLoader.withCredentials?"include":"same-origin",resourceBaseUrl:u,signal:r,loadingManager:this.fileLoader.manager})}catch(f){if(this.throwIfAborted(r),!(f instanceof ee.UnsupportedModelDecodeError)&&!(f instanceof te))throw f;console.info(`[ModelLoaderManager] Decode Worker fallback for ${e}: ${f.message}`)}}const c=await this.loadSourceBuffer(e,n,r);this.throwIfAborted(r);const l=o.LoaderUtils.extractUrlBase(e),h=this.createParseLoadingManager(r);try{switch(s){case"gltf":case"glb":{const u=await this.configureGltfLoader(new pe.GLTFLoader(h.manager)).parseAsync(c,l);return this.throwIfAborted(r),u.scene.animations=u.animations,J(u.scene)}case"sbmx":{const u=await this.configureGltfLoader(new fe(h.manager)).parseAsync(c,l);return this.throwIfAborted(r),u.scene.animations=u.animations,J(u.scene)}case"sbm":{const u=await new me(h.manager).setCrossOrigin(this.sbmLoader.crossOrigin).setRequestHeader(this.sbmLoader.requestHeader).setWithCredentials(this.sbmLoader.withCredentials).parseAsync(c,l);return this.throwIfAborted(r),J(u)}case"fbx":{const u=new Ee.FBXLoader(h.manager).setCrossOrigin(this.fbxLoader.crossOrigin).setRequestHeader(this.fbxLoader.requestHeader).setWithCredentials(this.fbxLoader.withCredentials).parse(c,l);return this.throwIfAborted(r),J(u)}case"obj":{const d=new TextDecoder().decode(c),u=this.objLoader.parse(d);return this.throwIfAborted(r),J(u)}case"stl":{const d=this.stlLoader.parse(c);return this.throwIfAborted(r),new o.Mesh(d,new o.MeshStandardNodeMaterial)}default:throw new Error(`Unsupported model format: ${s}`)}}finally{h.cleanup()}}static configureGltfLoader(e){return e.setDRACOLoader(this.dracoLoader).setKTX2Loader(this.ktx2Loader).setMeshoptDecoder(de.MeshoptDecoder).setCrossOrigin(this.gltfLoader.crossOrigin).setRequestHeader(this.gltfLoader.requestHeader).setWithCredentials(this.gltfLoader.withCredentials),e}static createParseLoadingManager(e){this.throwIfAborted(e);const t=this.fileLoader.manager,s=new o.LoadingManager;s.setURLModifier(r=>t.resolveURL(r)),s.itemStart=r=>t.itemStart(r),s.itemEnd=r=>t.itemEnd(r),s.itemError=r=>t.itemError(r);const n=()=>s.abort();return e?.addEventListener("abort",n,{once:!0}),{manager:s,cleanup:()=>e?.removeEventListener("abort",n)}}static async loadSourceBuffer(e,t,s){this.throwIfAborted(s);const n=this.fileLoader.manager,r=n.resolveURL(e);n.itemStart(r);try{let a;if(t&&typeof caches<"u")try{a=await caches.open(this.CACHE_NAME);const u=await a.match(r);if(this.throwIfAborted(s),u){const p=await u.arrayBuffer();return this.throwIfAborted(s),p}}catch(u){this.throwIfAborted(s),console.warn(`[ModelLoaderManager] Failed to read Cache Storage for ${r}:`,u)}const c=n.abortController.signal,l=s&&typeof AbortSignal.any=="function"?AbortSignal.any([s,c]):s??c,h=await fetch(r,{headers:this.fileLoader.requestHeader,credentials:this.fileLoader.withCredentials?"include":"same-origin",signal:l});if(!h.ok)throw new Error(`Failed to load model ${r}: ${h.status} ${h.statusText}`);const d=await h.arrayBuffer();if(this.throwIfAborted(s),a)try{await a.put(r,new Response(d.slice(0)))}catch(u){this.throwIfAborted(s),console.warn(`[ModelLoaderManager] Failed to write Cache Storage for ${r}:`,u)}return d}catch(a){throw n.itemError(r),a}finally{n.itemEnd(r)}}static throwIfAborted(e){if(e?.aborted)throw e.reason??new DOMException("Aborted","AbortError")}}class ts{static textureLoader=new o.TextureLoader;static hdrLoader=new Ct.HDRLoader;static cubeTextureLoader=new o.CubeTextureLoader;static setLoadingManager(e){this.textureLoader.manager=e,this.hdrLoader.manager=e,this.cubeTextureLoader.manager=e}static async loadAsyncTexture(e){return await this.textureLoader.loadAsync(e)}static async loadAsyncHDR(e){const t=await this.hdrLoader.loadAsync(e);return t.mapping=o.EquirectangularReflectionMapping,t}static async loadAsyncCubeTexture(e,t){return this.cubeTextureLoader.setPath(e),await this.cubeTextureLoader.loadAsync(t)}}class F extends o.Mesh{isBaseMesh=!0;type="BaseMesh";castShadow=!0;receiveShadow=!0;ignoreInvisibleWhenRaycast=!0;constructor(...e){super(...e)}raycast(e,t){return this.visible===!1&&this.ignoreInvisibleWhenRaycast===!0?!1:super.raycast(e,t)}}class q extends o.Group{isBaseGroup=!0;type="BaseGroup";ignoreInvisibleWhenRaycast=!0;constructor(...e){super(...e)}raycast(e,t){return this.visible===!1&&this.ignoreInvisibleWhenRaycast===!0?!1:super.raycast(e,t)}}class rt extends o.Sprite{isBaseSprite=!0;type="BaseSprite";ignoreInvisibleWhenRaycast=!0;constructor(...e){super(...e)}raycast(e,t){return this.visible===!1&&this.ignoreInvisibleWhenRaycast===!0?!1:super.raycast(e,t)}}class G extends q{isModel=!0;type="Model";static memoryCache=new Map;mixer=null;animations=[];actions=new Map;constructor(){super()}async loadAsync(e){const{url:t,cache:s=!0,persistent:n=!0,signal:r}=e;try{let a;if(s&&!r)if(G.memoryCache.has(t))a=G.memoryCache.get(t);else{const d=z.loadAsync(t,{persistent:n,signal:r}).catch(u=>{throw G.memoryCache.get(t)===d&&G.memoryCache.delete(t),u});G.memoryCache.set(t,d),a=d}else a=z.loadAsync(t,{persistent:n,signal:r});const c=await a,l=Me.clone(c);return this.add(l),l.animations&&l.animations.length>0&&(this.animations=l.animations,this.mixer=new o.AnimationMixer(l)),l}catch(a){return console.error(`[Model] Failed to load model from ${t}:`,a),null}}playAnimation(e,t={}){if(!this.mixer||this.animations.length===0)return null;const{loop:s=!0,repetitions:n=1/0,timeScale:r=1,clampWhenFinished:a=!1}=t;let c;if(e===void 0?c=this.animations[0]:typeof e=="number"?c=this.animations[e]:c=this.animations.find(h=>h.name===e),!c)return console.warn(`[Model] Animation not found: ${e}`),null;let l=this.actions.get(c.name);return l||(l=this.mixer.clipAction(c),this.actions.set(c.name,l)),l.setLoop(s?o.LoopRepeat:o.LoopOnce,n),l.clampWhenFinished=a,l.timeScale=r,l.reset().play(),l}playAllAnimations(e={}){return this.animations.map((t,s)=>this.playAnimation(s,e)).filter(t=>t!==null)}stopAnimation(e){if(!this.mixer)return;if(e===void 0){this.mixer.stopAllAction();return}let t;typeof e=="number"?t=this.animations[e]?.name:t=e,t&&this.actions.get(t)?.stop()}updateAnimation(e){this.mixer?.update(e)}getBoundingBox(){return new o.Box3().setFromObject(this)}getCenter(){const e=new o.Vector3;return this.getBoundingBox().getCenter(e),e}setMaterial(e){this.traverse(t=>{t instanceof o.Mesh&&(t.material=e)})}static clearMemoryCache(){this.memoryCache.clear()}static async clearPersistentCache(){typeof caches<"u"&&await caches.delete("u-space-model-loader-cache")}}class it extends F{isSphereMesh=!0;type="SphereMesh";constructor({geometryParameters:e,materialParameters:t}={}){super(),this.geometry=new o.SphereGeometry(e?.radius,e?.widthSegments,e?.heightSegments,e?.phiStart,e?.phiLength,e?.thetaStart,e?.thetaLength),this.material=new o.MeshStandardNodeMaterial(t)}}class ge extends F{isTubeMesh=!0;type="TubeMesh";constructor({geometryParameters:e,materialParameters:t}={}){super(),this.geometry=new o.TubeGeometry(e?.path,e?.tubularSegments,e?.radius,e?.radialSegments,e?.closed),this.material=new o.MeshStandardNodeMaterial(t)}}class ss extends q{isTopology=!0;type="Topology";parameters={nodeColor:255,nodeRadius:.5,edgeColor:65280,edgeRadius:.1,pathColor:16711935,pathRadius:.2};nodes=new Map;adjacencyMap=new Map;graphGroup=null;pathMeshes=[];constructor(e){super(),e&&Object.assign(this.parameters,e)}addNode(e,t){this.nodes.has(e)&&console.warn(`[Topology] Node ${e} already exists. Overwriting.`),this.nodes.set(e,t),this.adjacencyMap.has(e)||this.adjacencyMap.set(e,new Map)}removeNode(e){if(!this.nodes.has(e)){console.warn(`[Topology] Node ${e} does not exist.`);return}this.nodes.delete(e),this.adjacencyMap.delete(e)}addEdge(e,t,s,n=!0){const r=this.nodes.get(e),a=this.nodes.get(t);if(!r||!a){console.error(`[Topology] Cannot add edge. One or both nodes not found: ${e}, ${t}`);return}const c=s??r.distanceTo(a);this.getNeighbors(e)?.set(t,c),n&&this.getNeighbors(t)?.set(e,c)}removeEdge(e,t,s=!0){this.getNeighbors(e)?.delete(t),s&&this.getNeighbors(t)?.delete(e)}getShortestPath(e,t){if(!this.nodes.has(e)||!this.nodes.has(t))return console.warn("[Topology] Start or End node not found."),[];const s=new Map,n=new Map,r=new Set;for(const[l]of this.nodes)s.set(l,1/0),n.set(l,null),r.add(l);for(s.set(e,0);r.size>0;){let l=null,h=1/0;for(const u of r){const p=s.get(u);p<h&&(h=p,l=u)}if(l===null||l===t||h===1/0)break;r.delete(l);const d=this.adjacencyMap?.get(l);if(d)for(const[u,p]of d){if(!r.has(u))continue;const f=s.get(l)+p;f<s.get(u)&&(s.set(u,f),n.set(u,l))}}const a=[];let c=t;if(n.get(t)===null&&e!==t)return[];for(;c!==null;){const l=this.nodes.get(c);l&&a.unshift(l),c=n.get(c)||null}return a}renderGraph(){this.clearGraph(),this.graphGroup=new o.Group;const e=new it({geometryParameters:{radius:this.parameters.nodeRadius,widthSegments:16,heightSegments:16},materialParameters:{color:this.parameters.nodeColor}});this.nodes.forEach((s,n)=>{const r=e.clone();r.position.copy(s),Object.assign(r.userData,{id:n,type:"node"}),this.graphGroup.add(r)});const t=new Set;this.adjacencyMap.forEach((s,n)=>{s.forEach((r,a)=>{const c=[n,a].sort().join("-");if(t.has(c))return;t.add(c);const l=this.nodes.get(n),h=this.nodes.get(a);if(l&&h){const d=new o.LineCurve3(l,h),u=new ge({geometryParameters:{path:d,tubularSegments:1,radius:this.parameters.edgeRadius,radialSegments:8,closed:!1},materialParameters:{color:this.parameters.edgeColor}});Object.assign(u.userData,{from:n,to:a,weight:r,type:"edge"}),this.graphGroup.add(u)}})}),this.add(this.graphGroup)}clearGraph(){this.graphGroup&&(this.remove(this.graphGroup),this.graphGroup.traverse(e=>{e instanceof o.Mesh&&(e.geometry.dispose(),e.material.dispose())}),this.graphGroup=null)}renderPath(e,t=this.parameters.pathColor){if(e.length<2)return;const s=new o.CatmullRomCurve3(e,!1,"catmullrom",0),n=new ge({geometryParameters:{path:s,tubularSegments:e.length*10,radius:this.parameters.pathRadius,closed:!1},materialParameters:{color:t}});return this.add(n),this.pathMeshes.push(n),n}clearPaths(){this.pathMeshes.forEach(e=>{this.remove(e),e.geometry.dispose(),e.material.dispose()}),this.pathMeshes=[]}exportData(){const e={};this.nodes.forEach((n,r)=>{e[r]={x:n.x,y:n.y,z:n.z}});const t=[],s=new Set;return this.adjacencyMap.forEach((n,r)=>{n.forEach((a,c)=>{const l=[r,c].sort().join("-");s.has(l)||(s.add(l),t.push({from:r,to:c,weight:a}))})}),{nodes:e,edges:t}}importData(e){this.clearGraph(),this.clearPaths(),this.nodes.clear(),this.adjacencyMap.clear(),Object.entries(e.nodes).forEach(([t,s])=>{this.addNode(t,new o.Vector3(s.x,s.y,s.z))}),e.edges.forEach(({from:t,to:s,weight:n})=>{this.addEdge(t,s,n)}),this.renderGraph()}dispose(){this.clearGraph(),this.clearPaths()}getNeighbors(e){return this.adjacencyMap.get(e)}}class ns extends rt{isPoi=!0;type="Poi";parameters={img:"",text:"",fontSize:32,fontFamily:"Arial",color:"#ffffff",iconSize:64,padding:10,backgroundColor:"rgba(0, 0, 0, 0)",borderRadius:8,textPosition:"right",scaleFactor:.01};_canvas=document.createElement("canvas");_lastParametersJSON="";constructor(e={}){super(new o.SpriteNodeMaterial),Object.assign(this.parameters,e),this.updateAsync()}async updateAsync(e={}){Object.assign(this.parameters,e);const t=JSON.stringify(this.parameters);if(t===this._lastParametersJSON)return;this._lastParametersJSON=t;const s=this._canvas,n=s.getContext("2d");if(!n)return;n.font=`${this.parameters.fontSize}px ${this.parameters.fontFamily}`;let r=null;this.parameters.img&&(r=await this._loadImage(this.parameters.img));const{text:a,fontSize:c,color:l,iconSize:h,padding:d,backgroundColor:u,borderRadius:p,textPosition:f,scaleFactor:S}=this.parameters,C=n.measureText(a),D=a?C.width:0,O=a?c:0;let w=0,x=0,b=0,y=0,E=0,M=0;const I=!!r,A=!!a;if(I&&A)switch(f){case"top":w=Math.max(h,D),x=h+d+O,E=(w-D)/2,M=O/2,b=(w-h)/2,y=O+d;break;case"bottom":w=Math.max(h,D),x=h+d+O,b=(w-h)/2,y=0,E=(w-D)/2,M=h+d+O/2;break;case"left":w=h+d+D,x=Math.max(h,O),E=0,M=x/2,b=D+d,y=(x-h)/2;break;default:w=h+d+D,x=Math.max(h,O),b=0,y=(x-h)/2,E=h+d,M=x/2;break}else I?(w=h,x=h,b=0,y=0):A&&(w=D,x=O,E=0,M=O/2);const v=w+d*2,B=x+d*2;if(s.width=v,s.height=B,n.font=`${c}px ${this.parameters.fontFamily}`,u&&(n.fillStyle=u,this._drawRoundedRect(n,0,0,v,B,p),n.fill()),I&&n.drawImage(r,b+d,y+d,h,h),A){n.fillStyle=l;const m=n.measureText(a),N=m.actualBoundingBoxAscent+m.actualBoundingBoxDescent,_=m.actualBoundingBoxAscent-N/2;n.textBaseline="alphabetic",n.fillText(a,E+d,M+d+_)}const P=this.material.map,R=new o.CanvasTexture(s);R.colorSpace=o.SRGBColorSpace,this.material.map=R,P?.dispose(),this.scale.set(v*S,B*S,1)}_loadImage(e){return new Promise((t,s)=>{if(typeof e=="string"){const n=new Image;n.crossOrigin="Anonymous",n.onload=()=>t(n),n.onerror=()=>s(new Error(`Failed to load image: ${e}`)),n.src=e}else t(e)})}_drawRoundedRect(e,t,s,n,r,a){e.beginPath(),e.moveTo(t+a,s),e.lineTo(t+n-a,s),e.quadraticCurveTo(t+n,s,t+n,s+a),e.lineTo(t+n,s+r-a),e.quadraticCurveTo(t+n,s+r,t+n-a,s+r),e.lineTo(t+a,s+r),e.quadraticCurveTo(t,s+r,t,s+r-a),e.lineTo(t,s+a),e.quadraticCurveTo(t,s,t+a,s),e.closePath()}dispose(){this.material.map?.dispose(),this.material.dispose()}}class xe extends F{isShapeMesh=!0;type="ShapeMesh";constructor({geometryParameters:e,materialParameters:t}={}){super(),this.geometry=new o.ShapeGeometry(e?.shape,e?.curveSegments),this.material=new o.MeshStandardNodeMaterial(t),this.geometry.rotateX(-Math.PI/2)}static createFromPoints(e,t={}){return new xe({...t,geometryParameters:{...t.geometryParameters,shape:new o.Shape(e.map(s=>new o.Vector2(s.x,-s.z)))}})}}class Se extends F{isExtrudeMesh=!0;type="ExtrudeMesh";constructor({geometryParameters:e,materialParameters:t}={}){super(),this.geometry=new o.ExtrudeGeometry(e?.shape,e?.options),this.material=new o.MeshStandardNodeMaterial(t),this.geometry.rotateX(-Math.PI/2)}static createFromPoints(e,t={}){return e&&e.length===0&&(e=void 0),new Se({...t,geometryParameters:{...t.geometryParameters,shape:new o.Shape(e?.map(s=>new o.Vector2(s.x,-s.z)))}})}}class rs extends F{isPlaneMesh=!0;type="PlaneMesh";constructor({geometryParameters:e,materialParameters:t}={}){super(),this.geometry=new o.PlaneGeometry(e?.width,e?.height,e?.widthSegments,e?.heightSegments),this.material=new o.MeshStandardNodeMaterial(t)}}class is extends F{isCircleMesh=!0;type="CircleMesh";constructor({geometryParameters:e,materialParameters:t}={}){super(new o.CircleGeometry(e?.radius,e?.segments,e?.thetaStart,e?.thetaLength),new o.MeshStandardNodeMaterial(t)),this.geometry.rotateX(-Math.PI/2)}}class W{static traverseMeshes(e,t){e.traverse(s=>{s instanceof o.Mesh&&t(s)})}}const as=3,os=1,cs=0,ls=2,hs=.001,Ie=new o.Vector3,$=new o.Vector3,ds=new o.Quaternion;function Ce(i){return i.isInstanceObject===!0}function Be(i){let e=!1;return i.traverse(t=>{if(e)return;const s=t;e=s.isMesh===!0||s.isSprite===!0}),e}function us(i){let e=i;for(;e;){if(!e.visible)return!1;e=e.parent}return!0}function Oe(i){return i===void 0||!Number.isFinite(i)||i<=0?ls:i}class ps{static flow(e={}){const{baseColor:t=16777215,flowColor:s=65280,speed:n=1,scale:r=3,intensity:a=4}=e,c=g.color(new o.Color(t)),l=g.color(new o.Color(s)),h=g.uv().x.mul(r).sub(g.time.mul(n)),d=g.pow(g.sin(h).add(1).mul(.5),a);return g.mix(c,l,d)}static breathe(e={}){const{baseColor:t=16777215,breathColor:s=65280,speed:n=1,intensity:r=2}=e,a=g.color(new o.Color(t)),c=g.color(new o.Color(s)),l=g.sin(g.time.mul(n)).add(1).mul(.5),h=g.pow(l,r);return g.mix(a,c,h)}static fluid(e={}){const{baseColor:t=16777215,flowColor:s=255,speed:n=1,scale:r=1,intensity:a=1,distortion:c=.5}=e,l=g.color(new o.Color(t)),h=g.color(new o.Color(s)),d=g.uv().mul(r),u=g.time.mul(n),p=g.mx_noise_float(d.add(u),1,0),f=d.add(p.mul(c)),S=g.mx_noise_float(f,1,0).add(1).mul(.5),C=g.pow(S,a);return g.mix(l,h,C)}static outline(e={}){let t=[...e.selectedObjects??[]];const s=[],n=new Map,r=new o.Box3;let a=null,c=null,l=null,h=null,d=null,u=e.instanceBoundsProxy??!0,p=e.instanceBoundsPadding??0,f=e.instanceBoundsMinSize??hs,S=Oe(e.downSampleRatio);const C=g.uniform(e.edgeStrength??as),D=g.uniform(e.edgeThickness??os),O=g.uniform(e.edgeGlow??cs),w=g.uniform(new o.Color(e.visibleEdgeColor??16777215)),x=g.uniform(new o.Color(e.hiddenEdgeColor??5125686)),b=()=>(h??=new o.BoxGeometry(1,1,1),h),y=()=>(d||(d=new o.MeshBasicNodeMaterial({color:16777215}),d.colorWrite=!1,d.depthWrite=!1,d.name="u-space.outline.instanceBoundsProxy"),d),E=m=>{const{source:N,mesh:_}=m,L=N.getInstanceBoundingBox?.(r,!0);if(!L||L.isEmpty()||!us(N)){_.visible=!1;return}L.getCenter(Ie),L.getSize($);const k=Math.max(0,p),Y=Math.max(0,f);$.set(Math.max($.x+k*2,Y),Math.max($.y+k*2,Y),Math.max($.z+k*2,Y)),_.visible=!0,_.layers.mask=N.layers.mask,_.matrix.compose(Ie,ds,$),_.matrixWorldNeedsUpdate=!0},M=m=>{m.unsubscribe?.(),m.mesh.removeFromParent()},I=(m,N)=>{let _=n.get(m);if(!_){const L=new o.Mesh(b(),y());L.name=`u-space.outline.instanceBoundsProxy:${m.uuid}`,L.matrixAutoUpdate=!1,L.castShadow=!1,L.receiveShadow=!1,L.frustumCulled=!1,L.raycast=()=>{},L.userData.instanceObject=m,_={source:m,mesh:L,unsubscribe:m.onInstanceRenderDirty?.(()=>E(_))??null},n.set(m,_)}return _.mesh.parent!==N&&(_.mesh.removeFromParent(),N.add(_.mesh)),E(_),_.mesh.visible?_.mesh:null},A=(m,N)=>{const _=m.getInstanceRenderObject?.();return _&&Be(_)?_:Be(m)?m:u&&m.getInstanceBoundingBox?I(m,N):null},v=m=>{const N=new Set,_=new Set;for(const L of t){const k=Ce(L)?A(L,m):L;k&&(N.add(k),Ce(L)&&n.get(L)?.mesh===k&&_.add(L))}n.forEach((L,k)=>{_.has(k)||(M(L),n.delete(k))}),s.length=0,N.forEach(L=>s.push(L))},B=()=>{a?.dispose(),a=null},P=(m,N)=>{if(a&&c===m&&l===N)return a.downSampleRatio=S,a;B(),c=m,l=N,a=Bt.outline(m,N,{selectedObjects:s,edgeThickness:D,edgeGlow:O,downSampleRatio:S});const _=a.updateBefore.bind(a);return a.updateBefore=L=>(v(m),_(L)),a},R=((m,N)=>{const _=m.scene,L=m.camera;v(_);const k=P(_,L),Y=k.visibleEdge.mul(w).add(k.hiddenEdge.mul(x)).mul(C);return g.add(N,g.vec4(Y,0))});return Object.defineProperties(R,{outlineNode:{get:()=>a},selectedObjects:{get:()=>t}}),R.setSelectedObjects=m=>(t=[...m],c&&v(c),R),R.update=m=>(m.edgeStrength!==void 0&&(C.value=m.edgeStrength),m.edgeThickness!==void 0&&(D.value=m.edgeThickness),m.edgeGlow!==void 0&&(O.value=m.edgeGlow),m.visibleEdgeColor!==void 0&&w.value.set(m.visibleEdgeColor),m.hiddenEdgeColor!==void 0&&x.value.set(m.hiddenEdgeColor),m.instanceBoundsProxy!==void 0&&(u=m.instanceBoundsProxy),m.instanceBoundsPadding!==void 0&&(p=m.instanceBoundsPadding),m.instanceBoundsMinSize!==void 0&&(f=m.instanceBoundsMinSize),m.downSampleRatio!==void 0&&(S=Oe(m.downSampleRatio),a&&(a.downSampleRatio=S)),c&&v(c),R),R.dispose=()=>{B(),n.forEach(M),n.clear(),h?.dispose(),d?.dispose(),h=null,d=null,t=[],s.length=0,c=null,l=null},R}}function fs(i){}const X="uSpaceHighlight",ne=`${X}/enabled`,at=`${X}/opacity`,ot=`${X}/color`,ct=`${X}/overwrite`,lt=`${X}/multiplyOpacity`,oe=`${X}/instancedOriginalOpacity`,he="uSpaceBreathe",ce=`${he}/enabled`,ht=`${he}/color`,dt=`${he}/speed`,ut=`${he}/intensity`,le=new WeakMap,ms=g.Fn(()=>{const i=g.userData(ne,"uint"),e=g.userData(ot,"uint"),t=g.userData(ct,"uint"),s=Le(e),n=g.materialColor.mul(s),r=g.select(t.greaterThan(0),s,n),a=g.select(i.greaterThan(0),r,g.materialColor),c=g.userData(ce,"uint"),l=g.userData(ht,"uint"),h=g.userData(dt,"float"),d=g.userData(ut,"float"),u=Le(l),p=g.sin(g.time.mul(h)).add(1).mul(.5),f=g.pow(p,d),S=g.mix(a,u,f);return g.select(c.greaterThan(0),S,a)})(),gs=g.Fn(()=>{const i=g.userData(ne,"uint"),e=g.userData(at,"float"),t=g.userData(lt,"uint"),s=g.select(t.greaterThan(0),g.materialOpacity.mul(e),e);return g.select(i.greaterThan(0),s,g.materialOpacity)})();function se(i){return Array.isArray(i.material)?i.material:[i.material]}function Ae(i){se(i).forEach(t=>{if(!t)return;let s=le.get(t);s||(s={colorNode:t.colorNode,opacityNode:t.opacityNode,transparent:t.transparent,depthWrite:t.depthWrite,activeMeshes:new Set},le.set(t,s)),s.activeMeshes.add(i),t.transparent=!0,t.colorNode=ms,t.opacityNode=gs,t.needsUpdate=!0})}function _e(i){const e=i.userData[ne],t=i.userData[ce];if(e||t)return;se(i).forEach(n=>{if(!n)return;const r=le.get(n);r&&(r.activeMeshes.delete(i),!(r.activeMeshes.size>0)&&(n.colorNode=r.colorNode,n.opacityNode=r.opacityNode,n.transparent=r.transparent,n.depthWrite=r.depthWrite,n.needsUpdate=!0,le.delete(n)))})}function ys(i,e,t,s){const n=i,r=n.setInstanceHighlight;if(r)return r.call(i,e,t,s),!0;const a=n.setInstanceColor,c=n.setInstanceOpacity,l=n.getInstanceOpacity,h=n.getInstanceColor,d=n.hasInstanceColor;return!a||!c?!1:(i.userData[oe]===void 0&&(i.userData[oe]={hasColor:d?.call(i)??!1,color:h?.call(i,new o.Color).getHex()??16777215,opacity:l?.call(i)??1}),a.call(i,e),c.call(i,t),!0)}function bs(i){const e=i,t=e.clearInstanceHighlight;if(t)return t.call(i),!0;const s=e.resetInstanceColor,n=e.setInstanceColor,r=e.setInstanceOpacity;if(!s||!r)return!1;const a=i.userData[oe];return a&&(a.hasColor&&n?n.call(i,a.color):s.call(i),r.call(i,a.opacity),Reflect.deleteProperty(i.userData,oe)),!0}class H{static highlightColor(e,t={}){const s=Array.isArray(e)?e:[e],{opacity:n=.5,color:r=16711680,overwrite:a=!1,depthWrite:c,multiplyOpacity:l=!1}=t,h=new o.Color(r).getHex();for(const d of s)ys(d,r,n,a)||W.traverseMeshes(d,u=>{u.userData[ne]=1,u.userData[at]=n,u.userData[ot]=h,u.userData[ct]=a?1:0,u.userData[lt]=l?1:0,Ae(u),c!==void 0&&se(u).forEach(f=>{f&&(f.depthWrite=c)})})}static removeHighlightColor(e){const t=Array.isArray(e)?e:[e];for(const s of t)bs(s)||W.traverseMeshes(s,n=>{n.userData[ne]=0,_e(n)})}static breatheColor(e,t={}){const s=Array.isArray(e)?e:[e],n=Object.assign({color:65280,speed:1,intensity:2},t);n.color=new o.Color(n.color).getHex();for(const r of s)W.traverseMeshes(r,a=>{a.userData[ce]=1,a.userData[ht]=n.color,a.userData[dt]=n.speed,a.userData[ut]=n.intensity,Ae(a)})}static removeBreatheColor(e){const t=Array.isArray(e)?e:[e];for(const s of t)W.traverseMeshes(s,n=>{n.userData[ce]=0,_e(n)})}static wireframe(e,t=!0){const s=Array.isArray(e)?e:[e];for(const n of s)W.traverseMeshes(n,r=>{se(r).forEach(a=>{if(!a)return;const c=a;c.wireframe=t,c.needsUpdate=!0})})}static removeWireframe(e){H.wireframe(e,!1)}static fadeIn(e,t={}){const{duration:s=500}=t;return H._fade(e,0,1,s)}static fadeOut(e,t={}){const{duration:s=500}=t;return H._fade(e,1,0,s)}static _fade(e,t,s,n){const r=Array.isArray(e)?e:[e],a=new Map;for(const c of r)W.traverseMeshes(c,l=>{se(l).forEach(h=>{if(!h||a.has(h))return;const d=h.opacity,u=h.transparent,p=s>=1?d:s;a.set(h,{material:h,targetOpacity:p,originalOpacity:d,originalTransparent:u}),h.transparent=!0,h.opacity=t,h.needsUpdate=!0})});return a.size===0?Promise.resolve():new Promise(c=>{const l=performance.now();let h=0;const d=()=>{const u=performance.now()-l,p=Math.min(u/n,1);if(!r[0].parent){cancelAnimationFrame(h),c();return}for(const{material:S,targetOpacity:C}of a.values())S.opacity=t+(C-t)*p,S.needsUpdate=!0;if(p<1)h=requestAnimationFrame(d);else{if(s>=1)for(const{material:S,originalOpacity:C,originalTransparent:D}of a.values())S.opacity=C,S.transparent=D,S.needsUpdate=!0;c()}};h=requestAnimationFrame(d)})}}const Le=i=>{const e=i.shiftRight(16).bitAnd(255).toFloat().div(255),t=i.shiftRight(8).bitAnd(255).toFloat().div(255),s=i.bitAnd(255).toFloat().div(255);return g.vec3(e,t,s)};class pt extends T.Tween{viewer;constructor(e,t){super(t),this.viewer=e}_update=({time:e})=>{const t=this.update(e);this.viewer.invalidate(),t||this.viewer.removeEventListener("afterControlsUpdate",this._update)};easingByMode(e){const t=Ms[e];return super.easing(t)}start(e,t){return this.viewer.addEventListener("afterControlsUpdate",this._update),super.start(e,t)}stop(){return this.viewer.removeEventListener("afterControlsUpdate",this._update),super.stop()}}function ws(i,e,t,s={},n,r){return new Promise((a,c)=>{const{duration:l=1e3,delay:h=0,repeat:d=!1,mode:u="Linear.None",yoyo:p=!1}=s,f=new pt(i,e).to(t,l).easingByMode(u).delay(h).onUpdate(S=>{n?.(S,f)}).onComplete(()=>{a()}).onStop(()=>{c("animation stop")}).onStart(()=>{r?.(f)});typeof d=="number"?f.repeat(d):typeof d=="boolean"&&d&&f.repeat(1/0),p&&f.repeatDelay(20),f.yoyo(p),f.start()})}const Ms={"Linear.None":T.Easing.Linear.None,"Quadratic.In":T.Easing.Quadratic.In,"Quadratic.Out":T.Easing.Quadratic.Out,"Quadratic.InOut":T.Easing.Quadratic.InOut,"Cubic.In":T.Easing.Cubic.In,"Cubic.Out":T.Easing.Cubic.Out,"Cubic.InOut":T.Easing.Cubic.InOut,"Quartic.In":T.Easing.Quartic.In,"Quartic.Out":T.Easing.Quartic.Out,"Quartic.InOut":T.Easing.Quartic.InOut,"Quintic.In":T.Easing.Quintic.In,"Quintic.Out":T.Easing.Quintic.Out,"Quintic.InOut":T.Easing.Quintic.InOut,"Sinusoidal.In":T.Easing.Sinusoidal.In,"Sinusoidal.Out":T.Easing.Sinusoidal.Out,"Sinusoidal.InOut":T.Easing.Sinusoidal.InOut,"Exponential.In":T.Easing.Exponential.In,"Exponential.Out":T.Easing.Exponential.Out,"Exponential.InOut":T.Easing.Exponential.InOut,"Circular.In":T.Easing.Circular.In,"Circular.Out":T.Easing.Circular.Out,"Circular.InOut":T.Easing.Circular.InOut,"Elastic.In":T.Easing.Elastic.In,"Elastic.Out":T.Easing.Elastic.Out,"Elastic.InOut":T.Easing.Elastic.InOut,"Back.In":T.Easing.Back.In,"Back.Out":T.Easing.Back.Out,"Back.InOut":T.Easing.Back.InOut,"Bounce.In":T.Easing.Bounce.In,"Bounce.Out":T.Easing.Bounce.Out,"Bounce.InOut":T.Easing.Bounce.InOut};class xs{scene;planes=new Map;helpers=new Map;group;constructor(e){this.scene=e,this.group=new o.ClippingGroup,this.group.name="__clippingToolGroup",this.scene.add(this.group)}attach(){const e=[...this.scene.children];for(const t of e)t!==this.group&&this.group.add(t)}detach(){const e=[...this.group.children];for(const t of e)this.helpers.has(t.name)||this.scene.add(t)}enable(){this.group.enabled=!0}disable(){this.group.enabled=!1}addPlane(e,t={}){const{normal:s={x:0,y:-1,z:0},constant:n=0,showHelper:r=!1,helperSize:a=5,helperColor:c=16711680}=t,l=new o.Plane(new o.Vector3(s.x,s.y,s.z),n);return this.planes.set(e,l),this._syncPlanes(),r&&this.showHelper(e,a,c),l}addBox(e,t,s={}){const{showHelpers:n=!1,helperColor:r=16711680}=s,a=t.min,c=t.max,l=[{suffix:"+x",normal:{x:-1,y:0,z:0},constant:c.x},{suffix:"-x",normal:{x:1,y:0,z:0},constant:-a.x},{suffix:"+y",normal:{x:0,y:-1,z:0},constant:c.y},{suffix:"-y",normal:{x:0,y:1,z:0},constant:-a.y},{suffix:"+z",normal:{x:0,y:0,z:-1},constant:c.z},{suffix:"-z",normal:{x:0,y:0,z:1},constant:-a.z}],h=[];for(const d of l){const u=`${e}_${d.suffix}`;this.addPlane(u,{normal:d.normal,constant:d.constant,showHelper:n,helperColor:r}),h.push(u)}return h}addBoxFromObject(e,t,s=0,n={}){const r=new o.Box3().setFromObject(t);return r.expandByScalar(s),this.addBox(e,r,n)}setPlaneConstant(e,t){const s=this.planes.get(e);s&&(s.constant=t)}removePlane(e){this.planes.delete(e),this.hideHelper(e),this._syncPlanes()}removeBox(e){const t=["+x","-x","+y","-y","+z","-z"];for(const s of t)this.removePlane(`${e}_${s}`)}removeAll(){const e=Array.from(this.helpers.keys());for(const t of e)this.hideHelper(t);this.planes.clear(),this._syncPlanes()}showHelper(e,t=5,s=16711680){this.hideHelper(e);const n=this.planes.get(e);if(!n)return;const r=new o.PlaneHelper(n,t,new o.Color(s).getHex());r.name=e,this.helpers.set(e,r),this.scene.add(r)}hideHelper(e){const t=this.helpers.get(e);t&&(this.scene.remove(t),t.dispose(),this.helpers.delete(e))}get(e){return this.planes.get(e)}_syncPlanes(){this.group.clippingPlanes=Array.from(this.planes.values())}dispose(){this.detach(),this.removeAll(),this.scene.remove(this.group)}}class Ss{scene;measurements=new Map;_idCounter=0;constructor(e){this.scene=e}measureDistance(e,t,s={}){const{lineColor:n=16776960}=s,r=new o.Vector3(e.x,e.y,e.z),a=new o.Vector3(t.x,t.y,t.z),c=r.distanceTo(a),l=`measure_dist_${this._idCounter++}`,h=new o.Group;h.name=l;const d=new o.BufferGeometry().setFromPoints([r,a]),u=new o.LineBasicMaterial({color:n}),p=new o.Line(d,u);h.add(p),this.scene.add(h);const f={id:l,type:"distance",value:c,unit:"m",points:[r,a],object:h};return this.measurements.set(l,f),f}measureArea(e,t={}){const{lineColor:s=65280}=t;if(e.length<3)throw new Error("MeasureTool.measureArea requires at least 3 points");const n=e.map(f=>new o.Vector3(f.x,f.y,f.z)),r=this._calculatePolygonArea(n),a=`measure_area_${this._idCounter++}`,c=new o.Group;c.name=a;const l=[...n,n[0]],h=new o.BufferGeometry().setFromPoints(l),d=new o.LineBasicMaterial({color:s}),u=new o.Line(h,d);c.add(u),this.scene.add(c);const p={id:a,type:"area",value:r,unit:"m²",points:n,object:c};return this.measurements.set(a,p),p}measureAngle(e,t,s,n={}){const{lineColor:r=16746496}=n,a=new o.Vector3(e.x,e.y,e.z),c=new o.Vector3(t.x,t.y,t.z),l=new o.Vector3(s.x,s.y,s.z),h=a.clone().sub(c).normalize(),d=l.clone().sub(c).normalize(),p=Math.acos(Math.max(-1,Math.min(1,h.dot(d))))*180/Math.PI,f=`measure_angle_${this._idCounter++}`,S=new o.Group;S.name=f;const C=new o.BufferGeometry().setFromPoints([a,c,l]),D=new o.LineBasicMaterial({color:r}),O=new o.Line(C,D);S.add(O),this.scene.add(S);const w={id:f,type:"angle",value:p,unit:"°",points:[a,c,l],object:S};return this.measurements.set(f,w),w}get(e){return this.measurements.get(e)}remove(e){const t=this.measurements.get(e);t&&(this.scene.remove(t.object),t.object.traverse(s=>{s.geometry?.dispose(),s.material?.dispose()}),this.measurements.delete(e))}removeAll(){const e=Array.from(this.measurements.keys());for(const t of e)this.remove(t)}getAll(){return Array.from(this.measurements.values())}_calculatePolygonArea(e){const t=e.length,s=new o.Vector3;for(let r=0;r<t;r++){const a=e[r],c=e[(r+1)%t],l=new o.Vector3().crossVectors(a,c);s.add(l)}const n=new o.Vector3;if(t>=3){const r=e[1].clone().sub(e[0]),a=e[2].clone().sub(e[0]);n.crossVectors(r,a).normalize()}return Math.abs(s.dot(n))/2}dispose(){this.removeAll()}}class Es{scene;annotations=new Map;_idCounter=0;_createCSSObject=null;constructor(e){this.scene=e}setCSSObjectFactory(e){this._createCSSObject=e}add(e,t){this.annotations.has(e)&&this.remove(e);const s=new o.Group;s.name=`annotation_${e}`;const n=new o.Vector3(t.position.x,t.position.y,t.position.z);s.position.copy(n);const r=document.createElement("div");if(r.innerHTML=t.content,r.style.cssText=`
9
9
  padding: 4px 8px;
10
10
  background: rgba(0, 0, 0, 0.75);
11
11
  color: #fff;
@@ -13,4 +13,4 @@
13
13
  border-radius: 4px;
14
14
  pointer-events: auto;
15
15
  white-space: nowrap;
16
- `,t.labelStyle)for(const h of Object.keys(t.labelStyle)){const u=t.labelStyle[h];u!==void 0&&(r.style[h]=u)}let a=null;const c=t.labelOffset||{x:0,y:2,z:0};if(t.showLeaderLine!==!1){const{lineColor:h=16777215}=t,u=new o.BufferGeometry().setFromPoints([new o.Vector3(0,0,0),new o.Vector3(c.x,c.y,c.z)]),d=new o.LineBasicMaterial({color:h});a=new o.Line(u,d),s.add(a)}if(this._createCSSObject){const h=this._createCSSObject(r);h.position.set(c.x,c.y,c.z),s.add(h)}this.scene.add(s);const l={id:e,options:t,group:s,labelElement:r,line:a};return this.annotations.set(e,l),l}addText(e,t,s={}){const n=`annotation_${this._idCounter++}`;return this.add(n,{position:t,content:e,...s})}updateContent(e,t){const s=this.annotations.get(e);s&&(s.labelElement.innerHTML=t,s.options.content=t)}updatePosition(e,t){const s=this.annotations.get(e);s&&(s.group.position.set(t.x,t.y,t.z),s.options.position=t)}show(e){const t=this.annotations.get(e);t&&(t.group.visible=!0)}hide(e){const t=this.annotations.get(e);t&&(t.group.visible=!1)}get(e){return this.annotations.get(e)}remove(e){const t=this.annotations.get(e);if(t){const s=[...t.group.children];for(const n of s)t.group.remove(n),n.geometry?.dispose(),n.material?.dispose();this.scene.remove(t.group),this.annotations.delete(e)}}removeAll(){const e=Array.from(this.annotations.keys());for(const t of e)this.remove(t)}showAll(){for(const e of this.annotations.values())e.group.visible=!0}hideAll(){for(const e of this.annotations.values())e.group.visible=!1}keys(){return Array.from(this.annotations.keys())}get size(){return this.annotations.size}dispose(){this.removeAll()}}const Ee=new o.Matrix4,ds=1e-6,ps=1e-6,Be="uSpaceInstanceOriginalMaterialState",he=0,ne=1,ct=2;function fs(i){let e=i;for(;e;){if(!e.visible)return!1;e=e.parent}return!0}function ms(i,e){const t=i.elements,s=e.elements;for(let n=0;n<16;n++)if(Math.abs(t[n]-s[n])>ds)return!1;return!0}function lt(i){const e=i.material;return Array.isArray(e)?e:[e]}function ht(i){const e=i.userData,t=e[Be];if(t)return t;const s={transparent:i.transparent,opacity:i.opacity};return e[Be]=s,s}function gs(i,e){i.traverse(t=>{const s=t;s.isMesh&&lt(s).forEach(n=>{if(!n)return;const r=n,a=ht(r),c=a.opacity*e;r.transparent=a.transparent||c<1,r.opacity=c,r.needsUpdate=!0})})}function ys(i){i.traverse(e=>{const t=e;t.isMesh&&lt(t).forEach(s=>{if(!s)return;const n=s,r=ht(n);n.transparent=r.transparent,n.opacity=r.opacity,n.needsUpdate=!0})})}class bs extends K{isInstanceObject=!0;type="InstanceObject";instanceId="";instanceKind="";instanceName="";geometry=new o.BufferGeometry;boundingBox=null;boundingSphere=null;#t={color:null,colorMode:he,opacity:1};#a=null;#s=null;#e=null;#n=null;#r=new Set;#o=new o.Matrix4;#c=!1;#l=!0;#h=!1;#d;constructor(e={}){super(),this.#d=e.boundsName??"InstanceBounds"}setInstanceIdentity(e){let t=!1;if(e.id!==void 0){const s=e.id??"";this.instanceId!==s&&(this.instanceId=s,t=!0)}if(e.kind!==void 0){const s=e.kind??"";this.instanceKind!==s&&(this.instanceKind=s,t=!0)}if(e.name!==void 0){const s=e.name??"";this.instanceName!==s&&(this.instanceName=s,t=!0)}return t&&this.markInstanceRenderDirty(),this}setInstanceBounds(e){if(e.isEmpty())return this;this.#s&&this.remove(this.#s);const t=new o.BufferGeometry;t.boundingBox=e.clone();const s=new o.Object3D;return s.name=this.#d,s.visible=!1,s.geometry=t,s.raycast=()=>{},this.#s=s,this.add(s),this.#p(),this.markInstanceRenderDirty(),this}setInstanceRenderObject(e){return this.#e&&this.#e!==e&&this.#e.parent===this&&this.remove(this.#e),this.#e=e,e&&e.parent!==this&&this.add(e),this.#u(),this.#p(),this.markInstanceRenderDirty(),this}getInstanceRenderObject(){return this.#e}setInstanceMaterializer(e){return this.#n=e,this}hasInstanceMaterializer(e){return this.#n===e}clearInstanceMaterializer(e){return(e===void 0||this.#n===e)&&(this.#n=null),this}materialize(){return this.#n?.()??this.#e??null}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new o.Box3),this.getInstanceBoundingBox(this.boundingBox,!1)}computeBoundingSphere(){if(this.boundingSphere===null&&(this.boundingSphere=new o.Sphere),this.boundingBox===null&&this.computeBoundingBox(),!this.boundingBox||this.boundingBox.isEmpty()){this.boundingSphere.makeEmpty();return}this.boundingBox.getBoundingSphere(this.boundingSphere)}getInstanceBoundingBox(e=new o.Box3,t=!1){const s=this.#s?.geometry?.boundingBox;return s?(e.copy(s),t&&(this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)),e):this.#e?(e.setFromObject(this.#e),t||(this.updateWorldMatrix(!0,!1),Ee.copy(this.matrixWorld).invert(),e.applyMatrix4(Ee)),e):e.makeEmpty()}setInstanceVisible(e){return this.visible===e?this:(this.visible=e,this.markInstanceRenderDirty(),this)}setInstanceColor(e){return this.#t.color=new o.Color(e),this.#t.colorMode=ne,this.#u(),this.markInstanceRenderDirty(),this}resetInstanceColor(){return this.#t.color===null?this:(this.#t.color=null,this.#t.colorMode=he,this.#u(),this.markInstanceRenderDirty(),this)}setInstanceOpacity(e){const t=Math.max(0,Math.min(1,e));return Math.abs(this.#t.opacity-t)<=ps?this:(this.#t.opacity=t,this.#u(),this.markInstanceRenderDirty(),this)}getInstanceColor(e=new o.Color){const t=this.#f();return t.color?e.copy(t.color):e.setRGB(1,1,1)}hasInstanceColor(){return this.#f().color!==null}getInstanceOpacity(){return this.#f().opacity}setInstanceHighlight(e,t,s=!1){return this.#a={color:new o.Color(e),colorMode:s?ne:ct,opacity:Math.max(0,Math.min(1,t))},this.#u(),this.markInstanceRenderDirty(),this}clearInstanceHighlight(){return this.#a===null?this:(this.#a=null,this.#u(),this.markInstanceRenderDirty(),this)}getInstanceColorMode(){return this.#f().colorMode}onInstanceRenderDirty(e){return this.#r.add(e),()=>this.#r.delete(e)}markInstanceRenderDirty(){return this.#r.forEach(e=>e()),this}updateMatrixWorld(e){super.updateMatrixWorld(e),this.#i()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.#i()}#i(){const e=fs(this);(!this.#c||!ms(this.matrixWorld,this.#o)||!this.#h||e!==this.#l)&&(this.#c=!0,this.#h=!0,this.#o.copy(this.matrixWorld),this.#l=e,this.markInstanceRenderDirty())}#p(){this.boundingBox=null,this.boundingSphere=null}#f(){return this.#a??this.#t}#u(){if(!this.#e)return;const e=this.#f();if(e.color){ys(this.#e),W.highlightColor(this.#e,{color:e.color,opacity:e.opacity,overwrite:e.colorMode===ne,multiplyOpacity:!0});return}W.removeHighlightColor(this.#e),gs(this.#e,e.opacity)}}function xs(i){return i.isInstanceObject===!0}const ws=new Set(["MeshBasicMaterial","MeshLambertMaterial","MeshPhongMaterial","MeshStandardMaterial","MeshPhysicalMaterial"]),Ce=new WeakMap;let Ms=1;const _e=new o.Matrix4,Y=new o.Matrix4,Oe=new o.Matrix4;function Ss(i,e,t=1e-6){const s=i.elements,n=e.elements;for(let r=0;r<16;r++)if(Math.abs(s[r]-n[r])>t)return!1;return!0}function ut(i){let e=i;for(;e;){if(!e.visible)return!1;e=e.parent}return!0}function Is(i){const e=i.source.data;if(!e||typeof e!="object"&&typeof e!="function")return`texture:${i.uuid}`;let t=Ce.get(e);return t===void 0&&(t=Ms++,Ce.set(e,t)),`source:${t}`}function vs(i){return JSON.stringify([Is(i),i.mapping,i.channel,i.wrapS,i.wrapT,i.magFilter,i.minFilter,i.anisotropy,i.format,i.internalFormat,i.type,i.offset.toArray(),i.repeat.toArray(),i.center.toArray(),i.rotation,i.matrixAutoUpdate,i.matrix.toArray(),i.generateMipmaps,i.premultiplyAlpha,i.flipY,i.unpackAlignment,i.colorSpace,"compareFunction"in i?i.compareFunction:null])}function ue(i){if(Array.isArray(i))return i.map(ue);if(!i||typeof i!="object")return i;const e=i;return Object.fromEntries(Object.keys(e).sort().map(t=>[t,ue(e[t])]))}function de(i,e){if(Array.isArray(i))return i.map(s=>de(s,e));if(!i||typeof i!="object")return typeof i=="string"?e.get(i)??i:i;const t=i;return Object.fromEntries(Object.keys(t).filter(s=>s!=="metadata"&&s!=="uuid"&&s!=="name").sort().map(s=>[s,de(t[s],e)]))}function Es(i){if(!ws.has(i.type)||i.transparent||i.opacity<.999||i.visible===!1)return null;const e=i;if(Object.keys(e).some(r=>r.endsWith("Node")&&e[r]!=null)||Object.hasOwn(i,"onBeforeCompile"))return null;const t=new Map;Object.values(e).forEach(r=>{r instanceof o.Texture&&t.set(r.uuid,vs(r))});const s={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},n=i.toJSON(s);return JSON.stringify(ue(de(n,t)))}function Bs(i){if(Object.keys(i.morphAttributes).length>0||i.drawRange.start!==0||i.drawRange.count!==1/0)return null;const e=Object.entries(i.attributes).sort(([t],[s])=>t.localeCompare(s)).map(([t,s])=>"isInterleavedBufferAttribute"in s?null:[t,s.itemSize,s.normalized,s.array.constructor.name,s.gpuType]);return e.some(t=>t===null)?null:JSON.stringify([i.index?.array.constructor.name??"non-indexed",e])}function Cs(i,e){const t=[],s=new Set,n=new Set,r=!e&&(i.animations.length>0||i.mixer!==null);return r&&n.add("animation"),i.updateWorldMatrix(!0,!0),_e.copy(i.matrixWorld).invert(),i.traverseVisible(a=>{if(!(a instanceof o.Mesh))return;if(r){s.add(a);return}if(a instanceof o.SkinnedMesh){s.add(a),n.add("skinned");return}if(a.morphTargetInfluences){s.add(a),n.add("morph");return}if(Array.isArray(a.material)){s.add(a),n.add("material-array");return}const c=Es(a.material),l=Bs(a.geometry);if(!c){s.add(a),n.add(a.material.transparent||a.material.opacity<.999?"transparent":`material:${a.material.type}`);return}if(!l){s.add(a),n.add("geometry-layout");return}if(a.matrixWorld.determinant()<=0){s.add(a),n.add("negative-scale");return}t.push({mesh:a,localMatrix:_e.clone().multiply(a.matrixWorld),materialKey:c,geometryKey:l})}),t.length===0&&s.size===0&&n.add("empty"),{meshes:t,fallbackMeshes:s,fallbackReasons:n}}function _s(i,e){const t=pe.clone(i),s=[],n=[];return i.traverse(r=>{r instanceof o.Mesh&&s.push(r)}),t.traverse(r=>{r instanceof o.Mesh&&n.push(r)}),s.forEach((r,a)=>{e.has(r)&&n[a]&&(n[a].visible=!1)}),t}function Os(i){const e=pe.clone(i),t=new Map,s=n=>{let r=t.get(n);return r||(r=n.clone(),t.set(n,r)),r};return e.traverse(n=>{n instanceof o.Mesh&&(n.material=Array.isArray(n.material)?n.material.map(s):s(n.material))}),e}function As(i){return Math.max(1,Math.ceil(Math.sqrt(Math.max(1,i))))}function Ls(i){const e=new o.DataTexture(new Float32Array(i*i*4),i,i,o.RGBAFormat,o.FloatType);return e.magFilter=o.NearestFilter,e.minFilter=o.NearestFilter,e.generateMipmaps=!1,e.needsUpdate=!0,e}function Ts(i,e){const t=i.clone(),s=f.attribute("batchObjectIndex","float").toInt(),n=f.int(f.textureSize(f.textureLoad(e),f.int(0)).x).toConst(),r=s.mod(n).toConst(),a=s.div(n).toConst(),c=f.textureLoad(e,f.ivec2(r,a)),l=t.colorNode??f.materialColor,h=f.select(c.a.greaterThan(1.5),l.mul(c.rgb),c.rgb);return t.colorNode=f.select(c.a.greaterThan(.5),h,l),t.maskNode=c.a.greaterThan(-.5),t.needsUpdate=!0,t}function Ae(i){let e=0,t=i.parent;for(;t;)e++,t=t.parent;return e}class Ns extends k{objectIndices;states;#t;constructor(e,t,s,n){super(e,t),this.objectIndices=s,this.states=n,this.userData.editableGeometryBatch=!0}raycast(e,t){if(this.visible===!1&&this.ignoreInvisibleWhenRaycast===!0)return!1;this.#t===void 0&&(this.#t=j.getGeometryBoundsTree(this.geometry));const s=[];this.#t?this.#t.raycastObject3D(this,e,s):super.raycast(e,s),s.forEach(n=>{const r=n.faceIndex;if(r==null)return;const a=r*3,c=this.geometry.index?.getX(a)??a,l=this.objectIndices[c],h=l===void 0?void 0:this.states[l],u=h?.instance;!h||h.materialized||!u||!ut(u)||u.getInstanceOpacity()<=.001||(n.object=u,n.batchObjectIndex=l,t.push(n))})}}class Ps extends K{isEditableGeometryBatchLayer=!0;type="EditableGeometryBatchLayer";options;stats={instances:0,sourceMeshes:0,batches:0,drawCallsSaved:0,vertices:0,indices:0,unsupportedInstances:0,unsupportedByReason:{}};#t=[];#a=new Set;#s=[];#e=new Map;#n=new Set;#r=null;#o=new o.Matrix4;#c=!1;#l=!1;#h=!1;constructor(e={}){super(),this.name="EditableGeometryBatches",this.options={maxVerticesPerBatch:e.maxVerticesPerBatch??15e5,maxIndicesPerBatch:e.maxIndicesPerBatch??45e5,freezeAnimations:e.freezeAnimations??!1}}addSource(e){if(this.#l)throw new Error("EditableGeometryBatchLayer has been disposed.");if(this.#c)throw new Error("EditableGeometryBatchLayer has already been built.");const{key:t,template:s,instances:n}=e,r=new Set;n.forEach(h=>{if(r.has(h)||this.#a.has(h))throw new Error("EditableGeometryBatchLayer cannot batch the same InstanceObject more than once.");r.add(h)});const{meshes:a,fallbackMeshes:c,fallbackReasons:l}=Cs(s,this.options.freezeAnimations);return r.forEach(h=>this.#a.add(h)),this.#t.push({key:t,template:s,instances:[...n],meshes:a,fallbackMeshes:c,fallbackReasons:l,bounds:new o.Box3().setFromObject(s)}),a.length>0}build(){if(this.#l)throw new Error("EditableGeometryBatchLayer has been disposed.");if(this.#c)throw new Error("EditableGeometryBatchLayer.build() can only be called once.");this.#c=!0,this.updateWorldMatrix(!0,!1),this.#o.copy(this.matrixWorld).invert();const e=[],t=new Map,s=(r,a,c,l)=>{if(c.length===0)return;const h=l.size>0?[...l]:["unknown"];e.push({key:r.key,template:a,instances:c,reasons:h}),h.forEach(u=>{this.stats.unsupportedByReason[u]=(this.stats.unsupportedByReason[u]??0)+c.length})};this.#t.forEach(r=>{const a=[],c=[];r.instances.forEach(h=>{h.updateWorldMatrix(!0,!1),Y.multiplyMatrices(this.#o,h.matrixWorld),Y.determinant()<=0?c.push(h):a.push({instance:h,matrix:Y.clone()})});const l=r.fallbackReasons.size>0?r.fallbackReasons:new Set(["unknown"]);if(r.meshes.length===0){s(r,r.template,a.map(({instance:h})=>h),l),s(r,r.template,c,new Set([...l,"negative-scale"]));return}r.fallbackMeshes.size>0&&s(r,_s(r.template,new Set(r.meshes.map(({mesh:h})=>h))),a.map(({instance:h})=>h),l),s(r,r.template,c,new Set([...r.fallbackReasons,"negative-scale"])),a.forEach(({instance:h,matrix:u})=>{const d=this.#s.length,p=()=>this.materialize(h),m={instance:h,template:r.template,initialMatrix:u,objectIndex:d,materialized:!1,materializer:p,unsubscribe:()=>{}};m.unsubscribe=h.onInstanceRenderDirty(()=>this.#p(m)),this.#s.push(m),this.#e.set(h,m),h.setInstanceBounds(r.bounds),h.setInstanceMaterializer(p),this.#n.add(m),r.meshes.forEach(({mesh:g,localMatrix:w,materialKey:E,geometryKey:S})=>{Oe.multiplyMatrices(u,w);const b=g.geometry.clone().applyMatrix4(Oe),v=b.getAttribute("position");b.setAttribute("batchObjectIndex",new o.Float32BufferAttribute(new Float32Array(v.count).fill(d),1));const C=JSON.stringify([E,S,g.castShadow,g.receiveShadow,g.renderOrder]),A=t.get(C),L={geometry:b,material:g.material,castShadow:g.castShadow,receiveShadow:g.receiveShadow,renderOrder:g.renderOrder,objectIndices:new Array(v.count).fill(d)};A?A.push(L):t.set(C,[L]),this.stats.sourceMeshes++,this.stats.vertices+=v.count,this.stats.indices+=b.index?.count??v.count})})}),this.stats.instances=this.#s.length,this.stats.unsupportedInstances=e.reduce((r,a)=>r+a.instances.length,0);const n=As(this.#s.length);return this.#r=Ls(n),this.#i(),t.forEach(r=>this.#d(r)),this.stats.batches=this.children.length,this.stats.drawCallsSaved=Math.max(0,this.stats.sourceMeshes-this.stats.batches),this.children.forEach(r=>{r instanceof o.Mesh&&(r.onBeforeRender=()=>this.#i())}),{stats:{...this.stats},unsupported:e}}materialize(e){const t=this.#e.get(e);if(!t||t.materialized)return e.getInstanceRenderObject();const s=Os(t.template);return s.position.set(0,0,0),s.quaternion.identity(),s.scale.set(1,1,1),s.matrix.identity(),t.materialized=!0,e.setInstanceRenderObject(s),s.updateWorldMatrix(!0,!0),this.#n.add(t),this.dispatchEvent({type:"materialize",instance:e,object:s}),s}#d(e){const t=[];let s=[],n=0,r=0;e.forEach(a=>{const c=a.geometry.getAttribute("position").count,l=a.geometry.index?.count??c;s.length>0&&(n+c>this.options.maxVerticesPerBatch||r+l>this.options.maxIndicesPerBatch)&&(t.push(s),s=[],n=0,r=0),s.push(a),n+=c,r+=l}),s.length>0&&t.push(s),t.forEach(a=>{const c=It.mergeGeometries(a.map(p=>p.geometry),!1);if(a.forEach(p=>p.geometry.dispose()),!c||!this.#r)return;c.computeBoundingBox(),c.computeBoundingSphere();const l=a[0],h=a.flatMap(p=>p.objectIndices),u=Ts(l.material,this.#r),d=new Ns(c,u,h,this.#s);d.name=`EditableGeometryBatch:${this.children.length}`,d.castShadow=l.castShadow,d.receiveShadow=l.receiveShadow,d.renderOrder=l.renderOrder,d.matrixAutoUpdate=!1,this.add(d)})}#i(){if(!(!this.#r||this.#n.size===0||this.#h)){this.#h=!0;try{this.updateWorldMatrix(!0,!1),this.#o.copy(this.matrixWorld).invert();const e=this.#r.image.data;[...this.#n].sort((t,s)=>Ae(t.instance)-Ae(s.instance)).forEach(t=>{const{instance:s,objectIndex:n}=t;s.updateWorldMatrix(!0,!1),Y.multiplyMatrices(this.#o,s.matrixWorld),!t.materialized&&s.getInstanceRenderObject()!==null&&!s.hasInstanceMaterializer(t.materializer)&&(t.materialized=!0),!t.materialized&&!Ss(Y,t.initialMatrix)&&this.materialize(s),!t.materialized&&s.getInstanceOpacity()<.999&&this.materialize(s);const r=n*4,a=!t.materialized&&ut(s)&&s.getInstanceOpacity()>.001,c=s.getInstanceColor();e[r]=c.r,e[r+1]=c.g,e[r+2]=c.b,e[r+3]=a?s.getInstanceColorMode():-1,this.#n.delete(t)}),this.#r.needsUpdate=!0}finally{this.#h=!1}this.#n.size>0&&this.#i()}}#p(e){this.#n.add(e),this.#i()}dispose(){this.#l||(this.#l=!0,this.#s.forEach(e=>{e.unsubscribe(),e.instance.clearInstanceMaterializer(e.materializer)}),this.#s.length=0,this.#e.clear(),this.#a.clear(),this.#n.clear(),this.#t.length=0,this.#r?.dispose(),this.#r=null,this.traverse(e=>{if(!(e instanceof o.Mesh))return;e.geometry.dispose(),(Array.isArray(e.material)?e.material:[e.material]).forEach(s=>s.dispose())}),this.clear())}}const Le=new o.Matrix4,te=new o.Matrix4,Te=new o.Matrix4,Ne=new o.Matrix4,Pe=new o.Box3,De=new o.Sphere,Re=new o.Sphere,Ds=new o.Frustum,$=new o.Color,je=new o.Vector2,ze=new o.Vector3,Ue=new o.Matrix4,ke=new o.Matrix4,Ge=new o.Sphere,se=[],dt=1e-6,z=1e-6,pt=.999,Rs=0,We=1;function js(i,e,t){const s=i.elements;for(let n=0;n<16;n++)if(Math.abs(s[n]-e[t+n])>dt)return!1;return!0}function zs(i,e,t,s){return Math.abs(i.r-t[s])<=z&&Math.abs(i.g-t[s+1])<=z&&Math.abs(i.b-t[s+2])<=z&&Math.abs(e-t[s+3])<=z}function Fe(i,e){const t=i.elements,s=e.elements;for(let n=0;n<16;n++)if(Math.abs(t[n]-s[n])>dt)return!1;return!0}function ce(i){let e=i;for(;e;){if(!e.visible)return!1;e=e.parent}return!0}function Us(i){const e=i.geometry.morphAttributes;return Object.values(e).some(t=>t?.length)}function ks(i){const e=i.material;if(!Array.isArray(e))return!0;if(e.length===0||!e.every(Boolean))return!1;const t=i.geometry.groups;return t.length===0?!1:t.every(s=>{const n=s.materialIndex??0;return Number.isInteger(s.start)&&s.start>=0&&Number.isInteger(s.count)&&s.count>0&&Number.isInteger(n)&&n>=0&&n<e.length})}function Gs(i){return!i.isSkinnedMesh&&!Us(i)&&ks(i)}function He(i){return Array.isArray(i)?i:[i]}function ft(i){return i.transparent||i.opacity<pt}function $e(i,e,t){const s=i.clone(),n=f.instancedBufferAttribute(e,"vec4",4,0),r=f.instancedBufferAttribute(t,"float",1,0),a=s.colorNode??f.materialColor,c=s.opacityNode?f.float(s.opacityNode):f.materialOpacity,l=f.select(n.a.greaterThan(1.5),a.mul(n.rgb),n.rgb);return s.colorNode=f.select(n.a.greaterThan(.5),l,a),s.opacityNode=c.mul(r),s.transparent=ft(i),s.needsUpdate=!0,s}function Ws(i,e,t){return Array.isArray(i)?i.map(s=>$e(s,e,t)):$e(i,e,t)}function Fs(i){const e=[],t=new o.Matrix4;let s=!1;return i.updateWorldMatrix(!0,!0),t.copy(i.matrixWorld).invert(),i.traverse(n=>{if(!s&&!(!(n instanceof o.Mesh)||!n.visible)){if(!Gs(n)){s=!0;return}n.updateWorldMatrix(!0,!1),e.push({mesh:n,localMatrix:t.clone().multiply(n.matrixWorld)})}}),s?[]:e}function Hs(i){const e=new o.Box3;return i.forEach(({mesh:t,localMatrix:s})=>{const n=t.geometry;n.boundingBox||n.computeBoundingBox(),n.boundingBox&&(Pe.copy(n.boundingBox).applyMatrix4(s),e.union(Pe))}),e}function V(i){const e=i;"needsUpdate"in e&&(e.needsUpdate=!0)}function Ve(i,e=We){let t=Math.max(We,e);for(;t<i;)t*=2;return t}function $s(i){return i!==null&&typeof i=="object"&&Symbol.iterator in i}class Vs extends K{isModelInstancedLayer=!0;type="ModelInstancedLayer";#t=[];#a=new Map;#s=new Map;#e=new Map;#n=!0;#r=!1;#o=!0;#c=Rs;#l;#h;constructor(e={}){super(),this.name=e.name??"ModelInstances",this.#l=e.instanceKind??"",this.#h=e.getHitUserData??(()=>({}))}get instanceKind(){return this.#l}getInstances(){const e=[];return this.#i(t=>e.push(t)),e}getInstanceById(e){return this.#x(),this.#e.get(e)}hasInstance(e){return this.#x(),this.#e.has(e)}getInstanceCulling(){return{enabled:this.#r,frustum:this.#o,minScreenRadius:this.#c}}setInstanceCulling(e={}){let t=!1;if(e.enabled!==void 0&&this.#r!==e.enabled&&(this.#r=e.enabled,t=!0),e.frustum!==void 0&&this.#o!==e.frustum&&(this.#o=e.frustum,t=!0),e.minScreenRadius!==void 0){const s=Math.max(0,e.minScreenRadius);Math.abs(this.#c-s)>z&&(this.#c=s,t=!0)}return t&&this.#t.forEach(s=>this.#v(s)),this}setInstanceVisible(e){return this.visible!==e&&(this.visible=e),this.#i(t=>{t.setInstanceVisible(e)}),this}setInstanceColor(e){return this.#i(t=>{t.setInstanceColor(e)}),this}resetInstanceColor(){return this.#i(e=>{e.resetInstanceColor()}),this}setInstanceOpacity(e){return this.#i(t=>{t.setInstanceOpacity(e)}),this}setInstanceHighlight(e,t,s=!1){return this.#i(n=>{n.setInstanceHighlight(e,t,s)}),this}clearInstanceHighlight(){return this.#i(e=>{e.clearInstanceHighlight()}),this}reserveBatch(e,t,s){const n=Math.floor(s);return n<=0?!1:this.#d(e,t,n)!==null}addInstance(e,t,s){return this.addInstances(e,t,[s])}addInstances(e,t,s){if(s.length===0)return!1;const n=this.#a.has(e),r=this.#d(e,t,s.length);if(!r)return!1;const a=[],c=new Set;return s.forEach(l=>{c.has(l)||(c.add(l),this.#s.get(l)===r)||a.push(l)}),a.length===0?!0:this.#B(a)?(a.forEach(l=>{const h=this.#s.get(l);h&&h!==r&&this.#S(h,l)}),this.#M(r,r.instances.length+a.length),a.forEach(l=>{l.setInstanceBounds(r.templateBounds),r.instances.push(l),this.#s.set(l,r),r.unsubscribeByInstance.set(l,l.onInstanceRenderDirty(()=>{this.#g(),this.#y(r)}))}),this.#g(),this.#b(r),this.#y(r),!0):(!n&&r.instances.length===0&&this.#m(r),!1)}removeInstance(e){return this.removeInstances([e])>0}removeInstances(e){const t=new Set,s=new Set,n=typeof e=="string"||!$s(e)?[e]:e;for(const a of n)typeof a=="string"?t.add(a):this.#s.has(a)&&s.add(a);t.size>0&&(this.#x(),t.forEach(a=>{const c=this.#e.get(a);c&&s.add(c)}));let r=0;return s.forEach(a=>{const c=this.#s.get(a);c&&this.#S(c,a)&&r++}),r}removeBatch(e){const t=this.#a.get(e);return t?(this.#m(t),!0):!1}clearBatches(){return[...this.#a.values()].forEach(e=>this.#m(e)),this}#d(e,t,s){const n=this.#a.get(e);if(n)return this.#M(n,s),n;if(t.animations?.length)return null;const r=Fs(t);if(r.length===0)return null;const a=Hs(r),c=new o.Group;c.name=e,this.add(c);const l={url:e,batch:c,templateMeshes:r,templateBounds:a,records:[],instances:[],unsubscribeByInstance:new Map,capacity:Ve(s)};return r.forEach(({mesh:h,localMatrix:u},d)=>{const p=this.#p(l,h,u,d);l.records.push(p),this.#t.push(p)}),this.#a.set(e,l),this.#b(l),l}#i(e){const t=new Set;this.#a.forEach(s=>{s.instances.forEach(n=>{t.has(n)||(t.add(n),e(n))})})}#p(e,t,s,n){const r=new o.InstancedBufferAttribute(new Float32Array(e.capacity*4),4),a=new o.InstancedBufferAttribute(new Float32Array(e.capacity).fill(1),1);r.setUsage(o.DynamicDrawUsage),a.setUsage(o.DynamicDrawUsage);const c=Ws(t.material,r,a),l=He(c),h=He(t.material).some(ft),u=new o.InstancedMesh(t.geometry,c,e.capacity);u.instanceMatrix=new o.StorageInstancedBufferAttribute(e.capacity,16),u.count=0,u.name=t.name||`${e.url}#${n}`,u.castShadow=t.castShadow,u.receiveShadow=t.receiveShadow,u.frustumCulled=!0,u.matrixAutoUpdate=!1,u.instanceMatrix.setUsage(o.DynamicDrawUsage),u.userData.url=e.url;const d=new o.Mesh(t.geometry,c);d.matrixAutoUpdate=!1;const p={batchRecord:e,mesh:u,boundsTree:void 0,raycastMesh:d,localMatrix:s.clone(),fullBoundingSphere:new o.Sphere,materials:l,hasSourceTransparency:h,colorAttribute:r,opacityAttribute:a,renderedInstances:[],visibleInstances:[],lastCameraMatrixWorldInverse:new o.Matrix4,lastCameraProjectionMatrix:new o.Matrix4,lastViewportHeight:0,hasLastCameraState:!1,dirty:!0};u.userData.getInstanceObjectByRenderIndex=g=>p.renderedInstances[g],u.userData.raycastAcceleration="lazy";const m=u.raycast.bind(u);return u.raycast=(g,w)=>{if(this.#E(p),!this.#f(p,g))return;p.boundsTree===void 0&&(p.boundsTree=j.getGeometryBoundsTree(p.mesh.geometry),p.mesh.userData.raycastAcceleration=p.boundsTree?"three-mesh-bvh":"default");const E=w.length;p.boundsTree?this.#u(p,g,w):m(g,w);for(let S=E;S<w.length;){const b=w[S],v=b.instanceId;if(v===void 0){S++;continue}const C=p.renderedInstances[v];if(!C||!ce(C)){w.splice(S,1);continue}b.object=C,b.instanceObject=C,b.instanceObjectId=C.instanceId,b.instanceKind=C.instanceKind||this.#l,b.instanceName=C.instanceName,b.instanceIndex=v,Object.assign(b,this.#h(C,v)),S++}},u.onBeforeRender=(g,w,E)=>this.#E(p,g,E),e.batch.add(u),p}#f(e,t){const{mesh:s}=e;return s.count===0?!1:(s.boundingSphere===null&&s.computeBoundingSphere(),s.boundingSphere?(Ge.copy(s.boundingSphere).applyMatrix4(s.matrixWorld),t.ray.intersectsSphere(Ge)):!0)}#u(e,t,s){const{mesh:n,boundsTree:r,raycastMesh:a}=e;if(!(!r||n.count===0)){a.geometry=n.geometry,a.material=n.material;for(let c=0;c<n.count;c++)n.getMatrixAt(c,Ue),ke.multiplyMatrices(n.matrixWorld,Ue),a.matrixWorld.copy(ke),se.length=0,r.raycastObject3D(a,t,se),se.forEach(l=>{l.instanceId=c,l.object=n,s.push(l)}),se.length=0}}#M(e,t){if(t<=e.capacity)return;e.capacity=Ve(t,e.capacity);const s=new Set(e.records);s.forEach(n=>this.#I(n)),this.#t=this.#t.filter(n=>!s.has(n)),e.records=e.templateMeshes.map(({mesh:n,localMatrix:r},a)=>{const c=this.#p(e,n,r,a);return this.#t.push(c),c}),this.#y(e)}#S(e,t){const s=e.instances.indexOf(t);return s===-1?!1:(e.instances.splice(s,1),e.records.forEach(n=>n.visibleInstances.splice(s,1)),this.#s.delete(t),this.#g(),e.unsubscribeByInstance.get(t)?.(),e.unsubscribeByInstance.delete(t),e.instances.length===0?(this.#m(e),!0):(this.#b(e),this.#y(e),!0))}#m(e){e.unsubscribeByInstance.forEach(s=>s()),e.instances.forEach(s=>this.#s.delete(s)),e.unsubscribeByInstance.clear(),e.instances.length=0,this.#g();const t=new Set(e.records);t.forEach(s=>this.#I(s)),this.#t=this.#t.filter(s=>!t.has(s)),e.records.length=0,e.templateMeshes.length=0,this.#a.delete(e.url),this.remove(e.batch)}#I(e){e.batchRecord.batch.remove(e.mesh),e.mesh.dispose(),e.materials.forEach(t=>t.dispose())}#b(e){Object.assign(e.batch.userData,{url:e.url,count:e.instances.length,capacity:e.capacity,instanceKind:this.#l}),delete e.batch.userData.sceneInstances,delete e.batch.userData.facilities,e.records.forEach(t=>{delete t.mesh.userData.instances})}#B(e){const t=new Set(e),s=new Map;for(const r of e){const{instanceId:a}=r;if(!a)continue;const c=s.get(a);if(c&&c!==r)return!1;s.set(a,r)}let n=!0;return s.forEach((r,a)=>{n&&this.#i(c=>{!n||t.has(c)||c.instanceId===a&&(n=!1)})}),n}#x(){if(!this.#n)return;this.#e.clear();const e=new Set;this.#i(t=>{const{instanceId:s}=t;if(!s||e.has(s))return;const n=this.#e.get(s);if(n&&n!==t){this.#e.delete(s),e.add(s);return}this.#e.set(s,t)}),this.#n=!1}#g(){this.#n=!0}#y(e){e.records.forEach(t=>this.#v(t))}#v(e){e.dirty=!0,e.hasLastCameraState=!1,e.mesh.visible=!0,e.mesh.frustumCulled=!1,V(e.batchRecord.batch)}#E(e,t,s){const n=this.#_(t),r=this.#O(e,s,n);!e.dirty&&!this.#C(e)&&!r||this.#N(e,s,n)}#C(e){const{instances:t}=e.batchRecord;for(let s=0;s<t.length;s++)if(e.visibleInstances[s]!==ce(t[s]))return e.dirty=!0,V(e.batchRecord.batch),!0;return!1}#_(e){return e?.getDrawingBufferSize?(e.getDrawingBufferSize(je),je.y):0}#O(e,t,s){return this.#w(t,s)?e.hasLastCameraState?!Fe(e.lastCameraMatrixWorldInverse,t.matrixWorldInverse)||!Fe(e.lastCameraProjectionMatrix,t.projectionMatrix)||Math.abs(e.lastViewportHeight-s)>z:!0:!1}#w(e,t){return this.#r&&e!==void 0&&(this.#o||this.#c>0&&t>0)}#A(e,t){if(!this.#w(e,t))return null;let s=null;return this.#o&&(Ne.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),s=Ds.setFromProjectionMatrix(Ne)),{camera:e,frustum:s,viewportHeight:t}}#L(e,t){return t?t.frustum&&!t.frustum.intersectsSphere(e)?!1:this.#c<=0||t.viewportHeight<=0?!0:this.#T(e,t.camera,t.viewportHeight)>=this.#c:!0}#T(e,t,s){const n=Math.abs(t.projectionMatrix.elements[5]);if(n<=z)return 1/0;if(t.isOrthographicCamera)return e.radius*n*s*.5;ze.copy(e.center).applyMatrix4(t.matrixWorldInverse);const r=-ze.z;return r<=z?1/0:e.radius*n*s*.5/r}#N(e,t,s=0){this.updateWorldMatrix(!0,!1),Le.copy(this.matrixWorld).invert();const n=e.mesh.instanceMatrix.array,r=e.colorAttribute.array,a=e.opacityAttribute.array,c=e.mesh.geometry;let l=!1,h=!1,u=!1,d=0,p=0,m=!1;const g=e.mesh.count,w=this.#A(t,s);c.boundingSphere||c.computeBoundingSphere(),e.fullBoundingSphere.makeEmpty(),e.renderedInstances.length=0,e.batchRecord.instances.forEach((b,v)=>{const C=ce(b);e.visibleInstances[v]=C,b.updateWorldMatrix(!0,!1),te.multiplyMatrices(Le,b.matrixWorld).multiply(e.localMatrix);const A=b.getInstanceOpacity();if(!(C&&A>z)||(p++,c.boundingSphere&&(De.copy(c.boundingSphere).applyMatrix4(te),e.fullBoundingSphere.union(De),w&&(Te.multiplyMatrices(b.matrixWorld,e.localMatrix),Re.copy(c.boundingSphere).applyMatrix4(Te),!this.#L(Re,w)))))return;const x=d,O=x*16;js(te,n,O)||(e.mesh.setMatrixAt(x,te),l=!0),$.copy(b.getInstanceColor($));const R=b.getInstanceColorMode(),T=x*4;zs($,R,r,T)||(e.colorAttribute.setXYZW(x,$.r,$.g,$.b,R),h=!0),A<pt&&(m=!0),Math.abs(A-a[x])>z&&(e.opacityAttribute.setX(x,A),u=!0),e.renderedInstances[x]=b,d++}),e.mesh.count=d,g!==d&&(l=!0,h=!0,u=!0,V(e.batchRecord.batch));const E=p>0;e.mesh.visible!==E&&(e.mesh.visible=E,V(e.batchRecord.batch)),e.mesh.frustumCulled!==!0&&(e.mesh.frustumCulled=!0,V(e.batchRecord.batch)),l&&(e.mesh.instanceMatrix.needsUpdate=!0),h&&(e.colorAttribute.needsUpdate=!0),u&&(e.opacityAttribute.needsUpdate=!0),e.mesh.boundingSphere===null&&(e.mesh.boundingSphere=new o.Sphere),e.mesh.boundingSphere.copy(e.fullBoundingSphere);const S=e.hasSourceTransparency||m;e.materials.forEach(b=>{b.transparent!==S&&(b.transparent=S,b.needsUpdate=!0,V(e.batchRecord.batch))}),t&&this.#w(t,s)?(e.lastCameraMatrixWorldInverse.copy(t.matrixWorldInverse),e.lastCameraProjectionMatrix.copy(t.projectionMatrix),e.lastViewportHeight=s,e.hasLastCameraState=!0):e.hasLastCameraState=!1,e.dirty=!1}}const mt="0.0.30";typeof window<"u"&&(window.__USPACE__={version:mt});exports.CSSRenderer=j.CSSRenderer;exports.CameraControls=j.CameraControls;exports.InteractionEvent=j.InteractionEvent;exports.InteractionManager=j.InteractionManager;exports.ObjectManager=j.ObjectManager;exports.RenderPipeline=j.RenderPipeline;exports.RoomEnvironment=j.RoomEnvironment;exports.Viewer=j.Viewer;exports.enableMeshBVHRaycast=j.enableMeshBVHRaycast;exports.getGeometryBoundsTree=j.getGeometryBoundsTree;Object.defineProperty(exports,"CSS2DObject",{enumerable:!0,get:()=>vt.CSS2DObject});Object.defineProperty(exports,"CSS3DObject",{enumerable:!0,get:()=>qe.CSS3DObject});Object.defineProperty(exports,"CSS3DSprite",{enumerable:!0,get:()=>qe.CSS3DSprite});exports.AnnotationManager=us;exports.BaseGroup=K;exports.BaseMesh=k;exports.BaseSprite=Je;exports.CircleMesh=Kt;exports.ClippingTool=ls;exports.EditableGeometryBatchLayer=Ps;exports.ExtrudeMesh=me;exports.INSTANCE_COLOR_MODE_NONE=he;exports.INSTANCE_COLOR_MODE_OVERRIDE=ne;exports.INSTANCE_COLOR_MODE_TINT=ct;exports.InstanceObject=bs;exports.LightManager=Ct;exports.MaterialEffects=W;exports.MeasureTool=hs;exports.Model=J;exports.ModelInstancedLayer=Vs;exports.ModelLoaderManager=U;exports.ObjectUtils=G;exports.PlaneMesh=Vt;exports.Poi=$t;exports.SBMLoader=Ye;exports.SBMXLoader=Xe;exports.SceneManager=Bt;exports.Selection=Et;exports.ShapeMesh=fe;exports.SphereMesh=Ze;exports.TSLEffects=ts;exports.TextureLoaderManager=Ft;exports.Topology=Ht;exports.TubeMesh=le;exports.Tween=ot;exports.isInstanceObject=xs;exports.reinterpretType=ss;exports.tweenAnimation=os;exports.version=mt;
16
+ `,t.labelStyle)for(const h of Object.keys(t.labelStyle)){const d=t.labelStyle[h];d!==void 0&&(r.style[h]=d)}let a=null;const c=t.labelOffset||{x:0,y:2,z:0};if(t.showLeaderLine!==!1){const{lineColor:h=16777215}=t,d=new o.BufferGeometry().setFromPoints([new o.Vector3(0,0,0),new o.Vector3(c.x,c.y,c.z)]),u=new o.LineBasicMaterial({color:h});a=new o.Line(d,u),s.add(a)}if(this._createCSSObject){const h=this._createCSSObject(r);h.position.set(c.x,c.y,c.z),s.add(h)}this.scene.add(s);const l={id:e,options:t,group:s,labelElement:r,line:a};return this.annotations.set(e,l),l}addText(e,t,s={}){const n=`annotation_${this._idCounter++}`;return this.add(n,{position:t,content:e,...s})}updateContent(e,t){const s=this.annotations.get(e);s&&(s.labelElement.innerHTML=t,s.options.content=t)}updatePosition(e,t){const s=this.annotations.get(e);s&&(s.group.position.set(t.x,t.y,t.z),s.options.position=t)}show(e){const t=this.annotations.get(e);t&&(t.group.visible=!0)}hide(e){const t=this.annotations.get(e);t&&(t.group.visible=!1)}get(e){return this.annotations.get(e)}remove(e){const t=this.annotations.get(e);if(t){const s=[...t.group.children];for(const n of s)t.group.remove(n),n.geometry?.dispose(),n.material?.dispose();this.scene.remove(t.group),this.annotations.delete(e)}}removeAll(){const e=Array.from(this.annotations.keys());for(const t of e)this.remove(t)}showAll(){for(const e of this.annotations.values())e.group.visible=!0}hideAll(){for(const e of this.annotations.values())e.group.visible=!1}keys(){return Array.from(this.annotations.keys())}get size(){return this.annotations.size}dispose(){this.removeAll()}}const Te=new o.Matrix4,vs=1e-6,Is=1e-6,De="uSpaceInstanceOriginalMaterialState",ye=0,ae=1,ft=2;function Cs(i){let e=i;for(;e;){if(!e.visible)return!1;e=e.parent}return!0}function Bs(i,e){const t=i.elements,s=e.elements;for(let n=0;n<16;n++)if(Math.abs(t[n]-s[n])>vs)return!1;return!0}function mt(i){const e=i.material;return Array.isArray(e)?e:[e]}function gt(i){const e=i.userData,t=e[De];if(t)return t;const s={transparent:i.transparent,opacity:i.opacity};return e[De]=s,s}function Os(i,e){i.traverse(t=>{const s=t;s.isMesh&&mt(s).forEach(n=>{if(!n)return;const r=n,a=gt(r),c=a.opacity*e;r.transparent=a.transparent||c<1,r.opacity=c,r.needsUpdate=!0})})}function As(i){i.traverse(e=>{const t=e;t.isMesh&&mt(t).forEach(s=>{if(!s)return;const n=s,r=gt(n);n.transparent=r.transparent,n.opacity=r.opacity,n.needsUpdate=!0})})}class _s extends q{isInstanceObject=!0;type="InstanceObject";instanceId="";instanceKind="";instanceName="";geometry=new o.BufferGeometry;boundingBox=null;boundingSphere=null;#s={color:null,colorMode:ye,opacity:1};#a=null;#t=null;#e=null;#r=null;#n=new Set;#o=new o.Matrix4;#c=!1;#l=!0;#d=!1;#u;constructor(e={}){super(),this.#u=e.boundsName??"InstanceBounds"}setInstanceIdentity(e){let t=!1;if(e.id!==void 0){const s=e.id??"";this.instanceId!==s&&(this.instanceId=s,t=!0)}if(e.kind!==void 0){const s=e.kind??"";this.instanceKind!==s&&(this.instanceKind=s,t=!0)}if(e.name!==void 0){const s=e.name??"";this.instanceName!==s&&(this.instanceName=s,t=!0)}return t&&this.markInstanceRenderDirty(),this}setInstanceBounds(e){if(e.isEmpty())return this;this.#t&&this.remove(this.#t);const t=new o.BufferGeometry;t.boundingBox=e.clone();const s=new o.Object3D;return s.name=this.#u,s.visible=!1,s.geometry=t,s.raycast=()=>{},this.#t=s,this.add(s),this.#h(),this.markInstanceRenderDirty(),this}setInstanceRenderObject(e){return this.#e&&this.#e!==e&&this.#e.parent===this&&this.remove(this.#e),this.#e=e,e&&e.parent!==this&&this.add(e),this.#f(),this.#h(),this.markInstanceRenderDirty(),this}getInstanceRenderObject(){return this.#e}setInstanceMaterializer(e){return this.#r=e,this}hasInstanceMaterializer(e){return this.#r===e}clearInstanceMaterializer(e){return(e===void 0||this.#r===e)&&(this.#r=null),this}materialize(){return this.#r?.()??this.#e??null}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new o.Box3),this.getInstanceBoundingBox(this.boundingBox,!1)}computeBoundingSphere(){if(this.boundingSphere===null&&(this.boundingSphere=new o.Sphere),this.boundingBox===null&&this.computeBoundingBox(),!this.boundingBox||this.boundingBox.isEmpty()){this.boundingSphere.makeEmpty();return}this.boundingBox.getBoundingSphere(this.boundingSphere)}getInstanceBoundingBox(e=new o.Box3,t=!1){const s=this.#t?.geometry?.boundingBox;return s?(e.copy(s),t&&(this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)),e):this.#e?(e.setFromObject(this.#e),t||(this.updateWorldMatrix(!0,!1),Te.copy(this.matrixWorld).invert(),e.applyMatrix4(Te)),e):e.makeEmpty()}setInstanceVisible(e){return this.visible===e?this:(this.visible=e,this.markInstanceRenderDirty(),this)}setInstanceColor(e){return this.#s.color=new o.Color(e),this.#s.colorMode=ae,this.#f(),this.markInstanceRenderDirty(),this}resetInstanceColor(){return this.#s.color===null?this:(this.#s.color=null,this.#s.colorMode=ye,this.#f(),this.markInstanceRenderDirty(),this)}setInstanceOpacity(e){const t=Math.max(0,Math.min(1,e));return Math.abs(this.#s.opacity-t)<=Is?this:(this.#s.opacity=t,this.#f(),this.markInstanceRenderDirty(),this)}getInstanceColor(e=new o.Color){const t=this.#p();return t.color?e.copy(t.color):e.setRGB(1,1,1)}hasInstanceColor(){return this.#p().color!==null}getInstanceOpacity(){return this.#p().opacity}setInstanceHighlight(e,t,s=!1){return this.#a={color:new o.Color(e),colorMode:s?ae:ft,opacity:Math.max(0,Math.min(1,t))},this.#f(),this.markInstanceRenderDirty(),this}clearInstanceHighlight(){return this.#a===null?this:(this.#a=null,this.#f(),this.markInstanceRenderDirty(),this)}getInstanceColorMode(){return this.#p().colorMode}onInstanceRenderDirty(e){return this.#n.add(e),()=>this.#n.delete(e)}markInstanceRenderDirty(){return this.#n.forEach(e=>e()),this}updateMatrixWorld(e){super.updateMatrixWorld(e),this.#i()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.#i()}#i(){const e=Cs(this);(!this.#c||!Bs(this.matrixWorld,this.#o)||!this.#d||e!==this.#l)&&(this.#c=!0,this.#d=!0,this.#o.copy(this.matrixWorld),this.#l=e,this.markInstanceRenderDirty())}#h(){this.boundingBox=null,this.boundingSphere=null}#p(){return this.#a??this.#s}#f(){if(!this.#e)return;const e=this.#p();if(e.color){As(this.#e),H.highlightColor(this.#e,{color:e.color,opacity:e.opacity,overwrite:e.colorMode===ae,multiplyOpacity:!0});return}H.removeHighlightColor(this.#e),Os(this.#e,e.opacity)}}function Ls(i){return i.isInstanceObject===!0}const Ts=new Set(["MeshBasicMaterial","MeshLambertMaterial","MeshPhongMaterial","MeshStandardMaterial","MeshPhysicalMaterial"]),Ne=new WeakMap;let Ds=1;const Re=new o.Matrix4,Z=new o.Matrix4,Pe=new o.Matrix4;function Ns(i,e,t=1e-6){const s=i.elements,n=e.elements;for(let r=0;r<16;r++)if(Math.abs(s[r]-n[r])>t)return!1;return!0}function yt(i){let e=i;for(;e;){if(!e.visible)return!1;e=e.parent}return!0}function Rs(i){const e=i.source.data;if(!e||typeof e!="object"&&typeof e!="function")return`texture:${i.uuid}`;let t=Ne.get(e);return t===void 0&&(t=Ds++,Ne.set(e,t)),`source:${t}`}function Ps(i){return JSON.stringify([Rs(i),i.mapping,i.channel,i.wrapS,i.wrapT,i.magFilter,i.minFilter,i.anisotropy,i.format,i.internalFormat,i.type,i.offset.toArray(),i.repeat.toArray(),i.center.toArray(),i.rotation,i.matrixAutoUpdate,i.matrix.toArray(),i.generateMipmaps,i.premultiplyAlpha,i.flipY,i.unpackAlignment,i.colorSpace,"compareFunction"in i?i.compareFunction:null])}function be(i){if(Array.isArray(i))return i.map(be);if(!i||typeof i!="object")return i;const e=i;return Object.fromEntries(Object.keys(e).sort().map(t=>[t,be(e[t])]))}function we(i,e){if(Array.isArray(i))return i.map(s=>we(s,e));if(!i||typeof i!="object")return typeof i=="string"?e.get(i)??i:i;const t=i;return Object.fromEntries(Object.keys(t).filter(s=>s!=="metadata"&&s!=="uuid"&&s!=="name").sort().map(s=>[s,we(t[s],e)]))}function ks(i){if(!Ts.has(i.type)||i.transparent||i.opacity<.999||i.visible===!1)return null;const e=i;if(Object.keys(e).some(r=>r.endsWith("Node")&&e[r]!=null)||Object.hasOwn(i,"onBeforeCompile"))return null;const t=new Map;Object.values(e).forEach(r=>{r instanceof o.Texture&&t.set(r.uuid,Ps(r))});const s={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},n=i.toJSON(s);return JSON.stringify(be(we(n,t)))}function js(i){if(Object.keys(i.morphAttributes).length>0||i.drawRange.start!==0||i.drawRange.count!==1/0)return null;const e=Object.entries(i.attributes).sort(([t],[s])=>t.localeCompare(s)).map(([t,s])=>"isInterleavedBufferAttribute"in s?null:[t,s.itemSize,s.normalized,s.array.constructor.name,s.gpuType]);return e.some(t=>t===null)?null:JSON.stringify([i.index?.array.constructor.name??"non-indexed",e])}function Us(i,e){const t=[],s=new Set,n=new Set,r=!e&&(i.animations.length>0||i.mixer!==null);return r&&n.add("animation"),i.updateWorldMatrix(!0,!0),Re.copy(i.matrixWorld).invert(),i.traverseVisible(a=>{if(!(a instanceof o.Mesh))return;if(r){s.add(a);return}if(a instanceof o.SkinnedMesh){s.add(a),n.add("skinned");return}if(a.morphTargetInfluences){s.add(a),n.add("morph");return}if(Array.isArray(a.material)){s.add(a),n.add("material-array");return}const c=ks(a.material),l=js(a.geometry);if(!c){s.add(a),n.add(a.material.transparent||a.material.opacity<.999?"transparent":`material:${a.material.type}`);return}if(!l){s.add(a),n.add("geometry-layout");return}if(a.matrixWorld.determinant()<=0){s.add(a),n.add("negative-scale");return}t.push({mesh:a,localMatrix:Re.clone().multiply(a.matrixWorld),materialKey:c,geometryKey:l})}),t.length===0&&s.size===0&&n.add("empty"),{meshes:t,fallbackMeshes:s,fallbackReasons:n}}function zs(i,e){const t=Me.clone(i),s=[],n=[];return i.traverse(r=>{r instanceof o.Mesh&&s.push(r)}),t.traverse(r=>{r instanceof o.Mesh&&n.push(r)}),s.forEach((r,a)=>{e.has(r)&&n[a]&&(n[a].visible=!1)}),t}function Fs(i){const e=Me.clone(i),t=new Map,s=n=>{let r=t.get(n);return r||(r=n.clone(),t.set(n,r)),r};return e.traverse(n=>{n instanceof o.Mesh&&(n.material=Array.isArray(n.material)?n.material.map(s):s(n.material))}),e}function Ws(i){return Math.max(1,Math.ceil(Math.sqrt(Math.max(1,i))))}function Gs(i){const e=new o.DataTexture(new Float32Array(i*i*4),i,i,o.RGBAFormat,o.FloatType);return e.magFilter=o.NearestFilter,e.minFilter=o.NearestFilter,e.generateMipmaps=!1,e.needsUpdate=!0,e}function Hs(i,e){const t=i.clone(),s=g.attribute("batchObjectIndex","float").toInt(),n=g.int(g.textureSize(g.textureLoad(e),g.int(0)).x).toConst(),r=s.mod(n).toConst(),a=s.div(n).toConst(),c=g.textureLoad(e,g.ivec2(r,a)),l=t.colorNode??g.materialColor,h=g.select(c.a.greaterThan(1.5),l.mul(c.rgb),c.rgb);return t.colorNode=g.select(c.a.greaterThan(.5),h,l),t.maskNode=c.a.greaterThan(-.5),t.needsUpdate=!0,t}function ke(i){let e=0,t=i.parent;for(;t;)e++,t=t.parent;return e}class $s extends F{objectIndices;states;#s;constructor(e,t,s,n){super(e,t),this.objectIndices=s,this.states=n,this.userData.editableGeometryBatch=!0}raycast(e,t){if(this.visible===!1&&this.ignoreInvisibleWhenRaycast===!0)return!1;this.#s===void 0&&(this.#s=j.getGeometryBoundsTree(this.geometry));const s=[];this.#s?this.#s.raycastObject3D(this,e,s):super.raycast(e,s),s.forEach(n=>{const r=n.faceIndex;if(r==null)return;const a=r*3,c=this.geometry.index?.getX(a)??a,l=this.objectIndices[c],h=l===void 0?void 0:this.states[l],d=h?.instance;!h||h.materialized||!d||!yt(d)||d.getInstanceOpacity()<=.001||(n.object=d,n.batchObjectIndex=l,t.push(n))})}}class Vs extends q{isEditableGeometryBatchLayer=!0;type="EditableGeometryBatchLayer";options;stats={instances:0,sourceMeshes:0,batches:0,drawCallsSaved:0,vertices:0,indices:0,unsupportedInstances:0,unsupportedByReason:{}};#s=[];#a=new Set;#t=[];#e=new Map;#r=new Set;#n=null;#o=new o.Matrix4;#c=!1;#l=!1;#d=!1;constructor(e={}){super(),this.name="EditableGeometryBatches",this.options={maxVerticesPerBatch:e.maxVerticesPerBatch??15e5,maxIndicesPerBatch:e.maxIndicesPerBatch??45e5,freezeAnimations:e.freezeAnimations??!1}}addSource(e){if(this.#l)throw new Error("EditableGeometryBatchLayer has been disposed.");if(this.#c)throw new Error("EditableGeometryBatchLayer has already been built.");const{key:t,template:s,instances:n}=e,r=new Set;n.forEach(h=>{if(r.has(h)||this.#a.has(h))throw new Error("EditableGeometryBatchLayer cannot batch the same InstanceObject more than once.");r.add(h)});const{meshes:a,fallbackMeshes:c,fallbackReasons:l}=Us(s,this.options.freezeAnimations);return r.forEach(h=>this.#a.add(h)),this.#s.push({key:t,template:s,instances:[...n],meshes:a,fallbackMeshes:c,fallbackReasons:l,bounds:new o.Box3().setFromObject(s)}),a.length>0}build(){if(this.#l)throw new Error("EditableGeometryBatchLayer has been disposed.");if(this.#c)throw new Error("EditableGeometryBatchLayer.build() can only be called once.");this.#c=!0,this.updateWorldMatrix(!0,!1),this.#o.copy(this.matrixWorld).invert();const e=[],t=new Map,s=(r,a,c,l)=>{if(c.length===0)return;const h=l.size>0?[...l]:["unknown"];e.push({key:r.key,template:a,instances:c,reasons:h}),h.forEach(d=>{this.stats.unsupportedByReason[d]=(this.stats.unsupportedByReason[d]??0)+c.length})};this.#s.forEach(r=>{const a=[],c=[];r.instances.forEach(h=>{h.updateWorldMatrix(!0,!1),Z.multiplyMatrices(this.#o,h.matrixWorld),Z.determinant()<=0?c.push(h):a.push({instance:h,matrix:Z.clone()})});const l=r.fallbackReasons.size>0?r.fallbackReasons:new Set(["unknown"]);if(r.meshes.length===0){s(r,r.template,a.map(({instance:h})=>h),l),s(r,r.template,c,new Set([...l,"negative-scale"]));return}r.fallbackMeshes.size>0&&s(r,zs(r.template,new Set(r.meshes.map(({mesh:h})=>h))),a.map(({instance:h})=>h),l),s(r,r.template,c,new Set([...r.fallbackReasons,"negative-scale"])),a.forEach(({instance:h,matrix:d})=>{const u=this.#t.length,p=()=>this.materialize(h),f={instance:h,template:r.template,initialMatrix:d,objectIndex:u,materialized:!1,materializer:p,unsubscribe:()=>{}};f.unsubscribe=h.onInstanceRenderDirty(()=>this.#h(f)),this.#t.push(f),this.#e.set(h,f),h.setInstanceBounds(r.bounds),h.setInstanceMaterializer(p),this.#r.add(f),r.meshes.forEach(({mesh:S,localMatrix:C,materialKey:D,geometryKey:O})=>{Pe.multiplyMatrices(d,C);const w=S.geometry.clone().applyMatrix4(Pe),x=w.getAttribute("position");w.setAttribute("batchObjectIndex",new o.Float32BufferAttribute(new Float32Array(x.count).fill(u),1));const b=JSON.stringify([D,O,S.castShadow,S.receiveShadow,S.renderOrder]),y=t.get(b),E={geometry:w,material:S.material,castShadow:S.castShadow,receiveShadow:S.receiveShadow,renderOrder:S.renderOrder,objectIndices:new Array(x.count).fill(u)};y?y.push(E):t.set(b,[E]),this.stats.sourceMeshes++,this.stats.vertices+=x.count,this.stats.indices+=w.index?.count??x.count})})}),this.stats.instances=this.#t.length,this.stats.unsupportedInstances=e.reduce((r,a)=>r+a.instances.length,0);const n=Ws(this.#t.length);return this.#n=Gs(n),this.#i(),t.forEach(r=>this.#u(r)),this.stats.batches=this.children.length,this.stats.drawCallsSaved=Math.max(0,this.stats.sourceMeshes-this.stats.batches),this.children.forEach(r=>{r instanceof o.Mesh&&(r.onBeforeRender=()=>this.#i())}),{stats:{...this.stats},unsupported:e}}materialize(e){const t=this.#e.get(e);if(!t||t.materialized)return e.getInstanceRenderObject();const s=Fs(t.template);return s.position.set(0,0,0),s.quaternion.identity(),s.scale.set(1,1,1),s.matrix.identity(),t.materialized=!0,e.setInstanceRenderObject(s),s.updateWorldMatrix(!0,!0),this.#r.add(t),this.dispatchEvent({type:"materialize",instance:e,object:s}),s}#u(e){const t=[];let s=[],n=0,r=0;e.forEach(a=>{const c=a.geometry.getAttribute("position").count,l=a.geometry.index?.count??c;s.length>0&&(n+c>this.options.maxVerticesPerBatch||r+l>this.options.maxIndicesPerBatch)&&(t.push(s),s=[],n=0,r=0),s.push(a),n+=c,r+=l}),s.length>0&&t.push(s),t.forEach(a=>{const c=Ot.mergeGeometries(a.map(p=>p.geometry),!1);if(a.forEach(p=>p.geometry.dispose()),!c||!this.#n)return;c.computeBoundingBox(),c.computeBoundingSphere();const l=a[0],h=a.flatMap(p=>p.objectIndices),d=Hs(l.material,this.#n),u=new $s(c,d,h,this.#t);u.name=`EditableGeometryBatch:${this.children.length}`,u.castShadow=l.castShadow,u.receiveShadow=l.receiveShadow,u.renderOrder=l.renderOrder,u.matrixAutoUpdate=!1,this.add(u)})}#i(){if(!(!this.#n||this.#r.size===0||this.#d)){this.#d=!0;try{this.updateWorldMatrix(!0,!1),this.#o.copy(this.matrixWorld).invert();const e=this.#n.image.data;[...this.#r].sort((t,s)=>ke(t.instance)-ke(s.instance)).forEach(t=>{const{instance:s,objectIndex:n}=t;s.updateWorldMatrix(!0,!1),Z.multiplyMatrices(this.#o,s.matrixWorld),!t.materialized&&s.getInstanceRenderObject()!==null&&!s.hasInstanceMaterializer(t.materializer)&&(t.materialized=!0),!t.materialized&&!Ns(Z,t.initialMatrix)&&this.materialize(s),!t.materialized&&s.getInstanceOpacity()<.999&&this.materialize(s);const r=n*4,a=!t.materialized&&yt(s)&&s.getInstanceOpacity()>.001,c=s.getInstanceColor();e[r]=c.r,e[r+1]=c.g,e[r+2]=c.b,e[r+3]=a?s.getInstanceColorMode():-1,this.#r.delete(t)}),this.#n.needsUpdate=!0}finally{this.#d=!1}this.#r.size>0&&this.#i()}}#h(e){this.#r.add(e),this.#i()}dispose(){this.#l||(this.#l=!0,this.#t.forEach(e=>{e.unsubscribe(),e.instance.clearInstanceMaterializer(e.materializer)}),this.#t.length=0,this.#e.clear(),this.#a.clear(),this.#r.clear(),this.#s.length=0,this.#n?.dispose(),this.#n=null,this.traverse(e=>{if(!(e instanceof o.Mesh))return;e.geometry.dispose(),(Array.isArray(e.material)?e.material:[e.material]).forEach(s=>s.dispose())}),this.clear())}}const je=new o.Matrix4,re=new o.Matrix4,Ue=new o.Matrix4,ze=new o.Matrix4,Fe=new o.Box3,We=new o.Sphere,Ge=new o.Sphere,Ks=new o.Frustum,V=new o.Color,He=new o.Vector2,$e=new o.Vector3,Ve=new o.Matrix4,Ke=new o.Matrix4,qe=new o.Sphere,ie=[],bt=1e-6,U=1e-6,wt=.999,qs=0,Xe=1;function Xs(i,e,t){const s=i.elements;for(let n=0;n<16;n++)if(Math.abs(s[n]-e[t+n])>bt)return!1;return!0}function Ys(i,e,t,s){return Math.abs(i.r-t[s])<=U&&Math.abs(i.g-t[s+1])<=U&&Math.abs(i.b-t[s+2])<=U&&Math.abs(e-t[s+3])<=U}function Ye(i,e){const t=i.elements,s=e.elements;for(let n=0;n<16;n++)if(Math.abs(t[n]-s[n])>bt)return!1;return!0}function ue(i){let e=i;for(;e;){if(!e.visible)return!1;e=e.parent}return!0}function Qs(i){const e=i.geometry.morphAttributes;return Object.values(e).some(t=>t?.length)}function Js(i){const e=i.material;if(!Array.isArray(e))return!0;if(e.length===0||!e.every(Boolean))return!1;const t=i.geometry.groups;return t.length===0?!1:t.every(s=>{const n=s.materialIndex??0;return Number.isInteger(s.start)&&s.start>=0&&Number.isInteger(s.count)&&s.count>0&&Number.isInteger(n)&&n>=0&&n<e.length})}function Zs(i){return!i.isSkinnedMesh&&!Qs(i)&&Js(i)}function Qe(i){return Array.isArray(i)?i:[i]}function Mt(i){return i.transparent||i.opacity<wt}function Je(i,e,t){const s=i.clone(),n=g.instancedBufferAttribute(e,"vec4",4,0),r=g.instancedBufferAttribute(t,"float",1,0),a=s.colorNode??g.materialColor,c=s.opacityNode?g.float(s.opacityNode):g.materialOpacity,l=g.select(n.a.greaterThan(1.5),a.mul(n.rgb),n.rgb);return s.colorNode=g.select(n.a.greaterThan(.5),l,a),s.opacityNode=c.mul(r),s.transparent=Mt(i),s.needsUpdate=!0,s}function en(i,e,t){return Array.isArray(i)?i.map(s=>Je(s,e,t)):Je(i,e,t)}function tn(i){const e=[],t=new o.Matrix4;let s=!1;return i.updateWorldMatrix(!0,!0),t.copy(i.matrixWorld).invert(),i.traverse(n=>{if(!s&&!(!(n instanceof o.Mesh)||!n.visible)){if(!Zs(n)){s=!0;return}n.updateWorldMatrix(!0,!1),e.push({mesh:n,localMatrix:t.clone().multiply(n.matrixWorld)})}}),s?[]:e}function sn(i){const e=new o.Box3;return i.forEach(({mesh:t,localMatrix:s})=>{const n=t.geometry;n.boundingBox||n.computeBoundingBox(),n.boundingBox&&(Fe.copy(n.boundingBox).applyMatrix4(s),e.union(Fe))}),e}function K(i){const e=i;"needsUpdate"in e&&(e.needsUpdate=!0)}function Ze(i,e=Xe){let t=Math.max(Xe,e);for(;t<i;)t*=2;return t}function nn(i){return i!==null&&typeof i=="object"&&Symbol.iterator in i}class rn extends q{isModelInstancedLayer=!0;type="ModelInstancedLayer";#s=[];#a=new Map;#t=new Map;#e=new Map;#r=!0;#n=!1;#o=!0;#c=qs;#l;#d;constructor(e={}){super(),this.name=e.name??"ModelInstances",this.#l=e.instanceKind??"",this.#d=e.getHitUserData??(()=>({}))}get instanceKind(){return this.#l}getInstances(){const e=[];return this.#i(t=>e.push(t)),e}getInstanceById(e){return this.#w(),this.#e.get(e)}hasInstance(e){return this.#w(),this.#e.has(e)}getInstanceCulling(){return{enabled:this.#n,frustum:this.#o,minScreenRadius:this.#c}}setInstanceCulling(e={}){let t=!1;if(e.enabled!==void 0&&this.#n!==e.enabled&&(this.#n=e.enabled,t=!0),e.frustum!==void 0&&this.#o!==e.frustum&&(this.#o=e.frustum,t=!0),e.minScreenRadius!==void 0){const s=Math.max(0,e.minScreenRadius);Math.abs(this.#c-s)>U&&(this.#c=s,t=!0)}return t&&this.#s.forEach(s=>this.#v(s)),this}setInstanceVisible(e){return this.visible!==e&&(this.visible=e),this.#i(t=>{t.setInstanceVisible(e)}),this}setInstanceColor(e){return this.#i(t=>{t.setInstanceColor(e)}),this}resetInstanceColor(){return this.#i(e=>{e.resetInstanceColor()}),this}setInstanceOpacity(e){return this.#i(t=>{t.setInstanceOpacity(e)}),this}setInstanceHighlight(e,t,s=!1){return this.#i(n=>{n.setInstanceHighlight(e,t,s)}),this}clearInstanceHighlight(){return this.#i(e=>{e.clearInstanceHighlight()}),this}reserveBatch(e,t,s){const n=Math.floor(s);return n<=0?!1:this.#u(e,t,n)!==null}addInstance(e,t,s){return this.addInstances(e,t,[s])}addInstances(e,t,s){if(s.length===0)return!1;const n=this.#a.has(e),r=this.#u(e,t,s.length);if(!r)return!1;const a=[],c=new Set;return s.forEach(l=>{c.has(l)||(c.add(l),this.#t.get(l)===r)||a.push(l)}),a.length===0?!0:this.#C(a)?(a.forEach(l=>{const h=this.#t.get(l);h&&h!==r&&this.#S(h,l)}),this.#x(r,r.instances.length+a.length),a.forEach(l=>{l.setInstanceBounds(r.templateBounds),r.instances.push(l),this.#t.set(l,r),r.unsubscribeByInstance.set(l,l.onInstanceRenderDirty(()=>{this.#g(),this.#y(r)}))}),this.#g(),this.#b(r),this.#y(r),!0):(!n&&r.instances.length===0&&this.#m(r),!1)}removeInstance(e){return this.removeInstances([e])>0}removeInstances(e){const t=new Set,s=new Set,n=typeof e=="string"||!nn(e)?[e]:e;for(const a of n)typeof a=="string"?t.add(a):this.#t.has(a)&&s.add(a);t.size>0&&(this.#w(),t.forEach(a=>{const c=this.#e.get(a);c&&s.add(c)}));let r=0;return s.forEach(a=>{const c=this.#t.get(a);c&&this.#S(c,a)&&r++}),r}removeBatch(e){const t=this.#a.get(e);return t?(this.#m(t),!0):!1}clearBatches(){return[...this.#a.values()].forEach(e=>this.#m(e)),this}#u(e,t,s){const n=this.#a.get(e);if(n)return this.#x(n,s),n;if(t.animations?.length)return null;const r=tn(t);if(r.length===0)return null;const a=sn(r),c=new o.Group;c.name=e,this.add(c);const l={url:e,batch:c,templateMeshes:r,templateBounds:a,records:[],instances:[],unsubscribeByInstance:new Map,capacity:Ze(s)};return r.forEach(({mesh:h,localMatrix:d},u)=>{const p=this.#h(l,h,d,u);l.records.push(p),this.#s.push(p)}),this.#a.set(e,l),this.#b(l),l}#i(e){const t=new Set;this.#a.forEach(s=>{s.instances.forEach(n=>{t.has(n)||(t.add(n),e(n))})})}#h(e,t,s,n){const r=new o.InstancedBufferAttribute(new Float32Array(e.capacity*4),4),a=new o.InstancedBufferAttribute(new Float32Array(e.capacity).fill(1),1);r.setUsage(o.DynamicDrawUsage),a.setUsage(o.DynamicDrawUsage);const c=en(t.material,r,a),l=Qe(c),h=Qe(t.material).some(Mt),d=new o.InstancedMesh(t.geometry,c,e.capacity);d.instanceMatrix=new o.StorageInstancedBufferAttribute(e.capacity,16),d.count=0,d.name=t.name||`${e.url}#${n}`,d.castShadow=t.castShadow,d.receiveShadow=t.receiveShadow,d.frustumCulled=!0,d.matrixAutoUpdate=!1,d.instanceMatrix.setUsage(o.DynamicDrawUsage),d.userData.url=e.url;const u=new o.Mesh(t.geometry,c);u.matrixAutoUpdate=!1;const p={batchRecord:e,mesh:d,boundsTree:void 0,raycastMesh:u,localMatrix:s.clone(),fullBoundingSphere:new o.Sphere,materials:l,hasSourceTransparency:h,colorAttribute:r,opacityAttribute:a,renderedInstances:[],visibleInstances:[],lastCameraMatrixWorldInverse:new o.Matrix4,lastCameraProjectionMatrix:new o.Matrix4,lastViewportHeight:0,hasLastCameraState:!1,dirty:!0};d.userData.getInstanceObjectByRenderIndex=S=>p.renderedInstances[S],d.userData.raycastAcceleration="lazy";const f=d.raycast.bind(d);return d.raycast=(S,C)=>{if(this.#I(p),!this.#p(p,S))return;p.boundsTree===void 0&&(p.boundsTree=j.getGeometryBoundsTree(p.mesh.geometry),p.mesh.userData.raycastAcceleration=p.boundsTree?"three-mesh-bvh":"default");const D=C.length;p.boundsTree?this.#f(p,S,C):f(S,C);for(let O=D;O<C.length;){const w=C[O],x=w.instanceId;if(x===void 0){O++;continue}const b=p.renderedInstances[x];if(!b||!ue(b)){C.splice(O,1);continue}w.object=b,w.instanceObject=b,w.instanceObjectId=b.instanceId,w.instanceKind=b.instanceKind||this.#l,w.instanceName=b.instanceName,w.instanceIndex=x,Object.assign(w,this.#d(b,x)),O++}},d.onBeforeRender=(S,C,D)=>this.#I(p,S,D),e.batch.add(d),p}#p(e,t){const{mesh:s}=e;return s.count===0?!1:(s.boundingSphere===null&&s.computeBoundingSphere(),s.boundingSphere?(qe.copy(s.boundingSphere).applyMatrix4(s.matrixWorld),t.ray.intersectsSphere(qe)):!0)}#f(e,t,s){const{mesh:n,boundsTree:r,raycastMesh:a}=e;if(!(!r||n.count===0)){a.geometry=n.geometry,a.material=n.material;for(let c=0;c<n.count;c++)n.getMatrixAt(c,Ve),Ke.multiplyMatrices(n.matrixWorld,Ve),a.matrixWorld.copy(Ke),ie.length=0,r.raycastObject3D(a,t,ie),ie.forEach(l=>{l.instanceId=c,l.object=n,s.push(l)}),ie.length=0}}#x(e,t){if(t<=e.capacity)return;e.capacity=Ze(t,e.capacity);const s=new Set(e.records);s.forEach(n=>this.#E(n)),this.#s=this.#s.filter(n=>!s.has(n)),e.records=e.templateMeshes.map(({mesh:n,localMatrix:r},a)=>{const c=this.#h(e,n,r,a);return this.#s.push(c),c}),this.#y(e)}#S(e,t){const s=e.instances.indexOf(t);return s===-1?!1:(e.instances.splice(s,1),e.records.forEach(n=>n.visibleInstances.splice(s,1)),this.#t.delete(t),this.#g(),e.unsubscribeByInstance.get(t)?.(),e.unsubscribeByInstance.delete(t),e.instances.length===0?(this.#m(e),!0):(this.#b(e),this.#y(e),!0))}#m(e){e.unsubscribeByInstance.forEach(s=>s()),e.instances.forEach(s=>this.#t.delete(s)),e.unsubscribeByInstance.clear(),e.instances.length=0,this.#g();const t=new Set(e.records);t.forEach(s=>this.#E(s)),this.#s=this.#s.filter(s=>!t.has(s)),e.records.length=0,e.templateMeshes.length=0,this.#a.delete(e.url),this.remove(e.batch)}#E(e){e.batchRecord.batch.remove(e.mesh),e.mesh.dispose(),e.materials.forEach(t=>t.dispose())}#b(e){Object.assign(e.batch.userData,{url:e.url,count:e.instances.length,capacity:e.capacity,instanceKind:this.#l}),delete e.batch.userData.sceneInstances,delete e.batch.userData.facilities,e.records.forEach(t=>{delete t.mesh.userData.instances})}#C(e){const t=new Set(e),s=new Map;for(const r of e){const{instanceId:a}=r;if(!a)continue;const c=s.get(a);if(c&&c!==r)return!1;s.set(a,r)}let n=!0;return s.forEach((r,a)=>{n&&this.#i(c=>{!n||t.has(c)||c.instanceId===a&&(n=!1)})}),n}#w(){if(!this.#r)return;this.#e.clear();const e=new Set;this.#i(t=>{const{instanceId:s}=t;if(!s||e.has(s))return;const n=this.#e.get(s);if(n&&n!==t){this.#e.delete(s),e.add(s);return}this.#e.set(s,t)}),this.#r=!1}#g(){this.#r=!0}#y(e){e.records.forEach(t=>this.#v(t))}#v(e){e.dirty=!0,e.hasLastCameraState=!1,e.mesh.visible=!0,e.mesh.frustumCulled=!1,K(e.batchRecord.batch)}#I(e,t,s){const n=this.#O(t),r=this.#A(e,s,n);!e.dirty&&!this.#B(e)&&!r||this.#D(e,s,n)}#B(e){const{instances:t}=e.batchRecord;for(let s=0;s<t.length;s++)if(e.visibleInstances[s]!==ue(t[s]))return e.dirty=!0,K(e.batchRecord.batch),!0;return!1}#O(e){return e?.getDrawingBufferSize?(e.getDrawingBufferSize(He),He.y):0}#A(e,t,s){return this.#M(t,s)?e.hasLastCameraState?!Ye(e.lastCameraMatrixWorldInverse,t.matrixWorldInverse)||!Ye(e.lastCameraProjectionMatrix,t.projectionMatrix)||Math.abs(e.lastViewportHeight-s)>U:!0:!1}#M(e,t){return this.#n&&e!==void 0&&(this.#o||this.#c>0&&t>0)}#_(e,t){if(!this.#M(e,t))return null;let s=null;return this.#o&&(ze.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),s=Ks.setFromProjectionMatrix(ze)),{camera:e,frustum:s,viewportHeight:t}}#L(e,t){return t?t.frustum&&!t.frustum.intersectsSphere(e)?!1:this.#c<=0||t.viewportHeight<=0?!0:this.#T(e,t.camera,t.viewportHeight)>=this.#c:!0}#T(e,t,s){const n=Math.abs(t.projectionMatrix.elements[5]);if(n<=U)return 1/0;if(t.isOrthographicCamera)return e.radius*n*s*.5;$e.copy(e.center).applyMatrix4(t.matrixWorldInverse);const r=-$e.z;return r<=U?1/0:e.radius*n*s*.5/r}#D(e,t,s=0){this.updateWorldMatrix(!0,!1),je.copy(this.matrixWorld).invert();const n=e.mesh.instanceMatrix.array,r=e.colorAttribute.array,a=e.opacityAttribute.array,c=e.mesh.geometry;let l=!1,h=!1,d=!1,u=0,p=0,f=!1;const S=e.mesh.count,C=this.#_(t,s);c.boundingSphere||c.computeBoundingSphere(),e.fullBoundingSphere.makeEmpty(),e.renderedInstances.length=0,e.batchRecord.instances.forEach((w,x)=>{const b=ue(w);e.visibleInstances[x]=b,w.updateWorldMatrix(!0,!1),re.multiplyMatrices(je,w.matrixWorld).multiply(e.localMatrix);const y=w.getInstanceOpacity();if(!(b&&y>U)||(p++,c.boundingSphere&&(We.copy(c.boundingSphere).applyMatrix4(re),e.fullBoundingSphere.union(We),C&&(Ue.multiplyMatrices(w.matrixWorld,e.localMatrix),Ge.copy(c.boundingSphere).applyMatrix4(Ue),!this.#L(Ge,C)))))return;const M=u,I=M*16;Xs(re,n,I)||(e.mesh.setMatrixAt(M,re),l=!0),V.copy(w.getInstanceColor(V));const A=w.getInstanceColorMode(),v=M*4;Ys(V,A,r,v)||(e.colorAttribute.setXYZW(M,V.r,V.g,V.b,A),h=!0),y<wt&&(f=!0),Math.abs(y-a[M])>U&&(e.opacityAttribute.setX(M,y),d=!0),e.renderedInstances[M]=w,u++}),e.mesh.count=u,S!==u&&(l=!0,h=!0,d=!0,K(e.batchRecord.batch));const D=p>0;e.mesh.visible!==D&&(e.mesh.visible=D,K(e.batchRecord.batch)),e.mesh.frustumCulled!==!0&&(e.mesh.frustumCulled=!0,K(e.batchRecord.batch)),l&&(e.mesh.instanceMatrix.needsUpdate=!0),h&&(e.colorAttribute.needsUpdate=!0),d&&(e.opacityAttribute.needsUpdate=!0),e.mesh.boundingSphere===null&&(e.mesh.boundingSphere=new o.Sphere),e.mesh.boundingSphere.copy(e.fullBoundingSphere);const O=e.hasSourceTransparency||f;e.materials.forEach(w=>{w.transparent!==O&&(w.transparent=O,w.needsUpdate=!0,K(e.batchRecord.batch))}),t&&this.#M(t,s)?(e.lastCameraMatrixWorldInverse.copy(t.matrixWorldInverse),e.lastCameraProjectionMatrix.copy(t.projectionMatrix),e.lastViewportHeight=s,e.hasLastCameraState=!0):e.hasLastCameraState=!1,e.dirty=!1}}const xt="0.0.31";typeof window<"u"&&(window.__USPACE__={version:xt});exports.CSSRenderer=j.CSSRenderer;exports.CameraControls=j.CameraControls;exports.InteractionEvent=j.InteractionEvent;exports.InteractionManager=j.InteractionManager;exports.ObjectManager=j.ObjectManager;exports.RenderPipeline=j.RenderPipeline;exports.RoomEnvironment=j.RoomEnvironment;exports.Viewer=j.Viewer;exports.enableMeshBVHRaycast=j.enableMeshBVHRaycast;exports.getGeometryBoundsTree=j.getGeometryBoundsTree;Object.defineProperty(exports,"CSS2DObject",{enumerable:!0,get:()=>At.CSS2DObject});Object.defineProperty(exports,"CSS3DObject",{enumerable:!0,get:()=>et.CSS3DObject});Object.defineProperty(exports,"CSS3DSprite",{enumerable:!0,get:()=>et.CSS3DSprite});exports.AnnotationManager=Es;exports.BaseGroup=q;exports.BaseMesh=F;exports.BaseSprite=rt;exports.CircleMesh=is;exports.ClippingTool=xs;exports.EditableGeometryBatchLayer=Vs;exports.ExtrudeMesh=Se;exports.INSTANCE_COLOR_MODE_NONE=ye;exports.INSTANCE_COLOR_MODE_OVERRIDE=ae;exports.INSTANCE_COLOR_MODE_TINT=ft;exports.InstanceObject=_s;exports.LightManager=Tt;exports.MaterialEffects=H;exports.MeasureTool=Ss;exports.Model=G;exports.ModelDecodeWorkerClient=nt;exports.ModelDecodeWorkerUnavailableError=te;exports.ModelInstancedLayer=rn;exports.ModelLoaderManager=z;exports.ObjectUtils=W;exports.PlaneMesh=rs;exports.Poi=ns;exports.SBMLoader=me;exports.SBMXLoader=fe;exports.SceneManager=Lt;exports.Selection=_t;exports.ShapeMesh=xe;exports.SphereMesh=it;exports.TSLEffects=ps;exports.TextureLoaderManager=ts;exports.Topology=ss;exports.TubeMesh=ge;exports.Tween=pt;exports.isInstanceObject=Ls;exports.reinterpretType=fs;exports.reuseDecodedImageContent=st;exports.tweenAnimation=ws;exports.version=xt;