@selvajs/compute 2.6.0 → 3.0.0-beta.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.
Files changed (50) hide show
  1. package/dist/chunk-2KAHGLXE.js +4 -0
  2. package/dist/chunk-2KAHGLXE.js.map +1 -0
  3. package/dist/chunk-2QHLW6ZL.cjs +4 -0
  4. package/dist/{chunk-XA4OMT6Z.cjs.map → chunk-2QHLW6ZL.cjs.map} +1 -1
  5. package/dist/chunk-BF7OQEQG.cjs +2 -0
  6. package/dist/{chunk-XOEJMVK4.cjs.map → chunk-BF7OQEQG.cjs.map} +1 -1
  7. package/dist/chunk-HKU2XHQQ.js +55 -0
  8. package/dist/chunk-HKU2XHQQ.js.map +1 -0
  9. package/dist/chunk-SA67IFJH.cjs +55 -0
  10. package/dist/chunk-SA67IFJH.cjs.map +1 -0
  11. package/dist/chunk-WHB32TTR.js +2 -0
  12. package/dist/chunk-WHB32TTR.js.map +1 -0
  13. package/dist/core.cjs +1 -1
  14. package/dist/core.cjs.map +1 -1
  15. package/dist/core.d.cts +2 -25
  16. package/dist/core.d.ts +2 -25
  17. package/dist/core.js +1 -1
  18. package/dist/grasshopper.cjs +1 -1
  19. package/dist/grasshopper.cjs.map +1 -1
  20. package/dist/grasshopper.d.cts +21 -143
  21. package/dist/grasshopper.d.ts +21 -143
  22. package/dist/grasshopper.js +1 -1
  23. package/dist/{handle-files-UcwvknQ3.d.ts → handle-files-Bu2qmaPj.d.cts} +11 -1
  24. package/dist/{handle-files-UcwvknQ3.d.cts → handle-files-Bu2qmaPj.d.ts} +11 -1
  25. package/dist/index.cjs +1 -1
  26. package/dist/index.cjs.map +1 -1
  27. package/dist/index.d.cts +3 -3
  28. package/dist/index.d.ts +3 -3
  29. package/dist/index.js +1 -1
  30. package/dist/visualization-N3OJSZOY.js +2 -0
  31. package/dist/visualization-UOIWXLDL.cjs +2 -0
  32. package/dist/{visualization-ZFXCE5NW.cjs.map → visualization-UOIWXLDL.cjs.map} +1 -1
  33. package/dist/visualization.cjs +1 -1
  34. package/dist/visualization.d.cts +25 -10
  35. package/dist/visualization.d.ts +25 -10
  36. package/dist/visualization.js +1 -1
  37. package/package.json +1 -3
  38. package/dist/chunk-GY2WLD42.js +0 -4
  39. package/dist/chunk-GY2WLD42.js.map +0 -1
  40. package/dist/chunk-UH3HH7PS.js +0 -55
  41. package/dist/chunk-UH3HH7PS.js.map +0 -1
  42. package/dist/chunk-XA4OMT6Z.cjs +0 -4
  43. package/dist/chunk-XOEJMVK4.cjs +0 -2
  44. package/dist/chunk-XXA7NEQF.cjs +0 -55
  45. package/dist/chunk-XXA7NEQF.cjs.map +0 -1
  46. package/dist/chunk-Y7V63BG7.js +0 -2
  47. package/dist/chunk-Y7V63BG7.js.map +0 -1
  48. package/dist/visualization-RICQHNLJ.js +0 -2
  49. package/dist/visualization-ZFXCE5NW.cjs +0 -2
  50. /package/dist/{visualization-RICQHNLJ.js.map → visualization-N3OJSZOY.js.map} +0 -0
