@selvajs/compute 3.1.0-beta.4 → 3.1.0-beta.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-54O6BO24.js +4 -0
- package/dist/chunk-54O6BO24.js.map +1 -0
- package/dist/chunk-7KFBCOZM.cjs +2 -0
- package/dist/chunk-7KFBCOZM.cjs.map +1 -0
- package/dist/chunk-EZRBMUXT.cjs +62 -0
- package/dist/chunk-EZRBMUXT.cjs.map +1 -0
- package/dist/chunk-GF6ZIJWX.cjs +4 -0
- package/dist/chunk-GF6ZIJWX.cjs.map +1 -0
- package/dist/chunk-ORGJSKR4.js +62 -0
- package/dist/chunk-ORGJSKR4.js.map +1 -0
- package/dist/chunk-PJATLYMU.js +2 -0
- package/dist/chunk-PJATLYMU.js.map +1 -0
- package/dist/core.cjs +1 -1
- package/dist/core.d.cts +40 -3
- package/dist/core.d.ts +40 -3
- package/dist/core.js +1 -1
- package/dist/grasshopper.cjs +1 -1
- package/dist/grasshopper.cjs.map +1 -1
- package/dist/grasshopper.d.cts +220 -20
- package/dist/grasshopper.d.ts +220 -20
- package/dist/grasshopper.js +1 -1
- package/dist/{handle-files-9pkEgDIp.d.cts → handle-files-DMnx92gr.d.cts} +46 -10
- package/dist/{handle-files-9pkEgDIp.d.ts → handle-files-DMnx92gr.d.ts} +46 -10
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +1 -1
- package/dist/{types-V7G83j5m.d.cts → types-C9YpTbr3.d.cts} +27 -6
- package/dist/{types-V7G83j5m.d.ts → types-C9YpTbr3.d.ts} +27 -6
- package/dist/{types-DxPi5SEx.d.cts → types-Ci8Z0-hF.d.cts} +60 -17
- package/dist/{types-BBSF_ISX.d.ts → types-DuOh5XqS.d.ts} +60 -17
- package/dist/visualization-C3YOGQTW.js +2 -0
- package/dist/visualization-CERJ6XDX.cjs +2 -0
- package/dist/visualization-CERJ6XDX.cjs.map +1 -0
- package/dist/visualization.cjs +1 -1
- package/dist/visualization.d.cts +62 -8
- package/dist/visualization.d.ts +62 -8
- package/dist/visualization.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-33753HSV.cjs +0 -2
- package/dist/chunk-33753HSV.cjs.map +0 -1
- package/dist/chunk-4JNRO7TX.cjs +0 -62
- package/dist/chunk-4JNRO7TX.cjs.map +0 -1
- package/dist/chunk-6V6SUB4V.js +0 -62
- package/dist/chunk-6V6SUB4V.js.map +0 -1
- package/dist/chunk-D7A3YIYD.cjs +0 -4
- package/dist/chunk-D7A3YIYD.cjs.map +0 -1
- package/dist/chunk-EMXDP7KY.js +0 -4
- package/dist/chunk-EMXDP7KY.js.map +0 -1
- package/dist/chunk-MDFVHHH6.js +0 -2
- package/dist/chunk-MDFVHHH6.js.map +0 -1
- package/dist/visualization-3XYZHAIV.js +0 -2
- package/dist/visualization-DEAMRV7R.cjs +0 -2
- package/dist/visualization-DEAMRV7R.cjs.map +0 -1
- /package/dist/{visualization-3XYZHAIV.js.map → visualization-C3YOGQTW.js.map} +0 -0
|
@@ -0,0 +1,62 @@
|
|
|
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 _chunkGF6ZIJWXcjs = require('./chunk-GF6ZIJWX.cjs');var ht={};_chunkGF6ZIJWXcjs.a.call(void 0, ht,{CONCRETE_MATERIAL:()=>Le,EMISSIVE_MATERIAL:()=>Se,GLASS_MATERIAL:()=>Pe,METAL_MATERIAL:()=>De,PLASTIC_MATERIAL:()=>Oe,RUBBER_MATERIAL:()=>Ie,SHARED_MATERIALS:()=>ge,WOOD_MATERIAL:()=>Ve});var _three = require('three'); var P = _interopRequireWildcard(_three); var U = _interopRequireWildcard(_three); var k = _interopRequireWildcard(_three); var F = _interopRequireWildcard(_three); var N = _interopRequireWildcard(_three); var re = _interopRequireWildcard(_three); var Ne = _interopRequireWildcard(_three); var L = _interopRequireWildcard(_three); var fe = _interopRequireWildcard(_three); var h = _interopRequireWildcard(_three); var W = _interopRequireWildcard(_three); var I = _interopRequireWildcard(_three);var Se=new P.MeshPhysicalMaterial({color:0,emissive:new P.Color(16777215),emissiveIntensity:5,metalness:0,roughness:.2,clearcoat:.3,clearcoatRoughness:.2,depthWrite:!0,depthTest:!0,transparent:!1,alphaTest:0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1,side:P.FrontSide,dithering:!0}),De=new P.MeshPhysicalMaterial({color:new P.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,polygonOffsetFactor:1,polygonOffsetUnits:1,side:P.FrontSide,dithering:!0}),Le=new P.MeshPhysicalMaterial({color:new P.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:0,depthTest:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1,side:P.FrontSide,dithering:!0}),Oe=new P.MeshPhysicalMaterial({color:new P.Color(16777215),metalness:0,roughness:.3,envMapIntensity:.5,clearcoat:.5,clearcoatRoughness:.1,reflectivity:.5,ior:1.4,transmission:0,transparent:!1,depthWrite:!0,side:P.FrontSide,dithering:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),Pe=new P.MeshPhysicalMaterial({color:new P.Color(16777215),metalness:0,roughness:0,transmission:.95,transparent:!0,depthWrite:!1,envMapIntensity:1,clearcoat:1,clearcoatRoughness:0,ior:1.52,reflectivity:.9,thickness:1,side:P.DoubleSide,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),Ie=new P.MeshPhysicalMaterial({color:new P.Color(1710618),metalness:0,roughness:.9,envMapIntensity:.2,clearcoat:.1,clearcoatRoughness:.8,reflectivity:.2,ior:1.3,transmission:0,depthWrite:!0,side:P.FrontSide,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),Ve=new P.MeshPhysicalMaterial({color:new P.Color(8934707),metalness:0,roughness:.7,envMapIntensity:.3,clearcoat:.3,clearcoatRoughness:.4,reflectivity:.3,ior:1.3,transmission:0,depthWrite:!0,side:P.FrontSide,dithering:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),ge=new Set([Se,De,Le,Oe,Pe,Ie,Ve]);var Z={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 Sr(e,n,t,r,a){if(yt(e),n.length===0)return;n.forEach(d=>{e.add(d)});let o=oe(n),i=o.getCenter(new U.Vector3),s=o.getSize(new U.Vector3),l=Math.max(s.x,s.y,s.z);if(l/Math.min(s.x||1,s.y||1,s.z||1)>Z.SCALE_RATIO_THRESHOLD||l>Z.HUGE_THRESHOLD?(t.near=l*Z.NEAR_PLANE_FACTOR.TINY,t.far=l*Z.FAR_PLANE_FACTOR.HUGE):l>Z.LARGE_THRESHOLD?(t.near=l*Z.NEAR_PLANE_FACTOR.SMALL,t.far=l*Z.FAR_PLANE_FACTOR.LARGE):(t.near=Math.max(.01,l*Z.NEAR_PLANE_FACTOR.NORMAL),t.far=Math.max(2e3,l*Z.FAR_PLANE_FACTOR.NORMAL)),t.updateProjectionMatrix(),!a){let d=l*Z.INITIAL_DISTANCE_MULTIPLIER;t.position.set(i.x+d*.8,i.y+d,i.z+d*1.2),r.target.copy(i),r.update()}}function Be(e){if(!e||typeof e!="string")return _chunkGF6ZIJWXcjs.e.call(void 0, ).warn(`Invalid color input: ${e}, using white`),new U.Color(16777215);let n=e.trim();if(/^#?[0-9A-Fa-f]{6}$/.test(n))try{let r=n.startsWith("#")?n:`#${n}`;return new U.Color(r)}catch (e2){return _chunkGF6ZIJWXcjs.e.call(void 0, ).warn(`Invalid hex color: ${e}, using white`),new U.Color(16777215)}if(n.includes(",")){let r=n.split(",").map(a=>parseInt(a.trim(),10));if(r.length===3&&r.every(a=>!isNaN(a)&&a>=0&&a<=255))return new U.Color(r[0]/255,r[1]/255,r[2]/255)}let t=n.toLowerCase();return t in U.Color.NAMES?new U.Color(U.Color.NAMES[t]):(_chunkGF6ZIJWXcjs.e.call(void 0, ).warn(`Invalid color string: ${e}, using white`),new U.Color(16777215))}function Fe(e,n,t="z"){e.forEach(r=>{r.position[t]-=n})}function oe(e){let n=new U.Box3;return e.length===0||e.forEach(t=>{t.updateMatrixWorld(!0);let r=new U.Box3().setFromObject(t);n.union(r)}),n}var gt=new Set(["floor","grid","label-layer"]);function yt(e){[...e.children].forEach(t=>{gt.has(t.userData.id)||t.userData.source!=="user"&&(t.traverse(r=>{let a=r;if(!a.geometry&&!a.material)return;_optionalChain([a, 'access', _2 => _2.geometry, 'optionalAccess', _3 => _3.dispose, 'call', _4 => _4()]);let o=a.material;if(!o)return;(Array.isArray(o)?o:[o]).forEach(s=>{if(!ge.has(s)){for(let l of Object.values(s))l instanceof U.Texture&&l.dispose();s.dispose()}})}),t.removeFromParent())})}function bt(e){let n=e.clone().normalize(),t=new k.Vector3(0,0,1),r=new k.Vector3(0,1,0),a=Math.abs(n.dot(t))>.9?r:t,o=new k.Vector3().crossVectors(n,a).normalize(),i=new k.Vector3().crossVectors(o,n).normalize();return{top:n.clone(),bottom:n.clone().negate(),front:i.clone(),back:i.clone().negate(),right:o.clone(),left:o.clone().negate(),iso:i.clone().multiplyScalar(1.2).add(o.clone()).add(n.clone()).normalize()}}function Ue(e){let{scene:n,perspective:t,controls:r,onActiveCameraChange:a}=e,o=(_nullishCoalesce(e.up, () => (t.up))).clone().normalize(),i=bt(o),s=new k.OrthographicCamera(-1,1,1,-1,t.near,t.far);s.up.copy(o);let l="perspective",c=t.aspect,d=()=>l==="perspective"?t:s,u=null,f=()=>{_optionalChain([u, 'optionalAccess', _5 => _5.cancel, 'call', _6 => _6()]),u=null},p=()=>{let b=(l==="orthographic"?s:t).position.distanceTo(r.target)*Math.tan(t.fov*Math.PI/360),v=b*c;s.left=-v,s.right=v,s.top=b,s.bottom=-b,s.near=t.near,s.far=t.far,s.updateProjectionMatrix()},g=m=>{if(m!==l){if(f(),m==="orthographic")s.position.copy(t.position),s.up.copy(t.up),s.lookAt(r.target),s.zoom=1,p();else{let b=(s.top-s.bottom)/(2*s.zoom)/Math.tan(t.fov*Math.PI/360),v=s.position.clone().sub(r.target);v.lengthSq()<1e-12&&v.copy(o),v.normalize(),t.position.copy(r.target).add(v.multiplyScalar(b))}l=m,r.object=d(),r.update(),a(d())}},y=(m,T,b,v)=>{let A=t.fov*(Math.PI/180),V=T/(2*Math.tan(A/2))*1.5,$=vt(b,o),B=m.clone().add($.clone().multiplyScalar(V)),Y=d();l==="orthographic"&&(s.zoom=1),f(),v?u=Ht(Y,r,B,m,()=>{l==="orthographic"&&p()}):(Y.position.copy(B),r.target.copy(m),l==="orthographic"&&p(),r.update())},R=(m,T=!0)=>{let b=wt(n),v=b.isEmpty()?r.target.clone():b.getCenter(new k.Vector3),A=b.isEmpty()?new k.Vector3(1,1,1):b.getSize(new k.Vector3),V=Math.max(A.x,A.y,A.z)||1;y(v,V,m,T)};return{getActiveCamera:d,getProjection:()=>l,setProjection:g,toggleProjection:()=>(g(l==="perspective"?"orthographic":"perspective"),l),setView:(m,T=!0)=>{R(i[m],T)},setViewDirection:R,frameBounds:(m,T=!0)=>{if(m.isEmpty())return;let b=m.getCenter(new k.Vector3),v=m.getSize(new k.Vector3),A=Math.max(v.x,v.y,v.z)||1,V=d().position.clone().sub(r.target);V.lengthSq()<1e-12&&V.copy(i.iso),y(b,A,V.normalize(),T)},setRotateEnabled:m=>{r.enableRotate=m},isRotateEnabled:()=>r.enableRotate,updateAspect:(m,T)=>{c=T===0?c:m/T,l==="orthographic"&&p()},dispose:f}}var Tt=new Set(["grid","floor","label-layer","measure"]);function Rt(e){let n=e;for(;n;){if(typeof n.userData.id=="string"&&Tt.has(n.userData.id))return!0;n=n.parent}return!1}function wt(e){let n=[];return e.traverse(t=>{let r=t;t.visible&&!Rt(t)&&r.geometry&&n.push(t)}),oe(n)}function vt(e,n){let t=n.clone().normalize(),r=e.clone().normalize();if(Math.abs(r.dot(t))<.9999)return e;let a=Math.abs(t.dot(new k.Vector3(0,0,1)))>.9?new k.Vector3(0,1,0):new k.Vector3(0,0,1),o=new k.Vector3().crossVectors(t,a).normalize(),i=.5*Math.PI/180;return r.multiplyScalar(Math.cos(i)).add(o.multiplyScalar(Math.sin(i))).normalize()}var xt=e=>1-Math.pow(1-e,3);function Ht(e,n,t,r,a,o=250){let i=e.position.clone(),s=n.target.clone(),l=performance.now(),c=null,d=()=>{c=null;let u=xt(Math.min((performance.now()-l)/o,1));e.position.lerpVectors(i,t,u),n.target.lerpVectors(s,r,u),a(),n.update(),u<1&&(c=requestAnimationFrame(d))};return c=requestAnimationFrame(d),{cancel:()=>{c!==null&&(cancelAnimationFrame(c),c=null)}}}var Mt=`
|
|
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
|
+
`,Ct=`
|
|
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 ze(e={}){let{cellSize:n=1,majorEvery:t=10,cellColor:r=8947848,majorColor:a=4473924,fadeDistance:o=100,plane:i="y"}=e,s=i==="y"?new F.Vector2(0,2):i==="z"?new F.Vector2(0,1):new F.Vector2(1,2),l=o*2.5,c=new F.PlaneGeometry(l,l);i==="y"?c.rotateX(-Math.PI/2):i==="x"&&c.rotateY(Math.PI/2);let d=new F.ShaderMaterial({vertexShader:Mt,fragmentShader:Ct,transparent:!0,depthWrite:!1,side:F.DoubleSide,uniforms:{uAxes:{value:s},uCell:{value:n},uMajor:{value:t},uCellColor:{value:new F.Color(r)},uMajorColor:{value:new F.Color(a)},uCenter:{value:new F.Vector3},uFade:{value:o}}}),u=new F.Mesh(c,d);u.name="grid",u.userData.id="grid",u.renderOrder=-1;let f=new F.Vector3;return{object:u,update:p=>{i==="y"?(u.position.set(p.x,0,p.z),f.set(p.x,0,p.z)):i==="z"?(u.position.set(p.x,p.y,0),f.set(p.x,p.y,0)):(u.position.set(0,p.y,p.z),f.set(0,p.y,p.z)),d.uniforms.uCenter.value.copy(f)},setVisible:p=>{u.visible=p},dispose:()=>{u.removeFromParent(),c.dispose(),d.dispose()}}}var _ViewHelperjs = require('three/addons/helpers/ViewHelper.js');function _e(e){let{camera:n,domElement:t,controller:r}=e,a=new (0, _ViewHelperjs.ViewHelper)(n,t);a.setLabels("X","Y","Z");let o=!0,i=128,s=new N.Raycaster,l=new N.OrthographicCamera(-2,2,2,-2,0,4);l.position.set(0,0,2),l.updateMatrixWorld();let c={posX:new N.Vector3(1,0,0),negX:new N.Vector3(-1,0,0),posY:new N.Vector3(0,1,0),negY:new N.Vector3(0,-1,0),posZ:new N.Vector3(0,0,1),negZ:new N.Vector3(0,0,-1)},d=f=>{let p=t.getBoundingClientRect(),g=p.left+t.offsetWidth-i-a.location.right,y=p.top+t.offsetHeight-i-a.location.bottom,R=new N.Vector2((f.clientX-g)/i*2-1,-((f.clientY-y)/i)*2+1);if(Math.abs(R.x)>1||Math.abs(R.y)>1)return null;a.quaternion.copy(n.quaternion).invert(),a.updateMatrixWorld(),s.setFromCamera(R,l);let w=s.intersectObjects(a.children,!1);for(let E of w){let x=_optionalChain([E, 'access', _7 => _7.object, 'access', _8 => _8.userData, 'optionalAccess', _9 => _9.type]);if(typeof x=="string"&&x in c)return x}return null};return{render:f=>{if(!o)return;let p=f.autoClear;f.autoClear=!1,a.render(f),f.autoClear=p},update:()=>{},handleClick:f=>{if(!o)return!1;let p=d(f);return p?(r.getProjection()==="orthographic"&&r.setProjection("perspective"),r.setViewDirection(c[p],!1),!0):!1},isAnimating:!1,setVisible:f=>{o=f},isVisible:()=>o,dispose:()=>a.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 ce="edge-overlay",Lt=2236962,Ot=1.5,Pt=30,ye=new WeakMap;function je(e,n={}){let t=new re.Color(_nullishCoalesce(n.color, () => (Lt))),r=_nullishCoalesce(n.width, () => (Ot)),a=_nullishCoalesce(n.thresholdAngle, () => (Pt)),o=[];return e.traverse(i=>{if(!(i instanceof re.Mesh)||i.userData.id==="floor"||i.userData.id==="grid"||i.userData.kind===ce||i.children.some(l=>_optionalChain([l, 'access', _10 => _10.userData, 'optionalAccess', _11 => _11.kind])===ce)||!i.geometry)return;let s=Bt(i.geometry,t,r,a);i.add(s),o.push(s)}),o}function It(e,n){let t=ye.get(e);t||(t=new Map,ye.set(e,t));let r=t.get(n);if(!r){let a=new re.EdgesGeometry(e,n),o=new _LineSegmentsGeometryjs.LineSegmentsGeometry;o.setPositions(a.attributes.position.array),a.dispose(),r={geometry:o,refCount:0},t.set(n,r)}return r.refCount+=1,r.geometry}function Vt(e){let n=e.userData,t=n.edgeSource&&ye.get(n.edgeSource),r=n.edgeThresholdAngle!=null?_optionalChain([t, 'optionalAccess', _12 => _12.get, 'call', _13 => _13(n.edgeThresholdAngle)]):void 0;if(!r||r.geometry!==e.geometry){e.geometry.dispose();return}r.refCount-=1,r.refCount<=0&&(r.geometry.dispose(),t.delete(n.edgeThresholdAngle))}function Bt(e,n,t,r){let a=It(e,r),o=new (0, _LineMaterialjs.LineMaterial)({color:n});o.linewidth=t,o.polygonOffset=!0,o.polygonOffsetFactor=-1,o.polygonOffsetUnits=-4;let i=new (0, _LineSegments2js.LineSegments2)(a,o);return i.userData.kind=ce,i.userData.edgeSource=e,i.userData.edgeThresholdAngle=r,i.raycast=()=>{},i}function Ft(e){return _optionalChain([e, 'access', _14 => _14.userData, 'optionalAccess', _15 => _15.kind])===ce}function zr(e){let n=[];e.traverse(t=>{t instanceof _LineSegments2js.LineSegments2&&Ft(t)&&n.push(t)});for(let t of n)Vt(t),t.material.dispose(),t.removeFromParent();return n.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 _SMAAPassjs = require('three/addons/postprocessing/SMAAPass.js');var _OutputPassjs = require('three/addons/postprocessing/OutputPass.js');function Ge(e,n,t,r,a,o){let i=new (0, _EffectComposerjs.EffectComposer)(e),s=new (0, _RenderPassjs.RenderPass)(n,t);i.addPass(s);let l=new (0, _GTAOPassjs.GTAOPass)(n,t,r,a);l.blendIntensity=_nullishCoalesce(o.aoIntensity, () => (1)),l.updateGtaoMaterial({screenSpaceRadius:!0}),i.addPass(l);let c=new _SMAAPassjs.SMAAPass;i.addPass(c);let d=new _OutputPassjs.OutputPass;return i.addPass(d),e.toneMapping=o.toneMapping,e.toneMappingExposure=o.toneMappingExposure,i.setSize(r,a),{render:u=>i.render(u),setSize:(u,f,p)=>{i.setPixelRatio(p),i.setSize(u,f)},setCamera:u=>{s.camera=u,l.camera=u;let f=u.isPerspectiveCamera?1:0;l.gtaoMaterial.defines.PERSPECTIVE_CAMERA!==f&&(l.gtaoMaterial.defines.PERSPECTIVE_CAMERA=f,l.gtaoMaterial.needsUpdate=!0)},dispose:()=>{i.dispose(),l.dispose(),c.dispose(),d.dispose()}}}var _CSS2DRendererjs = require('three/addons/renderers/CSS2DRenderer.js');function We(e,n){let t=new _CSS2DRendererjs.CSS2DRenderer,r=t.domElement;r.style.position="absolute",r.style.top="0",r.style.left="0",r.style.overflow="hidden",r.style.pointerEvents="none",r.style.zIndex="30",getComputedStyle(e).position==="static"&&(e.style.position="relative"),e.appendChild(r);let a={width:e.clientWidth||1,height:e.clientHeight||1};t.setSize(a.width,a.height);let o=new Ne.Group;o.name="label-layer",o.userData.id="label-layer",n.add(o);let i=new Set;return{addLabel:(l,c,d)=>{let u=document.createElement("div");u.textContent=l,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 f=new (0, _CSS2DRendererjs.CSS2DObject)(u);return f.position.copy(c),o.add(f),i.add(f),{object:f,setPosition:p=>f.position.copy(p),setText:p=>{u.textContent=p},remove:()=>{f.removeFromParent(),u.remove(),i.delete(f)}}},render:(l,c)=>t.render(l,c),setSize:(l,c)=>t.setSize(l,c),dispose:()=>{i.forEach(l=>{l.removeFromParent(),l.element.remove()}),i.clear(),o.removeFromParent(),r.remove()}}}var _Line2js = require('three/addons/lines/Line2.js');var _LineGeometryjs = require('three/addons/lines/LineGeometry.js');var Xt=12,qt=16763904,$e=.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 Zt(e){let n=e&&Ye[e]||Ye.Meters;return t=>`${(t/n.metersPerUnit).toPrecision(3)} ${n.suffix}`}function Kt(e,n){if(e.isOrthographicCamera){let r=e;return Math.abs(r.top-r.bottom)/(r.zoom||1)*$e}return((n?e.position.distanceTo(n):e.position.length())||1)*$e}function Jt(e){let n=e.object;if(n instanceof L.Mesh)return e.face?[e.face.a,e.face.b,e.face.c]:null;if(n instanceof L.Points)return e.index!=null?[e.index]:null;if(n instanceof L.Line){if(e.index==null)return null;let t=n.geometry.index;return t?e.index+1>=t.count?null:[t.getX(e.index),t.getX(e.index+1)]:[e.index,e.index+1]}return null}function Qt(e,n,t,r){let a=e.point.clone(),o=e.object,i=Jt(e);if(!i||!o.geometry)return a;let s=o.geometry.attributes.position;if(!s)return a;let l=f=>{let p=f.clone().project(n);return new L.Vector2((p.x+1)/2*t.width,(1-p.y)/2*t.height)},c=l(a),d=a,u=r;for(let f of i){if(f>=s.count)continue;let g=new L.Vector3().fromBufferAttribute(s,f).applyMatrix4(o.matrixWorld),y=l(g).distanceTo(c);y<u&&(u=y,d=g)}return d}function Xe(e){let{canvas:n,scene:t,getActiveCamera:r,getViewTarget:a,labelLayer:o,options:i={}}=e,s=_nullishCoalesce(i.snapPixels, () => (Xt)),l=new L.Color(_nullishCoalesce(i.color, () => (qt))),c=Zt(i.displayUnit),d=(H,S)=>`${c(H)}
|
|
54
|
+
\u0394x ${c(S.x)} \u0394y ${c(S.y)} \u0394z ${c(S.z)}`,u=_nullishCoalesce(i.format, () => (d)),f=new L.Raycaster,p=new L.Vector2,g=!1,y=[],R=[],w=null,E=null,x=new L.PointsMaterial({color:l,size:8,sizeAttenuation:!1,depthTest:!1}),O=new L.PointsMaterial({color:l,size:11,sizeAttenuation:!1,depthTest:!1,transparent:!0,opacity:.5}),m=null,T=H=>{if(!H){m&&(m.visible=!1);return}if(!m){let S=new L.BufferGeometry;S.setAttribute("position",new L.Float32BufferAttribute([0,0,0],3)),m=new L.Points(S,O),m.renderOrder=1e3,m.userData.id="measure",m.raycast=()=>{},t.add(m)}m.position.copy(H),m.visible=!0},b=H=>{let S=new L.BufferGeometry;S.setAttribute("position",new L.Float32BufferAttribute([H.x,H.y,H.z],3));let z=new L.Points(S,x);return z.renderOrder=999,z.userData.id="measure",z.raycast=()=>{},t.add(z),z},v=()=>{y.length=0,R.forEach(H=>{H.geometry.dispose(),H.removeFromParent()}),R.length=0,w&&(w.geometry.dispose(),w.material.dispose(),w.removeFromParent(),w=null),_optionalChain([E, 'optionalAccess', _16 => _16.remove, 'call', _17 => _17()]),E=null},A=()=>{if(y.length!==2)return;let[H,S]=y,z=new _LineGeometryjs.LineGeometry;z.setPositions([H.x,H.y,H.z,S.x,S.y,S.z]);let J=new (0, _LineMaterialjs.LineMaterial)({color:l});J.linewidth=2,J.depthTest=!1,w=new (0, _Line2js.Line2)(z,J),w.renderOrder=998,w.userData.id="measure",w.raycast=()=>{},t.add(w);let Q=H.clone().add(S).multiplyScalar(.5),ee=new L.Vector3(Math.abs(S.x-H.x),Math.abs(S.y-H.y),Math.abs(S.z-H.z));E=o.addLabel(u(H.distanceTo(S),ee),Q,i.labelClassName)},V=H=>{let S=n.getBoundingClientRect();p.x=(H.clientX-S.left)/S.width*2-1,p.y=-((H.clientY-S.top)/S.height)*2+1;let z=r();f.setFromCamera(p,z);let J=Kt(z,_optionalChain([a, 'optionalCall', _18 => _18()]));f.params.Line.threshold=J,f.params.Points.threshold=J;let Q=f.intersectObjects(t.children,!0).filter(ee=>ee.object.userData.id!=="measure"&&ee.object.userData.id!=="grid");return Q.length===0?null:Qt(Q[0],z,{width:S.width,height:S.height},s)},$=null,B=0,Y=()=>{B&&(cancelAnimationFrame(B),B=0),$=null};return{setEnabled:H=>{g=H,H||(Y(),v(),T(null))},isEnabled:()=>g,handleClick:H=>{if(!g)return!1;y.length===2&&v();let S=V(H);return S===null||(y.push(S),R.push(b(S)),y.length===2&&A()),!0},handleMove:H=>{g&&($=H,!B&&(B=requestAnimationFrame(()=>{B=0;let S=$;$=null,!(!g||!S)&&T(V(S))})))},clear:v,dispose:()=>{Y(),v(),m&&(m.geometry.dispose(),m.removeFromParent(),m=null),x.dispose(),O.dispose()}}}var en=64,tn=256,X=new Map,ae=new Map,ue=0,me=class extends Error{constructor(n){super(`Texture load for ${n} resolved after clearTextureCache(); texture disposed.`),this.name="StaleTextureLoadError"}},de=1;function qe(e){de=Math.max(1,e);for(let n of X.values())n.anisotropy!==de&&(n.anisotropy=de,n.needsUpdate=!0)}function Ze(e,n){let t=nn(n),r=X.get(t);if(r){X.delete(t),X.set(t,r),e.map=r,e.needsUpdate=!0;return}typeof document>"u"||an(n,t).then(a=>{e.map=a,e.needsUpdate=!0}).catch(a=>{a instanceof me||_chunkGF6ZIJWXcjs.e.call(void 0, ).warn(`Failed to load material texture ${n}:`,a)})}function eo(){ue++;for(let e of X.values())e.dispose();X.clear(),ae.clear()}function nn(e){return e.length<=tn?e:`data-uri:${rn(e).toString(16)}:${e.length}`}function rn(e){let n=2166136261;for(let t=0;t<e.length;t++)n^=e.charCodeAt(t),n=Math.imul(n,16777619);return n>>>0}function on(e,n){for(X.set(e,n);X.size>en;){let t=X.keys().next().value,r=X.get(t);X.delete(t),r.dispose()}}function an(e,n){let t=ae.get(n);if(!t){let r=ue;t=new Promise((a,o)=>{new fe.TextureLoader().load(e,i=>{if(r!==ue){i.dispose(),o(new me(e));return}i.colorSpace=fe.SRGBColorSpace,i.anisotropy=de,on(n,i),ae.delete(n),a(i)},void 0,i=>{r===ue&&ae.delete(n),o(i)})}),ae.set(n,t)}return t}var _OrbitControlsjs = require('three/addons/controls/OrbitControls.js');var _HDRLoaderjs = require('three/addons/loaders/HDRLoader.js');var Ee=new h.Vector3(0,0,1),Te={technical:{toneMapping:h.NeutralToneMapping,toneMappingExposure:1,envMapIntensity:.5,cullBackfaces:!1,ambientOcclusion:!0,edges:!0,grid:!0},rendered:{toneMapping:h.ACESFilmicToneMapping,toneMappingExposure:1,envMapIntensity:1.3,cullBackfaces:!1,ambientOcclusion:!0,edges:!1,grid:!1}};function cn(e){let n=Te[e];return{envMapIntensity:n.envMapIntensity,cullBackfaces:n.cullBackfaces}}function un(e){let n=Math.abs(e.x),t=Math.abs(e.y),r=Math.abs(e.z);return r>=n&&r>=t?"z":t>=n&&t>=r?"y":"x"}var po=function(e,n){let t=dn(n||{}),r=_optionalChain([t, 'access', _19 => _19.environment, 'optionalAccess', _20 => _20.sceneUp])||Ee,a=_nullishCoalesce(t.render.pixelRatio, () => (Math.min(window.devicePixelRatio,2))),o=En(t),i=Tn(t,e);i.up.copy(r);let s=Rn(e,t,a);qe(s.capabilities.getMaxAnisotropy());let l=vn(i,e,t),c=Ue({scene:o,perspective:i,controls:l,onActiveCameraChange:()=>{},up:r}),d=()=>c.getActiveCamera(),u=!1;gn(o,t,()=>u);let f=yn(o,t),p=()=>{f&&pn(f,be(o))};_optionalChain([t, 'access', _21 => _21.floor, 'optionalAccess', _22 => _22.enabled])&&bn(o,t);let g=t.grid.enabled?ze({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;g&&o.add(g.object);let y=t.gizmo.enabled?_e({camera:i,domElement:e,controller:c}):null,R=_nullishCoalesce(e.parentElement, () => (e)),w=t.measure.enabled?We(R,o):null,E=t.measure.enabled&&w?Xe({canvas:e,scene:o,getActiveCamera:d,labelLayer:w,options:{snapPixels:t.measure.snapPixels,color:t.measure.color,labelClassName:t.measure.labelClassName,displayUnit:t.measure.displayUnit,format:t.measure.format}}):null,x=t.events.enableEventHandlers!==!1?wn(e,o,c,t):{dispose:()=>{},fitToView:()=>{},clearSelection:()=>{}},O=5,m=0,T=0,b=M=>{m=M.clientX,T=M.clientY},v=M=>Math.hypot(M.clientX-m,M.clientY-T)>O,A=M=>{if(!v(M)){if(_optionalChain([E, 'optionalAccess', _23 => _23.handleClick, 'call', _24 => _24(M)])){M.stopImmediatePropagation();return}_optionalChain([y, 'optionalAccess', _25 => _25.handleClick, 'call', _26 => _26(M)])&&M.stopImmediatePropagation()}};(y||E)&&(e.addEventListener("mousedown",b,{capture:!0}),e.addEventListener("click",A,{capture:!0}));let V=M=>_optionalChain([E, 'optionalAccess', _27 => _27.handleMove, 'call', _28 => _28(M)]);E&&e.addEventListener("mousemove",V,{passive:!0});let $=M=>{je(M,{color:t.edges.color,width:t.edges.width,thresholdAngle:t.edges.thresholdAngle})},B=e.parentElement,Y=()=>B?{width:B.clientWidth,height:B.clientHeight}:{width:window.innerWidth,height:window.innerHeight},G=null,q=()=>{let{width:M,height:D}=Y(),_=Ge(s,o,d(),Math.max(1,M),Math.max(1,D),{toneMapping:_nullishCoalesce(t.render.toneMapping, () => (h.NeutralToneMapping)),toneMappingExposure:_nullishCoalesce(t.render.toneMappingExposure, () => (1)),aoIntensity:t.render.aoIntensity});return _.setSize(Math.max(1,M),Math.max(1,D),a),_},H=M=>{M&&!G?G=q():!M&&G&&(G.dispose(),G=null)};t.render.ambientOcclusion&&(G=q());let S=M=>{let D=Te[M];z=M,s.toneMapping=D.toneMapping,s.toneMappingExposure=D.toneMappingExposure,t.render.toneMapping=D.toneMapping,t.render.toneMappingExposure=D.toneMappingExposure,G&&H(!1),H(D.ambientOcclusion),o.traverse(_=>{if(_.userData.source!=="compute")return;let le=_,pt=Array.isArray(le.material)?le.material:le.material?[le.material]:[];for(let Ce of pt)"envMapIntensity"in Ce&&(Ce.envMapIntensity=D.envMapIntensity)}),o.traverse(_=>{_.userData.kind==="edge-overlay"&&(_.visible=D.edges)}),g&&(g.object.visible=D.grid)},z=_nullishCoalesce(_optionalChain([n, 'optionalAccess', _29 => _29.renderStyle]), () => (null)),J=()=>z?cn(z):void 0,{animate:Q,dispose:ee}=hn(s,o,i,d,c,l,Y,a,t.events.onFrame,g,y,()=>G,w);Q(),o.up.set(r.x,r.y,r.z),p();let Me=M=>{M.traverse(D=>{let _=D;!_.geometry&&!_.material||(_optionalChain([_, 'access', _30 => _30.geometry, 'optionalAccess', _31 => _31.dispose, 'call', _32 => _32()]),Array.isArray(_.material)?_.material.forEach(pe):_.material&&pe(_.material))})},dt=M=>{M.userData.source="user",o.add(M)},mt=M=>{M.removeFromParent(),Me(M)},ft=()=>{o.children.filter(D=>D.userData.source==="user").forEach(D=>{D.removeFromParent(),Me(D)})};return{scene:o,camera:i,controls:l,renderer:s,cameraController:c,grid:g,gizmo:y,measureTool:E,applyEdges:$,setAmbientOcclusion:H,setRenderStyle:S,getMaterialAppearance:J,updateShadowBounds:p,dispose:()=>{u=!0,ee(),x.dispose(),(y||E)&&(e.removeEventListener("mousedown",b,{capture:!0}),e.removeEventListener("click",A,{capture:!0})),E&&e.removeEventListener("mousemove",V),_optionalChain([E, 'optionalAccess', _33 => _33.dispose, 'call', _34 => _34()]),_optionalChain([w, 'optionalAccess', _35 => _35.dispose, 'call', _36 => _36()]),_optionalChain([y, 'optionalAccess', _37 => _37.dispose, 'call', _38 => _38()]),_optionalChain([g, 'optionalAccess', _39 => _39.dispose, 'call', _40 => _40()]),_optionalChain([G, 'optionalAccess', _41 => _41.dispose, 'call', _42 => _42()]),c.dispose(),l.dispose(),s.dispose(),s.forceContextLoss(),o.traverse(M=>{let D=M;!D.geometry&&!D.material||(_optionalChain([D, 'access', _43 => _43.geometry, 'optionalAccess', _44 => _44.dispose, 'call', _45 => _45()]),Array.isArray(D.material)?D.material.forEach(pe):D.material&&pe(D.material))}),_optionalChain([o, 'access', _46 => _46.environment, 'optionalAccess', _47 => _47.dispose, 'call', _48 => _48()]),o.background instanceof h.Texture&&o.background.dispose()},fitToView:x.fitToView,clearSelection:x.clearSelection,addUserGeometry:dt,removeUserGeometry:mt,clearUserGeometry:ft}};function dn(e){let n=e.sceneScale||"m",r={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}}[n],a=e.renderStyle?Te[e.renderStyle]:null;return{sceneScale:n,renderStyle:_nullishCoalesce(e.renderStyle, () => ("technical")),camera:{position:_optionalChain([e, 'access', _49 => _49.camera, 'optionalAccess', _50 => _50.position])||new h.Vector3(-r.cameraDistance,-r.cameraDistance,r.cameraDistance),fov:_optionalChain([e, 'access', _51 => _51.camera, 'optionalAccess', _52 => _52.fov])||20,near:_optionalChain([e, 'access', _53 => _53.camera, 'optionalAccess', _54 => _54.near])||r.near,far:_optionalChain([e, 'access', _55 => _55.camera, 'optionalAccess', _56 => _56.far])||r.far,target:_optionalChain([e, 'access', _57 => _57.camera, 'optionalAccess', _58 => _58.target])||new h.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 h.Vector3(r.lightDistance,r.lightDistance,r.lightHeight),ambientLightColor:_optionalChain([e, 'access', _65 => _65.lighting, 'optionalAccess', _66 => _66.ambientLightColor])||new h.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 h.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])||r.floorSize,color:_optionalChain([e, 'access', _85 => _85.floor, 'optionalAccess', _86 => _86.color])||new h.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])||_optionalChain([a, 'optionalAccess', _103 => _103.toneMapping])||h.NeutralToneMapping,toneMappingExposure:_nullishCoalesce(_nullishCoalesce(_optionalChain([e, 'access', _104 => _104.render, 'optionalAccess', _105 => _105.toneMappingExposure]), () => (_optionalChain([a, 'optionalAccess', _106 => _106.toneMappingExposure]))), () => (1)),preserveDrawingBuffer:_nullishCoalesce(_optionalChain([e, 'access', _107 => _107.render, 'optionalAccess', _108 => _108.preserveDrawingBuffer]), () => (!1)),ambientOcclusion:_nullishCoalesce(_nullishCoalesce(_optionalChain([e, 'access', _109 => _109.render, 'optionalAccess', _110 => _110.ambientOcclusion]), () => (_optionalChain([a, 'optionalAccess', _111 => _111.ambientOcclusion]))), () => (!1)),aoIntensity:_nullishCoalesce(_optionalChain([e, 'access', _112 => _112.render, 'optionalAccess', _113 => _113.aoIntensity]), () => (1))},controls:{enableDamping:_nullishCoalesce(_optionalChain([e, 'access', _114 => _114.controls, 'optionalAccess', _115 => _115.enableDamping]), () => (!1)),dampingFactor:_optionalChain([e, 'access', _116 => _116.controls, 'optionalAccess', _117 => _117.dampingFactor])||.05,autoRotate:_nullishCoalesce(_optionalChain([e, 'access', _118 => _118.controls, 'optionalAccess', _119 => _119.autoRotate]), () => (!1)),autoRotateSpeed:_optionalChain([e, 'access', _120 => _120.controls, 'optionalAccess', _121 => _121.autoRotateSpeed])||.5,enableZoom:_nullishCoalesce(_optionalChain([e, 'access', _122 => _122.controls, 'optionalAccess', _123 => _123.enableZoom]), () => (!0)),enablePan:_nullishCoalesce(_optionalChain([e, 'access', _124 => _124.controls, 'optionalAccess', _125 => _125.enablePan]), () => (!0)),minDistance:_optionalChain([e, 'access', _126 => _126.controls, 'optionalAccess', _127 => _127.minDistance])||r.minDistance,maxDistance:_optionalChain([e, 'access', _128 => _128.controls, 'optionalAccess', _129 => _129.maxDistance])||1/0},grid:{enabled:_nullishCoalesce(_nullishCoalesce(_optionalChain([e, 'access', _130 => _130.grid, 'optionalAccess', _131 => _131.enabled]), () => (_optionalChain([a, 'optionalAccess', _132 => _132.grid]))), () => (!1)),cellSize:_nullishCoalesce(_optionalChain([e, 'access', _133 => _133.grid, 'optionalAccess', _134 => _134.cellSize]), () => (1)),majorEvery:_nullishCoalesce(_optionalChain([e, 'access', _135 => _135.grid, 'optionalAccess', _136 => _136.majorEvery]), () => (10)),cellColor:_nullishCoalesce(_optionalChain([e, 'access', _137 => _137.grid, 'optionalAccess', _138 => _138.cellColor]), () => (8947848)),majorColor:_nullishCoalesce(_optionalChain([e, 'access', _139 => _139.grid, 'optionalAccess', _140 => _140.majorColor]), () => (4473924)),fadeDistance:_nullishCoalesce(_optionalChain([e, 'access', _141 => _141.grid, 'optionalAccess', _142 => _142.fadeDistance]), () => (100)),plane:_nullishCoalesce(_optionalChain([e, 'access', _143 => _143.grid, 'optionalAccess', _144 => _144.plane]), () => (un(_nullishCoalesce(_optionalChain([e, 'access', _145 => _145.environment, 'optionalAccess', _146 => _146.sceneUp]), () => (Ee)))))},gizmo:{enabled:_nullishCoalesce(_optionalChain([e, 'access', _147 => _147.gizmo, 'optionalAccess', _148 => _148.enabled]), () => (!1))},edges:{enabled:_nullishCoalesce(_nullishCoalesce(_optionalChain([e, 'access', _149 => _149.edges, 'optionalAccess', _150 => _150.enabled]), () => (_optionalChain([a, 'optionalAccess', _151 => _151.edges]))), () => (!1)),color:_nullishCoalesce(_optionalChain([e, 'access', _152 => _152.edges, 'optionalAccess', _153 => _153.color]), () => (2236962)),width:_nullishCoalesce(_optionalChain([e, 'access', _154 => _154.edges, 'optionalAccess', _155 => _155.width]), () => (1.5)),thresholdAngle:_nullishCoalesce(_optionalChain([e, 'access', _156 => _156.edges, 'optionalAccess', _157 => _157.thresholdAngle]), () => (30))},measure:{enabled:_nullishCoalesce(_optionalChain([e, 'access', _158 => _158.measure, 'optionalAccess', _159 => _159.enabled]), () => (!1)),snapPixels:_optionalChain([e, 'access', _160 => _160.measure, 'optionalAccess', _161 => _161.snapPixels]),color:_optionalChain([e, 'access', _162 => _162.measure, 'optionalAccess', _163 => _163.color]),labelClassName:_optionalChain([e, 'access', _164 => _164.measure, 'optionalAccess', _165 => _165.labelClassName]),displayUnit:_optionalChain([e, 'access', _166 => _166.measure, 'optionalAccess', _167 => _167.displayUnit]),format:_optionalChain([e, 'access', _168 => _168.measure, 'optionalAccess', _169 => _169.format])},events:{onBackgroundClicked:_optionalChain([e, 'access', _170 => _170.events, 'optionalAccess', _171 => _171.onBackgroundClicked]),onObjectSelected:_optionalChain([e, 'access', _172 => _172.events, 'optionalAccess', _173 => _173.onObjectSelected]),onMeshMetadataClicked:_optionalChain([e, 'access', _174 => _174.events, 'optionalAccess', _175 => _175.onMeshMetadataClicked]),onMeshDoubleClicked:_optionalChain([e, 'access', _176 => _176.events, 'optionalAccess', _177 => _177.onMeshDoubleClicked]),selectionColor:_optionalChain([e, 'access', _178 => _178.events, 'optionalAccess', _179 => _179.selectionColor])||"#ff0000",enableEventHandlers:_nullishCoalesce(_optionalChain([e, 'access', _180 => _180.events, 'optionalAccess', _181 => _181.enableEventHandlers]), () => (!0)),enableKeyboardControls:_nullishCoalesce(_optionalChain([e, 'access', _182 => _182.events, 'optionalAccess', _183 => _183.enableKeyboardControls]), () => (!0)),enableClickToFocus:_nullishCoalesce(_optionalChain([e, 'access', _184 => _184.events, 'optionalAccess', _185 => _185.enableClickToFocus]), () => (!0)),enableDoubleClickZoom:_nullishCoalesce(_optionalChain([e, 'access', _186 => _186.events, 'optionalAccess', _187 => _187.enableDoubleClickZoom]), () => (!0)),onReady:_optionalChain([e, 'access', _188 => _188.events, 'optionalAccess', _189 => _189.onReady]),onFrame:_optionalChain([e, 'access', _190 => _190.events, 'optionalAccess', _191 => _191.onFrame])}}}function pe(e){for(let n of Object.values(e))n instanceof h.Texture&&n.dispose();e.dispose()}var mn=new Set(["grid","floor","label-layer","measure"]);function fn(e){let n=e;for(;n;){if(typeof n.userData.id=="string"&&mn.has(n.userData.id))return!0;n=n.parent}return!1}function be(e){let n=new h.Box3;return e.traverse(t=>{let r=t;t.visible&&!fn(t)&&r.geometry&&n.expandByObject(t)}),n}function pn(e,n){if(n.isEmpty())return;let t=n.getCenter(new h.Vector3),r=n.getSize(new h.Vector3).length()*.5*1.2,a=e.shadow.camera;a.left=-r,a.right=r,a.top=r,a.bottom=-r,e.target.position.copy(t),e.target.updateMatrixWorld();let o=e.position.distanceTo(t);a.near=Math.max(r*.01,o-r),a.far=o+r,a.updateProjectionMatrix()}function En(e){let n=new h.Scene,t=typeof e.environment.backgroundColor=="string"?new h.Color(e.environment.backgroundColor):e.environment.backgroundColor;return n.background=t||null,n}function hn(e,n,t,r,a,o,i,s,l,c,d,u,f){let p=null,g=performance.now(),y=()=>{let{width:E,height:x}=i();if(E===0||x===0)return;let O=Math.floor(E*s),m=Math.floor(x*s);(e.domElement.width!==O||e.domElement.height!==m)&&(e.setPixelRatio(s),e.setSize(E,x,!1),t.aspect=E/x,t.updateProjectionMatrix(),a.updateAspect(E,x),_optionalChain([u, 'optionalCall', _192 => _192(), 'optionalAccess', _193 => _193.setSize, 'call', _194 => _194(E,x,s)]),_optionalChain([f, 'optionalAccess', _195 => _195.setSize, 'call', _196 => _196(E,x)]))},R=function(){p=requestAnimationFrame(R);let E=performance.now(),x=(E-g)/1e3;g=E,y(),(o.enableDamping||o.autoRotate)&&o.update(),c&&c.update(r().position),d&&d.update(x),_optionalChain([l, 'optionalCall', _197 => _197(x)]);let O=r(),m=_optionalChain([u, 'optionalCall', _198 => _198()]);m?(m.setCamera(O),m.render(x)):e.render(n,O),f&&f.render(n,O),d&&d.render(e)};return{animate:R,dispose:()=>{p!==null&&(cancelAnimationFrame(p),p=null)}}}function gn(e,n,t){n.environment.enableEnvironmentLighting?new (0, _HDRLoaderjs.HDRLoader)().load(n.environment.hdrPath||"/baseHDR.hdr",function(r){if(t()){r.dispose();return}if(!_optionalChain([r, 'optionalAccess', _199 => _199.image])){_chunkGF6ZIJWXcjs.e.call(void 0, ).warn("HDR loaded without image data; skipping environment map."),_optionalChain([r, 'optionalAccess', _200 => _200.dispose, 'call', _201 => _201()]),_optionalChain([n, 'access', _202 => _202.events, 'access', _203 => _203.onReady, 'optionalCall', _204 => _204()]);return}r.mapping=h.EquirectangularReflectionMapping,e.environment=r,n.environment.showEnvironment&&(e.background=r),_optionalChain([n, 'access', _205 => _205.events, 'access', _206 => _206.onReady, 'optionalCall', _207 => _207()])},void 0,function(r){t()||(_chunkGF6ZIJWXcjs.e.call(void 0, ).warn("HDR texture could not be loaded, falling back to basic lighting:",r),_optionalChain([n, 'access', _208 => _208.events, 'access', _209 => _209.onReady, 'optionalCall', _210 => _210()]))}):_optionalChain([n, 'access', _211 => _211.events, 'access', _212 => _212.onReady, 'optionalCall', _213 => _213()])}function yn(e,n){let t=new h.AmbientLight(n.lighting.ambientLightColor,n.lighting.ambientLightIntensity);if(e.add(t),!n.lighting.enableSunlight)return null;let r=new h.DirectionalLight(_nullishCoalesce(n.lighting.sunlightColor, () => (16777215)),n.lighting.sunlightIntensity),a=n.lighting.sunlightPosition;return a&&r.position.set(a.x,a.y,a.z),n.render.enableShadows?(r.castShadow=!0,r.shadow.mapSize.width=n.render.shadowMapSize||2048,r.shadow.mapSize.height=n.render.shadowMapSize||2048,r.shadow.bias=-1e-4,r.shadow.normalBias=.02,r.shadow.radius=4,e.add(r),e.add(r.target),r):(e.add(r),null)}function bn(e,n){let t=n.floor.size,r=new h.PlaneGeometry(t,t),a=typeof n.floor.color=="string"?new h.Color(n.floor.color):n.floor.color,o=new h.MeshStandardMaterial({color:a,roughness:n.floor.roughness,metalness:n.floor.metalness,side:h.DoubleSide}),i=new h.Mesh(r,o);i.userData.id="floor",i.name="floor";let s=(_optionalChain([n, 'access', _214 => _214.environment, 'optionalAccess', _215 => _215.sceneUp])||Ee).clone().normalize();i.quaternion.setFromUnitVectors(new h.Vector3(0,0,1),s),i.position.set(0,0,0),n.floor.receiveShadow&&n.render.enableShadows&&(i.receiveShadow=!0),e.add(i)}function Tn(e,n){let t=n.parentElement,r=t?t.clientWidth:window.innerWidth,a=t?t.clientHeight:window.innerHeight,o=new h.PerspectiveCamera(e.camera.fov,r/a,e.camera.near,e.camera.far),i=e.camera.position;return i&&o.position.set(i.x,i.y,i.z),o}function Rn(e,n,t){let r=new h.WebGLRenderer({antialias:n.render.antialias,canvas:e,alpha:!0,powerPreference:"high-performance",preserveDrawingBuffer:n.render.preserveDrawingBuffer,logarithmicDepthBuffer:!1}),a=e.parentElement,o=a?a.clientWidth:window.innerWidth,i=a?a.clientHeight:window.innerHeight;return a&&(e.style.width="100%",e.style.height="100%",e.style.display="block"),r.setSize(o,i,!1),r.setPixelRatio(t),n.render.enableShadows&&(r.shadowMap.enabled=!0,r.shadowMap.type=h.VSMShadowMap),r.toneMapping=n.render.toneMapping,r.toneMappingExposure=_nullishCoalesce(n.render.toneMappingExposure, () => (1)),r.outputColorSpace=h.SRGBColorSpace,r.sortObjects=!0,r}function wn(e,n,t,r){let a=new Set,o=new Map,i=new h.Raycaster,s=new h.Vector2,l=new h.Vector2,c=()=>t.getActiveCamera(),d=m=>{let T=m;for(;T;){if(!T.visible)return!1;T=T.parent}return!0},u=()=>{let m=be(n);if(m.isEmpty()){_chunkGF6ZIJWXcjs.e.call(void 0, ).warn("No objects to fit to view");return}t.frameBounds(m,!1)},f=typeof r.events.selectionColor=="string"?new h.Color(r.events.selectionColor):r.events.selectionColor instanceof h.Color?r.events.selectionColor:new h.Color("#ff0000"),p=()=>{a.forEach(m=>{let T=m;if(o.has(m)){let b=o.get(m),v=T.material;v instanceof h.Material?v.dispose():Array.isArray(v)&&v.forEach(V=>V.dispose()),T.material=b,o.delete(m);let A=m;for(;A.parent;)A=A.parent;A!==n&&(b instanceof h.Material?b.dispose():b.forEach(V=>V.dispose()))}}),a.clear()},g=m=>{let T=m;if(!(T.material instanceof h.Material))return!1;o.set(m,T.material);let b=T.material.clone();return m instanceof h.Mesh&&"emissive"in b?b.emissive=f.clone():"color"in b&&(b.color=f.clone()),T.material=b,!0},y=()=>{let m=be(n),T=m.isEmpty()?1:m.getSize(new h.Vector3).length();i.params.Points.threshold=T*.01},R=m=>{l.set(m.clientX,m.clientY)},w=m=>{let T=new h.Vector2(m.clientX,m.clientY);if(l.distanceTo(T)>5)return;let b=e.getBoundingClientRect();s.x=(m.clientX-b.left)/b.width*2-1,s.y=-((m.clientY-b.top)/b.height)*2+1,y(),i.setFromCamera(s,c());let v=i.intersectObjects(n.children,!0).filter(A=>d(A.object));if(v.length>0){let A=v[0].object;a.has(A)||(p(),a.add(A),g(A),_optionalChain([r, 'access', _216 => _216.events, 'optionalAccess', _217 => _217.onObjectSelected, 'optionalCall', _218 => _218(A)]),A instanceof h.Mesh&&Object.keys(A.userData).length>0&&_optionalChain([r, 'access', _219 => _219.events, 'optionalAccess', _220 => _220.onMeshMetadataClicked, 'optionalCall', _221 => _221(A.userData)]))}else p(),_optionalChain([r, 'access', _222 => _222.events, 'optionalAccess', _223 => _223.onBackgroundClicked, 'optionalCall', _224 => _224({x:s.x,y:s.y})])},E=m=>{let T=e.getBoundingClientRect();s.x=(m.clientX-T.left)/T.width*2-1,s.y=-((m.clientY-T.top)/T.height)*2+1,y(),i.setFromCamera(s,c());let b=i.intersectObjects(n.children,!0).filter(V=>d(V.object));if(b.length===0)return;let v=b[0].object;if(_optionalChain([r, 'access', _225 => _225.events, 'optionalAccess', _226 => _226.onMeshDoubleClicked, 'optionalCall', _227 => _227(v)]),!_optionalChain([r, 'access', _228 => _228.events, 'optionalAccess', _229 => _229.enableDoubleClickZoom]))return;let A=new h.Box3().setFromObject(v);A.isEmpty()||t.frameBounds(A,!0)},x=m=>{if(_optionalChain([r, 'access', _230 => _230.events, 'optionalAccess', _231 => _231.enableKeyboardControls]))switch(m.key.toLowerCase()){case"f":m.preventDefault(),u();break;case"escape":m.preventDefault(),p();break;case" ":m.preventDefault(),u();break}};return _optionalChain([r, 'access', _232 => _232.events, 'optionalAccess', _233 => _233.enableClickToFocus])&&(e.addEventListener("mousedown",R),e.addEventListener("click",w),e.addEventListener("dblclick",E)),_optionalChain([r, 'access', _234 => _234.events, 'optionalAccess', _235 => _235.enableKeyboardControls])&&(e.setAttribute("tabindex","0"),e.addEventListener("keydown",x)),{dispose:()=>{e.removeEventListener("mousedown",R),e.removeEventListener("click",w),e.removeEventListener("dblclick",E),e.removeEventListener("keydown",x),p()},fitToView:u,clearSelection:p}}function vn(e,n,t){let r=new (0, _OrbitControlsjs.OrbitControls)(e,n),a=t.camera.target;return a&&r.target.set(a.x,a.y,a.z),r.enableDamping=t.controls.enableDamping||!1,r.dampingFactor=t.controls.dampingFactor||.05,r.autoRotate=t.controls.autoRotate||!1,r.autoRotateSpeed=t.controls.autoRotateSpeed||.5,r.enableZoom=_nullishCoalesce(t.controls.enableZoom, () => (!0)),r.enablePan=_nullishCoalesce(t.controls.enablePan, () => (!0)),r.minDistance=t.controls.minDistance||.001,r.maxDistance=t.controls.maxDistance||1/0,r.screenSpacePanning=!1,r.maxPolarAngle=Math.PI,r.update(),r}function he(e,n,t,r=!0){return{x:e,y:n,z:t}}var Cn="#ffffff",Ke=12,An=4e-4,Sn=12,Dn=.05;function Je(e,n={}){if(!e||e.length===0)return[];let{rhino:t,applyTransforms:r=!0}=n,a=[];for(let o of e)switch(o.kind){case"curve":{let i=On(o,t,r);i&&a.push(i);break}case"point":{let i=Pn(o,r);i&&a.push(i);break}default:{let s=o;_chunkGF6ZIJWXcjs.e.call(void 0, ).warn(`Skipping unknown display item kind: ${String(s.kind)}`);break}}return a}var Ln=2;function On(e,n,t){if(!n)return _chunkGF6ZIJWXcjs.e.call(void 0, ).warn("No rhino3dm instance provided; skipping curve display item."),null;let r=In(e.json,n);if(!r)return null;let a;try{a=Vn(r,t)}catch(u){return _chunkGF6ZIJWXcjs.e.call(void 0, ).warn("Failed to tessellate curve display item; skipping.",u),null}finally{ie(r)}if(a.length<2)return null;let o=[];for(let u of a)o.push(u.x,u.y,u.z);let i=new _LineGeometryjs.LineGeometry;i.setPositions(o);let s=Qe(e.color,e.opacity),l=new (0, _LineMaterialjs.LineMaterial)({color:s.color}),c=l;c.linewidth=_nullishCoalesce(e.width, () => (Ln)),c.transparent=s.transparent,c.opacity=s.opacity;let d=new (0, _Line2js.Line2)(i,l);return d.computeLineDistances(),d.name=e.name,d.userData={source:"compute",id:e.id,layer:e.layer,kind:"curve",metadata:e.metadata},d}function Pn(e,n){let{position:t}=e;if(!t||typeof t.X!="number"||!Number.isFinite(t.X)||typeof t.Y!="number"||!Number.isFinite(t.Y)||typeof t.Z!="number"||!Number.isFinite(t.Z))return _chunkGF6ZIJWXcjs.e.call(void 0, ).warn(`Skipping point display item with missing or non-finite position (id: ${String(e.id)}).`),null;let{x:r,y:a,z:o}=he(t.X,t.Y,t.Z,n),i=new W.BufferGeometry;i.setAttribute("position",new W.Float32BufferAttribute([r,a,o],3));let s=new W.PointsMaterial({...Qe(e.color,e.opacity),size:6,sizeAttenuation:!1}),l=new W.Points(i,s);return l.name=e.name,l.userData={source:"compute",id:e.id,layer:e.layer,kind:"point",metadata:e.metadata},l}function ie(e){_optionalChain([e, 'optionalAccess', _236 => _236.delete, 'optionalCall', _237 => _237()])}function In(e,n){try{let t=JSON.parse(e),r=n.CommonObject.decode(t);return r&&typeof r.pointAt=="function"?r:(ie(r),_chunkGF6ZIJWXcjs.e.call(void 0, ).warn("Decoded display-item JSON is not a curve; skipping."),null)}catch(t){return _chunkGF6ZIJWXcjs.e.call(void 0, ).warn("Failed to decode curve display item JSON:",t),null}}function Vn(e,n){let t=Bn(e,n);return t||Fn(e,n)}function Bn(e,n){if(!e.isPolyline())return null;let t=e.tryGetPolyline(),r=Array.isArray(t)?t[1]:t;if(!r||typeof r.count!="number"||r.count<2)return ie(r),null;let a=[];for(let o=0;o<r.count;o++){let i=r.get(o),{x:s,y:l,z:c}=he(i[0],i[1],i[2],n);a.push(new W.Vector3(s,l,c))}return ie(r),a}function Fn(e,n){let t=e.domain,r=t[0],o=t[1]-r,i=u=>{let f=e.pointAt(u),{x:p,y:g,z:y}=he(f[0],f[1],f[2],n);return new W.Vector3(p,g,y)},s=Un(e),l=r,c=i(r),d=[c];for(let u=0;u<Ke;u++){let f=r+o*(u+1)/Ke,p=i(f);Re(l,c,f,p,i,s,Sn,d),d.push(p),l=f,c=p}return d}function Re(e,n,t,r,a,o,i,s){if(i<=0)return;let l=(e+t)/2,c=a(l),d=_n(c,n,r),u=zn(n,c,r);d<=o&&u<=Dn||(Re(e,n,l,c,a,o,i-1,s),s.push(c),Re(l,c,t,r,a,o,i-1,s))}function Un(e){let n=e.getBoundingBox(),t=n.min,r=n.max;ie(n);let a=Math.hypot(r[0]-t[0],r[1]-t[1],r[2]-t[2]);return Math.max(a*An,1e-6)}function zn(e,n,t){let r=n.x-e.x,a=n.y-e.y,o=n.z-e.z,i=t.x-n.x,s=t.y-n.y,l=t.z-n.z,c=Math.sqrt(r*r+a*a+o*o),d=Math.sqrt(i*i+s*s+l*l);if(c===0||d===0)return 0;let u=r*i+a*s+o*l,f=Math.max(-1,Math.min(1,u/(c*d)));return Math.acos(f)}function _n(e,n,t){let r=t.x-n.x,a=t.y-n.y,o=t.z-n.z,i=r*r+a*a+o*o;if(i===0)return e.distanceTo(n);let s=e.x-n.x,l=e.y-n.y,c=e.z-n.z,d=Math.max(0,Math.min(1,(s*r+l*a+c*o)/i)),u=s-r*d,f=l-a*d,p=c-o*d;return Math.sqrt(u*u+f*f+p*p)}function Qe(e,n){let t=_nullishCoalesce(n, () => (1));return{color:new W.Color(_nullishCoalesce(e, () => (Cn))),transparent:t<1,opacity:t}}var _fflate = require('fflate');var et=1096174675,jn= exports.x =1515605075,tt= exports.y =3,nt= exports.z =1,ve= exports.A =1,Gn= exports.B =2,Nn= exports.C =4,Wn= exports.D =8,$n= exports.E =16,Mo= exports.F =0,Yn= exports.G =1,rt=12,ot=56,Xn=new Uint16Array(new Uint8Array([1,0]).buffer)[0]===1;function xe(e){if(!Xn)throw new (0, _chunkGF6ZIJWXcjs.d)("SLVA parsing requires a little-endian host: the zero-copy geometry readers view the wire bytes in host byte order.",_chunkGF6ZIJWXcjs.c.ENVIRONMENT_ERROR);let n=Jn(Kn(e)),t=new DataView(n.buffer,n.byteOffset,n.byteLength);if(n.byteLength<rt)throw j("Blob too small to contain SLVA header.",{expectedBytes:rt,availableBytes:n.byteLength});let r=0,a=t.getUint32(r,!0);if(r+=4,a!==et)throw j(`Invalid SLVA magic: 0x${a.toString(16)}`,{expectedMagic:`0x${et.toString(16)}`,actualMagic:`0x${a.toString(16)}`});let o=t.getUint32(r,!0);if(r+=4,o<nt||o>tt)throw j(`Unsupported SLVA version: ${o}`,{minSupportedVersion:nt,maxSupportedVersion:tt,actualVersion:o});let i=t.getUint32(r,!0);if(r+=4,r+i>n.byteLength)throw j("Insufficient data to read metadata JSON.",{expectedBytes:i,availableBytes:n.byteLength-r,offset:r});let s=n.subarray(r,r+i);r+=i;let l;try{l=JSON.parse(Qn(s))}catch(q){throw j(`Failed to parse metadata JSON: ${q instanceof Error?q.message:String(q)}`,{metadataLen:i})}if(r+ot>n.byteLength)throw j("Insufficient data to read geometry header.",{expectedBytes:ot,availableBytes:n.byteLength-r,offset:r});let c=t.getUint32(r,!0);r+=4;let d=t.getFloat64(r,!0);r+=8;let u=t.getFloat64(r,!0);r+=8;let f=t.getFloat64(r,!0);r+=8;let p=t.getFloat64(r,!0);r+=8;let g=t.getFloat64(r,!0);r+=8;let y=t.getFloat64(r,!0);r+=8;let R=t.getUint32(r,!0);r+=4;let w=(c&ve)!==0,E=(c&Nn)!==0,x=R*3,m=x*(w?4:2);if(r+m>n.byteLength)throw j("Insufficient data to read vertices.",{expectedBytes:m,availableBytes:n.byteLength-r,offset:r,useFloat32:w,vertexCount:R});let T=n.byteOffset+r,b;if(w?b=it(n.buffer,T,x):E?b=rr(we(n.buffer,T,x)):b=er(n.buffer,T,x),r+=m,r+4>n.byteLength)throw j("Insufficient data to read index count.",{expectedBytes:4,availableBytes:n.byteLength-r,offset:r});let v=t.getUint32(r,!0);r+=4;let A=(c&Gn)!==0,$=v*(A?2:4);if(r+$>n.byteLength)throw j("Insufficient data to read indices.",{expectedBytes:$,availableBytes:n.byteLength-r,offset:r,indexCount:v,useUint16Indices:A});let B=A?we(n.buffer,n.byteOffset+r,v):tr(n.buffer,n.byteOffset+r,v);E&&(B=B instanceof Uint16Array?or(B):ar(B)),nr(B,R),r+=$;let Y=null;if((c&Wn)!==0){let q=qn(n,t,r,R,E);Y=q.uvs,r=q.offset}let G=null;return(c&$n)!==0&&(G=Zn(n,r,R,E)),{metadata:l,flags:c,vertices:b,indices:B,origin:[d,u,f],scale:[p,g,y],uvs:Y,colors:G}}var at=36;function qn(e,n,t,r,a){if(t+at>e.byteLength)throw j("Insufficient data to read UV chunk header.",{expectedBytes:at,availableBytes:e.byteLength-t,offset:t});let o=n.getUint32(t,!0);t+=4;let i=n.getFloat64(t,!0);t+=8;let s=n.getFloat64(t,!0);t+=8;let l=n.getFloat64(t,!0);t+=8;let c=n.getFloat64(t,!0);t+=8;let d=r*2,u=o===Yn,f=d*(u?4:2);if(t+f>e.byteLength)throw j("Insufficient data to read UV chunk.",{expectedBytes:f,availableBytes:e.byteLength-t,offset:t,uvFormat:o,vertexCount:r});let p=e.byteOffset+t,g;if(u)g=it(e.buffer,p,d).slice();else{let y=we(e.buffer,p,d);g=new Float32Array(d);let R=0,w=0;for(let E=0;E<d;E+=2)a?(R=R+K(y[E])&65535,w=w+K(y[E+1])&65535):(R=y[E],w=y[E+1]),g[E]=i+R*l,g[E+1]=s+w*c}return{uvs:g,offset:t+f}}function Zn(e,n,t,r){let a=t*3;if(n+a>e.byteLength)throw j("Insufficient data to read vertex-color chunk.",{expectedBytes:a,availableBytes:e.byteLength-n,offset:n,vertexCount:t});let o=e.subarray(n,n+a);if(!r)return o.slice();let i=new Uint8Array(a),s=0,l=0,c=0;for(let d=0;d<a;d+=3)s=s+K(o[d])&255,l=l+K(o[d+1])&255,c=c+K(o[d+2])&255,i[d]=s,i[d+1]=l,i[d+2]=c;return i}function Kn(e){return typeof e=="string"?_chunkGF6ZIJWXcjs.j.call(void 0, e):e instanceof Uint8Array?e:new Uint8Array(e)}function Jn(e){if(e.byteLength<8)return e;let n=new DataView(e.buffer,e.byteOffset,e.byteLength);if(n.getUint32(0,!0)!==jn)return e;let t=n.getUint32(4,!0),r=e.subarray(8),a=Math.max(r.byteLength*1032+1024,1<<20);if(t>a)throw j("SLVZ header declares an implausible uncompressed length",{uncompressedLen:t,deflatedBytes:r.byteLength,maxPlausibleLen:a});let o;try{o=_fflate.inflateSync.call(void 0, r,{out:new Uint8Array(t+1)})}catch(i){throw j(`Failed to inflate SLVZ blob: ${i instanceof Error?i.message:String(i)}`,{uncompressedLen:t,deflatedBytes:r.byteLength})}if(o.byteLength!==t)throw j("SLVZ payload inflated to a different size than the header declares.",{declaredLen:t,actualLen:o.byteLength,deflatedBytes:r.byteLength});return o}function Qn(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, _chunkGF6ZIJWXcjs.d)("No UTF-8 decoder available in this environment.",_chunkGF6ZIJWXcjs.c.INVALID_STATE)}function er(e,n,t){if(t===0)return new Int16Array(0);if(n%2===0)return new Int16Array(e,n,t);let r=new Uint8Array(t*2);return r.set(new Uint8Array(e,n,t*2)),new Int16Array(r.buffer)}function it(e,n,t){if(t===0)return new Float32Array(0);if(n%4===0)return new Float32Array(e,n,t);let r=new Uint8Array(t*4);return r.set(new Uint8Array(e,n,t*4)),new Float32Array(r.buffer)}function we(e,n,t){if(t===0)return new Uint16Array(0);if(n%2===0)return new Uint16Array(e,n,t);let r=new Uint8Array(t*2);return r.set(new Uint8Array(e,n,t*2)),new Uint16Array(r.buffer)}function tr(e,n,t){if(t===0)return new Uint32Array(0);if(n%4===0)return new Uint32Array(e,n,t);let r=new Uint8Array(t*4);return r.set(new Uint8Array(e,n,t*4)),new Uint32Array(r.buffer)}function nr(e,n){if(e.length!==0&&!(e instanceof Uint16Array&&n>65535)){for(let t=0;t<e.length;t++)if(e[t]>=n)throw j("Index out of range of vertexCount.",{indexPosition:t,indexValue:e[t],vertexCount:n})}}function K(e){return e>>>1^-(e&1)}function rr(e){let n=new Int16Array(e.length),t=0,r=0,a=0;for(let o=0;o<e.length;o+=3)t=t+K(e[o])<<16>>16,r=r+K(e[o+1])<<16>>16,a=a+K(e[o+2])<<16>>16,n[o]=t,n[o+1]=r,n[o+2]=a;return n}function or(e){let n=new Uint16Array(e.length),t=0;for(let r=0;r<e.length;r++)t=t+K(e[r])&65535,n[r]=t;return n}function ar(e){let n=new Uint32Array(e.length),t=0;for(let r=0;r<e.length;r++)t=t+K(e[r])>>>0,n[r]=t;return n}function j(e,n){return new (0, _chunkGF6ZIJWXcjs.d)(e,_chunkGF6ZIJWXcjs.c.VALIDATION_ERROR,{context:n})}async function Po(e,n){let{debug:t=!1}=_nullishCoalesce(n, () => ({})),r=t?performance.now():0,a,o=performance.now();try{a=JSON.parse(e)}catch(s){return _chunkGF6ZIJWXcjs.e.call(void 0, ).error("Error parsing mesh batch envelope JSON:",s),[]}let i=performance.now()-o;return await He(a,n,{parseTime:i,perfStart:r})}async function He(e,n,t){let{mergeByMaterial:r=!0,applyTransforms:a=!0,debug:o=!1,material:i}=_nullishCoalesce(n, () => ({})),{parseTime:s=0,perfStart:l=o?performance.now():0}=_nullishCoalesce(t, () => ({}));if(!e.compressedData)return[];let c=performance.now(),d=xe(e.compressedData),u=performance.now()-c,f=o?fr(e.compressedData):0;return st(d,{mergeByMaterial:r,applyTransforms:a,debug:o,material:i,parseTime:s,decodeTime:u,perfStart:l,blobBytes:f,fallback:{materials:e.materials,groups:e.groups,sourceComponentId:e.sourceComponentId}})}async function Io(e,n){let{mergeByMaterial:t=!0,applyTransforms:r=!0,debug:a=!1,material:o}=_nullishCoalesce(n, () => ({})),i=a?performance.now():0,s=performance.now(),l=xe(e),c=performance.now()-s,d=e.byteLength;return st(l,{mergeByMaterial:t,applyTransforms:r,debug:a,material:o,parseTime:0,decodeTime:c,perfStart:i,blobBytes:d})}function st(e,n){let{mergeByMaterial:t,applyTransforms:r,debug:a,material:o,parseTime:i,decodeTime:s,perfStart:l,blobBytes:c,fallback:d}=n,u=_nullishCoalesce(_nullishCoalesce(e.metadata.materials, () => (_optionalChain([d, 'optionalAccess', _238 => _238.materials]))), () => ([])),f=_nullishCoalesce(_nullishCoalesce(e.metadata.groups, () => (_optionalChain([d, 'optionalAccess', _239 => _239.groups]))), () => ([])),p=_nullishCoalesce(_optionalChain([d, 'optionalAccess', _240 => _240.sourceComponentId]), () => (e.metadata.sourceComponentId)),g=(e.flags&ve)!==0;ir(f,u.length,e.vertices.length/3,e.indices.length);let y=g?lr(e.vertices,r):sr(e.vertices,e.origin,e.scale,r);if(a){let O=e.vertices.byteLength+e.indices.byteLength;_chunkGF6ZIJWXcjs.e.call(void 0, ).debug("Mesh Batch Stats:"),_chunkGF6ZIJWXcjs.e.call(void 0, ).debug(` Materials: ${u.length} | Groups: ${f.length}`),_chunkGF6ZIJWXcjs.e.call(void 0, ).debug(` Vertices: ${e.vertices.length/3} | Indices: ${e.indices.length}`),_chunkGF6ZIJWXcjs.e.call(void 0, ).debug(` Format: ${g?"float32":"int16 quantized"}`),_chunkGF6ZIJWXcjs.e.call(void 0, ).debug(` Blob: ${(c/1024/1024).toFixed(2)} MB | Geometry on wire: ${(O/1024/1024).toFixed(2)} MB`)}let R=performance.now(),w=u.map(O=>cr(O,{vertexColors:e.colors!=null,appearance:o})),E=[];for(let O of f)if(t&&O.meshes.length>1){let m=dr(O,y,e.indices,w,e.uvs,e.colors);m.userData.sourceComponentId=_nullishCoalesce(p, () => (null)),E.push(m)}else{let m=mr(O,y,e.indices,w,e.uvs,e.colors);for(let T of m)T.userData.sourceComponentId=_nullishCoalesce(p, () => (null));E.push(...m)}let x=performance.now()-R;if(a){let O=performance.now()-l;_chunkGF6ZIJWXcjs.e.call(void 0, ).debug("Performance:"),i>0&&_chunkGF6ZIJWXcjs.e.call(void 0, ).debug(` Parse JSON: ${i.toFixed(2)}ms`),_chunkGF6ZIJWXcjs.e.call(void 0, ).debug(` Decode binary: ${s.toFixed(2)}ms`),_chunkGF6ZIJWXcjs.e.call(void 0, ).debug(` Create Meshes: ${x.toFixed(2)}ms`),_chunkGF6ZIJWXcjs.e.call(void 0, ).debug(` Total: ${O.toFixed(2)}ms`)}return Promise.resolve(E)}function se(e,n){return new (0, _chunkGF6ZIJWXcjs.d)(e,_chunkGF6ZIJWXcjs.c.VALIDATION_ERROR,{context:n})}function ir(e,n,t,r){for(let a of e){if(!Number.isInteger(a.materialId)||a.materialId<0||a.materialId>=n)throw se("Group materialId out of range of the materials array.",{materialId:a.materialId,materialCount:n});for(let o of a.meshes){let i={vertexStart:o.vertexStart,vertexCount:o.vertexCount,indexStart:o.indexStart,indexCount:o.indexCount};for(let[s,l]of Object.entries(i))if(!Number.isInteger(l)||l<0)throw se(`Mesh metadata field "${s}" must be a non-negative integer.`,{meshName:o.name,field:s,value:l});if(o.vertexStart+o.vertexCount>t)throw se("Mesh vertex window exceeds the batch vertex buffer.",{meshName:o.name,vertexStart:o.vertexStart,vertexCount:o.vertexCount,totalVertexCount:t});if(o.indexStart+o.indexCount>r)throw se("Mesh index window exceeds the batch index buffer.",{meshName:o.name,indexStart:o.indexStart,indexCount:o.indexCount,totalIndexCount:r})}}}function lt(e,n){if(e<n.vertexStart||e>=n.vertexStart+n.vertexCount)throw se("Index references a vertex outside its mesh's vertex window.",{meshName:n.name,indexValue:e,vertexStart:n.vertexStart,vertexCount:n.vertexCount})}function sr(e,n,t,r){let a=new Float32Array(e.length),o=n[0],i=n[1],s=n[2],l=t[0],c=t[1],d=t[2];for(let u=0;u<e.length;u+=3)a[u]=o+(e[u]+32767)*l,a[u+1]=i+(e[u+1]+32767)*c,a[u+2]=s+(e[u+2]+32767)*d;return a}function lr(e,n){return e}function cr(e,n){let t=Be(e.color),r=_nullishCoalesce(_optionalChain([n, 'optionalAccess', _241 => _241.vertexColors]), () => (!1)),a=_optionalChain([n, 'optionalAccess', _242 => _242.appearance]),o=new I.MeshPhysicalMaterial({color:t,metalness:e.metalness,roughness:e.roughness,opacity:e.opacity,transparent:e.transparent,vertexColors:r,side:_optionalChain([a, 'optionalAccess', _243 => _243.cullBackfaces])?I.FrontSide:I.DoubleSide,polygonOffset:!0,polygonOffsetFactor:.5,polygonOffsetUnits:.5,depthWrite:!0,depthTest:!0});return _optionalChain([a, 'optionalAccess', _244 => _244.envMapIntensity])!=null&&(o.envMapIntensity=a.envMapIntensity),r&&ur(o),e.map&&Ze(o,e.map),o}function ur(e){e.onBeforeCompile=n=>{n.vertexShader=n.vertexShader.replace("#include <color_vertex>",`#include <color_vertex>
|
|
55
|
+
#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )
|
|
56
|
+
vColor.rgb = mix(
|
|
57
|
+
vColor.rgb / 12.92,
|
|
58
|
+
pow( ( vColor.rgb + 0.055 ) / 1.055, vec3( 2.4 ) ),
|
|
59
|
+
step( vec3( 0.04045 ), vColor.rgb )
|
|
60
|
+
);
|
|
61
|
+
#endif`)}}function dr(e,n,t,r,a=null,o=null){let i=0,s=0;for(let E of e.meshes)i+=E.vertexCount,s+=E.indexCount;let l=new Float32Array(i*3),c=new Uint32Array(s),d=a?new Float32Array(i*2):null,u=o?new Uint8Array(i*3):null,f=0,p=0;for(let E of e.meshes){let x=E.vertexStart*3,O=E.vertexCount*3;if(l.set(n.subarray(x,x+O),f*3),d&&a){let b=E.vertexStart*2;d.set(a.subarray(b,b+E.vertexCount*2),f*2)}u&&o&&u.set(o.subarray(x,x+O),f*3);let m=t.subarray(E.indexStart,E.indexStart+E.indexCount),T=f-E.vertexStart;for(let b=0;b<m.length;b++){let v=m[b];lt(v,E),c[p+b]=v+T}f+=E.vertexCount,p+=E.indexCount}let g=new I.BufferGeometry;g.setAttribute("position",new I.BufferAttribute(l,3)),g.setIndex(new I.BufferAttribute(c,1)),d&&g.setAttribute("uv",new I.BufferAttribute(d,2)),u&&g.setAttribute("color",new I.BufferAttribute(u,3,!0)),g.computeVertexNormals();let y=new I.Mesh(g,r[e.materialId]),R=e.meshes[0],w=e.meshes.map(E=>E.name).filter(E=>E&&E.length>0);return y.name=w.length>0?w[0]:`merged_material_${e.materialId}`,y.castShadow=!0,y.receiveShadow=!0,y.userData={source:"compute",name:y.name,layer:_nullishCoalesce(_optionalChain([R, 'optionalAccess', _245 => _245.layer]), () => ("")),originalIndex:_nullishCoalesce(_optionalChain([R, 'optionalAccess', _246 => _246.originalIndex]), () => (0)),metadata:_nullishCoalesce(_optionalChain([R, 'optionalAccess', _247 => _247.metadata]), () => ({})),mergedFrom:e.meshes.slice(1).map(E=>({name:E.name,layer:E.layer,originalIndex:E.originalIndex}))},y}function mr(e,n,t,r,a=null,o=null){let i=[];for(let s of e.meshes){let l=s.vertexStart*3,c=s.vertexCount*3,d=n.slice(l,l+c),u=t.subarray(s.indexStart,s.indexStart+s.indexCount),f=new Uint32Array(u.length),p=s.vertexStart;for(let R=0;R<u.length;R++){let w=u[R];lt(w,s),f[R]=w-p}let g=new I.BufferGeometry;if(g.setAttribute("position",new I.BufferAttribute(d,3)),g.setIndex(new I.BufferAttribute(f,1)),a){let R=s.vertexStart*2,w=a.slice(R,R+s.vertexCount*2);g.setAttribute("uv",new I.BufferAttribute(w,2))}if(o){let R=o.slice(l,l+c);g.setAttribute("color",new I.BufferAttribute(R,3,!0))}g.computeVertexNormals();let y=new I.Mesh(g,r[e.materialId]);y.name=s.name,y.userData={source:"compute",name:s.name,layer:_nullishCoalesce(s.layer, () => ("")),originalIndex:s.originalIndex,metadata:_nullishCoalesce(s.metadata, () => ({}))},y.castShadow=!0,y.receiveShadow=!0,i.push(y)}return i}function fr(e){return Math.floor(e.length*3/4)}var ct={Angstroms:1e-10,Nanometers:1e-9,Microns:1e-6,Millimeters:.001,Centimeters:.01,Decimeters:.1,Meters:1,Dekameters:10,Hectometers:100,Kilometers:1e3,Megameters:1e6,Gigameters:1e9,Microinches:254e-10,Mils:254e-7,Inches:.0254,Feet:.3048,Yards:.9144,Miles:1609.344,NauticalMiles:1852},pr="Display",Er="DisplayBatch";function hr(e){let n=e.split(".");return n.includes(pr)||n.includes(Er)}var ut=new Set;async function _o(e,n){let t=performance.now(),r=[],{allowScaling:a=!0,allowAutoPosition:o=!0,rhino:i,debug:s=!1,parsing:l={}}=_nullishCoalesce(n, () => ({}));try{let c=a?gr(e.modelunits):1;return await yr(e,r,c,l,i,s),o&&wr(r),r}catch(c){throw vr(c,r),c}finally{s&&Hr(t)}}function gr(e){let n=ct[e];return n!==void 0?n:(ut.has(e)||(ut.add(e),_chunkGF6ZIJWXcjs.e.call(void 0, ).warn(`Unknown Rhino model unit "${e}" \u2014 geometry will not be scaled (factor 1). Known units: ${Object.keys(ct).join(", ")}.`)),1)}async function yr(e,n,t,r,a,o){for(let i of e.values){let s=i.InnerTree;for(let l in s){let c=s[l];c&&await br(c,n,t,r,a,o)}}}async function br(e,n,t,r,a,o){for(let i of e){if(!hr(i.type))continue;let s={mergeByMaterial:!0,applyTransforms:!0,debug:!1,...r},l=Tr(i.data);if(!l){_chunkGF6ZIJWXcjs.e.call(void 0, ).error("Error parsing display batch envelope: invalid JSON");continue}let c=await He(l,s),d=Je(l.items,{rhino:a,applyTransforms:s.applyTransforms}),u=[...c,...d];if(t!==1)for(let f of u)f.scale.set(t,t,t);n.push(...u),o&&_chunkGF6ZIJWXcjs.e.call(void 0, ).debug(`Extracted ${c.length} meshes and ${d.length} items from batch`)}}function Tr(e){return typeof e=="string"?Rr(e):e}function Rr(e){try{return JSON.parse(e)}catch (e3){return}}function wr(e){if(e.length===0)return;let n=oe(e);Fe(e,n.min.z,"z")}function vr(e,n){_chunkGF6ZIJWXcjs.e.call(void 0, ).error("An unexpected error occurred:",e),xr(n)}function xr(e){for(let n of e){let t=n;t.geometry&&t.geometry.dispose(),t.material&&(Array.isArray(t.material)?t.material.forEach(r=>r.dispose()):t.material.dispose())}}function Hr(e){let n=performance.now()-e;_chunkGF6ZIJWXcjs.e.call(void 0, ).info("Time to process meshes:",`${n.toFixed(2)}ms`)}exports.a = ht; exports.b = Sr; exports.c = Be; exports.d = Fe; exports.e = oe; exports.f = Ue; exports.g = ze; exports.h = _e; exports.i = ce; exports.j = je; exports.k = Ft; exports.l = zr; exports.m = Ge; exports.n = We; exports.o = Qt; exports.p = Xe; exports.q = en; exports.r = qe; exports.s = eo; exports.t = cn; exports.u = po; exports.v = Je; exports.w = et; exports.x = jn; exports.y = tt; exports.z = nt; exports.A = ve; exports.B = Gn; exports.C = Nn; exports.D = Wn; exports.E = $n; exports.F = Mo; exports.G = Yn; exports.H = xe; exports.I = Po; exports.J = He; exports.K = Io; exports.L = ct; exports.M = _o;
|
|
62
|
+
//# sourceMappingURL=chunk-EZRBMUXT.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/selva-compute/selva-compute/dist/chunk-EZRBMUXT.cjs","../src/features/visualization/threejs/three-materials.ts","../src/features/visualization/threejs/three-helpers.ts","../src/features/visualization/threejs/grid.ts","../src/features/visualization/threejs/edges.ts","../src/features/visualization/threejs/three-initializer.ts","../src/features/visualization/webdisplay/batch-parser.ts","../src/features/visualization/webdisplay/webdisplay-parser.ts"],"names":["three_materials_exports","__export","CONCRETE_MATERIAL","EMISSIVE_MATERIAL","GLASS_MATERIAL","METAL_MATERIAL","PLASTIC_MATERIAL","RUBBER_MATERIAL","SHARED_MATERIALS","WOOD_MATERIAL","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,ICAxEA,EAAAA,CAAA,CAAA,CAAA,CAAAC,iCAAAA,EAAAD,CAAA,CAAA,iBAAA,CAAA,CAAA,CAAA,EAAAE,EAAAA,CAAA,iBAAA,CAAA,CAAA,CAAA,EAAAC,EAAAA,CAAA,cAAA,CAAA,CAAA,CAAA,EAAAC,EAAAA,CAAA,cAAA,CAAA,CAAA,CAAA,EAAAC,EAAAA,CAAA,gBAAA,CAAA,CAAA,CAAA,EAAAC,EAAAA,CAAA,eAAA,CAAA,CAAA,CAAA,EAAAC,EAAAA,CAAA,gBAAA,CAAA,CAAA,CAAA,EAAAC,EAAAA,CAAA,aAAA,CAAA,CAAA,CAAA,EAAAC,EAAAA,CAAAA,CAAAA,CAAA,6gBAAuB,IAEVN,EAAAA,CAAoB,IAAU,CAAA,CAAA,oBAAA,CAAqB,CAC/D,KAAA,CAAO,CAAA,CACP,QAAA,CAAU,IAAU,CAAA,CAAA,KAAA,CAAM,QAAQ,CAAA,CAClC,iBAAA,CAAmB,CAAA,CACnB,SAAA,CAAW,CAAA,CACX,SAAA,CAAW,EAAA,CACX,SAAA,CAAW,EAAA,CACX,kBAAA,CAAoB,EAAA,CACpB,UAAA,CAAY,CAAA,CAAA,CACZ,SAAA,CAAW,CAAA,CAAA,CACX,WAAA,CAAa,CAAA,CAAA,CACb,SAAA,CAAW,CAAA,CACX,aAAA,CAAe,CAAA,CAAA,CACf,mBAAA,CAAqB,CAAA,CACrB,kBAAA,CAAoB,CAAA,CACpB,IAAA,CAAY,CAAA,CAAA,SAAA,CACZ,SAAA,CAAW,CAAA,CACZ,CAAC,CAAA,CAEYE,EAAAA,CAAiB,IAAU,CAAA,CAAA,oBAAA,CAAqB,CAC5D,KAAA,CAAO,IAAU,CAAA,CAAA,KAAA,CAAM,CAAQ,CAAA,CAC/B,SAAA,CAAW,EAAA,CACX,SAAA,CAAW,EAAA,CACX,eAAA,CAAiB,GAAA,CACjB,SAAA,CAAW,EAAA,CACX,kBAAA,CAAoB,EAAA,CACpB,YAAA,CAAc,CAAA,CACd,GAAA,CAAK,GAAA,CACL,SAAA,CAAW,CAAA,CACX,UAAA,CAAY,CAAA,CAAA,CACZ,WAAA,CAAa,CAAA,CAAA,CACb,SAAA,CAAW,CAAA,CACX,SAAA,CAAW,CAAA,CAAA,CACX,aAAA,CAAe,CAAA,CAAA,CACf,mBAAA,CAAqB,CAAA,CACrB,kBAAA,CAAoB,CAAA,CACpB,IAAA,CAAY,CAAA,CAAA,SAAA,CACZ,SAAA,CAAW,CAAA,CACZ,CAAC,CAAA,CAEYH,EAAAA,CAAoB,IAAU,CAAA,CAAA,oBAAA,CAAqB,CAC/D,KAAA,CAAO,IAAU,CAAA,CAAA,KAAA,CAAM,QAAQ,CAAA,CAC/B,SAAA,CAAW,CAAA,CACX,SAAA,CAAW,GAAA,CACX,eAAA,CAAiB,GAAA,CACjB,SAAA,CAAW,GAAA,CACX,kBAAA,CAAoB,EAAA,CACpB,YAAA,CAAc,GAAA,CACd,YAAA,CAAc,CAAA,CACd,GAAA,CAAK,IAAA,CACL,SAAA,CAAW,CAAA,CACX,UAAA,CAAY,CAAA,CAAA,CACZ,WAAA,CAAa,CAAA,CAAA,CAGb,SAAA,CAAW,CAAA,CACX,SAAA,CAAW,CAAA,CAAA,CACX,aAAA,CAAe,CAAA,CAAA,CACf,mBAAA,CAAqB,CAAA,CACrB,kBAAA,CAAoB,CAAA,CACpB,IAAA,CAAY,CAAA,CAAA,SAAA,CACZ,SAAA,CAAW,CAAA,CACZ,CAAC,CAAA,CAEYI,EAAAA,CAAmB,IAAU,CAAA,CAAA,oBAAA,CAAqB,CAC9D,KAAA,CAAO,IAAU,CAAA,CAAA,KAAA,CAAM,QAAQ,CAAA,CAC/B,SAAA,CAAW,CAAA,CACX,SAAA,CAAW,EAAA,CACX,eAAA,CAAiB,EAAA,CACjB,SAAA,CAAW,EAAA,CACX,kBAAA,CAAoB,EAAA,CACpB,YAAA,CAAc,EAAA,CACd,GAAA,CAAK,GAAA,CACL,YAAA,CAAc,CAAA,CACd,WAAA,CAAa,CAAA,CAAA,CACb,UAAA,CAAY,CAAA,CAAA,CACZ,IAAA,CAAY,CAAA,CAAA,SAAA,CACZ,SAAA,CAAW,CAAA,CAAA,CACX,aAAA,CAAe,CAAA,CAAA,CACf,mBAAA,CAAqB,CAAA,CACrB,kBAAA,CAAoB,CACrB,CAAC,CAAA,CAEYF,EAAAA,CAAiB,IAAU,CAAA,CAAA,oBAAA,CAAqB,CAC5D,KAAA,CAAO,IAAU,CAAA,CAAA,KAAA,CAAM,QAAQ,CAAA,CAC/B,SAAA,CAAW,CAAA,CACX,SAAA,CAAW,CAAA,CAGX,YAAA,CAAc,GAAA,CACd,WAAA,CAAa,CAAA,CAAA,CAGb,UAAA,CAAY,CAAA,CAAA,CACZ,eAAA,CAAiB,CAAA,CACjB,SAAA,CAAW,CAAA,CACX,kBAAA,CAAoB,CAAA,CACpB,GAAA,CAAK,IAAA,CACL,YAAA,CAAc,EAAA,CACd,SAAA,CAAW,CAAA,CACX,IAAA,CAAY,CAAA,CAAA,UAAA,CACZ,aAAA,CAAe,CAAA,CAAA,CACf,mBAAA,CAAqB,CAAA,CACrB,kBAAA,CAAoB,CACrB,CAAC,CAAA,CAEYG,EAAAA,CAAkB,IAAU,CAAA,CAAA,oBAAA,CAAqB,CAC7D,KAAA,CAAO,IAAU,CAAA,CAAA,KAAA,CAAM,OAAQ,CAAA,CAC/B,SAAA,CAAW,CAAA,CACX,SAAA,CAAW,EAAA,CACX,eAAA,CAAiB,EAAA,CACjB,SAAA,CAAW,EAAA,CACX,kBAAA,CAAoB,EAAA,CACpB,YAAA,CAAc,EAAA,CACd,GAAA,CAAK,GAAA,CACL,YAAA,CAAc,CAAA,CACd,UAAA,CAAY,CAAA,CAAA,CACZ,IAAA,CAAY,CAAA,CAAA,SAAA,CACZ,aAAA,CAAe,CAAA,CAAA,CACf,mBAAA,CAAqB,CAAA,CACrB,kBAAA,CAAoB,CACrB,CAAC,CAAA,CAEYE,EAAAA,CAAgB,IAAU,CAAA,CAAA,oBAAA,CAAqB,CAC3D,KAAA,CAAO,IAAU,CAAA,CAAA,KAAA,CAAM,OAAQ,CAAA,CAC/B,SAAA,CAAW,CAAA,CACX,SAAA,CAAW,EAAA,CACX,eAAA,CAAiB,EAAA,CACjB,SAAA,CAAW,EAAA,CACX,kBAAA,CAAoB,EAAA,CACpB,YAAA,CAAc,EAAA,CACd,GAAA,CAAK,GAAA,CACL,YAAA,CAAc,CAAA,CACd,UAAA,CAAY,CAAA,CAAA,CACZ,IAAA,CAAY,CAAA,CAAA,SAAA,CACZ,SAAA,CAAW,CAAA,CAAA,CACX,aAAA,CAAe,CAAA,CAAA,CACf,mBAAA,CAAqB,CAAA,CACrB,kBAAA,CAAoB,CACrB,CAAC,CAAA,CAQYD,EAAAA,CAAgD,IAAI,GAAA,CAAoB,CACpFL,EAAAA,CACAE,EAAAA,CACAH,EAAAA,CACAI,EAAAA,CACAF,EAAAA,CACAG,EAAAA,CACAE,EACD,CAAC,CAAA,CC7JD,IAOMC,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,EAAAA,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,CA0B9C,EAAA,CAtBmBC,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,CAM1B,CAACE,CAAAA,CAAoB,CACxB,IAAMQ,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,CAE3BN,CAAAA,CAAS,MAAA,CAAO,CACjB,CACD,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;AC/E/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;AC4GvB;AC1JD,QAAA;AC2eN;AAAA;AAAA;AAAA;AAAA;AAAA;AC9PY,SAAA","file":"/home/runner/work/selva-compute/selva-compute/dist/chunk-EZRBMUXT.cjs","sourcesContent":[null,"import * as THREE from 'three';\n\nexport const EMISSIVE_MATERIAL = new THREE.MeshPhysicalMaterial({\n\tcolor: 0x000000,\n\temissive: new THREE.Color(0xffffff),\n\temissiveIntensity: 5,\n\tmetalness: 0.0,\n\troughness: 0.2,\n\tclearcoat: 0.3,\n\tclearcoatRoughness: 0.2,\n\tdepthWrite: true,\n\tdepthTest: true,\n\ttransparent: false,\n\talphaTest: 0.0,\n\tpolygonOffset: true,\n\tpolygonOffsetFactor: 1,\n\tpolygonOffsetUnits: 1,\n\tside: THREE.FrontSide,\n\tdithering: true\n});\n\nexport const METAL_MATERIAL = new THREE.MeshPhysicalMaterial({\n\tcolor: new THREE.Color(0x000000),\n\tmetalness: 0.9,\n\troughness: 0.3,\n\tenvMapIntensity: 1.2,\n\tclearcoat: 0.3,\n\tclearcoatRoughness: 0.2,\n\treflectivity: 1,\n\tior: 2.5,\n\tthickness: 1,\n\tdepthWrite: true,\n\ttransparent: false,\n\talphaTest: 0.0,\n\tdepthTest: true,\n\tpolygonOffset: true,\n\tpolygonOffsetFactor: 1,\n\tpolygonOffsetUnits: 1,\n\tside: THREE.FrontSide,\n\tdithering: true\n});\n\nexport const CONCRETE_MATERIAL = new THREE.MeshPhysicalMaterial({\n\tcolor: new THREE.Color(0xcccccc),\n\tmetalness: 0.0,\n\troughness: 0.92,\n\tenvMapIntensity: 0.15,\n\tclearcoat: 0.05,\n\tclearcoatRoughness: 0.9,\n\treflectivity: 0.15,\n\ttransmission: 0.0,\n\tior: 1.45,\n\tthickness: 0.0,\n\tdepthWrite: true,\n\ttransparent: false,\n\t// No alphaTest: concrete has no alpha map, and a nonzero alphaTest needlessly switches the\n\t// shader onto the alpha-test path.\n\talphaTest: 0.0,\n\tdepthTest: true,\n\tpolygonOffset: true,\n\tpolygonOffsetFactor: 1,\n\tpolygonOffsetUnits: 1,\n\tside: THREE.FrontSide,\n\tdithering: true\n});\n\nexport const PLASTIC_MATERIAL = new THREE.MeshPhysicalMaterial({\n\tcolor: new THREE.Color(0xffffff), // Default white plastic\n\tmetalness: 0.0,\n\troughness: 0.3,\n\tenvMapIntensity: 0.5,\n\tclearcoat: 0.5,\n\tclearcoatRoughness: 0.1,\n\treflectivity: 0.5,\n\tior: 1.4,\n\ttransmission: 0.0,\n\ttransparent: false,\n\tdepthWrite: true,\n\tside: THREE.FrontSide,\n\tdithering: true,\n\tpolygonOffset: true,\n\tpolygonOffsetFactor: 1,\n\tpolygonOffsetUnits: 1\n});\n\nexport const GLASS_MATERIAL = new THREE.MeshPhysicalMaterial({\n\tcolor: new THREE.Color(0xffffff),\n\tmetalness: 0.0,\n\troughness: 0.0,\n\t// Transmission alone models the see-through look; stacking a low `opacity` on top would\n\t// attenuate twice and render glass much darker than intended (opacity stays at its default 1).\n\ttransmission: 0.95,\n\ttransparent: true,\n\t// A depth-writing transparent DoubleSide surface culls whatever sorts behind it — objects\n\t// behind glass would intermittently vanish depending on draw order.\n\tdepthWrite: false,\n\tenvMapIntensity: 1.0,\n\tclearcoat: 1.0,\n\tclearcoatRoughness: 0.0,\n\tior: 1.52,\n\treflectivity: 0.9,\n\tthickness: 1.0,\n\tside: THREE.DoubleSide,\n\tpolygonOffset: true,\n\tpolygonOffsetFactor: 1,\n\tpolygonOffsetUnits: 1\n});\n\nexport const RUBBER_MATERIAL = new THREE.MeshPhysicalMaterial({\n\tcolor: new THREE.Color(0x1a1a1a),\n\tmetalness: 0.0,\n\troughness: 0.9,\n\tenvMapIntensity: 0.2,\n\tclearcoat: 0.1,\n\tclearcoatRoughness: 0.8,\n\treflectivity: 0.2,\n\tior: 1.3,\n\ttransmission: 0.0,\n\tdepthWrite: true,\n\tside: THREE.FrontSide,\n\tpolygonOffset: true,\n\tpolygonOffsetFactor: 1,\n\tpolygonOffsetUnits: 1\n});\n\nexport const WOOD_MATERIAL = new THREE.MeshPhysicalMaterial({\n\tcolor: new THREE.Color(0x885533),\n\tmetalness: 0.0,\n\troughness: 0.7,\n\tenvMapIntensity: 0.3,\n\tclearcoat: 0.3,\n\tclearcoatRoughness: 0.4,\n\treflectivity: 0.3,\n\tior: 1.3,\n\ttransmission: 0.0,\n\tdepthWrite: true,\n\tside: THREE.FrontSide,\n\tdithering: true,\n\tpolygonOffset: true,\n\tpolygonOffsetFactor: 1,\n\tpolygonOffsetUnits: 1\n});\n\n/**\n * The module-scope singleton materials above, as a set. Scene-clearing code must NOT dispose a\n * material in this set: they are shared across meshes and across solves, and `dispose()` on a\n * still-referenced material forces a shader program rebuild on its next use (and would free any\n * textures they gain later while other objects still use them).\n */\nexport const SHARED_MATERIALS: ReadonlySet<THREE.Material> = new Set<THREE.Material>([\n\tEMISSIVE_MATERIAL,\n\tMETAL_MATERIAL,\n\tCONCRETE_MATERIAL,\n\tPLASTIC_MATERIAL,\n\tGLASS_MATERIAL,\n\tRUBBER_MATERIAL,\n\tWOOD_MATERIAL\n]);\n","import * as THREE from 'three';\nimport { OrbitControls } from 'three/addons/controls/OrbitControls.js';\nimport { getLogger } from '@/core';\n\nimport { SHARED_MATERIALS } from './three-materials';\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\t// Zoom limits (min/maxDistance) are deliberately NOT touched here: they are owned by the\n\t// host via setupControls, and overwriting them per solve silently discarded user-supplied\n\t// configuration after the first geometry update.\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\n\t\tcontrols.update();\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. `new THREE.Color(name)` never throws on unknown names (it logs its own\n\t// warning and leaves the color white), so validate against three's CSS name table instead.\n\tconst named = trimmed.toLowerCase();\n\tif (named in THREE.Color.NAMES) {\n\t\treturn new THREE.Color(THREE.Color.NAMES[named as keyof typeof THREE.Color.NAMES]);\n\t}\n\n\tgetLogger().warn(`Invalid color string: ${colorString}, using white`);\n\treturn new THREE.Color(0xffffff);\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 — except the shared singleton materials (see {@link SHARED_MATERIALS}),\n * which outlive any one solve.\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 *\n * @internal exported for tests; production callers go through {@link updateScene}.\n */\nexport function 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// Module-scope singletons (METAL_MATERIAL et al.) are shared across meshes and across\n\t\t\t\t// solves — disposing one here would force a shader rebuild on its next use and free\n\t\t\t\t// textures still referenced by surviving objects.\n\t\t\t\tif (SHARED_MATERIALS.has(material)) return;\n\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\tmesh.removeFromParent(); // don't leave a dead mesh in the scene graph\n\t\t\tgeometry.dispose();\n\t\t\tmaterial.dispose();\n\t\t}\n\t};\n}\n","import * as THREE from 'three';\nimport { LineSegmentsGeometry } from 'three/addons/lines/LineSegmentsGeometry.js';\nimport { LineSegments2 } from 'three/addons/lines/LineSegments2.js';\nimport { LineMaterial } from 'three/addons/lines/LineMaterial.js';\n\n/**\n * Crisp boundary/crease edges overlaid on meshes — the defining \"technical drawing\" look that makes\n * shaded geometry read as discrete objects rather than blobs.\n *\n * Built with `EdgesGeometry` (which keeps only edges whose adjacent faces meet above a threshold\n * angle, so flat tessellation noise is dropped) rendered as a fat `LineSegments2` using the same\n * `LineMaterial` family as curves (Phase 1) — so edges get controllable thickness, not the 1px cap\n * of `THREE.LineSegments`. The overlay is added as a *child* of each mesh, so it inherits the mesh's\n * transform and is disposed when the mesh subtree is cleared.\n */\n\nexport interface EdgeOptions {\n\t/** Edge color. Default near-black. */\n\tcolor?: THREE.ColorRepresentation;\n\t/** Edge thickness in CSS px. Default 1.5. */\n\twidth?: number;\n\t/**\n\t * Crease angle in degrees: an edge is kept only where its two faces differ by more than this.\n\t * Default 30. Higher = fewer edges (only sharp creases); lower = more (catches gentle bends).\n\t */\n\tthresholdAngle?: number;\n}\n\n/** Tag on edge overlays so pick/fit/clear logic can recognize and skip or dispose them. */\nexport const EDGE_USERDATA_KIND = 'edge-overlay';\n\nconst DEFAULT_EDGE_COLOR = 0x222222;\nconst DEFAULT_EDGE_WIDTH = 1.5;\nconst DEFAULT_THRESHOLD_ANGLE = 30;\n\n/**\n * Extracted edge geometry, cached per source `BufferGeometry` (and per crease angle, since the\n * angle changes which edges survive). N meshes sharing one geometry — the common case for\n * instanced/repeated parts — get one extraction and one GPU buffer instead of N identical ones.\n *\n * Reference-counted so {@link removeEdges} only disposes a line geometry once its last overlay is\n * gone. The WeakMap keys on the source geometry, so entries vanish with the content they describe;\n * overlays disposed by whole-scene clears (which bypass removeEdges) just leave a refcount behind\n * on an entry that becomes unreachable together with its source geometry.\n */\ninterface EdgeGeometryEntry {\n\tgeometry: LineSegmentsGeometry;\n\trefCount: number;\n}\nconst edgeGeometryCache = new WeakMap<THREE.BufferGeometry, Map<number, EdgeGeometryEntry>>();\n\n/** Where an overlay's (possibly shared) line geometry came from, for refcounted disposal. */\ninterface EdgeOverlayUserData {\n\tkind: string;\n\tedgeSource?: THREE.BufferGeometry;\n\tedgeThresholdAngle?: number;\n}\n\n/**\n * Walk an object subtree and attach an edge overlay to every `Mesh` found, returning the created\n * overlays (so callers can dispose them explicitly if they don't clear the whole subtree). Meshes\n * that already carry an overlay are skipped, so this is safe to call more than once.\n *\n * Skips the floor and the grid (they're aids, not content) and anything already tagged as an edge.\n */\nexport function addEdges(root: THREE.Object3D, options: EdgeOptions = {}): LineSegments2[] {\n\tconst color = new THREE.Color(options.color ?? DEFAULT_EDGE_COLOR);\n\tconst width = options.width ?? DEFAULT_EDGE_WIDTH;\n\tconst thresholdAngle = options.thresholdAngle ?? DEFAULT_THRESHOLD_ANGLE;\n\n\tconst created: LineSegments2[] = [];\n\n\troot.traverse((object) => {\n\t\tif (!(object instanceof THREE.Mesh)) return;\n\t\tif (object.userData.id === 'floor' || object.userData.id === 'grid') return;\n\t\tif (object.userData.kind === EDGE_USERDATA_KIND) return;\n\t\tif (object.children.some((c) => c.userData?.kind === EDGE_USERDATA_KIND)) return; // already done\n\t\tif (!object.geometry) return;\n\n\t\tconst overlay = buildEdgeOverlay(object.geometry, color, width, thresholdAngle);\n\t\tobject.add(overlay); // child → inherits transform, disposed with the parent subtree\n\t\tcreated.push(overlay);\n\t});\n\n\treturn created;\n}\n\n/** Get (or extract and cache) the shared edge line geometry for a source geometry + crease angle. */\nfunction acquireEdgeGeometry(\n\tgeometry: THREE.BufferGeometry,\n\tthresholdAngle: number\n): LineSegmentsGeometry {\n\tlet byAngle = edgeGeometryCache.get(geometry);\n\tif (!byAngle) {\n\t\tbyAngle = new Map();\n\t\tedgeGeometryCache.set(geometry, byAngle);\n\t}\n\n\tlet entry = byAngle.get(thresholdAngle);\n\tif (!entry) {\n\t\tconst edges = new THREE.EdgesGeometry(geometry, thresholdAngle);\n\n\t\t// EdgesGeometry yields a Float32Array of line-segment endpoint pairs; LineSegmentsGeometry\n\t\t// consumes it as-is (round-tripping through Array.from would box every vertex into a JS array\n\t\t// only for setPositions to convert it straight back).\n\t\tconst lineGeometry = new LineSegmentsGeometry();\n\t\tlineGeometry.setPositions(edges.attributes.position.array as Float32Array);\n\t\tedges.dispose(); // frees only GPU-side state; the CPU array now backs the line geometry\n\n\t\tentry = { geometry: lineGeometry, refCount: 0 };\n\t\tbyAngle.set(thresholdAngle, entry);\n\t}\n\n\tentry.refCount += 1;\n\treturn entry.geometry;\n}\n\n/** Refcounted inverse of {@link acquireEdgeGeometry}: dispose only when the last overlay is gone. */\nfunction releaseEdgeGeometry(overlay: LineSegments2): void {\n\tconst userData = overlay.userData as EdgeOverlayUserData;\n\tconst byAngle = userData.edgeSource && edgeGeometryCache.get(userData.edgeSource);\n\tconst entry =\n\t\tuserData.edgeThresholdAngle != null ? byAngle?.get(userData.edgeThresholdAngle) : undefined;\n\n\tif (!entry || entry.geometry !== overlay.geometry) {\n\t\t// Not (or no longer) cache-managed — dispose directly.\n\t\toverlay.geometry.dispose();\n\t\treturn;\n\t}\n\n\tentry.refCount -= 1;\n\tif (entry.refCount <= 0) {\n\t\tentry.geometry.dispose();\n\t\tbyAngle!.delete(userData.edgeThresholdAngle!);\n\t}\n}\n\nfunction buildEdgeOverlay(\n\tgeometry: THREE.BufferGeometry,\n\tcolor: THREE.Color,\n\twidth: number,\n\tthresholdAngle: number\n): LineSegments2 {\n\tconst lineGeometry = acquireEdgeGeometry(geometry, thresholdAngle);\n\n\t// LineMaterialParameters omits linewidth/opacity from its type though both exist at runtime.\n\tconst material = new LineMaterial({ color });\n\t(material as LineMaterial & { linewidth: number }).linewidth = width;\n\t// Pull edges slightly toward the camera in depth so they don't z-fight the shaded surface.\n\t// The fat-line quads face the screen, so their depth slope is ~0 and the slope-scaled factor\n\t// term contributes nothing — the constant `units` term has to do the work. -1 unit is a single\n\t// depth ULP, which still stipples at glancing angles / far zoom on 24-bit depth buffers; a few\n\t// ULPs clears the surface reliably without visibly floating the edges.\n\tmaterial.polygonOffset = true;\n\tmaterial.polygonOffsetFactor = -1;\n\tmaterial.polygonOffsetUnits = -4;\n\n\tconst overlay = new LineSegments2(lineGeometry, material);\n\toverlay.userData.kind = EDGE_USERDATA_KIND;\n\t// Remember which cache entry backs this overlay so removeEdges can refcount its disposal. The\n\t// strong reference is fine: the overlay is a child of the mesh that owns the source geometry,\n\t// so their lifetimes already coincide.\n\toverlay.userData.edgeSource = geometry;\n\toverlay.userData.edgeThresholdAngle = thresholdAngle;\n\toverlay.raycast = () => {}; // never pickable; clicks should hit the mesh, not its outline\n\treturn overlay;\n}\n\n/** Whether an object is an edge overlay (for pick/fit filters elsewhere). */\nexport function isEdgeOverlay(object: THREE.Object3D): boolean {\n\treturn object.userData?.kind === EDGE_USERDATA_KIND;\n}\n\n/**\n * Remove every edge overlay under `root`, disposing its geometry and material. The inverse of\n * {@link addEdges}; together they make edges a live on/off toggle. Returns how many were removed.\n */\nexport function removeEdges(root: THREE.Object3D): number {\n\tconst overlays: LineSegments2[] = [];\n\troot.traverse((object) => {\n\t\tif (object instanceof LineSegments2 && isEdgeOverlay(object)) overlays.push(object);\n\t});\n\n\tfor (const overlay of overlays) {\n\t\treleaseEdgeGeometry(overlay); // geometry may be shared across overlays — refcounted dispose\n\t\t(overlay.material as LineMaterial).dispose();\n\t\toverlay.removeFromParent();\n\t}\n\treturn overlays.length;\n}\n","import * as THREE from 'three';\nimport { OrbitControls } from 'three/addons/controls/OrbitControls.js';\nimport { HDRLoader } from 'three/addons/loaders/HDRLoader.js';\n\nimport { getLogger } from '@/core';\nimport type { ThreeInitializerOptions, RenderStyle, RenderStylePreset } from '../types';\nimport type { MaterialAppearanceOptions } from '../webdisplay/types';\nimport { createCameraController, type CameraController } from './camera-controller';\nimport { createGrid, type Grid } from './grid';\nimport { createViewGizmo, type ViewGizmo } from './view-gizmo';\nimport { addEdges } from './edges';\nimport { createRenderPipeline, type RenderPipeline } from './render-pipeline';\nimport { createLabelLayer, type LabelLayer } from './label-layer';\nimport { createMeasureTool, type MeasureTool } from './measure';\nimport { setTextureAnisotropy } from '../webdisplay/texture-cache';\n\nconst defaultUp = new THREE.Vector3(0, 0, 1);\n\n/**\n * The two render-style looks, as concrete dial values. Single source of truth: consumed by\n * `applyDefaults` to seed construction-time defaults AND by `setRenderStyle` to re-apply a look at\n * runtime, so the two paths can never drift. See {@link RenderStyle} for what each look reads like.\n */\nconst RENDER_STYLE_PRESETS: Record<RenderStyle, RenderStylePreset> = {\n\ttechnical: {\n\t\ttoneMapping: THREE.NeutralToneMapping,\n\t\ttoneMappingExposure: 1,\n\t\tenvMapIntensity: 0.5,\n\t\tcullBackfaces: false,\n\t\tambientOcclusion: true,\n\t\tedges: true,\n\t\tgrid: true\n\t},\n\trendered: {\n\t\ttoneMapping: THREE.ACESFilmicToneMapping,\n\t\ttoneMappingExposure: 1,\n\t\tenvMapIntensity: 1.3,\n\t\tcullBackfaces: false,\n\t\tambientOcclusion: true,\n\t\tedges: false,\n\t\tgrid: false\n\t}\n};\n\n/**\n * The material-parse options implied by a render style — feed these into the batch parser's\n * `material` option so meshes are built to match the look (backface culling, IBL strength). Kept\n * out of the viewer's runtime dials because they're baked at parse time, not toggleable in place.\n */\nexport function materialAppearanceForStyle(style: RenderStyle): MaterialAppearanceOptions {\n\tconst preset = RENDER_STYLE_PRESETS[style];\n\treturn {\n\t\tenvMapIntensity: preset.envMapIntensity,\n\t\tcullBackfaces: preset.cullBackfaces\n\t};\n}\n\n/** Map an up vector to the grid's ground-plane axis (the axis the grid is laid perpendicular to). */\nfunction upToGroundPlane(up: THREE.Vector3): 'x' | 'y' | 'z' {\n\tconst ax = Math.abs(up.x);\n\tconst ay = Math.abs(up.y);\n\tconst az = Math.abs(up.z);\n\tif (az >= ax && az >= ay) return 'z';\n\tif (ay >= ax && ay >= az) return 'y';\n\treturn 'x';\n}\n\n/**\n * Initializes a Three.js environment with scene, camera, renderer, and event handling.\n */\nexport const initThree = function (\n\tcanvas: HTMLCanvasElement,\n\toptions?: ThreeInitializerOptions\n): {\n\tscene: THREE.Scene;\n\tcamera: THREE.PerspectiveCamera;\n\tcontrols: OrbitControls;\n\trenderer: THREE.WebGLRenderer;\n\tcameraController: CameraController;\n\tgrid: Grid | null;\n\tgizmo: ViewGizmo | null;\n\t/** Two-click distance measurement tool. Null unless `measure.enabled`; `setEnabled(true)` to use. */\n\tmeasureTool: MeasureTool | null;\n\t/**\n\t * Attach edge overlays to the meshes under `root` (no-op unless `edges.enabled`). Call after\n\t * loading meshes via `updateScene`, since meshes arrive after init.\n\t */\n\tapplyEdges: (root: THREE.Object3D) => void;\n\t/** Toggle ambient occlusion at runtime — builds or tears down the postprocessing pipeline. */\n\tsetAmbientOcclusion: (enabled: boolean) => void;\n\t/**\n\t * Apply a coherent look to the already-loaded scene: 'technical' (matte/CAD — edges, grid, low\n\t * IBL, neutral tone mapping) or 'rendered' (presentation — stronger IBL, ACES tone mapping, no\n\t * edges). Retunes viewer-owned dials only; per-material parse choices are set via the batch\n\t * parser's `material` option. Handy for comparing the two looks in a live viewer.\n\t */\n\tsetRenderStyle: (style: 'technical' | 'rendered') => void;\n\t/**\n\t * The parse-time material options (backface culling, IBL strength) matching the active render\n\t * style — feed into the batch parser's `material` option so freshly-loaded meshes are built to\n\t * match the look. Returns undefined when no style is active. See `setRenderStyle`.\n\t */\n\tgetMaterialAppearance: () => MaterialAppearanceOptions | undefined;\n\t/**\n\t * Refit the sun's shadow frustum to the current scene content for crisp shadows. Call after\n\t * loading or replacing geometry (e.g. after `updateScene`). No-op when sunlight/shadows are off.\n\t */\n\tupdateShadowBounds: () => void;\n\tdispose: () => void;\n\tfitToView: () => void;\n\tclearSelection: () => void;\n\t/**\n\t * Add caller-owned geometry (lines, annotations, construction aids) to the scene. The object is\n\t * tagged `userData.source = 'user'` so it persists across `updateScene` solves instead of being\n\t * cleared with compute content. It is treated as normal content for fit-to-view framing.\n\t */\n\taddUserGeometry: (object: THREE.Object3D) => void;\n\t/** Remove a single user-added object and dispose its geometry/materials. */\n\tremoveUserGeometry: (object: THREE.Object3D) => void;\n\t/** Remove and dispose all user-added geometry (every object tagged `source === 'user'`). */\n\tclearUserGeometry: () => void;\n} {\n\tconst config = applyDefaults(options || {});\n\n\tconst sceneUp = config.environment?.sceneUp || defaultUp;\n\n\t// The configured pixel ratio is the single source of truth for every DPR consumer — renderer\n\t// setup, the per-frame resize check, and the AO pipeline. Resolving it once here means a\n\t// host-configured value (e.g. `pixelRatio: 1` for performance) is never silently overridden\n\t// after the first resize check. (applyDefaults always sets it; the fallback is type narrowing.)\n\tconst pixelRatio = config.render.pixelRatio ?? Math.min(window.devicePixelRatio, 2);\n\n\tconst scene = createScene(config);\n\tconst camera = createCamera(config, canvas);\n\t// Set the camera's up to the scene up BEFORE OrbitControls/the controller read it — OrbitControls\n\t// captures the orbit basis from camera.up at construction, and the controller derives its presets\n\t// and ortho camera from it. Without this, a Z-up scene would orbit and frame as if Y-up.\n\tcamera.up.copy(sceneUp);\n\tconst renderer = setupRenderer(canvas, config, pixelRatio);\n\t// Report the GPU's max anisotropy to the texture cache so color maps stay sharp at grazing angles.\n\t// One-time; retroactively upgrades any texture already decoded this session.\n\tsetTextureAnisotropy(renderer.capabilities.getMaxAnisotropy());\n\tconst controls = setupControls(camera, canvas, config);\n\n\t// Tracks whichever camera (perspective or orthographic) is live; the controller swaps it.\n\t// Render loop, resize, and raycasting all read through getActiveCamera so 2D/3D stays coherent.\n\tconst cameraController = createCameraController({\n\t\tscene,\n\t\tperspective: camera,\n\t\tcontrols,\n\t\tonActiveCameraChange: () => {},\n\t\tup: sceneUp\n\t});\n\tconst getActiveCamera = () => cameraController.getActiveCamera();\n\n\t// The HDR environment decodes asynchronously; if the viewer is disposed before it lands, the\n\t// load callback must drop (and dispose) the texture instead of attaching it to a swept scene.\n\tlet disposed = false;\n\tsetupEnvironment(scene, config, () => disposed);\n\t// The shadow-casting sun (null when sunlight or shadows are off). Its shadow frustum is fitted to\n\t// the scene content below and again whenever the host calls updateShadowBounds after a geometry\n\t// change — keeping shadow-map texels packed onto the model for crisp shadows at any scale.\n\tconst sunlight = setupLighting(scene, config);\n\n\t/**\n\t * Refit the sun's shadow frustum to the current scene content. Call after loading or replacing\n\t * geometry (e.g. right after `updateScene`). No-op when there is no shadow-casting sun or no\n\t * content. Cheap: one bounds traversal, no per-frame cost.\n\t */\n\tconst updateShadowBounds = () => {\n\t\tif (sunlight) fitShadowToContent(sunlight, computeContentBounds(scene));\n\t};\n\n\tif (config.floor?.enabled) {\n\t\taddFloor(scene, config);\n\t}\n\n\t// Optional CAD aids: an infinite fading grid and the corner nav-cube gizmo. Both opt-in.\n\tconst grid = config.grid.enabled\n\t\t? createGrid({\n\t\t\t\tcellSize: config.grid.cellSize,\n\t\t\t\tmajorEvery: config.grid.majorEvery,\n\t\t\t\tcellColor: config.grid.cellColor,\n\t\t\t\tmajorColor: config.grid.majorColor,\n\t\t\t\tfadeDistance: config.grid.fadeDistance,\n\t\t\t\tplane: config.grid.plane\n\t\t\t})\n\t\t: null;\n\tif (grid) scene.add(grid.object);\n\n\tconst gizmo = config.gizmo.enabled\n\t\t? createViewGizmo({ camera, domElement: canvas, controller: cameraController })\n\t\t: null;\n\n\t// HTML label overlay (CSS2D) and the measurement tool built on it. Both opt-in; the label layer\n\t// is only created when something needs it (currently the measure tool).\n\tconst labelContainer = canvas.parentElement ?? canvas;\n\tconst labelLayer: LabelLayer | null = config.measure.enabled\n\t\t? createLabelLayer(labelContainer, scene)\n\t\t: null;\n\tconst measureTool: MeasureTool | null =\n\t\tconfig.measure.enabled && labelLayer\n\t\t\t? createMeasureTool({\n\t\t\t\t\tcanvas,\n\t\t\t\t\tscene,\n\t\t\t\t\tgetActiveCamera,\n\t\t\t\t\tlabelLayer,\n\t\t\t\t\toptions: {\n\t\t\t\t\t\tsnapPixels: config.measure.snapPixels,\n\t\t\t\t\t\tcolor: config.measure.color,\n\t\t\t\t\t\tlabelClassName: config.measure.labelClassName,\n\t\t\t\t\t\tdisplayUnit: config.measure.displayUnit,\n\t\t\t\t\t\tformat: config.measure.format\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t: null;\n\n\tconst eventHandlers =\n\t\tconfig.events.enableEventHandlers !== false\n\t\t\t? setupEventHandlers(canvas, scene, cameraController, config)\n\t\t\t: { dispose: () => {}, fitToView: () => {}, clearSelection: () => {} };\n\n\t// A drag to orbit/pan ends with a `click` on mouseup. Without guarding, that release click would\n\t// be taken as a measurement point (placing a stray point or clearing a finished measurement when\n\t// the user only meant to rotate). Record where the press started and treat the release as a click\n\t// only if the pointer barely moved — a real click, not a drag.\n\tconst DRAG_SLOP_PX = 5;\n\tlet pressX = 0;\n\tlet pressY = 0;\n\tconst handlePointerDown = (event: MouseEvent) => {\n\t\tpressX = event.clientX;\n\t\tpressY = event.clientY;\n\t};\n\tconst wasDrag = (event: MouseEvent) =>\n\t\tMath.hypot(event.clientX - pressX, event.clientY - pressY) > DRAG_SLOP_PX;\n\n\t// Capture-phase interceptors that pre-empt scene selection. Order: an active measurement claims\n\t// the click first, then the gizmo. stopImmediatePropagation keeps the selection handler from\n\t// also firing. (Both run in capture so they see the event before the bubble-phase selection.)\n\tconst handleToolClick = (event: MouseEvent) => {\n\t\tif (wasDrag(event)) return; // an orbit/pan release, not a measurement click — leave it alone\n\t\tif (measureTool?.handleClick(event)) {\n\t\t\tevent.stopImmediatePropagation();\n\t\t\treturn;\n\t\t}\n\t\tif (gizmo?.handleClick(event)) {\n\t\t\tevent.stopImmediatePropagation();\n\t\t}\n\t};\n\tif (gizmo || measureTool) {\n\t\tcanvas.addEventListener('mousedown', handlePointerDown, { capture: true });\n\t\tcanvas.addEventListener('click', handleToolClick, { capture: true });\n\t}\n\t// Forward movement to the measure tool so it can preview the snap point under the cursor. Passive:\n\t// it only reads, never consumes, so it never interferes with orbit/pan.\n\tconst handleToolMove = (event: MouseEvent) => measureTool?.handleMove(event);\n\tif (measureTool) {\n\t\tcanvas.addEventListener('mousemove', handleToolMove, { passive: true });\n\t}\n\n\t// Edge overlays: bind the configured options into a closure the consumer calls after loading\n\t// meshes. Always applies when called explicitly (the `edges.enabled` flag governs whether the\n\t// host *intends* edges, but an explicit call should never be silently ignored).\n\tconst applyEdges = (root: THREE.Object3D) => {\n\t\taddEdges(root, {\n\t\t\tcolor: config.edges.color,\n\t\t\twidth: config.edges.width,\n\t\t\tthresholdAngle: config.edges.thresholdAngle\n\t\t});\n\t};\n\n\tconst parent = canvas.parentElement;\n\tconst getCanvasSize = () =>\n\t\tparent\n\t\t\t? { width: parent.clientWidth, height: parent.clientHeight }\n\t\t\t: { width: window.innerWidth, height: window.innerHeight };\n\n\t// Optional AO postprocessing pipeline. Held in a mutable so it can be toggled at runtime\n\t// (setAmbientOcclusion below); the loop reads it through getRenderPipeline each frame. When null,\n\t// the loop uses the plain renderer.render path. Retargeted to the active camera every frame.\n\tlet renderPipeline: RenderPipeline | null = null;\n\n\tconst buildPipeline = (): RenderPipeline => {\n\t\tconst { width, height } = getCanvasSize();\n\t\tconst pipeline = createRenderPipeline(\n\t\t\trenderer,\n\t\t\tscene,\n\t\t\tgetActiveCamera(),\n\t\t\tMath.max(1, width),\n\t\t\tMath.max(1, height),\n\t\t\t{\n\t\t\t\ttoneMapping: config.render.toneMapping ?? THREE.NeutralToneMapping,\n\t\t\t\ttoneMappingExposure: config.render.toneMappingExposure ?? 1,\n\t\t\t\taoIntensity: config.render.aoIntensity\n\t\t\t}\n\t\t);\n\t\tpipeline.setSize(Math.max(1, width), Math.max(1, height), pixelRatio);\n\t\treturn pipeline;\n\t};\n\n\tconst setAmbientOcclusion = (enabled: boolean) => {\n\t\tif (enabled && !renderPipeline) {\n\t\t\trenderPipeline = buildPipeline();\n\t\t} else if (!enabled && renderPipeline) {\n\t\t\trenderPipeline.dispose();\n\t\t\trenderPipeline = null;\n\t\t}\n\t};\n\n\tif (config.render.ambientOcclusion) renderPipeline = buildPipeline();\n\n\t/**\n\t * Apply a coherent look to the *already-built* scene at runtime — a quick way to compare the two\n\t * presets in a live viewer. It retunes only what the viewer owns after load: tone mapping/exposure,\n\t * AO on/off, edge & grid visibility, and `envMapIntensity` on every compute material currently in\n\t * the scene. It does NOT rebuild geometry, so per-material choices baked at parse time (backface\n\t * culling, vertex-color decode) are unaffected — set those via the batch parser's `material` option.\n\t *\n\t * - 'technical': matte, drawing-like. Neutral tone mapping, low IBL, edges + grid on, AO on.\n\t * - 'rendered': presentation. ACES-filmic tone mapping, stronger IBL, edges off, AO on.\n\t */\n\tconst setRenderStyle = (style: RenderStyle) => {\n\t\tconst preset = RENDER_STYLE_PRESETS[style];\n\t\tactiveRenderStyle = style;\n\n\t\t// Tone mapping lives on the renderer (plain path) and is mirrored into the composer's OutputPass\n\t\t// when AO is active. Rebuild the pipeline so the composer picks up the new tone mapping.\n\t\trenderer.toneMapping = preset.toneMapping;\n\t\trenderer.toneMappingExposure = preset.toneMappingExposure;\n\t\tconfig.render.toneMapping = preset.toneMapping;\n\t\tconfig.render.toneMappingExposure = preset.toneMappingExposure;\n\n\t\tif (renderPipeline) {\n\t\t\t// Rebuild so the composer's OutputPass adopts the new tone mapping, then honor the target AO.\n\t\t\tsetAmbientOcclusion(false);\n\t\t\tsetAmbientOcclusion(preset.ambientOcclusion);\n\t\t} else {\n\t\t\tsetAmbientOcclusion(preset.ambientOcclusion);\n\t\t}\n\n\t\t// Retune IBL reflection strength on every compute mesh material in the scene.\n\t\tscene.traverse((object) => {\n\t\t\tif (object.userData.source !== 'compute') return;\n\t\t\tconst mesh = object as Partial<THREE.Mesh> & THREE.Object3D;\n\t\t\tconst materials = Array.isArray(mesh.material)\n\t\t\t\t? mesh.material\n\t\t\t\t: mesh.material\n\t\t\t\t\t? [mesh.material]\n\t\t\t\t\t: [];\n\t\t\tfor (const material of materials) {\n\t\t\t\tif ('envMapIntensity' in material) {\n\t\t\t\t\t(material as THREE.MeshStandardMaterial).envMapIntensity = preset.envMapIntensity;\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\t// Edge overlays live as children tagged 'edge-overlay'; toggle their visibility in place.\n\t\tscene.traverse((object) => {\n\t\t\tif (object.userData.kind === 'edge-overlay') object.visible = preset.edges;\n\t\t});\n\n\t\tif (grid) grid.object.visible = preset.grid;\n\t};\n\n\t// The style whose look is currently applied (null until the caller passes `renderStyle` or calls\n\t// setRenderStyle). Seeded from the raw option, not `config.renderStyle` — the latter is coerced to\n\t// a non-null default by Required<>, which would wrongly report a style when none was chosen.\n\t// Drives `getMaterialAppearance()` so the host feeds the parser matching material options.\n\tlet activeRenderStyle: RenderStyle | null = options?.renderStyle ?? null;\n\n\t/**\n\t * The parse-time material options (backface culling, IBL strength) that match the active style —\n\t * pass into the batch parser's `material` option so newly-loaded meshes are built to match the\n\t * look. Returns undefined when no style is active (plain per-field defaults).\n\t */\n\tconst getMaterialAppearance = (): MaterialAppearanceOptions | undefined =>\n\t\tactiveRenderStyle ? materialAppearanceForStyle(activeRenderStyle) : undefined;\n\n\t// Resize checked every frame so buffer resize and render happen in the same frame,\n\t// preventing visible blank frames on resize\n\tconst { animate, dispose: disposeAnimation } = createAnimationLoop(\n\t\trenderer,\n\t\tscene,\n\t\tcamera,\n\t\tgetActiveCamera,\n\t\tcameraController,\n\t\tcontrols,\n\t\tgetCanvasSize,\n\t\tpixelRatio,\n\t\tconfig.events.onFrame,\n\t\tgrid,\n\t\tgizmo,\n\t\t() => renderPipeline,\n\t\tlabelLayer\n\t);\n\tanimate();\n\n\tscene.up.set(sceneUp.x, sceneUp.y, sceneUp.z);\n\n\t// Initial fit so any geometry already present at construction casts crisp shadows. Hosts that add\n\t// geometry later (via updateScene) should call updateShadowBounds again afterwards.\n\tupdateShadowBounds();\n\n\t// Dispose one object's renderable resources (geometry + materials + their textures), recursing\n\t// into children so Groups of lines/points clean up fully.\n\tconst disposeObjectTree = (root: THREE.Object3D) => {\n\t\troot.traverse((object) => {\n\t\t\tconst renderable = object as Partial<THREE.Mesh> & THREE.Object3D;\n\t\t\tif (!renderable.geometry && !renderable.material) return;\n\t\t\trenderable.geometry?.dispose();\n\t\t\tif (Array.isArray(renderable.material)) {\n\t\t\t\trenderable.material.forEach(disposeMaterialWithTextures);\n\t\t\t} else if (renderable.material) {\n\t\t\t\tdisposeMaterialWithTextures(renderable.material);\n\t\t\t}\n\t\t});\n\t};\n\n\tconst addUserGeometry = (object: THREE.Object3D) => {\n\t\tobject.userData.source = 'user';\n\t\tscene.add(object);\n\t};\n\n\tconst removeUserGeometry = (object: THREE.Object3D) => {\n\t\tobject.removeFromParent();\n\t\tdisposeObjectTree(object);\n\t};\n\n\tconst clearUserGeometry = () => {\n\t\t// Snapshot first — removeFromParent mutates scene.children during iteration.\n\t\tconst userObjects = scene.children.filter((child) => child.userData.source === 'user');\n\t\tuserObjects.forEach((object) => {\n\t\t\tobject.removeFromParent();\n\t\t\tdisposeObjectTree(object);\n\t\t});\n\t};\n\n\tconst dispose = () => {\n\t\tdisposed = true;\n\t\tdisposeAnimation();\n\t\teventHandlers.dispose();\n\t\tif (gizmo || measureTool) {\n\t\t\tcanvas.removeEventListener('mousedown', handlePointerDown, { capture: true });\n\t\t\tcanvas.removeEventListener('click', handleToolClick, { capture: true });\n\t\t}\n\t\tif (measureTool) {\n\t\t\tcanvas.removeEventListener('mousemove', handleToolMove);\n\t\t}\n\t\tmeasureTool?.dispose();\n\t\tlabelLayer?.dispose();\n\t\tgizmo?.dispose();\n\t\tgrid?.dispose();\n\t\trenderPipeline?.dispose();\n\t\t// Stop any in-flight camera tween — its rAF ticks would otherwise keep touching the disposed\n\t\t// controls for up to the tween duration after teardown.\n\t\tcameraController.dispose();\n\t\tcontrols.dispose();\n\t\trenderer.dispose();\n\t\t// Free the GL context itself, not just its objects — browsers cap live WebGL contexts\n\t\t// (~16) and won't otherwise reclaim this one until GC, which can lag across rapid\n\t\t// mount/unmount cycles (e.g. navigating between definitions) and hit that cap.\n\t\trenderer.forceContextLoss();\n\n\t\tscene.traverse((object) => {\n\t\t\t// Dispose any renderable (mesh, line, points), not just meshes.\n\t\t\tconst renderable = object as Partial<THREE.Mesh> & THREE.Object3D;\n\t\t\tif (!renderable.geometry && !renderable.material) return;\n\n\t\t\trenderable.geometry?.dispose();\n\t\t\tif (Array.isArray(renderable.material)) {\n\t\t\t\trenderable.material.forEach(disposeMaterialWithTextures);\n\t\t\t} else if (renderable.material) {\n\t\t\t\tdisposeMaterialWithTextures(renderable.material);\n\t\t\t}\n\t\t});\n\n\t\t// Scene-level textures the traversal above can't reach.\n\t\tscene.environment?.dispose();\n\t\tif (scene.background instanceof THREE.Texture) {\n\t\t\tscene.background.dispose();\n\t\t}\n\t};\n\n\treturn {\n\t\tscene,\n\t\tcamera,\n\t\tcontrols,\n\t\trenderer,\n\t\tcameraController,\n\t\tgrid,\n\t\tgizmo,\n\t\tmeasureTool,\n\t\tapplyEdges,\n\t\tsetAmbientOcclusion,\n\t\tsetRenderStyle,\n\t\tgetMaterialAppearance,\n\t\tupdateShadowBounds,\n\t\tdispose,\n\t\tfitToView: eventHandlers.fitToView,\n\t\tclearSelection: eventHandlers.clearSelection,\n\t\taddUserGeometry,\n\t\tremoveUserGeometry,\n\t\tclearUserGeometry\n\t};\n};\n\nfunction applyDefaults(options: ThreeInitializerOptions): Required<ThreeInitializerOptions> {\n\tconst scale = options.sceneScale || 'm';\n\n\t// All Rhino geometry is normalized to METERS (1 unit = 1 meter), sceneScale just changes the viewing perspective\n\tconst scaleDefaults = {\n\t\tmm: {\n\t\t\tcameraDistance: 20,\n\t\t\tnear: 0.1,\n\t\t\tfar: 2000,\n\t\t\tfloorSize: 100,\n\t\t\tlightDistance: 10,\n\t\t\tlightHeight: 20,\n\t\t\tminDistance: 0.1,\n\t\t\tshadowSize: 100,\n\t\t\tscaleFactor: 1000\n\t\t},\n\t\tcm: {\n\t\t\tcameraDistance: 20,\n\t\t\tnear: 0.1,\n\t\t\tfar: 2000,\n\t\t\tfloorSize: 100,\n\t\t\tlightDistance: 25,\n\t\t\tlightHeight: 50,\n\t\t\tminDistance: 0.1,\n\t\t\tshadowSize: 100,\n\t\t\tscaleFactor: 100\n\t\t},\n\t\tm: {\n\t\t\tcameraDistance: 10,\n\t\t\tnear: 0.01,\n\t\t\tfar: 2000,\n\t\t\tfloorSize: 50,\n\t\t\tlightDistance: 25,\n\t\t\tlightHeight: 50,\n\t\t\tminDistance: 0.001,\n\t\t\tshadowSize: 100,\n\t\t\tscaleFactor: 1\n\t\t},\n\t\tinches: {\n\t\t\tcameraDistance: 15,\n\t\t\tnear: 0.1,\n\t\t\tfar: 2000,\n\t\t\tfloorSize: 80,\n\t\t\tlightDistance: 20,\n\t\t\tlightHeight: 40,\n\t\t\tminDistance: 0.1,\n\t\t\tshadowSize: 80,\n\t\t\tscaleFactor: 39.37\n\t\t},\n\t\tfeet: {\n\t\t\tcameraDistance: 8,\n\t\t\tnear: 0.1,\n\t\t\tfar: 2000,\n\t\t\tfloorSize: 40,\n\t\t\tlightDistance: 15,\n\t\t\tlightHeight: 30,\n\t\t\tminDistance: 0.1,\n\t\t\tshadowSize: 60,\n\t\t\tscaleFactor: 3.28084\n\t\t}\n\t};\n\n\tconst defaults = scaleDefaults[scale];\n\n\t// A chosen render style seeds the tone-mapping / AO / edges / grid defaults. It sits BELOW explicit\n\t// per-field options (those still win) and ABOVE the plain per-field defaults — so it only fills\n\t// what the caller left unspecified. Null when no style is chosen (plain defaults apply).\n\tconst style: RenderStylePreset | null = options.renderStyle\n\t\t? RENDER_STYLE_PRESETS[options.renderStyle]\n\t\t: null;\n\n\treturn {\n\t\tsceneScale: scale,\n\t\trenderStyle: options.renderStyle ?? 'technical',\n\t\tcamera: {\n\t\t\t// Default 3/4 iso for a Z-up scene: back-left and ABOVE (height on +Z).\n\t\t\tposition:\n\t\t\t\toptions.camera?.position ||\n\t\t\t\tnew THREE.Vector3(\n\t\t\t\t\t-defaults.cameraDistance,\n\t\t\t\t\t-defaults.cameraDistance,\n\t\t\t\t\tdefaults.cameraDistance\n\t\t\t\t),\n\t\t\tfov: options.camera?.fov || 20,\n\t\t\tnear: options.camera?.near || defaults.near,\n\t\t\tfar: options.camera?.far || defaults.far,\n\t\t\ttarget: options.camera?.target || new THREE.Vector3(0, 0, 0)\n\t\t},\n\t\tlighting: {\n\t\t\tenableSunlight: options.lighting?.enableSunlight ?? true,\n\t\t\tsunlightIntensity: options.lighting?.sunlightIntensity ?? 1,\n\t\t\t// Sun overhead in a Z-up scene: height on +Z, offset across X/Y.\n\t\t\tsunlightPosition:\n\t\t\t\toptions.lighting?.sunlightPosition ||\n\t\t\t\tnew THREE.Vector3(defaults.lightDistance, defaults.lightDistance, defaults.lightHeight),\n\t\t\tambientLightColor: options.lighting?.ambientLightColor || new THREE.Color(0x404040),\n\t\t\tambientLightIntensity: options.lighting?.ambientLightIntensity ?? 1,\n\t\t\tsunlightColor: options.lighting?.sunlightColor || 0xffffff // Default to white sunlight\n\t\t},\n\t\tenvironment: {\n\t\t\thdrPath: options.environment?.hdrPath || '/baseHDR.hdr',\n\t\t\tbackgroundColor: options.environment?.backgroundColor || new THREE.Color(0xf0f0f0),\n\t\t\tenableEnvironmentLighting: options.environment?.enableEnvironmentLighting ?? true,\n\t\t\tsceneUp: options.environment?.sceneUp || defaultUp,\n\t\t\tshowEnvironment: options.environment?.showEnvironment ?? false\n\t\t},\n\t\tfloor: {\n\t\t\tenabled: options.floor?.enabled ?? false,\n\t\t\tsize: options.floor?.size || defaults.floorSize,\n\t\t\tcolor: options.floor?.color || new THREE.Color(0x808080),\n\t\t\troughness: options.floor?.roughness ?? 0.7,\n\t\t\tmetalness: options.floor?.metalness ?? 0.0,\n\t\t\treceiveShadow: options.floor?.receiveShadow ?? true\n\t\t},\n\t\trender: {\n\t\t\tenableShadows: options.render?.enableShadows ?? true,\n\t\t\tshadowMapSize: options.render?.shadowMapSize || 2048,\n\t\t\tantialias: options.render?.antialias ?? true,\n\t\t\tpixelRatio: options.render?.pixelRatio || Math.min(window.devicePixelRatio, 2),\n\t\t\ttoneMapping: options.render?.toneMapping || style?.toneMapping || THREE.NeutralToneMapping,\n\t\t\ttoneMappingExposure: options.render?.toneMappingExposure ?? style?.toneMappingExposure ?? 1,\n\t\t\tpreserveDrawingBuffer: options.render?.preserveDrawingBuffer ?? false,\n\t\t\tambientOcclusion: options.render?.ambientOcclusion ?? style?.ambientOcclusion ?? false,\n\t\t\taoIntensity: options.render?.aoIntensity ?? 1\n\t\t},\n\t\tcontrols: {\n\t\t\tenableDamping: options.controls?.enableDamping ?? false,\n\t\t\tdampingFactor: options.controls?.dampingFactor || 0.05,\n\t\t\tautoRotate: options.controls?.autoRotate ?? false,\n\t\t\tautoRotateSpeed: options.controls?.autoRotateSpeed || 0.5,\n\t\t\tenableZoom: options.controls?.enableZoom ?? true,\n\t\t\tenablePan: options.controls?.enablePan ?? true,\n\t\t\tminDistance: options.controls?.minDistance || defaults.minDistance,\n\t\t\tmaxDistance: options.controls?.maxDistance || Infinity\n\t\t},\n\t\tgrid: {\n\t\t\t// Defaults mirror createGrid's so the two never drift. A render style can switch the grid on.\n\t\t\tenabled: options.grid?.enabled ?? style?.grid ?? false,\n\t\t\tcellSize: options.grid?.cellSize ?? 1,\n\t\t\tmajorEvery: options.grid?.majorEvery ?? 10,\n\t\t\tcellColor: options.grid?.cellColor ?? 0x888888,\n\t\t\tmajorColor: options.grid?.majorColor ?? 0x444444,\n\t\t\tfadeDistance: options.grid?.fadeDistance ?? 100,\n\t\t\t// The \"ground\" plane is the one orthogonal to the scene up axis, so the grid lies under the\n\t\t\t// model regardless of up convention (Z-up Rhino → 'z'; Y-up → 'y'). Explicit `plane` wins.\n\t\t\tplane: options.grid?.plane ?? upToGroundPlane(options.environment?.sceneUp ?? defaultUp)\n\t\t},\n\t\tgizmo: {\n\t\t\tenabled: options.gizmo?.enabled ?? false\n\t\t},\n\t\tedges: {\n\t\t\t// Defaults mirror addEdges' so the two never drift. A render style can switch edges on.\n\t\t\tenabled: options.edges?.enabled ?? style?.edges ?? false,\n\t\t\tcolor: options.edges?.color ?? 0x222222,\n\t\t\twidth: options.edges?.width ?? 1.5,\n\t\t\tthresholdAngle: options.edges?.thresholdAngle ?? 30\n\t\t},\n\t\tmeasure: {\n\t\t\t// Visual defaults live in createMeasureTool; only `enabled` needs a value here, the rest\n\t\t\t// pass through (undefined → the tool's own default).\n\t\t\tenabled: options.measure?.enabled ?? false,\n\t\t\tsnapPixels: options.measure?.snapPixels,\n\t\t\tcolor: options.measure?.color,\n\t\t\tlabelClassName: options.measure?.labelClassName,\n\t\t\tdisplayUnit: options.measure?.displayUnit,\n\t\t\tformat: options.measure?.format\n\t\t},\n\t\tevents: {\n\t\t\tonBackgroundClicked: options.events?.onBackgroundClicked,\n\t\t\tonObjectSelected: options.events?.onObjectSelected,\n\t\t\tonMeshMetadataClicked: options.events?.onMeshMetadataClicked,\n\t\t\tonMeshDoubleClicked: options.events?.onMeshDoubleClicked,\n\t\t\tselectionColor: options.events?.selectionColor || '#ff0000', // Default to red\n\t\t\tenableEventHandlers: options.events?.enableEventHandlers ?? true,\n\t\t\tenableKeyboardControls: options.events?.enableKeyboardControls ?? true,\n\t\t\tenableClickToFocus: options.events?.enableClickToFocus ?? true,\n\t\t\tenableDoubleClickZoom: options.events?.enableDoubleClickZoom ?? true,\n\t\t\tonReady: options.events?.onReady,\n\t\t\tonFrame: options.events?.onFrame\n\t\t}\n\t};\n}\n\n/**\n * Dispose a material together with any textures it references (`map`, `roughnessMap`, …), matching\n * `clearScene`'s texture sweep (three-helpers) so no teardown path leaks GPU textures across viewer\n * mount/unmount cycles. Walks own enumerable properties only — `for...in` would needlessly iterate\n * the prototype chain.\n */\nexport function disposeMaterialWithTextures(material: THREE.Material): void {\n\tfor (const value of Object.values(material)) {\n\t\tif (value instanceof THREE.Texture) {\n\t\t\tvalue.dispose();\n\t\t}\n\t}\n\tmaterial.dispose();\n}\n\n/**\n * Viewer aids (grid, floor, label overlay, measure markers) are not scene *content* — exclude them\n * from fit-to-view bounds and other content queries. Tagged via `userData.id` at creation.\n */\nconst VIEWER_AID_IDS = new Set(['grid', 'floor', 'label-layer', 'measure']);\nfunction isViewerAid(object: THREE.Object3D): boolean {\n\tlet current: THREE.Object3D | null = object;\n\twhile (current) {\n\t\tif (typeof current.userData.id === 'string' && VIEWER_AID_IDS.has(current.userData.id)) {\n\t\t\treturn true;\n\t\t}\n\t\tcurrent = current.parent;\n\t}\n\treturn false;\n}\n\n/**\n * Axis-aligned bounds of the scene's renderable *content* — every visible mesh/line/points, with\n * viewer aids excluded. The grid (a huge camera-tracking plane) and the floor would otherwise\n * dominate the box. Shared by fit-to-view, pick-threshold scaling, and shadow-frustum fitting so\n * they all measure the same thing. Returns an empty Box3 when there is no content.\n */\nfunction computeContentBounds(scene: THREE.Scene): THREE.Box3 {\n\tconst box = new THREE.Box3();\n\tscene.traverse((object) => {\n\t\tconst renderable = object as Partial<THREE.Mesh> & THREE.Object3D;\n\t\tif (object.visible && !isViewerAid(object) && renderable.geometry) {\n\t\t\tbox.expandByObject(object);\n\t\t}\n\t});\n\treturn box;\n}\n\n/**\n * Fit a directional light's shadow camera to the scene content. The orthographic shadow frustum is\n * sized to the content's bounding sphere (padded), so the fixed shadow-map texels cover only the\n * model rather than a generous constant area — the dominant lever on shadow crispness. Near/far are\n * derived from how far the light sits from the content centre, keeping depth precision tight.\n *\n * No-op when there is no content (an empty box would collapse the frustum to a point).\n */\nfunction fitShadowToContent(light: THREE.DirectionalLight, bounds: THREE.Box3): void {\n\tif (bounds.isEmpty()) return;\n\n\tconst center = bounds.getCenter(new THREE.Vector3());\n\t// Bounding-sphere radius makes the frustum rotation-invariant: the light can shine from any\n\t// angle and the model still fits, with no per-angle recompute. Pad so grazing-angle casters and\n\t// soft-shadow (VSM) blur near the edges don't clip.\n\tconst radius = bounds.getSize(new THREE.Vector3()).length() * 0.5 * 1.2;\n\n\tconst cam = light.shadow.camera;\n\tcam.left = -radius;\n\tcam.right = radius;\n\tcam.top = radius;\n\tcam.bottom = -radius;\n\n\t// Aim the shadow camera at the content centre. The light keeps its configured *position*; only\n\t// its target moves, so the lighting direction is preserved while the shadow frustum recentres.\n\tlight.target.position.copy(center);\n\tlight.target.updateMatrixWorld();\n\n\t// Near/far bracket the content along the light→centre axis. Clamp near to a small positive value\n\t// so a light sitting inside the bounds can't push near ≤ 0.\n\tconst lightDistance = light.position.distanceTo(center);\n\tcam.near = Math.max(radius * 0.01, lightDistance - radius);\n\tcam.far = lightDistance + radius;\n\tcam.updateProjectionMatrix();\n}\n\nfunction createScene(config: Required<ThreeInitializerOptions>): THREE.Scene {\n\tconst scene = new THREE.Scene();\n\n\tconst bgColor =\n\t\ttypeof config.environment.backgroundColor === 'string'\n\t\t\t? new THREE.Color(config.environment.backgroundColor)\n\t\t\t: config.environment.backgroundColor;\n\tscene.background = bgColor || null;\n\n\treturn scene;\n}\n\n// Resize applied before render so buffer clear and draw happen in the same frame,\n// preventing visible blank frames when the canvas is resized\nfunction createAnimationLoop(\n\trenderer: THREE.WebGLRenderer,\n\tscene: THREE.Scene,\n\tcamera: THREE.PerspectiveCamera,\n\tgetActiveCamera: () => THREE.Camera,\n\tcameraController: CameraController,\n\tcontrols: OrbitControls,\n\tgetCanvasSize: () => { width: number; height: number },\n\t// The resolved config.render.pixelRatio — the single source of truth for DPR (see initThree).\n\tpixelRatio: number,\n\tonFrame?: (delta: number) => void,\n\tgrid?: Grid | null,\n\tgizmo?: ViewGizmo | null,\n\tgetRenderPipeline?: () => RenderPipeline | null,\n\tlabelLayer?: LabelLayer | null\n): { animate: () => void; dispose: () => void } {\n\tlet animationId: number | null = null;\n\tlet lastTime = performance.now();\n\n\tconst checkResize = () => {\n\t\tconst { width, height } = getCanvasSize();\n\t\tif (width === 0 || height === 0) return;\n\n\t\t// Must floor, not round: renderer.setSize floors the buffer size, and a mismatched rounding\n\t\t// here makes the comparison never settle — the resize branch would then run every frame.\n\t\tconst newW = Math.floor(width * pixelRatio);\n\t\tconst newH = Math.floor(height * pixelRatio);\n\n\t\tif (renderer.domElement.width !== newW || renderer.domElement.height !== newH) {\n\t\t\trenderer.setPixelRatio(pixelRatio);\n\t\t\trenderer.setSize(width, height, false);\n\t\t\tcamera.aspect = width / height;\n\t\t\tcamera.updateProjectionMatrix();\n\t\t\t// Reshape the orthographic frustum too, if it's the active projection.\n\t\t\tcameraController.updateAspect(width, height);\n\t\t\t// Keep the AO composer's render targets in step with the canvas.\n\t\t\tgetRenderPipeline?.()?.setSize(width, height, pixelRatio);\n\t\t\t// CSS2D overlay matches the canvas's CSS size (not the pixel-ratio buffer size).\n\t\t\tlabelLayer?.setSize(width, height);\n\t\t}\n\t};\n\n\tconst animate = function () {\n\t\tanimationId = requestAnimationFrame(animate);\n\n\t\tconst now = performance.now();\n\t\tconst delta = (now - lastTime) / 1000;\n\t\tlastTime = now;\n\n\t\tcheckResize();\n\n\t\tif (controls.enableDamping || controls.autoRotate) {\n\t\t\tcontrols.update();\n\t\t}\n\n\t\t// Keep the grid centered on the camera so it reads as infinite.\n\t\tif (grid) grid.update(getActiveCamera().position);\n\n\t\t// Advance the gizmo's fade/spin animation (no-op when idle).\n\t\tif (gizmo) gizmo.update(delta);\n\n\t\tonFrame?.(delta);\n\n\t\tconst activeCamera = getActiveCamera();\n\t\tconst renderPipeline = getRenderPipeline?.();\n\t\tif (renderPipeline) {\n\t\t\t// AO path: composer owns the render. Retarget to the active camera in case 2D/3D swapped.\n\t\t\trenderPipeline.setCamera(activeCamera);\n\t\t\trenderPipeline.render(delta);\n\t\t} else {\n\t\t\trenderer.render(scene, activeCamera);\n\t\t}\n\n\t\t// HTML labels follow their 3D anchors — render the DOM overlay against the active camera.\n\t\tif (labelLayer) labelLayer.render(scene, activeCamera);\n\n\t\t// The gizmo draws as an overlay in a corner viewport with its own clear; render it last so it\n\t\t// sits on top of the scene.\n\t\tif (gizmo) gizmo.render(renderer);\n\t};\n\n\tconst dispose = () => {\n\t\tif (animationId !== null) {\n\t\t\tcancelAnimationFrame(animationId);\n\t\t\tanimationId = null;\n\t\t}\n\t};\n\n\treturn { animate, dispose };\n}\n\nfunction setupEnvironment(\n\tscene: THREE.Scene,\n\tconfig: Required<ThreeInitializerOptions>,\n\tisDisposed: () => boolean\n) {\n\tif (config.environment.enableEnvironmentLighting) {\n\t\tnew HDRLoader().load(\n\t\t\tconfig.environment.hdrPath || '/baseHDR.hdr',\n\t\t\tfunction (envMap) {\n\t\t\t\t// The viewer can be torn down while the HDR is still fetching/decoding (fast\n\t\t\t\t// mount/unmount). dispose() has already swept the scene, so adopting the texture now\n\t\t\t\t// would leak it — and onReady must not fire on a dead viewer.\n\t\t\t\tif (isDisposed()) {\n\t\t\t\t\tenvMap.dispose();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (!envMap?.image) {\n\t\t\t\t\tgetLogger().warn('HDR loaded without image data; skipping environment map.');\n\t\t\t\t\t// The texture object still holds GPU/CPU resources even without usable image data —\n\t\t\t\t\t// dispose it, since it will never be attached to the scene.\n\t\t\t\t\tenvMap?.dispose();\n\t\t\t\t\tconfig.events.onReady?.();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tenvMap.mapping = THREE.EquirectangularReflectionMapping;\n\t\t\t\tscene.environment = envMap;\n\t\t\t\tif (config.environment.showEnvironment) {\n\t\t\t\t\tscene.background = envMap;\n\t\t\t\t}\n\t\t\t\tconfig.events.onReady?.();\n\t\t\t},\n\t\t\tundefined,\n\t\t\tfunction (error) {\n\t\t\t\tif (isDisposed()) return;\n\t\t\t\tgetLogger().warn('HDR texture could not be loaded, falling back to basic lighting:', error);\n\t\t\t\tconfig.events.onReady?.();\n\t\t\t}\n\t\t);\n\t} else {\n\t\tconfig.events.onReady?.();\n\t}\n}\n\n/**\n * Set up scene lighting. Returns the shadow-casting sun, if any, so the caller can refit its shadow\n * frustum to the scene whenever geometry changes (see `fitShadowToContent`). Returns null when\n * sunlight is disabled or shadows are off — there is then nothing to refit.\n */\nfunction setupLighting(\n\tscene: THREE.Scene,\n\tconfig: Required<ThreeInitializerOptions>\n): THREE.DirectionalLight | null {\n\tconst ambientLight = new THREE.AmbientLight(\n\t\tconfig.lighting.ambientLightColor,\n\t\tconfig.lighting.ambientLightIntensity\n\t);\n\tscene.add(ambientLight);\n\n\tif (!config.lighting.enableSunlight) return null;\n\n\tconst sunlight = new THREE.DirectionalLight(\n\t\tconfig.lighting.sunlightColor ?? 0xffffff,\n\t\tconfig.lighting.sunlightIntensity\n\t);\n\tconst pos = config.lighting.sunlightPosition;\n\tif (pos) {\n\t\tsunlight.position.set(pos.x, pos.y, pos.z);\n\t}\n\n\tif (!config.render.enableShadows) {\n\t\tscene.add(sunlight);\n\t\treturn null;\n\t}\n\n\tsunlight.castShadow = true;\n\n\t// The frustum bounds (left/right/top/bottom/near/far) are not set here — they are fitted to the\n\t// scene content by fitShadowToContent, called at init and on every geometry change. Sizing them\n\t// to the model instead of a fixed constant is the dominant lever on shadow crispness.\n\tsunlight.shadow.mapSize.width = config.render.shadowMapSize || 2048;\n\tsunlight.shadow.mapSize.height = config.render.shadowMapSize || 2048;\n\n\tsunlight.shadow.bias = -0.0001;\n\tsunlight.shadow.normalBias = 0.02;\n\t// Soften VSM edges; cheap and only meaningful once the frustum is tight (see fitShadowToContent).\n\tsunlight.shadow.radius = 4;\n\n\tscene.add(sunlight);\n\t// A DirectionalLight aims at its target's world position; the target must be in the scene graph\n\t// for its matrix to update. fitShadowToContent moves this target to the content centre.\n\tscene.add(sunlight.target);\n\treturn sunlight;\n}\n\nfunction addFloor(scene: THREE.Scene, config: Required<ThreeInitializerOptions>) {\n\tconst floorSize = config.floor.size;\n\tconst floorGeometry = new THREE.PlaneGeometry(floorSize, floorSize);\n\n\tconst floorColor =\n\t\ttypeof config.floor.color === 'string'\n\t\t\t? new THREE.Color(config.floor.color)\n\t\t\t: config.floor.color;\n\n\tconst floorMaterial = new THREE.MeshStandardMaterial({\n\t\tcolor: floorColor,\n\t\troughness: config.floor.roughness,\n\t\tmetalness: config.floor.metalness,\n\t\tside: THREE.DoubleSide\n\t});\n\n\tconst floor = new THREE.Mesh(floorGeometry, floorMaterial);\n\tfloor.userData.id = 'floor';\n\tfloor.name = 'floor';\n\t// PlaneGeometry lies in XY with a +Z normal — already the ground for a Z-up scene. Orient its\n\t// normal to the scene up axis so the floor is the ground plane in any up convention.\n\tconst up = (config.environment?.sceneUp || defaultUp).clone().normalize();\n\tfloor.quaternion.setFromUnitVectors(new THREE.Vector3(0, 0, 1), up);\n\tfloor.position.set(0, 0, 0);\n\n\tif (config.floor.receiveShadow && config.render.enableShadows) {\n\t\tfloor.receiveShadow = true;\n\t}\n\n\tscene.add(floor);\n}\n\nfunction createCamera(\n\tconfig: Required<ThreeInitializerOptions>,\n\tcanvas: HTMLCanvasElement\n): THREE.PerspectiveCamera {\n\tconst parent = canvas.parentElement;\n\tconst width = parent ? parent.clientWidth : window.innerWidth;\n\tconst height = parent ? parent.clientHeight : window.innerHeight;\n\n\tconst camera = new THREE.PerspectiveCamera(\n\t\tconfig.camera.fov,\n\t\twidth / height,\n\t\tconfig.camera.near,\n\t\tconfig.camera.far\n\t);\n\n\tconst pos = config.camera.position;\n\tif (pos) {\n\t\tcamera.position.set(pos.x, pos.y, pos.z);\n\t}\n\n\treturn camera;\n}\n\nfunction setupRenderer(\n\tcanvas: HTMLCanvasElement,\n\tconfig: Required<ThreeInitializerOptions>,\n\tpixelRatio: number\n): THREE.WebGLRenderer {\n\tconst renderer = new THREE.WebGLRenderer({\n\t\tantialias: config.render.antialias,\n\t\tcanvas,\n\t\talpha: true,\n\t\tpowerPreference: 'high-performance',\n\t\tpreserveDrawingBuffer: config.render.preserveDrawingBuffer,\n\t\t// Deliberately NOT logarithmic: three's depth-based post passes (our GTAO pipeline) reconstruct\n\t\t// view-space positions assuming standard perspective depth and do not support log-encoded\n\t\t// depth — with it on, AO is computed from wrong depths (haloing, wrong-scale occlusion). The\n\t\t// per-scale near/far defaults (see applyDefaults) keep standard depth precision adequate for\n\t\t// the viewer's scene scales. If log depth is ever needed, AO must be disabled with it.\n\t\tlogarithmicDepthBuffer: false\n\t});\n\n\tconst parent = canvas.parentElement;\n\tconst width = parent ? parent.clientWidth : window.innerWidth;\n\tconst height = parent ? parent.clientHeight : window.innerHeight;\n\n\tif (parent) {\n\t\tcanvas.style.width = '100%';\n\t\tcanvas.style.height = '100%';\n\t\tcanvas.style.display = 'block';\n\t}\n\n\trenderer.setSize(width, height, false);\n\trenderer.setPixelRatio(pixelRatio);\n\n\tif (config.render.enableShadows) {\n\t\trenderer.shadowMap.enabled = true;\n\t\trenderer.shadowMap.type = THREE.VSMShadowMap;\n\t}\n\n\trenderer.toneMapping = config.render.toneMapping!;\n\trenderer.toneMappingExposure = config.render.toneMappingExposure ?? 1.0;\n\trenderer.outputColorSpace = THREE.SRGBColorSpace;\n\n\trenderer.sortObjects = true;\n\n\treturn renderer;\n}\n\nfunction setupEventHandlers(\n\tcanvas: HTMLCanvasElement,\n\tscene: THREE.Scene,\n\tcameraController: CameraController,\n\tconfig: Required<ThreeInitializerOptions>\n): {\n\tdispose: () => void;\n\tfitToView: () => void;\n\tclearSelection: () => void;\n} {\n\tconst selectedObjects = new Set<THREE.Object3D>();\n\tconst originalMaterials = new Map<THREE.Object3D, THREE.Material | THREE.Material[]>();\n\tconst raycaster = new THREE.Raycaster();\n\tconst mouse = new THREE.Vector2();\n\tconst mouseDownPosition = new THREE.Vector2();\n\tconst getActiveCamera = () => cameraController.getActiveCamera();\n\n\t// An object is hittable only if every ancestor is also visible. Three.js's\n\t// recursive intersect doesn't enforce that — it can hit a visible Mesh inside\n\t// a hidden Group.\n\tconst isFullyVisible = (object: THREE.Object3D): boolean => {\n\t\tlet current: THREE.Object3D | null = object;\n\t\twhile (current) {\n\t\t\tif (!current.visible) return false;\n\t\t\tcurrent = current.parent;\n\t\t}\n\t\treturn true;\n\t};\n\n\tconst fitToView = () => {\n\t\t// Frame the scene's renderable content; viewer aids (grid/floor/labels/measure) are excluded so\n\t\t// the camera-tracking grid plane can't dominate the bounds and blow up the fit distance.\n\t\tconst box = computeContentBounds(scene);\n\n\t\tif (box.isEmpty()) {\n\t\t\tgetLogger().warn('No objects to fit to view');\n\t\t\treturn;\n\t\t}\n\n\t\t// Delegate the move to the camera controller: it frames from the current view direction and\n\t\t// repositions whichever camera is LIVE, re-deriving the ortho frustum in 2D mode — whereas\n\t\t// moving the perspective camera directly would change nothing visible in 2D (and silently\n\t\t// drag the invisible perspective camera out of sync).\n\t\tcameraController.frameBounds(box, false);\n\t};\n\n\tconst selectionColorObj =\n\t\ttypeof config.events.selectionColor === 'string'\n\t\t\t? new THREE.Color(config.events.selectionColor)\n\t\t\t: config.events.selectionColor instanceof THREE.Color\n\t\t\t\t? config.events.selectionColor\n\t\t\t\t: new THREE.Color('#ff0000');\n\n\tconst clearSelection = () => {\n\t\tselectedObjects.forEach((obj) => {\n\t\t\tconst restorable = obj as THREE.Object3D & {\n\t\t\t\tmaterial?: THREE.Material | THREE.Material[];\n\t\t\t};\n\t\t\tif (originalMaterials.has(obj)) {\n\t\t\t\tconst original = originalMaterials.get(obj)!;\n\t\t\t\t// Dispose the clone we swapped in before restoring the original.\n\t\t\t\tconst clone = restorable.material;\n\t\t\t\tif (clone instanceof THREE.Material) clone.dispose();\n\t\t\t\telse if (Array.isArray(clone)) clone.forEach((m) => m.dispose());\n\t\t\t\trestorable.material = original;\n\t\t\t\toriginalMaterials.delete(obj);\n\n\t\t\t\t// If the object left the scene while selected (a solve's clearScene only saw — and\n\t\t\t\t// disposed — the highlight clone), no later scene traversal can reach the original we\n\t\t\t\t// just restored, so it must be disposed here. Compute content is cleared wholesale per\n\t\t\t\t// solve, so a detached object's material has no surviving sharers.\n\t\t\t\tlet root: THREE.Object3D = obj;\n\t\t\t\twhile (root.parent) root = root.parent;\n\t\t\t\tif (root !== scene) {\n\t\t\t\t\tif (original instanceof THREE.Material) original.dispose();\n\t\t\t\t\telse original.forEach((m) => m.dispose());\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tselectedObjects.clear();\n\t};\n\n\t// Highlight a selected object by cloning its material and recoloring. Meshes get an `emissive`\n\t// tint (so the surface keeps its base color); lines and points have no emissive channel, so we\n\t// recolor `color` directly. Returns true if a highlight was applied (a material was found).\n\tconst applyHighlight = (object: THREE.Object3D): boolean => {\n\t\tconst target = object as THREE.Object3D & { material?: THREE.Material | THREE.Material[] };\n\t\tif (!(target.material instanceof THREE.Material)) return false;\n\n\t\toriginalMaterials.set(object, target.material);\n\t\tconst clone = target.material.clone();\n\n\t\tif (object instanceof THREE.Mesh && 'emissive' in clone) {\n\t\t\t(clone as THREE.MeshStandardMaterial).emissive = selectionColorObj.clone();\n\t\t} else if ('color' in clone) {\n\t\t\t(clone as THREE.LineBasicMaterial).color = selectionColorObj.clone();\n\t\t}\n\n\t\ttarget.material = clone;\n\t\treturn true;\n\t};\n\n\t// Picking lines and points needs a ray-to-geometry tolerance, scaled to the scene so it holds at\n\t// any zoom. Plain THREE.Points use Raycaster.params.Points.threshold; fat Line2 uses its own\n\t// material linewidth, so only Points needs this. (THREE.Line would use params.Line.threshold, but\n\t// curves here are Line2.) Recomputed per pick from the current scene bounds.\n\tconst updatePickThresholds = () => {\n\t\tconst box = computeContentBounds(scene);\n\t\tconst diagonal = box.isEmpty() ? 1 : box.getSize(new THREE.Vector3()).length();\n\t\traycaster.params.Points.threshold = diagonal * 0.01;\n\t};\n\n\tconst handleMouseDown = (event: MouseEvent) => {\n\t\tmouseDownPosition.set(event.clientX, event.clientY);\n\t};\n\n\tconst handleCanvasClick = (event: MouseEvent) => {\n\t\t// Ignore if mouse has moved (drag)\n\t\tconst currentMousePosition = new THREE.Vector2(event.clientX, event.clientY);\n\t\tif (mouseDownPosition.distanceTo(currentMousePosition) > 5) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst rect = canvas.getBoundingClientRect();\n\t\tmouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;\n\t\tmouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;\n\n\t\tupdatePickThresholds();\n\t\traycaster.setFromCamera(mouse, getActiveCamera());\n\t\tconst intersects = raycaster\n\t\t\t.intersectObjects(scene.children, true)\n\t\t\t.filter((i) => isFullyVisible(i.object));\n\n\t\tif (intersects.length > 0) {\n\t\t\tconst clickedObject = intersects[0].object;\n\n\t\t\tif (!selectedObjects.has(clickedObject)) {\n\t\t\t\tclearSelection();\n\t\t\t\tselectedObjects.add(clickedObject);\n\n\t\t\t\t// Clone material (so siblings sharing it are untouched) and recolor to highlight.\n\t\t\t\t// Handles meshes, fat lines, and points alike.\n\t\t\t\tapplyHighlight(clickedObject);\n\n\t\t\t\tconfig.events?.onObjectSelected?.(clickedObject);\n\n\t\t\t\tif (clickedObject instanceof THREE.Mesh && Object.keys(clickedObject.userData).length > 0) {\n\t\t\t\t\tconfig.events?.onMeshMetadataClicked?.(clickedObject.userData);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tclearSelection();\n\t\t\tconfig.events?.onBackgroundClicked?.({ x: mouse.x, y: mouse.y });\n\t\t}\n\t};\n\n\tconst handleDoubleClick = (event: MouseEvent) => {\n\t\tconst rect = canvas.getBoundingClientRect();\n\t\tmouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;\n\t\tmouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;\n\n\t\tupdatePickThresholds();\n\t\traycaster.setFromCamera(mouse, getActiveCamera());\n\t\tconst intersects = raycaster\n\t\t\t.intersectObjects(scene.children, true)\n\t\t\t.filter((i) => isFullyVisible(i.object));\n\n\t\tif (intersects.length === 0) return;\n\n\t\tconst target = intersects[0].object;\n\t\tconfig.events?.onMeshDoubleClicked?.(target);\n\n\t\tif (!config.events?.enableDoubleClickZoom) return;\n\n\t\tconst box = new THREE.Box3().setFromObject(target);\n\t\tif (box.isEmpty()) return;\n\n\t\t// Frame the clicked object via the controller so the ACTIVE camera moves (ortho included —\n\t\t// its frustum is re-derived, since translating an ortho camera alone zooms nothing). The\n\t\t// controller's tween is cancellable: a rapid second double-click replaces the first tween\n\t\t// instead of running a competing loop, and dispose() stops it outright.\n\t\tcameraController.frameBounds(box, true);\n\t};\n\n\tconst handleKeydown = (event: KeyboardEvent) => {\n\t\tif (!config.events?.enableKeyboardControls) return;\n\n\t\tswitch (event.key.toLowerCase()) {\n\t\t\tcase 'f':\n\t\t\t\tevent.preventDefault();\n\t\t\t\tfitToView();\n\t\t\t\tbreak;\n\t\t\tcase 'escape':\n\t\t\t\tevent.preventDefault();\n\t\t\t\tclearSelection();\n\t\t\t\tbreak;\n\t\t\tcase ' ':\n\t\t\t\tevent.preventDefault();\n\t\t\t\tfitToView();\n\t\t\t\tbreak;\n\t\t}\n\t};\n\n\tif (config.events?.enableClickToFocus) {\n\t\tcanvas.addEventListener('mousedown', handleMouseDown);\n\t\tcanvas.addEventListener('click', handleCanvasClick);\n\t\tcanvas.addEventListener('dblclick', handleDoubleClick);\n\t}\n\n\tif (config.events?.enableKeyboardControls) {\n\t\tcanvas.setAttribute('tabindex', '0');\n\t\tcanvas.addEventListener('keydown', handleKeydown);\n\t}\n\n\tconst dispose = () => {\n\t\tcanvas.removeEventListener('mousedown', handleMouseDown);\n\t\tcanvas.removeEventListener('click', handleCanvasClick);\n\t\tcanvas.removeEventListener('dblclick', handleDoubleClick);\n\t\tcanvas.removeEventListener('keydown', handleKeydown);\n\t\tclearSelection();\n\t};\n\n\treturn { dispose, fitToView, clearSelection };\n}\n\nfunction setupControls(\n\tcamera: THREE.PerspectiveCamera,\n\tcanvas: HTMLCanvasElement,\n\tconfig: Required<ThreeInitializerOptions>\n): OrbitControls {\n\tconst controls = new OrbitControls(camera, canvas);\n\n\tconst target = config.camera.target;\n\tif (target) {\n\t\tcontrols.target.set(target.x, target.y, target.z);\n\t}\n\n\tcontrols.enableDamping = config.controls.enableDamping || false;\n\tcontrols.dampingFactor = config.controls.dampingFactor || 0.05;\n\n\tcontrols.autoRotate = config.controls.autoRotate || false;\n\tcontrols.autoRotateSpeed = config.controls.autoRotateSpeed || 0.5;\n\n\tcontrols.enableZoom = config.controls.enableZoom ?? true;\n\tcontrols.enablePan = config.controls.enablePan ?? true;\n\tcontrols.minDistance = config.controls.minDistance || 0.001;\n\tcontrols.maxDistance = config.controls.maxDistance || Infinity;\n\n\tcontrols.screenSpacePanning = false;\n\tcontrols.maxPolarAngle = Math.PI;\n\n\tcontrols.update();\n\treturn controls;\n}\n","import * as THREE from 'three';\n\nimport { parseColor } from '../threejs/three-helpers.js';\nimport { getLogger } from '@/core';\nimport { RhinoComputeError, ErrorCodes } from '@/core/errors';\n\nimport { FLAG_FLOAT32, parseBinaryMeshBatch } from './binary-parser.js';\nimport { applyTextureMap } from './texture-cache.js';\n\nimport type { ParsedBinaryMeshBatch } from './binary-parser.js';\nimport type {\n\tDisplayBatch,\n\tMaterialAppearanceOptions,\n\tMaterialGroup,\n\tMeshBatchParsingOptions,\n\tMeshMetadata,\n\tSerializableMaterial\n} from './types.js';\n\n/**\n * Internal-only telemetry threaded from an outer entry point (e.g. the JSON\n * `parseMeshBatch` measuring its own `JSON.parse` cost) into the shared build\n * step. Never part of any public options surface — callers don't supply timings.\n */\ninterface ParseTelemetry {\n\tparseTime?: number;\n\tperfStart?: number;\n}\n\n/**\n * Parses a batched mesh JSON and creates Three.js meshes.\n *\n * The geometry payload is the binary \"SLVA\" blob produced by the C# `BinaryGeometryWriter`,\n * base64-encoded into the outer JSON envelope. We `JSON.parse` the small envelope, then hand the\n * blob to `parseBinaryMeshBatch` which decodes the geometry without ever turning it into a string.\n *\n * An invalid JSON envelope (not a batch at all) logs and returns `[]` — that is the\n * \"genuinely absent data\" case. A batch whose *blob* is corrupt, truncated, or unsupported throws\n * instead of silently rendering an empty scene.\n *\n * @param batchJson - JSON string containing the batched mesh data\n * @param options - Rendering options\n * @returns Promise resolving to array of Three.js mesh objects\n * @throws {RhinoComputeError} On a corrupt/truncated/unsupported mesh blob or malformed group metadata.\n */\nexport async function parseMeshBatch(\n\tbatchJson: string,\n\toptions?: MeshBatchParsingOptions\n): Promise<THREE.Mesh[]> {\n\tconst { debug = false } = options ?? {};\n\n\tconst perfStart = debug ? performance.now() : 0;\n\n\t// Narrow catch: only the envelope JSON.parse is allowed to degrade to []. Blob parse errors\n\t// from parseMeshBatchObject propagate — see that entry point's contract.\n\tlet batch: DisplayBatch;\n\tconst parseStart = performance.now();\n\ttry {\n\t\tbatch = JSON.parse(batchJson);\n\t} catch (error) {\n\t\tgetLogger().error('Error parsing mesh batch envelope JSON:', error);\n\t\treturn [];\n\t}\n\tconst parseTime = performance.now() - parseStart;\n\n\treturn await parseMeshBatchObject(batch, options, { parseTime, perfStart });\n}\n\n/**\n * Parses a DisplayBatch object and creates Three.js meshes from its mesh blob.\n *\n * The path is synchronous internally — `parseBinaryMeshBatch` does no IO, just typed-array views\n * over the blob. The function stays `async` so callers don't have to change shape if we move\n * parsing into a worker later.\n *\n * A batch with no `compressedData` (genuinely empty/absent geometry) resolves to `[]`. A corrupt,\n * truncated, or unsupported blob throws so callers get a signal instead of a silent empty scene —\n * `getThreeMeshesFromComputeResponse` documents (and now delivers) exactly that rethrow.\n *\n * @param batch - DisplayBatch object\n * @param options - Rendering options\n * @returns Promise resolving to array of Three.js mesh objects\n * @throws {RhinoComputeError} On a corrupt/truncated/unsupported mesh blob or malformed group metadata.\n */\nexport async function parseMeshBatchObject(\n\tbatch: DisplayBatch,\n\toptions?: MeshBatchParsingOptions,\n\t/** @internal Timings threaded from an outer entry point; not a caller option. */\n\ttelemetry?: ParseTelemetry\n): Promise<THREE.Mesh[]> {\n\tconst { mergeByMaterial = true, applyTransforms = true, debug = false, material } = options ?? {};\n\tconst { parseTime = 0, perfStart = debug ? performance.now() : 0 } = telemetry ?? {};\n\n\tif (!batch.compressedData) {\n\t\t// No blob at all — an items-only or empty batch. This is the one entry-point path that\n\t\t// legitimately yields [] rather than throwing.\n\t\treturn [];\n\t}\n\n\tconst decodeStart = performance.now();\n\tconst parsed = parseBinaryMeshBatch(batch.compressedData);\n\tconst decodeTime = performance.now() - decodeStart;\n\n\tconst blobBytes = debug ? approximateBase64DecodedBytes(batch.compressedData) : 0;\n\n\treturn buildMeshesFromParsed(parsed, {\n\t\tmergeByMaterial,\n\t\tapplyTransforms,\n\t\tdebug,\n\t\tmaterial,\n\t\tparseTime,\n\t\tdecodeTime,\n\t\tperfStart,\n\t\tblobBytes,\n\t\tfallback: {\n\t\t\tmaterials: batch.materials,\n\t\t\tgroups: batch.groups,\n\t\t\tsourceComponentId: batch.sourceComponentId\n\t\t}\n\t});\n}\n\n/**\n * Parses a raw binary mesh batch blob (SLVA wire format) and creates Three.js meshes.\n *\n * Use this entry point when the blob arrives as a binary WebSocket frame (Phase 1b transport):\n * the JSON envelope no longer carries `displayData`, so there's nothing to `JSON.parse`. The blob\n * is self-describing — materials, groups, and `sourceComponentId` come from its embedded metadata\n * header.\n *\n * @param blob - Raw blob bytes from a binary WebSocket frame.\n * @param options - Rendering options.\n * @returns Promise resolving to array of Three.js mesh objects.\n * @throws {RhinoComputeError} On a corrupt/truncated/unsupported mesh blob or malformed group metadata.\n */\nexport async function parseMeshBatchBlob(\n\tblob: ArrayBuffer | Uint8Array,\n\toptions?: MeshBatchParsingOptions\n): Promise<THREE.Mesh[]> {\n\tconst { mergeByMaterial = true, applyTransforms = true, debug = false, material } = options ?? {};\n\n\tconst perfStart = debug ? performance.now() : 0;\n\n\tconst decodeStart = performance.now();\n\tconst parsed = parseBinaryMeshBatch(blob);\n\tconst decodeTime = performance.now() - decodeStart;\n\n\tconst blobBytes = blob.byteLength;\n\n\treturn buildMeshesFromParsed(parsed, {\n\t\tmergeByMaterial,\n\t\tapplyTransforms,\n\t\tdebug,\n\t\tmaterial,\n\t\tparseTime: 0,\n\t\tdecodeTime,\n\t\tperfStart,\n\t\tblobBytes\n\t});\n}\n\ninterface BuildOptions {\n\tmergeByMaterial: boolean;\n\tapplyTransforms: boolean;\n\tdebug: boolean;\n\tmaterial?: MaterialAppearanceOptions;\n\tparseTime: number;\n\tdecodeTime: number;\n\tperfStart: number;\n\tblobBytes: number;\n\t/** Outer-envelope fallback when the blob's metadata is missing fields (defensive). */\n\tfallback?: {\n\t\tmaterials?: SerializableMaterial[];\n\t\tgroups?: MaterialGroup[];\n\t\tsourceComponentId?: string;\n\t};\n}\n\nfunction buildMeshesFromParsed(\n\tparsed: ParsedBinaryMeshBatch,\n\topts: BuildOptions\n): Promise<THREE.Mesh[]> {\n\tconst {\n\t\tmergeByMaterial,\n\t\tapplyTransforms,\n\t\tdebug,\n\t\tmaterial: materialAppearance,\n\t\tparseTime,\n\t\tdecodeTime,\n\t\tperfStart,\n\t\tblobBytes,\n\t\tfallback\n\t} = opts;\n\n\tconst materialsSrc = parsed.metadata.materials ?? fallback?.materials ?? [];\n\tconst groups = parsed.metadata.groups ?? fallback?.groups ?? [];\n\t// Prefer the outer envelope's sourceComponentId over the blob's embedded one. The blob bakes in\n\t// the id at encode time, but a reloaded part (e.g. from a .dmf instanced many times) re-stamps a\n\t// fresh id on the envelope to keep web pick identity distinct per placement. The blob value is\n\t// the fallback for the raw-blob transport, which has no envelope.\n\tconst sourceComponentId = fallback?.sourceComponentId ?? parsed.metadata.sourceComponentId;\n\n\tconst isFloat32 = (parsed.flags & FLAG_FLOAT32) !== 0;\n\n\t// Group metadata arrives as embedded (or envelope) JSON and is used arithmetically below —\n\t// unchecked, a bad vertexStart/indexStart wraps rebased indices into a Uint32Array, `subarray`\n\t// silently clamps, and an out-of-range materialId feeds `undefined` into `new THREE.Mesh`.\n\t// Fail the parse instead of silently corrupting the render.\n\tvalidateGroupMetadata(\n\t\tgroups,\n\t\tmaterialsSrc.length,\n\t\tparsed.vertices.length / 3,\n\t\tparsed.indices.length\n\t);\n\n\t// Dequantize once up-front into a single Float32Array. Downstream code (per-group merging,\n\t// computeVertexNormals, ground-offset) all expect world-unit floats, and a single\n\t// linear pass over the int16 buffer is far cheaper than the legacy gunzip + base64 path. The\n\t// Z-up -> Y-up rotation, when requested, is folded into the same pass.\n\tconst worldVertices = isFloat32\n\t\t? maybeRotateFloat32Vertices(parsed.vertices as Float32Array, applyTransforms)\n\t\t: dequantizeInt16(parsed.vertices as Int16Array, parsed.origin, parsed.scale, applyTransforms);\n\n\tif (debug) {\n\t\tconst wireBytes = parsed.vertices.byteLength + parsed.indices.byteLength;\n\t\tgetLogger().debug('Mesh Batch Stats:');\n\t\tgetLogger().debug(` Materials: ${materialsSrc.length} | Groups: ${groups.length}`);\n\t\tgetLogger().debug(\n\t\t\t` Vertices: ${parsed.vertices.length / 3} | Indices: ${parsed.indices.length}`\n\t\t);\n\t\tgetLogger().debug(` Format: ${isFloat32 ? 'float32' : 'int16 quantized'}`);\n\t\tgetLogger().debug(\n\t\t\t` Blob: ${(blobBytes / 1024 / 1024).toFixed(2)} MB | Geometry on wire: ${(wireBytes / 1024 / 1024).toFixed(2)} MB`\n\t\t);\n\t}\n\n\tconst meshCreateStart = performance.now();\n\t// Vertex colors are batch-wide when present (meshes without real colors carry a white fill,\n\t// which multiplies to identity), so the material can enable vertexColors unconditionally.\n\tconst materials = materialsSrc.map((m) =>\n\t\tcreateMaterial(m, {\n\t\t\tvertexColors: parsed.colors != null,\n\t\t\tappearance: materialAppearance\n\t\t})\n\t);\n\n\tconst meshes: THREE.Mesh[] = [];\n\n\tfor (const group of groups) {\n\t\tif (mergeByMaterial && group.meshes.length > 1) {\n\t\t\tconst mergedMesh = createMergedMesh(\n\t\t\t\tgroup,\n\t\t\t\tworldVertices,\n\t\t\t\tparsed.indices,\n\t\t\t\tmaterials,\n\t\t\t\tparsed.uvs,\n\t\t\t\tparsed.colors\n\t\t\t);\n\t\t\tmergedMesh.userData.sourceComponentId = sourceComponentId ?? null;\n\t\t\tmeshes.push(mergedMesh);\n\t\t} else {\n\t\t\tconst individualMeshes = createIndividualMeshes(\n\t\t\t\tgroup,\n\t\t\t\tworldVertices,\n\t\t\t\tparsed.indices,\n\t\t\t\tmaterials,\n\t\t\t\tparsed.uvs,\n\t\t\t\tparsed.colors\n\t\t\t);\n\t\t\tfor (const mesh of individualMeshes) {\n\t\t\t\tmesh.userData.sourceComponentId = sourceComponentId ?? null;\n\t\t\t}\n\t\t\tmeshes.push(...individualMeshes);\n\t\t}\n\t}\n\n\tconst meshCreateTime = performance.now() - meshCreateStart;\n\n\tif (debug) {\n\t\tconst totalTime = performance.now() - perfStart;\n\t\tgetLogger().debug('Performance:');\n\t\tif (parseTime > 0) getLogger().debug(` Parse JSON: ${parseTime.toFixed(2)}ms`);\n\t\tgetLogger().debug(` Decode binary: ${decodeTime.toFixed(2)}ms`);\n\t\tgetLogger().debug(` Create Meshes: ${meshCreateTime.toFixed(2)}ms`);\n\t\tgetLogger().debug(` Total: ${totalTime.toFixed(2)}ms`);\n\t}\n\n\treturn Promise.resolve(meshes);\n}\n\n// ============================================================================\n// GROUP METADATA VALIDATION\n// ============================================================================\n\nfunction metadataFail(message: string, context: Record<string, unknown>): RhinoComputeError {\n\treturn new RhinoComputeError(message, ErrorCodes.VALIDATION_ERROR, { context });\n}\n\n/**\n * Validates the batch's group/mesh metadata against the decoded geometry buffers before any of it\n * is used arithmetically. Throws a VALIDATION_ERROR on the first inconsistency (out-of-range\n * `materialId`, non-integer or negative offsets/counts, or vertex/index windows that overrun the\n * buffers) so malformed or version-skewed metadata fails the parse loudly.\n */\nfunction validateGroupMetadata(\n\tgroups: MaterialGroup[],\n\tmaterialCount: number,\n\ttotalVertexCount: number,\n\ttotalIndexCount: number\n): void {\n\tfor (const group of groups) {\n\t\tif (\n\t\t\t!Number.isInteger(group.materialId) ||\n\t\t\tgroup.materialId < 0 ||\n\t\t\tgroup.materialId >= materialCount\n\t\t) {\n\t\t\tthrow metadataFail('Group materialId out of range of the materials array.', {\n\t\t\t\tmaterialId: group.materialId,\n\t\t\t\tmaterialCount\n\t\t\t});\n\t\t}\n\n\t\tfor (const mesh of group.meshes) {\n\t\t\tconst fields = {\n\t\t\t\tvertexStart: mesh.vertexStart,\n\t\t\t\tvertexCount: mesh.vertexCount,\n\t\t\t\tindexStart: mesh.indexStart,\n\t\t\t\tindexCount: mesh.indexCount\n\t\t\t};\n\t\t\tfor (const [field, value] of Object.entries(fields)) {\n\t\t\t\tif (!Number.isInteger(value) || value < 0) {\n\t\t\t\t\tthrow metadataFail(`Mesh metadata field \"${field}\" must be a non-negative integer.`, {\n\t\t\t\t\t\tmeshName: mesh.name,\n\t\t\t\t\t\tfield,\n\t\t\t\t\t\tvalue\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (mesh.vertexStart + mesh.vertexCount > totalVertexCount) {\n\t\t\t\tthrow metadataFail('Mesh vertex window exceeds the batch vertex buffer.', {\n\t\t\t\t\tmeshName: mesh.name,\n\t\t\t\t\tvertexStart: mesh.vertexStart,\n\t\t\t\t\tvertexCount: mesh.vertexCount,\n\t\t\t\t\ttotalVertexCount\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif (mesh.indexStart + mesh.indexCount > totalIndexCount) {\n\t\t\t\tthrow metadataFail('Mesh index window exceeds the batch index buffer.', {\n\t\t\t\t\tmeshName: mesh.name,\n\t\t\t\t\tindexStart: mesh.indexStart,\n\t\t\t\t\tindexCount: mesh.indexCount,\n\t\t\t\t\ttotalIndexCount\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Asserts an index value falls inside its mesh's declared vertex window\n * `[vertexStart, vertexStart + vertexCount)`. Rebasing (`index - vertexStart`) writes into an\n * unsigned array, so a violation would otherwise wrap to ~4 billion and corrupt the geometry.\n */\nfunction assertIndexInWindow(indexValue: number, meshMeta: MeshMetadata): void {\n\tif (\n\t\tindexValue < meshMeta.vertexStart ||\n\t\tindexValue >= meshMeta.vertexStart + meshMeta.vertexCount\n\t) {\n\t\tthrow metadataFail(\"Index references a vertex outside its mesh's vertex window.\", {\n\t\t\tmeshName: meshMeta.name,\n\t\t\tindexValue,\n\t\t\tvertexStart: meshMeta.vertexStart,\n\t\t\tvertexCount: meshMeta.vertexCount\n\t\t});\n\t}\n}\n\n// ============================================================================\n// DEQUANTIZATION\n// ============================================================================\n\n/**\n * Reconstructs world-unit float32 positions from int16 quantized values.\n *\n * Mirrors the encoder formula: `world = origin + (q + 32767) * scale`. Selva keeps one coordinate\n * frame end to end (the Three scene is Rhino's Z-up frame — see `../coordinate-transform.ts`), so\n * vertices pass through unrotated. `_applyCoordinateTransform` is retained for call-site\n * compatibility and no longer changes the output.\n */\nfunction dequantizeInt16(\n\tq: Int16Array,\n\torigin: [number, number, number],\n\tscale: [number, number, number],\n\t_applyCoordinateTransform: boolean\n): Float32Array {\n\tconst out = new Float32Array(q.length);\n\tconst ox = origin[0];\n\tconst oy = origin[1];\n\tconst oz = origin[2];\n\tconst sx = scale[0];\n\tconst sy = scale[1];\n\tconst sz = scale[2];\n\n\tfor (let i = 0; i < q.length; i += 3) {\n\t\tout[i] = ox + (q[i]! + 32767) * sx;\n\t\tout[i + 1] = oy + (q[i + 1]! + 32767) * sy;\n\t\tout[i + 2] = oz + (q[i + 2]! + 32767) * sz;\n\t}\n\n\treturn out;\n}\n\n/**\n * For float32 batches the parser's view is already in the scene frame (Rhino Z-up), so we pass it\n * through without copying. `_applyCoordinateTransform` is retained for call-site compatibility and\n * no longer rotates.\n */\nfunction maybeRotateFloat32Vertices(\n\tvertices: Float32Array,\n\t_applyCoordinateTransform: boolean\n): Float32Array {\n\treturn vertices;\n}\n\n// ============================================================================\n// MATERIAL CONSTRUCTION\n// ============================================================================\n\nfunction createMaterial(\n\tmatData: SerializableMaterial,\n\toptions?: { vertexColors?: boolean; appearance?: MaterialAppearanceOptions }\n): THREE.MeshPhysicalMaterial {\n\tconst color = parseColor(matData.color);\n\tconst vertexColors = options?.vertexColors ?? false;\n\tconst appearance = options?.appearance;\n\n\tconst material = new THREE.MeshPhysicalMaterial({\n\t\tcolor,\n\t\tmetalness: matData.metalness,\n\t\troughness: matData.roughness,\n\t\topacity: matData.opacity,\n\t\ttransparent: matData.transparent,\n\t\tvertexColors,\n\t\t// Cull back faces for closed solids (crisper silhouette, less overdraw); keep both sides for\n\t\t// open surfaces. Caller-controlled since Rhino emits both — default DoubleSide is the safe read.\n\t\tside: appearance?.cullBackfaces ? THREE.FrontSide : THREE.DoubleSide,\n\t\t// Reduced polygon offset to minimize artifacts\n\t\t// Only use minimal offset to prevent z-fighting on coplanar faces\n\t\tpolygonOffset: true,\n\t\tpolygonOffsetFactor: 0.5,\n\t\tpolygonOffsetUnits: 0.5,\n\t\t// Improve depth rendering\n\t\tdepthWrite: true,\n\t\tdepthTest: true\n\t});\n\n\t// HDR image-based-lighting reflection strength. Left at three's default (1) unless the caller\n\t// dials it: <1 flattens reflections toward a matte/technical read, >1 pushes a glossier look.\n\tif (appearance?.envMapIntensity != null) {\n\t\tmaterial.envMapIntensity = appearance.envMapIntensity;\n\t}\n\n\t// Vertex colors arrive as raw sRGB bytes, but three's vertex-color path multiplies them into the\n\t// (linear) working space with no decode — so they render washed out. Patch the vertex shader to\n\t// sRGB→linear decode `color` before use. Only meshes with real vertex colors take this path.\n\tif (vertexColors) {\n\t\tapplyVertexColorSRGBDecode(material);\n\t}\n\n\t// Texture loading is async (image decode); the cache assigns `material.map` when ready and\n\t// flags needsUpdate, so the mesh renders untextured for at most the first frames. Hash-keyed\n\t// asset URLs are immutable, so each texture is fetched and decoded once per session.\n\tif (matData.map) {\n\t\tapplyTextureMap(material, matData.map);\n\t}\n\n\treturn material;\n}\n\n/**\n * Patch a material's vertex shader to decode its per-vertex `color` attribute from sRGB to linear.\n * three.js uploads vertex colors verbatim and its `color_vertex` chunk multiplies them straight into\n * the linear working color space (unlike textures, which carry a `colorSpace` and get decoded) — so\n * sRGB-authored vertex colors render too bright without this. Done in the shader (not a CPU pass over\n * the buffer) to keep the hot per-solve parse cheap; the decode is a handful of GPU ops per vertex.\n */\nfunction applyVertexColorSRGBDecode(material: THREE.Material): void {\n\tmaterial.onBeforeCompile = (shader) => {\n\t\tshader.vertexShader = shader.vertexShader.replace(\n\t\t\t'#include <color_vertex>',\n\t\t\t`#include <color_vertex>\n\t\t\t#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )\n\t\t\t\tvColor.rgb = mix(\n\t\t\t\t\tvColor.rgb / 12.92,\n\t\t\t\t\tpow( ( vColor.rgb + 0.055 ) / 1.055, vec3( 2.4 ) ),\n\t\t\t\t\tstep( vec3( 0.04045 ), vColor.rgb )\n\t\t\t\t);\n\t\t\t#endif`\n\t\t);\n\t};\n}\n\n// ============================================================================\n// MESH CONSTRUCTION\n// ============================================================================\n\n/**\n * Creates a merged mesh from multiple meshes sharing the same material.\n *\n * Indices in the parser output already reference offsets into the combined vertex array (the C#\n * pipeline rebases per-mesh local indices into combined-array indices when assembling the batch).\n * For merged meshes we copy the relevant slices into a fresh contiguous buffer and shift indices\n * to match the new layout.\n */\nfunction createMergedMesh(\n\tgroup: MaterialGroup,\n\tallVertices: Float32Array,\n\tallIndices: Uint16Array | Uint32Array,\n\tmaterials: THREE.Material[],\n\tallUvs: Float32Array | null = null,\n\tallColors: Uint8Array | null = null\n): THREE.Mesh {\n\tlet totalVertexCount = 0;\n\tlet totalIndexCount = 0;\n\tfor (const meshMeta of group.meshes) {\n\t\ttotalVertexCount += meshMeta.vertexCount;\n\t\ttotalIndexCount += meshMeta.indexCount;\n\t}\n\n\tconst mergedVertices = new Float32Array(totalVertexCount * 3);\n\tconst mergedIndices = new Uint32Array(totalIndexCount);\n\tconst mergedUvs = allUvs ? new Float32Array(totalVertexCount * 2) : null;\n\tconst mergedColors = allColors ? new Uint8Array(totalVertexCount * 3) : null;\n\n\tlet vertexWriteCursor = 0;\n\tlet indexWriteCursor = 0;\n\n\tfor (const meshMeta of group.meshes) {\n\t\tconst componentStart = meshMeta.vertexStart * 3;\n\t\tconst componentLen = meshMeta.vertexCount * 3;\n\t\tmergedVertices.set(\n\t\t\tallVertices.subarray(componentStart, componentStart + componentLen),\n\t\t\tvertexWriteCursor * 3\n\t\t);\n\n\t\tif (mergedUvs && allUvs) {\n\t\t\tconst uvStart = meshMeta.vertexStart * 2;\n\t\t\tmergedUvs.set(\n\t\t\t\tallUvs.subarray(uvStart, uvStart + meshMeta.vertexCount * 2),\n\t\t\t\tvertexWriteCursor * 2\n\t\t\t);\n\t\t}\n\n\t\tif (mergedColors && allColors) {\n\t\t\tmergedColors.set(\n\t\t\t\tallColors.subarray(componentStart, componentStart + componentLen),\n\t\t\t\tvertexWriteCursor * 3\n\t\t\t);\n\t\t}\n\n\t\tconst indicesSlice = allIndices.subarray(\n\t\t\tmeshMeta.indexStart,\n\t\t\tmeshMeta.indexStart + meshMeta.indexCount\n\t\t);\n\t\tconst indexShift = vertexWriteCursor - meshMeta.vertexStart;\n\t\tfor (let i = 0; i < indicesSlice.length; i++) {\n\t\t\tconst indexValue = indicesSlice[i]!;\n\t\t\tassertIndexInWindow(indexValue, meshMeta);\n\t\t\tmergedIndices[indexWriteCursor + i] = indexValue + indexShift;\n\t\t}\n\n\t\tvertexWriteCursor += meshMeta.vertexCount;\n\t\tindexWriteCursor += meshMeta.indexCount;\n\t}\n\n\tconst geometry = new THREE.BufferGeometry();\n\tgeometry.setAttribute('position', new THREE.BufferAttribute(mergedVertices, 3));\n\tgeometry.setIndex(new THREE.BufferAttribute(mergedIndices, 1));\n\tif (mergedUvs) {\n\t\tgeometry.setAttribute('uv', new THREE.BufferAttribute(mergedUvs, 2));\n\t}\n\tif (mergedColors) {\n\t\tgeometry.setAttribute('color', new THREE.BufferAttribute(mergedColors, 3, true));\n\t}\n\tgeometry.computeVertexNormals();\n\n\tconst threeMesh = new THREE.Mesh(geometry, materials[group.materialId]);\n\tconst firstMesh = group.meshes[0];\n\tconst meshNames = group.meshes.map((m) => m.name).filter((name) => name && name.length > 0);\n\tthreeMesh.name = meshNames.length > 0 ? meshNames[0]! : `merged_material_${group.materialId}`;\n\tthreeMesh.castShadow = true;\n\tthreeMesh.receiveShadow = true;\n\n\tthreeMesh.userData = {\n\t\tsource: 'compute',\n\t\tname: threeMesh.name,\n\t\tlayer: firstMesh?.layer ?? '',\n\t\toriginalIndex: firstMesh?.originalIndex ?? 0,\n\t\tmetadata: firstMesh?.metadata ?? {},\n\t\tmergedFrom: group.meshes.slice(1).map((m) => ({\n\t\t\tname: m.name,\n\t\t\tlayer: m.layer,\n\t\t\toriginalIndex: m.originalIndex\n\t\t}))\n\t};\n\n\treturn threeMesh;\n}\n\n/**\n * Creates individual meshes from a material group. Each mesh's indices are rebased so they\n * address its own local vertex slice starting from 0.\n */\nfunction createIndividualMeshes(\n\tgroup: MaterialGroup,\n\tallVertices: Float32Array,\n\tallIndices: Uint16Array | Uint32Array,\n\tmaterials: THREE.Material[],\n\tallUvs: Float32Array | null = null,\n\tallColors: Uint8Array | null = null\n): THREE.Mesh[] {\n\tconst meshes: THREE.Mesh[] = [];\n\n\tfor (const meshMeta of group.meshes) {\n\t\tconst componentStart = meshMeta.vertexStart * 3;\n\t\tconst componentLen = meshMeta.vertexCount * 3;\n\n\t\t// `subarray` returns a view; copy via `slice` so the BufferAttribute owns its memory and\n\t\t// downstream code (dispose/reuse) can't surprise us by sharing the parser's buffer.\n\t\tconst vertices = allVertices.slice(componentStart, componentStart + componentLen);\n\n\t\tconst indicesSlice = allIndices.subarray(\n\t\t\tmeshMeta.indexStart,\n\t\t\tmeshMeta.indexStart + meshMeta.indexCount\n\t\t);\n\t\tconst rebasedIndices = new Uint32Array(indicesSlice.length);\n\t\tconst baseIndex = meshMeta.vertexStart;\n\t\tfor (let i = 0; i < indicesSlice.length; i++) {\n\t\t\tconst indexValue = indicesSlice[i]!;\n\t\t\tassertIndexInWindow(indexValue, meshMeta);\n\t\t\trebasedIndices[i] = indexValue - baseIndex;\n\t\t}\n\n\t\tconst geometry = new THREE.BufferGeometry();\n\t\tgeometry.setAttribute('position', new THREE.BufferAttribute(vertices, 3));\n\t\tgeometry.setIndex(new THREE.BufferAttribute(rebasedIndices, 1));\n\t\tif (allUvs) {\n\t\t\tconst uvStart = meshMeta.vertexStart * 2;\n\t\t\tconst uvs = allUvs.slice(uvStart, uvStart + meshMeta.vertexCount * 2);\n\t\t\tgeometry.setAttribute('uv', new THREE.BufferAttribute(uvs, 2));\n\t\t}\n\t\tif (allColors) {\n\t\t\tconst colors = allColors.slice(componentStart, componentStart + componentLen);\n\t\t\tgeometry.setAttribute('color', new THREE.BufferAttribute(colors, 3, true));\n\t\t}\n\t\tgeometry.computeVertexNormals();\n\n\t\tconst mesh = new THREE.Mesh(geometry, materials[group.materialId]);\n\t\tmesh.name = meshMeta.name;\n\t\tmesh.userData = {\n\t\t\tsource: 'compute',\n\t\t\tname: meshMeta.name,\n\t\t\tlayer: meshMeta.layer ?? '',\n\t\t\toriginalIndex: meshMeta.originalIndex,\n\t\t\tmetadata: meshMeta.metadata ?? {}\n\t\t};\n\t\tmesh.castShadow = true;\n\t\tmesh.receiveShadow = true;\n\n\t\tmeshes.push(mesh);\n\t}\n\n\treturn meshes;\n}\n\n// ============================================================================\n// DEBUG HELPERS\n// ============================================================================\n\nfunction approximateBase64DecodedBytes(base64: string): number {\n\treturn Math.floor((base64.length * 3) / 4);\n}\n","import * as THREE from 'three';\n\nimport { applyOffset, computeCombinedBoundingBox } from '../threejs/three-helpers.js';\nimport { getLogger } from '@/core';\n\nimport { parseDisplayItems } from '../display-items/display-items-parser.js';\n\nimport { parseMeshBatchObject } from './batch-parser.js';\n\nimport type { DataItem, GrasshopperComputeResponse } from '@/features/grasshopper/types';\nimport type { DisplayBatch, MeshExtractionOptions, MeshBatchParsingOptions } from './types.js';\nimport type { RhinoModule } from 'rhino3dm';\n\n// Constants\n\n/**\n * Metres per model unit, keyed by Rhino `UnitSystem` name (the `modelunits` string on the compute\n * response). Imperial factors are the exact international definitions (1 in = 0.0254 m,\n * 1 ft = 0.3048 m, 1 mi = 1609.344 m). Units not in this table scale 1 and log a one-time warning\n * — see {@link getScaleFactor}.\n */\nexport const SCALE_FACTORS: Record<string, number> = {\n\t// Metric\n\tAngstroms: 1e-10,\n\tNanometers: 1e-9,\n\tMicrons: 1e-6,\n\tMillimeters: 1e-3,\n\tCentimeters: 1e-2,\n\tDecimeters: 0.1,\n\tMeters: 1,\n\tDekameters: 10,\n\tHectometers: 100,\n\tKilometers: 1000,\n\tMegameters: 1e6,\n\tGigameters: 1e9,\n\t// Imperial (exact: 1 inch = 0.0254 m)\n\tMicroinches: 0.0254e-6,\n\tMils: 0.0254e-3,\n\tInches: 0.0254,\n\tFeet: 0.3048,\n\tYards: 0.9144,\n\tMiles: 1609.344,\n\tNauticalMiles: 1852\n};\n\n/**\n * Wire `type` token identifying a Selva Display payload. The real wire value is namespaced (e.g.\n * `Selva.GH.Features.Display.Services.DisplayBatch`), so dispatch matches exact dot-separated\n * tokens — never substrings, which would misroute any unrelated type merely containing \"Display\".\n */\nconst DISPLAY_COMPONENT_TYPE = 'Display';\nconst DISPLAY_BATCH_TYPE = 'DisplayBatch';\n\n/**\n * True when a wire `type` denotes a Display payload: one of its dot-separated tokens is exactly\n * `Display` or `DisplayBatch`. Matches the bare `Display` used by older servers and the namespaced\n * `Selva.GH.Features.Display.Services.DisplayBatch`, but not e.g. `System.DisplayText`.\n */\nfunction isDisplayItemType(type: string): boolean {\n\tconst tokens = type.split('.');\n\treturn tokens.includes(DISPLAY_COMPONENT_TYPE) || tokens.includes(DISPLAY_BATCH_TYPE);\n}\n\n/** Unknown-unit names already warned about, so a per-solve parse doesn't spam the log. */\nconst warnedUnknownUnits = new Set<string>();\n\n/**\n * Extracts and processes display meshes from a ComputePointerResponse using the Grasshopper WebDisplay component.\n *\n * This is the primary entry point for extracting mesh geometry from Grasshopper compute responses.\n * It handles all aspects of mesh processing: decompression, coordinate transformation, scaling, and positioning.\n *\n * **Note:** The entire pipeline (base64 decode, inflate, dequantization, mesh construction) runs\n * synchronously on the calling thread — large batches will block the UI for their duration. The\n * function is `async` only so its shape can stay stable if parsing moves off-thread later.\n *\n * @param data - The ComputePointerResponse containing Grasshopper output trees.\n * @param options - Configuration for mesh extraction and parsing behavior. All options are optional with sensible defaults.\n * @returns Promise resolving to array of THREE.Mesh objects (may be empty).\n * @throws Rethrows unexpected errors after attempting to dispose any created meshes.\n *\n * @remarks\n * - Only works with the WebDisplay component of GHHeadless.\n * - Requires changes to Rhino.Compute (see https://github.com/TheVessen/compute.rhino3d).\n * - Provides a performant way to display mesh data in Three.js.\n * - All decoding is synchronous on the main thread; there is no Web Worker offload today.\n * - Supports mesh metadata (names, user data) if provided in the compute response.\n *\n * @internal Internal helper: high-level extraction remains public via visualization module, but this\n * function is considered internal implementation detail for mesh extraction.\n *\n * @example\n * ```ts\n * // Simple usage with defaults (all processing enabled)\n * const meshes = await getThreeMeshesFromComputeResponse(response);\n *\n * // With debugging enabled\n * const meshes = await getThreeMeshesFromComputeResponse(response, { debug: true });\n *\n * // With advanced options\n * const meshes = await getThreeMeshesFromComputeResponse(response, {\n * debug: true,\n * allowScaling: true,\n * allowAutoPosition: false,\n * parsing: {\n * mergeByMaterial: false,\n * applyTransforms: true,\n * debug: true,\n * },\n * });\n * ```\n */\nexport async function getThreeMeshesFromComputeResponse(\n\tdata: GrasshopperComputeResponse,\n\toptions?: MeshExtractionOptions\n): Promise<THREE.Object3D[]> {\n\tconst startTime = performance.now();\n\tconst objects: THREE.Object3D[] = [];\n\n\tconst {\n\t\tallowScaling = true,\n\t\tallowAutoPosition = true,\n\t\trhino,\n\t\tdebug = false,\n\t\tparsing: parsingOptions = {}\n\t} = options ?? {};\n\n\ttry {\n\t\tconst scaleFactor = allowScaling ? getScaleFactor(data.modelunits) : 1;\n\t\tawait extractDisplayFromData(data, objects, scaleFactor, parsingOptions, rhino, debug);\n\n\t\tif (allowAutoPosition) {\n\t\t\tapplyGroundOffset(objects);\n\t\t}\n\n\t\treturn objects;\n\t} catch (error) {\n\t\thandleError(error, objects);\n\t\tthrow error;\n\t} finally {\n\t\tif (debug) {\n\t\t\tlogProcessingTime(startTime);\n\t\t}\n\t}\n}\n\n/**\n * Gets the metres-per-unit scale factor for the given Rhino unit name. Unknown units fall back to\n * 1 (no scaling) with a one-time warning per unit name — a kilometers model rendering 1000× off\n * should at least say why.\n */\nfunction getScaleFactor(modelUnits: string): number {\n\tconst factor = SCALE_FACTORS[modelUnits];\n\tif (factor !== undefined) {\n\t\treturn factor;\n\t}\n\tif (!warnedUnknownUnits.has(modelUnits)) {\n\t\twarnedUnknownUnits.add(modelUnits);\n\t\tgetLogger().warn(\n\t\t\t`Unknown Rhino model unit \"${modelUnits}\" — geometry will not be scaled (factor 1). ` +\n\t\t\t\t`Known units: ${Object.keys(SCALE_FACTORS).join(', ')}.`\n\t\t);\n\t}\n\treturn 1;\n}\n\n/**\n * Extracts meshes and non-mesh display items (curves, points) from compute response data.\n */\nasync function extractDisplayFromData(\n\tdata: GrasshopperComputeResponse,\n\tobjects: THREE.Object3D[],\n\tscaleFactor: number,\n\tparsingOptions: MeshBatchParsingOptions,\n\trhino: RhinoModule | undefined,\n\tdebug: boolean\n): Promise<void> {\n\tfor (const value of data.values) {\n\t\tconst innerTree = value.InnerTree as { [key: string]: DataItem[] };\n\n\t\tfor (const path in innerTree) {\n\t\t\tconst branch = innerTree[path];\n\t\t\tif (!branch) continue;\n\n\t\t\tawait processDataBranch(branch, objects, scaleFactor, parsingOptions, rhino, debug);\n\t\t}\n\t}\n}\n\n/**\n * Processes a single data branch to extract a DisplayBatch's meshes (binary blob) and items\n * (curves/points JSON). Both get the same unit scale so they share one frame.\n */\nasync function processDataBranch(\n\tbranch: DataItem[],\n\tobjects: THREE.Object3D[],\n\tscaleFactor: number,\n\tparsingOptions: MeshBatchParsingOptions,\n\trhino: RhinoModule | undefined,\n\tdebug: boolean\n): Promise<void> {\n\tfor (const item of branch) {\n\t\tif (!isDisplayItemType(item.type)) continue;\n\n\t\tconst mergedParsingOptions = {\n\t\t\tmergeByMaterial: true,\n\t\t\tapplyTransforms: true,\n\t\t\tdebug: false,\n\t\t\t...parsingOptions\n\t\t};\n\n\t\t// Parse the JSON envelope once — it contains the full multi-MB base64 SLVA blob as a string,\n\t\t// so letting the mesh parser and the display-item extractor each parse it doubles both the\n\t\t// synchronous main-thread CPU and the transient string memory.\n\t\tconst batch = extractBatch(item.data);\n\t\tif (!batch) {\n\t\t\tgetLogger().error('Error parsing display batch envelope: invalid JSON');\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst batchMeshes = await parseMeshBatchObject(batch, mergedParsingOptions);\n\n\t\tconst batchItems = parseDisplayItems(batch.items, {\n\t\t\trhino,\n\t\t\tapplyTransforms: mergedParsingOptions.applyTransforms\n\t\t});\n\n\t\tconst batchObjects: THREE.Object3D[] = [...batchMeshes, ...batchItems];\n\n\t\tif (scaleFactor !== 1) {\n\t\t\tfor (const obj of batchObjects) {\n\t\t\t\tobj.scale.set(scaleFactor, scaleFactor, scaleFactor);\n\t\t\t}\n\t\t}\n\n\t\tobjects.push(...batchObjects);\n\n\t\tif (debug) {\n\t\t\tgetLogger().debug(\n\t\t\t\t`Extracted ${batchMeshes.length} meshes and ${batchItems.length} items from batch`\n\t\t\t);\n\t\t}\n\t}\n}\n\n/**\n * Resolves a raw DisplayBatch payload to a parsed object, tolerating either a parsed object or a\n * JSON string (the blob-bearing `item.data` is the same envelope the mesh parser reads).\n */\nfunction extractBatch(data: unknown): DisplayBatch | undefined {\n\treturn typeof data === 'string' ? safeParse(data) : (data as DisplayBatch | undefined);\n}\n\nfunction safeParse(s: string): DisplayBatch | undefined {\n\ttry {\n\t\treturn JSON.parse(s) as DisplayBatch;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Applies vertical offset to position objects on the Z=0 plane (the ground of the unified\n * Z-up scene frame — see ../coordinate-transform.ts).\n */\nfunction applyGroundOffset(meshes: THREE.Object3D[]): void {\n\tif (meshes.length === 0) return;\n\n\tconst combinedBoundingBox = computeCombinedBoundingBox(meshes);\n\tapplyOffset(meshes, combinedBoundingBox.min.z, 'z');\n}\n\n/**\n * Handles errors by disposing created objects and logging.\n */\nfunction handleError(error: unknown, meshes: THREE.Object3D[]): void {\n\tgetLogger().error('An unexpected error occurred:', error);\n\tdisposeMeshes(meshes);\n}\n\n/**\n * Disposes of all objects (meshes, lines, points) and their associated resources.\n */\nfunction disposeMeshes(meshes: THREE.Object3D[]): void {\n\tfor (const obj of meshes) {\n\t\tconst mesh = obj as Partial<THREE.Mesh> & THREE.Object3D;\n\t\tif (mesh.geometry) {\n\t\t\tmesh.geometry.dispose();\n\t\t}\n\n\t\tif (mesh.material) {\n\t\t\tif (Array.isArray(mesh.material)) {\n\t\t\t\tmesh.material.forEach((material) => material.dispose());\n\t\t\t} else {\n\t\t\t\tmesh.material.dispose();\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Logs the processing time for mesh extraction.\n */\nfunction logProcessingTime(startTime: number): void {\n\tconst elapsed = performance.now() - startTime;\n\tgetLogger().info('Time to process meshes:', `${elapsed.toFixed(2)}ms`);\n}\n"]}
|