selva-compute 1.2.0 → 1.3.0

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.
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkQCHPQ22Ycjs = require('./chunk-QCHPQ22Y.cjs');var _chunkPE2FMBXDcjs = require('./chunk-PE2FMBXD.cjs');var _three = require('three'); var i = _interopRequireWildcard(_three); var w = _interopRequireWildcard(_three); var u = _interopRequireWildcard(_three); var b = _interopRequireWildcard(_three);var _OrbitControlsjs = require('three/addons/controls/OrbitControls.js');var _HDRLoaderjs = require('three/addons/loaders/HDRLoader.js');var G=new i.Vector3(0,0,1),U= exports.initThree =function(e,r){let t=ne(r||{}),n=re(t),o=fe(t,e),s=de(e,t),a=me(o,e,t);ie(n,t),ce(n,t),_optionalChain([t, 'access', _2 => _2.floor, 'optionalAccess', _3 => _3.enabled])&&le(n,t);let l=t.events.enableEventHandlers!==!1?he(e,n,o,a,t):{dispose:()=>{},fitToView:()=>{},clearSelection:()=>{}},{resize:c,dispose:R}=ae(e,s,o),{animate:m,dispose:h}=se(s,n,o,a);m();let E=_optionalChain([t, 'access', _4 => _4.environment, 'optionalAccess', _5 => _5.sceneUp])||G;return n.up.set(E.x,E.y,E.z),{scene:n,camera:o,controls:a,renderer:s,dispose:()=>{h(),R(),l.dispose(),a.dispose(),s.dispose(),n.traverse(f=>{f instanceof i.Mesh&&(_optionalChain([f, 'access', _6 => _6.geometry, 'optionalAccess', _7 => _7.dispose, 'call', _8 => _8()]),Array.isArray(f.material)?f.material.forEach(H=>H.dispose()):_optionalChain([f, 'access', _9 => _9.material, 'optionalAccess', _10 => _10.dispose, 'call', _11 => _11()]))})},resize:c,fitToView:l.fitToView,clearSelection:l.clearSelection}};function ne(e){let r=e.sceneScale||"m",n={mm:{cameraDistance:20,near:.1,far:2e3,floorSize:100,lightDistance:10,lightHeight:20,minDistance:.1,shadowSize:100,scaleFactor:1e3},cm:{cameraDistance:20,near:.1,far:2e3,floorSize:100,lightDistance:25,lightHeight:50,minDistance:.1,shadowSize:100,scaleFactor:100},m:{cameraDistance:10,near:.01,far:2e3,floorSize:50,lightDistance:25,lightHeight:50,minDistance:.001,shadowSize:100,scaleFactor:1},inches:{cameraDistance:15,near:.1,far:2e3,floorSize:80,lightDistance:20,lightHeight:40,minDistance:.1,shadowSize:80,scaleFactor:39.37},feet:{cameraDistance:8,near:.1,far:2e3,floorSize:40,lightDistance:15,lightHeight:30,minDistance:.1,shadowSize:60,scaleFactor:3.28084}}[r];return{sceneScale:r,camera:{position:_optionalChain([e, 'access', _12 => _12.camera, 'optionalAccess', _13 => _13.position])||new i.Vector3(-n.cameraDistance,n.cameraDistance,n.cameraDistance),fov:_optionalChain([e, 'access', _14 => _14.camera, 'optionalAccess', _15 => _15.fov])||20,near:_optionalChain([e, 'access', _16 => _16.camera, 'optionalAccess', _17 => _17.near])||n.near,far:_optionalChain([e, 'access', _18 => _18.camera, 'optionalAccess', _19 => _19.far])||n.far,target:_optionalChain([e, 'access', _20 => _20.camera, 'optionalAccess', _21 => _21.target])||new i.Vector3(0,0,0)},lighting:{enableSunlight:_nullishCoalesce(_optionalChain([e, 'access', _22 => _22.lighting, 'optionalAccess', _23 => _23.enableSunlight]), () => (!0)),sunlightIntensity:_optionalChain([e, 'access', _24 => _24.lighting, 'optionalAccess', _25 => _25.sunlightIntensity])||1,sunlightPosition:_optionalChain([e, 'access', _26 => _26.lighting, 'optionalAccess', _27 => _27.sunlightPosition])||new i.Vector3(n.lightDistance,n.lightHeight,n.lightDistance),ambientLightColor:_optionalChain([e, 'access', _28 => _28.lighting, 'optionalAccess', _29 => _29.ambientLightColor])||new i.Color(4210752),ambientLightIntensity:_optionalChain([e, 'access', _30 => _30.lighting, 'optionalAccess', _31 => _31.ambientLightIntensity])||1,sunlightColor:_optionalChain([e, 'access', _32 => _32.lighting, 'optionalAccess', _33 => _33.sunlightColor])||16777215},environment:{hdrPath:_optionalChain([e, 'access', _34 => _34.environment, 'optionalAccess', _35 => _35.hdrPath])||"/baseHDR.hdr",backgroundColor:_optionalChain([e, 'access', _36 => _36.environment, 'optionalAccess', _37 => _37.backgroundColor])||new i.Color(15790320),enableEnvironmentLighting:_nullishCoalesce(_optionalChain([e, 'access', _38 => _38.environment, 'optionalAccess', _39 => _39.enableEnvironmentLighting]), () => (!0)),sceneUp:_optionalChain([e, 'access', _40 => _40.environment, 'optionalAccess', _41 => _41.sceneUp])||G,showEnvironment:_nullishCoalesce(_optionalChain([e, 'access', _42 => _42.environment, 'optionalAccess', _43 => _43.showEnvironment]), () => (!1))},floor:{enabled:_nullishCoalesce(_optionalChain([e, 'access', _44 => _44.floor, 'optionalAccess', _45 => _45.enabled]), () => (!1)),size:_optionalChain([e, 'access', _46 => _46.floor, 'optionalAccess', _47 => _47.size])||n.floorSize,color:_optionalChain([e, 'access', _48 => _48.floor, 'optionalAccess', _49 => _49.color])||new i.Color(8421504),roughness:_optionalChain([e, 'access', _50 => _50.floor, 'optionalAccess', _51 => _51.roughness])||.7,metalness:_optionalChain([e, 'access', _52 => _52.floor, 'optionalAccess', _53 => _53.metalness])||0,receiveShadow:_nullishCoalesce(_optionalChain([e, 'access', _54 => _54.floor, 'optionalAccess', _55 => _55.receiveShadow]), () => (!0))},render:{enableShadows:_nullishCoalesce(_optionalChain([e, 'access', _56 => _56.render, 'optionalAccess', _57 => _57.enableShadows]), () => (!0)),shadowMapSize:_optionalChain([e, 'access', _58 => _58.render, 'optionalAccess', _59 => _59.shadowMapSize])||2048,antialias:_nullishCoalesce(_optionalChain([e, 'access', _60 => _60.render, 'optionalAccess', _61 => _61.antialias]), () => (!0)),pixelRatio:_optionalChain([e, 'access', _62 => _62.render, 'optionalAccess', _63 => _63.pixelRatio])||Math.min(window.devicePixelRatio,2),toneMapping:_optionalChain([e, 'access', _64 => _64.render, 'optionalAccess', _65 => _65.toneMapping])||i.NeutralToneMapping,toneMappingExposure:_optionalChain([e, 'access', _66 => _66.render, 'optionalAccess', _67 => _67.toneMappingExposure])||1,preserveDrawingBuffer:_nullishCoalesce(_optionalChain([e, 'access', _68 => _68.render, 'optionalAccess', _69 => _69.preserveDrawingBuffer]), () => (!1))},controls:{enableDamping:_nullishCoalesce(_optionalChain([e, 'access', _70 => _70.controls, 'optionalAccess', _71 => _71.enableDamping]), () => (!1)),dampingFactor:_optionalChain([e, 'access', _72 => _72.controls, 'optionalAccess', _73 => _73.dampingFactor])||.05,autoRotate:_nullishCoalesce(_optionalChain([e, 'access', _74 => _74.controls, 'optionalAccess', _75 => _75.autoRotate]), () => (!1)),autoRotateSpeed:_optionalChain([e, 'access', _76 => _76.controls, 'optionalAccess', _77 => _77.autoRotateSpeed])||.5,enableZoom:_nullishCoalesce(_optionalChain([e, 'access', _78 => _78.controls, 'optionalAccess', _79 => _79.enableZoom]), () => (!0)),enablePan:_nullishCoalesce(_optionalChain([e, 'access', _80 => _80.controls, 'optionalAccess', _81 => _81.enablePan]), () => (!0)),minDistance:_optionalChain([e, 'access', _82 => _82.controls, 'optionalAccess', _83 => _83.minDistance])||n.minDistance,maxDistance:_optionalChain([e, 'access', _84 => _84.controls, 'optionalAccess', _85 => _85.maxDistance])||1/0},events:{onBackgroundClicked:_optionalChain([e, 'access', _86 => _86.events, 'optionalAccess', _87 => _87.onBackgroundClicked]),onObjectSelected:_optionalChain([e, 'access', _88 => _88.events, 'optionalAccess', _89 => _89.onObjectSelected]),onMeshMetadataClicked:_optionalChain([e, 'access', _90 => _90.events, 'optionalAccess', _91 => _91.onMeshMetadataClicked]),onMeshDoubleClicked:_optionalChain([e, 'access', _92 => _92.events, 'optionalAccess', _93 => _93.onMeshDoubleClicked]),selectionColor:_optionalChain([e, 'access', _94 => _94.events, 'optionalAccess', _95 => _95.selectionColor])||"#ff0000",enableEventHandlers:_nullishCoalesce(_optionalChain([e, 'access', _96 => _96.events, 'optionalAccess', _97 => _97.enableEventHandlers]), () => (!0)),enableKeyboardControls:_nullishCoalesce(_optionalChain([e, 'access', _98 => _98.events, 'optionalAccess', _99 => _99.enableKeyboardControls]), () => (!0)),enableClickToFocus:_nullishCoalesce(_optionalChain([e, 'access', _100 => _100.events, 'optionalAccess', _101 => _101.enableClickToFocus]), () => (!0)),enableDoubleClickZoom:_nullishCoalesce(_optionalChain([e, 'access', _102 => _102.events, 'optionalAccess', _103 => _103.enableDoubleClickZoom]), () => (!0))}}}function re(e){let r=new i.Scene,t=typeof e.environment.backgroundColor=="string"?new i.Color(e.environment.backgroundColor):e.environment.backgroundColor;return r.background=t||null,r}function oe(e,r,t,n,o=200){let s=e.position.clone(),a=r.target.clone(),l=performance.now(),c=m=>1-Math.pow(1-m,3),R=()=>{let m=performance.now()-l,h=c(Math.min(m/o,1));e.position.lerpVectors(s,t,h),r.target.lerpVectors(a,n,h),r.update(),h<1&&requestAnimationFrame(R)};requestAnimationFrame(R)}function se(e,r,t,n){let o=null,s=function(){o=requestAnimationFrame(s),(n.enableDamping||n.autoRotate)&&n.update(),e.render(r,t)};return{animate:s,dispose:()=>{o!==null&&(cancelAnimationFrame(o),o=null)}}}function ae(e,r,t){let n=e.parentElement,o=null,s=null,a=()=>n?{width:n.clientWidth,height:n.clientHeight}:{width:window.innerWidth,height:window.innerHeight},l=()=>{let{width:m,height:h}=a();if(m===0||h===0)return;let E=Math.min(window.devicePixelRatio,2),M=Math.round(r.domElement.clientWidth*E),f=Math.round(r.domElement.clientHeight*E),H=Math.round(m*E),C=Math.round(h*E);(M!==H||f!==C)&&(r.setPixelRatio(E),r.setSize(m,h,!0),t.aspect=m/h,t.updateProjectionMatrix())},c=()=>{o!==null&&cancelAnimationFrame(o),o=requestAnimationFrame(()=>{o=requestAnimationFrame(()=>{o=null,l()})})};return typeof ResizeObserver<"u"?(s=new ResizeObserver(c),n?s.observe(n):s.observe(e)):window.addEventListener("resize",c),{resize:c,dispose:()=>{o!==null&&(cancelAnimationFrame(o),o=null),s?s.disconnect():window.removeEventListener("resize",c)}}}function ie(e,r){r.environment.enableEnvironmentLighting&&new (0, _HDRLoaderjs.HDRLoader)().load(r.environment.hdrPath||"/baseHDR.hdr",function(t){t.mapping=i.EquirectangularReflectionMapping,e.environment=t,r.environment.showEnvironment&&(e.background=t)},void 0,function(t){_chunkPE2FMBXDcjs.i.call(void 0, ).warn("HDR texture could not be loaded, falling back to basic lighting:",t)})}function ce(e,r){let t=new i.AmbientLight(r.lighting.ambientLightColor,r.lighting.ambientLightIntensity);if(e.add(t),r.lighting.enableSunlight){let n=new i.DirectionalLight(_nullishCoalesce(r.lighting.sunlightColor, () => (16777215)),r.lighting.sunlightIntensity),o=r.lighting.sunlightPosition;if(o&&n.position.set(o.x,o.y,o.z),r.render.enableShadows){n.castShadow=!0;let s=r.sceneScale==="mm"?.1:r.sceneScale==="cm"?10:100;n.shadow.camera.left=-s,n.shadow.camera.right=s,n.shadow.camera.top=s,n.shadow.camera.bottom=-s;let a=r.sceneScale==="mm"?.001:r.sceneScale==="cm"?.1:.5,l=r.sceneScale==="mm"?1:r.sceneScale==="cm"?100:500;n.shadow.camera.near=a,n.shadow.camera.far=l,n.shadow.mapSize.width=r.render.shadowMapSize||2048,n.shadow.mapSize.height=r.render.shadowMapSize||2048,n.shadow.bias=-1e-4,n.shadow.normalBias=.02}e.add(n)}}function le(e,r){let t=r.floor.size,n=new i.PlaneGeometry(t,t),o=typeof r.floor.color=="string"?new i.Color(r.floor.color):r.floor.color,s=new i.MeshStandardMaterial({color:o,roughness:r.floor.roughness,metalness:r.floor.metalness,side:i.DoubleSide}),a=new i.Mesh(n,s);a.userData.id="floor",a.name="floor",a.rotation.x=-Math.PI/2,a.position.y=0,r.floor.receiveShadow&&r.render.enableShadows&&(a.receiveShadow=!0),e.add(a)}function fe(e,r){let t=r.parentElement,n=t?t.clientWidth:window.innerWidth,o=t?t.clientHeight:window.innerHeight,s=new i.PerspectiveCamera(e.camera.fov,n/o,e.camera.near,e.camera.far),a=e.camera.position;return a&&s.position.set(a.x,a.y,a.z),s}function de(e,r){let t=new i.WebGLRenderer({antialias:r.render.antialias,canvas:e,alpha:!0,powerPreference:"high-performance",preserveDrawingBuffer:r.render.preserveDrawingBuffer,logarithmicDepthBuffer:!0}),n=e.parentElement,o=n?n.clientWidth:window.innerWidth,s=n?n.clientHeight:window.innerHeight;return n&&(e.style.width="100%",e.style.height="100%",e.style.display="block"),t.setSize(o,s,!0),t.setPixelRatio(r.render.pixelRatio||Math.min(window.devicePixelRatio,2)),r.render.enableShadows&&(t.shadowMap.enabled=!0,t.shadowMap.type=i.VSMShadowMap),t.toneMapping=r.render.toneMapping||i.ACESFilmicToneMapping,t.toneMappingExposure=r.render.toneMappingExposure||1,t.outputColorSpace=i.SRGBColorSpace,t.sortObjects=!0,t}function he(e,r,t,n,o){let s=new Set,a=new Map,l=new i.Raycaster,c=new i.Vector2,R=new i.Vector2,m=()=>{let d=new i.Box3;if(r.traverse(D=>{D.visible&&D.userData.id!=="floor"&&D instanceof i.Mesh&&d.expandByObject(D)}),d.isEmpty()){_chunkPE2FMBXDcjs.i.call(void 0, ).warn("No objects to fit to view");return}let g=d.getCenter(new i.Vector3),y=d.getSize(new i.Vector3),A=Math.max(y.x,y.y,y.z),T=t.fov*(Math.PI/180),O=A/(2*Math.tan(T/2));O*=1.5;let L=t.position.clone().sub(n.target).normalize();t.position.copy(g.clone().add(L.multiplyScalar(O))),n.target.copy(g),n.update()},h=typeof o.events.selectionColor=="string"?new i.Color(o.events.selectionColor):o.events.selectionColor instanceof i.Color?o.events.selectionColor:new i.Color("#ff0000"),E=()=>{s.forEach(d=>{d instanceof i.Mesh&&a.has(d)&&(d.material=a.get(d),a.delete(d))}),s.clear()},M=d=>{R.set(d.clientX,d.clientY)},f=d=>{let g=new i.Vector2(d.clientX,d.clientY);if(R.distanceTo(g)>5)return;let y=e.getBoundingClientRect();c.x=(d.clientX-y.left)/y.width*2-1,c.y=-((d.clientY-y.top)/y.height)*2+1,l.setFromCamera(c,t);let A=l.intersectObjects(r.children,!0);if(A.length>0){let T=A[0].object;if(!s.has(T)){if(E(),s.add(T),T instanceof i.Mesh&&T.material instanceof i.Material){a.set(T,T.material);let O=T.material.clone();O.emissive=h.clone(),T.material=O}_optionalChain([o, 'access', _104 => _104.events, 'optionalAccess', _105 => _105.onObjectSelected, 'optionalCall', _106 => _106(T)]),T instanceof i.Mesh&&Object.keys(T.userData).length>0&&_optionalChain([o, 'access', _107 => _107.events, 'optionalAccess', _108 => _108.onMeshMetadataClicked, 'optionalCall', _109 => _109(T.userData)])}}else E(),_optionalChain([o, 'access', _110 => _110.events, 'optionalAccess', _111 => _111.onBackgroundClicked, 'optionalCall', _112 => _112({x:c.x,y:c.y})])},H=d=>{let g=e.getBoundingClientRect();c.x=(d.clientX-g.left)/g.width*2-1,c.y=-((d.clientY-g.top)/g.height)*2+1,l.setFromCamera(c,t);let y=l.intersectObjects(r.children,!0);if(y.length===0)return;let A=y[0].object;if(_optionalChain([o, 'access', _113 => _113.events, 'optionalAccess', _114 => _114.onMeshDoubleClicked, 'optionalCall', _115 => _115(A)]),!_optionalChain([o, 'access', _116 => _116.events, 'optionalAccess', _117 => _117.enableDoubleClickZoom]))return;let T=new i.Box3().setFromObject(A);if(T.isEmpty())return;let O=T.getCenter(new i.Vector3),L=T.getSize(new i.Vector3),D=Math.max(L.x,L.y,L.z),j=t.fov*(Math.PI/180),Z=D/(2*Math.tan(j/2))*1.5,K=t.position.clone().sub(n.target).normalize(),X=O.clone().add(K.multiplyScalar(Z));oe(t,n,X,O)},C=d=>{if(_optionalChain([o, 'access', _118 => _118.events, 'optionalAccess', _119 => _119.enableKeyboardControls]))switch(d.key.toLowerCase()){case"f":d.preventDefault(),m();break;case"escape":d.preventDefault(),E();break;case" ":d.preventDefault(),m();break}};return _optionalChain([o, 'access', _120 => _120.events, 'optionalAccess', _121 => _121.enableClickToFocus])&&(e.addEventListener("mousedown",M),e.addEventListener("click",f),e.addEventListener("dblclick",H)),_optionalChain([o, 'access', _122 => _122.events, 'optionalAccess', _123 => _123.enableKeyboardControls])&&(e.setAttribute("tabindex","0"),e.addEventListener("keydown",C)),{dispose:()=>{e.removeEventListener("mousedown",M),e.removeEventListener("click",f),e.removeEventListener("dblclick",H),e.removeEventListener("keydown",C),E()},fitToView:m,clearSelection:E}}function me(e,r,t){let n=new (0, _OrbitControlsjs.OrbitControls)(e,r),o=t.camera.target;return o&&n.target.set(o.x,o.y,o.z),n.enableDamping=t.controls.enableDamping||!1,n.dampingFactor=t.controls.dampingFactor||.05,n.autoRotate=t.controls.autoRotate||!1,n.autoRotateSpeed=t.controls.autoRotateSpeed||.5,n.enableZoom=_nullishCoalesce(t.controls.enableZoom, () => (!0)),n.enablePan=_nullishCoalesce(t.controls.enablePan, () => (!0)),n.minDistance=t.controls.minDistance||.001,n.maxDistance=t.controls.maxDistance||1/0,n.screenSpacePanning=!1,n.maxPolarAngle=Math.PI,n.update(),n}var v={HUGE_THRESHOLD:1e4,LARGE_THRESHOLD:1e3,SCALE_RATIO_THRESHOLD:100,NEAR_PLANE_FACTOR:{TINY:1e-4,SMALL:.001,NORMAL:.01},FAR_PLANE_FACTOR:{HUGE:100,LARGE:50,NORMAL:20},InitialDistanceMultiplier:4};function W(e,r,t,n,o){if(Ee(e),r.length===0)return;r.forEach(m=>{e.add(m)});let s=B(r),a=s.getCenter(new w.Vector3),l=s.getSize(new w.Vector3),c=Math.max(l.x,l.y,l.z);if(c/Math.min(l.x||1,l.y||1,l.z||1)>v.SCALE_RATIO_THRESHOLD||c>v.HUGE_THRESHOLD?(t.near=c*v.NEAR_PLANE_FACTOR.TINY,t.far=c*v.FAR_PLANE_FACTOR.HUGE):c>v.LARGE_THRESHOLD?(t.near=c*v.NEAR_PLANE_FACTOR.SMALL,t.far=c*v.FAR_PLANE_FACTOR.LARGE):(t.near=Math.max(.01,c*v.NEAR_PLANE_FACTOR.NORMAL),t.far=Math.max(2e3,c*v.FAR_PLANE_FACTOR.NORMAL)),t.updateProjectionMatrix(),o)n.minDistance=t.near*2,n.maxDistance=t.far*.9;else{let m=c*v.InitialDistanceMultiplier;t.position.set(a.x+m*.8,a.y+m,a.z+m*1.2),n.target.copy(a),n.minDistance=t.near*2,n.maxDistance=t.far*.9,n.update()}}function F(e){if(!e||typeof e!="string")return _chunkPE2FMBXDcjs.i.call(void 0, ).warn(`Invalid color input: ${e}, using white`),new w.Color(16777215);let r=e.trim();if(r.startsWith("#")||/^[0-9A-Fa-f]{6}$/.test(r))try{let t=r.startsWith("#")?r:`#${r}`;return new w.Color(t)}catch (e2){return _chunkPE2FMBXDcjs.i.call(void 0, ).warn(`Invalid hex color: ${e}, using white`),new w.Color(16777215)}if(r.includes(",")){let t=r.split(",").map(n=>parseInt(n.trim(),10));if(t.length===3&&t.every(n=>!isNaN(n)&&n>=0&&n<=255))return new w.Color(t[0]/255,t[1]/255,t[2]/255)}try{return new w.Color(r.toLowerCase())}catch (e3){return _chunkPE2FMBXDcjs.i.call(void 0, ).warn(`Invalid color string: ${e}, using white`),new w.Color(16777215)}}function P(e,r){e.forEach(t=>{t.position.y-=r,t.updateMatrix()})}function B(e){let r=new w.Box3;return e.forEach(t=>{t.updateMatrixWorld(!0);let n=new w.Box3().setFromObject(t);r.union(n)}),r}function Ee(e){let r=[];e.traverse(t=>{t instanceof w.Mesh&&t.userData.id!=="floor"&&r.push(t)}),r.forEach(t=>{t instanceof w.Mesh&&(_optionalChain([t, 'access', _124 => _124.geometry, 'optionalAccess', _125 => _125.dispose, 'call', _126 => _126()]),(Array.isArray(t.material)?t.material:[t.material]).forEach(o=>{for(let s in o){let a=o[s];a&&a instanceof w.Texture&&a.dispose()}o.dispose()})),t.removeFromParent()})}var z={};_chunkPE2FMBXDcjs.a.call(void 0, z,{CONCRETE_MATERIAL:()=>ge,EMISSIVE_MATERIAL:()=>ue,GLASS_MATERIAL:()=>Te,METAL_MATERIAL:()=>pe,PLASTIC_MATERIAL:()=>Re,RUBBER_MATERIAL:()=>we,WOOD_MATERIAL:()=>ye});var ue=new u.MeshPhysicalMaterial({color:0,emissive:new u.Color(16777215),emissiveIntensity:5,metalness:0,roughness:.2,clearcoat:.3,clearcoatRoughness:.2,depthWrite:!0,depthTest:!0,transparent:!1,alphaTest:0,polygonOffset:!0,side:u.FrontSide,dithering:!0}),pe=new u.MeshPhysicalMaterial({color:new u.Color(0),metalness:.9,roughness:.3,envMapIntensity:1.2,clearcoat:.3,clearcoatRoughness:.2,reflectivity:1,ior:2.5,thickness:1,depthWrite:!0,transparent:!1,alphaTest:0,depthTest:!0,polygonOffset:!0,side:u.FrontSide,dithering:!0}),ge=new u.MeshPhysicalMaterial({color:new u.Color(13421772),metalness:0,roughness:.92,envMapIntensity:.15,clearcoat:.05,clearcoatRoughness:.9,reflectivity:.15,transmission:0,ior:1.45,thickness:0,depthWrite:!0,transparent:!1,alphaTest:.5,depthTest:!0,polygonOffset:!0,side:u.FrontSide,dithering:!0}),Re=new u.MeshPhysicalMaterial({color:new u.Color(16777215),metalness:0,roughness:.3,envMapIntensity:.5,clearcoat:.5,clearcoatRoughness:.1,reflectivity:.5,ior:1.4,transmission:0,transparent:!1,depthWrite:!0,side:u.FrontSide,dithering:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),Te=new u.MeshPhysicalMaterial({color:new u.Color(16777215),metalness:0,roughness:0,transmission:.95,transparent:!0,opacity:.3,envMapIntensity:1,clearcoat:1,clearcoatRoughness:0,ior:1.52,reflectivity:.9,thickness:1,side:u.DoubleSide,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),we=new u.MeshPhysicalMaterial({color:new u.Color(1710618),metalness:0,roughness:.9,envMapIntensity:.2,clearcoat:.1,clearcoatRoughness:.8,reflectivity:.2,ior:1.3,transmission:0,depthWrite:!0,side:u.FrontSide,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),ye=new u.MeshPhysicalMaterial({color:new u.Color(8934707),metalness:0,roughness:.7,envMapIntensity:.3,clearcoat:.3,clearcoatRoughness:.4,reflectivity:.3,ior:1.3,transmission:0,depthWrite:!0,side:u.FrontSide,dithering:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1});var _fflate = require('fflate'); var $ = _interopRequireWildcard(_fflate);_chunkPE2FMBXDcjs.h.call(void 0, );async function q(e){return new Promise((r,t)=>{try{let n=()=>{try{let o=_chunkQCHPQ22Ycjs.c.call(void 0, e),s=$.gunzipSync(o),a=be(s);r(a)}catch(o){t(new (0, _chunkPE2FMBXDcjs.e)(o instanceof _chunkPE2FMBXDcjs.e?o.message:`Failed to decompress batched data: ${o instanceof Error?o.message:String(o)}`,o instanceof _chunkPE2FMBXDcjs.e?o.code:_chunkPE2FMBXDcjs.d.VALIDATION_ERROR,{context:{base64StringLength:e.length},originalError:o instanceof Error?o:new Error(String(o))}))}};"requestIdleCallback"in globalThis?globalThis.requestIdleCallback(n,{timeout:5e3}):setTimeout(n,0)}catch(n){t(new (0, _chunkPE2FMBXDcjs.e)(`Failed to schedule decompression: ${n instanceof Error?n.message:String(n)}`,_chunkPE2FMBXDcjs.d.VALIDATION_ERROR,{originalError:n instanceof Error?n:new Error(String(n))}))}})}function be(e){let r=new DataView(e.buffer,e.byteOffset,e.byteLength),t=0;if(t+4>r.byteLength)throw new (0, _chunkPE2FMBXDcjs.e)("Insufficient data to read the number of vertex floats.",_chunkPE2FMBXDcjs.d.VALIDATION_ERROR,{context:{expectedBytes:4,availableBytes:r.byteLength,offset:t}});let n=r.getUint32(t,!0);if(t+=4,n%3!==0)throw new (0, _chunkPE2FMBXDcjs.e)("Invalid number of vertex floats; should be divisible by 3.",_chunkPE2FMBXDcjs.d.VALIDATION_ERROR,{context:{numVertexFloats:n,remainder:n%3,totalBytes:r.byteLength}});let o=n*Float32Array.BYTES_PER_ELEMENT;if(t+o>r.byteLength)throw new (0, _chunkPE2FMBXDcjs.e)("Insufficient data to read vertices.",_chunkPE2FMBXDcjs.d.VALIDATION_ERROR,{context:{expectedBytes:o,availableBytes:r.byteLength-t,offset:t}});let s=new Float32Array(e.buffer,e.byteOffset+t,n);if(t+=o,t+4>r.byteLength)throw new (0, _chunkPE2FMBXDcjs.e)("Insufficient data to read the number of face indices.",_chunkPE2FMBXDcjs.d.VALIDATION_ERROR,{context:{expectedBytes:4,availableBytes:r.byteLength-t,offset:t}});let a=r.getUint32(t,!0);t+=4;let l=a*Uint32Array.BYTES_PER_ELEMENT;if(t+l>r.byteLength)throw new (0, _chunkPE2FMBXDcjs.e)("Insufficient data to read face indices.",_chunkPE2FMBXDcjs.d.VALIDATION_ERROR,{context:{expectedBytes:l,availableBytes:r.byteLength-t,offset:t}});let c=new Uint32Array(e.buffer,e.byteOffset+t,a);return{vertices:s,faces:c}}async function _(e,r){let{mergeByMaterial:t=!0,applyTransforms:n=!0,debug:o=!1}=_nullishCoalesce(r, () => ({})),s=o?performance.now():0,a=0;try{let l=performance.now(),c=JSON.parse(e);return a=performance.now()-l,await V(c,{mergeByMaterial:t,applyTransforms:n,debug:o,parseTime:a,perfStart:s})}catch(l){return _chunkPE2FMBXDcjs.i.call(void 0, ).error("Error parsing mesh batch:",l),[]}}async function V(e,r){let{mergeByMaterial:t=!0,applyTransforms:n=!0,scaleFactor:o=1,debug:s=!1,parseTime:a=0,perfStart:l=s?performance.now():0}=_nullishCoalesce(r, () => ({})),c=0,R=0;try{let m=performance.now(),{vertices:h,faces:E}=await q(e.compressedData);c=performance.now()-m;let M=(e.compressedData.length*.75/1024/1024).toFixed(2),f=((h.byteLength+E.byteLength)/1024/1024).toFixed(2),H=((1-parseFloat(M)/parseFloat(f))*100).toFixed(1);s&&(_chunkPE2FMBXDcjs.i.call(void 0, ).debug("Mesh Batch Stats:"),_chunkPE2FMBXDcjs.i.call(void 0, ).debug(` Materials: ${e.materials.length} | Groups: ${e.groups.length}`),_chunkPE2FMBXDcjs.i.call(void 0, ).debug(` Vertices: ${(h.length/3).toLocaleString()} | Faces: ${(E.length/3).toLocaleString()}`),_chunkPE2FMBXDcjs.i.call(void 0, ).debug(` Compressed: ${M} MB | Uncompressed: ${f} MB`),_chunkPE2FMBXDcjs.i.call(void 0, ).debug(` Compression Ratio: ${H}%`)),n&&ve(h);let C=performance.now(),I=e.materials.map(Me),d=[];for(let g of e.groups)if(t&&g.meshes.length>1){let y=He(g,h,E,I);d.push(y)}else{let y=xe(g,h,E,I);d.push(...y)}if(o!==1)for(let g of d)g.scale.set(o,o,o);if(R=performance.now()-C,s){let g=performance.now()-l;_chunkPE2FMBXDcjs.i.call(void 0, ).debug("Performance:"),a>0&&_chunkPE2FMBXDcjs.i.call(void 0, ).debug(` Parse JSON: ${a.toFixed(2)}ms`),_chunkPE2FMBXDcjs.i.call(void 0, ).debug(` Decompress: ${c.toFixed(2)}ms`),_chunkPE2FMBXDcjs.i.call(void 0, ).debug(` Create Meshes: ${R.toFixed(2)}ms`),_chunkPE2FMBXDcjs.i.call(void 0, ).debug(` Total: ${g.toFixed(2)}ms`)}return d}catch(m){return _chunkPE2FMBXDcjs.i.call(void 0, ).error("Error parsing mesh batch object:",m),[]}}function Me(e){let r=F(e.color);return new b.MeshPhysicalMaterial({color:r,metalness:e.metalness,roughness:e.roughness,opacity:e.opacity,transparent:e.transparent,side:b.DoubleSide,polygonOffset:!0,polygonOffsetFactor:.5,polygonOffsetUnits:.5,depthWrite:!0,depthTest:!0})}function He(e,r,t,n){let o=new b.BufferGeometry,s=0,a=0;for(let f of e.meshes)s+=f.vertexCount,a+=f.faceCount;let l=new Float32Array(s),c=new Uint32Array(a),R=0,m=0;for(let f of e.meshes){l.set(r.subarray(f.vertexOffset,f.vertexOffset+f.vertexCount),R);let H=t.subarray(f.faceOffset,f.faceOffset+f.faceCount),C=Math.floor(f.vertexOffset/3),d=Math.floor(R/3)-C;for(let g=0;g<H.length;g++)c[m+g]=H[g]+d;R+=f.vertexCount,m+=f.faceCount}o.setAttribute("position",new b.BufferAttribute(l,3)),o.setIndex(new b.BufferAttribute(c,1)),o.computeVertexNormals();let h=new b.Mesh(o,n[e.materialId]),E=e.meshes.map(f=>f.name).filter(f=>f&&f.length>0);h.name=E.length>0?E[0]:`merged_material_${e.materialId}`,h.castShadow=!0,h.receiveShadow=!0;let M=e.meshes.map(f=>f.metadata).filter(f=>f);return M.length>0&&(h.userData.mergedMetadata=M),h}function xe(e,r,t,n){let o=[];for(let s of e.meshes){let a=new b.BufferGeometry,l=r.subarray(s.vertexOffset,s.vertexOffset+s.vertexCount),c=t.subarray(s.faceOffset,s.faceOffset+s.faceCount),R=Math.floor(s.vertexOffset/3),m=new Uint32Array(c.length);for(let E=0;E<c.length;E++)m[E]=c[E]-R;a.setAttribute("position",new b.BufferAttribute(l,3)),a.setIndex(new b.BufferAttribute(m,1)),a.computeVertexNormals();let h=new b.Mesh(a,n[e.materialId]);h.name=s.name,s.metadata&&(h.userData={...h.userData,...s.metadata}),h.castShadow=!0,h.receiveShadow=!0,o.push(h)}return o}function ve(e){let r=Math.cos(-Math.PI/2),t=Math.sin(-Math.PI/2);for(let n=0;n<e.length;n+=3){let o=e[n],s=e[n+1],a=e[n+2];e[n]=o,e[n+1]=s*r-a*t,e[n+2]=s*t+a*r}}var k={Millimeters:1/1e3,Centimeters:1/100,Meters:1,Inches:1/39.37,Feet:1/3.28084},Ce="Display";async function Y(e,r){let t=performance.now(),n=[],{allowScaling:o=!0,allowAutoPosition:s=!0,debug:a=!1,parsing:l={}}=_nullishCoalesce(r, () => ({}));try{let c=o?Oe(e.modelunits):1;return await Se(e,n,c,l,a),s&&De(n),n}catch(c){throw Le(c,n),c}finally{a&&Be(t)}}function Oe(e){return _nullishCoalesce(k[e], () => (1))}async function Se(e,r,t,n,o){for(let s of e.values){let a=s.InnerTree;for(let l in a){let c=a[l];c&&await Ae(c,r,t,n,o)}}}async function Ae(e,r,t,n,o){for(let s of e)if(s.type.includes(Ce)){let a={mergeByMaterial:!0,applyTransforms:!0,debug:!1,...n},l=await _(s.data,a);if(t!==1)for(let c of l)c.scale.set(t,t,t);r.push(...l),o&&_chunkPE2FMBXDcjs.i.call(void 0, ).debug(`Extracted ${l.length} meshes from batch`)}}function De(e){if(e.length===0)return;let t=B(e).min.y;P(e,t)}function Le(e,r){_chunkPE2FMBXDcjs.i.call(void 0, ).error("An unexpected error occurred:",e),Ie(r)}function Ie(e){for(let r of e)r.geometry&&r.geometry.dispose(),r.material&&(Array.isArray(r.material)?r.material.forEach(t=>t.dispose()):r.material.dispose())}function Be(e){let r=performance.now()-e;_chunkPE2FMBXDcjs.i.call(void 0, ).info("Time to process meshes:",`${r.toFixed(2)}ms`)}exports.Materials = z; exports.SCALE_FACTORS = k; exports.getThreeMeshesFromComputeResponse = Y; exports.initThree = U; exports.parseMeshBatchObject = V; exports.updateScene = W;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkFB4LUGFJcjs = require('./chunk-FB4LUGFJ.cjs');var _chunkMTDJ3VNBcjs = require('./chunk-MTDJ3VNB.cjs');var _three = require('three'); var i = _interopRequireWildcard(_three); var w = _interopRequireWildcard(_three); var u = _interopRequireWildcard(_three); var b = _interopRequireWildcard(_three);var _OrbitControlsjs = require('three/addons/controls/OrbitControls.js');var _HDRLoaderjs = require('three/addons/loaders/HDRLoader.js');var G=new i.Vector3(0,0,1),U= exports.initThree =function(e,r){let t=ne(r||{}),n=re(t),o=fe(t,e),s=de(e,t),a=me(o,e,t);ie(n,t),ce(n,t),_optionalChain([t, 'access', _2 => _2.floor, 'optionalAccess', _3 => _3.enabled])&&le(n,t);let l=t.events.enableEventHandlers!==!1?he(e,n,o,a,t):{dispose:()=>{},fitToView:()=>{},clearSelection:()=>{}},{resize:c,dispose:R}=ae(e,s,o),{animate:m,dispose:h}=se(s,n,o,a);m();let E=_optionalChain([t, 'access', _4 => _4.environment, 'optionalAccess', _5 => _5.sceneUp])||G;return n.up.set(E.x,E.y,E.z),{scene:n,camera:o,controls:a,renderer:s,dispose:()=>{h(),R(),l.dispose(),a.dispose(),s.dispose(),n.traverse(f=>{f instanceof i.Mesh&&(_optionalChain([f, 'access', _6 => _6.geometry, 'optionalAccess', _7 => _7.dispose, 'call', _8 => _8()]),Array.isArray(f.material)?f.material.forEach(H=>H.dispose()):_optionalChain([f, 'access', _9 => _9.material, 'optionalAccess', _10 => _10.dispose, 'call', _11 => _11()]))})},resize:c,fitToView:l.fitToView,clearSelection:l.clearSelection}};function ne(e){let r=e.sceneScale||"m",n={mm:{cameraDistance:20,near:.1,far:2e3,floorSize:100,lightDistance:10,lightHeight:20,minDistance:.1,shadowSize:100,scaleFactor:1e3},cm:{cameraDistance:20,near:.1,far:2e3,floorSize:100,lightDistance:25,lightHeight:50,minDistance:.1,shadowSize:100,scaleFactor:100},m:{cameraDistance:10,near:.01,far:2e3,floorSize:50,lightDistance:25,lightHeight:50,minDistance:.001,shadowSize:100,scaleFactor:1},inches:{cameraDistance:15,near:.1,far:2e3,floorSize:80,lightDistance:20,lightHeight:40,minDistance:.1,shadowSize:80,scaleFactor:39.37},feet:{cameraDistance:8,near:.1,far:2e3,floorSize:40,lightDistance:15,lightHeight:30,minDistance:.1,shadowSize:60,scaleFactor:3.28084}}[r];return{sceneScale:r,camera:{position:_optionalChain([e, 'access', _12 => _12.camera, 'optionalAccess', _13 => _13.position])||new i.Vector3(-n.cameraDistance,n.cameraDistance,n.cameraDistance),fov:_optionalChain([e, 'access', _14 => _14.camera, 'optionalAccess', _15 => _15.fov])||20,near:_optionalChain([e, 'access', _16 => _16.camera, 'optionalAccess', _17 => _17.near])||n.near,far:_optionalChain([e, 'access', _18 => _18.camera, 'optionalAccess', _19 => _19.far])||n.far,target:_optionalChain([e, 'access', _20 => _20.camera, 'optionalAccess', _21 => _21.target])||new i.Vector3(0,0,0)},lighting:{enableSunlight:_nullishCoalesce(_optionalChain([e, 'access', _22 => _22.lighting, 'optionalAccess', _23 => _23.enableSunlight]), () => (!0)),sunlightIntensity:_optionalChain([e, 'access', _24 => _24.lighting, 'optionalAccess', _25 => _25.sunlightIntensity])||1,sunlightPosition:_optionalChain([e, 'access', _26 => _26.lighting, 'optionalAccess', _27 => _27.sunlightPosition])||new i.Vector3(n.lightDistance,n.lightHeight,n.lightDistance),ambientLightColor:_optionalChain([e, 'access', _28 => _28.lighting, 'optionalAccess', _29 => _29.ambientLightColor])||new i.Color(4210752),ambientLightIntensity:_optionalChain([e, 'access', _30 => _30.lighting, 'optionalAccess', _31 => _31.ambientLightIntensity])||1,sunlightColor:_optionalChain([e, 'access', _32 => _32.lighting, 'optionalAccess', _33 => _33.sunlightColor])||16777215},environment:{hdrPath:_optionalChain([e, 'access', _34 => _34.environment, 'optionalAccess', _35 => _35.hdrPath])||"/baseHDR.hdr",backgroundColor:_optionalChain([e, 'access', _36 => _36.environment, 'optionalAccess', _37 => _37.backgroundColor])||new i.Color(15790320),enableEnvironmentLighting:_nullishCoalesce(_optionalChain([e, 'access', _38 => _38.environment, 'optionalAccess', _39 => _39.enableEnvironmentLighting]), () => (!0)),sceneUp:_optionalChain([e, 'access', _40 => _40.environment, 'optionalAccess', _41 => _41.sceneUp])||G,showEnvironment:_nullishCoalesce(_optionalChain([e, 'access', _42 => _42.environment, 'optionalAccess', _43 => _43.showEnvironment]), () => (!1))},floor:{enabled:_nullishCoalesce(_optionalChain([e, 'access', _44 => _44.floor, 'optionalAccess', _45 => _45.enabled]), () => (!1)),size:_optionalChain([e, 'access', _46 => _46.floor, 'optionalAccess', _47 => _47.size])||n.floorSize,color:_optionalChain([e, 'access', _48 => _48.floor, 'optionalAccess', _49 => _49.color])||new i.Color(8421504),roughness:_optionalChain([e, 'access', _50 => _50.floor, 'optionalAccess', _51 => _51.roughness])||.7,metalness:_optionalChain([e, 'access', _52 => _52.floor, 'optionalAccess', _53 => _53.metalness])||0,receiveShadow:_nullishCoalesce(_optionalChain([e, 'access', _54 => _54.floor, 'optionalAccess', _55 => _55.receiveShadow]), () => (!0))},render:{enableShadows:_nullishCoalesce(_optionalChain([e, 'access', _56 => _56.render, 'optionalAccess', _57 => _57.enableShadows]), () => (!0)),shadowMapSize:_optionalChain([e, 'access', _58 => _58.render, 'optionalAccess', _59 => _59.shadowMapSize])||2048,antialias:_nullishCoalesce(_optionalChain([e, 'access', _60 => _60.render, 'optionalAccess', _61 => _61.antialias]), () => (!0)),pixelRatio:_optionalChain([e, 'access', _62 => _62.render, 'optionalAccess', _63 => _63.pixelRatio])||Math.min(window.devicePixelRatio,2),toneMapping:_optionalChain([e, 'access', _64 => _64.render, 'optionalAccess', _65 => _65.toneMapping])||i.NeutralToneMapping,toneMappingExposure:_optionalChain([e, 'access', _66 => _66.render, 'optionalAccess', _67 => _67.toneMappingExposure])||1,preserveDrawingBuffer:_nullishCoalesce(_optionalChain([e, 'access', _68 => _68.render, 'optionalAccess', _69 => _69.preserveDrawingBuffer]), () => (!1))},controls:{enableDamping:_nullishCoalesce(_optionalChain([e, 'access', _70 => _70.controls, 'optionalAccess', _71 => _71.enableDamping]), () => (!1)),dampingFactor:_optionalChain([e, 'access', _72 => _72.controls, 'optionalAccess', _73 => _73.dampingFactor])||.05,autoRotate:_nullishCoalesce(_optionalChain([e, 'access', _74 => _74.controls, 'optionalAccess', _75 => _75.autoRotate]), () => (!1)),autoRotateSpeed:_optionalChain([e, 'access', _76 => _76.controls, 'optionalAccess', _77 => _77.autoRotateSpeed])||.5,enableZoom:_nullishCoalesce(_optionalChain([e, 'access', _78 => _78.controls, 'optionalAccess', _79 => _79.enableZoom]), () => (!0)),enablePan:_nullishCoalesce(_optionalChain([e, 'access', _80 => _80.controls, 'optionalAccess', _81 => _81.enablePan]), () => (!0)),minDistance:_optionalChain([e, 'access', _82 => _82.controls, 'optionalAccess', _83 => _83.minDistance])||n.minDistance,maxDistance:_optionalChain([e, 'access', _84 => _84.controls, 'optionalAccess', _85 => _85.maxDistance])||1/0},events:{onBackgroundClicked:_optionalChain([e, 'access', _86 => _86.events, 'optionalAccess', _87 => _87.onBackgroundClicked]),onObjectSelected:_optionalChain([e, 'access', _88 => _88.events, 'optionalAccess', _89 => _89.onObjectSelected]),onMeshMetadataClicked:_optionalChain([e, 'access', _90 => _90.events, 'optionalAccess', _91 => _91.onMeshMetadataClicked]),onMeshDoubleClicked:_optionalChain([e, 'access', _92 => _92.events, 'optionalAccess', _93 => _93.onMeshDoubleClicked]),selectionColor:_optionalChain([e, 'access', _94 => _94.events, 'optionalAccess', _95 => _95.selectionColor])||"#ff0000",enableEventHandlers:_nullishCoalesce(_optionalChain([e, 'access', _96 => _96.events, 'optionalAccess', _97 => _97.enableEventHandlers]), () => (!0)),enableKeyboardControls:_nullishCoalesce(_optionalChain([e, 'access', _98 => _98.events, 'optionalAccess', _99 => _99.enableKeyboardControls]), () => (!0)),enableClickToFocus:_nullishCoalesce(_optionalChain([e, 'access', _100 => _100.events, 'optionalAccess', _101 => _101.enableClickToFocus]), () => (!0)),enableDoubleClickZoom:_nullishCoalesce(_optionalChain([e, 'access', _102 => _102.events, 'optionalAccess', _103 => _103.enableDoubleClickZoom]), () => (!0))}}}function re(e){let r=new i.Scene,t=typeof e.environment.backgroundColor=="string"?new i.Color(e.environment.backgroundColor):e.environment.backgroundColor;return r.background=t||null,r}function oe(e,r,t,n,o=200){let s=e.position.clone(),a=r.target.clone(),l=performance.now(),c=m=>1-Math.pow(1-m,3),R=()=>{let m=performance.now()-l,h=c(Math.min(m/o,1));e.position.lerpVectors(s,t,h),r.target.lerpVectors(a,n,h),r.update(),h<1&&requestAnimationFrame(R)};requestAnimationFrame(R)}function se(e,r,t,n){let o=null,s=function(){o=requestAnimationFrame(s),(n.enableDamping||n.autoRotate)&&n.update(),e.render(r,t)};return{animate:s,dispose:()=>{o!==null&&(cancelAnimationFrame(o),o=null)}}}function ae(e,r,t){let n=e.parentElement,o=null,s=null,a=()=>n?{width:n.clientWidth,height:n.clientHeight}:{width:window.innerWidth,height:window.innerHeight},l=()=>{let{width:m,height:h}=a();if(m===0||h===0)return;let E=Math.min(window.devicePixelRatio,2),M=Math.round(r.domElement.clientWidth*E),f=Math.round(r.domElement.clientHeight*E),H=Math.round(m*E),C=Math.round(h*E);(M!==H||f!==C)&&(r.setPixelRatio(E),r.setSize(m,h,!0),t.aspect=m/h,t.updateProjectionMatrix())},c=()=>{o!==null&&cancelAnimationFrame(o),o=requestAnimationFrame(()=>{o=requestAnimationFrame(()=>{o=null,l()})})};return typeof ResizeObserver<"u"?(s=new ResizeObserver(c),n?s.observe(n):s.observe(e)):window.addEventListener("resize",c),{resize:c,dispose:()=>{o!==null&&(cancelAnimationFrame(o),o=null),s?s.disconnect():window.removeEventListener("resize",c)}}}function ie(e,r){r.environment.enableEnvironmentLighting&&new (0, _HDRLoaderjs.HDRLoader)().load(r.environment.hdrPath||"/baseHDR.hdr",function(t){t.mapping=i.EquirectangularReflectionMapping,e.environment=t,r.environment.showEnvironment&&(e.background=t)},void 0,function(t){_chunkMTDJ3VNBcjs.i.call(void 0, ).warn("HDR texture could not be loaded, falling back to basic lighting:",t)})}function ce(e,r){let t=new i.AmbientLight(r.lighting.ambientLightColor,r.lighting.ambientLightIntensity);if(e.add(t),r.lighting.enableSunlight){let n=new i.DirectionalLight(_nullishCoalesce(r.lighting.sunlightColor, () => (16777215)),r.lighting.sunlightIntensity),o=r.lighting.sunlightPosition;if(o&&n.position.set(o.x,o.y,o.z),r.render.enableShadows){n.castShadow=!0;let s=r.sceneScale==="mm"?.1:r.sceneScale==="cm"?10:100;n.shadow.camera.left=-s,n.shadow.camera.right=s,n.shadow.camera.top=s,n.shadow.camera.bottom=-s;let a=r.sceneScale==="mm"?.001:r.sceneScale==="cm"?.1:.5,l=r.sceneScale==="mm"?1:r.sceneScale==="cm"?100:500;n.shadow.camera.near=a,n.shadow.camera.far=l,n.shadow.mapSize.width=r.render.shadowMapSize||2048,n.shadow.mapSize.height=r.render.shadowMapSize||2048,n.shadow.bias=-1e-4,n.shadow.normalBias=.02}e.add(n)}}function le(e,r){let t=r.floor.size,n=new i.PlaneGeometry(t,t),o=typeof r.floor.color=="string"?new i.Color(r.floor.color):r.floor.color,s=new i.MeshStandardMaterial({color:o,roughness:r.floor.roughness,metalness:r.floor.metalness,side:i.DoubleSide}),a=new i.Mesh(n,s);a.userData.id="floor",a.name="floor",a.rotation.x=-Math.PI/2,a.position.y=0,r.floor.receiveShadow&&r.render.enableShadows&&(a.receiveShadow=!0),e.add(a)}function fe(e,r){let t=r.parentElement,n=t?t.clientWidth:window.innerWidth,o=t?t.clientHeight:window.innerHeight,s=new i.PerspectiveCamera(e.camera.fov,n/o,e.camera.near,e.camera.far),a=e.camera.position;return a&&s.position.set(a.x,a.y,a.z),s}function de(e,r){let t=new i.WebGLRenderer({antialias:r.render.antialias,canvas:e,alpha:!0,powerPreference:"high-performance",preserveDrawingBuffer:r.render.preserveDrawingBuffer,logarithmicDepthBuffer:!0}),n=e.parentElement,o=n?n.clientWidth:window.innerWidth,s=n?n.clientHeight:window.innerHeight;return n&&(e.style.width="100%",e.style.height="100%",e.style.display="block"),t.setSize(o,s,!0),t.setPixelRatio(r.render.pixelRatio||Math.min(window.devicePixelRatio,2)),r.render.enableShadows&&(t.shadowMap.enabled=!0,t.shadowMap.type=i.VSMShadowMap),t.toneMapping=r.render.toneMapping||i.ACESFilmicToneMapping,t.toneMappingExposure=r.render.toneMappingExposure||1,t.outputColorSpace=i.SRGBColorSpace,t.sortObjects=!0,t}function he(e,r,t,n,o){let s=new Set,a=new Map,l=new i.Raycaster,c=new i.Vector2,R=new i.Vector2,m=()=>{let d=new i.Box3;if(r.traverse(D=>{D.visible&&D.userData.id!=="floor"&&D instanceof i.Mesh&&d.expandByObject(D)}),d.isEmpty()){_chunkMTDJ3VNBcjs.i.call(void 0, ).warn("No objects to fit to view");return}let g=d.getCenter(new i.Vector3),y=d.getSize(new i.Vector3),A=Math.max(y.x,y.y,y.z),T=t.fov*(Math.PI/180),O=A/(2*Math.tan(T/2));O*=1.5;let L=t.position.clone().sub(n.target).normalize();t.position.copy(g.clone().add(L.multiplyScalar(O))),n.target.copy(g),n.update()},h=typeof o.events.selectionColor=="string"?new i.Color(o.events.selectionColor):o.events.selectionColor instanceof i.Color?o.events.selectionColor:new i.Color("#ff0000"),E=()=>{s.forEach(d=>{d instanceof i.Mesh&&a.has(d)&&(d.material=a.get(d),a.delete(d))}),s.clear()},M=d=>{R.set(d.clientX,d.clientY)},f=d=>{let g=new i.Vector2(d.clientX,d.clientY);if(R.distanceTo(g)>5)return;let y=e.getBoundingClientRect();c.x=(d.clientX-y.left)/y.width*2-1,c.y=-((d.clientY-y.top)/y.height)*2+1,l.setFromCamera(c,t);let A=l.intersectObjects(r.children,!0);if(A.length>0){let T=A[0].object;if(!s.has(T)){if(E(),s.add(T),T instanceof i.Mesh&&T.material instanceof i.Material){a.set(T,T.material);let O=T.material.clone();O.emissive=h.clone(),T.material=O}_optionalChain([o, 'access', _104 => _104.events, 'optionalAccess', _105 => _105.onObjectSelected, 'optionalCall', _106 => _106(T)]),T instanceof i.Mesh&&Object.keys(T.userData).length>0&&_optionalChain([o, 'access', _107 => _107.events, 'optionalAccess', _108 => _108.onMeshMetadataClicked, 'optionalCall', _109 => _109(T.userData)])}}else E(),_optionalChain([o, 'access', _110 => _110.events, 'optionalAccess', _111 => _111.onBackgroundClicked, 'optionalCall', _112 => _112({x:c.x,y:c.y})])},H=d=>{let g=e.getBoundingClientRect();c.x=(d.clientX-g.left)/g.width*2-1,c.y=-((d.clientY-g.top)/g.height)*2+1,l.setFromCamera(c,t);let y=l.intersectObjects(r.children,!0);if(y.length===0)return;let A=y[0].object;if(_optionalChain([o, 'access', _113 => _113.events, 'optionalAccess', _114 => _114.onMeshDoubleClicked, 'optionalCall', _115 => _115(A)]),!_optionalChain([o, 'access', _116 => _116.events, 'optionalAccess', _117 => _117.enableDoubleClickZoom]))return;let T=new i.Box3().setFromObject(A);if(T.isEmpty())return;let O=T.getCenter(new i.Vector3),L=T.getSize(new i.Vector3),D=Math.max(L.x,L.y,L.z),j=t.fov*(Math.PI/180),Z=D/(2*Math.tan(j/2))*1.5,K=t.position.clone().sub(n.target).normalize(),X=O.clone().add(K.multiplyScalar(Z));oe(t,n,X,O)},C=d=>{if(_optionalChain([o, 'access', _118 => _118.events, 'optionalAccess', _119 => _119.enableKeyboardControls]))switch(d.key.toLowerCase()){case"f":d.preventDefault(),m();break;case"escape":d.preventDefault(),E();break;case" ":d.preventDefault(),m();break}};return _optionalChain([o, 'access', _120 => _120.events, 'optionalAccess', _121 => _121.enableClickToFocus])&&(e.addEventListener("mousedown",M),e.addEventListener("click",f),e.addEventListener("dblclick",H)),_optionalChain([o, 'access', _122 => _122.events, 'optionalAccess', _123 => _123.enableKeyboardControls])&&(e.setAttribute("tabindex","0"),e.addEventListener("keydown",C)),{dispose:()=>{e.removeEventListener("mousedown",M),e.removeEventListener("click",f),e.removeEventListener("dblclick",H),e.removeEventListener("keydown",C),E()},fitToView:m,clearSelection:E}}function me(e,r,t){let n=new (0, _OrbitControlsjs.OrbitControls)(e,r),o=t.camera.target;return o&&n.target.set(o.x,o.y,o.z),n.enableDamping=t.controls.enableDamping||!1,n.dampingFactor=t.controls.dampingFactor||.05,n.autoRotate=t.controls.autoRotate||!1,n.autoRotateSpeed=t.controls.autoRotateSpeed||.5,n.enableZoom=_nullishCoalesce(t.controls.enableZoom, () => (!0)),n.enablePan=_nullishCoalesce(t.controls.enablePan, () => (!0)),n.minDistance=t.controls.minDistance||.001,n.maxDistance=t.controls.maxDistance||1/0,n.screenSpacePanning=!1,n.maxPolarAngle=Math.PI,n.update(),n}var v={HUGE_THRESHOLD:1e4,LARGE_THRESHOLD:1e3,SCALE_RATIO_THRESHOLD:100,NEAR_PLANE_FACTOR:{TINY:1e-4,SMALL:.001,NORMAL:.01},FAR_PLANE_FACTOR:{HUGE:100,LARGE:50,NORMAL:20},InitialDistanceMultiplier:4};function W(e,r,t,n,o){if(Ee(e),r.length===0)return;r.forEach(m=>{e.add(m)});let s=B(r),a=s.getCenter(new w.Vector3),l=s.getSize(new w.Vector3),c=Math.max(l.x,l.y,l.z);if(c/Math.min(l.x||1,l.y||1,l.z||1)>v.SCALE_RATIO_THRESHOLD||c>v.HUGE_THRESHOLD?(t.near=c*v.NEAR_PLANE_FACTOR.TINY,t.far=c*v.FAR_PLANE_FACTOR.HUGE):c>v.LARGE_THRESHOLD?(t.near=c*v.NEAR_PLANE_FACTOR.SMALL,t.far=c*v.FAR_PLANE_FACTOR.LARGE):(t.near=Math.max(.01,c*v.NEAR_PLANE_FACTOR.NORMAL),t.far=Math.max(2e3,c*v.FAR_PLANE_FACTOR.NORMAL)),t.updateProjectionMatrix(),o)n.minDistance=t.near*2,n.maxDistance=t.far*.9;else{let m=c*v.InitialDistanceMultiplier;t.position.set(a.x+m*.8,a.y+m,a.z+m*1.2),n.target.copy(a),n.minDistance=t.near*2,n.maxDistance=t.far*.9,n.update()}}function F(e){if(!e||typeof e!="string")return _chunkMTDJ3VNBcjs.i.call(void 0, ).warn(`Invalid color input: ${e}, using white`),new w.Color(16777215);let r=e.trim();if(r.startsWith("#")||/^[0-9A-Fa-f]{6}$/.test(r))try{let t=r.startsWith("#")?r:`#${r}`;return new w.Color(t)}catch (e2){return _chunkMTDJ3VNBcjs.i.call(void 0, ).warn(`Invalid hex color: ${e}, using white`),new w.Color(16777215)}if(r.includes(",")){let t=r.split(",").map(n=>parseInt(n.trim(),10));if(t.length===3&&t.every(n=>!isNaN(n)&&n>=0&&n<=255))return new w.Color(t[0]/255,t[1]/255,t[2]/255)}try{return new w.Color(r.toLowerCase())}catch (e3){return _chunkMTDJ3VNBcjs.i.call(void 0, ).warn(`Invalid color string: ${e}, using white`),new w.Color(16777215)}}function P(e,r){e.forEach(t=>{t.position.y-=r,t.updateMatrix()})}function B(e){let r=new w.Box3;return e.forEach(t=>{t.updateMatrixWorld(!0);let n=new w.Box3().setFromObject(t);r.union(n)}),r}function Ee(e){let r=[];e.traverse(t=>{t instanceof w.Mesh&&t.userData.id!=="floor"&&r.push(t)}),r.forEach(t=>{t instanceof w.Mesh&&(_optionalChain([t, 'access', _124 => _124.geometry, 'optionalAccess', _125 => _125.dispose, 'call', _126 => _126()]),(Array.isArray(t.material)?t.material:[t.material]).forEach(o=>{for(let s in o){let a=o[s];a&&a instanceof w.Texture&&a.dispose()}o.dispose()})),t.removeFromParent()})}var z={};_chunkMTDJ3VNBcjs.a.call(void 0, z,{CONCRETE_MATERIAL:()=>ge,EMISSIVE_MATERIAL:()=>ue,GLASS_MATERIAL:()=>Te,METAL_MATERIAL:()=>pe,PLASTIC_MATERIAL:()=>Re,RUBBER_MATERIAL:()=>we,WOOD_MATERIAL:()=>ye});var ue=new u.MeshPhysicalMaterial({color:0,emissive:new u.Color(16777215),emissiveIntensity:5,metalness:0,roughness:.2,clearcoat:.3,clearcoatRoughness:.2,depthWrite:!0,depthTest:!0,transparent:!1,alphaTest:0,polygonOffset:!0,side:u.FrontSide,dithering:!0}),pe=new u.MeshPhysicalMaterial({color:new u.Color(0),metalness:.9,roughness:.3,envMapIntensity:1.2,clearcoat:.3,clearcoatRoughness:.2,reflectivity:1,ior:2.5,thickness:1,depthWrite:!0,transparent:!1,alphaTest:0,depthTest:!0,polygonOffset:!0,side:u.FrontSide,dithering:!0}),ge=new u.MeshPhysicalMaterial({color:new u.Color(13421772),metalness:0,roughness:.92,envMapIntensity:.15,clearcoat:.05,clearcoatRoughness:.9,reflectivity:.15,transmission:0,ior:1.45,thickness:0,depthWrite:!0,transparent:!1,alphaTest:.5,depthTest:!0,polygonOffset:!0,side:u.FrontSide,dithering:!0}),Re=new u.MeshPhysicalMaterial({color:new u.Color(16777215),metalness:0,roughness:.3,envMapIntensity:.5,clearcoat:.5,clearcoatRoughness:.1,reflectivity:.5,ior:1.4,transmission:0,transparent:!1,depthWrite:!0,side:u.FrontSide,dithering:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),Te=new u.MeshPhysicalMaterial({color:new u.Color(16777215),metalness:0,roughness:0,transmission:.95,transparent:!0,opacity:.3,envMapIntensity:1,clearcoat:1,clearcoatRoughness:0,ior:1.52,reflectivity:.9,thickness:1,side:u.DoubleSide,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),we=new u.MeshPhysicalMaterial({color:new u.Color(1710618),metalness:0,roughness:.9,envMapIntensity:.2,clearcoat:.1,clearcoatRoughness:.8,reflectivity:.2,ior:1.3,transmission:0,depthWrite:!0,side:u.FrontSide,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),ye=new u.MeshPhysicalMaterial({color:new u.Color(8934707),metalness:0,roughness:.7,envMapIntensity:.3,clearcoat:.3,clearcoatRoughness:.4,reflectivity:.3,ior:1.3,transmission:0,depthWrite:!0,side:u.FrontSide,dithering:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1});var _fflate = require('fflate'); var $ = _interopRequireWildcard(_fflate);_chunkMTDJ3VNBcjs.h.call(void 0, );async function q(e){return new Promise((r,t)=>{try{let n=()=>{try{let o=_chunkFB4LUGFJcjs.c.call(void 0, e),s=$.gunzipSync(o),a=be(s);r(a)}catch(o){t(new (0, _chunkMTDJ3VNBcjs.e)(o instanceof _chunkMTDJ3VNBcjs.e?o.message:`Failed to decompress batched data: ${o instanceof Error?o.message:String(o)}`,o instanceof _chunkMTDJ3VNBcjs.e?o.code:_chunkMTDJ3VNBcjs.d.VALIDATION_ERROR,{context:{base64StringLength:e.length},originalError:o instanceof Error?o:new Error(String(o))}))}};"requestIdleCallback"in globalThis?globalThis.requestIdleCallback(n,{timeout:5e3}):setTimeout(n,0)}catch(n){t(new (0, _chunkMTDJ3VNBcjs.e)(`Failed to schedule decompression: ${n instanceof Error?n.message:String(n)}`,_chunkMTDJ3VNBcjs.d.VALIDATION_ERROR,{originalError:n instanceof Error?n:new Error(String(n))}))}})}function be(e){let r=new DataView(e.buffer,e.byteOffset,e.byteLength),t=0;if(t+4>r.byteLength)throw new (0, _chunkMTDJ3VNBcjs.e)("Insufficient data to read the number of vertex floats.",_chunkMTDJ3VNBcjs.d.VALIDATION_ERROR,{context:{expectedBytes:4,availableBytes:r.byteLength,offset:t}});let n=r.getUint32(t,!0);if(t+=4,n%3!==0)throw new (0, _chunkMTDJ3VNBcjs.e)("Invalid number of vertex floats; should be divisible by 3.",_chunkMTDJ3VNBcjs.d.VALIDATION_ERROR,{context:{numVertexFloats:n,remainder:n%3,totalBytes:r.byteLength}});let o=n*Float32Array.BYTES_PER_ELEMENT;if(t+o>r.byteLength)throw new (0, _chunkMTDJ3VNBcjs.e)("Insufficient data to read vertices.",_chunkMTDJ3VNBcjs.d.VALIDATION_ERROR,{context:{expectedBytes:o,availableBytes:r.byteLength-t,offset:t}});let s=new Float32Array(e.buffer,e.byteOffset+t,n);if(t+=o,t+4>r.byteLength)throw new (0, _chunkMTDJ3VNBcjs.e)("Insufficient data to read the number of face indices.",_chunkMTDJ3VNBcjs.d.VALIDATION_ERROR,{context:{expectedBytes:4,availableBytes:r.byteLength-t,offset:t}});let a=r.getUint32(t,!0);t+=4;let l=a*Uint32Array.BYTES_PER_ELEMENT;if(t+l>r.byteLength)throw new (0, _chunkMTDJ3VNBcjs.e)("Insufficient data to read face indices.",_chunkMTDJ3VNBcjs.d.VALIDATION_ERROR,{context:{expectedBytes:l,availableBytes:r.byteLength-t,offset:t}});let c=new Uint32Array(e.buffer,e.byteOffset+t,a);return{vertices:s,faces:c}}async function _(e,r){let{mergeByMaterial:t=!0,applyTransforms:n=!0,debug:o=!1}=_nullishCoalesce(r, () => ({})),s=o?performance.now():0,a=0;try{let l=performance.now(),c=JSON.parse(e);return a=performance.now()-l,await V(c,{mergeByMaterial:t,applyTransforms:n,debug:o,parseTime:a,perfStart:s})}catch(l){return _chunkMTDJ3VNBcjs.i.call(void 0, ).error("Error parsing mesh batch:",l),[]}}async function V(e,r){let{mergeByMaterial:t=!0,applyTransforms:n=!0,scaleFactor:o=1,debug:s=!1,parseTime:a=0,perfStart:l=s?performance.now():0}=_nullishCoalesce(r, () => ({})),c=0,R=0;try{let m=performance.now(),{vertices:h,faces:E}=await q(e.compressedData);c=performance.now()-m;let M=(e.compressedData.length*.75/1024/1024).toFixed(2),f=((h.byteLength+E.byteLength)/1024/1024).toFixed(2),H=((1-parseFloat(M)/parseFloat(f))*100).toFixed(1);s&&(_chunkMTDJ3VNBcjs.i.call(void 0, ).debug("Mesh Batch Stats:"),_chunkMTDJ3VNBcjs.i.call(void 0, ).debug(` Materials: ${e.materials.length} | Groups: ${e.groups.length}`),_chunkMTDJ3VNBcjs.i.call(void 0, ).debug(` Vertices: ${(h.length/3).toLocaleString()} | Faces: ${(E.length/3).toLocaleString()}`),_chunkMTDJ3VNBcjs.i.call(void 0, ).debug(` Compressed: ${M} MB | Uncompressed: ${f} MB`),_chunkMTDJ3VNBcjs.i.call(void 0, ).debug(` Compression Ratio: ${H}%`)),n&&ve(h);let C=performance.now(),I=e.materials.map(Me),d=[];for(let g of e.groups)if(t&&g.meshes.length>1){let y=He(g,h,E,I);d.push(y)}else{let y=xe(g,h,E,I);d.push(...y)}if(o!==1)for(let g of d)g.scale.set(o,o,o);if(R=performance.now()-C,s){let g=performance.now()-l;_chunkMTDJ3VNBcjs.i.call(void 0, ).debug("Performance:"),a>0&&_chunkMTDJ3VNBcjs.i.call(void 0, ).debug(` Parse JSON: ${a.toFixed(2)}ms`),_chunkMTDJ3VNBcjs.i.call(void 0, ).debug(` Decompress: ${c.toFixed(2)}ms`),_chunkMTDJ3VNBcjs.i.call(void 0, ).debug(` Create Meshes: ${R.toFixed(2)}ms`),_chunkMTDJ3VNBcjs.i.call(void 0, ).debug(` Total: ${g.toFixed(2)}ms`)}return d}catch(m){return _chunkMTDJ3VNBcjs.i.call(void 0, ).error("Error parsing mesh batch object:",m),[]}}function Me(e){let r=F(e.color);return new b.MeshPhysicalMaterial({color:r,metalness:e.metalness,roughness:e.roughness,opacity:e.opacity,transparent:e.transparent,side:b.DoubleSide,polygonOffset:!0,polygonOffsetFactor:.5,polygonOffsetUnits:.5,depthWrite:!0,depthTest:!0})}function He(e,r,t,n){let o=new b.BufferGeometry,s=0,a=0;for(let f of e.meshes)s+=f.vertexCount,a+=f.faceCount;let l=new Float32Array(s),c=new Uint32Array(a),R=0,m=0;for(let f of e.meshes){l.set(r.subarray(f.vertexOffset,f.vertexOffset+f.vertexCount),R);let H=t.subarray(f.faceOffset,f.faceOffset+f.faceCount),C=Math.floor(f.vertexOffset/3),d=Math.floor(R/3)-C;for(let g=0;g<H.length;g++)c[m+g]=H[g]+d;R+=f.vertexCount,m+=f.faceCount}o.setAttribute("position",new b.BufferAttribute(l,3)),o.setIndex(new b.BufferAttribute(c,1)),o.computeVertexNormals();let h=new b.Mesh(o,n[e.materialId]),E=e.meshes.map(f=>f.name).filter(f=>f&&f.length>0);h.name=E.length>0?E[0]:`merged_material_${e.materialId}`,h.castShadow=!0,h.receiveShadow=!0;let M=e.meshes.map(f=>f.metadata).filter(f=>f);return M.length>0&&(h.userData.mergedMetadata=M),h}function xe(e,r,t,n){let o=[];for(let s of e.meshes){let a=new b.BufferGeometry,l=r.subarray(s.vertexOffset,s.vertexOffset+s.vertexCount),c=t.subarray(s.faceOffset,s.faceOffset+s.faceCount),R=Math.floor(s.vertexOffset/3),m=new Uint32Array(c.length);for(let E=0;E<c.length;E++)m[E]=c[E]-R;a.setAttribute("position",new b.BufferAttribute(l,3)),a.setIndex(new b.BufferAttribute(m,1)),a.computeVertexNormals();let h=new b.Mesh(a,n[e.materialId]);h.name=s.name,s.metadata&&(h.userData={...h.userData,...s.metadata}),h.castShadow=!0,h.receiveShadow=!0,o.push(h)}return o}function ve(e){let r=Math.cos(-Math.PI/2),t=Math.sin(-Math.PI/2);for(let n=0;n<e.length;n+=3){let o=e[n],s=e[n+1],a=e[n+2];e[n]=o,e[n+1]=s*r-a*t,e[n+2]=s*t+a*r}}var k={Millimeters:1/1e3,Centimeters:1/100,Meters:1,Inches:1/39.37,Feet:1/3.28084},Ce="Display";async function Y(e,r){let t=performance.now(),n=[],{allowScaling:o=!0,allowAutoPosition:s=!0,debug:a=!1,parsing:l={}}=_nullishCoalesce(r, () => ({}));try{let c=o?Oe(e.modelunits):1;return await Se(e,n,c,l,a),s&&De(n),n}catch(c){throw Le(c,n),c}finally{a&&Be(t)}}function Oe(e){return _nullishCoalesce(k[e], () => (1))}async function Se(e,r,t,n,o){for(let s of e.values){let a=s.InnerTree;for(let l in a){let c=a[l];c&&await Ae(c,r,t,n,o)}}}async function Ae(e,r,t,n,o){for(let s of e)if(s.type.includes(Ce)){let a={mergeByMaterial:!0,applyTransforms:!0,debug:!1,...n},l=await _(s.data,a);if(t!==1)for(let c of l)c.scale.set(t,t,t);r.push(...l),o&&_chunkMTDJ3VNBcjs.i.call(void 0, ).debug(`Extracted ${l.length} meshes from batch`)}}function De(e){if(e.length===0)return;let t=B(e).min.y;P(e,t)}function Le(e,r){_chunkMTDJ3VNBcjs.i.call(void 0, ).error("An unexpected error occurred:",e),Ie(r)}function Ie(e){for(let r of e)r.geometry&&r.geometry.dispose(),r.material&&(Array.isArray(r.material)?r.material.forEach(t=>t.dispose()):r.material.dispose())}function Be(e){let r=performance.now()-e;_chunkMTDJ3VNBcjs.i.call(void 0, ).info("Time to process meshes:",`${r.toFixed(2)}ms`)}exports.Materials = z; exports.SCALE_FACTORS = k; exports.getThreeMeshesFromComputeResponse = Y; exports.initThree = U; exports.parseMeshBatchObject = V; exports.updateScene = W;
2
2
  //# sourceMappingURL=visualization.cjs.map
@@ -1,2 +1,2 @@
1
- import{c as N}from"./chunk-WD3ENUAA.js";import{a as J,d as S,e as x,h as Q,i as p}from"./chunk-MK3M76VN.js";import*as i from"three";import{OrbitControls as ee}from"three/addons/controls/OrbitControls.js";import{HDRLoader as te}from"three/addons/loaders/HDRLoader.js";var G=new i.Vector3(0,0,1),U=function(e,r){let t=ne(r||{}),n=re(t),o=fe(t,e),s=de(e,t),a=me(o,e,t);ie(n,t),ce(n,t),t.floor?.enabled&&le(n,t);let l=t.events.enableEventHandlers!==!1?he(e,n,o,a,t):{dispose:()=>{},fitToView:()=>{},clearSelection:()=>{}},{resize:c,dispose:R}=ae(e,s,o),{animate:m,dispose:h}=se(s,n,o,a);m();let E=t.environment?.sceneUp||G;return n.up.set(E.x,E.y,E.z),{scene:n,camera:o,controls:a,renderer:s,dispose:()=>{h(),R(),l.dispose(),a.dispose(),s.dispose(),n.traverse(f=>{f instanceof i.Mesh&&(f.geometry?.dispose(),Array.isArray(f.material)?f.material.forEach(H=>H.dispose()):f.material?.dispose())})},resize:c,fitToView:l.fitToView,clearSelection:l.clearSelection}};function ne(e){let r=e.sceneScale||"m",n={mm:{cameraDistance:20,near:.1,far:2e3,floorSize:100,lightDistance:10,lightHeight:20,minDistance:.1,shadowSize:100,scaleFactor:1e3},cm:{cameraDistance:20,near:.1,far:2e3,floorSize:100,lightDistance:25,lightHeight:50,minDistance:.1,shadowSize:100,scaleFactor:100},m:{cameraDistance:10,near:.01,far:2e3,floorSize:50,lightDistance:25,lightHeight:50,minDistance:.001,shadowSize:100,scaleFactor:1},inches:{cameraDistance:15,near:.1,far:2e3,floorSize:80,lightDistance:20,lightHeight:40,minDistance:.1,shadowSize:80,scaleFactor:39.37},feet:{cameraDistance:8,near:.1,far:2e3,floorSize:40,lightDistance:15,lightHeight:30,minDistance:.1,shadowSize:60,scaleFactor:3.28084}}[r];return{sceneScale:r,camera:{position:e.camera?.position||new i.Vector3(-n.cameraDistance,n.cameraDistance,n.cameraDistance),fov:e.camera?.fov||20,near:e.camera?.near||n.near,far:e.camera?.far||n.far,target:e.camera?.target||new i.Vector3(0,0,0)},lighting:{enableSunlight:e.lighting?.enableSunlight??!0,sunlightIntensity:e.lighting?.sunlightIntensity||1,sunlightPosition:e.lighting?.sunlightPosition||new i.Vector3(n.lightDistance,n.lightHeight,n.lightDistance),ambientLightColor:e.lighting?.ambientLightColor||new i.Color(4210752),ambientLightIntensity:e.lighting?.ambientLightIntensity||1,sunlightColor:e.lighting?.sunlightColor||16777215},environment:{hdrPath:e.environment?.hdrPath||"/baseHDR.hdr",backgroundColor:e.environment?.backgroundColor||new i.Color(15790320),enableEnvironmentLighting:e.environment?.enableEnvironmentLighting??!0,sceneUp:e.environment?.sceneUp||G,showEnvironment:e.environment?.showEnvironment??!1},floor:{enabled:e.floor?.enabled??!1,size:e.floor?.size||n.floorSize,color:e.floor?.color||new i.Color(8421504),roughness:e.floor?.roughness||.7,metalness:e.floor?.metalness||0,receiveShadow:e.floor?.receiveShadow??!0},render:{enableShadows:e.render?.enableShadows??!0,shadowMapSize:e.render?.shadowMapSize||2048,antialias:e.render?.antialias??!0,pixelRatio:e.render?.pixelRatio||Math.min(window.devicePixelRatio,2),toneMapping:e.render?.toneMapping||i.NeutralToneMapping,toneMappingExposure:e.render?.toneMappingExposure||1,preserveDrawingBuffer:e.render?.preserveDrawingBuffer??!1},controls:{enableDamping:e.controls?.enableDamping??!1,dampingFactor:e.controls?.dampingFactor||.05,autoRotate:e.controls?.autoRotate??!1,autoRotateSpeed:e.controls?.autoRotateSpeed||.5,enableZoom:e.controls?.enableZoom??!0,enablePan:e.controls?.enablePan??!0,minDistance:e.controls?.minDistance||n.minDistance,maxDistance:e.controls?.maxDistance||1/0},events:{onBackgroundClicked:e.events?.onBackgroundClicked,onObjectSelected:e.events?.onObjectSelected,onMeshMetadataClicked:e.events?.onMeshMetadataClicked,onMeshDoubleClicked:e.events?.onMeshDoubleClicked,selectionColor:e.events?.selectionColor||"#ff0000",enableEventHandlers:e.events?.enableEventHandlers??!0,enableKeyboardControls:e.events?.enableKeyboardControls??!0,enableClickToFocus:e.events?.enableClickToFocus??!0,enableDoubleClickZoom:e.events?.enableDoubleClickZoom??!0}}}function re(e){let r=new i.Scene,t=typeof e.environment.backgroundColor=="string"?new i.Color(e.environment.backgroundColor):e.environment.backgroundColor;return r.background=t||null,r}function oe(e,r,t,n,o=200){let s=e.position.clone(),a=r.target.clone(),l=performance.now(),c=m=>1-Math.pow(1-m,3),R=()=>{let m=performance.now()-l,h=c(Math.min(m/o,1));e.position.lerpVectors(s,t,h),r.target.lerpVectors(a,n,h),r.update(),h<1&&requestAnimationFrame(R)};requestAnimationFrame(R)}function se(e,r,t,n){let o=null,s=function(){o=requestAnimationFrame(s),(n.enableDamping||n.autoRotate)&&n.update(),e.render(r,t)};return{animate:s,dispose:()=>{o!==null&&(cancelAnimationFrame(o),o=null)}}}function ae(e,r,t){let n=e.parentElement,o=null,s=null,a=()=>n?{width:n.clientWidth,height:n.clientHeight}:{width:window.innerWidth,height:window.innerHeight},l=()=>{let{width:m,height:h}=a();if(m===0||h===0)return;let E=Math.min(window.devicePixelRatio,2),M=Math.round(r.domElement.clientWidth*E),f=Math.round(r.domElement.clientHeight*E),H=Math.round(m*E),C=Math.round(h*E);(M!==H||f!==C)&&(r.setPixelRatio(E),r.setSize(m,h,!0),t.aspect=m/h,t.updateProjectionMatrix())},c=()=>{o!==null&&cancelAnimationFrame(o),o=requestAnimationFrame(()=>{o=requestAnimationFrame(()=>{o=null,l()})})};return typeof ResizeObserver<"u"?(s=new ResizeObserver(c),n?s.observe(n):s.observe(e)):window.addEventListener("resize",c),{resize:c,dispose:()=>{o!==null&&(cancelAnimationFrame(o),o=null),s?s.disconnect():window.removeEventListener("resize",c)}}}function ie(e,r){r.environment.enableEnvironmentLighting&&new te().load(r.environment.hdrPath||"/baseHDR.hdr",function(t){t.mapping=i.EquirectangularReflectionMapping,e.environment=t,r.environment.showEnvironment&&(e.background=t)},void 0,function(t){p().warn("HDR texture could not be loaded, falling back to basic lighting:",t)})}function ce(e,r){let t=new i.AmbientLight(r.lighting.ambientLightColor,r.lighting.ambientLightIntensity);if(e.add(t),r.lighting.enableSunlight){let n=new i.DirectionalLight(r.lighting.sunlightColor??16777215,r.lighting.sunlightIntensity),o=r.lighting.sunlightPosition;if(o&&n.position.set(o.x,o.y,o.z),r.render.enableShadows){n.castShadow=!0;let s=r.sceneScale==="mm"?.1:r.sceneScale==="cm"?10:100;n.shadow.camera.left=-s,n.shadow.camera.right=s,n.shadow.camera.top=s,n.shadow.camera.bottom=-s;let a=r.sceneScale==="mm"?.001:r.sceneScale==="cm"?.1:.5,l=r.sceneScale==="mm"?1:r.sceneScale==="cm"?100:500;n.shadow.camera.near=a,n.shadow.camera.far=l,n.shadow.mapSize.width=r.render.shadowMapSize||2048,n.shadow.mapSize.height=r.render.shadowMapSize||2048,n.shadow.bias=-1e-4,n.shadow.normalBias=.02}e.add(n)}}function le(e,r){let t=r.floor.size,n=new i.PlaneGeometry(t,t),o=typeof r.floor.color=="string"?new i.Color(r.floor.color):r.floor.color,s=new i.MeshStandardMaterial({color:o,roughness:r.floor.roughness,metalness:r.floor.metalness,side:i.DoubleSide}),a=new i.Mesh(n,s);a.userData.id="floor",a.name="floor",a.rotation.x=-Math.PI/2,a.position.y=0,r.floor.receiveShadow&&r.render.enableShadows&&(a.receiveShadow=!0),e.add(a)}function fe(e,r){let t=r.parentElement,n=t?t.clientWidth:window.innerWidth,o=t?t.clientHeight:window.innerHeight,s=new i.PerspectiveCamera(e.camera.fov,n/o,e.camera.near,e.camera.far),a=e.camera.position;return a&&s.position.set(a.x,a.y,a.z),s}function de(e,r){let t=new i.WebGLRenderer({antialias:r.render.antialias,canvas:e,alpha:!0,powerPreference:"high-performance",preserveDrawingBuffer:r.render.preserveDrawingBuffer,logarithmicDepthBuffer:!0}),n=e.parentElement,o=n?n.clientWidth:window.innerWidth,s=n?n.clientHeight:window.innerHeight;return n&&(e.style.width="100%",e.style.height="100%",e.style.display="block"),t.setSize(o,s,!0),t.setPixelRatio(r.render.pixelRatio||Math.min(window.devicePixelRatio,2)),r.render.enableShadows&&(t.shadowMap.enabled=!0,t.shadowMap.type=i.VSMShadowMap),t.toneMapping=r.render.toneMapping||i.ACESFilmicToneMapping,t.toneMappingExposure=r.render.toneMappingExposure||1,t.outputColorSpace=i.SRGBColorSpace,t.sortObjects=!0,t}function he(e,r,t,n,o){let s=new Set,a=new Map,l=new i.Raycaster,c=new i.Vector2,R=new i.Vector2,m=()=>{let d=new i.Box3;if(r.traverse(D=>{D.visible&&D.userData.id!=="floor"&&D instanceof i.Mesh&&d.expandByObject(D)}),d.isEmpty()){p().warn("No objects to fit to view");return}let g=d.getCenter(new i.Vector3),y=d.getSize(new i.Vector3),A=Math.max(y.x,y.y,y.z),T=t.fov*(Math.PI/180),O=A/(2*Math.tan(T/2));O*=1.5;let L=t.position.clone().sub(n.target).normalize();t.position.copy(g.clone().add(L.multiplyScalar(O))),n.target.copy(g),n.update()},h=typeof o.events.selectionColor=="string"?new i.Color(o.events.selectionColor):o.events.selectionColor instanceof i.Color?o.events.selectionColor:new i.Color("#ff0000"),E=()=>{s.forEach(d=>{d instanceof i.Mesh&&a.has(d)&&(d.material=a.get(d),a.delete(d))}),s.clear()},M=d=>{R.set(d.clientX,d.clientY)},f=d=>{let g=new i.Vector2(d.clientX,d.clientY);if(R.distanceTo(g)>5)return;let y=e.getBoundingClientRect();c.x=(d.clientX-y.left)/y.width*2-1,c.y=-((d.clientY-y.top)/y.height)*2+1,l.setFromCamera(c,t);let A=l.intersectObjects(r.children,!0);if(A.length>0){let T=A[0].object;if(!s.has(T)){if(E(),s.add(T),T instanceof i.Mesh&&T.material instanceof i.Material){a.set(T,T.material);let O=T.material.clone();O.emissive=h.clone(),T.material=O}o.events?.onObjectSelected?.(T),T instanceof i.Mesh&&Object.keys(T.userData).length>0&&o.events?.onMeshMetadataClicked?.(T.userData)}}else E(),o.events?.onBackgroundClicked?.({x:c.x,y:c.y})},H=d=>{let g=e.getBoundingClientRect();c.x=(d.clientX-g.left)/g.width*2-1,c.y=-((d.clientY-g.top)/g.height)*2+1,l.setFromCamera(c,t);let y=l.intersectObjects(r.children,!0);if(y.length===0)return;let A=y[0].object;if(o.events?.onMeshDoubleClicked?.(A),!o.events?.enableDoubleClickZoom)return;let T=new i.Box3().setFromObject(A);if(T.isEmpty())return;let O=T.getCenter(new i.Vector3),L=T.getSize(new i.Vector3),D=Math.max(L.x,L.y,L.z),j=t.fov*(Math.PI/180),Z=D/(2*Math.tan(j/2))*1.5,K=t.position.clone().sub(n.target).normalize(),X=O.clone().add(K.multiplyScalar(Z));oe(t,n,X,O)},C=d=>{if(o.events?.enableKeyboardControls)switch(d.key.toLowerCase()){case"f":d.preventDefault(),m();break;case"escape":d.preventDefault(),E();break;case" ":d.preventDefault(),m();break}};return o.events?.enableClickToFocus&&(e.addEventListener("mousedown",M),e.addEventListener("click",f),e.addEventListener("dblclick",H)),o.events?.enableKeyboardControls&&(e.setAttribute("tabindex","0"),e.addEventListener("keydown",C)),{dispose:()=>{e.removeEventListener("mousedown",M),e.removeEventListener("click",f),e.removeEventListener("dblclick",H),e.removeEventListener("keydown",C),E()},fitToView:m,clearSelection:E}}function me(e,r,t){let n=new ee(e,r),o=t.camera.target;return o&&n.target.set(o.x,o.y,o.z),n.enableDamping=t.controls.enableDamping||!1,n.dampingFactor=t.controls.dampingFactor||.05,n.autoRotate=t.controls.autoRotate||!1,n.autoRotateSpeed=t.controls.autoRotateSpeed||.5,n.enableZoom=t.controls.enableZoom??!0,n.enablePan=t.controls.enablePan??!0,n.minDistance=t.controls.minDistance||.001,n.maxDistance=t.controls.maxDistance||1/0,n.screenSpacePanning=!1,n.maxPolarAngle=Math.PI,n.update(),n}import*as w from"three";var v={HUGE_THRESHOLD:1e4,LARGE_THRESHOLD:1e3,SCALE_RATIO_THRESHOLD:100,NEAR_PLANE_FACTOR:{TINY:1e-4,SMALL:.001,NORMAL:.01},FAR_PLANE_FACTOR:{HUGE:100,LARGE:50,NORMAL:20},InitialDistanceMultiplier:4};function W(e,r,t,n,o){if(Ee(e),r.length===0)return;r.forEach(m=>{e.add(m)});let s=B(r),a=s.getCenter(new w.Vector3),l=s.getSize(new w.Vector3),c=Math.max(l.x,l.y,l.z);if(c/Math.min(l.x||1,l.y||1,l.z||1)>v.SCALE_RATIO_THRESHOLD||c>v.HUGE_THRESHOLD?(t.near=c*v.NEAR_PLANE_FACTOR.TINY,t.far=c*v.FAR_PLANE_FACTOR.HUGE):c>v.LARGE_THRESHOLD?(t.near=c*v.NEAR_PLANE_FACTOR.SMALL,t.far=c*v.FAR_PLANE_FACTOR.LARGE):(t.near=Math.max(.01,c*v.NEAR_PLANE_FACTOR.NORMAL),t.far=Math.max(2e3,c*v.FAR_PLANE_FACTOR.NORMAL)),t.updateProjectionMatrix(),o)n.minDistance=t.near*2,n.maxDistance=t.far*.9;else{let m=c*v.InitialDistanceMultiplier;t.position.set(a.x+m*.8,a.y+m,a.z+m*1.2),n.target.copy(a),n.minDistance=t.near*2,n.maxDistance=t.far*.9,n.update()}}function F(e){if(!e||typeof e!="string")return p().warn(`Invalid color input: ${e}, using white`),new w.Color(16777215);let r=e.trim();if(r.startsWith("#")||/^[0-9A-Fa-f]{6}$/.test(r))try{let t=r.startsWith("#")?r:`#${r}`;return new w.Color(t)}catch{return p().warn(`Invalid hex color: ${e}, using white`),new w.Color(16777215)}if(r.includes(",")){let t=r.split(",").map(n=>parseInt(n.trim(),10));if(t.length===3&&t.every(n=>!isNaN(n)&&n>=0&&n<=255))return new w.Color(t[0]/255,t[1]/255,t[2]/255)}try{return new w.Color(r.toLowerCase())}catch{return p().warn(`Invalid color string: ${e}, using white`),new w.Color(16777215)}}function P(e,r){e.forEach(t=>{t.position.y-=r,t.updateMatrix()})}function B(e){let r=new w.Box3;return e.forEach(t=>{t.updateMatrixWorld(!0);let n=new w.Box3().setFromObject(t);r.union(n)}),r}function Ee(e){let r=[];e.traverse(t=>{t instanceof w.Mesh&&t.userData.id!=="floor"&&r.push(t)}),r.forEach(t=>{t instanceof w.Mesh&&(t.geometry?.dispose(),(Array.isArray(t.material)?t.material:[t.material]).forEach(o=>{for(let s in o){let a=o[s];a&&a instanceof w.Texture&&a.dispose()}o.dispose()})),t.removeFromParent()})}var z={};J(z,{CONCRETE_MATERIAL:()=>ge,EMISSIVE_MATERIAL:()=>ue,GLASS_MATERIAL:()=>Te,METAL_MATERIAL:()=>pe,PLASTIC_MATERIAL:()=>Re,RUBBER_MATERIAL:()=>we,WOOD_MATERIAL:()=>ye});import*as u from"three";var ue=new u.MeshPhysicalMaterial({color:0,emissive:new u.Color(16777215),emissiveIntensity:5,metalness:0,roughness:.2,clearcoat:.3,clearcoatRoughness:.2,depthWrite:!0,depthTest:!0,transparent:!1,alphaTest:0,polygonOffset:!0,side:u.FrontSide,dithering:!0}),pe=new u.MeshPhysicalMaterial({color:new u.Color(0),metalness:.9,roughness:.3,envMapIntensity:1.2,clearcoat:.3,clearcoatRoughness:.2,reflectivity:1,ior:2.5,thickness:1,depthWrite:!0,transparent:!1,alphaTest:0,depthTest:!0,polygonOffset:!0,side:u.FrontSide,dithering:!0}),ge=new u.MeshPhysicalMaterial({color:new u.Color(13421772),metalness:0,roughness:.92,envMapIntensity:.15,clearcoat:.05,clearcoatRoughness:.9,reflectivity:.15,transmission:0,ior:1.45,thickness:0,depthWrite:!0,transparent:!1,alphaTest:.5,depthTest:!0,polygonOffset:!0,side:u.FrontSide,dithering:!0}),Re=new u.MeshPhysicalMaterial({color:new u.Color(16777215),metalness:0,roughness:.3,envMapIntensity:.5,clearcoat:.5,clearcoatRoughness:.1,reflectivity:.5,ior:1.4,transmission:0,transparent:!1,depthWrite:!0,side:u.FrontSide,dithering:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),Te=new u.MeshPhysicalMaterial({color:new u.Color(16777215),metalness:0,roughness:0,transmission:.95,transparent:!0,opacity:.3,envMapIntensity:1,clearcoat:1,clearcoatRoughness:0,ior:1.52,reflectivity:.9,thickness:1,side:u.DoubleSide,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),we=new u.MeshPhysicalMaterial({color:new u.Color(1710618),metalness:0,roughness:.9,envMapIntensity:.2,clearcoat:.1,clearcoatRoughness:.8,reflectivity:.2,ior:1.3,transmission:0,depthWrite:!0,side:u.FrontSide,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),ye=new u.MeshPhysicalMaterial({color:new u.Color(8934707),metalness:0,roughness:.7,envMapIntensity:.3,clearcoat:.3,clearcoatRoughness:.4,reflectivity:.3,ior:1.3,transmission:0,depthWrite:!0,side:u.FrontSide,dithering:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1});import*as b from"three";import*as $ from"fflate";Q();async function q(e){return new Promise((r,t)=>{try{let n=()=>{try{let o=N(e),s=$.gunzipSync(o),a=be(s);r(a)}catch(o){t(new x(o instanceof x?o.message:`Failed to decompress batched data: ${o instanceof Error?o.message:String(o)}`,o instanceof x?o.code:S.VALIDATION_ERROR,{context:{base64StringLength:e.length},originalError:o instanceof Error?o:new Error(String(o))}))}};"requestIdleCallback"in globalThis?globalThis.requestIdleCallback(n,{timeout:5e3}):setTimeout(n,0)}catch(n){t(new x(`Failed to schedule decompression: ${n instanceof Error?n.message:String(n)}`,S.VALIDATION_ERROR,{originalError:n instanceof Error?n:new Error(String(n))}))}})}function be(e){let r=new DataView(e.buffer,e.byteOffset,e.byteLength),t=0;if(t+4>r.byteLength)throw new x("Insufficient data to read the number of vertex floats.",S.VALIDATION_ERROR,{context:{expectedBytes:4,availableBytes:r.byteLength,offset:t}});let n=r.getUint32(t,!0);if(t+=4,n%3!==0)throw new x("Invalid number of vertex floats; should be divisible by 3.",S.VALIDATION_ERROR,{context:{numVertexFloats:n,remainder:n%3,totalBytes:r.byteLength}});let o=n*Float32Array.BYTES_PER_ELEMENT;if(t+o>r.byteLength)throw new x("Insufficient data to read vertices.",S.VALIDATION_ERROR,{context:{expectedBytes:o,availableBytes:r.byteLength-t,offset:t}});let s=new Float32Array(e.buffer,e.byteOffset+t,n);if(t+=o,t+4>r.byteLength)throw new x("Insufficient data to read the number of face indices.",S.VALIDATION_ERROR,{context:{expectedBytes:4,availableBytes:r.byteLength-t,offset:t}});let a=r.getUint32(t,!0);t+=4;let l=a*Uint32Array.BYTES_PER_ELEMENT;if(t+l>r.byteLength)throw new x("Insufficient data to read face indices.",S.VALIDATION_ERROR,{context:{expectedBytes:l,availableBytes:r.byteLength-t,offset:t}});let c=new Uint32Array(e.buffer,e.byteOffset+t,a);return{vertices:s,faces:c}}async function _(e,r){let{mergeByMaterial:t=!0,applyTransforms:n=!0,debug:o=!1}=r??{},s=o?performance.now():0,a=0;try{let l=performance.now(),c=JSON.parse(e);return a=performance.now()-l,await V(c,{mergeByMaterial:t,applyTransforms:n,debug:o,parseTime:a,perfStart:s})}catch(l){return p().error("Error parsing mesh batch:",l),[]}}async function V(e,r){let{mergeByMaterial:t=!0,applyTransforms:n=!0,scaleFactor:o=1,debug:s=!1,parseTime:a=0,perfStart:l=s?performance.now():0}=r??{},c=0,R=0;try{let m=performance.now(),{vertices:h,faces:E}=await q(e.compressedData);c=performance.now()-m;let M=(e.compressedData.length*.75/1024/1024).toFixed(2),f=((h.byteLength+E.byteLength)/1024/1024).toFixed(2),H=((1-parseFloat(M)/parseFloat(f))*100).toFixed(1);s&&(p().debug("Mesh Batch Stats:"),p().debug(` Materials: ${e.materials.length} | Groups: ${e.groups.length}`),p().debug(` Vertices: ${(h.length/3).toLocaleString()} | Faces: ${(E.length/3).toLocaleString()}`),p().debug(` Compressed: ${M} MB | Uncompressed: ${f} MB`),p().debug(` Compression Ratio: ${H}%`)),n&&ve(h);let C=performance.now(),I=e.materials.map(Me),d=[];for(let g of e.groups)if(t&&g.meshes.length>1){let y=He(g,h,E,I);d.push(y)}else{let y=xe(g,h,E,I);d.push(...y)}if(o!==1)for(let g of d)g.scale.set(o,o,o);if(R=performance.now()-C,s){let g=performance.now()-l;p().debug("Performance:"),a>0&&p().debug(` Parse JSON: ${a.toFixed(2)}ms`),p().debug(` Decompress: ${c.toFixed(2)}ms`),p().debug(` Create Meshes: ${R.toFixed(2)}ms`),p().debug(` Total: ${g.toFixed(2)}ms`)}return d}catch(m){return p().error("Error parsing mesh batch object:",m),[]}}function Me(e){let r=F(e.color);return new b.MeshPhysicalMaterial({color:r,metalness:e.metalness,roughness:e.roughness,opacity:e.opacity,transparent:e.transparent,side:b.DoubleSide,polygonOffset:!0,polygonOffsetFactor:.5,polygonOffsetUnits:.5,depthWrite:!0,depthTest:!0})}function He(e,r,t,n){let o=new b.BufferGeometry,s=0,a=0;for(let f of e.meshes)s+=f.vertexCount,a+=f.faceCount;let l=new Float32Array(s),c=new Uint32Array(a),R=0,m=0;for(let f of e.meshes){l.set(r.subarray(f.vertexOffset,f.vertexOffset+f.vertexCount),R);let H=t.subarray(f.faceOffset,f.faceOffset+f.faceCount),C=Math.floor(f.vertexOffset/3),d=Math.floor(R/3)-C;for(let g=0;g<H.length;g++)c[m+g]=H[g]+d;R+=f.vertexCount,m+=f.faceCount}o.setAttribute("position",new b.BufferAttribute(l,3)),o.setIndex(new b.BufferAttribute(c,1)),o.computeVertexNormals();let h=new b.Mesh(o,n[e.materialId]),E=e.meshes.map(f=>f.name).filter(f=>f&&f.length>0);h.name=E.length>0?E[0]:`merged_material_${e.materialId}`,h.castShadow=!0,h.receiveShadow=!0;let M=e.meshes.map(f=>f.metadata).filter(f=>f);return M.length>0&&(h.userData.mergedMetadata=M),h}function xe(e,r,t,n){let o=[];for(let s of e.meshes){let a=new b.BufferGeometry,l=r.subarray(s.vertexOffset,s.vertexOffset+s.vertexCount),c=t.subarray(s.faceOffset,s.faceOffset+s.faceCount),R=Math.floor(s.vertexOffset/3),m=new Uint32Array(c.length);for(let E=0;E<c.length;E++)m[E]=c[E]-R;a.setAttribute("position",new b.BufferAttribute(l,3)),a.setIndex(new b.BufferAttribute(m,1)),a.computeVertexNormals();let h=new b.Mesh(a,n[e.materialId]);h.name=s.name,s.metadata&&(h.userData={...h.userData,...s.metadata}),h.castShadow=!0,h.receiveShadow=!0,o.push(h)}return o}function ve(e){let r=Math.cos(-Math.PI/2),t=Math.sin(-Math.PI/2);for(let n=0;n<e.length;n+=3){let o=e[n],s=e[n+1],a=e[n+2];e[n]=o,e[n+1]=s*r-a*t,e[n+2]=s*t+a*r}}var k={Millimeters:1/1e3,Centimeters:1/100,Meters:1,Inches:1/39.37,Feet:1/3.28084},Ce="Display";async function Y(e,r){let t=performance.now(),n=[],{allowScaling:o=!0,allowAutoPosition:s=!0,debug:a=!1,parsing:l={}}=r??{};try{let c=o?Oe(e.modelunits):1;return await Se(e,n,c,l,a),s&&De(n),n}catch(c){throw Le(c,n),c}finally{a&&Be(t)}}function Oe(e){return k[e]??1}async function Se(e,r,t,n,o){for(let s of e.values){let a=s.InnerTree;for(let l in a){let c=a[l];c&&await Ae(c,r,t,n,o)}}}async function Ae(e,r,t,n,o){for(let s of e)if(s.type.includes(Ce)){let a={mergeByMaterial:!0,applyTransforms:!0,debug:!1,...n},l=await _(s.data,a);if(t!==1)for(let c of l)c.scale.set(t,t,t);r.push(...l),o&&p().debug(`Extracted ${l.length} meshes from batch`)}}function De(e){if(e.length===0)return;let t=B(e).min.y;P(e,t)}function Le(e,r){p().error("An unexpected error occurred:",e),Ie(r)}function Ie(e){for(let r of e)r.geometry&&r.geometry.dispose(),r.material&&(Array.isArray(r.material)?r.material.forEach(t=>t.dispose()):r.material.dispose())}function Be(e){let r=performance.now()-e;p().info("Time to process meshes:",`${r.toFixed(2)}ms`)}export{z as Materials,k as SCALE_FACTORS,Y as getThreeMeshesFromComputeResponse,U as initThree,V as parseMeshBatchObject,W as updateScene};
1
+ import{c as N}from"./chunk-RGHW3SLU.js";import{a as J,d as S,e as x,h as Q,i as p}from"./chunk-BL2RNK2F.js";import*as i from"three";import{OrbitControls as ee}from"three/addons/controls/OrbitControls.js";import{HDRLoader as te}from"three/addons/loaders/HDRLoader.js";var G=new i.Vector3(0,0,1),U=function(e,r){let t=ne(r||{}),n=re(t),o=fe(t,e),s=de(e,t),a=me(o,e,t);ie(n,t),ce(n,t),t.floor?.enabled&&le(n,t);let l=t.events.enableEventHandlers!==!1?he(e,n,o,a,t):{dispose:()=>{},fitToView:()=>{},clearSelection:()=>{}},{resize:c,dispose:R}=ae(e,s,o),{animate:m,dispose:h}=se(s,n,o,a);m();let E=t.environment?.sceneUp||G;return n.up.set(E.x,E.y,E.z),{scene:n,camera:o,controls:a,renderer:s,dispose:()=>{h(),R(),l.dispose(),a.dispose(),s.dispose(),n.traverse(f=>{f instanceof i.Mesh&&(f.geometry?.dispose(),Array.isArray(f.material)?f.material.forEach(H=>H.dispose()):f.material?.dispose())})},resize:c,fitToView:l.fitToView,clearSelection:l.clearSelection}};function ne(e){let r=e.sceneScale||"m",n={mm:{cameraDistance:20,near:.1,far:2e3,floorSize:100,lightDistance:10,lightHeight:20,minDistance:.1,shadowSize:100,scaleFactor:1e3},cm:{cameraDistance:20,near:.1,far:2e3,floorSize:100,lightDistance:25,lightHeight:50,minDistance:.1,shadowSize:100,scaleFactor:100},m:{cameraDistance:10,near:.01,far:2e3,floorSize:50,lightDistance:25,lightHeight:50,minDistance:.001,shadowSize:100,scaleFactor:1},inches:{cameraDistance:15,near:.1,far:2e3,floorSize:80,lightDistance:20,lightHeight:40,minDistance:.1,shadowSize:80,scaleFactor:39.37},feet:{cameraDistance:8,near:.1,far:2e3,floorSize:40,lightDistance:15,lightHeight:30,minDistance:.1,shadowSize:60,scaleFactor:3.28084}}[r];return{sceneScale:r,camera:{position:e.camera?.position||new i.Vector3(-n.cameraDistance,n.cameraDistance,n.cameraDistance),fov:e.camera?.fov||20,near:e.camera?.near||n.near,far:e.camera?.far||n.far,target:e.camera?.target||new i.Vector3(0,0,0)},lighting:{enableSunlight:e.lighting?.enableSunlight??!0,sunlightIntensity:e.lighting?.sunlightIntensity||1,sunlightPosition:e.lighting?.sunlightPosition||new i.Vector3(n.lightDistance,n.lightHeight,n.lightDistance),ambientLightColor:e.lighting?.ambientLightColor||new i.Color(4210752),ambientLightIntensity:e.lighting?.ambientLightIntensity||1,sunlightColor:e.lighting?.sunlightColor||16777215},environment:{hdrPath:e.environment?.hdrPath||"/baseHDR.hdr",backgroundColor:e.environment?.backgroundColor||new i.Color(15790320),enableEnvironmentLighting:e.environment?.enableEnvironmentLighting??!0,sceneUp:e.environment?.sceneUp||G,showEnvironment:e.environment?.showEnvironment??!1},floor:{enabled:e.floor?.enabled??!1,size:e.floor?.size||n.floorSize,color:e.floor?.color||new i.Color(8421504),roughness:e.floor?.roughness||.7,metalness:e.floor?.metalness||0,receiveShadow:e.floor?.receiveShadow??!0},render:{enableShadows:e.render?.enableShadows??!0,shadowMapSize:e.render?.shadowMapSize||2048,antialias:e.render?.antialias??!0,pixelRatio:e.render?.pixelRatio||Math.min(window.devicePixelRatio,2),toneMapping:e.render?.toneMapping||i.NeutralToneMapping,toneMappingExposure:e.render?.toneMappingExposure||1,preserveDrawingBuffer:e.render?.preserveDrawingBuffer??!1},controls:{enableDamping:e.controls?.enableDamping??!1,dampingFactor:e.controls?.dampingFactor||.05,autoRotate:e.controls?.autoRotate??!1,autoRotateSpeed:e.controls?.autoRotateSpeed||.5,enableZoom:e.controls?.enableZoom??!0,enablePan:e.controls?.enablePan??!0,minDistance:e.controls?.minDistance||n.minDistance,maxDistance:e.controls?.maxDistance||1/0},events:{onBackgroundClicked:e.events?.onBackgroundClicked,onObjectSelected:e.events?.onObjectSelected,onMeshMetadataClicked:e.events?.onMeshMetadataClicked,onMeshDoubleClicked:e.events?.onMeshDoubleClicked,selectionColor:e.events?.selectionColor||"#ff0000",enableEventHandlers:e.events?.enableEventHandlers??!0,enableKeyboardControls:e.events?.enableKeyboardControls??!0,enableClickToFocus:e.events?.enableClickToFocus??!0,enableDoubleClickZoom:e.events?.enableDoubleClickZoom??!0}}}function re(e){let r=new i.Scene,t=typeof e.environment.backgroundColor=="string"?new i.Color(e.environment.backgroundColor):e.environment.backgroundColor;return r.background=t||null,r}function oe(e,r,t,n,o=200){let s=e.position.clone(),a=r.target.clone(),l=performance.now(),c=m=>1-Math.pow(1-m,3),R=()=>{let m=performance.now()-l,h=c(Math.min(m/o,1));e.position.lerpVectors(s,t,h),r.target.lerpVectors(a,n,h),r.update(),h<1&&requestAnimationFrame(R)};requestAnimationFrame(R)}function se(e,r,t,n){let o=null,s=function(){o=requestAnimationFrame(s),(n.enableDamping||n.autoRotate)&&n.update(),e.render(r,t)};return{animate:s,dispose:()=>{o!==null&&(cancelAnimationFrame(o),o=null)}}}function ae(e,r,t){let n=e.parentElement,o=null,s=null,a=()=>n?{width:n.clientWidth,height:n.clientHeight}:{width:window.innerWidth,height:window.innerHeight},l=()=>{let{width:m,height:h}=a();if(m===0||h===0)return;let E=Math.min(window.devicePixelRatio,2),M=Math.round(r.domElement.clientWidth*E),f=Math.round(r.domElement.clientHeight*E),H=Math.round(m*E),C=Math.round(h*E);(M!==H||f!==C)&&(r.setPixelRatio(E),r.setSize(m,h,!0),t.aspect=m/h,t.updateProjectionMatrix())},c=()=>{o!==null&&cancelAnimationFrame(o),o=requestAnimationFrame(()=>{o=requestAnimationFrame(()=>{o=null,l()})})};return typeof ResizeObserver<"u"?(s=new ResizeObserver(c),n?s.observe(n):s.observe(e)):window.addEventListener("resize",c),{resize:c,dispose:()=>{o!==null&&(cancelAnimationFrame(o),o=null),s?s.disconnect():window.removeEventListener("resize",c)}}}function ie(e,r){r.environment.enableEnvironmentLighting&&new te().load(r.environment.hdrPath||"/baseHDR.hdr",function(t){t.mapping=i.EquirectangularReflectionMapping,e.environment=t,r.environment.showEnvironment&&(e.background=t)},void 0,function(t){p().warn("HDR texture could not be loaded, falling back to basic lighting:",t)})}function ce(e,r){let t=new i.AmbientLight(r.lighting.ambientLightColor,r.lighting.ambientLightIntensity);if(e.add(t),r.lighting.enableSunlight){let n=new i.DirectionalLight(r.lighting.sunlightColor??16777215,r.lighting.sunlightIntensity),o=r.lighting.sunlightPosition;if(o&&n.position.set(o.x,o.y,o.z),r.render.enableShadows){n.castShadow=!0;let s=r.sceneScale==="mm"?.1:r.sceneScale==="cm"?10:100;n.shadow.camera.left=-s,n.shadow.camera.right=s,n.shadow.camera.top=s,n.shadow.camera.bottom=-s;let a=r.sceneScale==="mm"?.001:r.sceneScale==="cm"?.1:.5,l=r.sceneScale==="mm"?1:r.sceneScale==="cm"?100:500;n.shadow.camera.near=a,n.shadow.camera.far=l,n.shadow.mapSize.width=r.render.shadowMapSize||2048,n.shadow.mapSize.height=r.render.shadowMapSize||2048,n.shadow.bias=-1e-4,n.shadow.normalBias=.02}e.add(n)}}function le(e,r){let t=r.floor.size,n=new i.PlaneGeometry(t,t),o=typeof r.floor.color=="string"?new i.Color(r.floor.color):r.floor.color,s=new i.MeshStandardMaterial({color:o,roughness:r.floor.roughness,metalness:r.floor.metalness,side:i.DoubleSide}),a=new i.Mesh(n,s);a.userData.id="floor",a.name="floor",a.rotation.x=-Math.PI/2,a.position.y=0,r.floor.receiveShadow&&r.render.enableShadows&&(a.receiveShadow=!0),e.add(a)}function fe(e,r){let t=r.parentElement,n=t?t.clientWidth:window.innerWidth,o=t?t.clientHeight:window.innerHeight,s=new i.PerspectiveCamera(e.camera.fov,n/o,e.camera.near,e.camera.far),a=e.camera.position;return a&&s.position.set(a.x,a.y,a.z),s}function de(e,r){let t=new i.WebGLRenderer({antialias:r.render.antialias,canvas:e,alpha:!0,powerPreference:"high-performance",preserveDrawingBuffer:r.render.preserveDrawingBuffer,logarithmicDepthBuffer:!0}),n=e.parentElement,o=n?n.clientWidth:window.innerWidth,s=n?n.clientHeight:window.innerHeight;return n&&(e.style.width="100%",e.style.height="100%",e.style.display="block"),t.setSize(o,s,!0),t.setPixelRatio(r.render.pixelRatio||Math.min(window.devicePixelRatio,2)),r.render.enableShadows&&(t.shadowMap.enabled=!0,t.shadowMap.type=i.VSMShadowMap),t.toneMapping=r.render.toneMapping||i.ACESFilmicToneMapping,t.toneMappingExposure=r.render.toneMappingExposure||1,t.outputColorSpace=i.SRGBColorSpace,t.sortObjects=!0,t}function he(e,r,t,n,o){let s=new Set,a=new Map,l=new i.Raycaster,c=new i.Vector2,R=new i.Vector2,m=()=>{let d=new i.Box3;if(r.traverse(D=>{D.visible&&D.userData.id!=="floor"&&D instanceof i.Mesh&&d.expandByObject(D)}),d.isEmpty()){p().warn("No objects to fit to view");return}let g=d.getCenter(new i.Vector3),y=d.getSize(new i.Vector3),A=Math.max(y.x,y.y,y.z),T=t.fov*(Math.PI/180),O=A/(2*Math.tan(T/2));O*=1.5;let L=t.position.clone().sub(n.target).normalize();t.position.copy(g.clone().add(L.multiplyScalar(O))),n.target.copy(g),n.update()},h=typeof o.events.selectionColor=="string"?new i.Color(o.events.selectionColor):o.events.selectionColor instanceof i.Color?o.events.selectionColor:new i.Color("#ff0000"),E=()=>{s.forEach(d=>{d instanceof i.Mesh&&a.has(d)&&(d.material=a.get(d),a.delete(d))}),s.clear()},M=d=>{R.set(d.clientX,d.clientY)},f=d=>{let g=new i.Vector2(d.clientX,d.clientY);if(R.distanceTo(g)>5)return;let y=e.getBoundingClientRect();c.x=(d.clientX-y.left)/y.width*2-1,c.y=-((d.clientY-y.top)/y.height)*2+1,l.setFromCamera(c,t);let A=l.intersectObjects(r.children,!0);if(A.length>0){let T=A[0].object;if(!s.has(T)){if(E(),s.add(T),T instanceof i.Mesh&&T.material instanceof i.Material){a.set(T,T.material);let O=T.material.clone();O.emissive=h.clone(),T.material=O}o.events?.onObjectSelected?.(T),T instanceof i.Mesh&&Object.keys(T.userData).length>0&&o.events?.onMeshMetadataClicked?.(T.userData)}}else E(),o.events?.onBackgroundClicked?.({x:c.x,y:c.y})},H=d=>{let g=e.getBoundingClientRect();c.x=(d.clientX-g.left)/g.width*2-1,c.y=-((d.clientY-g.top)/g.height)*2+1,l.setFromCamera(c,t);let y=l.intersectObjects(r.children,!0);if(y.length===0)return;let A=y[0].object;if(o.events?.onMeshDoubleClicked?.(A),!o.events?.enableDoubleClickZoom)return;let T=new i.Box3().setFromObject(A);if(T.isEmpty())return;let O=T.getCenter(new i.Vector3),L=T.getSize(new i.Vector3),D=Math.max(L.x,L.y,L.z),j=t.fov*(Math.PI/180),Z=D/(2*Math.tan(j/2))*1.5,K=t.position.clone().sub(n.target).normalize(),X=O.clone().add(K.multiplyScalar(Z));oe(t,n,X,O)},C=d=>{if(o.events?.enableKeyboardControls)switch(d.key.toLowerCase()){case"f":d.preventDefault(),m();break;case"escape":d.preventDefault(),E();break;case" ":d.preventDefault(),m();break}};return o.events?.enableClickToFocus&&(e.addEventListener("mousedown",M),e.addEventListener("click",f),e.addEventListener("dblclick",H)),o.events?.enableKeyboardControls&&(e.setAttribute("tabindex","0"),e.addEventListener("keydown",C)),{dispose:()=>{e.removeEventListener("mousedown",M),e.removeEventListener("click",f),e.removeEventListener("dblclick",H),e.removeEventListener("keydown",C),E()},fitToView:m,clearSelection:E}}function me(e,r,t){let n=new ee(e,r),o=t.camera.target;return o&&n.target.set(o.x,o.y,o.z),n.enableDamping=t.controls.enableDamping||!1,n.dampingFactor=t.controls.dampingFactor||.05,n.autoRotate=t.controls.autoRotate||!1,n.autoRotateSpeed=t.controls.autoRotateSpeed||.5,n.enableZoom=t.controls.enableZoom??!0,n.enablePan=t.controls.enablePan??!0,n.minDistance=t.controls.minDistance||.001,n.maxDistance=t.controls.maxDistance||1/0,n.screenSpacePanning=!1,n.maxPolarAngle=Math.PI,n.update(),n}import*as w from"three";var v={HUGE_THRESHOLD:1e4,LARGE_THRESHOLD:1e3,SCALE_RATIO_THRESHOLD:100,NEAR_PLANE_FACTOR:{TINY:1e-4,SMALL:.001,NORMAL:.01},FAR_PLANE_FACTOR:{HUGE:100,LARGE:50,NORMAL:20},InitialDistanceMultiplier:4};function W(e,r,t,n,o){if(Ee(e),r.length===0)return;r.forEach(m=>{e.add(m)});let s=B(r),a=s.getCenter(new w.Vector3),l=s.getSize(new w.Vector3),c=Math.max(l.x,l.y,l.z);if(c/Math.min(l.x||1,l.y||1,l.z||1)>v.SCALE_RATIO_THRESHOLD||c>v.HUGE_THRESHOLD?(t.near=c*v.NEAR_PLANE_FACTOR.TINY,t.far=c*v.FAR_PLANE_FACTOR.HUGE):c>v.LARGE_THRESHOLD?(t.near=c*v.NEAR_PLANE_FACTOR.SMALL,t.far=c*v.FAR_PLANE_FACTOR.LARGE):(t.near=Math.max(.01,c*v.NEAR_PLANE_FACTOR.NORMAL),t.far=Math.max(2e3,c*v.FAR_PLANE_FACTOR.NORMAL)),t.updateProjectionMatrix(),o)n.minDistance=t.near*2,n.maxDistance=t.far*.9;else{let m=c*v.InitialDistanceMultiplier;t.position.set(a.x+m*.8,a.y+m,a.z+m*1.2),n.target.copy(a),n.minDistance=t.near*2,n.maxDistance=t.far*.9,n.update()}}function F(e){if(!e||typeof e!="string")return p().warn(`Invalid color input: ${e}, using white`),new w.Color(16777215);let r=e.trim();if(r.startsWith("#")||/^[0-9A-Fa-f]{6}$/.test(r))try{let t=r.startsWith("#")?r:`#${r}`;return new w.Color(t)}catch{return p().warn(`Invalid hex color: ${e}, using white`),new w.Color(16777215)}if(r.includes(",")){let t=r.split(",").map(n=>parseInt(n.trim(),10));if(t.length===3&&t.every(n=>!isNaN(n)&&n>=0&&n<=255))return new w.Color(t[0]/255,t[1]/255,t[2]/255)}try{return new w.Color(r.toLowerCase())}catch{return p().warn(`Invalid color string: ${e}, using white`),new w.Color(16777215)}}function P(e,r){e.forEach(t=>{t.position.y-=r,t.updateMatrix()})}function B(e){let r=new w.Box3;return e.forEach(t=>{t.updateMatrixWorld(!0);let n=new w.Box3().setFromObject(t);r.union(n)}),r}function Ee(e){let r=[];e.traverse(t=>{t instanceof w.Mesh&&t.userData.id!=="floor"&&r.push(t)}),r.forEach(t=>{t instanceof w.Mesh&&(t.geometry?.dispose(),(Array.isArray(t.material)?t.material:[t.material]).forEach(o=>{for(let s in o){let a=o[s];a&&a instanceof w.Texture&&a.dispose()}o.dispose()})),t.removeFromParent()})}var z={};J(z,{CONCRETE_MATERIAL:()=>ge,EMISSIVE_MATERIAL:()=>ue,GLASS_MATERIAL:()=>Te,METAL_MATERIAL:()=>pe,PLASTIC_MATERIAL:()=>Re,RUBBER_MATERIAL:()=>we,WOOD_MATERIAL:()=>ye});import*as u from"three";var ue=new u.MeshPhysicalMaterial({color:0,emissive:new u.Color(16777215),emissiveIntensity:5,metalness:0,roughness:.2,clearcoat:.3,clearcoatRoughness:.2,depthWrite:!0,depthTest:!0,transparent:!1,alphaTest:0,polygonOffset:!0,side:u.FrontSide,dithering:!0}),pe=new u.MeshPhysicalMaterial({color:new u.Color(0),metalness:.9,roughness:.3,envMapIntensity:1.2,clearcoat:.3,clearcoatRoughness:.2,reflectivity:1,ior:2.5,thickness:1,depthWrite:!0,transparent:!1,alphaTest:0,depthTest:!0,polygonOffset:!0,side:u.FrontSide,dithering:!0}),ge=new u.MeshPhysicalMaterial({color:new u.Color(13421772),metalness:0,roughness:.92,envMapIntensity:.15,clearcoat:.05,clearcoatRoughness:.9,reflectivity:.15,transmission:0,ior:1.45,thickness:0,depthWrite:!0,transparent:!1,alphaTest:.5,depthTest:!0,polygonOffset:!0,side:u.FrontSide,dithering:!0}),Re=new u.MeshPhysicalMaterial({color:new u.Color(16777215),metalness:0,roughness:.3,envMapIntensity:.5,clearcoat:.5,clearcoatRoughness:.1,reflectivity:.5,ior:1.4,transmission:0,transparent:!1,depthWrite:!0,side:u.FrontSide,dithering:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),Te=new u.MeshPhysicalMaterial({color:new u.Color(16777215),metalness:0,roughness:0,transmission:.95,transparent:!0,opacity:.3,envMapIntensity:1,clearcoat:1,clearcoatRoughness:0,ior:1.52,reflectivity:.9,thickness:1,side:u.DoubleSide,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),we=new u.MeshPhysicalMaterial({color:new u.Color(1710618),metalness:0,roughness:.9,envMapIntensity:.2,clearcoat:.1,clearcoatRoughness:.8,reflectivity:.2,ior:1.3,transmission:0,depthWrite:!0,side:u.FrontSide,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),ye=new u.MeshPhysicalMaterial({color:new u.Color(8934707),metalness:0,roughness:.7,envMapIntensity:.3,clearcoat:.3,clearcoatRoughness:.4,reflectivity:.3,ior:1.3,transmission:0,depthWrite:!0,side:u.FrontSide,dithering:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1});import*as b from"three";import*as $ from"fflate";Q();async function q(e){return new Promise((r,t)=>{try{let n=()=>{try{let o=N(e),s=$.gunzipSync(o),a=be(s);r(a)}catch(o){t(new x(o instanceof x?o.message:`Failed to decompress batched data: ${o instanceof Error?o.message:String(o)}`,o instanceof x?o.code:S.VALIDATION_ERROR,{context:{base64StringLength:e.length},originalError:o instanceof Error?o:new Error(String(o))}))}};"requestIdleCallback"in globalThis?globalThis.requestIdleCallback(n,{timeout:5e3}):setTimeout(n,0)}catch(n){t(new x(`Failed to schedule decompression: ${n instanceof Error?n.message:String(n)}`,S.VALIDATION_ERROR,{originalError:n instanceof Error?n:new Error(String(n))}))}})}function be(e){let r=new DataView(e.buffer,e.byteOffset,e.byteLength),t=0;if(t+4>r.byteLength)throw new x("Insufficient data to read the number of vertex floats.",S.VALIDATION_ERROR,{context:{expectedBytes:4,availableBytes:r.byteLength,offset:t}});let n=r.getUint32(t,!0);if(t+=4,n%3!==0)throw new x("Invalid number of vertex floats; should be divisible by 3.",S.VALIDATION_ERROR,{context:{numVertexFloats:n,remainder:n%3,totalBytes:r.byteLength}});let o=n*Float32Array.BYTES_PER_ELEMENT;if(t+o>r.byteLength)throw new x("Insufficient data to read vertices.",S.VALIDATION_ERROR,{context:{expectedBytes:o,availableBytes:r.byteLength-t,offset:t}});let s=new Float32Array(e.buffer,e.byteOffset+t,n);if(t+=o,t+4>r.byteLength)throw new x("Insufficient data to read the number of face indices.",S.VALIDATION_ERROR,{context:{expectedBytes:4,availableBytes:r.byteLength-t,offset:t}});let a=r.getUint32(t,!0);t+=4;let l=a*Uint32Array.BYTES_PER_ELEMENT;if(t+l>r.byteLength)throw new x("Insufficient data to read face indices.",S.VALIDATION_ERROR,{context:{expectedBytes:l,availableBytes:r.byteLength-t,offset:t}});let c=new Uint32Array(e.buffer,e.byteOffset+t,a);return{vertices:s,faces:c}}async function _(e,r){let{mergeByMaterial:t=!0,applyTransforms:n=!0,debug:o=!1}=r??{},s=o?performance.now():0,a=0;try{let l=performance.now(),c=JSON.parse(e);return a=performance.now()-l,await V(c,{mergeByMaterial:t,applyTransforms:n,debug:o,parseTime:a,perfStart:s})}catch(l){return p().error("Error parsing mesh batch:",l),[]}}async function V(e,r){let{mergeByMaterial:t=!0,applyTransforms:n=!0,scaleFactor:o=1,debug:s=!1,parseTime:a=0,perfStart:l=s?performance.now():0}=r??{},c=0,R=0;try{let m=performance.now(),{vertices:h,faces:E}=await q(e.compressedData);c=performance.now()-m;let M=(e.compressedData.length*.75/1024/1024).toFixed(2),f=((h.byteLength+E.byteLength)/1024/1024).toFixed(2),H=((1-parseFloat(M)/parseFloat(f))*100).toFixed(1);s&&(p().debug("Mesh Batch Stats:"),p().debug(` Materials: ${e.materials.length} | Groups: ${e.groups.length}`),p().debug(` Vertices: ${(h.length/3).toLocaleString()} | Faces: ${(E.length/3).toLocaleString()}`),p().debug(` Compressed: ${M} MB | Uncompressed: ${f} MB`),p().debug(` Compression Ratio: ${H}%`)),n&&ve(h);let C=performance.now(),I=e.materials.map(Me),d=[];for(let g of e.groups)if(t&&g.meshes.length>1){let y=He(g,h,E,I);d.push(y)}else{let y=xe(g,h,E,I);d.push(...y)}if(o!==1)for(let g of d)g.scale.set(o,o,o);if(R=performance.now()-C,s){let g=performance.now()-l;p().debug("Performance:"),a>0&&p().debug(` Parse JSON: ${a.toFixed(2)}ms`),p().debug(` Decompress: ${c.toFixed(2)}ms`),p().debug(` Create Meshes: ${R.toFixed(2)}ms`),p().debug(` Total: ${g.toFixed(2)}ms`)}return d}catch(m){return p().error("Error parsing mesh batch object:",m),[]}}function Me(e){let r=F(e.color);return new b.MeshPhysicalMaterial({color:r,metalness:e.metalness,roughness:e.roughness,opacity:e.opacity,transparent:e.transparent,side:b.DoubleSide,polygonOffset:!0,polygonOffsetFactor:.5,polygonOffsetUnits:.5,depthWrite:!0,depthTest:!0})}function He(e,r,t,n){let o=new b.BufferGeometry,s=0,a=0;for(let f of e.meshes)s+=f.vertexCount,a+=f.faceCount;let l=new Float32Array(s),c=new Uint32Array(a),R=0,m=0;for(let f of e.meshes){l.set(r.subarray(f.vertexOffset,f.vertexOffset+f.vertexCount),R);let H=t.subarray(f.faceOffset,f.faceOffset+f.faceCount),C=Math.floor(f.vertexOffset/3),d=Math.floor(R/3)-C;for(let g=0;g<H.length;g++)c[m+g]=H[g]+d;R+=f.vertexCount,m+=f.faceCount}o.setAttribute("position",new b.BufferAttribute(l,3)),o.setIndex(new b.BufferAttribute(c,1)),o.computeVertexNormals();let h=new b.Mesh(o,n[e.materialId]),E=e.meshes.map(f=>f.name).filter(f=>f&&f.length>0);h.name=E.length>0?E[0]:`merged_material_${e.materialId}`,h.castShadow=!0,h.receiveShadow=!0;let M=e.meshes.map(f=>f.metadata).filter(f=>f);return M.length>0&&(h.userData.mergedMetadata=M),h}function xe(e,r,t,n){let o=[];for(let s of e.meshes){let a=new b.BufferGeometry,l=r.subarray(s.vertexOffset,s.vertexOffset+s.vertexCount),c=t.subarray(s.faceOffset,s.faceOffset+s.faceCount),R=Math.floor(s.vertexOffset/3),m=new Uint32Array(c.length);for(let E=0;E<c.length;E++)m[E]=c[E]-R;a.setAttribute("position",new b.BufferAttribute(l,3)),a.setIndex(new b.BufferAttribute(m,1)),a.computeVertexNormals();let h=new b.Mesh(a,n[e.materialId]);h.name=s.name,s.metadata&&(h.userData={...h.userData,...s.metadata}),h.castShadow=!0,h.receiveShadow=!0,o.push(h)}return o}function ve(e){let r=Math.cos(-Math.PI/2),t=Math.sin(-Math.PI/2);for(let n=0;n<e.length;n+=3){let o=e[n],s=e[n+1],a=e[n+2];e[n]=o,e[n+1]=s*r-a*t,e[n+2]=s*t+a*r}}var k={Millimeters:1/1e3,Centimeters:1/100,Meters:1,Inches:1/39.37,Feet:1/3.28084},Ce="Display";async function Y(e,r){let t=performance.now(),n=[],{allowScaling:o=!0,allowAutoPosition:s=!0,debug:a=!1,parsing:l={}}=r??{};try{let c=o?Oe(e.modelunits):1;return await Se(e,n,c,l,a),s&&De(n),n}catch(c){throw Le(c,n),c}finally{a&&Be(t)}}function Oe(e){return k[e]??1}async function Se(e,r,t,n,o){for(let s of e.values){let a=s.InnerTree;for(let l in a){let c=a[l];c&&await Ae(c,r,t,n,o)}}}async function Ae(e,r,t,n,o){for(let s of e)if(s.type.includes(Ce)){let a={mergeByMaterial:!0,applyTransforms:!0,debug:!1,...n},l=await _(s.data,a);if(t!==1)for(let c of l)c.scale.set(t,t,t);r.push(...l),o&&p().debug(`Extracted ${l.length} meshes from batch`)}}function De(e){if(e.length===0)return;let t=B(e).min.y;P(e,t)}function Le(e,r){p().error("An unexpected error occurred:",e),Ie(r)}function Ie(e){for(let r of e)r.geometry&&r.geometry.dispose(),r.material&&(Array.isArray(r.material)?r.material.forEach(t=>t.dispose()):r.material.dispose())}function Be(e){let r=performance.now()-e;p().info("Time to process meshes:",`${r.toFixed(2)}ms`)}export{z as Materials,k as SCALE_FACTORS,Y as getThreeMeshesFromComputeResponse,U as initThree,V as parseMeshBatchObject,W as updateScene};
2
2
  //# sourceMappingURL=visualization.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "selva-compute",
3
- "version": "1.2.0",
3
+ "version": "1.3.0",
4
4
  "description": "TypeScript library for Rhino Compute Server - Grasshopper and RhinoCommon",
5
5
  "author": "VektorNode",
6
6
  "license": "MIT",
@@ -1,2 +0,0 @@
1
- import{a as $,b as z,c as W,d as q}from"./chunk-WD3ENUAA.js";import{b as ae,c as d,d as c,e as l,f as se,g as oe,h as N,i as f,l as L,m as V,n as j}from"./chunk-MK3M76VN.js";N();se();L();var T=class e{constructor(r){d(this,"config");d(this,"serverStats");d(this,"disposed",!1);this.config=this.normalizeComputeConfig(r),this.serverStats=new j(this.config.serverUrl,this.config.apiKey)}static async create(r){let t=new e(r);if(!await t.serverStats.isServerOnline())throw new l("Rhino Compute server is not online",c.NETWORK_ERROR,{context:{serverUrl:t.config.serverUrl}});return t}getConfig(){return this.ensureNotDisposed(),{...this.config}}async getIO(r){return this.ensureNotDisposed(),P(r,this.config)}async getRawIO(r){return this.ensureNotDisposed(),b(r,this.config)}async solve(r,t){this.ensureNotDisposed();try{if(typeof r=="string"&&!r?.trim())throw new l("Definition URL/content is required",c.INVALID_INPUT,{context:{receivedUrl:r}});if(r instanceof Uint8Array&&r.length===0)throw new l("Definition content is empty",c.INVALID_INPUT);if(!await this.serverStats.isServerOnline())throw new l("Rhino Compute server is not online",c.NETWORK_ERROR,{context:{serverUrl:this.config.serverUrl}});let n=await C(t,r,this.config);if(n&&typeof n=="object"&&"message"in n&&!("fileData"in n))throw new l(n.message||"Computation failed",c.COMPUTATION_ERROR,{context:{definition:typeof r=="string"&&r.length<200?r:"...content...",inputs:t}});return n}catch(n){throw this.config.debug&&f().error("Compute failed:",n),n instanceof l?n:new l(n instanceof Error?n.message:String(n),c.COMPUTATION_ERROR,{context:{definition:typeof r=="string"&&r.length<200?r:"...content...",inputs:t},originalError:n instanceof Error?n:new Error(String(n))})}}async dispose(){this.disposed||(this.disposed=!0,"dispose"in this.serverStats&&typeof this.serverStats.dispose=="function"&&await this.serverStats.dispose())}ensureNotDisposed(){if(this.disposed)throw new l("GrasshopperClient has been disposed and cannot be used",c.INVALID_STATE)}normalizeComputeConfig(r){if(!r.serverUrl?.trim())throw new l("serverUrl is required",c.INVALID_CONFIG,{context:{receivedServerUrl:r.serverUrl}});try{new URL(r.serverUrl)}catch{throw new l("serverUrl must be a valid URL",c.INVALID_CONFIG,{context:{receivedServerUrl:r.serverUrl}})}if(r.serverUrl===""||r.serverUrl==="https://compute.rhino3d.com/")throw new l("serverUrl must be set to your Compute server URL. The default public endpoint is not allowed.",c.INVALID_CONFIG,{context:{receivedServerUrl:r.serverUrl}});return{...r,serverUrl:r.serverUrl.replace(/\/+$/,""),apiKey:r.apiKey,authToken:r.authToken,debug:r.debug??!1,suppressClientSideWarning:r.suppressClientSideWarning}}};var B=async(e,r=null)=>{try{return await K(e,r)}catch(t){throw new l("Failed to extract files from compute response",c.INVALID_STATE,{context:{originalError:t instanceof Error?t.message:String(t)},originalError:t instanceof Error?t:void 0})}},S=async(e,r,t=null)=>{if(typeof document>"u"||typeof Blob>"u")throw new l("File download functionality is only available in browser environments. This function requires the DOM API (document, Blob).",c.BROWSER_ONLY,{context:{environment:typeof window<"u"?"browser (SSR)":"Node.js",documentAvailable:typeof document<"u",blobAvailable:typeof Blob<"u"}});try{let n=await K(e,t);await ie(n,r)}catch(n){throw n instanceof l?n:new l("Failed to download files from compute response",c.INVALID_STATE,{context:{originalError:n instanceof Error?n.message:String(n)},originalError:n instanceof Error?n:void 0})}},K=async(e,r)=>{let t=[];if(e.forEach(n=>{let a=`${n.fileName}${n.fileType}`;if(n.subFolder&&n.subFolder.trim()!==""&&(a=`${n.subFolder}/${a}`),n.isBase64Encoded===!0&&n.data){let s=W(n.data);t.push({fileName:`${n.fileName}${n.fileType}`,content:new Uint8Array(s.buffer),path:a})}else n.isBase64Encoded===!1&&n.data&&t.push({fileName:`${n.fileName}${n.fileType}`,content:n.data,path:a})}),r){let n=Array.isArray(r)?r:[r],a=await Promise.all(n.map(async s=>{try{let o=await fetch(s.filePath);if(!o.ok)return f().warn(`Failed to fetch additional file from URL: ${s.filePath}`),null;let u=await(await o.blob()).arrayBuffer();return{fileName:s.fileName,content:new Uint8Array(u),path:s.fileName}}catch(o){return f().error(`Error fetching additional file from URL: ${s.filePath}`,o),null}}));t.push(...a.filter(s=>s!==null))}return t};async function ie(e,r){let{zipSync:t,strToU8:n}=await import("fflate"),a={};e.forEach(i=>{a[i.path]=typeof i.content=="string"?n(i.content):i.content});let s=t(a,{level:6}),o=new Blob([s],{type:"application/zip"});ue(o,`${r}.zip`)}function ue(e,r){if(typeof document>"u")throw new l("saveFile requires a browser environment with DOM API access.",c.BROWSER_ONLY,{context:{function:"saveFile",requiredAPI:"document"}});let t=document.createElement("a");t.href=URL.createObjectURL(e),t.download=r,t.click(),URL.revokeObjectURL(t.href)}var F=new Map;function Y(e,r){F.set(e,r)}Y("Rhino.Geometry.Point3d",(e,r)=>{let t=r;return!t||typeof t.X!="number"?null:new e.Point([t.X,t.Y,t.Z])});Y("Rhino.Geometry.Line",(e,r)=>{let t=r;return!t||!t.From||!t.To?null:new e.Line([t.From.X,t.From.Y,t.From.Z],[t.To.X,t.To.Y,t.To.Z])});function le(e){if(F.has(e))return F.get(e);for(let[r,t]of F)if(e.startsWith(r))return t}function pe(e){return!e||typeof e!="object"?null:e.data??e.value??null}function J(e,r,t){let n=le(r);if(n)try{return n(t,e)}catch(a){f().warn(`Failed to decode Rhino type ${r}:`,a)}try{let a=pe(e);if(a)return t.CommonObject.decode(a)}catch(a){return f().warn(`Failed to decode ${r} with CommonObject:`,a),{__decodeError:!0,type:r,raw:e}}return e}var D={STRING:"System.String",INT:"System.Int32",DOUBLE:"System.Double",BOOL:"System.Boolean"},fe="Rhino.Geometry.",ce=["WebDisplay"],me="FileData";function de(e){return ce.some(r=>e.includes(r))}function X(e){if(typeof e!="string")return e;let r=e.trim();if(!(r.startsWith("{")||r.startsWith("[")||r.startsWith('"')))return e;try{let n=JSON.parse(r);if(typeof n=="string")try{return JSON.parse(n)}catch{return n}return n}catch{return e}}function ye(e,r,t){switch(r){case D.STRING:return typeof e!="string"?e:e.replace(/^"(.*)"$/,"$1");case D.INT:return Number.parseInt(e,10);case D.DOUBLE:return Number.parseFloat(e);case D.BOOL:return String(e).toLowerCase()==="true";default:return t&&r.startsWith(fe)?J(e,r,t):e}}function _(e,r,t,n){if(de(r))return null;if(typeof e!="string")return e;let a=t?X(e):e;return ye(a,r,n)}function w(e,r){for(let t of Object.values(e))if(Array.isArray(t))for(let n of t)r(n)}function Z(e,r=!1,t={}){let{parseValues:n=!0,rhino:a,stringOnly:s=!1}=t,o={};for(let i of e.values)w(i.InnerTree,u=>{if(s&&u.type!==D.STRING)return;let p=r?u.id:i.ParamName;if(!p)return;let m=_(u.data,u.type,n,a);o[p]===void 0?o[p]=m:Array.isArray(o[p])?o[p].push(m):o[p]=[o[p],m]});return{values:o}}function H(e){let r=[];for(let t of e.values)w(t.InnerTree,n=>{if(!n.type.includes(me))return;let a=X(n.data);a&&a.FileName&&a.FileType&&a.Data&&r.push(a)});return r}function U(e,r,t={}){let{parseValues:n=!0,rhino:a,stringOnly:s=!1}=t,o;if("byName"in r?o=e.values.find(u=>u.ParamName===r.byName):o=e.values.find(u=>{let p=!1;return w(u.InnerTree,m=>{m.id===r.byId&&(p=!0)}),p}),!o)return;let i=[];if(w(o.InnerTree,u=>{if("byId"in r&&u.id!==r.byId||s&&u.type!==D.STRING)return;let p=_(u.data,u.type,n,a);i.push(p)}),i.length!==0)return i.length===1?i[0]:i}var I=class{constructor(r,t=!1){this.response=r;this.debug=t}getValues(r=!1,t={}){return Z(this.response,r,t)}getValueByParamName(r,t){return U(this.response,{byName:r},t)}getValueByParamId(r,t){return U(this.response,{byId:r},t)}async extractMeshesFromResponse(r){let t={debug:this.debug,...r};try{let{getThreeMeshesFromComputeResponse:n}=await import("./visualization.js");return n(this.response,t)}catch(n){let{RhinoComputeError:a,ErrorCodes:s}=(N(),ae(oe));throw new a("Failed to load three.js visualization module. Ensure three.js is installed as a peer dependency.",s.INVALID_STATE,{context:{originalError:n instanceof Error?n.message:String(n)}})}}getFileData(){return H(this.response)}getAndDownloadFiles(r,t){let n=this.getFileData();S(n,r,t)}};L();function A(e,r){r||typeof window<"u"&&f().warn(`Warning: ${e} is running on the client side. For better performance and security, consider running this on the server side.`)}async function C(e,r,t){t.debug&&A("solveGrasshopperDefinition",t.suppressClientSideWarning);let n=M(r,e);he(n,t);let a=await V("grasshopper",n,t);return"pointer"in a&&delete a.pointer,a}function M(e,r){let t={algo:null,pointer:null,values:r};return e instanceof Uint8Array?t.algo=q(e):e.startsWith("http")?t.pointer=e:z(e)?t.algo=e:t.algo=$(e),t}function he(e,r){r.cachesolve!==null&&(e.cachesolve=r.cachesolve),r.modelunits!==null&&(e.modelunits=r.modelunits),r.angletolerance!==null&&(e.angletolerance=r.angletolerance),r.absolutetolerance!==null&&(e.absolutetolerance=r.absolutetolerance),r.dataversion!==null&&(e.dataversion=r.dataversion)}function ge(e,r={}){let{preserveSpaces:t=!1}=r,n=e.trim();return t?(n=n.charAt(0).toLowerCase()+n.slice(1).replace(/[-_](.)/g,(a,s)=>s?s.toUpperCase():""),n):(n=n.replace(/^[A-Z]/,a=>a.toLowerCase()).replace(/[\s-_]+(.)?/g,(a,s)=>s?s.toUpperCase():""),n)}function G(e,r={}){return!e||typeof e!="object"?e:Array.isArray(e)?r.deep?e.map(t=>G(t,r)):e:Object.keys(e).reduce((t,n)=>{let a=ge(n,{preserveSpaces:r.preserveSpaces}),s=e[n];return t[a]=r.deep?G(s,r):s,t},{})}N();function Q(e){if(typeof e.default!="object"||e.default===null)return;if(!("innerTree"in e.default)){f().warn("Unexpected structure in input.default:",e.default),e.default=null;return}let r=e.default.innerTree;if(Object.keys(r).length===0){e.default=void 0;return}if(e.treeAccess||e.atMost&&e.atMost>1){let n={};for(let[a,s]of Object.entries(r))n[a]=s.map(o=>{if(typeof o.data=="string"){if(o.type==="System.Double"||o.type==="System.Int32"){let i=Number(o.data);return Number.isNaN(i)?o.data:i}if(o.type==="System.Boolean")return o.data.toLowerCase()==="true";if(o.type.startsWith("Rhino.Geometry")||o.type==="System.String")try{return JSON.parse(o.data)}catch{return o.data}}return o.data});e.default=n;return}let t=[];for(let n of Object.values(r))Array.isArray(n)&&n.forEach(a=>{a&&typeof a=="object"&&"data"in a&&t.push(a.data)});t.length===0?e.default=void 0:t.length===1?e.default=t[0]:e.default=t}N();function R(e,r){let{transform:t,setUndefinedOnEmpty:n=!0}=r;if(!(e.default===void 0||e.default===null))if(Array.isArray(e.default)){let a=e.default.map(t).filter(s=>s!==null);e.default=a.length>0?a:void 0}else{let a=t(e.default);a!==null?e.default=a:n&&(e.default=void 0)}}function Te(){return e=>{if(typeof e=="number")return e;if(typeof e=="string"){let r=Number(e.trim());return Number.isNaN(r)?null:r}return null}}function be(){return e=>{if(typeof e=="boolean")return e;if(typeof e=="string"){let r=e.toLowerCase();if(r==="true")return!0;if(r==="false")return!1;throw new Error(`Invalid boolean string: "${e}"`)}return null}}function De(){return e=>typeof e=="string"?e.startsWith('"')&&e.endsWith('"')||e.startsWith('"')?e.slice(1,-1):e:null}function Ie(){return e=>{if(typeof e=="string"){let r=e.trim();return r.startsWith('"')&&r.endsWith('"')&&(r=r.slice(1,-1).trim()),r}return null}}function xe(e){R(e,{transform:Ie(),setUndefinedOnEmpty:!1})}function Ce(e="unknown"){return r=>{if(typeof r=="object"&&r!==null)return r;if(typeof r=="string"&&r.trim()!=="")try{let t=JSON.parse(r);return typeof t=="object"&&t!==null?t:(f().warn(`Parsed value for input ${e} is not an object`),null)}catch(t){return f().warn(`Failed to parse object value "${r}" for input ${e}`,t),null}return null}}function ee(e,r,t){let n=Number(e.toFixed(r));return Math.abs(e-n)<t?n:e}function Pe(e,r=1e-8){if(!Number.isFinite(e)||e===0)return .1;let t=Math.abs(e);if(t>=1){let y=String(e).split(".")[1];if(y&&y.length>0){let h=Math.min(y.length,12),g=Math.pow(10,-h),k=Number(g.toFixed(h));return Math.abs(k-g)<r?k:g}return 1}let n=String(e),a=n.toLowerCase().match(/e(-?\d+)/);if(a){let E=Number(a[1]);if(E<0||n.toLowerCase().includes("e-")){let y=Math.abs(E),h=Math.pow(10,-y),g=Number(h.toFixed(y));return Math.abs(g-h)<r?g:h}return .1}let s=12,i=t.toFixed(s).replace(/0+$/,""),u=Math.min((i.split(".")[1]||"").length,s);if(u===0)return .1;let p=Math.pow(10,-u),m=Number(p.toFixed(u));return Math.abs(m-p)<r?m:p}function re(e,r=1e-8){let t=e.paramType==="Integer";if(R(e,{transform:Te()}),t){Array.isArray(e.default)?e.default=e.default.map(s=>typeof s=="number"?Math.round(s):s):typeof e.default=="number"&&(e.default=Math.round(e.default)),e.stepSize=1;return}let n=Array.isArray(e.default)?e.default[0]:e.default,a;if(typeof n=="number"&&Number.isFinite(n)&&n!==0?a=n:typeof e.minimum=="number"&&Number.isFinite(e.minimum)&&e.minimum!==0?a=e.minimum:typeof e.maximum=="number"&&Number.isFinite(e.maximum)&&e.maximum!==0&&(a=e.maximum),a!==void 0?e.stepSize=Pe(a,r):e.stepSize=.1,typeof e.stepSize=="number"){let s=0,o=String(e.stepSize),i=o.toLowerCase().match(/e(-?\d+)/);if(i?s=Math.abs(Number(i[1])):s=o.split(".")[1]?.length??0,s===0&&typeof n=="number"&&n!==0&&Math.abs(n)<1){let u=Math.ceil(-Math.log10(Math.abs(n)));Number.isFinite(u)&&u>0&&(s=u)}s=Math.min(Math.max(s,0),12),Array.isArray(e.default)?e.default=e.default.map(u=>typeof u=="number"?ee(u,s,r):u):typeof e.default=="number"&&(e.default=ee(e.default,s,r))}}function Se(e){try{R(e,{transform:be(),setUndefinedOnEmpty:!1})}catch(r){throw r instanceof Error?new l(r.message):r}}function Re(e){R(e,{transform:De(),setUndefinedOnEmpty:!1})}function te(e){R(e,{transform:Ce(e.nickname||"unnamed"),setUndefinedOnEmpty:!0})}function ve(e){if(!e.values||typeof e.values!="object"||Object.keys(e.values).length===0)throw l.missingValues(e.nickname||"unnamed","ValueList");if(e.default!==void 0&&e.default!==null){let r=String(e.default).toLowerCase();Object.keys(e.values).some(n=>n.toLowerCase()===r)||f().warn(`ValueList input "${e.nickname||"unnamed"}" default value "${e.default}" is not in available values`)}}var ne={Number:re,Integer:re,Boolean:Se,Text:Re,ValueList:ve,Geometry:te,File:te,Color:xe};L();function Oe(e,r){switch(e.paramType){case"Number":case"Integer":return{...r,paramType:e.paramType,minimum:e.minimum,maximum:e.maximum,atLeast:e.atLeast,atMost:e.atMost,default:e.atMost>1?[0]:0};case"Boolean":return{...r,paramType:"Boolean",default:e.atMost>1?[!1]:!1};case"Text":return{...r,paramType:"Text",default:e.atMost>1?[""]:""};case"ValueList":return{...r,paramType:"ValueList",values:e.values??{},default:e.atMost>1?[e.default]:e.default};case"File":return{...r,paramType:"File",default:e.atMost>1?[null]:null};case"Color":return{...r,paramType:"Color",default:e.atMost>1?["0, 0, 0"]:"0, 0, 0"};default:return{...r,paramType:"Geometry",default:e.atMost>1?[null]:null}}}function v(e){let r={description:e.description,name:e.name,nickname:e.nickname,treeAccess:e.treeAccess,groupName:e.groupName??"",id:e.id};try{Q(e);let t=ne[e.paramType];if(!t)throw l.unknownParamType(e.paramType,e.name);switch(t(e),e.paramType){case"Number":case"Integer":return{...r,paramType:e.paramType,minimum:e.minimum,maximum:e.maximum,atLeast:e.atLeast,atMost:e.atMost,stepSize:e.stepSize,default:e.default};case"Boolean":return{...r,paramType:"Boolean",default:e.default};case"Text":return{...r,paramType:"Text",default:e.default};case"ValueList":return{...r,paramType:"ValueList",values:e.values,default:e.default};case"Geometry":return{...r,paramType:e.paramType,default:e.default};case"File":return{...r,paramType:e.paramType,acceptedFormats:e.acceptedFormats,default:e.default};case"Color":return{...r,paramType:"Color",default:e.default};default:throw l.unknownParamType(e.paramType,e.name)}}catch(t){if(t instanceof l)return f().error(`Validation error for input ${e.name||"unknown"}:`,t.message),Oe(e,r);throw new l(t instanceof Error?t.message:String(t),"VALIDATION_ERROR",{context:{paramName:e.name,paramType:e.paramType},originalError:t instanceof Error?t:new Error(String(t))})}}function x(e){return e.map(r=>v(r))}async function b(e,r){let t=M(e,[]),n={};t.algo&&(n.algo=t.algo),t.pointer&&(n.pointer=t.pointer);let a=await V("io",n,r);if(!a||typeof a!="object")throw new l("Invalid IO response structure",c.INVALID_INPUT,{context:{response:a,definition:e}});let s=G(a,{deep:!0});return{inputs:s.inputs,outputs:s.outputs}}async function P(e,r){A("fetchParsedDefinitionIO",r.suppressClientSideWarning);let{inputs:t,outputs:n}=await b(e,r);return{inputs:x(t),outputs:n}}var O=class e{constructor(r){d(this,"innerTree");d(this,"paramName");this.paramName=r,this.innerTree={}}append(r,t){let n=e.formatPathString(r);this.innerTree[n]||(this.innerTree[n]=[]);let a=t.map(s=>({data:e.serializeValue(s)}));return this.innerTree[n].push(...a),this}appendSingle(r,t){return this.append(r,[t])}fromDataTreeDefault(r){this.innerTree={};for(let[t,n]of Object.entries(r)){if(!Array.isArray(n))continue;let a=e.parsePathString(t);this.append(a,n)}return this}appendFlat(r){let t=Array.isArray(r)?r:[r];return this.append([0],t)}flatten(){let r=[];for(let t of Object.values(this.innerTree))if(Array.isArray(t))for(let n of t)r.push(e.deserializeValue(n.data));return r}getPaths(){return Object.keys(this.innerTree)}getPath(r){let t=e.formatPathString(r),n=this.innerTree[t];if(n)return n.map(a=>e.deserializeValue(a.data))}toComputeFormat(){return{ParamName:this.paramName,InnerTree:this.innerTree}}getInnerTree(){return this.innerTree}getParamName(){return this.paramName}static fromInputParams(r){return r.filter(t=>e.hasValidValue(t.default)).map(t=>{let n=new e(t.nickname||"unnamed"),a=t.default;if(t.treeAccess&&e.isDataTreeStructure(a))n.fromDataTreeDefault(a),e.isNumericInput(t)&&n.applyNumericConstraints(t.minimum,t.maximum,t.nickname||"unnamed");else{let s=Array.isArray(a)?a:[a],o=e.processValues(s,t);n.appendFlat(o)}return n.toComputeFormat()})}static fromInputParam(r){return e.hasValidValue(r.default)?e.fromInputParams([r])[0]:void 0}static replaceTreeValue(r,t,n){if(r.length>0&&r[0]instanceof e){let s=r,o=s.findIndex(u=>u.getParamName()===t),i=new e(t);return typeof n=="object"&&n!==null&&!Array.isArray(n)&&e.isDataTreeStructure(n)?i.fromDataTreeDefault(n):(Array.isArray(n),i.appendFlat(n)),o!==-1?s[o]=i:s.push(i),s}else{let s=r,o=s.findIndex(p=>p.ParamName===t),i=new e(t);typeof n=="object"&&n!==null&&!Array.isArray(n)&&e.isDataTreeStructure(n)?i.fromDataTreeDefault(n):(Array.isArray(n),i.appendFlat(n));let u=i.toComputeFormat();return o!==-1?s[o]=u:s.push(u),s}}static getTreeValue(r,t){if(r.length>0&&r[0]instanceof e){let s=r.find(i=>i.getParamName()===t);if(!s)return null;let o=s.flatten();return o.length===0?null:o.length===1?o[0]:o}else{let s=r.find(p=>p.ParamName===t);if(!s)return null;let o=s.InnerTree;if(!o)return null;let i=Object.keys(o)[0];if(!i)return null;let u=o[i];if(Array.isArray(u)){if(u.length===1){let p=u[0]?.data;return p!==void 0?e.deserializeValue(p):null}return u.map(p=>p?.data!==void 0?e.deserializeValue(p.data):null).filter(p=>p!==null)}return u?.data!==void 0?e.deserializeValue(u.data):u}}static parsePathString(r){let t=r.match(/^\{([\d;]+)\}$/);return t?t[1].split(";").map(Number):(f().warn(`Invalid TreeBuilder path format: ${r}, using [0]`),[0])}static formatPathString(r){return`{${r.join(";")}}`}applyNumericConstraints(r,t,n){for(let a of Object.values(this.innerTree))if(Array.isArray(a))for(let s of a){let o=e.deserializeValue(s.data);if(typeof o=="number"){let i=e.clampValue(o,r,t,n);s.data=e.serializeValue(i)}}}static serializeValue(r){return typeof r=="boolean"||typeof r=="number"||typeof r=="string"?r:typeof r=="object"&&r!==null?JSON.stringify(r):String(r)}static deserializeValue(r){if(typeof r=="boolean"||typeof r=="number"||typeof r!="string")return r;if(r.startsWith("{")||r.startsWith("["))try{return JSON.parse(r)}catch{return r}return isNaN(Number(r))?r==="true"?!0:r==="false"?!1:r:Number(r)}static hasValidValue(r){return r==null?!1:typeof r=="string"?!0:!(Array.isArray(r)&&r.length===0||typeof r=="object"&&!Array.isArray(r)&&Object.keys(r).length===0)}static isDataTreeStructure(r){return typeof r!="object"||r===null||Array.isArray(r)?!1:Object.entries(r).every(([t,n])=>typeof t=="string"&&/^\{[\d;]+\}$/.test(t)&&Array.isArray(n))}static isNumericInput(r){return r.paramType==="Number"||r.paramType==="Integer"}static processValues(r,t){return r.map(n=>e.isNumericInput(t)&&typeof n=="number"?e.clampValue(n,t.minimum,t.maximum,t.nickname||"unnamed"):n).filter(n=>n!=null)}static clampValue(r,t,n,a){let s=r;return t!=null&&s<t&&(f().warn(`${a}: ${r} below min ${t}, clamping`),s=t),n!=null&&s>n&&(f().warn(`${a}: ${r} above max ${n}, clamping`),s=n),s}};export{T as a,B as b,S as c,I as d,C as e,v as f,x as g,b as h,P as i,O as j};
2
- //# sourceMappingURL=chunk-3MVIRDAI.js.map