@@ -0,0 +1,55 @@
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 _chunk2QHLW6ZLcjs = require('./chunk-2QHLW6ZL.cjs');var _three = require('three'); var z = _interopRequireWildcard(_three); var k = _interopRequireWildcard(_three); var O = _interopRequireWildcard(_three); var U = _interopRequireWildcard(_three); var Z = _interopRequireWildcard(_three); var ge = _interopRequireWildcard(_three); var D = _interopRequireWildcard(_three); var E = _interopRequireWildcard(_three); var L = _interopRequireWildcard(_three); var _ = _interopRequireWildcard(_three); var F = _interopRequireWildcard(_three);var W={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},INITIAL_DISTANCE_MULTIPLIER:4};function On(e,r,t,n,o){if(Ve(e),r.length===0)return;r.forEach(d=>{e.add(d)});let a=J(r),i=a.getCenter(new z.Vector3),l=a.getSize(new z.Vector3),s=Math.max(l.x,l.y,l.z);if(s/Math.min(l.x||1,l.y||1,l.z||1)>W.SCALE_RATIO_THRESHOLD||s>W.HUGE_THRESHOLD?(t.near=s*W.NEAR_PLANE_FACTOR.TINY,t.far=s*W.FAR_PLANE_FACTOR.HUGE):s>W.LARGE_THRESHOLD?(t.near=s*W.NEAR_PLANE_FACTOR.SMALL,t.far=s*W.FAR_PLANE_FACTOR.LARGE):(t.near=Math.max(.01,s*W.NEAR_PLANE_FACTOR.NORMAL),t.far=Math.max(2e3,s*W.FAR_PLANE_FACTOR.NORMAL)),t.updateProjectionMatrix(),o)n.minDistance=t.near*2,n.maxDistance=t.far*.9;else{let d=s*W.INITIAL_DISTANCE_MULTIPLIER;t.position.set(i.x+d*.8,i.y+d,i.z+d*1.2),n.target.copy(i),n.minDistance=t.near*2,n.maxDistance=t.far*.9,n.update()}}function ce(e){if(!e||typeof e!="string")return _chunk2QHLW6ZLcjs.e.call(void 0, ).warn(`Invalid color input: ${e}, using white`),new z.Color(16777215);let r=e.trim();if(/^#?[0-9A-Fa-f]{6}$/.test(r))try{let t=r.startsWith("#")?r:`#${r}`;return new z.Color(t)}catch (e2){return _chunk2QHLW6ZLcjs.e.call(void 0, ).warn(`Invalid hex color: ${e}, using white`),new z.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 z.Color(t[0]/255,t[1]/255,t[2]/255)}try{return new z.Color(r.toLowerCase())}catch (e3){return _chunk2QHLW6ZLcjs.e.call(void 0, ).warn(`Invalid color string: ${e}, using white`),new z.Color(16777215)}}function ue(e,r,t="z"){e.forEach(n=>{n.position[t]-=r})}function J(e){let r=new z.Box3;return e.length===0||e.forEach(t=>{t.updateMatrixWorld(!0);let n=new z.Box3().setFromObject(t);r.union(n)}),r}var Ie=new Set(["floor","grid","label-layer"]);function Ve(e){[...e.children].forEach(t=>{Ie.has(t.userData.id)||t.userData.source!=="user"&&(t.traverse(n=>{let o=n;if(!o.geometry&&!o.material)return;_optionalChain([o, 'access', _2 => _2.geometry, 'optionalAccess', _3 => _3.dispose, 'call', _4 => _4()]);let a=o.material;if(!a)return;(Array.isArray(a)?a:[a]).forEach(l=>{for(let s of Object.values(l))s instanceof z.Texture&&s.dispose();l.dispose()})}),t.removeFromParent())})}function Be(e){let r=e.clone().normalize(),t=new k.Vector3(0,0,1),n=new k.Vector3(0,1,0),o=Math.abs(r.dot(t))>.9?n:t,a=new k.Vector3().crossVectors(r,o).normalize(),i=new k.Vector3().crossVectors(a,r).normalize();return{top:r.clone(),bottom:r.clone().negate(),front:i.clone(),back:i.clone().negate(),right:a.clone(),left:a.clone().negate(),iso:i.clone().multiplyScalar(1.2).add(a.clone()).add(r.clone()).normalize()}}function de(e){let{scene:r,perspective:t,controls:n,onActiveCameraChange:o}=e,a=(_nullishCoalesce(e.up, () => (t.up))).clone().normalize(),i=Be(a),l=new k.OrthographicCamera(-1,1,1,-1,t.near,t.far);l.up.copy(a);let s="perspective",c=t.aspect,d=()=>s==="perspective"?t:l,u=()=>{let y=t.position.distanceTo(n.target)*Math.tan(t.fov*Math.PI/360),b=y*c;l.left=-b,l.right=b,l.top=y,l.bottom=-y,l.near=t.near,l.far=t.far,l.updateProjectionMatrix()},m=g=>{g!==s&&(g==="orthographic"?(l.position.copy(t.position),l.up.copy(t.up),l.lookAt(n.target),u()):t.position.copy(l.position),s=g,n.object=d(),n.update(),o(d()))},p=(g,y=!0)=>{let b=je(r),T=b.isEmpty()?n.target.clone():b.getCenter(new k.Vector3),I=b.isEmpty()?new k.Vector3(1,1,1):b.getSize(new k.Vector3),R=Math.max(I.x,I.y,I.z)||1,w=t.fov*(Math.PI/180),C=R/(2*Math.tan(w/2))*1.5,P=ke(g,a),A=T.clone().add(P.clone().multiplyScalar(C)),j=d();y?_e(j,n,A,T,()=>{s==="orthographic"&&u()}):(j.position.copy(A),n.target.copy(T),s==="orthographic"&&u(),n.update())};return{getActiveCamera:d,getProjection:()=>s,setProjection:m,toggleProjection:()=>(m(s==="perspective"?"orthographic":"perspective"),s),setView:(g,y=!0)=>{p(i[g],y)},setViewDirection:p,setRotateEnabled:g=>{n.enableRotate=g},isRotateEnabled:()=>n.enableRotate,updateAspect:(g,y)=>{c=y===0?c:g/y,s==="orthographic"&&u()}}}var ze=new Set(["grid","floor","label-layer","measure"]);function Fe(e){let r=e;for(;r;){if(typeof r.userData.id=="string"&&ze.has(r.userData.id))return!0;r=r.parent}return!1}function je(e){let r=[];return e.traverse(t=>{let n=t;t.visible&&!Fe(t)&&n.geometry&&r.push(t)}),J(r)}function ke(e,r){let t=r.clone().normalize(),n=e.clone().normalize();if(Math.abs(n.dot(t))<.9999)return e;let o=Math.abs(t.dot(new k.Vector3(0,0,1)))>.9?new k.Vector3(0,1,0):new k.Vector3(0,0,1),a=new k.Vector3().crossVectors(t,o).normalize(),i=.5*Math.PI/180;return n.multiplyScalar(Math.cos(i)).add(a.multiplyScalar(Math.sin(i))).normalize()}var Ue=e=>1-Math.pow(1-e,3);function _e(e,r,t,n,o,a=250){let i=e.position.clone(),l=r.target.clone(),s=performance.now(),c=()=>{let d=Ue(Math.min((performance.now()-s)/a,1));e.position.lerpVectors(i,t,d),r.target.lerpVectors(l,n,d),o(),r.update(),d<1&&requestAnimationFrame(c)};requestAnimationFrame(c)}var Ge=`
2
+ varying vec3 vWorldPos;
3
+ void main() {
4
+ vec4 world = modelMatrix * vec4(position, 1.0);
5
+ vWorldPos = world.xyz;
6
+ gl_Position = projectionMatrix * viewMatrix * world;
7
+ }
8
+ `,Ne=`
9
+ precision highp float;
10
+ varying vec3 vWorldPos;
11
+
12
+ uniform vec2 uAxes; // indices (0=x,1=y,2=z) of the two in-plane world axes
13
+ uniform float uCell;
14
+ uniform float uMajor;
15
+ uniform vec3 uCellColor;
16
+ uniform vec3 uMajorColor;
17
+ uniform vec3 uCenter; // fade center (camera position), projected onto plane
18
+ uniform float uFade;
19
+
20
+ // Antialiased grid line intensity for a given spacing, using screen-space derivatives so lines
21
+ // stay ~1px regardless of zoom (the standard "pristine grid" technique).
22
+ float gridLine(vec2 coord, float spacing) {
23
+ vec2 c = coord / spacing;
24
+ vec2 d = fwidth(c);
25
+ vec2 g = abs(fract(c - 0.5) - 0.5) / max(d, 1e-6);
26
+ float line = min(g.x, g.y);
27
+ return 1.0 - clamp(line, 0.0, 1.0);
28
+ }
29
+
30
+ // Index a vec3 by a float axis id (0/1/2) without dynamic indexing (WebGL1-safe).
31
+ float axis(vec3 v, float i) {
32
+ return i < 0.5 ? v.x : (i < 1.5 ? v.y : v.z);
33
+ }
34
+
35
+ void main() {
36
+ // Pick the two in-plane world coordinates.
37
+ vec2 coord = vec2(axis(vWorldPos, uAxes.x), axis(vWorldPos, uAxes.y));
38
+
39
+ float minor = gridLine(coord, uCell);
40
+ float major = gridLine(coord, uCell * uMajor);
41
+
42
+ vec3 color = mix(uCellColor, uMajorColor, major);
43
+ float alpha = max(minor, major);
44
+
45
+ // Radial fade from the camera-projected center.
46
+ float dist = distance(vWorldPos, uCenter);
47
+ float fade = 1.0 - clamp(dist / uFade, 0.0, 1.0);
48
+ alpha *= fade * fade;
49
+
50
+ if (alpha < 0.001) discard;
51
+ gl_FragColor = vec4(color, alpha);
52
+ }
53
+ `;function me(e={}){let{cellSize:r=1,majorEvery:t=10,cellColor:n=8947848,majorColor:o=4473924,fadeDistance:a=100,plane:i="y"}=e,l=i==="y"?new O.Vector2(0,2):i==="z"?new O.Vector2(0,1):new O.Vector2(1,2),s=a*2.5,c=new O.PlaneGeometry(s,s);i==="y"?c.rotateX(-Math.PI/2):i==="x"&&c.rotateY(Math.PI/2);let d=new O.ShaderMaterial({vertexShader:Ge,fragmentShader:Ne,transparent:!0,depthWrite:!1,side:O.DoubleSide,uniforms:{uAxes:{value:l},uCell:{value:r},uMajor:{value:t},uCellColor:{value:new O.Color(n)},uMajorColor:{value:new O.Color(o)},uCenter:{value:new O.Vector3},uFade:{value:a}}}),u=new O.Mesh(c,d);u.name="grid",u.userData.id="grid",u.renderOrder=-1;let m=new O.Vector3;return{object:u,update:p=>{i==="y"?(u.position.set(p.x,0,p.z),m.set(p.x,0,p.z)):i==="z"?(u.position.set(p.x,p.y,0),m.set(p.x,p.y,0)):(u.position.set(0,p.y,p.z),m.set(0,p.y,p.z)),d.uniforms.uCenter.value.copy(m)},setVisible:p=>{u.visible=p},dispose:()=>{c.dispose(),d.dispose()}}}var _ViewHelperjs = require('three/addons/helpers/ViewHelper.js');function pe(e){let{camera:r,domElement:t,controller:n}=e,o=new (0, _ViewHelperjs.ViewHelper)(r,t);o.setLabels("X","Y","Z");let a=!0,i=128,l=new U.Raycaster,s=new U.OrthographicCamera(-2,2,2,-2,0,4);s.position.set(0,0,2);let c={posX:new U.Vector3(1,0,0),negX:new U.Vector3(-1,0,0),posY:new U.Vector3(0,1,0),negY:new U.Vector3(0,-1,0),posZ:new U.Vector3(0,0,1),negZ:new U.Vector3(0,0,-1)},d=m=>{let p=t.getBoundingClientRect(),f=p.left+t.offsetWidth-i-o.location.right,S=p.top+t.offsetHeight-i-o.location.bottom,H=new U.Vector2((m.clientX-f)/i*2-1,-((m.clientY-S)/i)*2+1);if(Math.abs(H.x)>1||Math.abs(H.y)>1)return null;o.quaternion.copy(r.quaternion).invert(),o.updateMatrixWorld(),l.setFromCamera(H,s);let g=l.intersectObjects(o.children,!1);for(let y of g){let b=_optionalChain([y, 'access', _5 => _5.object, 'access', _6 => _6.userData, 'optionalAccess', _7 => _7.type]);if(typeof b=="string"&&b in c)return b}return null};return{render:m=>{if(!a)return;let p=m.autoClear;m.autoClear=!1,o.render(m),m.autoClear=p},update:m=>{o.animating&&o.update(m)},handleClick:m=>{if(!a)return!1;let p=d(m);return p?(n.getProjection()==="orthographic"&&n.setProjection("perspective"),n.setViewDirection(c[p],!1),!0):!1},get isAnimating(){return o.animating},setVisible:m=>{a=m},isVisible:()=>a,dispose:()=>o.dispose()}}var _LineSegmentsGeometryjs = require('three/addons/lines/LineSegmentsGeometry.js');var _LineSegments2js = require('three/addons/lines/LineSegments2.js');var _LineMaterialjs = require('three/addons/lines/LineMaterial.js');var Q="edge-overlay",Xe=2236962,qe=1.5,Ze=30;function fe(e,r={}){let t=new Z.Color(_nullishCoalesce(r.color, () => (Xe))),n=_nullishCoalesce(r.width, () => (qe)),o=_nullishCoalesce(r.thresholdAngle, () => (Ze)),a=[];return e.traverse(i=>{if(!(i instanceof Z.Mesh)||i.userData.id==="floor"||i.userData.id==="grid"||i.userData.kind===Q||i.children.some(s=>_optionalChain([s, 'access', _8 => _8.userData, 'optionalAccess', _9 => _9.kind])===Q)||!i.geometry)return;let l=Je(i.geometry,t,n,o);i.add(l),a.push(l)}),a}function Je(e,r,t,n){let o=new Z.EdgesGeometry(e,n),a=new _LineSegmentsGeometryjs.LineSegmentsGeometry;a.setPositions(Array.from(o.attributes.position.array)),o.dispose();let i=new (0, _LineMaterialjs.LineMaterial)({color:r});i.linewidth=t,i.polygonOffset=!0,i.polygonOffsetFactor=-1,i.polygonOffsetUnits=-1;let l=new (0, _LineSegments2js.LineSegments2)(a,i);return l.userData.kind=Q,l.raycast=()=>{},l}function Ke(e){return _optionalChain([e, 'access', _10 => _10.userData, 'optionalAccess', _11 => _11.kind])===Q}function Gn(e){let r=[];e.traverse(t=>{t instanceof _LineSegments2js.LineSegments2&&Ke(t)&&r.push(t)});for(let t of r)t.geometry.dispose(),t.material.dispose(),t.removeFromParent();return r.length}var _EffectComposerjs = require('three/addons/postprocessing/EffectComposer.js');var _RenderPassjs = require('three/addons/postprocessing/RenderPass.js');var _GTAOPassjs = require('three/addons/postprocessing/GTAOPass.js');var _OutputPassjs = require('three/addons/postprocessing/OutputPass.js');function he(e,r,t,n,o,a){let i=new (0, _EffectComposerjs.EffectComposer)(e),l=new (0, _RenderPassjs.RenderPass)(r,t);i.addPass(l);let s=new (0, _GTAOPassjs.GTAOPass)(r,t,n,o);s.blendIntensity=_nullishCoalesce(a.aoIntensity, () => (1)),s.updateGtaoMaterial({screenSpaceRadius:!0}),i.addPass(s);let c=new _OutputPassjs.OutputPass;return i.addPass(c),e.toneMapping=a.toneMapping,e.toneMappingExposure=a.toneMappingExposure,i.setSize(n,o),{render:d=>i.render(d),setSize:(d,u,m)=>{i.setPixelRatio(m),i.setSize(d,u),s.setSize(d,u)},setCamera:d=>{l.camera=d,s.camera=d},dispose:()=>{i.dispose(),s.dispose(),c.dispose()}}}var _CSS2DRendererjs = require('three/addons/renderers/CSS2DRenderer.js');function be(e,r){let t=new _CSS2DRendererjs.CSS2DRenderer,n=t.domElement;n.style.position="absolute",n.style.top="0",n.style.left="0",n.style.width="100%",n.style.height="100%",n.style.overflow="hidden",n.style.pointerEvents="none",n.style.zIndex="30",getComputedStyle(e).position==="static"&&(e.style.position="relative"),e.appendChild(n);let o={width:e.clientWidth||1,height:e.clientHeight||1};t.setSize(o.width,o.height);let a=new ge.Group;a.name="label-layer",a.userData.id="label-layer",r.add(a);let i=new Set;return{addLabel:(s,c,d)=>{let u=document.createElement("div");u.textContent=s,d?u.className=d:Object.assign(u.style,{padding:"2px 6px",borderRadius:"4px",background:"rgba(20, 20, 20, 0.78)",color:"#fff",font:"12px/1.3 system-ui, sans-serif",whiteSpace:"pre",textAlign:"center",userSelect:"none"}),u.style.pointerEvents="none";let m=new (0, _CSS2DRendererjs.CSS2DObject)(u);return m.position.copy(c),a.add(m),i.add(m),{object:m,setPosition:p=>m.position.copy(p),setText:p=>{u.textContent=p},remove:()=>{m.removeFromParent(),u.remove(),i.delete(m)}}},render:(s,c)=>t.render(s,c),setSize:(s,c)=>t.setSize(s,c),dispose:()=>{i.forEach(s=>{s.removeFromParent(),s.element.remove()}),i.clear(),a.removeFromParent(),n.remove()}}}var _Line2js = require('three/addons/lines/Line2.js');var _LineGeometryjs = require('three/addons/lines/LineGeometry.js');var lt=12,ct=16763904,ut=.015,ye={Millimeters:{metersPerUnit:1/1e3,suffix:"mm"},Centimeters:{metersPerUnit:1/100,suffix:"cm"},Meters:{metersPerUnit:1,suffix:"m"},Inches:{metersPerUnit:1/39.37,suffix:"in"},Feet:{metersPerUnit:1/3.28084,suffix:"ft"}};function dt(e){let r=e&&ye[e]||ye.Meters;return t=>`${(t/r.metersPerUnit).toPrecision(3)} ${r.suffix}`}function mt(e){let r=e.object;return r instanceof D.Mesh?e.face?[e.face.a,e.face.b,e.face.c]:null:r instanceof D.Points?e.index!=null?[e.index]:null:r instanceof D.Line&&e.index!=null?[e.index,e.index+1]:null}function pt(e,r,t,n){let o=e.point.clone(),a=e.object,i=mt(e);if(!i||!a.geometry)return o;let l=a.geometry.attributes.position;if(!l)return o;let s=m=>{let p=m.clone().project(r);return new D.Vector2((p.x+1)/2*t.width,(1-p.y)/2*t.height)},c=s(o),d=o,u=n;for(let m of i){if(m>=l.count)continue;let f=new D.Vector3().fromBufferAttribute(l,m).applyMatrix4(a.matrixWorld),S=s(f).distanceTo(c);S<u&&(u=S,d=f)}return d}function Re(e){let{canvas:r,scene:t,getActiveCamera:n,labelLayer:o,options:a={}}=e,i=_nullishCoalesce(a.snapPixels, () => (lt)),l=new D.Color(_nullishCoalesce(a.color, () => (ct))),s=dt(a.displayUnit),c=(h,v)=>`${s(h)}
54
+ \u0394x ${s(v.x)} \u0394y ${s(v.y)} \u0394z ${s(v.z)}`,d=_nullishCoalesce(a.format, () => (c)),u=new D.Raycaster,m=new D.Vector2,p=!1,f=[],S=[],H=null,g=null,y=new D.PointsMaterial({color:l,size:8,sizeAttenuation:!1,depthTest:!1}),b=new D.PointsMaterial({color:l,size:11,sizeAttenuation:!1,depthTest:!1,transparent:!0,opacity:.5}),T=null,I=h=>{if(!h){T&&(T.visible=!1);return}if(!T){let v=new D.BufferGeometry;v.setAttribute("position",new D.Float32BufferAttribute([0,0,0],3)),T=new D.Points(v,b),T.renderOrder=1e3,T.userData.id="measure",T.raycast=()=>{},t.add(T)}T.position.copy(h),T.visible=!0},R=h=>{let v=new D.BufferGeometry;v.setAttribute("position",new D.Float32BufferAttribute([h.x,h.y,h.z],3));let V=new D.Points(v,y);return V.renderOrder=999,V.userData.id="measure",V.raycast=()=>{},t.add(V),V},w=()=>{f.length=0,S.forEach(h=>{h.geometry.dispose(),h.removeFromParent()}),S.length=0,H&&(H.geometry.dispose(),H.material.dispose(),H.removeFromParent(),H=null),_optionalChain([g, 'optionalAccess', _12 => _12.remove, 'call', _13 => _13()]),g=null},C=()=>{if(f.length!==2)return;let[h,v]=f,V=new _LineGeometryjs.LineGeometry;V.setPositions([h.x,h.y,h.z,v.x,v.y,v.z]);let Y=new (0, _LineMaterialjs.LineMaterial)({color:l});Y.linewidth=2,Y.depthTest=!1,H=new (0, _Line2js.Line2)(V,Y),H.renderOrder=998,H.userData.id="measure",H.raycast=()=>{},t.add(H);let X=h.clone().add(v).multiplyScalar(.5),$=new D.Vector3(Math.abs(v.x-h.x),Math.abs(v.y-h.y),Math.abs(v.z-h.z));g=o.addLabel(d(h.distanceTo(v),$),X,a.labelClassName)},P=h=>{let v=r.getBoundingClientRect();m.x=(h.clientX-v.left)/v.width*2-1,m.y=-((h.clientY-v.top)/v.height)*2+1;let V=n();u.setFromCamera(m,V);let X=V.position.length()*ut;u.params.Line.threshold=X,u.params.Points.threshold=X;let $=u.intersectObjects(t.children,!0).filter(q=>q.object.userData.id!=="measure"&&q.object.userData.id!=="grid");return $.length===0?null:pt($[0],V,{width:v.width,height:v.height},i)};return{setEnabled:h=>{p=h,h||(w(),I(null))},isEnabled:()=>p,handleClick:h=>{if(!p)return!1;f.length===2&&w();let v=P(h);return v===null||(f.push(v),S.push(R(v)),f.length===2&&C()),!0},handleMove:h=>{p&&I(P(h))},clear:w,dispose:()=>{w(),T&&(T.geometry.dispose(),T.removeFromParent(),T=null),y.dispose(),b.dispose()}}}var _OrbitControlsjs = require('three/addons/controls/OrbitControls.js');var _HDRLoaderjs = require('three/addons/loaders/HDRLoader.js');var ee=new E.Vector3(0,0,1);function ht(e){let r=Math.abs(e.x),t=Math.abs(e.y),n=Math.abs(e.z);return n>=r&&n>=t?"z":t>=r&&t>=n?"y":"x"}var mr=function(e,r){let t=gt(r||{}),n=_optionalChain([t, 'access', _14 => _14.environment, 'optionalAccess', _15 => _15.sceneUp])||ee,o=Tt(t),a=Ct(t,e);a.up.copy(n);let i=St(e,t),l=Dt(a,e,t),s=de({scene:o,perspective:a,controls:l,onActiveCameraChange:()=>{},up:n}),c=()=>s.getActiveCamera();vt(o,t);let d=Mt(o,t),u=()=>{d&&Rt(d,oe(o))};_optionalChain([t, 'access', _16 => _16.floor, 'optionalAccess', _17 => _17.enabled])&&xt(o,t);let m=t.grid.enabled?me({cellSize:t.grid.cellSize,majorEvery:t.grid.majorEvery,cellColor:t.grid.cellColor,majorColor:t.grid.majorColor,fadeDistance:t.grid.fadeDistance,plane:t.grid.plane}):null;m&&o.add(m.object);let p=t.gizmo.enabled?pe({camera:a,domElement:e,controller:s}):null,f=_nullishCoalesce(e.parentElement, () => (e)),S=t.measure.enabled?be(f,o):null,H=t.measure.enabled&&S?Re({canvas:e,scene:o,getActiveCamera:c,labelLayer:S,options:{snapPixels:t.measure.snapPixels,color:t.measure.color,labelClassName:t.measure.labelClassName,displayUnit:t.measure.displayUnit,format:t.measure.format}}):null,g=t.events.enableEventHandlers!==!1?At(e,o,c,a,l,t):{dispose:()=>{},fitToView:()=>{},clearSelection:()=>{}},y=5,b=0,T=0,I=M=>{b=M.clientX,T=M.clientY},R=M=>Math.hypot(M.clientX-b,M.clientY-T)>y,w=M=>{if(!R(M)){if(_optionalChain([H, 'optionalAccess', _18 => _18.handleClick, 'call', _19 => _19(M)])){M.stopImmediatePropagation();return}_optionalChain([p, 'optionalAccess', _20 => _20.handleClick, 'call', _21 => _21(M)])&&M.stopImmediatePropagation()}};(p||H)&&(e.addEventListener("mousedown",I,{capture:!0}),e.addEventListener("click",w,{capture:!0}));let C=M=>_optionalChain([H, 'optionalAccess', _22 => _22.handleMove, 'call', _23 => _23(M)]);H&&e.addEventListener("mousemove",C,{passive:!0});let P=M=>{fe(M,{color:t.edges.color,width:t.edges.width,thresholdAngle:t.edges.thresholdAngle})},A=e.parentElement,j=()=>A?{width:A.clientWidth,height:A.clientHeight}:{width:window.innerWidth,height:window.innerHeight},h=null,v=()=>{let{width:M,height:B}=j(),N=Math.min(window.devicePixelRatio,2),K=he(i,o,c(),Math.max(1,M),Math.max(1,B),{toneMapping:_nullishCoalesce(t.render.toneMapping, () => (E.NeutralToneMapping)),toneMappingExposure:_nullishCoalesce(t.render.toneMappingExposure, () => (1)),aoIntensity:t.render.aoIntensity});return K.setSize(Math.max(1,M),Math.max(1,B),N),K},V=M=>{M&&!h?h=v():!M&&h&&(h.dispose(),h=null)};t.render.ambientOcclusion&&(h=v());let{animate:Y,dispose:X}=Ht(i,o,a,c,s,l,j,t.events.onFrame,m,p,()=>h,S);Y(),o.up.set(n.x,n.y,n.z),u();let $=M=>{M.traverse(B=>{let N=B;!N.geometry&&!N.material||(_optionalChain([N, 'access', _24 => _24.geometry, 'optionalAccess', _25 => _25.dispose, 'call', _26 => _26()]),Array.isArray(N.material)?N.material.forEach(K=>K.dispose()):_optionalChain([N, 'access', _27 => _27.material, 'optionalAccess', _28 => _28.dispose, 'call', _29 => _29()]))})},q=M=>{M.userData.source="user",o.add(M)},Le=M=>{M.removeFromParent(),$(M)},Pe=()=>{o.children.filter(B=>B.userData.source==="user").forEach(B=>{B.removeFromParent(),$(B)})};return{scene:o,camera:a,controls:l,renderer:i,cameraController:s,grid:m,gizmo:p,measureTool:H,applyEdges:P,setAmbientOcclusion:V,updateShadowBounds:u,dispose:()=>{X(),g.dispose(),(p||H)&&(e.removeEventListener("mousedown",I,{capture:!0}),e.removeEventListener("click",w,{capture:!0})),H&&e.removeEventListener("mousemove",C),_optionalChain([H, 'optionalAccess', _30 => _30.dispose, 'call', _31 => _31()]),_optionalChain([S, 'optionalAccess', _32 => _32.dispose, 'call', _33 => _33()]),_optionalChain([p, 'optionalAccess', _34 => _34.dispose, 'call', _35 => _35()]),_optionalChain([m, 'optionalAccess', _36 => _36.dispose, 'call', _37 => _37()]),_optionalChain([h, 'optionalAccess', _38 => _38.dispose, 'call', _39 => _39()]),l.dispose(),i.dispose(),o.traverse(M=>{let B=M;!B.geometry&&!B.material||(_optionalChain([B, 'access', _40 => _40.geometry, 'optionalAccess', _41 => _41.dispose, 'call', _42 => _42()]),Array.isArray(B.material)?B.material.forEach(N=>N.dispose()):_optionalChain([B, 'access', _43 => _43.material, 'optionalAccess', _44 => _44.dispose, 'call', _45 => _45()]))}),_optionalChain([o, 'access', _46 => _46.environment, 'optionalAccess', _47 => _47.dispose, 'call', _48 => _48()]),o.background instanceof E.Texture&&o.background.dispose()},fitToView:g.fitToView,clearSelection:g.clearSelection,addUserGeometry:q,removeUserGeometry:Le,clearUserGeometry:Pe}};function gt(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', _49 => _49.camera, 'optionalAccess', _50 => _50.position])||new E.Vector3(-n.cameraDistance,-n.cameraDistance,n.cameraDistance),fov:_optionalChain([e, 'access', _51 => _51.camera, 'optionalAccess', _52 => _52.fov])||20,near:_optionalChain([e, 'access', _53 => _53.camera, 'optionalAccess', _54 => _54.near])||n.near,far:_optionalChain([e, 'access', _55 => _55.camera, 'optionalAccess', _56 => _56.far])||n.far,target:_optionalChain([e, 'access', _57 => _57.camera, 'optionalAccess', _58 => _58.target])||new E.Vector3(0,0,0)},lighting:{enableSunlight:_nullishCoalesce(_optionalChain([e, 'access', _59 => _59.lighting, 'optionalAccess', _60 => _60.enableSunlight]), () => (!0)),sunlightIntensity:_nullishCoalesce(_optionalChain([e, 'access', _61 => _61.lighting, 'optionalAccess', _62 => _62.sunlightIntensity]), () => (1)),sunlightPosition:_optionalChain([e, 'access', _63 => _63.lighting, 'optionalAccess', _64 => _64.sunlightPosition])||new E.Vector3(n.lightDistance,n.lightDistance,n.lightHeight),ambientLightColor:_optionalChain([e, 'access', _65 => _65.lighting, 'optionalAccess', _66 => _66.ambientLightColor])||new E.Color(4210752),ambientLightIntensity:_nullishCoalesce(_optionalChain([e, 'access', _67 => _67.lighting, 'optionalAccess', _68 => _68.ambientLightIntensity]), () => (1)),sunlightColor:_optionalChain([e, 'access', _69 => _69.lighting, 'optionalAccess', _70 => _70.sunlightColor])||16777215},environment:{hdrPath:_optionalChain([e, 'access', _71 => _71.environment, 'optionalAccess', _72 => _72.hdrPath])||"/baseHDR.hdr",backgroundColor:_optionalChain([e, 'access', _73 => _73.environment, 'optionalAccess', _74 => _74.backgroundColor])||new E.Color(15790320),enableEnvironmentLighting:_nullishCoalesce(_optionalChain([e, 'access', _75 => _75.environment, 'optionalAccess', _76 => _76.enableEnvironmentLighting]), () => (!0)),sceneUp:_optionalChain([e, 'access', _77 => _77.environment, 'optionalAccess', _78 => _78.sceneUp])||ee,showEnvironment:_nullishCoalesce(_optionalChain([e, 'access', _79 => _79.environment, 'optionalAccess', _80 => _80.showEnvironment]), () => (!1))},floor:{enabled:_nullishCoalesce(_optionalChain([e, 'access', _81 => _81.floor, 'optionalAccess', _82 => _82.enabled]), () => (!1)),size:_optionalChain([e, 'access', _83 => _83.floor, 'optionalAccess', _84 => _84.size])||n.floorSize,color:_optionalChain([e, 'access', _85 => _85.floor, 'optionalAccess', _86 => _86.color])||new E.Color(8421504),roughness:_nullishCoalesce(_optionalChain([e, 'access', _87 => _87.floor, 'optionalAccess', _88 => _88.roughness]), () => (.7)),metalness:_nullishCoalesce(_optionalChain([e, 'access', _89 => _89.floor, 'optionalAccess', _90 => _90.metalness]), () => (0)),receiveShadow:_nullishCoalesce(_optionalChain([e, 'access', _91 => _91.floor, 'optionalAccess', _92 => _92.receiveShadow]), () => (!0))},render:{enableShadows:_nullishCoalesce(_optionalChain([e, 'access', _93 => _93.render, 'optionalAccess', _94 => _94.enableShadows]), () => (!0)),shadowMapSize:_optionalChain([e, 'access', _95 => _95.render, 'optionalAccess', _96 => _96.shadowMapSize])||2048,antialias:_nullishCoalesce(_optionalChain([e, 'access', _97 => _97.render, 'optionalAccess', _98 => _98.antialias]), () => (!0)),pixelRatio:_optionalChain([e, 'access', _99 => _99.render, 'optionalAccess', _100 => _100.pixelRatio])||Math.min(window.devicePixelRatio,2),toneMapping:_optionalChain([e, 'access', _101 => _101.render, 'optionalAccess', _102 => _102.toneMapping])||E.NeutralToneMapping,toneMappingExposure:_nullishCoalesce(_optionalChain([e, 'access', _103 => _103.render, 'optionalAccess', _104 => _104.toneMappingExposure]), () => (1)),preserveDrawingBuffer:_nullishCoalesce(_optionalChain([e, 'access', _105 => _105.render, 'optionalAccess', _106 => _106.preserveDrawingBuffer]), () => (!1)),ambientOcclusion:_nullishCoalesce(_optionalChain([e, 'access', _107 => _107.render, 'optionalAccess', _108 => _108.ambientOcclusion]), () => (!1)),aoIntensity:_nullishCoalesce(_optionalChain([e, 'access', _109 => _109.render, 'optionalAccess', _110 => _110.aoIntensity]), () => (1))},controls:{enableDamping:_nullishCoalesce(_optionalChain([e, 'access', _111 => _111.controls, 'optionalAccess', _112 => _112.enableDamping]), () => (!1)),dampingFactor:_optionalChain([e, 'access', _113 => _113.controls, 'optionalAccess', _114 => _114.dampingFactor])||.05,autoRotate:_nullishCoalesce(_optionalChain([e, 'access', _115 => _115.controls, 'optionalAccess', _116 => _116.autoRotate]), () => (!1)),autoRotateSpeed:_optionalChain([e, 'access', _117 => _117.controls, 'optionalAccess', _118 => _118.autoRotateSpeed])||.5,enableZoom:_nullishCoalesce(_optionalChain([e, 'access', _119 => _119.controls, 'optionalAccess', _120 => _120.enableZoom]), () => (!0)),enablePan:_nullishCoalesce(_optionalChain([e, 'access', _121 => _121.controls, 'optionalAccess', _122 => _122.enablePan]), () => (!0)),minDistance:_optionalChain([e, 'access', _123 => _123.controls, 'optionalAccess', _124 => _124.minDistance])||n.minDistance,maxDistance:_optionalChain([e, 'access', _125 => _125.controls, 'optionalAccess', _126 => _126.maxDistance])||1/0},grid:{enabled:_nullishCoalesce(_optionalChain([e, 'access', _127 => _127.grid, 'optionalAccess', _128 => _128.enabled]), () => (!1)),cellSize:_nullishCoalesce(_optionalChain([e, 'access', _129 => _129.grid, 'optionalAccess', _130 => _130.cellSize]), () => (1)),majorEvery:_nullishCoalesce(_optionalChain([e, 'access', _131 => _131.grid, 'optionalAccess', _132 => _132.majorEvery]), () => (10)),cellColor:_nullishCoalesce(_optionalChain([e, 'access', _133 => _133.grid, 'optionalAccess', _134 => _134.cellColor]), () => (8947848)),majorColor:_nullishCoalesce(_optionalChain([e, 'access', _135 => _135.grid, 'optionalAccess', _136 => _136.majorColor]), () => (4473924)),fadeDistance:_nullishCoalesce(_optionalChain([e, 'access', _137 => _137.grid, 'optionalAccess', _138 => _138.fadeDistance]), () => (100)),plane:_nullishCoalesce(_optionalChain([e, 'access', _139 => _139.grid, 'optionalAccess', _140 => _140.plane]), () => (ht(_nullishCoalesce(_optionalChain([e, 'access', _141 => _141.environment, 'optionalAccess', _142 => _142.sceneUp]), () => (ee)))))},gizmo:{enabled:_nullishCoalesce(_optionalChain([e, 'access', _143 => _143.gizmo, 'optionalAccess', _144 => _144.enabled]), () => (!1))},edges:{enabled:_nullishCoalesce(_optionalChain([e, 'access', _145 => _145.edges, 'optionalAccess', _146 => _146.enabled]), () => (!1)),color:_nullishCoalesce(_optionalChain([e, 'access', _147 => _147.edges, 'optionalAccess', _148 => _148.color]), () => (2236962)),width:_nullishCoalesce(_optionalChain([e, 'access', _149 => _149.edges, 'optionalAccess', _150 => _150.width]), () => (1.5)),thresholdAngle:_nullishCoalesce(_optionalChain([e, 'access', _151 => _151.edges, 'optionalAccess', _152 => _152.thresholdAngle]), () => (30))},measure:{enabled:_nullishCoalesce(_optionalChain([e, 'access', _153 => _153.measure, 'optionalAccess', _154 => _154.enabled]), () => (!1)),snapPixels:_optionalChain([e, 'access', _155 => _155.measure, 'optionalAccess', _156 => _156.snapPixels]),color:_optionalChain([e, 'access', _157 => _157.measure, 'optionalAccess', _158 => _158.color]),labelClassName:_optionalChain([e, 'access', _159 => _159.measure, 'optionalAccess', _160 => _160.labelClassName]),displayUnit:_optionalChain([e, 'access', _161 => _161.measure, 'optionalAccess', _162 => _162.displayUnit]),format:_optionalChain([e, 'access', _163 => _163.measure, 'optionalAccess', _164 => _164.format])},events:{onBackgroundClicked:_optionalChain([e, 'access', _165 => _165.events, 'optionalAccess', _166 => _166.onBackgroundClicked]),onObjectSelected:_optionalChain([e, 'access', _167 => _167.events, 'optionalAccess', _168 => _168.onObjectSelected]),onMeshMetadataClicked:_optionalChain([e, 'access', _169 => _169.events, 'optionalAccess', _170 => _170.onMeshMetadataClicked]),onMeshDoubleClicked:_optionalChain([e, 'access', _171 => _171.events, 'optionalAccess', _172 => _172.onMeshDoubleClicked]),selectionColor:_optionalChain([e, 'access', _173 => _173.events, 'optionalAccess', _174 => _174.selectionColor])||"#ff0000",enableEventHandlers:_nullishCoalesce(_optionalChain([e, 'access', _175 => _175.events, 'optionalAccess', _176 => _176.enableEventHandlers]), () => (!0)),enableKeyboardControls:_nullishCoalesce(_optionalChain([e, 'access', _177 => _177.events, 'optionalAccess', _178 => _178.enableKeyboardControls]), () => (!0)),enableClickToFocus:_nullishCoalesce(_optionalChain([e, 'access', _179 => _179.events, 'optionalAccess', _180 => _180.enableClickToFocus]), () => (!0)),enableDoubleClickZoom:_nullishCoalesce(_optionalChain([e, 'access', _181 => _181.events, 'optionalAccess', _182 => _182.enableDoubleClickZoom]), () => (!0)),onReady:_optionalChain([e, 'access', _183 => _183.events, 'optionalAccess', _184 => _184.onReady]),onFrame:_optionalChain([e, 'access', _185 => _185.events, 'optionalAccess', _186 => _186.onFrame])}}}var bt=new Set(["grid","floor","label-layer","measure"]);function yt(e){let r=e;for(;r;){if(typeof r.userData.id=="string"&&bt.has(r.userData.id))return!0;r=r.parent}return!1}function oe(e){let r=new E.Box3;return e.traverse(t=>{let n=t;t.visible&&!yt(t)&&n.geometry&&r.expandByObject(t)}),r}function Rt(e,r){if(r.isEmpty())return;let t=r.getCenter(new E.Vector3),n=r.getSize(new E.Vector3).length()*.5*1.2,o=e.shadow.camera;o.left=-n,o.right=n,o.top=n,o.bottom=-n,e.target.position.copy(t),e.target.updateMatrixWorld();let a=e.position.distanceTo(t);o.near=Math.max(n*.01,a-n),o.far=a+n,o.updateProjectionMatrix()}function Tt(e){let r=new E.Scene,t=typeof e.environment.backgroundColor=="string"?new E.Color(e.environment.backgroundColor):e.environment.backgroundColor;return r.background=t||null,r}function wt(e,r,t,n,o=200){let a=e.position.clone(),i=r.target.clone(),l=performance.now(),s=d=>1-Math.pow(1-d,3),c=()=>{let d=performance.now()-l,u=s(Math.min(d/o,1));e.position.lerpVectors(a,t,u),r.target.lerpVectors(i,n,u),r.update(),u<1&&requestAnimationFrame(c)};requestAnimationFrame(c)}function Ht(e,r,t,n,o,a,i,l,s,c,d,u){let m=null,p=performance.now(),f=()=>{let{width:g,height:y}=i();if(g===0||y===0)return;let b=Math.min(window.devicePixelRatio,2),T=Math.round(g*b),I=Math.round(y*b);(e.domElement.width!==T||e.domElement.height!==I)&&(e.setPixelRatio(b),e.setSize(g,y,!1),t.aspect=g/y,t.updateProjectionMatrix(),o.updateAspect(g,y),_optionalChain([d, 'optionalCall', _187 => _187(), 'optionalAccess', _188 => _188.setSize, 'call', _189 => _189(g,y,b)]),_optionalChain([u, 'optionalAccess', _190 => _190.setSize, 'call', _191 => _191(g,y)]))},S=function(){m=requestAnimationFrame(S);let g=performance.now(),y=(g-p)/1e3;p=g,f(),(a.enableDamping||a.autoRotate)&&a.update(),s&&s.update(n().position),c&&c.update(y),_optionalChain([l, 'optionalCall', _192 => _192(y)]);let b=n(),T=_optionalChain([d, 'optionalCall', _193 => _193()]);T?(T.setCamera(b),T.render(y)):e.render(r,b),u&&u.render(r,b),c&&c.render(e)};return{animate:S,dispose:()=>{m!==null&&(cancelAnimationFrame(m),m=null)}}}function vt(e,r){r.environment.enableEnvironmentLighting?new (0, _HDRLoaderjs.HDRLoader)().load(r.environment.hdrPath||"/baseHDR.hdr",function(t){if(!_optionalChain([t, 'optionalAccess', _194 => _194.image])){_chunk2QHLW6ZLcjs.e.call(void 0, ).warn("HDR loaded without image data; skipping environment map."),_optionalChain([r, 'access', _195 => _195.events, 'access', _196 => _196.onReady, 'optionalCall', _197 => _197()]);return}t.mapping=E.EquirectangularReflectionMapping,e.environment=t,r.environment.showEnvironment&&(e.background=t),_optionalChain([r, 'access', _198 => _198.events, 'access', _199 => _199.onReady, 'optionalCall', _200 => _200()])},void 0,function(t){_chunk2QHLW6ZLcjs.e.call(void 0, ).warn("HDR texture could not be loaded, falling back to basic lighting:",t),_optionalChain([r, 'access', _201 => _201.events, 'access', _202 => _202.onReady, 'optionalCall', _203 => _203()])}):_optionalChain([r, 'access', _204 => _204.events, 'access', _205 => _205.onReady, 'optionalCall', _206 => _206()])}function Mt(e,r){let t=new E.AmbientLight(r.lighting.ambientLightColor,r.lighting.ambientLightIntensity);if(e.add(t),!r.lighting.enableSunlight)return null;let n=new E.DirectionalLight(_nullishCoalesce(r.lighting.sunlightColor, () => (16777215)),r.lighting.sunlightIntensity),o=r.lighting.sunlightPosition;return o&&n.position.set(o.x,o.y,o.z),r.render.enableShadows?(n.castShadow=!0,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,n.shadow.radius=4,e.add(n),e.add(n.target),n):(e.add(n),null)}function xt(e,r){let t=r.floor.size,n=new E.PlaneGeometry(t,t),o=typeof r.floor.color=="string"?new E.Color(r.floor.color):r.floor.color,a=new E.MeshStandardMaterial({color:o,roughness:r.floor.roughness,metalness:r.floor.metalness,side:E.DoubleSide}),i=new E.Mesh(n,a);i.userData.id="floor",i.name="floor";let l=(_optionalChain([r, 'access', _207 => _207.environment, 'optionalAccess', _208 => _208.sceneUp])||ee).clone().normalize();i.quaternion.setFromUnitVectors(new E.Vector3(0,0,1),l),i.position.set(0,0,0),r.floor.receiveShadow&&r.render.enableShadows&&(i.receiveShadow=!0),e.add(i)}function Ct(e,r){let t=r.parentElement,n=t?t.clientWidth:window.innerWidth,o=t?t.clientHeight:window.innerHeight,a=new E.PerspectiveCamera(e.camera.fov,n/o,e.camera.near,e.camera.far),i=e.camera.position;return i&&a.position.set(i.x,i.y,i.z),a}function St(e,r){let t=new E.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,a=n?n.clientHeight:window.innerHeight;return n&&(e.style.width="100%",e.style.height="100%",e.style.display="block"),t.setSize(o,a,!1),t.setPixelRatio(r.render.pixelRatio||Math.min(window.devicePixelRatio,2)),r.render.enableShadows&&(t.shadowMap.enabled=!0,t.shadowMap.type=E.VSMShadowMap),t.toneMapping=r.render.toneMapping,t.toneMappingExposure=_nullishCoalesce(r.render.toneMappingExposure, () => (1)),t.outputColorSpace=E.SRGBColorSpace,t.sortObjects=!0,t}function At(e,r,t,n,o,a){let i=new Set,l=new Map,s=new E.Raycaster,c=new E.Vector2,d=new E.Vector2,u=R=>{let w=R;for(;w;){if(!w.visible)return!1;w=w.parent}return!0},m=()=>{let R=oe(r);if(R.isEmpty()){_chunk2QHLW6ZLcjs.e.call(void 0, ).warn("No objects to fit to view");return}let w=R.getCenter(new E.Vector3),C=R.getSize(new E.Vector3),P=Math.max(C.x,C.y,C.z),A=n.fov*(Math.PI/180),j=P/(2*Math.tan(A/2));j*=1.5;let h=n.position.clone().sub(o.target);h.lengthSq()<1e-12&&h.set(.8,1,1.2),h.normalize(),n.position.copy(w.clone().add(h.multiplyScalar(j))),o.target.copy(w),o.update()},p=typeof a.events.selectionColor=="string"?new E.Color(a.events.selectionColor):a.events.selectionColor instanceof E.Color?a.events.selectionColor:new E.Color("#ff0000"),f=()=>{i.forEach(R=>{let w=R;if(l.has(R)){let C=l.get(R),P=w.material;P instanceof E.Material?P.dispose():Array.isArray(P)&&P.forEach(A=>A.dispose()),w.material=C,l.delete(R)}}),i.clear()},S=R=>{let w=R;if(!(w.material instanceof E.Material))return!1;l.set(R,w.material);let C=w.material.clone();return R instanceof E.Mesh&&"emissive"in C?C.emissive=p.clone():"color"in C&&(C.color=p.clone()),w.material=C,!0},H=()=>{let R=oe(r),w=R.isEmpty()?1:R.getSize(new E.Vector3).length();s.params.Points.threshold=w*.01},g=R=>{d.set(R.clientX,R.clientY)},y=R=>{let w=new E.Vector2(R.clientX,R.clientY);if(d.distanceTo(w)>5)return;let C=e.getBoundingClientRect();c.x=(R.clientX-C.left)/C.width*2-1,c.y=-((R.clientY-C.top)/C.height)*2+1,H(),s.setFromCamera(c,t());let P=s.intersectObjects(r.children,!0).filter(A=>u(A.object));if(P.length>0){let A=P[0].object;i.has(A)||(f(),i.add(A),S(A),_optionalChain([a, 'access', _209 => _209.events, 'optionalAccess', _210 => _210.onObjectSelected, 'optionalCall', _211 => _211(A)]),A instanceof E.Mesh&&Object.keys(A.userData).length>0&&_optionalChain([a, 'access', _212 => _212.events, 'optionalAccess', _213 => _213.onMeshMetadataClicked, 'optionalCall', _214 => _214(A.userData)]))}else f(),_optionalChain([a, 'access', _215 => _215.events, 'optionalAccess', _216 => _216.onBackgroundClicked, 'optionalCall', _217 => _217({x:c.x,y:c.y})])},b=R=>{let w=e.getBoundingClientRect();c.x=(R.clientX-w.left)/w.width*2-1,c.y=-((R.clientY-w.top)/w.height)*2+1,H(),s.setFromCamera(c,t());let C=s.intersectObjects(r.children,!0).filter(q=>u(q.object));if(C.length===0)return;let P=C[0].object;if(_optionalChain([a, 'access', _218 => _218.events, 'optionalAccess', _219 => _219.onMeshDoubleClicked, 'optionalCall', _220 => _220(P)]),!_optionalChain([a, 'access', _221 => _221.events, 'optionalAccess', _222 => _222.enableDoubleClickZoom]))return;let A=new E.Box3().setFromObject(P);if(A.isEmpty())return;let j=A.getCenter(new E.Vector3),h=A.getSize(new E.Vector3),v=Math.max(h.x,h.y,h.z),V=n.fov*(Math.PI/180),Y=v/(2*Math.tan(V/2))*1.5,X=n.position.clone().sub(o.target).normalize(),$=j.clone().add(X.multiplyScalar(Y));wt(n,o,$,j)},T=R=>{if(_optionalChain([a, 'access', _223 => _223.events, 'optionalAccess', _224 => _224.enableKeyboardControls]))switch(R.key.toLowerCase()){case"f":R.preventDefault(),m();break;case"escape":R.preventDefault(),f();break;case" ":R.preventDefault(),m();break}};return _optionalChain([a, 'access', _225 => _225.events, 'optionalAccess', _226 => _226.enableClickToFocus])&&(e.addEventListener("mousedown",g),e.addEventListener("click",y),e.addEventListener("dblclick",b)),_optionalChain([a, 'access', _227 => _227.events, 'optionalAccess', _228 => _228.enableKeyboardControls])&&(e.setAttribute("tabindex","0"),e.addEventListener("keydown",T)),{dispose:()=>{e.removeEventListener("mousedown",g),e.removeEventListener("click",y),e.removeEventListener("dblclick",b),e.removeEventListener("keydown",T),f()},fitToView:m,clearSelection:f}}function Dt(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 Ft={};_chunk2QHLW6ZLcjs.a.call(void 0, Ft,{CONCRETE_MATERIAL:()=>Ot,EMISSIVE_MATERIAL:()=>Lt,GLASS_MATERIAL:()=>Vt,METAL_MATERIAL:()=>Pt,PLASTIC_MATERIAL:()=>It,RUBBER_MATERIAL:()=>Bt,WOOD_MATERIAL:()=>zt});var Lt=new L.MeshPhysicalMaterial({color:0,emissive:new L.Color(16777215),emissiveIntensity:5,metalness:0,roughness:.2,clearcoat:.3,clearcoatRoughness:.2,depthWrite:!0,depthTest:!0,transparent:!1,alphaTest:0,polygonOffset:!0,side:L.FrontSide,dithering:!0}),Pt=new L.MeshPhysicalMaterial({color:new L.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:L.FrontSide,dithering:!0}),Ot=new L.MeshPhysicalMaterial({color:new L.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:L.FrontSide,dithering:!0}),It=new L.MeshPhysicalMaterial({color:new L.Color(16777215),metalness:0,roughness:.3,envMapIntensity:.5,clearcoat:.5,clearcoatRoughness:.1,reflectivity:.5,ior:1.4,transmission:0,transparent:!1,depthWrite:!0,side:L.FrontSide,dithering:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),Vt=new L.MeshPhysicalMaterial({color:new L.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:L.DoubleSide,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),Bt=new L.MeshPhysicalMaterial({color:new L.Color(1710618),metalness:0,roughness:.9,envMapIntensity:.2,clearcoat:.1,clearcoatRoughness:.8,reflectivity:.2,ior:1.3,transmission:0,depthWrite:!0,side:L.FrontSide,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),zt=new L.MeshPhysicalMaterial({color:new L.Color(8934707),metalness:0,roughness:.7,envMapIntensity:.3,clearcoat:.3,clearcoatRoughness:.4,reflectivity:.3,ior:1.3,transmission:0,depthWrite:!0,side:L.FrontSide,dithering:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1});function te(e,r,t,n=!0){return{x:e,y:r,z:t}}var _t="#ffffff",Te=12,Gt=4e-4,Nt=12,Wt=.05;function we(e,r={}){if(!e||e.length===0)return[];let{rhino:t,applyTransforms:n=!0}=r,o=[];for(let a of e)switch(a.kind){case"curve":{let i=Yt(a,t,n);i&&o.push(i);break}case"point":{o.push(Xt(a,n));break}default:{let i=a;_chunk2QHLW6ZLcjs.e.call(void 0, ).warn(`Skipping unknown display item kind: ${String(i.kind)}`);break}}return o}var $t=2;function Yt(e,r,t){if(!r)return _chunk2QHLW6ZLcjs.e.call(void 0, ).warn("No rhino3dm instance provided; skipping curve display item."),null;let n=qt(e.json,r);if(!n)return null;let o=Zt(n,t);if(o.length<2)return null;let a=[];for(let u of o)a.push(u.x,u.y,u.z);let i=new _LineGeometryjs.LineGeometry;i.setPositions(a);let l=He(e.color,e.opacity),s=new (0, _LineMaterialjs.LineMaterial)({color:l.color}),c=s;c.linewidth=_nullishCoalesce(e.width, () => ($t)),c.transparent=l.transparent,c.opacity=l.opacity;let d=new (0, _Line2js.Line2)(i,s);return d.computeLineDistances(),d.name=e.name,d.userData={source:"compute",id:e.id,layer:e.layer,kind:"curve",metadata:e.metadata},d}function Xt(e,r){let{x:t,y:n,z:o}=te(e.position.X,e.position.Y,e.position.Z,r),a=new _.BufferGeometry;a.setAttribute("position",new _.Float32BufferAttribute([t,n,o],3));let i=new _.PointsMaterial({...He(e.color,e.opacity),size:6,sizeAttenuation:!1}),l=new _.Points(a,i);return l.name=e.name,l.userData={source:"compute",id:e.id,layer:e.layer,kind:"point",metadata:e.metadata},l}function qt(e,r){try{let t=JSON.parse(e),n=r.CommonObject.decode(t);return n&&typeof n.pointAt=="function"?n:(_chunk2QHLW6ZLcjs.e.call(void 0, ).warn("Decoded display-item JSON is not a curve; skipping."),null)}catch(t){return _chunk2QHLW6ZLcjs.e.call(void 0, ).warn("Failed to decode curve display item JSON:",t),null}}function Zt(e,r){let t=Jt(e,r);return t||Kt(e,r)}function Jt(e,r){if(!e.isPolyline())return null;let t=e.tryGetPolyline(),n=Array.isArray(t)?t[1]:t;if(!n||typeof n.count!="number"||n.count<2)return null;let o=[];for(let a=0;a<n.count;a++){let i=n.get(a),{x:l,y:s,z:c}=te(i[0],i[1],i[2],r);o.push(new _.Vector3(l,s,c))}return o}function Kt(e,r){let t=e.domain,n=t[0],a=t[1]-n,i=u=>{let m=e.pointAt(u),{x:p,y:f,z:S}=te(m[0],m[1],m[2],r);return new _.Vector3(p,f,S)},l=Qt(e),s=n,c=i(n),d=[c];for(let u=0;u<Te;u++){let m=n+a*(u+1)/Te,p=i(m);ae(s,c,m,p,i,l,Nt,d),d.push(p),s=m,c=p}return d}function ae(e,r,t,n,o,a,i,l){if(i<=0)return;let s=(e+t)/2,c=o(s),d=tn(c,r,n),u=en(r,c,n);d<=a&&u<=Wt||(ae(e,r,s,c,o,a,i-1,l),l.push(c),ae(s,c,t,n,o,a,i-1,l))}function Qt(e){let r=e.getBoundingBox(),t=r.min,n=r.max,o=Math.hypot(n[0]-t[0],n[1]-t[1],n[2]-t[2]);return Math.max(o*Gt,1e-6)}function en(e,r,t){let n=r.clone().sub(e),o=t.clone().sub(r),a=n.length(),i=o.length();if(a===0||i===0)return 0;let l=Math.max(-1,Math.min(1,n.dot(o)/(a*i)));return Math.acos(l)}function tn(e,r,t){let n=t.clone().sub(r),o=n.lengthSq();if(o===0)return e.distanceTo(r);let a=Math.max(0,Math.min(1,e.clone().sub(r).dot(n)/o)),i=r.clone().addScaledVector(n,a);return e.distanceTo(i)}function He(e,r){let t=_nullishCoalesce(r, () => (1));return{color:new _.Color(_nullishCoalesce(e, () => (_t))),transparent:t<1,opacity:t}}var _fflate = require('fflate');var ve=1096174675,rn=1515605075,Me= exports.t =2,xe=1,ie= exports.u =1,on=2,Ce=12,Se=56;function se(e){let r=sn(an(e)),t=new DataView(r.buffer,r.byteOffset,r.byteLength);if(r.byteLength<Ce)throw G("Blob too small to contain SLVA header.",{expectedBytes:Ce,availableBytes:r.byteLength});let n=0,o=t.getUint32(n,!0);if(n+=4,o!==ve)throw G(`Invalid SLVA magic: 0x${o.toString(16)}`,{expectedMagic:`0x${ve.toString(16)}`,actualMagic:`0x${o.toString(16)}`});let a=t.getUint32(n,!0);if(n+=4,a<xe||a>Me)throw G(`Unsupported SLVA version: ${a}`,{minSupportedVersion:xe,maxSupportedVersion:Me,actualVersion:a});let i=t.getUint32(n,!0);if(n+=4,n+i>r.byteLength)throw G("Insufficient data to read metadata JSON.",{expectedBytes:i,availableBytes:r.byteLength-n,offset:n});let l=r.subarray(n,n+i);n+=i;let s;try{s=JSON.parse(ln(l))}catch(h){throw G(`Failed to parse metadata JSON: ${h instanceof Error?h.message:String(h)}`,{metadataLen:i})}if(n+Se>r.byteLength)throw G("Insufficient data to read geometry header.",{expectedBytes:Se,availableBytes:r.byteLength-n,offset:n});let c=t.getUint32(n,!0);n+=4;let d=t.getFloat64(n,!0);n+=8;let u=t.getFloat64(n,!0);n+=8;let m=t.getFloat64(n,!0);n+=8;let p=t.getFloat64(n,!0);n+=8;let f=t.getFloat64(n,!0);n+=8;let S=t.getFloat64(n,!0);n+=8;let H=t.getUint32(n,!0);n+=4;let g=(c&ie)!==0,y=H*3,T=y*(g?4:2);if(n+T>r.byteLength)throw G("Insufficient data to read vertices.",{expectedBytes:T,availableBytes:r.byteLength-n,offset:n,useFloat32:g,vertexCount:H});let I=r.byteOffset+n,R=g?un(r.buffer,I,y):cn(r.buffer,I,y);if(n+=T,n+4>r.byteLength)throw G("Insufficient data to read index count.",{expectedBytes:4,availableBytes:r.byteLength-n,offset:n});let w=t.getUint32(n,!0);n+=4;let C=(c&on)!==0,A=w*(C?2:4);if(n+A>r.byteLength)throw G("Insufficient data to read indices.",{expectedBytes:A,availableBytes:r.byteLength-n,offset:n,indexCount:w,useUint16Indices:C});let j=C?dn(r.buffer,r.byteOffset+n,w):mn(r.buffer,r.byteOffset+n,w);return{metadata:s,flags:c,vertices:R,indices:j,origin:[d,u,m],scale:[p,f,S]}}function an(e){return typeof e=="string"?_chunk2QHLW6ZLcjs.m.call(void 0, e):e instanceof Uint8Array?e:new Uint8Array(e)}function sn(e){if(e.byteLength<8)return e;let r=new DataView(e.buffer,e.byteOffset,e.byteLength);if(r.getUint32(0,!0)!==rn)return e;let t=r.getUint32(4,!0),n=e.subarray(8),o=Math.max(n.byteLength*1032+1024,1<<20);if(t>o)throw G("SLVZ header declares an implausible uncompressed length",{uncompressedLen:t,deflatedBytes:n.byteLength,maxPlausibleLen:o});try{return _fflate.inflateSync.call(void 0, n,{out:new Uint8Array(t)})}catch(a){throw G(`Failed to inflate SLVZ blob: ${a instanceof Error?a.message:String(a)}`,{uncompressedLen:t,deflatedBytes:n.byteLength})}}function ln(e){if(typeof TextDecoder<"u")return new TextDecoder("utf-8").decode(e);if(typeof globalThis.Buffer<"u")return globalThis.Buffer.from(e).toString("utf-8");throw new (0, _chunk2QHLW6ZLcjs.d)("No UTF-8 decoder available in this environment.",_chunk2QHLW6ZLcjs.c.INVALID_STATE)}function cn(e,r,t){if(t===0)return new Int16Array(0);if(r%2===0)return new Int16Array(e,r,t);let n=new Uint8Array(t*2);return n.set(new Uint8Array(e,r,t*2)),new Int16Array(n.buffer)}function un(e,r,t){if(t===0)return new Float32Array(0);if(r%4===0)return new Float32Array(e,r,t);let n=new Uint8Array(t*4);return n.set(new Uint8Array(e,r,t*4)),new Float32Array(n.buffer)}function dn(e,r,t){if(t===0)return new Uint16Array(0);if(r%2===0)return new Uint16Array(e,r,t);let n=new Uint8Array(t*2);return n.set(new Uint8Array(e,r,t*2)),new Uint16Array(n.buffer)}function mn(e,r,t){if(t===0)return new Uint32Array(0);if(r%4===0)return new Uint32Array(e,r,t);let n=new Uint8Array(t*4);return n.set(new Uint8Array(e,r,t*4)),new Uint32Array(n.buffer)}function G(e,r){return new (0, _chunk2QHLW6ZLcjs.d)(e,_chunk2QHLW6ZLcjs.c.VALIDATION_ERROR,{context:r})}async function Ae(e,r){let{debug:t=!1}=_nullishCoalesce(r, () => ({})),n=t?performance.now():0;try{let o=performance.now(),a=JSON.parse(e),i=performance.now()-o;return await pn(a,r,{parseTime:i,perfStart:n})}catch(o){return _chunk2QHLW6ZLcjs.e.call(void 0, ).error("Error parsing mesh batch:",o),[]}}async function pn(e,r,t){let{mergeByMaterial:n=!0,applyTransforms:o=!0,debug:a=!1}=_nullishCoalesce(r, () => ({})),{parseTime:i=0,perfStart:l=a?performance.now():0}=_nullishCoalesce(t, () => ({}));try{let s=performance.now(),c=se(e.compressedData),d=performance.now()-s,u=a?yn(e.compressedData):0;return De(c,{mergeByMaterial:n,applyTransforms:o,debug:a,parseTime:i,decodeTime:d,perfStart:l,blobBytes:u,fallback:{materials:e.materials,groups:e.groups,sourceComponentId:e.sourceComponentId}})}catch(s){return _chunk2QHLW6ZLcjs.e.call(void 0, ).error("Error parsing mesh batch object:",s),[]}}async function Sr(e,r){let{mergeByMaterial:t=!0,applyTransforms:n=!0,debug:o=!1}=_nullishCoalesce(r, () => ({})),a=o?performance.now():0;try{let i=performance.now(),l=se(e),s=performance.now()-i,c=e.byteLength;return De(l,{mergeByMaterial:t,applyTransforms:n,debug:o,parseTime:0,decodeTime:s,perfStart:a,blobBytes:c})}catch(i){return _chunk2QHLW6ZLcjs.e.call(void 0, ).error("Error parsing mesh batch blob:",i),[]}}function De(e,r){let{mergeByMaterial:t,applyTransforms:n,debug:o,parseTime:a,decodeTime:i,perfStart:l,blobBytes:s,fallback:c}=r,d=_nullishCoalesce(_nullishCoalesce(e.metadata.materials, () => (_optionalChain([c, 'optionalAccess', _229 => _229.materials]))), () => ([])),u=_nullishCoalesce(_nullishCoalesce(e.metadata.groups, () => (_optionalChain([c, 'optionalAccess', _230 => _230.groups]))), () => ([])),m=_nullishCoalesce(_optionalChain([c, 'optionalAccess', _231 => _231.sourceComponentId]), () => (e.metadata.sourceComponentId)),p=(e.flags&ie)!==0,f=p?fn(e.vertices,n):En(e.vertices,e.origin,e.scale,n);if(o){let b=e.vertices.byteLength+e.indices.byteLength;_chunk2QHLW6ZLcjs.e.call(void 0, ).debug("Mesh Batch Stats:"),_chunk2QHLW6ZLcjs.e.call(void 0, ).debug(` Materials: ${d.length} | Groups: ${u.length}`),_chunk2QHLW6ZLcjs.e.call(void 0, ).debug(` Vertices: ${e.vertices.length/3} | Indices: ${e.indices.length}`),_chunk2QHLW6ZLcjs.e.call(void 0, ).debug(` Format: ${p?"float32":"int16 quantized"}`),_chunk2QHLW6ZLcjs.e.call(void 0, ).debug(` Blob: ${(s/1024/1024).toFixed(2)} MB | Geometry on wire: ${(b/1024/1024).toFixed(2)} MB`)}let S=performance.now(),H=d.map(hn),g=[];for(let b of u)if(t&&b.meshes.length>1){let T=gn(b,f,e.indices,H);T.userData.sourceComponentId=_nullishCoalesce(m, () => (null)),g.push(T)}else{let T=bn(b,f,e.indices,H);for(let I of T)I.userData.sourceComponentId=_nullishCoalesce(m, () => (null));g.push(...T)}let y=performance.now()-S;if(o){let b=performance.now()-l;_chunk2QHLW6ZLcjs.e.call(void 0, ).debug("Performance:"),a>0&&_chunk2QHLW6ZLcjs.e.call(void 0, ).debug(` Parse JSON: ${a.toFixed(2)}ms`),_chunk2QHLW6ZLcjs.e.call(void 0, ).debug(` Decode binary: ${i.toFixed(2)}ms`),_chunk2QHLW6ZLcjs.e.call(void 0, ).debug(` Create Meshes: ${y.toFixed(2)}ms`),_chunk2QHLW6ZLcjs.e.call(void 0, ).debug(` Total: ${b.toFixed(2)}ms`)}return Promise.resolve(g)}function En(e,r,t,n){let o=new Float32Array(e.length),a=r[0],i=r[1],l=r[2],s=t[0],c=t[1],d=t[2];for(let u=0;u<e.length;u+=3)o[u]=a+(e[u]+32767)*s,o[u+1]=i+(e[u+1]+32767)*c,o[u+2]=l+(e[u+2]+32767)*d;return o}function fn(e,r){return e}function hn(e){let r=ce(e.color);return new F.MeshPhysicalMaterial({color:r,metalness:e.metalness,roughness:e.roughness,opacity:e.opacity,transparent:e.transparent,side:F.DoubleSide,polygonOffset:!0,polygonOffsetFactor:.5,polygonOffsetUnits:.5,depthWrite:!0,depthTest:!0})}function gn(e,r,t,n){let o=0,a=0;for(let f of e.meshes)o+=f.vertexCount,a+=f.indexCount;let i=new Float32Array(o*3),l=new Uint32Array(a),s=0,c=0;for(let f of e.meshes){let S=f.vertexStart*3,H=f.vertexCount*3;i.set(r.subarray(S,S+H),s*3);let g=t.subarray(f.indexStart,f.indexStart+f.indexCount),y=s-f.vertexStart;if(y===0)l.set(g,c);else for(let b=0;b<g.length;b++)l[c+b]=g[b]+y;s+=f.vertexCount,c+=f.indexCount}let d=new F.BufferGeometry;d.setAttribute("position",new F.BufferAttribute(i,3)),d.setIndex(new F.BufferAttribute(l,1)),d.computeVertexNormals();let u=new F.Mesh(d,n[e.materialId]),m=e.meshes[0],p=e.meshes.map(f=>f.name).filter(f=>f&&f.length>0);return u.name=p.length>0?p[0]:`merged_material_${e.materialId}`,u.castShadow=!0,u.receiveShadow=!0,u.userData={source:"compute",name:u.name,layer:_nullishCoalesce(_optionalChain([m, 'optionalAccess', _232 => _232.layer]), () => ("")),originalIndex:_nullishCoalesce(_optionalChain([m, 'optionalAccess', _233 => _233.originalIndex]), () => (0)),metadata:_nullishCoalesce(_optionalChain([m, 'optionalAccess', _234 => _234.metadata]), () => ({})),mergedFrom:e.meshes.slice(1).map(f=>({name:f.name,layer:f.layer,originalIndex:f.originalIndex}))},u}function bn(e,r,t,n){let o=[];for(let a of e.meshes){let i=a.vertexStart*3,l=a.vertexCount*3,s=r.slice(i,i+l),c=t.subarray(a.indexStart,a.indexStart+a.indexCount),d=new Uint32Array(c.length),u=a.vertexStart;for(let f=0;f<c.length;f++)d[f]=c[f]-u;let m=new F.BufferGeometry;m.setAttribute("position",new F.BufferAttribute(s,3)),m.setIndex(new F.BufferAttribute(d,1)),m.computeVertexNormals();let p=new F.Mesh(m,n[e.materialId]);p.name=a.name,p.userData={source:"compute",name:a.name,layer:_nullishCoalesce(a.layer, () => ("")),originalIndex:a.originalIndex,metadata:_nullishCoalesce(a.metadata, () => ({}))},p.castShadow=!0,p.receiveShadow=!0,o.push(p)}return o}function yn(e){return Math.floor(e.length*3/4)}var Rn={Millimeters:1/1e3,Centimeters:1/100,Meters:1,Inches:1/39.37,Feet:1/3.28084},Tn="Display";async function Ir(e,r){let t=performance.now(),n=[],{allowScaling:o=!0,allowAutoPosition:a=!0,rhino:i,debug:l=!1,parsing:s={}}=_nullishCoalesce(r, () => ({}));try{let c=o?wn(e.modelunits):1;return await Hn(e,n,c,s,i,l),a&&Cn(n),n}catch(c){throw Sn(c,n),c}finally{l&&Dn(t)}}function wn(e){return _nullishCoalesce(Rn[e], () => (1))}async function Hn(e,r,t,n,o,a){for(let i of e.values){let l=i.InnerTree;for(let s in l){let c=l[s];c&&await vn(c,r,t,n,o,a)}}}async function vn(e,r,t,n,o,a){for(let i of e){if(!i.type.includes(Tn))continue;let l={mergeByMaterial:!0,applyTransforms:!0,debug:!1,...n},s=await Ae(i.data,l),c=we(Mn(i.data),{rhino:o,applyTransforms:l.applyTransforms}),d=[...s,...c];if(t!==1)for(let u of d)u.scale.set(t,t,t);r.push(...d),a&&_chunk2QHLW6ZLcjs.e.call(void 0, ).debug(`Extracted ${s.length} meshes and ${c.length} items from batch`)}}function Mn(e){return_optionalChain([(typeof e=="string"?xn(e):e), 'optionalAccess', _235 => _235.items])}function xn(e){try{return JSON.parse(e)}catch (e4){return}}function Cn(e){if(e.length===0)return;let r=J(e);ue(e,r.min.z,"z")}function Sn(e,r){_chunk2QHLW6ZLcjs.e.call(void 0, ).error("An unexpected error occurred:",e),An(r)}function An(e){for(let r of e){let t=r;t.geometry&&t.geometry.dispose(),t.material&&(Array.isArray(t.material)?t.material.forEach(n=>n.dispose()):t.material.dispose())}}function Dn(e){let r=performance.now()-e;_chunk2QHLW6ZLcjs.e.call(void 0, ).info("Time to process meshes:",`${r.toFixed(2)}ms`)}exports.a = On; exports.b = ce; exports.c = ue; exports.d = J; exports.e = de; exports.f = me; exports.g = pe; exports.h = Q; exports.i = fe; exports.j = Ke; exports.k = Gn; exports.l = he; exports.m = be; exports.n = pt; exports.o = Re; exports.p = mr; exports.q = Ft; exports.r = we; exports.s = ve; exports.t = Me; exports.u = ie; exports.v = se; exports.w = Ae; exports.x = pn; exports.y = Sr; exports.z = Rn; exports.A = Ir;
55
+ //# sourceMappingURL=chunk-SA67IFJH.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/selva-compute/selva-compute/dist/chunk-SA67IFJH.cjs","../src/features/visualization/threejs/three-helpers.ts","../src/features/visualization/threejs/grid.ts","../src/features/visualization/threejs/view-gizmo.ts","../src/features/visualization/threejs/measure.ts"],"names":["CAMERA_CONFIG","updateScene","scene","meshes","camera","controls","initialPositionSet","clearScene","mesh","unionBoundingBox","computeCombinedBoundingBox","center","size","maxDim","distance","parseColor","colorString","getLogger","trimmed","hex"],"mappings":"AAAA,2/BAAwE,keCAjD,IAKjBA,CAAAA,CAAgB,CACrB,cAAA,CAAgB,GAAA,CAChB,eAAA,CAAiB,GAAA,CACjB,qBAAA,CAAuB,GAAA,CACvB,iBAAA,CAAmB,CAClB,IAAA,CAAM,IAAA,CACN,KAAA,CAAO,IAAA,CACP,MAAA,CAAQ,GACT,CAAA,CACA,gBAAA,CAAkB,CACjB,IAAA,CAAM,GAAA,CACN,KAAA,CAAO,EAAA,CACP,MAAA,CAAQ,EACT,CAAA,CACA,2BAAA,CAA6B,CAC9B,CAAA,CAWO,SAASC,EAAAA,CACfC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACC,CAGD,EAAA,CAFAC,EAAAA,CAAWL,CAAK,CAAA,CAEZC,CAAAA,CAAO,MAAA,GAAW,CAAA,CAAG,MAAA,CAGzBA,CAAAA,CAAO,OAAA,CAASK,CAAAA,EAAS,CACxBN,CAAAA,CAAM,GAAA,CAAIM,CAAI,CACf,CAAC,CAAA,CAGD,IAAMC,CAAAA,CAAmBC,CAAAA,CAA2BP,CAAM,CAAA,CAGpDQ,CAAAA,CAASF,CAAAA,CAAiB,SAAA,CAAU,IAAU,CAAA,CAAA,OAAS,CAAA,CACvDG,CAAAA,CAAOH,CAAAA,CAAiB,OAAA,CAAQ,IAAU,CAAA,CAAA,OAAS,CAAA,CAGnDI,CAAAA,CAAS,IAAA,CAAK,GAAA,CAAID,CAAAA,CAAK,CAAA,CAAGA,CAAAA,CAAK,CAAA,CAAGA,CAAAA,CAAK,CAAC,CAAA,CAuB9C,EAAA,CAnBmBC,CAAAA,CAAS,IAAA,CAAK,GAAA,CAAID,CAAAA,CAAK,CAAA,EAAK,CAAA,CAAGA,CAAAA,CAAK,CAAA,EAAK,CAAA,CAAGA,CAAAA,CAAK,CAAA,EAAK,CAAC,CAAA,CAEzDZ,CAAAA,CAAc,qBAAA,EAAyBa,CAAAA,CAASb,CAAAA,CAAc,cAAA,CAAA,CAE9EI,CAAAA,CAAO,IAAA,CAAOS,CAAAA,CAASb,CAAAA,CAAc,iBAAA,CAAkB,IAAA,CACvDI,CAAAA,CAAO,GAAA,CAAMS,CAAAA,CAASb,CAAAA,CAAc,gBAAA,CAAiB,IAAA,CAAA,CAC3Ca,CAAAA,CAASb,CAAAA,CAAc,eAAA,CAAA,CAEjCI,CAAAA,CAAO,IAAA,CAAOS,CAAAA,CAASb,CAAAA,CAAc,iBAAA,CAAkB,KAAA,CACvDI,CAAAA,CAAO,GAAA,CAAMS,CAAAA,CAASb,CAAAA,CAAc,gBAAA,CAAiB,KAAA,CAAA,CAAA,CAGrDI,CAAAA,CAAO,IAAA,CAAO,IAAA,CAAK,GAAA,CAAI,GAAA,CAAMS,CAAAA,CAASb,CAAAA,CAAc,iBAAA,CAAkB,MAAM,CAAA,CAC5EI,CAAAA,CAAO,GAAA,CAAM,IAAA,CAAK,GAAA,CAAI,GAAA,CAAMS,CAAAA,CAASb,CAAAA,CAAc,gBAAA,CAAiB,MAAM,CAAA,CAAA,CAG3EI,CAAAA,CAAO,sBAAA,CAAuB,CAAA,CAGzBE,CAAAA,CAWJD,CAAAA,CAAS,WAAA,CAAcD,CAAAA,CAAO,IAAA,CAAO,CAAA,CACrCC,CAAAA,CAAS,WAAA,CAAcD,CAAAA,CAAO,GAAA,CAAM,EAAA,CAAA,IAZZ,CACxB,IAAMU,CAAAA,CAAWD,CAAAA,CAASb,CAAAA,CAAc,2BAAA,CAExCI,CAAAA,CAAO,QAAA,CAAS,GAAA,CAAIO,CAAAA,CAAO,CAAA,CAAIG,CAAAA,CAAW,EAAA,CAAKH,CAAAA,CAAO,CAAA,CAAIG,CAAAA,CAAUH,CAAAA,CAAO,CAAA,CAAIG,CAAAA,CAAW,GAAG,CAAA,CAC7FT,CAAAA,CAAS,MAAA,CAAO,IAAA,CAAKM,CAAM,CAAA,CAC3BN,CAAAA,CAAS,WAAA,CAAcD,CAAAA,CAAO,IAAA,CAAO,CAAA,CACrCC,CAAAA,CAAS,WAAA,CAAcD,CAAAA,CAAO,GAAA,CAAM,EAAA,CAEpCC,CAAAA,CAAS,MAAA,CAAO,CACjB,CAKD,CAeO,SAASU,EAAAA,CAAWC,CAAAA,CAAkC,CAC5D,EAAA,CAAI,CAACA,CAAAA,EAAe,OAAOA,CAAAA,EAAgB,QAAA,CAC1C,OAAAC,iCAAAA,CAAU,CAAE,IAAA,CAAK,CAAA,qBAAA,EAAwBD,CAAW,CAAA,aAAA,CAAe,CAAA,CAC5D,IAAU,CAAA,CAAA,KAAA,CAAM,QAAQ,CAAA,CAGhC,IAAME,CAAAA,CAAUF,CAAAA,CAAY,IAAA,CAAK,CAAA,CAGjC,EAAA,CAAI,oBAAA,CAAqB,IAAA,CAAKE,CAAO,CAAA,CACpC,GAAI,CACH,IAAMC,CAAAA,CAAMD,CAAAA,CAAQ,UAAA,CAAW,GAAG,CAAA,CAAIA,CAAAA,CAAU,CAAA,CAAA,EAAIA,CAAO,CAAA,CAAA;AChF/B;AAAA;AAAA;AAAA;AAAA;AAAA;AASE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;ACe/B;AC8MwB,QAAA","file":"/home/runner/work/selva-compute/selva-compute/dist/chunk-SA67IFJH.cjs","sourcesContent":[null,"import * as THREE from 'three';\nimport { OrbitControls } from 'three/addons/controls/OrbitControls.js';\nimport { getLogger } from '@/core';\n\n// Camera configuration constants\nconst CAMERA_CONFIG = {\n\tHUGE_THRESHOLD: 10000,\n\tLARGE_THRESHOLD: 1000,\n\tSCALE_RATIO_THRESHOLD: 100,\n\tNEAR_PLANE_FACTOR: {\n\t\tTINY: 0.0001,\n\t\tSMALL: 0.001,\n\t\tNORMAL: 0.01\n\t},\n\tFAR_PLANE_FACTOR: {\n\t\tHUGE: 100,\n\t\tLARGE: 50,\n\t\tNORMAL: 20\n\t},\n\tINITIAL_DISTANCE_MULTIPLIER: 4\n};\n\n/**\n * Updates the scene with the given meshes and camera settings.\n * If initialPositionSet is false, it positions the camera and sets the controls target based on the bounding boxes of the meshes.\n * @param scene - The THREE.Scene object to update.\n * @param meshes - An array of THREE.Mesh objects to add to the scene.\n * @param camera - The THREE.PerspectiveCamera object to position.\n * @param controls - The OrbitControls object to update.\n * @param initialPositionSet - A boolean indicating whether the initial position of the camera and controls have been set.\n */\nexport function updateScene(\n\tscene: THREE.Scene,\n\tmeshes: THREE.Object3D[],\n\tcamera: THREE.PerspectiveCamera,\n\tcontrols: OrbitControls,\n\tinitialPositionSet: boolean\n) {\n\tclearScene(scene);\n\n\tif (meshes.length === 0) return;\n\n\t// Add new objects (meshes, lines, points) to scene\n\tmeshes.forEach((mesh) => {\n\t\tscene.add(mesh);\n\t});\n\n\t// Calculate bounds of the new content\n\tconst unionBoundingBox = computeCombinedBoundingBox(meshes);\n\n\t// Get the center of the union bounding box\n\tconst center = unionBoundingBox.getCenter(new THREE.Vector3());\n\tconst size = unionBoundingBox.getSize(new THREE.Vector3());\n\n\t// Calculate a distance that is slightly larger than the largest dimension of the union bounding box\n\tconst maxDim = Math.max(size.x, size.y, size.z);\n\n\t// Always update camera frustum to ensure geometry is visible\n\t// This prevents clipping when geometry size changes significantly\n\tconst scaleRatio = maxDim / Math.min(size.x || 1, size.y || 1, size.z || 1);\n\n\tif (scaleRatio > CAMERA_CONFIG.SCALE_RATIO_THRESHOLD || maxDim > CAMERA_CONFIG.HUGE_THRESHOLD) {\n\t\t// Large scale range detected - use logarithmic depth buffer approach\n\t\tcamera.near = maxDim * CAMERA_CONFIG.NEAR_PLANE_FACTOR.TINY;\n\t\tcamera.far = maxDim * CAMERA_CONFIG.FAR_PLANE_FACTOR.HUGE;\n\t} else if (maxDim > CAMERA_CONFIG.LARGE_THRESHOLD) {\n\t\t// Large scene\n\t\tcamera.near = maxDim * CAMERA_CONFIG.NEAR_PLANE_FACTOR.SMALL;\n\t\tcamera.far = maxDim * CAMERA_CONFIG.FAR_PLANE_FACTOR.LARGE;\n\t} else {\n\t\t// Normal scene\n\t\tcamera.near = Math.max(0.01, maxDim * CAMERA_CONFIG.NEAR_PLANE_FACTOR.NORMAL);\n\t\tcamera.far = Math.max(2000, maxDim * CAMERA_CONFIG.FAR_PLANE_FACTOR.NORMAL);\n\t}\n\n\tcamera.updateProjectionMatrix();\n\n\t// Only reposition camera and controls on first frame\n\tif (!initialPositionSet) {\n\t\tconst distance = maxDim * CAMERA_CONFIG.INITIAL_DISTANCE_MULTIPLIER;\n\n\t\tcamera.position.set(center.x + distance * 0.8, center.y + distance, center.z + distance * 1.2);\n\t\tcontrols.target.copy(center);\n\t\tcontrols.minDistance = camera.near * 2;\n\t\tcontrols.maxDistance = camera.far * 0.9;\n\n\t\tcontrols.update();\n\t} else {\n\t\t// Update control constraints to match new frustum\n\t\tcontrols.minDistance = camera.near * 2;\n\t\tcontrols.maxDistance = camera.far * 0.9;\n\t}\n}\n\n// =========================\n// Helper functions\n// =========================\n\n/**\n * Parses a color string in multiple formats to a THREE.Color object.\n * Supported formats:\n * - Hex: \"#C7A5A5\", \"C7A5A5\"\n * - RGB: \"199, 165, 165\"\n * - CSS named colors: \"red\", \"blue\", etc.\n * @param colorString - The color string to parse.\n * @returns A THREE.Color object.\n */\nexport function parseColor(colorString: string): THREE.Color {\n\tif (!colorString || typeof colorString !== 'string') {\n\t\tgetLogger().warn(`Invalid color input: ${colorString}, using white`);\n\t\treturn new THREE.Color(0xffffff);\n\t}\n\n\tconst trimmed = colorString.trim();\n\n\t// Try hex format (#C7A5A5 or C7A5A5) — require exactly 6 hex chars\n\tif (/^#?[0-9A-Fa-f]{6}$/.test(trimmed)) {\n\t\ttry {\n\t\t\tconst hex = trimmed.startsWith('#') ? trimmed : `#${trimmed}`;\n\t\t\treturn new THREE.Color(hex);\n\t\t} catch {\n\t\t\tgetLogger().warn(`Invalid hex color: ${colorString}, using white`);\n\t\t\treturn new THREE.Color(0xffffff);\n\t\t}\n\t}\n\n\t// Try RGB format (R, G, B)\n\tif (trimmed.includes(',')) {\n\t\tconst rgb = trimmed.split(',').map((c) => parseInt(c.trim(), 10));\n\t\tif (rgb.length === 3 && rgb.every((n) => !isNaN(n) && n >= 0 && n <= 255)) {\n\t\t\treturn new THREE.Color(rgb[0] / 255, rgb[1] / 255, rgb[2] / 255);\n\t\t}\n\t}\n\n\t// Try CSS named color\n\ttry {\n\t\treturn new THREE.Color(trimmed.toLowerCase());\n\t} catch {\n\t\tgetLogger().warn(`Invalid color string: ${colorString}, using white`);\n\t\treturn new THREE.Color(0xffffff);\n\t}\n}\n\n/**\n * Shift objects along one world axis. Defaults to `z` — the up axis of the unified Z-up scene\n * frame (see `../coordinate-transform.ts`), so grounding subtracts the content's lowest z.\n */\nexport function applyOffset(\n\tmeshes: THREE.Object3D[],\n\toffset: number,\n\taxis: 'x' | 'y' | 'z' = 'z'\n): void {\n\tmeshes.forEach((mesh) => {\n\t\tmesh.position[axis] -= offset;\n\t});\n}\n\n/**\n * Computes the combined world-axis-aligned bounding box of a set of objects (meshes, lines, points).\n * Correctly accounts for transformations (rotation, position, scale).\n */\nexport function computeCombinedBoundingBox(meshes: THREE.Object3D[]): THREE.Box3 {\n\tconst combinedBoundingBox = new THREE.Box3();\n\tif (meshes.length === 0) return combinedBoundingBox;\n\tmeshes.forEach((mesh) => {\n\t\t// Ensure the world matrix is up to date before calculating the box\n\t\tmesh.updateMatrixWorld(true);\n\t\tconst bbox = new THREE.Box3().setFromObject(mesh);\n\t\tcombinedBoundingBox.union(bbox);\n\t});\n\treturn combinedBoundingBox;\n}\n\n/**\n * `userData.id`s of scene infrastructure that is created once at init and must survive content\n * updates: the floor, the grid, and the CSS2D label layer's group. Compute content\n * (meshes/lines/points) carries no such id and is cleared on every solve.\n *\n * A second persistence mechanism exists alongside this one: objects tagged `userData.source ===\n * 'user'` (added via the viewer's `addUserGeometry`) also survive solves — see {@link clearScene}.\n * Use that for user-drawn geometry; this set is reserved for init-time viewer infrastructure.\n */\nconst PERSISTENT_SCENE_IDS = new Set(['floor', 'grid', 'label-layer']);\n\n/**\n * Clears the given THREE.Scene by removing all top-level content children (everything except\n * persistent infrastructure, see {@link PERSISTENT_SCENE_IDS}) and recursively disposing of their\n * geometry and materials.\n *\n * Removes at the top level rather than traversing for meshes, so parent Groups\n * don't accumulate as ghost nodes after their mesh children are disposed.\n */\nfunction clearScene(scene: THREE.Scene): void {\n\t// Snapshot children — we mutate the array via removeFromParent during iteration\n\tconst topLevel = [...scene.children];\n\n\ttopLevel.forEach((object) => {\n\t\t// Persistent scene infrastructure (floor, grid, the CSS2D label layer) outlives content\n\t\t// updates — it's added once at init, not per solve. Removing the label-layer group here\n\t\t// orphans it, so labels created afterwards never render (the CSS2D renderer walks the live\n\t\t// scene and never finds them).\n\t\tif (PERSISTENT_SCENE_IDS.has(object.userData.id)) return;\n\n\t\t// User-drawn geometry (added via the viewer's addUserGeometry, tagged source==='user')\n\t\t// persists across solves so it isn't lost when compute content is replaced.\n\t\tif (object.userData.source === 'user') return;\n\n\t\t// Recursively dispose all renderable objects (meshes, lines, points) in this subtree.\n\t\tobject.traverse((child) => {\n\t\t\tconst renderable = child as Partial<THREE.Mesh> & THREE.Object3D;\n\t\t\tif (!renderable.geometry && !renderable.material) return;\n\n\t\t\trenderable.geometry?.dispose();\n\n\t\t\tconst material = renderable.material;\n\t\t\tif (!material) return;\n\t\t\tconst materials = Array.isArray(material) ? material : [material];\n\t\t\tmaterials.forEach((material) => {\n\t\t\t\t// Walk only own enumerable properties — `for...in` on a Three.js material\n\t\t\t\t// also iterates the prototype chain, which is needlessly expensive.\n\t\t\t\tfor (const value of Object.values(material)) {\n\t\t\t\t\tif (value instanceof THREE.Texture) {\n\t\t\t\t\t\tvalue.dispose();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tmaterial.dispose();\n\t\t\t});\n\t\t});\n\n\t\tobject.removeFromParent();\n\t});\n}\n","import * as THREE from 'three';\n\n/**\n * An \"infinite\", distance-fading reference grid — the single strongest visual cue that reads as CAD.\n *\n * Why not `GridHelper`: it's a fixed-size square of line segments that visibly ends and looks wrong\n * once you pan or zoom past it. Instead we draw one large screen-facing plane and compute the grid\n * in the fragment shader from world coordinates, fading lines out with distance so the edge is never\n * a hard cutoff. The plane is big enough to cover any reasonable view; the fade hides its bounds.\n *\n * Two line frequencies (minor + major every 10th) give the usual graph-paper depth read. Spacing is\n * in world units (meters — the scene's normalized unit), so a `cellSize` of 1 = 1m minor cells.\n */\n\nexport interface GridOptions {\n\t/** Minor cell size in world units (meters). Default 1. */\n\tcellSize?: number;\n\t/** How many minor cells per major line. Default 10. */\n\tmajorEvery?: number;\n\t/** Minor line color. */\n\tcellColor?: THREE.ColorRepresentation;\n\t/** Major line color. */\n\tmajorColor?: THREE.ColorRepresentation;\n\t/** World-space radius at which the grid has fully faded out. Default 100. */\n\tfadeDistance?: number;\n\t/** Plane to lay the grid on. 'y' = horizontal ground (Three Y-up). Default 'y'. */\n\tplane?: 'x' | 'y' | 'z';\n}\n\nexport interface Grid {\n\t/** The grid mesh; add to the scene. Tagged `userData.id = 'grid'` so pick/fit code skips it. */\n\treadonly object: THREE.Mesh;\n\t/** Keep the fade centered on the camera so the grid feels infinite as you move. Call per frame. */\n\tupdate(cameraPosition: THREE.Vector3): void;\n\tsetVisible(visible: boolean): void;\n\tdispose(): void;\n}\n\nconst GRID_VERTEX = /* glsl */ `\n\tvarying vec3 vWorldPos;\n\tvoid main() {\n\t\tvec4 world = modelMatrix * vec4(position, 1.0);\n\t\tvWorldPos = world.xyz;\n\t\tgl_Position = projectionMatrix * viewMatrix * world;\n\t}\n`;\n\nconst GRID_FRAGMENT = /* glsl */ `\n\tprecision highp float;\n\tvarying vec3 vWorldPos;\n\n\tuniform vec2 uAxes; // indices (0=x,1=y,2=z) of the two in-plane world axes\n\tuniform float uCell;\n\tuniform float uMajor;\n\tuniform vec3 uCellColor;\n\tuniform vec3 uMajorColor;\n\tuniform vec3 uCenter; // fade center (camera position), projected onto plane\n\tuniform float uFade;\n\n\t// Antialiased grid line intensity for a given spacing, using screen-space derivatives so lines\n\t// stay ~1px regardless of zoom (the standard \"pristine grid\" technique).\n\tfloat gridLine(vec2 coord, float spacing) {\n\t\tvec2 c = coord / spacing;\n\t\tvec2 d = fwidth(c);\n\t\tvec2 g = abs(fract(c - 0.5) - 0.5) / max(d, 1e-6);\n\t\tfloat line = min(g.x, g.y);\n\t\treturn 1.0 - clamp(line, 0.0, 1.0);\n\t}\n\n\t// Index a vec3 by a float axis id (0/1/2) without dynamic indexing (WebGL1-safe).\n\tfloat axis(vec3 v, float i) {\n\t\treturn i < 0.5 ? v.x : (i < 1.5 ? v.y : v.z);\n\t}\n\n\tvoid main() {\n\t\t// Pick the two in-plane world coordinates.\n\t\tvec2 coord = vec2(axis(vWorldPos, uAxes.x), axis(vWorldPos, uAxes.y));\n\n\t\tfloat minor = gridLine(coord, uCell);\n\t\tfloat major = gridLine(coord, uCell * uMajor);\n\n\t\tvec3 color = mix(uCellColor, uMajorColor, major);\n\t\tfloat alpha = max(minor, major);\n\n\t\t// Radial fade from the camera-projected center.\n\t\tfloat dist = distance(vWorldPos, uCenter);\n\t\tfloat fade = 1.0 - clamp(dist / uFade, 0.0, 1.0);\n\t\talpha *= fade * fade;\n\n\t\tif (alpha < 0.001) discard;\n\t\tgl_FragColor = vec4(color, alpha);\n\t}\n`;\n\nexport function createGrid(options: GridOptions = {}): Grid {\n\tconst {\n\t\tcellSize = 1,\n\t\tmajorEvery = 10,\n\t\tcellColor = 0x888888,\n\t\tmajorColor = 0x444444,\n\t\tfadeDistance = 100,\n\t\tplane = 'y'\n\t} = options;\n\n\t// The two in-plane world axes (0=x,1=y,2=z): ground 'y' grids over x,z; 'z' over x,y; 'x' over y,z.\n\tconst axes =\n\t\tplane === 'y'\n\t\t\t? new THREE.Vector2(0, 2) // x, z\n\t\t\t: plane === 'z'\n\t\t\t\t? new THREE.Vector2(0, 1) // x, y\n\t\t\t\t: new THREE.Vector2(1, 2); // y, z\n\n\tconst size = fadeDistance * 2.5; // comfortably larger than the fade radius\n\tconst geometry = new THREE.PlaneGeometry(size, size);\n\n\t// PlaneGeometry is in the XY plane by default; rotate it onto the requested world plane.\n\tif (plane === 'y') geometry.rotateX(-Math.PI / 2);\n\telse if (plane === 'x') geometry.rotateY(Math.PI / 2);\n\n\tconst material = new THREE.ShaderMaterial({\n\t\tvertexShader: GRID_VERTEX,\n\t\tfragmentShader: GRID_FRAGMENT,\n\t\ttransparent: true,\n\t\tdepthWrite: false,\n\t\tside: THREE.DoubleSide,\n\t\tuniforms: {\n\t\t\tuAxes: { value: axes },\n\t\t\tuCell: { value: cellSize },\n\t\t\tuMajor: { value: majorEvery },\n\t\t\tuCellColor: { value: new THREE.Color(cellColor) },\n\t\t\tuMajorColor: { value: new THREE.Color(majorColor) },\n\t\t\tuCenter: { value: new THREE.Vector3() },\n\t\t\tuFade: { value: fadeDistance }\n\t\t}\n\t});\n\n\tconst mesh = new THREE.Mesh(geometry, material);\n\tmesh.name = 'grid';\n\tmesh.userData.id = 'grid'; // excluded from raycasting/fit-to-view, like the floor\n\tmesh.renderOrder = -1; // draw before content so transparent geometry blends over it\n\n\tconst center = new THREE.Vector3();\n\n\treturn {\n\t\tobject: mesh,\n\t\tupdate: (cameraPosition) => {\n\t\t\t// Re-center the plane and the fade on the camera so the grid tracks the view \"infinitely\".\n\t\t\t// Keep the plane's own axis fixed (don't lift the ground grid up to the camera height).\n\t\t\tif (plane === 'y') {\n\t\t\t\tmesh.position.set(cameraPosition.x, 0, cameraPosition.z);\n\t\t\t\tcenter.set(cameraPosition.x, 0, cameraPosition.z);\n\t\t\t} else if (plane === 'z') {\n\t\t\t\tmesh.position.set(cameraPosition.x, cameraPosition.y, 0);\n\t\t\t\tcenter.set(cameraPosition.x, cameraPosition.y, 0);\n\t\t\t} else {\n\t\t\t\tmesh.position.set(0, cameraPosition.y, cameraPosition.z);\n\t\t\t\tcenter.set(0, cameraPosition.y, cameraPosition.z);\n\t\t\t}\n\t\t\tmaterial.uniforms.uCenter.value.copy(center);\n\t\t},\n\t\tsetVisible: (visible) => {\n\t\t\tmesh.visible = visible;\n\t\t},\n\t\tdispose: () => {\n\t\t\tgeometry.dispose();\n\t\t\tmaterial.dispose();\n\t\t}\n\t};\n}\n","import * as THREE from 'three';\nimport { ViewHelper } from 'three/addons/helpers/ViewHelper.js';\n\nimport type { CameraController } from './camera-controller';\n\n/**\n * The corner nav-cube/axis gizmo. Uses three's {@link ViewHelper} purely as the rendered widget, but\n * NOT its click→animate behavior: ViewHelper's built-in snap assumes a Y-up world and animates the\n * camera straight onto the up axis, which in our Z-up scene rolls the view and makes the gizmo jitter\n * at the pole. Instead we hit-test the axis sprites ourselves and drive the viewer's up-aware camera\n * controller, which snaps (no animation) with a pole nudge so the orbit basis never degenerates.\n *\n * Integration points with the viewer's dual-camera setup:\n * 1. The snap frames the current orbit target via the controller, so it rotates about what the user\n * is looking at (not the world origin).\n * 2. The nav cube is inherently a 3D-orientation tool, so if the viewer is in orthographic (2D) mode\n * when the gizmo is clicked, we first flip back to perspective.\n *\n * Caller responsibilities (mirror ViewHelper's own contract):\n * - call {@link ViewGizmo.render} *after* the main scene render each frame (overlay viewport),\n * - call {@link ViewGizmo.update} each frame (no-op now; kept for API symmetry),\n * - forward pointer clicks to {@link ViewGizmo.handleClick}.\n */\nexport interface ViewGizmo {\n\trender(renderer: THREE.WebGLRenderer): void;\n\tupdate(delta: number): void;\n\t/** Hit-test a click. Returns true if it hit the gizmo (and a view change started). */\n\thandleClick(event: MouseEvent): boolean;\n\treadonly isAnimating: boolean;\n\t/** Show/hide the gizmo at runtime. Hidden = not rendered and not click-hittable. */\n\tsetVisible(visible: boolean): void;\n\tisVisible(): boolean;\n\tdispose(): void;\n}\n\ninterface ViewGizmoDeps {\n\t/** The perspective (primary) camera the gizmo visualizes and re-orients. */\n\tcamera: THREE.PerspectiveCamera;\n\tdomElement: HTMLElement;\n\tcontroller: CameraController;\n}\n\nexport function createViewGizmo(deps: ViewGizmoDeps): ViewGizmo {\n\tconst { camera, domElement, controller } = deps;\n\n\tconst helper = new ViewHelper(camera, domElement);\n\thelper.setLabels('X', 'Y', 'Z');\n\n\tlet visible = true;\n\n\t// Our own hit-test against the helper's axis sprites, mirroring ViewHelper's internal viewport math\n\t// (a `dim`×`dim` square in the corner given by `location`). We do this instead of ViewHelper's own\n\t// `handleClick` so the camera move goes through the viewer's up-aware controller — ViewHelper's\n\t// built-in snap assumes a Y-up world and animates straight onto the pole, which rolls the view and\n\t// makes the gizmo jitter in our Z-up scene.\n\tconst DIM = 128;\n\tconst raycaster = new THREE.Raycaster();\n\tconst gizmoCamera = new THREE.OrthographicCamera(-2, 2, 2, -2, 0, 4);\n\tgizmoCamera.position.set(0, 0, 2);\n\n\t// Map a clicked axis sprite to the world-space view direction (from target toward camera).\n\tconst AXIS_DIRECTIONS: Record<string, THREE.Vector3> = {\n\t\tposX: new THREE.Vector3(1, 0, 0),\n\t\tnegX: new THREE.Vector3(-1, 0, 0),\n\t\tposY: new THREE.Vector3(0, 1, 0),\n\t\tnegY: new THREE.Vector3(0, -1, 0),\n\t\tposZ: new THREE.Vector3(0, 0, 1),\n\t\tnegZ: new THREE.Vector3(0, 0, -1)\n\t};\n\n\t/** Which axis sprite (if any) a click landed on. Returns its `userData.type` or null. */\n\tconst pickAxis = (event: MouseEvent): string | null => {\n\t\tconst rect = domElement.getBoundingClientRect();\n\t\t// The gizmo viewport sits in the bottom-right corner (helper.location defaults: right/bottom 0).\n\t\tconst offsetX = rect.left + domElement.offsetWidth - DIM - helper.location.right;\n\t\tconst offsetY = rect.top + domElement.offsetHeight - DIM - helper.location.bottom;\n\n\t\tconst mouse = new THREE.Vector2(\n\t\t\t((event.clientX - offsetX) / DIM) * 2 - 1,\n\t\t\t-((event.clientY - offsetY) / DIM) * 2 + 1\n\t\t);\n\t\t// Outside the gizmo square — not our click.\n\t\tif (Math.abs(mouse.x) > 1 || Math.abs(mouse.y) > 1) return null;\n\n\t\t// Orient the helper as it's rendered (inverse of the camera), so the sprites are where the user\n\t\t// sees them, then raycast the interactive axis sprites.\n\t\thelper.quaternion.copy(camera.quaternion).invert();\n\t\thelper.updateMatrixWorld();\n\n\t\traycaster.setFromCamera(mouse, gizmoCamera);\n\t\tconst hits = raycaster.intersectObjects(helper.children, false);\n\t\tfor (const hit of hits) {\n\t\t\tconst type = hit.object.userData?.type;\n\t\t\tif (typeof type === 'string' && type in AXIS_DIRECTIONS) return type;\n\t\t}\n\t\treturn null;\n\t};\n\n\tconst handleClick = (event: MouseEvent): boolean => {\n\t\tif (!visible) return false;\n\n\t\tconst axis = pickAxis(event);\n\t\tif (!axis) return false;\n\n\t\t// The cube orients in 3D, so a click while in 2D returns us to perspective first.\n\t\tif (controller.getProjection() === 'orthographic') {\n\t\t\tcontroller.setProjection('perspective');\n\t\t}\n\n\t\t// Snap directly via the up-aware controller — no animation, no Y-up pole roll.\n\t\tcontroller.setViewDirection(AXIS_DIRECTIONS[axis]!, false);\n\t\treturn true;\n\t};\n\n\treturn {\n\t\trender: (renderer) => {\n\t\t\tif (!visible) return;\n\t\t\t// ViewHelper.render() calls renderer.render(this, orthoCamera), which with the default\n\t\t\t// autoClear=true clears the FULL framebuffer (to the scene's grey clear color) before drawing\n\t\t\t// the cube in its corner viewport — wiping the just-rendered scene. It only needs the depth\n\t\t\t// clear it does internally (clearDepth). So suppress the automatic color/depth clear here.\n\t\t\tconst prevAutoClear = renderer.autoClear;\n\t\t\trenderer.autoClear = false;\n\t\t\thelper.render(renderer);\n\t\t\trenderer.autoClear = prevAutoClear;\n\t\t},\n\t\t// ViewHelper.update() unconditionally rewrites camera.position from (center, radius, q1) — at\n\t\t// rest (radius 0, center origin) that pins the camera to the origin every frame, blanking the\n\t\t// view. It's only meant to run while a click-snap is animating, so guard on `animating`.\n\t\tupdate: (delta) => {\n\t\t\tif (helper.animating) helper.update(delta);\n\t\t},\n\t\thandleClick,\n\t\tget isAnimating() {\n\t\t\treturn helper.animating;\n\t\t},\n\t\tsetVisible: (value) => {\n\t\t\tvisible = value;\n\t\t},\n\t\tisVisible: () => visible,\n\t\tdispose: () => helper.dispose()\n\t};\n}\n","import * as THREE from 'three';\nimport { Line2 } from 'three/addons/lines/Line2.js';\nimport { LineGeometry } from 'three/addons/lines/LineGeometry.js';\nimport { LineMaterial } from 'three/addons/lines/LineMaterial.js';\n\nimport type { LabelLayer, LabelHandle } from './label-layer';\n\n/**\n * A two-click distance measurement tool — the CAD verb users expect. Click a point, click a second,\n * read the distance off a label on the connecting line; a third click starts a new measurement.\n *\n * Picking snaps to geometry so measurements are exact, not \"wherever the ray happened to land\":\n * on a mesh hit we snap to the nearest vertex of the struck triangle if it's within\n * {@link MeasureOptions.snapPixels} on screen, else use the raw hit point. This is a cheap local\n * snap (three candidate vertices), no spatial index — enough for clean vertex-to-vertex measurement\n * without the cost/complexity of full edge/midpoint snapping (a later refinement).\n *\n * The tool is dormant until {@link MeasureTool.setEnabled}(true). While enabled it intercepts clicks\n * (the caller forwards them and swallows the event when {@link MeasureTool.handleClick} returns\n * true) so measuring doesn't also select objects.\n */\n\nexport interface MeasureTool {\n\tsetEnabled(enabled: boolean): void;\n\tisEnabled(): boolean;\n\t/** Process a click. Returns true if the tool consumed it (caller should not also select). */\n\thandleClick(event: MouseEvent): boolean;\n\t/**\n\t * Process pointer movement to preview the next snap point — a ghost marker tracks the cursor and\n\t * jumps to the vertex a click would snap to, so users can aim before committing. No-op when the\n\t * tool is disabled. The caller forwards mousemove; nothing is consumed.\n\t */\n\thandleMove(event: MouseEvent): void;\n\t/** Clear the current measurement (markers, line, label). */\n\tclear(): void;\n\tdispose(): void;\n}\n\nexport interface MeasureOptions {\n\t/** Snap to a vertex when the cursor is within this many screen pixels of it. Default 12. */\n\tsnapPixels?: number;\n\t/** Marker + line color. Default yellow. */\n\tcolor?: THREE.ColorRepresentation;\n\t/** CSS class applied to the distance label, for styling. */\n\tlabelClassName?: string;\n\t/**\n\t * The model's unit (pass `data.modelunits`). The scene is in meters, so the default formatter\n\t * converts and labels in this unit — e.g. a mm model reads \"25.0 mm\", not \"0.025 m\". Defaults\n\t * to meters. Ignored when a custom `format` is supplied.\n\t */\n\tdisplayUnit?: string;\n\t/**\n\t * Format the measurement → label text. Receives the straight-line `distance` and the per-axis\n\t * `delta` (|b − a| on each axis), both in **meters**. May return multi-line text or HTML; the\n\t * default renders the total plus a Δx/Δy/Δz breakdown in `displayUnit`. Overrides `displayUnit`.\n\t */\n\tformat?: (distance: number, delta: THREE.Vector3) => string;\n}\n\ninterface MeasureDeps {\n\tcanvas: HTMLCanvasElement;\n\tscene: THREE.Scene;\n\tgetActiveCamera: () => THREE.Camera;\n\tlabelLayer: LabelLayer;\n\toptions?: MeasureOptions;\n}\n\nconst DEFAULT_SNAP_PIXELS = 12;\nconst DEFAULT_COLOR = 0xffcc00;\n// Line/Points raycast threshold as a fraction of the view distance (camera→target). ~1.5% gives a\n// comfortable few-pixel grab band at typical framing without snapping to far-off geometry.\nconst LINE_PICK_FRACTION = 0.015;\n\n/**\n * Scene geometry is loaded in meters (the webdisplay parser scales to meters when\n * `allowScaling` is on), so distances come out in meters. To label in the model's\n * own unit, convert with `metersPerUnit` and append `suffix`. Keep this in sync\n * with the webdisplay parser's SCALE_FACTORS.\n */\nconst UNIT_DISPLAY: Record<string, { metersPerUnit: number; suffix: string }> = {\n\tMillimeters: { metersPerUnit: 1 / 1000, suffix: 'mm' },\n\tCentimeters: { metersPerUnit: 1 / 100, suffix: 'cm' },\n\tMeters: { metersPerUnit: 1, suffix: 'm' },\n\tInches: { metersPerUnit: 1 / 39.37, suffix: 'in' },\n\tFeet: { metersPerUnit: 1 / 3.28084, suffix: 'ft' }\n};\n\n/**\n * Build a `meters → label` formatter for the given display unit (defaults to meters).\n * @internal exported for tests\n */\nexport function makeFormatter(displayUnit?: string): (n: number) => string {\n\tconst unit = (displayUnit && UNIT_DISPLAY[displayUnit]) || UNIT_DISPLAY.Meters;\n\treturn (meters: number) => `${(meters / unit.metersPerUnit).toPrecision(3)} ${unit.suffix}`;\n}\n\n/**\n * The vertex indices to consider snapping to for a given hit, by object type:\n * - Mesh: the three vertices of the struck triangle (`hit.face`).\n * - Line / LineSegments: the two endpoints of the struck segment (`hit.index`, `hit.index + 1`).\n * - Points: the struck vertex (`hit.index`).\n * Returns null when the hit carries no usable index info (e.g. a fat `Line2`), so the caller keeps\n * the raw hit point.\n */\nfunction snapCandidateIndices(hit: THREE.Intersection): number[] | null {\n\tconst obj = hit.object;\n\tif (obj instanceof THREE.Mesh) {\n\t\treturn hit.face ? [hit.face.a, hit.face.b, hit.face.c] : null;\n\t}\n\tif (obj instanceof THREE.Points) {\n\t\treturn hit.index != null ? [hit.index] : null;\n\t}\n\t// THREE.Line / LineSegments / LineLoop. `hit.index` is the first vertex of the struck segment.\n\tif (obj instanceof THREE.Line) {\n\t\treturn hit.index != null ? [hit.index, hit.index + 1] : null;\n\t}\n\treturn null;\n}\n\n/**\n * Snap a raycast hit to the nearest geometry vertex within `snapPixels` on screen; otherwise return\n * the raw hit point. Works for meshes (triangle vertices), lines (segment endpoints), and points\n * (the vertex itself). Pure (no DOM) so it's unit-testable: it takes the screen size explicitly\n * rather than reading the canvas. Exported for that reason.\n *\n * Falls back to the raw point for hits without usable vertex indices or positions.\n */\nexport function snapToVertex(\n\thit: THREE.Intersection,\n\tcamera: THREE.Camera,\n\tscreenSize: { width: number; height: number },\n\tsnapPixels: number\n): THREE.Vector3 {\n\tconst raw = hit.point.clone();\n\tconst obj = hit.object as THREE.Object3D & { geometry?: THREE.BufferGeometry };\n\tconst indices = snapCandidateIndices(hit);\n\tif (!indices || !obj.geometry) return raw;\n\n\tconst pos = obj.geometry.attributes.position as THREE.BufferAttribute | undefined;\n\tif (!pos) return raw;\n\n\tconst toScreen = (worldP: THREE.Vector3): THREE.Vector2 => {\n\t\tconst ndc = worldP.clone().project(camera);\n\t\treturn new THREE.Vector2(\n\t\t\t((ndc.x + 1) / 2) * screenSize.width,\n\t\t\t((1 - ndc.y) / 2) * screenSize.height\n\t\t);\n\t};\n\tconst rawScreen = toScreen(raw);\n\n\tlet best = raw;\n\tlet bestPx = snapPixels;\n\tfor (const idx of indices) {\n\t\tif (idx >= pos.count) continue; // guard the line `index + 1` against the geometry end\n\t\tconst local = new THREE.Vector3().fromBufferAttribute(pos, idx);\n\t\tconst world = local.applyMatrix4(obj.matrixWorld);\n\t\tconst px = toScreen(world).distanceTo(rawScreen);\n\t\tif (px < bestPx) {\n\t\t\tbestPx = px;\n\t\t\tbest = world;\n\t\t}\n\t}\n\treturn best;\n}\n\nexport function createMeasureTool(deps: MeasureDeps): MeasureTool {\n\tconst { canvas, scene, getActiveCamera, labelLayer, options = {} } = deps;\n\tconst snapPixels = options.snapPixels ?? DEFAULT_SNAP_PIXELS;\n\tconst color = new THREE.Color(options.color ?? DEFAULT_COLOR);\n\tconst fmt = makeFormatter(options.displayUnit);\n\tconst defaultFormat = (d: number, delta: THREE.Vector3) =>\n\t\t`${fmt(d)}\\nΔx ${fmt(delta.x)} Δy ${fmt(delta.y)} Δz ${fmt(delta.z)}`;\n\tconst format = options.format ?? defaultFormat;\n\n\tconst raycaster = new THREE.Raycaster();\n\tconst pointer = new THREE.Vector2();\n\n\tlet enabled = false;\n\tconst points: THREE.Vector3[] = [];\n\n\t// Visuals, created lazily and reused. Markers are small always-on-top points; the line connects\n\t// them; the label rides the line's midpoint.\n\tconst markers: THREE.Points[] = [];\n\tlet line: Line2 | null = null;\n\tlet label: LabelHandle | null = null;\n\n\tconst markerMaterial = new THREE.PointsMaterial({\n\t\tcolor,\n\t\tsize: 8,\n\t\tsizeAttenuation: false,\n\t\tdepthTest: false // markers stay visible through geometry, like CAD snap dots\n\t});\n\n\t// A hollow-feeling preview dot: dimmer + bigger than a committed marker so the snap target the\n\t// next click will lock onto is obvious before clicking. Shown only while hovering geometry.\n\tconst hoverMaterial = new THREE.PointsMaterial({\n\t\tcolor,\n\t\tsize: 11,\n\t\tsizeAttenuation: false,\n\t\tdepthTest: false,\n\t\ttransparent: true,\n\t\topacity: 0.5\n\t});\n\tlet hoverMarker: THREE.Points | null = null;\n\n\tconst showHover = (p: THREE.Vector3 | null) => {\n\t\tif (!p) {\n\t\t\tif (hoverMarker) hoverMarker.visible = false;\n\t\t\treturn;\n\t\t}\n\t\tif (!hoverMarker) {\n\t\t\tconst geometry = new THREE.BufferGeometry();\n\t\t\tgeometry.setAttribute('position', new THREE.Float32BufferAttribute([0, 0, 0], 3));\n\t\t\thoverMarker = new THREE.Points(geometry, hoverMaterial);\n\t\t\thoverMarker.renderOrder = 1000;\n\t\t\thoverMarker.userData.id = 'measure';\n\t\t\thoverMarker.raycast = () => {};\n\t\t\tscene.add(hoverMarker);\n\t\t}\n\t\thoverMarker.position.copy(p);\n\t\thoverMarker.visible = true;\n\t};\n\n\tconst makeMarker = (p: THREE.Vector3): THREE.Points => {\n\t\tconst geometry = new THREE.BufferGeometry();\n\t\tgeometry.setAttribute('position', new THREE.Float32BufferAttribute([p.x, p.y, p.z], 3));\n\t\tconst marker = new THREE.Points(geometry, markerMaterial);\n\t\tmarker.renderOrder = 999;\n\t\tmarker.userData.id = 'measure'; // excluded from pick/fit\n\t\tmarker.raycast = () => {}; // don't let markers be measure targets themselves\n\t\tscene.add(marker);\n\t\treturn marker;\n\t};\n\n\tconst clear = () => {\n\t\tpoints.length = 0;\n\t\tmarkers.forEach((m) => {\n\t\t\tm.geometry.dispose();\n\t\t\tm.removeFromParent();\n\t\t});\n\t\tmarkers.length = 0;\n\t\tif (line) {\n\t\t\tline.geometry.dispose();\n\t\t\t(line.material as LineMaterial).dispose();\n\t\t\tline.removeFromParent();\n\t\t\tline = null;\n\t\t}\n\t\tlabel?.remove();\n\t\tlabel = null;\n\t};\n\n\tconst drawMeasurement = () => {\n\t\tif (points.length !== 2) return;\n\t\tconst [a, b] = points;\n\n\t\tconst geometry = new LineGeometry();\n\t\tgeometry.setPositions([a.x, a.y, a.z, b.x, b.y, b.z]);\n\t\tconst material = new LineMaterial({ color });\n\t\t(material as LineMaterial & { linewidth: number; depthTest: boolean }).linewidth = 2;\n\t\tmaterial.depthTest = false;\n\n\t\tline = new Line2(geometry, material);\n\t\tline.renderOrder = 998;\n\t\tline.userData.id = 'measure';\n\t\tline.raycast = () => {};\n\t\tscene.add(line);\n\n\t\tconst mid = a.clone().add(b).multiplyScalar(0.5);\n\t\tconst delta = new THREE.Vector3(Math.abs(b.x - a.x), Math.abs(b.y - a.y), Math.abs(b.z - a.z));\n\t\tlabel = labelLayer.addLabel(format(a.distanceTo(b), delta), mid, options.labelClassName);\n\t};\n\n\t/** Raycast the cursor and return the snapped pick point, or null if it hit no measurable geometry. */\n\tconst pickPoint = (event: MouseEvent): THREE.Vector3 | null => {\n\t\tconst rect = canvas.getBoundingClientRect();\n\t\tpointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;\n\t\tpointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;\n\n\t\tconst camera = getActiveCamera();\n\t\traycaster.setFromCamera(pointer, camera);\n\n\t\t// Lines and points have no surface area, so they're only \"hit\" when the ray passes within a\n\t\t// world-space threshold of them — left at the default ~1 unit they're nearly impossible to\n\t\t// click. Scale the threshold with the view size (camera distance to the orbit target, here the\n\t\t// origin) so the pick tolerance stays roughly constant on screen as the user zooms.\n\t\tconst viewScale = camera.position.length();\n\t\tconst threshold = viewScale * LINE_PICK_FRACTION;\n\t\traycaster.params.Line!.threshold = threshold;\n\t\traycaster.params.Points!.threshold = threshold;\n\n\t\tconst hits = raycaster\n\t\t\t.intersectObjects(scene.children, true)\n\t\t\t.filter((i) => i.object.userData.id !== 'measure' && i.object.userData.id !== 'grid');\n\n\t\tif (hits.length === 0) return null;\n\t\treturn snapToVertex(hits[0], camera, { width: rect.width, height: rect.height }, snapPixels);\n\t};\n\n\tconst handleMove = (event: MouseEvent): void => {\n\t\tif (!enabled) return;\n\t\tshowHover(pickPoint(event));\n\t};\n\n\tconst handleClick = (event: MouseEvent): boolean => {\n\t\tif (!enabled) return false;\n\n\t\t// A third click after a completed measurement starts fresh.\n\t\tif (points.length === 2) clear();\n\n\t\tconst point = pickPoint(event);\n\t\tif (point === null) return true; // consumed: a measuring click that missed still isn't a select\n\n\t\tpoints.push(point);\n\t\tmarkers.push(makeMarker(point));\n\n\t\tif (points.length === 2) drawMeasurement();\n\t\treturn true;\n\t};\n\n\treturn {\n\t\tsetEnabled: (value) => {\n\t\t\tenabled = value;\n\t\t\tif (!value) {\n\t\t\t\tclear();\n\t\t\t\tshowHover(null);\n\t\t\t}\n\t\t},\n\t\tisEnabled: () => enabled,\n\t\thandleClick,\n\t\thandleMove,\n\t\tclear,\n\t\tdispose: () => {\n\t\t\tclear();\n\t\t\tif (hoverMarker) {\n\t\t\t\thoverMarker.geometry.dispose();\n\t\t\t\thoverMarker.removeFromParent();\n\t\t\t\thoverMarker = null;\n\t\t\t}\n\t\t\tmarkerMaterial.dispose();\n\t\t\thoverMaterial.dispose();\n\t\t}\n\t};\n}\n"]}
@@ -0,0 +1,2 @@
1
+ import{b as l,c as h,d as f,e as d,h as A,i as K,j as z,k as $,l as _,n as q,p as N}from"./chunk-2KAHGLXE.js";function p(t,e){if(!t||typeof t!="object")return;let r=t;if(e in r)return r[e];let n=e.toLowerCase();for(let s of Object.keys(r))if(s.toLowerCase()===n)return r[s]}function L(t,e){if(!t||typeof t!="object")return!1;let r=t;if(e in r)return!0;let n=e.toLowerCase();return Object.keys(r).some(s=>s.toLowerCase()===n)}function C(t,e){e||typeof window<"u"&&d().warn(`Warning: ${t} is running on the client side. For better performance and security, consider running this on the server side.`)}var Ce="Unable to load grasshopper definition";function Se(t){return t instanceof f?t.code===h.DEFINITION_NOT_CACHED||t.message.includes(Ce):!1}function H(t,e){if(!e)return;let r=p(t,"values");if(!Array.isArray(r)||r.length===0)return;let n=[];for(let o of r){let a=p(o,"innerTree");(!a||Object.keys(a).length===0)&&n.push(p(o,"paramName")??"<unnamed>")}if(n.length===0)return;let s=n.length===r.length?"all":`${n.length}/${r.length}`;d().warn(`Solve returned empty output(s) (${s}): ${n.join(", ")}. These parameters produced no data \u2014 check the definition's inputs and the branch feeding each.`)}async function D(t,e,r){r.debug&&C("solveGrasshopperDefinition",r.suppressBrowserWarning??r.suppressClientSideWarning);let{response:n}=await O(P(e,t),r);return n}async function J(t,e,r){return r.debug&&C("solveGrasshopperDefinitionWithCacheKey",r.suppressBrowserWarning??r.suppressClientSideWarning),O(P(e,t),r)}async function Y(t,e,r,n){n.debug&&C("solveByCacheKey",n.suppressBrowserWarning??n.suppressClientSideWarning);let s={algo:null,pointer:e,values:t};try{return{...await O(s,n),missed:!1}}catch(o){if(!Se(o))throw o;return{...await O(P(r,t),n),missed:!0}}}async function O(t,e){Ie(t,e);let r=await A("grasshopper",t,e);if("pointer"in r){let{pointer:n,...s}=r,o=s;return H(o,e.debug),{response:o,cacheKey:typeof n=="string"?n:null}}return H(r,e.debug),{response:r,cacheKey:null}}function P(t,e){let r={algo:null,pointer:null,values:e};return t instanceof Uint8Array?r.algo=q(t):/^https?:\/\//i.test(t)?r.pointer=t:_(t)?r.algo=t:r.algo=$(t),r}function Ie(t,e){e.cachesolve!=null&&(t.cachesolve=e.cachesolve),e.cacheerroredsolves!=null&&(t.cacheerroredsolves=e.cacheerroredsolves),e.modelunits!=null&&(t.modelunits=e.modelunits),e.angletolerance!=null&&(t.angletolerance=e.angletolerance),e.absolutetolerance!=null&&(t.absolutetolerance=e.absolutetolerance),e.dataversion!=null&&(t.dataversion=e.dataversion)}function xe(t){let e=new WeakSet,r=n=>{if(n==null)return JSON.stringify(n);if(typeof n=="number")return Number.isFinite(n)?String(n):JSON.stringify(null);if(typeof n=="string"||typeof n=="boolean")return JSON.stringify(n);if(typeof n=="bigint")return JSON.stringify(n.toString());if(n instanceof Uint8Array){let s=n.length>64?Array.from(n.slice(0,32)).concat(Array.from(n.slice(-32))):Array.from(n);return JSON.stringify({__u8:!0,len:n.length,sample:s})}return Array.isArray(n)?`[${n.map(r).join(",")}]`:typeof n=="object"?e.has(n)?JSON.stringify("[Circular]"):(e.add(n),`{${Object.keys(n).sort().map(a=>`${JSON.stringify(a)}:${r(n[a])}`).join(",")}}`):JSON.stringify(null)};return r(t)}function Q(t,e){let r=2166136261;for(let n=0;n<t;n++)r^=e(n),r=r+((r<<1)+(r<<4)+(r<<7)+(r<<8)+(r<<24))>>>0;return r.toString(16).padStart(8,"0")}function X(t){return Q(t.length,e=>t.charCodeAt(e))}function De(t){return Q(t.length,e=>t[e])}function Z(t,e){return X(`${W(t)}|${xe(e)}`)}function W(t){return typeof t=="string"?`s:${t.length}:${X(t)}`:`u8:${t.length}:${De(t)}`}var Pe=100;function Re(t){return t instanceof Uint8Array?!0:!/^https?:\/\//i.test(t)}var S=class{constructor(e,r,n={},s){l(this,"executor");l(this,"baseConfig");l(this,"mode");l(this,"maxConcurrent");l(this,"timeoutMs");l(this,"retry");l(this,"cacheEnabled");l(this,"cacheMax");l(this,"cacheTtl");l(this,"cache",new Map);l(this,"cacheKeyExecutor");l(this,"reuseServerDefinitionCache");l(this,"serverCacheKeys",new Map);l(this,"onStart");l(this,"onSettle");l(this,"onSuperseded");l(this,"subscribers",new Set);l(this,"inFlight",new Set);l(this,"pendingForLatestWins",null);l(this,"fifoQueue",[]);l(this,"_lastResult",null);l(this,"_lastError",null);l(this,"_lastDurationMs",null);l(this,"disposed",!1);this.executor=e,this.cacheKeyExecutor=s,this.baseConfig=r,this.mode=n.mode??"latest-wins",this.maxConcurrent=Math.max(1,n.maxConcurrent??(this.mode==="parallel"?4:1)),this.timeoutMs=n.timeoutMs,this.retry=n.retry;let o=n.cache;this.cacheEnabled=o!==void 0&&o!==!1;let a=typeof o=="object"?o:{};this.cacheMax=a.maxEntries??50,this.cacheTtl=a.ttlMs??0,this.reuseServerDefinitionCache=!!s&&(n.reuseServerDefinitionCache??!0),this.onStart=n.onStart,this.onSettle=n.onSettle,this.onSuperseded=n.onSuperseded}get isSolving(){return this.inFlight.size>0}get hasPending(){return this.pendingForLatestWins!==null||this.fifoQueue.length>0}get inFlightCount(){return this.inFlight.size}get queueDepth(){return this.fifoQueue.length+(this.pendingForLatestWins?1:0)}get lastResult(){return this._lastResult}get lastError(){return this._lastError}get lastDurationMs(){return this._lastDurationMs}subscribe(e){return this.subscribers.add(e),()=>this.subscribers.delete(e)}notify(){for(let e of this.subscribers)try{e()}catch(r){d().error("[SolveScheduler] subscriber threw:",r)}}solve(e,r,n){if(this.disposed)return Promise.reject(new f("SolveScheduler has been disposed and cannot be used",h.INVALID_STATE));let s=Z(e,r),o={key:s,enqueuedAt:Date.now(),startedAt:null};if(this.cacheEnabled){let a=this.readCache(s);if(a){let i={status:"success",response:a,durationMs:0,fromCache:!0};return this._lastResult=a,this._lastError=null,this._lastDurationMs=0,this.runHook(this.onStart,o),this.runHook(this.onSettle,o,i),this.notify(),Promise.resolve(a)}}return new Promise((a,i)=>{let u={definition:e,dataTree:r,ctx:o,resolve:a,reject:i,externalSignal:n?.signal};if(u.externalSignal?.aborted){this.settleError(u,this.makeAbortError(o));return}this.enqueue(u)})}enqueue(e){switch(this.mode){case"latest-wins":{this.pendingForLatestWins&&(this.supersede(this.pendingForLatestWins),this.pendingForLatestWins=null);for(let r of this.inFlight)this.supersede(r),r.controller.abort();this.inFlight.size===0?this.execute(e):this.pendingForLatestWins=e;break}case"queue":case"parallel":{this.inFlight.size<this.maxConcurrent?this.execute(e):this.fifoQueue.push(e);break}}this.notify()}async execute(e){let r=new AbortController,n=e;n.controller=r,this.inFlight.add(n),e.ctx.startedAt=Date.now();let s=()=>r.abort();e.externalSignal?.addEventListener("abort",s,{once:!0}),this.runHook(this.onStart,e.ctx),this.notify();let o=performance.now();try{let a={...this.baseConfig,signal:r.signal,...this.timeoutMs!==void 0&&{timeoutMs:this.timeoutMs},...this.retry!==void 0&&{retry:this.retry}},{response:i,definitionReuploaded:u}=await this.runExecutor(e.definition,e.dataTree,a),c=performance.now()-o;if(this.cacheEnabled&&this.writeCache(e.ctx.key,i),!this.settleSuccess(e,i))return;this._lastResult=i,this._lastError=null,this._lastDurationMs=c,this.runHook(this.onSettle,e.ctx,{status:"success",response:i,durationMs:c,fromCache:!1,definitionReuploaded:u})}catch(a){let i=performance.now()-o,u=this.normalizeExecutionError(a,n);this._lastError=u,this._lastDurationMs=i,this.settleError(e,u)&&this.runHook(this.onSettle,e.ctx,{status:"error",error:u,durationMs:i})}finally{e.externalSignal?.removeEventListener("abort",s),this.inFlight.delete(n),this.drainNext(),this.notify()}}async runExecutor(e,r,n){if(!this.cacheKeyExecutor||!this.reuseServerDefinitionCache||!Re(e))return{response:await this.executor(e,r,n)};let s=W(e),o=this.serverCacheKeys.get(s)??null,a=await this.cacheKeyExecutor(e,r,o,n);if(a.cacheKey)for(this.serverCacheKeys.delete(s),this.serverCacheKeys.set(s,a.cacheKey);this.serverCacheKeys.size>Pe;){let i=this.serverCacheKeys.keys().next().value;if(i===void 0)break;this.serverCacheKeys.delete(i)}else this.serverCacheKeys.delete(s);return{response:a.response,definitionReuploaded:a.missed}}drainNext(){if(!this.disposed){if(this.mode==="latest-wins"){if(this.pendingForLatestWins&&this.inFlight.size===0){let e=this.pendingForLatestWins;this.pendingForLatestWins=null,this.execute(e)}return}for(;this.fifoQueue.length>0&&this.inFlight.size<this.maxConcurrent;){let e=this.fifoQueue.shift();this.execute(e)}}}supersede(e){let r=new f("Superseded by newer solve",h.SUPERSEDED,{context:{key:e.ctx.key,enqueuedAt:e.ctx.enqueuedAt}});this.settleError(e,r)&&this.runHook(this.onSuperseded,e.ctx)}makeAbortError(e){return new f("Request aborted by caller",h.ABORTED,{context:{key:e.key,enqueuedAt:e.enqueuedAt}})}settleError(e,r){return e.settled?!1:(e.settled={error:r},e.reject(r),!0)}settleSuccess(e,r){return e.settled?!1:(e.settled={ok:!0},e.resolve(r),!0)}isAbortLikeError(e){if(e instanceof Error){if(e.name==="AbortError")return!0;if(typeof DOMException<"u"&&e instanceof DOMException)return e.name==="AbortError"}return!1}normalizeExecutionError(e,r){return r.settled&&"error"in r.settled?r.settled.error:e instanceof f?e:this.isAbortLikeError(e)?this.makeAbortError(r.ctx):new f(e instanceof Error?e.message:String(e),h.UNKNOWN_ERROR,{originalError:e instanceof Error?e:new Error(String(e))})}cancelAll(){for(this.pendingForLatestWins&&(this.rejectAsAborted(this.pendingForLatestWins),this.pendingForLatestWins=null);this.fifoQueue.length>0;){let e=this.fifoQueue.shift();this.rejectAsAborted(e)}for(let e of this.inFlight){let r=this.makeAbortError(e.ctx);this.settleError(e,r)&&this.runHook(this.onSettle,e.ctx,{status:"error",error:r,durationMs:e.ctx.startedAt?performance.now()-e.ctx.startedAt:0}),e.controller.abort()}this.notify()}rejectAsAborted(e){this.settleError(e,this.makeAbortError(e.ctx))}readCache(e){if(!this.cacheEnabled)return null;let r=this.cache.get(e);return r?this.cacheTtl>0&&Date.now()-r.insertedAt>this.cacheTtl?(this.cache.delete(e),null):(this.cache.delete(e),this.cache.set(e,r),r.response):null}writeCache(e,r){if(this.cacheEnabled)for(this.cache.set(e,{response:r,insertedAt:Date.now()});this.cache.size>this.cacheMax;){let n=this.cache.keys().next().value;if(n===void 0)break;this.cache.delete(n)}}clearCache(){this.cache.clear()}dispose(){this.disposed||(this.disposed=!0,this.cancelAll(),this.subscribers.clear(),this.cache.clear())}runHook(e,...r){if(e)try{e(...r)}catch(n){d().error("[SolveScheduler] hook threw:",n)}}};var R=class t{constructor(e){l(this,"config");l(this,"serverStats");l(this,"disposed",!1);this.config=this.normalizeComputeConfig(e),this.serverStats=new z(this.config.serverUrl,this.config.apiKey)}static async create(e){let r=new t(e),n=Math.max(1,(e.retry?.attempts??2)+1),s=e.retry?.baseDelayMs??250,o=e.retry?.maxDelayMs??1e3;for(let a=0;a<n;a++){if(await r.serverStats.isServerOnline())return r;if(a<n-1){let i=Math.min(s*2**a,o);await new Promise(u=>setTimeout(u,i))}}throw await r.dispose(),new f("Rhino Compute server is not online",h.NETWORK_ERROR,{context:{serverUrl:r.config.serverUrl,attempts:n}})}getConfig(){return this.ensureNotDisposed(),{...this.config}}async getIO(e){return this.ensureNotDisposed(),F(e,this.config)}async getRawIO(e){return this.ensureNotDisposed(),E(e,this.config)}async solve(e,r,n){this.ensureNotDisposed();try{if(typeof e=="string"&&!e?.trim())throw new f("Definition URL/content is required",h.INVALID_INPUT,{context:{receivedUrl:e}});if(e instanceof Uint8Array&&e.length===0)throw new f("Definition content is empty",h.INVALID_INPUT);let s={...this.config,...n?.signal!==void 0&&{signal:n.signal},...n?.timeoutMs!==void 0&&{timeoutMs:n.timeoutMs},...n?.retry!==void 0&&{retry:n.retry}},o=await D(r,e,s);if(o?.errors&&o.errors.length>0)throw new f(o.errors.join("; ")||"Computation failed",h.COMPUTATION_ERROR,{context:{definition:typeof e=="string"&&e.length<200?e:"...content...",inputs:r,errors:o.errors,warnings:o.warnings}});return o}catch(s){throw this.config.debug&&d().error("Compute failed:",s),s instanceof f?s:new f(s instanceof Error?s.message:String(s),h.COMPUTATION_ERROR,{context:{definition:typeof e=="string"&&e.length<200?e:"...content...",inputs:r},originalError:s instanceof Error?s:new Error(String(s))})}}createScheduler(e){this.ensureNotDisposed();let r=(s,o,a)=>D(o,s,a),n=(s,o,a,i)=>a===null?J(o,s,i).then(u=>({...u,missed:!1})):Y(o,a,s,i);return new S(r,this.config,e,n)}async dispose(){this.disposed||(this.disposed=!0,await this.serverStats.dispose())}ensureNotDisposed(){if(this.disposed)throw new f("GrasshopperClient has been disposed and cannot be used",h.INVALID_STATE)}normalizeComputeConfig(e){return{...e,serverUrl:K(e.serverUrl),apiKey:e.apiKey,authToken:e.authToken,debug:e.debug??!1,suppressBrowserWarning:e.suppressBrowserWarning??e.suppressClientSideWarning}}};var G=new Map;function ee(t,e){G.set(t,e)}ee("Rhino.Geometry.Point3d",(t,e)=>{let r=e;return!r||typeof r.X!="number"?null:new t.Point([r.X,r.Y,r.Z])});ee("Rhino.Geometry.Line",(t,e)=>{let r=e;return!r||!r.From||!r.To?null:new t.Line([r.From.X,r.From.Y,r.From.Z],[r.To.X,r.To.Y,r.To.Z])});function Ee(t){if(G.has(t))return G.get(t);for(let[e,r]of G)if(t.startsWith(e))return r}function we(t){return!t||typeof t!="object"?null:t.data??t.value??null}function te(t,e,r){let n=Ee(e);if(n)try{return n(r,t)}catch(s){d().warn(`Failed to decode Rhino type ${e}:`,s)}try{let s=we(t);if(s)return r.CommonObject.decode(s)}catch(s){return d().warn(`Failed to decode ${e} with CommonObject:`,s),{__decodeError:!0,type:e,raw:t}}return t}var I={STRING:"System.String",INT:"System.Int32",DOUBLE:"System.Double",BOOL:"System.Boolean"},ve="Rhino.Geometry.",Ae=["WebDisplay"],Ne="FileData";function re(t){return Ae.some(e=>t.includes(e))}function ne(t){if(typeof t!="string")return t;let e=t.trim();if(!(e.startsWith("{")||e.startsWith("[")||e.startsWith('"')))return t;try{let n=JSON.parse(e);if(typeof n=="string")try{return JSON.parse(n)}catch{return n}return n}catch{return t}}function Oe(t,e,r){switch(e){case I.STRING:return typeof t!="string"?t:t.replace(/^"(.*)"$/,"$1");case I.INT:return Number.parseInt(t,10);case I.DOUBLE:return Number.parseFloat(t);case I.BOOL:return String(t).toLowerCase()==="true";default:return r&&e.startsWith(ve)?te(t,e,r):t}}function se(t,e,r,n){if(typeof t!="string")return t;let s=r?ne(t):t;return Oe(s,e,n)}function Fe(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.fileName=="string"&&typeof e.fileType=="string"&&"data"in e&&typeof e.isBase64Encoded=="boolean"&&typeof e.subFolder=="string"}function k(t,e){for(let r of Object.values(t))if(Array.isArray(r))for(let n of r)e(n)}function oe(t,e=!1,r={}){let{parseValues:n=!0,rhino:s,stringOnly:o=!1}=r,a={},i=new Set;for(let u of t.values)k(u.InnerTree,c=>{if(re(c.type)||o&&c.type!==I.STRING)return;let m=e?c.id:u.ParamName;if(!m)return;let y=se(c.data,c.type,n,s);m in a?i.has(m)?a[m].push(y):(a[m]=[a[m],y],i.add(m)):a[m]=y});return{values:a}}function ae(t){let e=[];for(let r of t.values)k(r.InnerTree,n=>{if(!n.type.includes(Ne))return;let s=ne(n.data);Fe(s)&&e.push(s)});return e}function ie(t,e,r={}){let{parseValues:n=!0,rhino:s,stringOnly:o=!1}=r,a;if("byName"in e?a=t.values.find(u=>u.ParamName===e.byName):a=t.values.find(u=>{let c=!1;return k(u.InnerTree,m=>{m.id===e.byId&&(c=!0)}),c}),!a)return;let i=[];if(k(a.InnerTree,u=>{if("byId"in e&&u.id!==e.byId||re(u.type)||o&&u.type!==I.STRING)return;let c=se(u.data,u.type,n,s);i.push(c)}),i.length!==0)return i.length===1?i[0]:i}var w=class{constructor(e,r=!1){this.response=e;this.debug=r}getValues(e=!1,r={}){return oe(this.response,e,r)}getValue(e,r){return ie(this.response,e,r)}async extractMeshesFromResponse(e){let r={debug:this.debug,...e},n;try{({getThreeMeshesFromComputeResponse:n}=await import("./visualization-N3OJSZOY.js"))}catch(s){throw new f("Failed to load three.js visualization module. Ensure three.js is installed as a peer dependency.",h.INVALID_STATE,{context:{originalError:s instanceof Error?s.message:String(s)}})}return n(this.response,r)}getFileData(){return ae(this.response)}async getAndDownloadFiles(e,r){let n=this.getFileData();await N(n,e,r)}};function ue(t){return p(t,"data")}function Ge(t){return p(t,"type")}function pe(t){if(typeof t.default!="object"||t.default===null)return{schema:t};if(!L(t.default,"innerTree")){let n=`Input "${t.name??"unknown"}" default had an unrecognized shape (no innerTree key); the default was dropped.`;return d().warn("Unexpected structure in input.default:",t.default),{schema:{...t,default:null},warning:{code:"MALFORMED_DEFAULT",message:n}}}let e=p(t.default,"innerTree")??{};if(Object.keys(e).length===0)return{schema:{...t,default:void 0}};if(t.treeAccess||t.atMost&&t.atMost>1){let n={};for(let[s,o]of Object.entries(e))n[s]=o.map(a=>{let i=ue(a),u=Ge(a);if(typeof i=="string"){if(u==="System.Double"||u==="System.Int32"){let c=Number(i);return Number.isNaN(c)?i:c}if(u==="System.Boolean")return i.toLowerCase()==="true";if(u?.startsWith("Rhino.Geometry"))try{return JSON.parse(i)}catch{return i}}return i});return{schema:{...t,default:n}}}let r=[];for(let n of Object.values(e))Array.isArray(n)&&n.forEach(s=>{s&&typeof s=="object"&&L(s,"data")&&r.push(ue(s))});return r.length===0?{schema:{...t,default:void 0}}:r.length===1?{schema:{...t,default:r[0]}}:{schema:{...t,default:r}}}var B=/^\{(\d+(?:;\d+)*)?\}$/;function v(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=Object.entries(t);return e.length>0&&e.every(([r,n])=>B.test(r)&&Array.isArray(n))}function x(t,e,r){if(t==null)return t;if(Array.isArray(t)){let s=t.map(e).filter(o=>o!==null);return s.length>0?s:void 0}let n=e(t);return n!==null?n:r?void 0:t}var ke=t=>{if(typeof t=="number")return t;if(typeof t=="string"){let e=t.trim();if(e==="")return null;let r=Number(e);return Number.isNaN(r)?null:r}return null},Ve=t=>{if(typeof t=="boolean")return t;if(typeof t=="string"){let e=t.toLowerCase();if(e==="true")return!0;if(e==="false")return!1;throw new Error(`Invalid boolean string: "${t}"`)}return null},Me=t=>typeof t=="string"?t.length>=2&&t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t.startsWith('"')?t.slice(1):t:null,Le=t=>{if(typeof t=="string"){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')&&(e=e.slice(1,-1).trim()),e}return null};function ce(t){return e=>{if(typeof e=="object"&&e!==null)return e;if(typeof e=="string"&&e.trim()!=="")try{let r=JSON.parse(e);return typeof r=="object"&&r!==null?r:(d().warn(`Parsed value for input ${t} is not an object`),null)}catch(r){return d().warn(`Failed to parse object value "${e}" for input ${t}`,r),null}return null}}function le(t,e,r){let n=Number(t.toFixed(e));return Math.abs(t-n)<r?n:t}function We(t,e){if(!Number.isFinite(t)||t===0)return .1;let r=Math.abs(t);if(r>=1){let g=String(t).split(".")[1];if(g&&g.length>0){let b=Math.min(g.length,12),T=Math.pow(10,-b),U=Number(T.toFixed(b));return Math.abs(U-T)<e?U:T}return 1}let n=String(t),s=n.toLowerCase().match(/e(-?\d+)/);if(s){let y=Number(s[1]);if(y<0||n.toLowerCase().includes("e-")){let g=Math.abs(y),b=Math.pow(10,-g),T=Number(b.toFixed(g));return Math.abs(T-b)<e?T:b}return .1}let o=12,i=r.toFixed(o).replace(/0+$/,""),u=Math.min((i.split(".")[1]||"").length,o);if(u===0)return .1;let c=Math.pow(10,-u),m=Number(c.toFixed(u));return Math.abs(m-c)<e?m:c}function Be(t,e=1e-8){let r=t.paramType==="Integer";if(v(t.default))return{default:t.default,stepSize:r?1:.1};let n=x(t.default,ke,!0);if(r)return Array.isArray(n)?n=n.map(m=>typeof m=="number"?Math.round(m):m):typeof n=="number"&&(n=Math.round(n)),{default:n,stepSize:1};let s=Array.isArray(n)?n[0]:n,o;typeof s=="number"&&Number.isFinite(s)&&s!==0?o=s:typeof t.minimum=="number"&&Number.isFinite(t.minimum)&&t.minimum!==0?o=t.minimum:typeof t.maximum=="number"&&Number.isFinite(t.maximum)&&t.maximum!==0&&(o=t.maximum);let a=o!==void 0?We(o,e):.1,i=0,u=String(a),c=u.toLowerCase().match(/e(-?\d+)/);if(c?i=Math.abs(Number(c[1])):i=u.split(".")[1]?.length??0,i===0&&typeof s=="number"&&s!==0&&Math.abs(s)<1){let m=Math.ceil(-Math.log10(Math.abs(s)));Number.isFinite(m)&&m>0&&(i=m)}return i=Math.min(Math.max(i,0),12),Array.isArray(n)?n=n.map(m=>typeof m=="number"?le(m,i,e):m):typeof n=="number"&&(n=le(n,i,e)),{default:n,stepSize:a}}var je={types:["Number","Integer"],parse(t,e){let{default:r,stepSize:n}=Be(t);return{...e,paramType:t.paramType,minimum:t.minimum,maximum:t.maximum,atLeast:t.atLeast,atMost:t.atMost,stepSize:n,default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:t.paramType,minimum:t.minimum,maximum:t.maximum,atLeast:t.atLeast,atMost:t.atMost,default:r?[0]:0}}},Ue={types:["Boolean"],parse(t,e){let r;try{r=x(t.default,Ve,!1)}catch(n){throw n instanceof Error?new f(n.message):n}return{...e,paramType:"Boolean",default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"Boolean",default:r?[!1]:!1}}},Ke={types:["Text"],parse(t,e){let r=x(t.default,Me,!1);return{...e,paramType:"Text",default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"Text",default:r?[""]:""}}},ze={types:["ValueList"],parse(t,e){if(!t.values||typeof t.values!="object"||Object.keys(t.values).length===0)throw f.missingValues(t.nickname||"unnamed","ValueList");if(t.default!==void 0&&t.default!==null){let r=String(t.default).toLowerCase();Object.keys(t.values).some(s=>s.toLowerCase()===r)||d().warn(`ValueList input "${t.nickname||"unnamed"}" default value "${t.default}" is not in available values`)}return{...e,paramType:"ValueList",values:t.values,default:t.default}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"ValueList",values:t.values??{},default:r?[t.default]:t.default}}},fe={types:["Geometry"],parse(t,e){let r=x(t.default,ce(t.nickname||"unnamed"),!0);return{...e,paramType:"Geometry",default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"Geometry",default:r?[null]:null}}},$e={types:["File"],parse(t,e){let r=x(t.default,ce(t.nickname||"unnamed"),!0);return{...e,paramType:"File",acceptedFormats:t.acceptedFormats,default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"File",default:r?[null]:null}}},_e={types:["Color"],parse(t,e){let r=x(t.default,Le,!1);return{...e,paramType:"Color",default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"Color",default:r?["0, 0, 0"]:"0, 0, 0"}}},qe=[je,Ue,Ke,ze,fe,$e,_e],j=new Map(qe.flatMap(t=>t.types.map(e=>[e,t]))),me=fe;var He=new Map([...j.keys()].map(t=>[t.toLowerCase(),t]));function Je(t){return He.get(t?.toLowerCase())??t}function de(t){return he(t).input}function he(t){let e={description:t.description,name:t.name,nickname:t.nickname,treeAccess:t.treeAccess,groupName:t.groupName??"",id:t.id},r=Je(t.paramType),{schema:n,warning:s}=pe({...t,paramType:r}),o=s&&{inputName:t.name||"unknown",paramType:r,message:s.message,code:s.code},a=j.get(r);try{if(!a)throw f.unknownParamType(r,t.name);return{input:a.parse(n,e),error:o}}catch(i){if(i instanceof f)return d().error(`Validation error for input ${t.name||"unknown"}:`,i.message),{input:(a??me).fallback(n,e),error:{inputName:t.name||"unknown",paramType:r,message:i.message,code:i.code}};throw new f(i instanceof Error?i.message:String(i),"VALIDATION_ERROR",{context:{paramName:t.name,paramType:r},originalError:i instanceof Error?i:new Error(String(i))})}}function ye(t){return V(t).inputs}function V(t){let e=[],r=[];for(let n of t){let{input:s,error:o}=he(n);e.push(s),o&&r.push(o)}return{inputs:e,parseErrors:r}}function ge(t){return{id:p(t,"id"),name:p(t,"name"),nickname:p(t,"nickname")??null,description:p(t,"description"),paramType:p(t,"paramType"),treeAccess:p(t,"treeAccess"),minimum:p(t,"minimum")??null,maximum:p(t,"maximum")??null,atLeast:p(t,"atLeast"),atMost:p(t,"atMost"),stepSize:p(t,"stepSize"),default:p(t,"default"),values:p(t,"values"),acceptedFormats:p(t,"acceptedFormats"),groupName:p(t,"groupName")??""}}function be(t){return{name:p(t,"name"),nickname:p(t,"nickname")??null,paramType:p(t,"paramType"),id:p(t,"id")}}async function E(t,e){let r=P(t,[]),n={};if(r.algo&&(n.algo=r.algo),r.pointer&&(n.pointer=r.pointer),!n.algo&&!n.pointer)throw new f("Definition must resolve to either a URL pointer or base64 algo",h.INVALID_INPUT,{context:{definition:t}});let s=await A("io",n,e);if(!s||typeof s!="object")throw new f("Invalid IO response structure",h.INVALID_INPUT,{context:{response:s,definition:t}});let o=Te(p(s,"warnings")),a=Te(p(s,"errors")),i=p(s,"inputs"),u=p(s,"outputs");return{inputs:Array.isArray(i)?i.map(ge):[],outputs:Array.isArray(u)?u.map(be):[],...o&&{loadWarnings:o},...a&&{loadErrors:a}}}function Te(t){if(!Array.isArray(t))return;let e=t.filter(r=>typeof r=="string"&&r.trim().length>0);return e.length>0?e:void 0}async function F(t,e){C("fetchParsedDefinitionIO",e.suppressBrowserWarning??e.suppressClientSideWarning);let{inputs:r,outputs:n,loadWarnings:s,loadErrors:o}=await E(t,e),{inputs:a,parseErrors:i}=V(r);return{inputs:a,outputs:n,...i.length>0&&{parseErrors:i},...s&&{loadWarnings:s},...o&&{loadErrors:o}}}var M=class t{constructor(e){l(this,"innerTree");l(this,"paramName");this.paramName=e,this.innerTree={}}append(e,r){let n=t.formatPathString(e);this.innerTree[n]||(this.innerTree[n]=[]);let s=r.map(o=>({data:t.serializeValue(o)}));return this.innerTree[n].push(...s),this}appendSingle(e,r){return this.append(e,[r])}fromDataTreeDefault(e){this.innerTree={};for(let[r,n]of Object.entries(e)){if(!Array.isArray(n))continue;let s=t.parsePathString(r);this.append(s,n)}return this}appendFlat(e){let r=Array.isArray(e)?e:[e];return this.append([0],r)}flatten(){let e=[];for(let r of Object.values(this.innerTree))if(Array.isArray(r))for(let n of r)e.push(t.deserializeValue(n.data));return e}getPaths(){return Object.keys(this.innerTree)}getPath(e){let r=t.formatPathString(e),n=this.innerTree[r];if(n)return n.map(s=>t.deserializeValue(s.data))}toComputeFormat(){return{ParamName:this.paramName,InnerTree:this.innerTree}}getInnerTree(){return this.innerTree}getParamName(){return this.paramName}static fromInputParams(e){return e.filter(r=>t.hasValidValue(r.default)).map(r=>{let n=new t(r.nickname||"unnamed"),s=r.default;if(r.treeAccess&&v(s))n.fromDataTreeDefault(s),t.isNumericInput(r)&&n.applyNumericConstraints(r.minimum,r.maximum,r.nickname||"unnamed");else{let o=Array.isArray(s)?s:[s],a=t.processValues(o,r);n.appendFlat(a)}return n.toComputeFormat()})}static fromInputParam(e){return t.hasValidValue(e.default)?t.fromInputParams([e])[0]:void 0}static replaceTreeValue(e,r,n){let s=e.length>0&&e[0]instanceof t,o=t.buildFromValue(r,n);if(s){let c=e,m=c.findIndex(y=>y.getParamName()===r);return m!==-1?c[m]=o:c.push(o),c}let a=e,i=o.toComputeFormat(),u=a.findIndex(c=>c.ParamName===r);return u!==-1?a[u]=i:a.push(i),a}static buildFromValue(e,r){let n=new t(e);return v(r)?n.fromDataTreeDefault(r):n.appendFlat(r),n}static getTreeValue(e,r){let s=e.length>0&&e[0]instanceof t?t.readFromBuilders(e,r):t.readFromDataTrees(e,r);return s===null||s.length===0?null:s.length===1?s[0]:s}static readFromBuilders(e,r){let n=e.find(s=>s.getParamName()===r);return n?n.flatten():null}static readFromDataTrees(e,r){let n=e.find(a=>a.ParamName===r);if(!n?.InnerTree)return null;let s=Object.keys(n.InnerTree)[0];if(!s)return null;let o=n.InnerTree[s];return Array.isArray(o)?o.map(a=>a?.data!==void 0?t.deserializeValue(a.data):null).filter(a=>a!==null):o?.data!==void 0?[t.deserializeValue(o.data)]:o!==void 0?[o]:null}static parsePathString(e){let r=e.match(B);return r?r[1]?r[1].split(";").map(Number):[]:(d().warn(`Invalid TreeBuilder path format: ${e}, using [0]`),[0])}static formatPathString(e){return`{${e.join(";")}}`}applyNumericConstraints(e,r,n){for(let s of Object.values(this.innerTree))if(Array.isArray(s))for(let o of s){let a=t.deserializeValue(o.data);if(typeof a=="number"){let i=t.clampValue(a,e,r,n);o.data=t.serializeValue(i)}}}static serializeValue(e){return typeof e=="boolean"||typeof e=="number"||typeof e=="string"?e:typeof e=="object"&&e!==null?JSON.stringify(e):String(e)}static deserializeValue(e){if(typeof e=="boolean"||typeof e=="number"||typeof e!="string")return e;if(e.startsWith("{")||e.startsWith("["))try{return JSON.parse(e)}catch{return e}return e.trim()!==""&&!isNaN(Number(e))?Number(e):e==="true"?!0:e==="false"?!1:e}static hasValidValue(e){return e==null?!1:typeof e=="string"?!0:!(Array.isArray(e)&&e.length===0||typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0)}static isNumericInput(e){return e.paramType==="Number"||e.paramType==="Integer"}static processValues(e,r){return e.map(n=>t.isNumericInput(r)&&typeof n=="number"?t.clampValue(n,r.minimum,r.maximum,r.nickname||"unnamed"):n).filter(n=>n!=null)}static clampValue(e,r,n,s){let o=e;return r!=null&&o<r&&(d().warn(`${s}: ${e} below min ${r}, clamping`),o=r),n!=null&&o>n&&(d().warn(`${s}: ${e} above max ${n}, clamping`),o=n),o}};export{D as a,S as b,R as c,w as d,de as e,ye as f,E as g,F as h,M as i};
2
+ //# sourceMappingURL=chunk-WHB32TTR.js.map