@selvajs/compute 3.1.0-beta.6 → 3.1.0-beta.7

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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/features/visualization/threejs/three-materials.ts","../src/features/visualization/threejs/three-helpers.ts","../src/features/visualization/threejs/camera-controller.ts","../src/features/visualization/threejs/grid.ts","../src/features/visualization/threejs/view-gizmo.ts","../src/features/visualization/threejs/edges.ts","../src/features/visualization/threejs/render-pipeline.ts","../src/features/visualization/threejs/label-layer.ts","../src/features/visualization/threejs/measure.ts","../src/features/visualization/webdisplay/texture-cache.ts","../src/features/visualization/threejs/three-initializer.ts","../src/features/visualization/display-items/display-items-parser.ts","../src/features/visualization/coordinate-transform.ts","../src/features/visualization/webdisplay/binary-parser.ts","../src/features/visualization/webdisplay/batch-parser.ts","../src/features/visualization/webdisplay/webdisplay-parser.ts"],"sourcesContent":["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/** Shared singleton materials; must not be disposed (rebuilds shaders, frees textures). */\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\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/** Updates scene with meshes and positions camera on first call. */\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/** Parses color strings (hex, RGB, CSS names). */\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 of objects that are viewer *aids*, not content — the grid, floor, CSS2D label layer and\n * measure markers. Excluded from every content-bounds query: the grid especially is a huge plane that\n * re-centers on the camera each frame, so including it would make fit-to-view frame the camera's\n * position instead of the geometry.\n */\nconst VIEWER_AID_IDS = new Set(['grid', 'floor', 'label-layer', 'measure']);\n\n/** True if the object or any ancestor is a viewer aid (grid/floor/labels/measure markers). */\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 world bounds of the scene's renderable *content* — every visible mesh/line/points, with\n * viewer aids (grid/floor/labels/measure) excluded. The single content-bounds function: shared by\n * fit-to-view, pick-threshold scaling, camera framing (`setView`), and shadow-frustum fitting so they\n * all measure exactly the same box. Returns an empty Box3 when there is no content.\n *\n * Refreshes world matrices once up front (one traversal) so `expandByObject` reads current transforms\n * regardless of when the caller invokes this — cheaper and more correct than updating per object.\n */\nexport function computeContentBounds(scene: THREE.Scene): THREE.Box3 {\n\tscene.updateMatrixWorld(true);\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/** IDs of scene infrastructure that survives content updates (floor, grid, label layer). */\nconst PERSISTENT_SCENE_IDS = new Set(['floor', 'grid', 'label-layer']);\n\n/** Removes all compute content except persistent infrastructure and shared materials. */\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';\nimport { OrbitControls } from 'three/addons/controls/OrbitControls.js';\n\nimport { computeContentBounds } from './three-helpers';\n\n/**\n * Runtime camera control for the viewer: preset views (top/front/…), a true 2D/3D toggle\n * (orthographic ⇄ perspective), and a rotate lock.\n *\n * Why a controller and not just loose methods: all three features have to agree on *which* camera\n * is active. Switching projection swaps the camera object OrbitControls drives, the animation loop\n * renders, the resize handler reshapes, and the raycaster picks with. Centralizing that here keeps\n * those four call sites reading one source of truth ({@link getActiveCamera}) instead of each\n * branching on a `mode` flag.\n *\n * The perspective camera stays the primary (it's what {@link updateScene} and existing consumers\n * size). The orthographic camera shadows it: same position/target, frustum derived from the\n * perspective FOV + current distance so the 3D→2D switch doesn't visually jump.\n */\n\n/** The six axis-aligned presets plus the default 3/4 iso. Named in Three's Y-up frame. */\nexport type ViewPreset = 'top' | 'bottom' | 'front' | 'back' | 'left' | 'right' | 'iso';\n\nexport type CameraProjection = 'perspective' | 'orthographic';\n\nexport interface CameraController {\n\t/** The camera currently being rendered/picked with. Swaps identity on {@link setProjection}. */\n\tgetActiveCamera(): THREE.Camera;\n\t/** Current projection mode. */\n\tgetProjection(): CameraProjection;\n\t/** Switch between perspective (3D) and orthographic (2D). No-op if already in that mode. */\n\tsetProjection(projection: CameraProjection): void;\n\t/** Convenience toggle for a 2D/3D button. */\n\ttoggleProjection(): CameraProjection;\n\t/** Move the camera to a preset orientation, framing current scene content. Animated. */\n\tsetView(preset: ViewPreset, animate?: boolean): void;\n\t/**\n\t * Frame current content viewed from `direction` (a world-space vector from target toward camera).\n\t * Like {@link setView} but takes an explicit direction — used by the nav-cube, whose clicked axis\n\t * is a world axis, not a named preset. Pole directions are nudged off-axis to avoid the orbit\n\t * singularity.\n\t */\n\tsetViewDirection(direction: THREE.Vector3, animate?: boolean): void;\n\t/**\n\t * Frame an arbitrary world-space box (e.g. a double-clicked object) from the current view\n\t * direction, moving the *active* camera — in 2D mode that means resizing the ortho frustum, not\n\t * just translating. No-op on an empty box.\n\t */\n\tframeBounds(box: THREE.Box3, animate?: boolean): void;\n\t/** Enable/disable orbit rotation at runtime (pan/zoom unaffected). */\n\tsetRotateEnabled(enabled: boolean): void;\n\t/** Whether rotation is currently enabled. */\n\tisRotateEnabled(): boolean;\n\t/** Keep the orthographic frustum aspect in sync on canvas resize. Called by the resize loop. */\n\tupdateAspect(width: number, height: number): void;\n\t/** Cancel any in-flight camera tween. Call on viewer teardown so ticks can't touch disposed controls. */\n\tdispose(): void;\n}\n\ninterface CameraControllerDeps {\n\tscene: THREE.Scene;\n\tperspective: THREE.PerspectiveCamera;\n\tcontrols: OrbitControls;\n\t/** Called whenever the active camera identity changes, so callers can re-point the renderer/raycaster. */\n\tonActiveCameraChange: (camera: THREE.Camera) => void;\n\t/**\n\t * The scene's up axis. Presets, the orthographic camera's up, and the iso direction are all derived\n\t * from this so the controller is correct in any up convention (Three's native Y-up, Rhino's Z-up, …)\n\t * without hardcoding an axis. Defaults to Y-up.\n\t */\n\tup?: THREE.Vector3;\n}\n\n/**\n * Build the seven preset view directions (from target toward camera, unit vectors) for a given up\n * axis. \"Top\" looks straight down the up axis; front/back/left/right are the two axes orthogonal to\n * up, with \"front\" chosen as the more conventional facing for that up convention; iso is a 3/4 blend.\n *\n * Deriving these from `up` (instead of a fixed Y-up table) is what keeps Top/Front/… meaningful for\n * Z-up Rhino scenes — otherwise \"Top\" would frame the side of the model.\n */\nfunction buildViewDirections(up: THREE.Vector3): Record<ViewPreset, THREE.Vector3> {\n\tconst u = up.clone().normalize();\n\n\t// Two axes spanning the ground plane (orthogonal to up). `forward` is the camera-facing \"front\"\n\t// direction, `right` completes a right-handed basis with up.\n\tconst worldZ = new THREE.Vector3(0, 0, 1);\n\tconst worldY = new THREE.Vector3(0, 1, 0);\n\t// Pick a seed not parallel to up to derive an in-plane axis from.\n\tconst seed = Math.abs(u.dot(worldZ)) > 0.9 ? worldY : worldZ;\n\tconst right = new THREE.Vector3().crossVectors(u, seed).normalize();\n\tconst forward = new THREE.Vector3().crossVectors(right, u).normalize();\n\n\treturn {\n\t\ttop: u.clone(),\n\t\tbottom: u.clone().negate(),\n\t\tfront: forward.clone(),\n\t\tback: forward.clone().negate(),\n\t\tright: right.clone(),\n\t\tleft: right.clone().negate(),\n\t\t// 3/4 iso: blend front, right, and up so it reads as a corner view regardless of up axis.\n\t\tiso: forward.clone().multiplyScalar(1.2).add(right.clone()).add(u.clone()).normalize()\n\t};\n}\n\nexport function createCameraController(deps: CameraControllerDeps): CameraController {\n\tconst { scene, perspective, controls, onActiveCameraChange } = deps;\n\n\t// Up axis drives presets, the ortho camera's up, and the iso direction. Prefer an explicit `up`,\n\t// fall back to the perspective camera's current up (which initThree sets to sceneUp).\n\tconst up = (deps.up ?? perspective.up).clone().normalize();\n\tconst VIEW_DIRECTIONS = buildViewDirections(up);\n\n\tconst ortho = new THREE.OrthographicCamera(-1, 1, 1, -1, perspective.near, perspective.far);\n\tortho.up.copy(up);\n\n\tlet projection: CameraProjection = 'perspective';\n\tlet aspect = perspective.aspect;\n\n\tconst active = (): THREE.Camera => (projection === 'perspective' ? perspective : ortho);\n\n\t// The one in-flight camera tween, if any. Starting a new tween cancels the previous one (two\n\t// concurrent loops would fight, each lerping from its own snapshot), and dispose() cancels it so\n\t// no tick can touch disposed controls after teardown.\n\tlet activeTween: TweenHandle | null = null;\n\tconst cancelTween = () => {\n\t\tactiveTween?.cancel();\n\t\tactiveTween = null;\n\t};\n\n\t// Sizes the ortho frustum so its on-screen content matches the perspective view at the current\n\t// distance — the apparent height of the perspective view at the target plane is\n\t// 2 * distance * tan(fov/2). Half-height drives top/bottom; aspect drives left/right.\n\tconst syncOrthoFrustum = () => {\n\t\t// While ortho is active, the ORTHO camera is the one presets/fit move (OrbitControls only\n\t\t// changes its zoom); the perspective camera's distance is stale until the next 3D switch.\n\t\t// Measure whichever camera is live so presets and resizes in 2D size the frustum correctly.\n\t\tconst reference = projection === 'orthographic' ? ortho : perspective;\n\t\tconst distance = reference.position.distanceTo(controls.target);\n\t\tconst halfH = distance * Math.tan((perspective.fov * Math.PI) / 360);\n\t\tconst halfW = halfH * aspect;\n\t\tortho.left = -halfW;\n\t\tortho.right = halfW;\n\t\tortho.top = halfH;\n\t\tortho.bottom = -halfH;\n\t\tortho.near = perspective.near;\n\t\tortho.far = perspective.far;\n\t\tortho.updateProjectionMatrix();\n\t};\n\n\tconst setProjection = (next: CameraProjection) => {\n\t\tif (next === projection) return;\n\t\t// A tween mid-flight would keep lerping the OLD active camera after the swap.\n\t\tcancelTween();\n\n\t\t// Carry position/target across so the switch doesn't jump.\n\t\tif (next === 'orthographic') {\n\t\t\tortho.position.copy(perspective.position);\n\t\t\tortho.up.copy(perspective.up);\n\t\t\tortho.lookAt(controls.target);\n\t\t\t// OrbitControls dollies an ortho camera via `zoom`, not position — start each 2D session\n\t\t\t// at 1 so the freshly-derived frustum isn't still multiplied by zoom left over from a\n\t\t\t// previous 2D session (which showed as a zoom jump on every 2D→3D→2D round-trip).\n\t\t\tortho.zoom = 1;\n\t\t\tsyncOrthoFrustum();\n\t\t} else {\n\t\t\t// Carry the ortho dolly back as perspective DISTANCE so the switch preserves apparent\n\t\t\t// size: the ortho view shows a half-height of top/zoom at the target plane, and the\n\t\t\t// perspective camera shows the same at distance = halfH / tan(fov/2). Copying position\n\t\t\t// alone would discard any zooming done in 2D.\n\t\t\tconst halfH = (ortho.top - ortho.bottom) / (2 * ortho.zoom);\n\t\t\tconst distance = halfH / Math.tan((perspective.fov * Math.PI) / 360);\n\t\t\tconst direction = ortho.position.clone().sub(controls.target);\n\t\t\tif (direction.lengthSq() < 1e-12) direction.copy(up);\n\t\t\tdirection.normalize();\n\t\t\tperspective.position.copy(controls.target).add(direction.multiplyScalar(distance));\n\t\t}\n\n\t\tprojection = next;\n\t\tcontrols.object = active();\n\t\tcontrols.update();\n\t\tonActiveCameraChange(active());\n\t};\n\n\t// Shared framing move: position the ACTIVE camera along `direction` at the distance that fits\n\t// `maxDim`, retargeting controls at `center`. In ortho mode the dolly zoom is reset and the\n\t// frustum re-derived (per tick while animating) — moving position alone wouldn't change the\n\t// apparent size of an orthographic view.\n\tconst frame = (\n\t\tcenter: THREE.Vector3,\n\t\tmaxDim: number,\n\t\tdirection: THREE.Vector3,\n\t\tanimate: boolean\n\t) => {\n\t\t// Distance to fit the content for the perspective camera; ortho reuses it via syncOrthoFrustum.\n\t\tconst fov = perspective.fov * (Math.PI / 180);\n\t\tconst distance = (maxDim / (2 * Math.tan(fov / 2))) * 1.5;\n\n\t\t// A direction along the up axis (top/bottom) puts the view direction parallel to camera.up — an\n\t\t// OrbitControls singularity (the next mouse drag flips the view 180° and the gizmo jitters).\n\t\t// Tilt it a hair off-axis so the orbit basis stays well-defined.\n\t\tconst dir = nudgeOffPole(direction, up);\n\t\tconst toPosition = center.clone().add(dir.clone().multiplyScalar(distance));\n\n\t\tconst cam = active();\n\t\t// Framing means fitting: a leftover ortho dolly (OrbitControls zooms ortho via `zoom`) would\n\t\t// keep multiplying the freshly-derived frustum and defeat the fit.\n\t\tif (projection === 'orthographic') ortho.zoom = 1;\n\n\t\tcancelTween();\n\t\tif (animate) {\n\t\t\tactiveTween = animateMove(cam, controls, toPosition, center, () => {\n\t\t\t\tif (projection === 'orthographic') syncOrthoFrustum();\n\t\t\t});\n\t\t} else {\n\t\t\tcam.position.copy(toPosition);\n\t\t\tcontrols.target.copy(center);\n\t\t\tif (projection === 'orthographic') syncOrthoFrustum();\n\t\t\tcontrols.update();\n\t\t}\n\t};\n\n\tconst setViewDirection = (direction: THREE.Vector3, animate = true) => {\n\t\tconst box = computeContentBounds(scene);\n\t\tconst center = box.isEmpty() ? controls.target.clone() : box.getCenter(new THREE.Vector3());\n\t\tconst size = box.isEmpty() ? new THREE.Vector3(1, 1, 1) : box.getSize(new THREE.Vector3());\n\t\tconst maxDim = Math.max(size.x, size.y, size.z) || 1;\n\t\tframe(center, maxDim, direction, animate);\n\t};\n\n\tconst frameBounds = (box: THREE.Box3, animate = true) => {\n\t\tif (box.isEmpty()) return;\n\t\tconst center = box.getCenter(new THREE.Vector3());\n\t\tconst size = box.getSize(new THREE.Vector3());\n\t\tconst maxDim = Math.max(size.x, size.y, size.z) || 1;\n\t\t// Keep the user's current viewing direction; only the distance/target change.\n\t\tconst direction = active().position.clone().sub(controls.target);\n\t\tif (direction.lengthSq() < 1e-12) direction.copy(VIEW_DIRECTIONS.iso);\n\t\tframe(center, maxDim, direction.normalize(), animate);\n\t};\n\n\tconst setView = (preset: ViewPreset, animate = true) => {\n\t\tsetViewDirection(VIEW_DIRECTIONS[preset], animate);\n\t};\n\n\tconst setRotateEnabled = (enabled: boolean) => {\n\t\tcontrols.enableRotate = enabled;\n\t};\n\n\tconst updateAspect = (width: number, height: number) => {\n\t\taspect = height === 0 ? aspect : width / height;\n\t\tif (projection === 'orthographic') syncOrthoFrustum();\n\t};\n\n\treturn {\n\t\tgetActiveCamera: active,\n\t\tgetProjection: () => projection,\n\t\tsetProjection,\n\t\ttoggleProjection: () => {\n\t\t\tsetProjection(projection === 'perspective' ? 'orthographic' : 'perspective');\n\t\t\treturn projection;\n\t\t},\n\t\tsetView,\n\t\tsetViewDirection,\n\t\tframeBounds,\n\t\tsetRotateEnabled,\n\t\tisRotateEnabled: () => controls.enableRotate,\n\t\tupdateAspect,\n\t\tdispose: cancelTween\n\t};\n}\n\n/**\n * If a view direction is (nearly) parallel to the up axis — i.e. top/bottom — tilt it a fraction of\n * a degree toward an in-plane axis. Looking exactly down `up` is an OrbitControls singularity: the\n * camera direction coincides with `camera.up`, so azimuth is undefined and the first drag snaps the\n * view. A ~0.5° tilt is imperceptible but keeps the orbit basis well-defined. Non-pole presets pass\n * through unchanged.\n */\nfunction nudgeOffPole(dir: THREE.Vector3, up: THREE.Vector3): THREE.Vector3 {\n\tconst u = up.clone().normalize();\n\tconst d = dir.clone().normalize();\n\tif (Math.abs(d.dot(u)) < 0.9999) return dir;\n\n\t// Derive an in-plane axis (orthogonal to up) to lean toward, same construction as the presets.\n\tconst seed =\n\t\tMath.abs(u.dot(new THREE.Vector3(0, 0, 1))) > 0.9\n\t\t\t? new THREE.Vector3(0, 1, 0)\n\t\t\t: new THREE.Vector3(0, 0, 1);\n\tconst inPlane = new THREE.Vector3().crossVectors(u, seed).normalize();\n\tconst tilt = (0.5 * Math.PI) / 180; // ~0.5°\n\treturn d\n\t\t.multiplyScalar(Math.cos(tilt))\n\t\t.add(inPlane.multiplyScalar(Math.sin(tilt)))\n\t\t.normalize();\n}\n\nconst easeOut = (t: number) => 1 - Math.pow(1 - t, 3);\n\n/** Handle to a running camera tween, so callers can stop it (new move, projection swap, teardown). */\ninterface TweenHandle {\n\tcancel(): void;\n}\n\n/**\n * Tween camera position + controls target. Returns a cancel handle: the controller cancels the\n * previous tween before starting a new one (two loops would fight over the camera) and on\n * dispose() so no tick touches disposed controls after teardown.\n */\nfunction animateMove(\n\tcamera: THREE.Camera,\n\tcontrols: OrbitControls,\n\ttoPosition: THREE.Vector3,\n\ttoTarget: THREE.Vector3,\n\tonTick: () => void,\n\tdurationMs = 250\n): TweenHandle {\n\tconst fromPosition = camera.position.clone();\n\tconst fromTarget = controls.target.clone();\n\tconst startTime = performance.now();\n\tlet rafId: number | null = null;\n\n\tconst tick = () => {\n\t\trafId = null;\n\t\tconst t = easeOut(Math.min((performance.now() - startTime) / durationMs, 1));\n\t\tcamera.position.lerpVectors(fromPosition, toPosition, t);\n\t\tcontrols.target.lerpVectors(fromTarget, toTarget, t);\n\t\tonTick();\n\t\tcontrols.update();\n\t\tif (t < 1) rafId = requestAnimationFrame(tick);\n\t};\n\n\trafId = requestAnimationFrame(tick);\n\n\treturn {\n\t\tcancel: () => {\n\t\t\tif (rafId !== null) {\n\t\t\t\tcancelAnimationFrame(rafId);\n\t\t\t\trafId = null;\n\t\t\t}\n\t\t}\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 { ViewHelper } from 'three/addons/helpers/ViewHelper.js';\n\nimport type { CameraController } from './camera-controller';\n\n/**\n * The corner nav-cube/axis gizmo. Uses three's {@link ViewHelper} purely as the rendered widget, but\n * NOT its click→animate behavior: ViewHelper's built-in snap assumes a Y-up world and animates the\n * camera straight onto the up axis, which in our Z-up scene rolls the view and makes the gizmo jitter\n * at the pole. Instead we hit-test the axis sprites ourselves and drive the viewer's up-aware camera\n * controller, which snaps (no animation) with a pole nudge so the orbit basis never degenerates.\n *\n * Integration points with the viewer's dual-camera setup:\n * 1. The snap frames the current orbit target via the controller, so it rotates about what the user\n * is looking at (not the world origin).\n * 2. The nav cube is inherently a 3D-orientation tool, so if the viewer is in orthographic (2D) mode\n * when the gizmo is clicked, we first flip back to perspective.\n *\n * Caller responsibilities (mirror ViewHelper's own contract):\n * - call {@link ViewGizmo.render} *after* the main scene render each frame (overlay viewport),\n * - forward pointer clicks to {@link ViewGizmo.handleClick}.\n */\nexport interface ViewGizmo {\n\trender(renderer: THREE.WebGLRenderer): void;\n\t/**\n\t * @deprecated No-op, kept only for API stability. This wrapper never uses ViewHelper's\n\t * click→animate path (see module comment) — view changes snap instantly through the camera\n\t * controller — so there is never a gizmo animation to advance. Safe to stop calling.\n\t */\n\tupdate(delta: number): void;\n\t/** Hit-test a click. Returns true if it hit the gizmo (and a view change started). */\n\thandleClick(event: MouseEvent): boolean;\n\t/**\n\t * @deprecated Always `false`, kept only for API stability. Gizmo clicks snap the view\n\t * instantly rather than animating (deliberately — ViewHelper's built-in animation assumes a\n\t * Y-up world and rolls the view in this Z-up scene), so there is no animation window to gate\n\t * input on.\n\t */\n\treadonly isAnimating: boolean;\n\t/** Show/hide the gizmo at runtime. Hidden = not rendered and not click-hittable. */\n\tsetVisible(visible: boolean): void;\n\tisVisible(): boolean;\n\tdispose(): void;\n}\n\ninterface ViewGizmoDeps {\n\t/** The perspective (primary) camera the gizmo visualizes and re-orients. */\n\tcamera: THREE.PerspectiveCamera;\n\tdomElement: HTMLElement;\n\tcontroller: CameraController;\n}\n\nexport function createViewGizmo(deps: ViewGizmoDeps): ViewGizmo {\n\tconst { camera, domElement, controller } = deps;\n\n\tconst helper = new ViewHelper(camera, domElement);\n\thelper.setLabels('X', 'Y', 'Z');\n\n\tlet visible = true;\n\n\t// Our own hit-test against the helper's axis sprites, mirroring ViewHelper's internal viewport math\n\t// (a `dim`×`dim` square in the corner given by `location`). We do this instead of ViewHelper's own\n\t// `handleClick` so the camera move goes through the viewer's up-aware controller — ViewHelper's\n\t// built-in snap assumes a Y-up world and animates straight onto the pole, which rolls the view and\n\t// makes the gizmo jitter in our Z-up scene.\n\tconst DIM = 128;\n\tconst raycaster = new THREE.Raycaster();\n\tconst gizmoCamera = new THREE.OrthographicCamera(-2, 2, 2, -2, 0, 4);\n\tgizmoCamera.position.set(0, 0, 2);\n\t// This camera is never rendered, so nothing else computes its matrixWorld — and\n\t// Raycaster.setFromCamera doesn't either. Without this the ray originates at the identity\n\t// position (z = 0, the cube's mid-plane) and the camera-facing axis sprites sit behind it.\n\tgizmoCamera.updateMatrixWorld();\n\n\t// Map a clicked axis sprite to the world-space view direction (from target toward camera).\n\tconst AXIS_DIRECTIONS: Record<string, THREE.Vector3> = {\n\t\tposX: new THREE.Vector3(1, 0, 0),\n\t\tnegX: new THREE.Vector3(-1, 0, 0),\n\t\tposY: new THREE.Vector3(0, 1, 0),\n\t\tnegY: new THREE.Vector3(0, -1, 0),\n\t\tposZ: new THREE.Vector3(0, 0, 1),\n\t\tnegZ: new THREE.Vector3(0, 0, -1)\n\t};\n\n\t/** Which axis sprite (if any) a click landed on. Returns its `userData.type` or null. */\n\tconst pickAxis = (event: MouseEvent): string | null => {\n\t\tconst rect = domElement.getBoundingClientRect();\n\t\t// The gizmo viewport sits in the bottom-right corner (helper.location defaults: right/bottom 0).\n\t\tconst offsetX = rect.left + domElement.offsetWidth - DIM - helper.location.right;\n\t\tconst offsetY = rect.top + domElement.offsetHeight - DIM - helper.location.bottom;\n\n\t\tconst mouse = new THREE.Vector2(\n\t\t\t((event.clientX - offsetX) / DIM) * 2 - 1,\n\t\t\t-((event.clientY - offsetY) / DIM) * 2 + 1\n\t\t);\n\t\t// Outside the gizmo square — not our click.\n\t\tif (Math.abs(mouse.x) > 1 || Math.abs(mouse.y) > 1) return null;\n\n\t\t// Orient the helper as it's rendered (inverse of the camera), so the sprites are where the user\n\t\t// sees them, then raycast the interactive axis sprites.\n\t\thelper.quaternion.copy(camera.quaternion).invert();\n\t\thelper.updateMatrixWorld();\n\n\t\traycaster.setFromCamera(mouse, gizmoCamera);\n\t\tconst hits = raycaster.intersectObjects(helper.children, false);\n\t\tfor (const hit of hits) {\n\t\t\tconst type = hit.object.userData?.type;\n\t\t\tif (typeof type === 'string' && type in AXIS_DIRECTIONS) return type;\n\t\t}\n\t\treturn null;\n\t};\n\n\tconst handleClick = (event: MouseEvent): boolean => {\n\t\tif (!visible) return false;\n\n\t\tconst axis = pickAxis(event);\n\t\tif (!axis) return false;\n\n\t\t// The cube orients in 3D, so a click while in 2D returns us to perspective first.\n\t\tif (controller.getProjection() === 'orthographic') {\n\t\t\tcontroller.setProjection('perspective');\n\t\t}\n\n\t\t// Snap directly via the up-aware controller — no animation, no Y-up pole roll.\n\t\tcontroller.setViewDirection(AXIS_DIRECTIONS[axis]!, false);\n\t\treturn true;\n\t};\n\n\treturn {\n\t\trender: (renderer) => {\n\t\t\tif (!visible) return;\n\t\t\t// ViewHelper.render() calls renderer.render(this, orthoCamera), which with the default\n\t\t\t// autoClear=true clears the FULL framebuffer (to the scene's grey clear color) before drawing\n\t\t\t// the cube in its corner viewport — wiping the just-rendered scene. It only needs the depth\n\t\t\t// clear it does internally (clearDepth). So suppress the automatic color/depth clear here.\n\t\t\tconst prevAutoClear = renderer.autoClear;\n\t\t\trenderer.autoClear = false;\n\t\t\thelper.render(renderer);\n\t\t\trenderer.autoClear = prevAutoClear;\n\t\t},\n\t\t// Deliberately a no-op (see the interface docs): ViewHelper.update() only exists to advance\n\t\t// its click-snap animation, which this wrapper never starts (handleClick snaps via the\n\t\t// camera controller instead). Calling helper.update() outside an animation would rewrite\n\t\t// camera.position from (center=origin, radius=0) and blank the view.\n\t\tupdate: () => {},\n\t\thandleClick,\n\t\t// Honestly constant (see the interface docs): nothing here ever animates.\n\t\tisAnimating: false,\n\t\tsetVisible: (value) => {\n\t\t\tvisible = value;\n\t\t},\n\t\tisVisible: () => visible,\n\t\tdispose: () => helper.dispose()\n\t};\n}\n","import * as THREE from 'three';\nimport { 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 { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';\nimport { RenderPass } from 'three/addons/postprocessing/RenderPass.js';\nimport { GTAOPass } from 'three/addons/postprocessing/GTAOPass.js';\nimport { SMAAPass } from 'three/addons/postprocessing/SMAAPass.js';\nimport { OutputPass } from 'three/addons/postprocessing/OutputPass.js';\n\n/**\n * Optional postprocessing pipeline for ambient occlusion. Default-OFF: the viewer only constructs\n * this when `render.ambientOcclusion` is enabled, and otherwise renders with a plain\n * `renderer.render` so the cheap path stays cheap (the chosen tradeoff — see cad-viewer-plan.md).\n *\n * Pipeline: RenderPass → GTAOPass → SMAAPass → OutputPass. GTAO (ground-truth AO) is the modern\n * replacement for SSAO/SAO — better contact shadows in crevices, the \"engineered\" depth cue.\n * `screenSpaceRadius` is on so the AO radius is in screen space, which keeps it scale-robust across\n * the viewer's mm→m scenes without per-scene tuning.\n *\n * SMAA restores antialiasing on this path. The EffectComposer renders into an offscreen target, so\n * the WebGLRenderer's own MSAA (`antialias: true`) does nothing here — without a dedicated AA pass,\n * enabling AO would visibly *worsen* edge quality. SMAA is chosen over TAA because TAA's temporal\n * jitter smears during OrbitControls drags; SMAA is single-frame, cheap, and stable while orbiting.\n *\n * OutputPass applies tone mapping + color space last (taking over the roles the renderer did\n * directly in the non-composer path), so SMAA operates on the pre-tonemapped image as intended.\n *\n * Camera swaps: the active camera can flip perspective↔ortho. Rather than rebuild the composer, we\n * retarget the passes' `camera` each render via {@link setCamera}.\n */\n\nexport interface RenderPipeline {\n\trender(deltaTime: number): void;\n\tsetSize(width: number, height: number, pixelRatio: number): void;\n\t/** Point the passes at the currently active camera (call when projection changes). */\n\tsetCamera(camera: THREE.Camera): void;\n\tdispose(): void;\n}\n\nexport interface RenderPipelineOptions {\n\t/** Tone mapping to apply in OutputPass (mirror the renderer's). */\n\ttoneMapping: THREE.ToneMapping;\n\ttoneMappingExposure: number;\n\t/** AO strength 0–1. Default 1. */\n\taoIntensity?: number;\n\t/**\n\t * Cap on the device-pixel-ratio used for the composer's (AO) buffers. AO is low-frequency, so\n\t * rendering below the display DPR is nearly invisible but far cheaper. `setSize`'s incoming\n\t * pixelRatio is clamped to this. Default 1.\n\t */\n\taoPixelRatio?: number;\n}\n\nexport function createRenderPipeline(\n\trenderer: THREE.WebGLRenderer,\n\tscene: THREE.Scene,\n\tcamera: THREE.Camera,\n\twidth: number,\n\theight: number,\n\toptions: RenderPipelineOptions\n): RenderPipeline {\n\tconst composer = new EffectComposer(renderer);\n\n\tconst renderPass = new RenderPass(scene, camera);\n\tcomposer.addPass(renderPass);\n\n\tconst gtaoPass = new GTAOPass(scene, camera, width, height);\n\tgtaoPass.blendIntensity = options.aoIntensity ?? 1;\n\tgtaoPass.updateGtaoMaterial({ screenSpaceRadius: true });\n\tcomposer.addPass(gtaoPass);\n\n\t// Restore antialiasing lost when rendering through the composer's offscreen target (see header).\n\t// Sized by composer.setSize below, like every other pass.\n\tconst smaaPass = new SMAAPass();\n\tcomposer.addPass(smaaPass);\n\n\tconst outputPass = new OutputPass();\n\tcomposer.addPass(outputPass);\n\n\t// OutputPass owns tone mapping in the composer path; match the renderer's settings.\n\trenderer.toneMapping = options.toneMapping;\n\trenderer.toneMappingExposure = options.toneMappingExposure;\n\n\t// Clamp the composer's DPR so GTAO's buffers don't render at the full display resolution (4× the\n\t// pixels on a DPR-2 Retina panel). AO is low-frequency; a 1× buffer upscales near-invisibly.\n\tconst aoPixelRatioCap = options.aoPixelRatio ?? 1;\n\tcomposer.setSize(width, height);\n\n\treturn {\n\t\trender: (deltaTime) => composer.render(deltaTime),\n\t\t// composer.setSize propagates the pixel-ratio-multiplied size to every pass; calling\n\t\t// pass.setSize(w, h) here again would knock the AO/AA targets back down to logical CSS size.\n\t\tsetSize: (w, h, pixelRatio) => {\n\t\t\tcomposer.setPixelRatio(Math.min(pixelRatio, aoPixelRatioCap));\n\t\t\tcomposer.setSize(w, h);\n\t\t},\n\t\tsetCamera: (cam) => {\n\t\t\trenderPass.camera = cam;\n\t\t\tgtaoPass.camera = cam;\n\t\t\t// GTAOPass bakes the camera type into its AO shader as a define at construction; merely\n\t\t\t// reassigning `camera` leaves the old projection's depth/view-position reconstruction\n\t\t\t// active (garbage AO after a perspective ⇄ ortho toggle). Refresh the define — and force a\n\t\t\t// shader recompile — whenever the projection type actually changes. Near/far/projection\n\t\t\t// uniforms need no handling here: GTAOPass.render() re-reads them from `camera` per frame.\n\t\t\tconst isPerspective = (cam as Partial<THREE.PerspectiveCamera>).isPerspectiveCamera ? 1 : 0;\n\t\t\tif (gtaoPass.gtaoMaterial.defines.PERSPECTIVE_CAMERA !== isPerspective) {\n\t\t\t\tgtaoPass.gtaoMaterial.defines.PERSPECTIVE_CAMERA = isPerspective;\n\t\t\t\tgtaoPass.gtaoMaterial.needsUpdate = true;\n\t\t\t}\n\t\t},\n\t\t// composer.dispose() doesn't free added passes — dispose them explicitly.\n\t\tdispose: () => {\n\t\t\tcomposer.dispose();\n\t\t\tgtaoPass.dispose();\n\t\t\tsmaaPass.dispose();\n\t\t\toutputPass.dispose();\n\t\t}\n\t};\n}\n","import * as THREE from 'three';\nimport { CSS2DRenderer, CSS2DObject } from 'three/addons/renderers/CSS2DRenderer.js';\n\n/**\n * An HTML label layer that tracks 3D positions, via three's {@link CSS2DRenderer}. Labels are real\n * DOM nodes (crisp text, CSS-stylable) positioned each frame to follow points in the scene — the\n * foundation for measurement readouts, dimension annotations, and point tags.\n *\n * The CSS2D renderer draws into its own absolutely-positioned DOM overlay stacked on top of the\n * WebGL canvas (pointer-events disabled so it never steals clicks from the viewer). The viewer owns\n * one of these; features like the measure tool add/remove labels through it.\n */\n\nexport interface LabelHandle {\n\t/** The CSS2DObject in the scene graph. */\n\treadonly object: CSS2DObject;\n\t/** Move the label to a new world position. */\n\tsetPosition(position: THREE.Vector3): void;\n\t/** Replace the label's text/HTML. */\n\tsetText(text: string): void;\n\t/** Remove the label from the scene and the DOM. */\n\tremove(): void;\n}\n\nexport interface LabelLayer {\n\t/** Create a label at a world position. `className` lets callers theme groups of labels. */\n\taddLabel(text: string, position: THREE.Vector3, className?: string): LabelHandle;\n\t/** Render the DOM overlay. Call each frame after the WebGL render, with the active camera. */\n\trender(scene: THREE.Scene, camera: THREE.Camera): void;\n\tsetSize(width: number, height: number): void;\n\tdispose(): void;\n}\n\n/**\n * @param container element to overlay labels onto — normally the canvas's parent, so the overlay and\n * canvas share a positioning context. The overlay is appended here and absolutely positioned.\n * @param scene labels are parented to a group added to this scene, so they render and follow the\n * camera without the caller wiring scene-graph parenting.\n */\nexport function createLabelLayer(container: HTMLElement, scene: THREE.Scene): LabelLayer {\n\tconst renderer = new CSS2DRenderer();\n\tconst dom = renderer.domElement;\n\tdom.style.position = 'absolute';\n\tdom.style.top = '0';\n\tdom.style.left = '0';\n\t// The overlay must never intercept viewer interaction. CSS2DRenderer sizes its root div to the\n\t// renderer size and stacks it above the canvas; without an explicit non-interactive, clipped box\n\t// it can cover the canvas and swallow orbit/clicks. Note the box is sized in PIXELS by\n\t// `setSize` (CSS2DRenderer overwrites width/height styles and bases its projection math on the\n\t// same values, so percentage sizing can't work here) — the host's resize handling must call\n\t// `setSize` whenever the container resizes, exactly as it does for the WebGL renderer.\n\tdom.style.overflow = 'hidden';\n\tdom.style.pointerEvents = 'none';\n\t// Stack above the canvas and any host overlays (e.g. blur/loading scrims) that share the\n\t// container's positioning context — without an explicit z-index the overlay sits at z-auto and\n\t// such scrims paint over the labels. Kept below typical menu/popover layers.\n\tdom.style.zIndex = '30';\n\t// The container is the canvas's positioning context; make sure it actually establishes one.\n\tif (getComputedStyle(container).position === 'static') {\n\t\tcontainer.style.position = 'relative';\n\t}\n\tcontainer.appendChild(dom);\n\n\tconst size = { width: container.clientWidth || 1, height: container.clientHeight || 1 };\n\trenderer.setSize(size.width, size.height);\n\n\t// Labels live under a dedicated group so they're easy to find/exclude and removed en masse on\n\t// dispose. Tagged so pick/fit logic ignores it.\n\tconst group = new THREE.Group();\n\tgroup.name = 'label-layer';\n\tgroup.userData.id = 'label-layer';\n\tscene.add(group);\n\n\tconst labels = new Set<CSS2DObject>();\n\n\tconst addLabel = (text: string, position: THREE.Vector3, className?: string): LabelHandle => {\n\t\tconst el = document.createElement('div');\n\t\tel.textContent = text;\n\t\tif (className) {\n\t\t\tel.className = className;\n\t\t} else {\n\t\t\t// Default styling that stays legible on any background (light or dark scene/page): a dark\n\t\t\t// translucent pill with light text. Callers wanting their own look pass a className, which\n\t\t\t// opts out of all of this. Kept inline so the layer needs no external stylesheet.\n\t\t\tObject.assign(el.style, {\n\t\t\t\tpadding: '2px 6px',\n\t\t\t\tborderRadius: '4px',\n\t\t\t\tbackground: 'rgba(20, 20, 20, 0.78)',\n\t\t\t\tcolor: '#fff',\n\t\t\t\tfont: '12px/1.3 system-ui, sans-serif',\n\t\t\t\t// `pre` so a multi-line readout (e.g. total + per-axis deltas) keeps its line breaks.\n\t\t\t\twhiteSpace: 'pre',\n\t\t\t\ttextAlign: 'center',\n\t\t\t\tuserSelect: 'none'\n\t\t\t} satisfies Partial<CSSStyleDeclaration>);\n\t\t}\n\t\t// Individual labels stay non-interactive by default (the overlay is too, but be explicit so a\n\t\t// caller that opts a label into pointer-events doesn't get surprised by inherited none).\n\t\tel.style.pointerEvents = 'none';\n\n\t\tconst object = new CSS2DObject(el);\n\t\tobject.position.copy(position);\n\t\tgroup.add(object);\n\t\tlabels.add(object);\n\n\t\treturn {\n\t\t\tobject,\n\t\t\tsetPosition: (p) => object.position.copy(p),\n\t\t\tsetText: (t) => {\n\t\t\t\tel.textContent = t;\n\t\t\t},\n\t\t\tremove: () => {\n\t\t\t\tobject.removeFromParent();\n\t\t\t\tel.remove();\n\t\t\t\tlabels.delete(object);\n\t\t\t}\n\t\t};\n\t};\n\n\treturn {\n\t\taddLabel,\n\t\trender: (scene, camera) => renderer.render(scene, camera),\n\t\tsetSize: (width, height) => renderer.setSize(width, height),\n\t\tdispose: () => {\n\t\t\tlabels.forEach((object) => {\n\t\t\t\tobject.removeFromParent();\n\t\t\t\t(object.element as HTMLElement).remove();\n\t\t\t});\n\t\t\tlabels.clear();\n\t\t\tgroup.removeFromParent();\n\t\t\tdom.remove();\n\t\t}\n\t};\n}\n","import * as THREE from 'three';\nimport { Line2 } from 'three/addons/lines/Line2.js';\nimport { LineGeometry } from 'three/addons/lines/LineGeometry.js';\nimport { LineMaterial } from 'three/addons/lines/LineMaterial.js';\n\nimport type { LabelLayer, LabelHandle } from './label-layer';\n\n/**\n * A two-click distance measurement tool — the CAD verb users expect. Click a point, click a second,\n * read the distance off a label on the connecting line; a third click starts a new measurement.\n *\n * Picking snaps to geometry so measurements are exact, not \"wherever the ray happened to land\":\n * on a mesh hit we snap to the nearest vertex of the struck triangle if it's within\n * {@link MeasureOptions.snapPixels} on screen, else use the raw hit point. This is a cheap local\n * snap (three candidate vertices), no spatial index — enough for clean vertex-to-vertex measurement\n * without the cost/complexity of full edge/midpoint snapping (a later refinement).\n *\n * The tool is dormant until {@link MeasureTool.setEnabled}(true). While enabled it intercepts clicks\n * (the caller forwards them and swallows the event when {@link MeasureTool.handleClick} returns\n * true) so measuring doesn't also select objects.\n */\n\nexport interface MeasureTool {\n\tsetEnabled(enabled: boolean): void;\n\tisEnabled(): boolean;\n\t/** Process a click. Returns true if the tool consumed it (caller should not also select). */\n\thandleClick(event: MouseEvent): boolean;\n\t/**\n\t * Process pointer movement to preview the next snap point — a ghost marker tracks the cursor and\n\t * jumps to the vertex a click would snap to, so users can aim before committing. No-op when the\n\t * tool is disabled. The caller forwards mousemove; nothing is consumed.\n\t */\n\thandleMove(event: MouseEvent): void;\n\t/** Clear the current measurement (markers, line, label). */\n\tclear(): void;\n\tdispose(): void;\n}\n\nexport interface MeasureOptions {\n\t/** Snap to a vertex when the cursor is within this many screen pixels of it. Default 12. */\n\tsnapPixels?: number;\n\t/** Marker + line color. Default yellow. */\n\tcolor?: THREE.ColorRepresentation;\n\t/** CSS class applied to the distance label, for styling. */\n\tlabelClassName?: string;\n\t/**\n\t * The model's unit (pass `data.modelunits`). The scene is in meters, so the default formatter\n\t * converts and labels in this unit — e.g. a mm model reads \"25.0 mm\", not \"0.025 m\". Defaults\n\t * to meters. Ignored when a custom `format` is supplied.\n\t */\n\tdisplayUnit?: string;\n\t/**\n\t * Format the measurement → label text. Receives the straight-line `distance` and the per-axis\n\t * `delta` (|b − a| on each axis), both in **meters**. May return multi-line text or HTML; the\n\t * default renders the total plus a Δx/Δy/Δz breakdown in `displayUnit`. Overrides `displayUnit`.\n\t */\n\tformat?: (distance: number, delta: THREE.Vector3) => string;\n}\n\ninterface MeasureDeps {\n\tcanvas: HTMLCanvasElement;\n\tscene: THREE.Scene;\n\tgetActiveCamera: () => THREE.Camera;\n\t/**\n\t * The current orbit target (e.g. `controls.target`). Used to scale the line/point pick\n\t * threshold with the view: the tolerance is a fraction of the camera→target distance, so it\n\t * stays roughly constant on screen wherever the user has framed the model. Optional for\n\t * backward compatibility — without it the perspective fallback is the camera's distance to the\n\t * world origin, which misjudges the threshold for off-origin content. Thread it in when you can.\n\t */\n\tgetViewTarget?: () => THREE.Vector3;\n\tlabelLayer: LabelLayer;\n\toptions?: MeasureOptions;\n}\n\nconst DEFAULT_SNAP_PIXELS = 12;\nconst DEFAULT_COLOR = 0xffcc00;\n// Line/Points raycast threshold as a fraction of the view distance (camera→target). ~1.5% gives a\n// comfortable few-pixel grab band at typical framing without snapping to far-off geometry.\nconst LINE_PICK_FRACTION = 0.015;\n\n/**\n * Scene geometry is loaded in meters (the webdisplay parser scales to meters when\n * `allowScaling` is on), so distances come out in meters. To label in the model's\n * own unit, convert with `metersPerUnit` and append `suffix`. Keep this in sync\n * with the webdisplay parser's SCALE_FACTORS.\n */\nconst UNIT_DISPLAY: Record<string, { metersPerUnit: number; suffix: string }> = {\n\tMillimeters: { metersPerUnit: 1 / 1000, suffix: 'mm' },\n\tCentimeters: { metersPerUnit: 1 / 100, suffix: 'cm' },\n\tMeters: { metersPerUnit: 1, suffix: 'm' },\n\tInches: { metersPerUnit: 1 / 39.37, suffix: 'in' },\n\tFeet: { metersPerUnit: 1 / 3.28084, suffix: 'ft' }\n};\n\n/**\n * Build a `meters → label` formatter for the given display unit (defaults to meters).\n * @internal exported for tests\n */\nexport function makeFormatter(displayUnit?: string): (n: number) => string {\n\tconst unit = (displayUnit && UNIT_DISPLAY[displayUnit]) || UNIT_DISPLAY.Meters;\n\treturn (meters: number) => `${(meters / unit.metersPerUnit).toPrecision(3)} ${unit.suffix}`;\n}\n\n/**\n * World-space raycast threshold for picking lines/points (which have no surface area and are only\n * \"hit\" when the ray passes within this distance of them). A fixed fraction of the view size keeps\n * the grab band roughly constant on screen as the user zooms:\n * - perspective: fraction of the camera→target distance (the framed view size). Falls back to the\n * camera's distance to the world origin when no target is supplied — see `MeasureDeps.getViewTarget`.\n * - orthographic: fraction of the visible frustum height, `(top − bottom) / zoom`. Ortho zoom\n * changes `camera.zoom`, not the camera position, so distance-based scaling would never react.\n * @internal exported for tests\n */\nexport function pickThreshold(camera: THREE.Camera, viewTarget?: THREE.Vector3): number {\n\tif ((camera as THREE.OrthographicCamera).isOrthographicCamera) {\n\t\tconst ortho = camera as THREE.OrthographicCamera;\n\t\tconst visibleHeight = Math.abs(ortho.top - ortho.bottom) / (ortho.zoom || 1);\n\t\treturn visibleHeight * LINE_PICK_FRACTION;\n\t}\n\tconst viewScale = viewTarget ? camera.position.distanceTo(viewTarget) : camera.position.length();\n\treturn (viewScale || 1) * LINE_PICK_FRACTION;\n}\n\n/**\n * The vertex indices to consider snapping to for a given hit, by object type:\n * - Mesh: the three vertices of the struck triangle (`hit.face`).\n * - Line / LineSegments: the two endpoints of the struck segment (`hit.index`, `hit.index + 1`).\n * - Points: the struck vertex (`hit.index`).\n * Returns null when the hit carries no usable index info (e.g. a fat `Line2`), so the caller keeps\n * the raw hit point.\n */\nfunction snapCandidateIndices(hit: THREE.Intersection): number[] | null {\n\tconst obj = hit.object;\n\tif (obj instanceof THREE.Mesh) {\n\t\treturn hit.face ? [hit.face.a, hit.face.b, hit.face.c] : null;\n\t}\n\tif (obj instanceof THREE.Points) {\n\t\t// Points.raycast resolves indexed geometry itself: `hit.index` is always a position index.\n\t\treturn hit.index != null ? [hit.index] : null;\n\t}\n\t// THREE.Line / LineSegments / LineLoop. For non-indexed geometry `hit.index` is the first\n\t// vertex of the struck segment; for INDEXED geometry it is a cursor into the index buffer\n\t// (three r184 Line.raycast reports the loop counter, not the resolved vertex), so the segment's\n\t// endpoints must be looked up through the index before reading the position attribute.\n\tif (obj instanceof THREE.Line) {\n\t\tif (hit.index == null) return null;\n\t\tconst index = obj.geometry.index;\n\t\tif (index) {\n\t\t\tif (hit.index + 1 >= index.count) return null; // stale/inconsistent hit; keep raw point\n\t\t\treturn [index.getX(hit.index), index.getX(hit.index + 1)];\n\t\t}\n\t\treturn [hit.index, hit.index + 1];\n\t}\n\treturn null;\n}\n\n/**\n * Snap a raycast hit to the nearest geometry vertex within `snapPixels` on screen; otherwise return\n * the raw hit point. Works for meshes (triangle vertices), lines (segment endpoints), and points\n * (the vertex itself). Pure (no DOM) so it's unit-testable: it takes the screen size explicitly\n * rather than reading the canvas. Exported for that reason.\n *\n * Falls back to the raw point for hits without usable vertex indices or positions.\n */\nexport function snapToVertex(\n\thit: THREE.Intersection,\n\tcamera: THREE.Camera,\n\tscreenSize: { width: number; height: number },\n\tsnapPixels: number\n): THREE.Vector3 {\n\tconst raw = hit.point.clone();\n\tconst obj = hit.object as THREE.Object3D & { geometry?: THREE.BufferGeometry };\n\tconst indices = snapCandidateIndices(hit);\n\tif (!indices || !obj.geometry) return raw;\n\n\tconst pos = obj.geometry.attributes.position as THREE.BufferAttribute | undefined;\n\tif (!pos) return raw;\n\n\tconst toScreen = (worldP: THREE.Vector3): THREE.Vector2 => {\n\t\tconst ndc = worldP.clone().project(camera);\n\t\treturn new THREE.Vector2(\n\t\t\t((ndc.x + 1) / 2) * screenSize.width,\n\t\t\t((1 - ndc.y) / 2) * screenSize.height\n\t\t);\n\t};\n\tconst rawScreen = toScreen(raw);\n\n\tlet best = raw;\n\tlet bestPx = snapPixels;\n\tfor (const idx of indices) {\n\t\tif (idx >= pos.count) continue; // guard the line `index + 1` against the geometry end\n\t\tconst local = new THREE.Vector3().fromBufferAttribute(pos, idx);\n\t\tconst world = local.applyMatrix4(obj.matrixWorld);\n\t\tconst px = toScreen(world).distanceTo(rawScreen);\n\t\tif (px < bestPx) {\n\t\t\tbestPx = px;\n\t\t\tbest = world;\n\t\t}\n\t}\n\treturn best;\n}\n\nexport function createMeasureTool(deps: MeasureDeps): MeasureTool {\n\tconst { canvas, scene, getActiveCamera, getViewTarget, labelLayer, options = {} } = deps;\n\tconst snapPixels = options.snapPixels ?? DEFAULT_SNAP_PIXELS;\n\tconst color = new THREE.Color(options.color ?? DEFAULT_COLOR);\n\tconst fmt = makeFormatter(options.displayUnit);\n\tconst defaultFormat = (d: number, delta: THREE.Vector3) =>\n\t\t`${fmt(d)}\\nΔx ${fmt(delta.x)} Δy ${fmt(delta.y)} Δz ${fmt(delta.z)}`;\n\tconst format = options.format ?? defaultFormat;\n\n\tconst raycaster = new THREE.Raycaster();\n\tconst pointer = new THREE.Vector2();\n\n\tlet enabled = false;\n\tconst points: THREE.Vector3[] = [];\n\n\t// Visuals, created lazily and reused. Markers are small always-on-top points; the line connects\n\t// them; the label rides the line's midpoint.\n\tconst markers: THREE.Points[] = [];\n\tlet line: Line2 | null = null;\n\tlet label: LabelHandle | null = null;\n\n\tconst markerMaterial = new THREE.PointsMaterial({\n\t\tcolor,\n\t\tsize: 8,\n\t\tsizeAttenuation: false,\n\t\tdepthTest: false // markers stay visible through geometry, like CAD snap dots\n\t});\n\n\t// A hollow-feeling preview dot: dimmer + bigger than a committed marker so the snap target the\n\t// next click will lock onto is obvious before clicking. Shown only while hovering geometry.\n\tconst hoverMaterial = new THREE.PointsMaterial({\n\t\tcolor,\n\t\tsize: 11,\n\t\tsizeAttenuation: false,\n\t\tdepthTest: false,\n\t\ttransparent: true,\n\t\topacity: 0.5\n\t});\n\tlet hoverMarker: THREE.Points | null = null;\n\n\tconst showHover = (p: THREE.Vector3 | null) => {\n\t\tif (!p) {\n\t\t\tif (hoverMarker) hoverMarker.visible = false;\n\t\t\treturn;\n\t\t}\n\t\tif (!hoverMarker) {\n\t\t\tconst geometry = new THREE.BufferGeometry();\n\t\t\tgeometry.setAttribute('position', new THREE.Float32BufferAttribute([0, 0, 0], 3));\n\t\t\thoverMarker = new THREE.Points(geometry, hoverMaterial);\n\t\t\thoverMarker.renderOrder = 1000;\n\t\t\thoverMarker.userData.id = 'measure';\n\t\t\thoverMarker.raycast = () => {};\n\t\t\tscene.add(hoverMarker);\n\t\t}\n\t\thoverMarker.position.copy(p);\n\t\thoverMarker.visible = true;\n\t};\n\n\tconst makeMarker = (p: THREE.Vector3): THREE.Points => {\n\t\tconst geometry = new THREE.BufferGeometry();\n\t\tgeometry.setAttribute('position', new THREE.Float32BufferAttribute([p.x, p.y, p.z], 3));\n\t\tconst marker = new THREE.Points(geometry, markerMaterial);\n\t\tmarker.renderOrder = 999;\n\t\tmarker.userData.id = 'measure'; // excluded from pick/fit\n\t\tmarker.raycast = () => {}; // don't let markers be measure targets themselves\n\t\tscene.add(marker);\n\t\treturn marker;\n\t};\n\n\tconst clear = () => {\n\t\tpoints.length = 0;\n\t\tmarkers.forEach((m) => {\n\t\t\tm.geometry.dispose();\n\t\t\tm.removeFromParent();\n\t\t});\n\t\tmarkers.length = 0;\n\t\tif (line) {\n\t\t\tline.geometry.dispose();\n\t\t\t(line.material as LineMaterial).dispose();\n\t\t\tline.removeFromParent();\n\t\t\tline = null;\n\t\t}\n\t\tlabel?.remove();\n\t\tlabel = null;\n\t};\n\n\tconst drawMeasurement = () => {\n\t\tif (points.length !== 2) return;\n\t\tconst [a, b] = points;\n\n\t\tconst geometry = new LineGeometry();\n\t\tgeometry.setPositions([a.x, a.y, a.z, b.x, b.y, b.z]);\n\t\tconst material = new LineMaterial({ color });\n\t\t(material as LineMaterial & { linewidth: number; depthTest: boolean }).linewidth = 2;\n\t\tmaterial.depthTest = false;\n\n\t\tline = new Line2(geometry, material);\n\t\tline.renderOrder = 998;\n\t\tline.userData.id = 'measure';\n\t\tline.raycast = () => {};\n\t\tscene.add(line);\n\n\t\tconst mid = a.clone().add(b).multiplyScalar(0.5);\n\t\tconst delta = new THREE.Vector3(Math.abs(b.x - a.x), Math.abs(b.y - a.y), Math.abs(b.z - a.z));\n\t\tlabel = labelLayer.addLabel(format(a.distanceTo(b), delta), mid, options.labelClassName);\n\t};\n\n\t/** Raycast the cursor and return the snapped pick point, or null if it hit no measurable geometry. */\n\tconst pickPoint = (event: MouseEvent): THREE.Vector3 | null => {\n\t\tconst rect = canvas.getBoundingClientRect();\n\t\tpointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;\n\t\tpointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;\n\n\t\tconst camera = getActiveCamera();\n\t\traycaster.setFromCamera(pointer, camera);\n\n\t\t// Lines and points have no surface area, so they're only \"hit\" when the ray passes within a\n\t\t// world-space threshold of them — left at the default ~1 unit they're nearly impossible to\n\t\t// click. Scale the threshold with the view (camera→target distance, or the ortho frustum\n\t\t// height under zoom) so the pick tolerance stays roughly constant on screen — see pickThreshold.\n\t\tconst threshold = pickThreshold(camera, getViewTarget?.());\n\t\traycaster.params.Line!.threshold = threshold;\n\t\traycaster.params.Points!.threshold = threshold;\n\n\t\tconst hits = raycaster\n\t\t\t.intersectObjects(scene.children, true)\n\t\t\t.filter((i) => i.object.userData.id !== 'measure' && i.object.userData.id !== 'grid');\n\n\t\tif (hits.length === 0) return null;\n\t\treturn snapToVertex(hits[0], camera, { width: rect.width, height: rect.height }, snapPixels);\n\t};\n\n\t// Coalesce hover raycasts to one per animation frame: mousemove can fire far more often than\n\t// the display refreshes, and a full-scene recursive raycast per event hitches on large models.\n\t// Only the latest event matters for the preview, so intermediate ones are simply dropped.\n\tlet pendingMove: MouseEvent | null = null;\n\tlet moveRaf = 0;\n\n\tconst cancelPendingMove = () => {\n\t\tif (moveRaf) {\n\t\t\tcancelAnimationFrame(moveRaf);\n\t\t\tmoveRaf = 0;\n\t\t}\n\t\tpendingMove = null;\n\t};\n\n\tconst handleMove = (event: MouseEvent): void => {\n\t\tif (!enabled) return;\n\t\tpendingMove = event;\n\t\tif (moveRaf) return;\n\t\tmoveRaf = requestAnimationFrame(() => {\n\t\t\tmoveRaf = 0;\n\t\t\tconst latest = pendingMove;\n\t\t\tpendingMove = null;\n\t\t\tif (!enabled || !latest) return;\n\t\t\tshowHover(pickPoint(latest));\n\t\t});\n\t};\n\n\tconst handleClick = (event: MouseEvent): boolean => {\n\t\tif (!enabled) return false;\n\n\t\t// A third click after a completed measurement starts fresh.\n\t\tif (points.length === 2) clear();\n\n\t\tconst point = pickPoint(event);\n\t\tif (point === null) return true; // consumed: a measuring click that missed still isn't a select\n\n\t\tpoints.push(point);\n\t\tmarkers.push(makeMarker(point));\n\n\t\tif (points.length === 2) drawMeasurement();\n\t\treturn true;\n\t};\n\n\treturn {\n\t\tsetEnabled: (value) => {\n\t\t\tenabled = value;\n\t\t\tif (!value) {\n\t\t\t\tcancelPendingMove();\n\t\t\t\tclear();\n\t\t\t\tshowHover(null);\n\t\t\t}\n\t\t},\n\t\tisEnabled: () => enabled,\n\t\thandleClick,\n\t\thandleMove,\n\t\tclear,\n\t\tdispose: () => {\n\t\t\tcancelPendingMove();\n\t\t\tclear();\n\t\t\tif (hoverMarker) {\n\t\t\t\thoverMarker.geometry.dispose();\n\t\t\t\thoverMarker.removeFromParent();\n\t\t\t\thoverMarker = null;\n\t\t\t}\n\t\t\tmarkerMaterial.dispose();\n\t\t\thoverMaterial.dispose();\n\t\t}\n\t};\n}\n","import * as THREE from 'three';\n\nimport { getLogger } from '@/core';\n\n/**\n * Maximum number of decoded textures retained by the module-level cache. When a fresh load pushes\n * the cache past this bound, the least-recently-used entry is evicted and its GPU texture disposed.\n * Sized generously above any realistic per-scene texture count (a solve's materials re-touch their\n * textures on every re-parse, keeping live entries recent), so eviction only ever trims textures\n * that no current scene references — e.g. a workflow regenerating a data-URI texture per solve.\n */\nexport const TEXTURE_CACHE_MAX_ENTRIES = 64;\n\n/**\n * Cache keys longer than this are replaced by a compact hash. Content-hashed asset URLs and normal\n * http(s) URLs stay comfortably below it; multi-KB/MB data URIs (whose full string would otherwise\n * be retained as the Map key for as long as the texture lives) exceed it and get hashed.\n */\nconst MAX_KEY_LENGTH = 256;\n\n/**\n * Module-level texture cache keyed by URL (or a hash of it — see {@link cacheKeyFor}).\n *\n * Material texture references are immutable by construction — the plugin serves bitmap/file\n * textures at content-hashed URLs (`/assets/{hash}`) and http(s)/data URIs identify their own\n * content — so each URL is fetched and GPU-decoded exactly once per session no matter how many\n * solves or materials reference it. Selva's hot loop re-parses batches on every slider nudge;\n * without this cache every solve would re-decode every texture.\n *\n * The Map doubles as the LRU order: hits re-insert their entry, so iteration order is\n * least-recently-used first and eviction pops the first key.\n */\nconst textureCache = new Map<string, THREE.Texture>();\nconst inFlight = new Map<string, Promise<THREE.Texture>>();\n\n/**\n * Bumped by {@link clearTextureCache}. A load that started before a clear compares its captured\n * generation on resolve: if the cache was cleared meanwhile, the freshly decoded texture is\n * disposed instead of repopulating the just-emptied cache (which would leak it past viewer\n * teardown and silently serve it to future materials despite the intended full reset).\n */\nlet cacheGeneration = 0;\n\n/**\n * Rejection used when a load resolves after {@link clearTextureCache} wiped the cache. Expected\n * during viewer teardown, so {@link applyTextureMap} swallows it silently instead of warning.\n */\nclass StaleTextureLoadError extends Error {\n\tconstructor(url: string) {\n\t\tsuper(`Texture load for ${url} resolved after clearTextureCache(); texture disposed.`);\n\t\tthis.name = 'StaleTextureLoadError';\n\t}\n}\n\n/**\n * Max anisotropic-filtering samples applied to color maps, keeping textures sharp at grazing angles\n * (floors, long walls receding to the horizon) instead of blurring. The ceiling is hardware-defined\n * (`renderer.capabilities.getMaxAnisotropy()`, typically 16); the viewer reports it once at init via\n * {@link setTextureAnisotropy}. Defaults to 1 (three's default — no anisotropy) so the module is\n * correct even if the viewer never calls in.\n */\nlet maxAnisotropy = 1;\n\n/**\n * Set the anisotropy applied to all color-map textures. Call once from the viewer with\n * `renderer.capabilities.getMaxAnisotropy()`. Retroactively updates already-cached textures so\n * textures decoded before this call still benefit.\n */\nexport function setTextureAnisotropy(value: number): void {\n\tmaxAnisotropy = Math.max(1, value);\n\tfor (const texture of textureCache.values()) {\n\t\tif (texture.anisotropy !== maxAnisotropy) {\n\t\t\ttexture.anisotropy = maxAnisotropy;\n\t\t\ttexture.needsUpdate = true;\n\t\t}\n\t}\n}\n\n/**\n * Assigns a texture to `material.map`, synchronously when cached, otherwise asynchronously once\n * the image is fetched and decoded (flagging `needsUpdate` — the mesh renders untextured for at\n * most the first frames). Load failures log a warning and leave the material untextured rather\n * than breaking the batch. A load that resolves after {@link clearTextureCache} is discarded\n * silently (its texture disposed) — the clear signals the viewer no longer wants it.\n */\nexport function applyTextureMap(material: THREE.MeshPhysicalMaterial, url: string): void {\n\tconst key = cacheKeyFor(url);\n\tconst cached = textureCache.get(key);\n\tif (cached) {\n\t\t// Refresh LRU recency: re-insert so this entry moves to the back of the eviction order.\n\t\ttextureCache.delete(key);\n\t\ttextureCache.set(key, cached);\n\t\tmaterial.map = cached;\n\t\tmaterial.needsUpdate = true;\n\t\treturn;\n\t}\n\n\t// No DOM (SSR / tests): textures can't decode without an image element; skip quietly.\n\tif (typeof document === 'undefined') {\n\t\treturn;\n\t}\n\n\tloadTexture(url, key)\n\t\t.then((texture) => {\n\t\t\tmaterial.map = texture;\n\t\t\tmaterial.needsUpdate = true;\n\t\t})\n\t\t.catch((error) => {\n\t\t\tif (error instanceof StaleTextureLoadError) {\n\t\t\t\treturn; // Cache cleared mid-load (teardown/reset) — untextured is the intended state.\n\t\t\t}\n\t\t\tgetLogger().warn(`Failed to load material texture ${url}:`, error);\n\t\t});\n}\n\n/**\n * Disposes all cached textures and empties the cache (e.g. on viewer teardown). Loads still in\n * flight are orphaned: when they resolve they see the bumped generation, dispose their texture,\n * and do not repopulate the cache.\n */\nexport function clearTextureCache(): void {\n\tcacheGeneration++;\n\tfor (const texture of textureCache.values()) {\n\t\ttexture.dispose();\n\t}\n\ttextureCache.clear();\n\tinFlight.clear();\n}\n\n/**\n * Maps a texture URL to its cache key. Short URLs key by themselves; oversized ones (data URIs)\n * key by a 32-bit FNV-1a hash plus length so the multi-KB/MB URI string isn't retained as a Map\n * key. The `data-uri:` prefix keeps hashed keys disjoint from literal URL keys.\n */\nfunction cacheKeyFor(url: string): string {\n\tif (url.length <= MAX_KEY_LENGTH) {\n\t\treturn url;\n\t}\n\treturn `data-uri:${fnv1aString(url).toString(16)}:${url.length}`;\n}\n\n/** 32-bit FNV-1a over the string's UTF-16 code units. */\nfunction fnv1aString(s: string): number {\n\tlet hash = 0x811c9dc5;\n\tfor (let i = 0; i < s.length; i++) {\n\t\thash ^= s.charCodeAt(i);\n\t\thash = Math.imul(hash, 0x01000193);\n\t}\n\treturn hash >>> 0;\n}\n\n/** Inserts a texture, evicting (and disposing) least-recently-used entries past the bound. */\nfunction storeTexture(key: string, texture: THREE.Texture): void {\n\ttextureCache.set(key, texture);\n\twhile (textureCache.size > TEXTURE_CACHE_MAX_ENTRIES) {\n\t\tconst oldestKey = textureCache.keys().next().value as string;\n\t\tconst evicted = textureCache.get(oldestKey)!;\n\t\ttextureCache.delete(oldestKey);\n\t\tevicted.dispose();\n\t}\n}\n\nfunction loadTexture(url: string, key: string): Promise<THREE.Texture> {\n\tlet pending = inFlight.get(key);\n\tif (!pending) {\n\t\tconst generation = cacheGeneration;\n\t\tpending = new Promise<THREE.Texture>((resolve, reject) => {\n\t\t\tnew THREE.TextureLoader().load(\n\t\t\t\turl,\n\t\t\t\t(texture) => {\n\t\t\t\t\tif (generation !== cacheGeneration) {\n\t\t\t\t\t\t// clearTextureCache() ran while this load was in flight: the cache (and the\n\t\t\t\t\t\t// viewer that wanted this texture) is gone. Repopulating would leak a live GPU\n\t\t\t\t\t\t// texture past teardown, so dispose it and reject as stale.\n\t\t\t\t\t\ttexture.dispose();\n\t\t\t\t\t\treject(new StaleTextureLoadError(url));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\t// Color maps are sRGB; without this the render is washed out.\n\t\t\t\t\ttexture.colorSpace = THREE.SRGBColorSpace;\n\t\t\t\t\t// Keep textures crisp at grazing angles (see maxAnisotropy).\n\t\t\t\t\ttexture.anisotropy = maxAnisotropy;\n\t\t\t\t\tstoreTexture(key, texture);\n\t\t\t\t\tinFlight.delete(key);\n\t\t\t\t\tresolve(texture);\n\t\t\t\t},\n\t\t\t\tundefined,\n\t\t\t\t(error) => {\n\t\t\t\t\t// Guarded so a failure resolving after a clear can't delete a *newer* in-flight\n\t\t\t\t\t// entry for the same key (the clear already wiped this one).\n\t\t\t\t\tif (generation === cacheGeneration) {\n\t\t\t\t\t\tinFlight.delete(key);\n\t\t\t\t\t}\n\t\t\t\t\treject(error);\n\t\t\t\t}\n\t\t\t);\n\t\t});\n\t\tinFlight.set(key, pending);\n\t}\n\n\treturn pending;\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, Look, LookPreset } 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 { computeContentBounds } from './three-helpers';\nimport { setTextureAnisotropy } from '../webdisplay/texture-cache';\n\nconst defaultUp = new THREE.Vector3(0, 0, 1);\n\n/** The look applied when the caller passes no `look` option. */\nconst DEFAULT_LOOK: Look = 'technical';\n\n/**\n * The ready-to-go looks, as concrete lighting/material dial values. Single source of truth: consumed\n * by `applyDefaults` to seed construction-time defaults AND by `setLook` to re-apply a look at\n * runtime, so the two paths can never drift. A look carries ONLY lighting/material — never edges or\n * grid (those are independent overlays). See {@link Look} for what each reads like.\n *\n * Every look ships with `ambientOcclusion: false`: GTAO is a heavy full-screen postprocessing path\n * that can dominate frame time, so it stays opt-in (via `render.ambientOcclusion` or the runtime\n * `setAmbientOcclusion(true)`) rather than costing every viewer 60fps by default.\n */\nexport const LOOK_PRESETS: Record<Look, LookPreset> = {\n\t// The default \"just works\" look: ACES + hemisphere fill + lifted HDR so products are well-lit\n\t// regardless of the environment map, while ambient stays low so colour doesn't wash out.\n\tstudio: {\n\t\ttoneMapping: THREE.ACESFilmicToneMapping,\n\t\ttoneMappingExposure: 1,\n\t\tenvMapIntensity: 1.3,\n\t\tenvironmentIntensity: 1.2,\n\t\themisphereIntensity: 1.0,\n\t\tambientIntensity: 0.3,\n\t\tcullBackfaces: false,\n\t\tambientOcclusion: false\n\t},\n\t// Flat CAD/drawing look: neutral tone mapping, low IBL, no fill — full flat ambient only.\n\ttechnical: {\n\t\ttoneMapping: THREE.NeutralToneMapping,\n\t\ttoneMappingExposure: 1,\n\t\tenvMapIntensity: 0.5,\n\t\tenvironmentIntensity: 1,\n\t\themisphereIntensity: 0,\n\t\tambientIntensity: 1,\n\t\tcullBackfaces: false,\n\t\tambientOcclusion: false\n\t},\n\t// Punchier presentation: like studio but stronger IBL/fill and a touch more exposure.\n\tshowcase: {\n\t\ttoneMapping: THREE.ACESFilmicToneMapping,\n\t\ttoneMappingExposure: 1.05,\n\t\tenvMapIntensity: 1.6,\n\t\tenvironmentIntensity: 1.35,\n\t\themisphereIntensity: 1.2,\n\t\tambientIntensity: 0.25,\n\t\tcullBackfaces: false,\n\t\tambientOcclusion: false\n\t}\n};\n\n/**\n * The material-parse options implied by a look — feed these into the batch parser's `material` option\n * so meshes are built to match it (backface culling, IBL strength). Kept out of the viewer's runtime\n * dials because they're baked at parse time, not toggleable in place.\n */\nexport function materialAppearanceForLook(look: Look): MaterialAppearanceOptions {\n\tconst preset = LOOK_PRESETS[look];\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\t/**\n\t * Switch the viewer to a ready-to-go look at runtime ('studio' | 'technical' | 'showcase'). Retunes\n\t * lighting/material only (tone mapping, fill, IBL, AO) — never edges/grid. A straight preset apply:\n\t * overwrites any granular lighting dials you set earlier.\n\t */\n\tsetLook: (look: 'studio' | 'technical' | 'showcase') => void;\n\t/**\n\t * Retune the fill lights at runtime: the direction-aware hemisphere fill (sky/ground) and the flat\n\t * ambient. Raising `hemisphereIntensity` is the most effective way to lift shadowed / under-facing\n\t * surfaces a dark HDR leaves black. A positive `hemisphereIntensity` lazily creates the hemisphere\n\t * light if the viewer was built without one; `0` switches it off.\n\t */\n\tsetFillLights: (opts: {\n\t\themisphereIntensity?: number;\n\t\themisphereSkyColor?: THREE.Color | number;\n\t\themisphereGroundColor?: THREE.Color | number;\n\t\tambientIntensity?: number;\n\t}) => void;\n\t/**\n\t * Set the uniform multiplier on the HDR's image-based lighting (`scene.environmentIntensity`) at\n\t * runtime — normalizes brightness across HDRs of differing exposure so the scene isn't at the\n\t * mercy of whichever HDR is loaded. Applies immediately, even before the HDR finishes decoding.\n\t */\n\tsetEnvironmentIntensity: (intensity: number) => void;\n\t/** Set renderer tone-mapping exposure at runtime. Higher lifts shadows and overall brightness. */\n\tsetToneMappingExposure: (exposure: number) => void;\n\t/** Set GTAO strength at runtime (0–1). No-op when ambient occlusion isn't active. */\n\tsetAoIntensity: (intensity: number) => void;\n\t/**\n\t * The parse-time material options (backface culling, IBL strength) matching the active look — feed\n\t * into the batch parser's `material` option so freshly-loaded meshes are built to match it. See\n\t * `setLook`.\n\t */\n\tgetMaterialAppearance: () => MaterialAppearanceOptions;\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// Scene lights. The shadow-casting sun (null when sunlight or shadows are off) has its shadow\n\t// frustum fitted to the scene content below and again whenever the host calls updateShadowBounds\n\t// after a geometry change — keeping shadow-map texels packed onto the model for crisp shadows at\n\t// any scale. The ambient + optional hemisphere fill are retunable at runtime via the setters below.\n\tconst lights = setupLighting(scene, config);\n\tconst sunlight = lights.sun;\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\taoPixelRatio: config.render.aoPixelRatio\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 * Retune the fill lights at runtime — the direction-aware hemisphere fill and the flat ambient.\n\t * Raising the hemisphere intensity is the most effective way to lift shadowed/under-facing\n\t * surfaces that a dark HDR leaves black, without washing the whole scene flat the way ambient does.\n\t * Pass `hemisphereIntensity: 0` to switch the fill off; a positive value creates the light lazily\n\t * if the viewer was built without one.\n\t */\n\tconst setFillLights = (opts: {\n\t\themisphereIntensity?: number;\n\t\themisphereSkyColor?: THREE.Color | number;\n\t\themisphereGroundColor?: THREE.Color | number;\n\t\tambientIntensity?: number;\n\t}) => {\n\t\tif (opts.ambientIntensity !== undefined) {\n\t\t\tlights.ambient.intensity = opts.ambientIntensity;\n\t\t}\n\t\tif (\n\t\t\topts.hemisphereIntensity !== undefined &&\n\t\t\t!lights.hemisphere &&\n\t\t\topts.hemisphereIntensity > 0\n\t\t) {\n\t\t\t// Built without a hemisphere light — create one on first positive intensity so hosts can\n\t\t\t// enable the fill purely at runtime.\n\t\t\tlights.hemisphere = new THREE.HemisphereLight(\n\t\t\t\topts.hemisphereSkyColor ?? config.lighting.hemisphereSkyColor,\n\t\t\t\topts.hemisphereGroundColor ?? config.lighting.hemisphereGroundColor,\n\t\t\t\topts.hemisphereIntensity\n\t\t\t);\n\t\t\tlights.hemisphere.position.copy(config.environment.sceneUp ?? defaultUp);\n\t\t\tscene.add(lights.hemisphere);\n\t\t}\n\t\tif (lights.hemisphere) {\n\t\t\tif (opts.hemisphereIntensity !== undefined)\n\t\t\t\tlights.hemisphere.intensity = opts.hemisphereIntensity;\n\t\t\tif (opts.hemisphereSkyColor !== undefined)\n\t\t\t\tlights.hemisphere.color.set(opts.hemisphereSkyColor);\n\t\t\tif (opts.hemisphereGroundColor !== undefined)\n\t\t\t\tlights.hemisphere.groundColor.set(opts.hemisphereGroundColor);\n\t\t}\n\t};\n\n\t/**\n\t * Set the uniform multiplier on the HDR's image-based lighting (`scene.environmentIntensity`).\n\t * Normalizes brightness across HDRs of differing exposure — lift a dim HDR or tame a bright one —\n\t * so the scene isn't at the mercy of whichever HDR is loaded. Applies immediately, even before the\n\t * HDR has finished decoding.\n\t */\n\tconst setEnvironmentIntensity = (intensity: number) => {\n\t\tconfig.environment.environmentIntensity = intensity;\n\t\tscene.environmentIntensity = intensity;\n\t};\n\n\t/** Set renderer tone-mapping exposure at runtime. Higher lifts shadows and overall brightness. */\n\tconst setToneMappingExposure = (exposure: number) => {\n\t\tconfig.render.toneMappingExposure = exposure;\n\t\trenderer.toneMappingExposure = exposure;\n\t\t// When AO is on, tone mapping is applied by the composer's OutputPass — rebuild so it adopts\n\t\t// the new exposure.\n\t\tif (renderPipeline) {\n\t\t\tsetAmbientOcclusion(false);\n\t\t\tsetAmbientOcclusion(true);\n\t\t}\n\t};\n\n\t/** Set GTAO strength at runtime (0 = off-looking, 1 = full). No-op when AO isn't active. */\n\tconst setAoIntensity = (intensity: number) => {\n\t\tconfig.render.aoIntensity = intensity;\n\t\tif (renderPipeline) {\n\t\t\tsetAmbientOcclusion(false);\n\t\t\tsetAmbientOcclusion(true);\n\t\t}\n\t};\n\n\t/**\n\t * Apply a ready-to-go look to the *already-built* scene at runtime — a quick way to switch looks in\n\t * a live viewer. It retunes only LIGHTING/MATERIAL: tone mapping/exposure, hemisphere fill +\n\t * ambient, HDR environment intensity, AO on/off, and `envMapIntensity` on every compute material\n\t * currently in the scene. It deliberately does NOT touch edges or grid (those are independent\n\t * overlays — toggle them via `grid.setVisible()` / `applyEdges`). It does not rebuild geometry, so\n\t * parse-time material choices (backface culling, vertex-color decode) are unaffected — set those via\n\t * the batch parser's `material` option (see `getMaterialAppearance`).\n\t *\n\t * Note: this is a straight preset apply. Any dial you set earlier via a granular setter\n\t * (`setToneMappingExposure`, `setFillLights`, …) is overwritten to the new look's value.\n\t */\n\tconst setLook = (look: Look) => {\n\t\tconst preset = LOOK_PRESETS[look];\n\t\tactiveLook = look;\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\t// Fill lighting + HDR normalization: studio/showcase add hemisphere fill and lift the environment\n\t\t// so shadowed surfaces read well regardless of the HDR; technical zeroes the fill back to a flat\n\t\t// CAD look. Applied through the same setters a host would call.\n\t\tsetFillLights({\n\t\t\themisphereIntensity: preset.hemisphereIntensity,\n\t\t\tambientIntensity: preset.ambientIntensity\n\t\t});\n\t\tsetEnvironmentIntensity(preset.environmentIntensity);\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\t};\n\n\t// The look currently applied. Always a real look (the default is 'studio'), seeded from the same\n\t// resolved value as the construction defaults. Drives `getMaterialAppearance()`.\n\tlet activeLook: Look = config.look;\n\n\t/**\n\t * The parse-time material options (backface culling, IBL strength) that match the active look —\n\t * pass into the batch parser's `material` option so newly-loaded meshes are built to match it.\n\t */\n\tconst getMaterialAppearance = (): MaterialAppearanceOptions =>\n\t\tmaterialAppearanceForLook(activeLook);\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\t// Idempotent: a second call would re-run forceContextLoss() on an already-lost\n\t\t// context, throwing \"INVALID_OPERATION: loseContext: context already lost\".\n\t\t// Double-dispose happens naturally (React StrictMode effect double-invoke, hosts\n\t\t// that unmount twice), so guard on the flag we already track.\n\t\tif (disposed) return;\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\tsetLook,\n\t\tsetFillLights,\n\t\tsetEnvironmentIntensity,\n\t\tsetToneMappingExposure,\n\t\tsetAoIntensity,\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\n// Exported for unit testing the option-precedence logic (initThree itself needs a real WebGL canvas).\nexport function 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// The chosen look seeds the lighting/material defaults (tone mapping, AO, IBL, fill). It sits BELOW\n\t// explicit per-field options (those still win) and ABOVE the plain per-field defaults — so it only\n\t// fills what the caller left unspecified. Always a real preset: the default IS a look ('studio'),\n\t// so there's no \"no look\" state to represent. A look never touches edges/grid — those resolve from\n\t// their own configs below.\n\tconst look = options.look ?? DEFAULT_LOOK;\n\tconst preset = LOOK_PRESETS[look];\n\n\treturn {\n\t\tsceneScale: scale,\n\t\tlook,\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\t// The look sets ambient (low on studio/showcase, where the hemisphere fill carries the lift\n\t\t\t// instead; full on technical). Explicit option still wins.\n\t\t\tambientLightIntensity: options.lighting?.ambientLightIntensity ?? preset.ambientIntensity,\n\t\t\tsunlightColor: options.lighting?.sunlightColor || 0xffffff, // Default to white sunlight\n\t\t\t// Direction-aware fill. The look decides whether it's on (a positive hemisphereIntensity is\n\t\t\t// what actually creates the light in setupLighting); an explicit option overrides.\n\t\t\tenableHemisphereLight:\n\t\t\t\toptions.lighting?.enableHemisphereLight ?? preset.hemisphereIntensity > 0,\n\t\t\themisphereSkyColor: options.lighting?.hemisphereSkyColor ?? 0xdfe6ff,\n\t\t\t// A slightly warm ground tint reads as bounced light and keeps fill from desaturating colour.\n\t\t\themisphereGroundColor: options.lighting?.hemisphereGroundColor ?? 0x6b5f52,\n\t\t\themisphereIntensity: options.lighting?.hemisphereIntensity ?? preset.hemisphereIntensity\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\tenvironmentIntensity: options.environment?.environmentIntensity ?? preset.environmentIntensity\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\t// ?? not || so an explicit NoToneMapping (=== 0) is honoured rather than falling through.\n\t\t\ttoneMapping: options.render?.toneMapping ?? preset.toneMapping,\n\t\t\ttoneMappingExposure: options.render?.toneMappingExposure ?? preset.toneMappingExposure,\n\t\t\tpreserveDrawingBuffer: options.render?.preserveDrawingBuffer ?? false,\n\t\t\tambientOcclusion: options.render?.ambientOcclusion ?? preset.ambientOcclusion,\n\t\t\taoIntensity: options.render?.aoIntensity ?? 1,\n\t\t\t// Cap AO buffers at 1× by default — the biggest lever on GTAO cost on high-DPI displays.\n\t\t\taoPixelRatio: options.render?.aoPixelRatio ?? 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. Grid is an independent overlay — a\n\t\t\t// look never toggles it.\n\t\t\tenabled: options.grid?.enabled ?? 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. Edges are an independent overlay — a\n\t\t\t// look never toggles them.\n\t\t\tenabled: options.edges?.enabled ?? 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 * 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\t// Normalize the HDR's IBL contribution so brightness is consistent across HDRs of\n\t\t\t\t// differing exposure, instead of dim-HDR-looks-dim / bright-HDR-blows-out.\n\t\t\t\tscene.environmentIntensity = config.environment.environmentIntensity ?? 1;\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/** The lights created by {@link setupLighting}, handed back so runtime setters can retune them. */\ntype SceneLights = {\n\tambient: THREE.AmbientLight;\n\t/** Hemisphere fill light — null unless `lighting.enableHemisphereLight`. */\n\themisphere: THREE.HemisphereLight | null;\n\t/**\n\t * Shadow-casting sun. Null when sunlight is disabled or shadows are off — the caller uses it only\n\t * to refit the shadow frustum on geometry change (see `fitShadowToContent`), so null means nothing\n\t * to refit.\n\t */\n\tsun: THREE.DirectionalLight | null;\n};\n\n/**\n * Set up scene lighting. Returns handles to the created lights so the caller can refit the sun's\n * shadow frustum on geometry change and retune fill lights at runtime.\n */\nfunction setupLighting(scene: THREE.Scene, config: Required<ThreeInitializerOptions>): SceneLights {\n\tconst ambient = new THREE.AmbientLight(\n\t\tconfig.lighting.ambientLightColor,\n\t\tconfig.lighting.ambientLightIntensity\n\t);\n\tscene.add(ambient);\n\n\t// Hemisphere fill: soft sky-from-above / ground-from-below light that lifts occluded and\n\t// downward-facing surfaces the HDR may leave dark. Aligned to the scene up so \"sky\" is genuinely\n\t// up in a Z-up scene (a HemisphereLight defaults to +Y up).\n\tlet hemisphere: THREE.HemisphereLight | null = null;\n\tif (config.lighting.enableHemisphereLight) {\n\t\themisphere = new THREE.HemisphereLight(\n\t\t\tconfig.lighting.hemisphereSkyColor,\n\t\t\tconfig.lighting.hemisphereGroundColor,\n\t\t\tconfig.lighting.hemisphereIntensity\n\t\t);\n\t\tconst up = config.environment.sceneUp ?? defaultUp;\n\t\themisphere.position.copy(up);\n\t\tscene.add(hemisphere);\n\t}\n\n\tif (!config.lighting.enableSunlight) return { ambient, hemisphere, sun: 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 { ambient, hemisphere, sun: 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 { ambient, hemisphere, sun: 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';\nimport { Line2 } from 'three/addons/lines/Line2.js';\nimport { LineGeometry } from 'three/addons/lines/LineGeometry.js';\nimport { LineMaterial } from 'three/addons/lines/LineMaterial.js';\n\nimport { getLogger } from '@/core';\n\nimport { rhinoToThree } from '../coordinate-transform';\n\nimport type { DisplayCurve, DisplayItem, DisplayPoint } from './types';\nimport type { RhinoModule } from 'rhino3dm';\n\n/**\n * Builds THREE.js objects from the non-mesh display items on a DisplayBatch — curves (decoded from\n * Rhino-native JSON via rhino3dm and tessellated to a fat `Line2`) and points (raw positions\n * rendered as one {@link THREE.Points}). Mirrors the mesh path's coordinate handling: every position\n * goes through {@link rhinoToThree}, which is the identity — the Three scene IS Rhino's Z-up frame,\n * so items land at their Rhino coordinates, same as meshes (see `../coordinate-transform.ts`).\n *\n * selva-compute does not own the rhino3dm WASM instance (it is heavy and the host app initializes\n * it once); the caller threads it in, same as the response decoder. If no instance is supplied,\n * curves are skipped with a warning and points still render — they need no decode.\n */\n\nconst DEFAULT_COLOR = '#ffffff';\n\n/**\n * Adaptive tessellation parameters. Rather than a fixed segment count, curved spans are recursively\n * split until the midpoint of a span sits within {@link CURVE_CHORD_TOLERANCE_RATIO} of the curve's\n * size from the straight chord — so a span gets points in proportion to how much it actually bends.\n */\n/** Initial uniform splits before adaptive refinement kicks in (ensures closed/looping curves aren't collapsed). */\nconst CURVE_INITIAL_SEGMENTS = 12;\n/** Chord-deviation tolerance as a fraction of the curve's bounding-box diagonal. Smaller = smoother. */\nconst CURVE_CHORD_TOLERANCE_RATIO = 0.0004;\n/** Hard recursion-depth cap per initial span, so pathological curves can't explode the vertex count. */\nconst CURVE_MAX_SUBDIVISION_DEPTH = 12;\n/** Max turn angle (radians) allowed across a span before it's split. ~3° keeps arcs visibly smooth. */\nconst CURVE_MAX_TURN_RADIANS = 0.05;\n\nexport interface DisplayItemParseOptions {\n\t/** rhino3dm instance for decoding curve JSON. Omit to skip curves (points still render). */\n\trhino?: RhinoModule;\n\t/**\n\t * No-op. Historically toggled the Rhino Z-up → Three Y-up rotation, but the pipeline now keeps\n\t * one coordinate frame end to end ({@link rhinoToThree} is the identity), so this flag no longer\n\t * changes the result. Do NOT pre-rotate your own geometry to compensate — none is applied.\n\t *\n\t * @deprecated Retained only so existing call sites compile unchanged; has no effect.\n\t */\n\tapplyTransforms?: boolean;\n}\n\n/**\n * Parse a batch's `items` into renderable THREE objects. Returns an empty array when there are no\n * items. Unknown kinds are skipped with a warning (forward-compatible with future label/icon kinds\n * a viewer hasn't taught itself to render yet).\n */\nexport function parseDisplayItems(\n\titems: DisplayItem[] | undefined,\n\toptions: DisplayItemParseOptions = {}\n): THREE.Object3D[] {\n\tif (!items || items.length === 0) return [];\n\n\tconst { rhino, applyTransforms = true } = options;\n\tconst objects: THREE.Object3D[] = [];\n\n\tfor (const item of items) {\n\t\tswitch (item.kind) {\n\t\t\tcase 'curve': {\n\t\t\t\tconst line = buildCurveLine(item, rhino, applyTransforms);\n\t\t\t\tif (line) objects.push(line);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'point': {\n\t\t\t\tconst point = buildPoint(item, applyTransforms);\n\t\t\t\tif (point) objects.push(point);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault: {\n\t\t\t\t// Exhaustiveness guard: assigning to `never` makes a new kind added to the union\n\t\t\t\t// without a case here a compile error. At runtime (plain-JS callers, newer\n\t\t\t\t// producers) an unrecognized kind still reaches this branch and is skipped.\n\t\t\t\tconst unhandled: never = item;\n\t\t\t\tconst unknown = unhandled as { kind?: string };\n\t\t\t\tgetLogger().warn(`Skipping unknown display item kind: ${String(unknown.kind)}`);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn objects;\n}\n\n/** Default fat-line thickness (CSS px) when a curve carries no explicit {@link DisplayCurve.width}. */\nconst DEFAULT_LINE_WIDTH = 2;\n\n/**\n * Decode a curve's Rhino JSON and tessellate it to a fat `Line2`. Returns null if rhino3dm is absent\n * or decoding fails, so one bad curve never aborts the whole batch.\n *\n * Uses `Line2`/`LineMaterial` rather than `THREE.Line` so thickness (`item.width`) is actually\n * honoured — plain `THREE.Line` is hard-capped at 1px on every major GPU backend. `LineMaterial`\n * needs its `resolution` set to the drawing-buffer size, but `Line2.onBeforeRender` does that\n * automatically from the renderer each frame, so the parser needs no renderer reference.\n */\nfunction buildCurveLine(\n\titem: DisplayCurve,\n\trhino: RhinoModule | undefined,\n\tapplyTransforms: boolean\n): Line2 | null {\n\tif (!rhino) {\n\t\tgetLogger().warn('No rhino3dm instance provided; skipping curve display item.');\n\t\treturn null;\n\t}\n\n\tconst curve = decodeCurve(item.json, rhino);\n\tif (!curve) return null;\n\n\tlet points: THREE.Vector3[];\n\ttry {\n\t\tpoints = tessellate(curve, applyTransforms);\n\t} catch (error) {\n\t\t// WASM calls (pointAt / tryGetPolyline / getBoundingBox) can throw on malformed geometry.\n\t\t// Log and skip this curve so one bad item never aborts the whole batch (contract above).\n\t\tgetLogger().warn('Failed to tessellate curve display item; skipping.', error);\n\t\treturn null;\n\t} finally {\n\t\tdeleteRhinoObject(curve);\n\t}\n\tif (points.length < 2) return null;\n\n\tconst positions: number[] = [];\n\tfor (const p of points) positions.push(p.x, p.y, p.z);\n\n\tconst geometry = new LineGeometry();\n\tgeometry.setPositions(positions);\n\n\t// @types/three's LineMaterial omits `linewidth` (and doesn't surface `transparent`/`opacity`\n\t// through its chain) though all exist at runtime. Set them via a narrow typed view rather than\n\t// scattering casts.\n\tconst params = materialParams(item.color, item.opacity);\n\tconst material = new LineMaterial({ color: params.color });\n\tconst styled = material as LineMaterial & {\n\t\tlinewidth: number;\n\t\ttransparent: boolean;\n\t\topacity: number;\n\t};\n\tstyled.linewidth = item.width ?? DEFAULT_LINE_WIDTH; // CSS px (worldUnits defaults false)\n\tstyled.transparent = params.transparent;\n\tstyled.opacity = params.opacity;\n\n\tconst line = new Line2(geometry, material);\n\tline.computeLineDistances(); // required for any future dashed styling; cheap\n\tline.name = item.name;\n\tline.userData = {\n\t\tsource: 'compute',\n\t\tid: item.id,\n\t\tlayer: item.layer,\n\t\tkind: 'curve',\n\t\tmetadata: item.metadata\n\t};\n\treturn line;\n}\n\n/**\n * Render a single point as a one-vertex THREE.Points. Returns null (with a warning) when the item's\n * position is missing or non-finite — display items arrive as network JSON, so a malformed point\n * must be skipped rather than throwing or pushing NaN into the buffer (a NaN vertex poisons the\n * bounding sphere and can break camera fit-to-view for the whole scene).\n */\nfunction buildPoint(item: DisplayPoint, applyTransforms: boolean): THREE.Points | null {\n\t// Validate before trusting the declared type: `position` comes off the wire.\n\tconst { position } = item as { position?: { X?: unknown; Y?: unknown; Z?: unknown } };\n\tif (\n\t\t!position ||\n\t\ttypeof position.X !== 'number' ||\n\t\t!Number.isFinite(position.X) ||\n\t\ttypeof position.Y !== 'number' ||\n\t\t!Number.isFinite(position.Y) ||\n\t\ttypeof position.Z !== 'number' ||\n\t\t!Number.isFinite(position.Z)\n\t) {\n\t\tgetLogger().warn(\n\t\t\t`Skipping point display item with missing or non-finite position (id: ${String(item.id)}).`\n\t\t);\n\t\treturn null;\n\t}\n\n\tconst { x, y, z } = rhinoToThree(position.X, position.Y, position.Z, applyTransforms);\n\n\tconst geometry = new THREE.BufferGeometry();\n\tgeometry.setAttribute('position', new THREE.Float32BufferAttribute([x, y, z], 3));\n\n\tconst material = new THREE.PointsMaterial({\n\t\t...materialParams(item.color, item.opacity),\n\t\tsize: 6,\n\t\tsizeAttenuation: false\n\t});\n\n\tconst points = new THREE.Points(geometry, material);\n\tpoints.name = item.name;\n\tpoints.userData = {\n\t\tsource: 'compute',\n\t\tid: item.id,\n\t\tlayer: item.layer,\n\t\tkind: 'point',\n\t\tmetadata: item.metadata\n\t};\n\treturn points;\n}\n\n/**\n * Free a rhino3dm object's WASM-heap memory. rhino3dm objects are emscripten bindings — JS GC\n * never reclaims their heap allocation, so everything decoded during a solve must be deleted\n * explicitly or the WASM heap grows monotonically across solves.\n */\nfunction deleteRhinoObject(obj: unknown): void {\n\t(obj as { delete?: () => void } | null | undefined)?.delete?.();\n}\n\n/** Decode Rhino CommonObject JSON into a rhino3dm Curve (or null on failure). */\nfunction decodeCurve(json: string, rhino: RhinoModule): InstanceType<RhinoModule['Curve']> | null {\n\ttry {\n\t\tconst parsed = JSON.parse(json);\n\t\tconst obj = rhino.CommonObject.decode(parsed);\n\t\t// decode returns a CommonObject; only curves carry domain/pointAt. Treat anything else as a miss.\n\t\tif (obj && typeof (obj as { pointAt?: unknown }).pointAt === 'function') {\n\t\t\treturn obj as InstanceType<RhinoModule['Curve']>;\n\t\t}\n\t\tdeleteRhinoObject(obj);\n\t\tgetLogger().warn('Decoded display-item JSON is not a curve; skipping.');\n\t\treturn null;\n\t} catch (error) {\n\t\tgetLogger().warn('Failed to decode curve display item JSON:', error);\n\t\treturn null;\n\t}\n}\n\n/**\n * Tessellate a curve to THREE points (passed through the shared — identity — coordinate mapping).\n *\n * Most curves Grasshopper emits are linear — a line is 2 vertices, a polyline is N+1 — yet uniform\n * sampling would inflate every one to {@link CURVE_INITIAL_SEGMENTS}+1 points. So we first ask\n * rhino3dm if the curve *is* a polyline (covers lines, polylines, and degree-1 nurbs/polycurves) and\n * emit its exact vertices when so. Only genuinely curved geometry (arcs, nurbs, polycurves with\n * curved spans) falls through to {@link sampleUniform}.\n */\nfunction tessellate(\n\tcurve: InstanceType<RhinoModule['Curve']>,\n\tapplyTransforms: boolean\n): THREE.Vector3[] {\n\tconst exact = tryPolylineVertices(curve, applyTransforms);\n\tif (exact) return exact;\n\n\treturn sampleUniform(curve, applyTransforms);\n}\n\n/** Minimal shape we use off a rhino3dm Polyline (a Point3dList). */\ninterface PolylineLike {\n\tcount: number;\n\tget(index: number): number[];\n}\n\n/**\n * If the curve has an exact polyline form, return its vertices; otherwise null. `tryGetPolyline`\n * returns `[ok, Polyline]`; the Polyline is a Point3dList (`count` + `get(i) → [x,y,z]`).\n */\nfunction tryPolylineVertices(\n\tcurve: InstanceType<RhinoModule['Curve']>,\n\tapplyTransforms: boolean\n): THREE.Vector3[] | null {\n\tif (!curve.isPolyline()) return null;\n\n\t// rhino3dm's WASM `tryGetPolyline` returns the Polyline directly (not the documented\n\t// `[ok, Polyline]` tuple). Accept either: unwrap a tuple if we got one, else use it as-is.\n\tconst result = curve.tryGetPolyline() as unknown;\n\tconst polyline = (Array.isArray(result) ? result[1] : result) as PolylineLike | null;\n\tif (!polyline || typeof polyline.count !== 'number' || polyline.count < 2) {\n\t\tdeleteRhinoObject(polyline);\n\t\treturn null;\n\t}\n\n\tconst out: THREE.Vector3[] = [];\n\tfor (let i = 0; i < polyline.count; i++) {\n\t\tconst p = polyline.get(i); // [x, y, z] in Rhino Z-up\n\t\tconst { x, y, z } = rhinoToThree(p[0], p[1], p[2], applyTransforms);\n\t\tout.push(new THREE.Vector3(x, y, z));\n\t}\n\n\tdeleteRhinoObject(polyline);\n\treturn out;\n}\n\n/**\n * Adaptively sample a curve across its domain via `pointAt`. Robust for any curved type (arc, nurbs,\n * polycurve). Instead of a fixed segment count, we start from {@link CURVE_INITIAL_SEGMENTS} uniform\n * spans and recursively subdivide each only where it actually bends — a span is split when its\n * parameter-midpoint deviates from the straight chord by more than a tolerance derived from the\n * curve's bounding-box diagonal. Result: smooth on tight bends, sparse on near-straight runs, and\n * scale-independent (a tiny fillet and a huge arc both hit the same *visual* smoothness).\n */\nfunction sampleUniform(\n\tcurve: InstanceType<RhinoModule['Curve']>,\n\tapplyTransforms: boolean\n): THREE.Vector3[] {\n\tconst domain = curve.domain;\n\tconst t0 = domain[0];\n\tconst t1 = domain[1];\n\tconst span = t1 - t0;\n\n\tconst evalAt = (t: number): THREE.Vector3 => {\n\t\tconst p = curve.pointAt(t); // [x, y, z] in Rhino Z-up\n\t\tconst { x, y, z } = rhinoToThree(p[0], p[1], p[2], applyTransforms);\n\t\treturn new THREE.Vector3(x, y, z);\n\t};\n\n\tconst tolerance = chordTolerance(curve);\n\n\t// Evaluate each segment boundary once and carry it forward as the next `pa`,\n\t// instead of re-evaluating ta/tb (3 pointAt calls per segment → 1).\n\tlet ta = t0;\n\tlet pa = evalAt(t0);\n\tconst out: THREE.Vector3[] = [pa];\n\tfor (let i = 0; i < CURVE_INITIAL_SEGMENTS; i++) {\n\t\tconst tb = t0 + (span * (i + 1)) / CURVE_INITIAL_SEGMENTS;\n\t\tconst pb = evalAt(tb);\n\t\tsubdivide(ta, pa, tb, pb, evalAt, tolerance, CURVE_MAX_SUBDIVISION_DEPTH, out);\n\t\tout.push(pb);\n\t\tta = tb;\n\t\tpa = pb;\n\t}\n\n\treturn out;\n}\n\n/**\n * Recursively refine the span [ta, tb]. If the curve point at the parameter-midpoint lies farther\n * than `tolerance` from the chord pa→pb, split and recurse on both halves; otherwise the chord is a\n * good-enough approximation and nothing is added. Pushes interior points (excluding endpoints — the\n * caller owns those) into `out` in parameter order.\n */\nfunction subdivide(\n\tta: number,\n\tpa: THREE.Vector3,\n\ttb: number,\n\tpb: THREE.Vector3,\n\tevalAt: (t: number) => THREE.Vector3,\n\ttolerance: number,\n\tdepth: number,\n\tout: THREE.Vector3[]\n): void {\n\tif (depth <= 0) return;\n\n\tconst tm = (ta + tb) / 2;\n\tconst pm = evalAt(tm);\n\n\t// Subdivide on chord deviation OR on the turn angle at the midpoint. A pure deviation test can\n\t// pass a long, gently-curving span whose endpoints straddle the chord symmetrically; the angle\n\t// test catches the visible kink at span joints that deviation alone misses.\n\tconst deviation = distanceToSegment(pm, pa, pb);\n\tconst turn = turnAngle(pa, pm, pb);\n\tif (deviation <= tolerance && turn <= CURVE_MAX_TURN_RADIANS) return;\n\n\tsubdivide(ta, pa, tm, pm, evalAt, tolerance, depth - 1, out);\n\tout.push(pm);\n\tsubdivide(tm, pm, tb, pb, evalAt, tolerance, depth - 1, out);\n}\n\n/** Tolerance in world units: a fraction of the curve's bounding-box diagonal, with a tiny floor. */\nfunction chordTolerance(curve: InstanceType<RhinoModule['Curve']>): number {\n\t// rhino3dm WASM's getBoundingBox takes no args at runtime despite the .d.ts signature.\n\tconst box = (\n\t\tcurve as unknown as { getBoundingBox(): InstanceType<RhinoModule['BoundingBox']> }\n\t).getBoundingBox();\n\tconst min = box.min;\n\tconst max = box.max;\n\tdeleteRhinoObject(box);\n\tconst diagonal = Math.hypot(max[0] - min[0], max[1] - min[1], max[2] - min[2]);\n\treturn Math.max(diagonal * CURVE_CHORD_TOLERANCE_RATIO, 1e-6);\n}\n\n/**\n * Angle (radians) of the turn at `b` along the path a→b→c. 0 = straight, π = full reversal.\n *\n * Scalar math on purpose: this runs once per subdivision test inside a recursion that can evaluate\n * ~2^12 spans per curve, so `Vector3.clone()` temporaries here caused measurable GC churn (and\n * module-scope scratch vectors would be unsafe across the recursive calls).\n */\nfunction turnAngle(a: THREE.Vector3, b: THREE.Vector3, c: THREE.Vector3): number {\n\tconst abx = b.x - a.x;\n\tconst aby = b.y - a.y;\n\tconst abz = b.z - a.z;\n\tconst bcx = c.x - b.x;\n\tconst bcy = c.y - b.y;\n\tconst bcz = c.z - b.z;\n\n\tconst lenAb = Math.sqrt(abx * abx + aby * aby + abz * abz);\n\tconst lenBc = Math.sqrt(bcx * bcx + bcy * bcy + bcz * bcz);\n\tif (lenAb === 0 || lenBc === 0) return 0;\n\n\tconst dot = abx * bcx + aby * bcy + abz * bcz;\n\tconst cos = Math.max(-1, Math.min(1, dot / (lenAb * lenBc)));\n\treturn Math.acos(cos);\n}\n\n/**\n * Perpendicular distance from point `p` to the segment a→b (clamped to the segment endpoints).\n * Scalar math for the same allocation-churn reason as {@link turnAngle}.\n */\nfunction distanceToSegment(p: THREE.Vector3, a: THREE.Vector3, b: THREE.Vector3): number {\n\tconst abx = b.x - a.x;\n\tconst aby = b.y - a.y;\n\tconst abz = b.z - a.z;\n\tconst lengthSq = abx * abx + aby * aby + abz * abz;\n\tif (lengthSq === 0) return p.distanceTo(a);\n\n\tconst apx = p.x - a.x;\n\tconst apy = p.y - a.y;\n\tconst apz = p.z - a.z;\n\tconst t = Math.max(0, Math.min(1, (apx * abx + apy * aby + apz * abz) / lengthSq));\n\n\tconst dx = apx - abx * t;\n\tconst dy = apy - aby * t;\n\tconst dz = apz - abz * t;\n\treturn Math.sqrt(dx * dx + dy * dy + dz * dz);\n}\n\n/** Shared color/opacity → THREE material params. Opacity < 1 flips `transparent` on. */\nfunction materialParams(\n\tcolor: string | undefined,\n\topacity: number | undefined\n): { color: THREE.Color; transparent: boolean; opacity: number } {\n\tconst resolved = opacity ?? 1;\n\treturn {\n\t\tcolor: new THREE.Color(color ?? DEFAULT_COLOR),\n\t\ttransparent: resolved < 1,\n\t\topacity: resolved\n\t};\n}\n","/** Rhino and Three use the same Z-up coordinate frame (identity transform). */\n\n/** A point in either frame (the frames are now identical). */\nexport interface Vec3 {\n\tx: number;\n\ty: number;\n\tz: number;\n}\n\n/** Identity transform (both frames Z-up). Deprecated; use coordinates directly. */\nexport function rhinoToThree(x: number, y: number, z: number, _apply = true): Vec3 {\n\treturn { x, y, z };\n}\n","import { inflateSync } from 'fflate';\n\nimport { decodeBase64ToBinary } from '@/core/utils/encoding';\nimport { RhinoComputeError, ErrorCodes } from '@/core/errors';\n\nimport type { MaterialGroup, SerializableMaterial } from './types.js';\n\n// ============================================================================\n// WIRE FORMAT CONSTANTS\n// ============================================================================\n\n/** \"SLVA\" little-endian — an uncompressed mesh blob. */\nexport const BINARY_MESH_MAGIC = 0x41564c53;\n/**\n * \"SLVZ\" little-endian — a gzip (raw DEFLATE) container around a SLVA blob. The plugin applies this\n * optionally when it shrinks the payload (the wire is otherwise uncompressed). Layout:\n * [4] magic = SLVZ, [4] uncompressedLen (uint32), [N] raw-deflate stream of the SLVA blob.\n */\nexport const COMPRESSED_MESH_MAGIC = 0x5a564c53;\n/**\n * Current writer version. v2 added the uint16-index flag (FLAG_UINT16_INDICES); v3 added the\n * delta+zigzag filter flag (FLAG_DELTA_ENCODED).\n */\nexport const BINARY_MESH_VERSION = 3;\n/**\n * Oldest wire version this parser still decodes. Each version only added a flag bit — v1 always\n * used uint32 indices, v2 introduced uint16 indices, v3 the delta filter — so the flag-driven read\n * path handles every older blob unchanged. Accepting them keeps persisted/cached blobs (saved `.gh`\n * files, DMF files, cached compute results) decodable after upgrade.\n */\nexport const MIN_SUPPORTED_VERSION = 1;\n/** Bit 0 of the geometry flags word: 0 = int16 quantized, 1 = float32 raw. */\nexport const FLAG_FLOAT32 = 0x1;\n/** Bit 1 of the geometry flags word: 0 = uint32 indices, 1 = uint16 indices. */\nexport const FLAG_UINT16_INDICES = 0x2;\n/**\n * Bit 2 of the geometry flags word: int16 vertex components and the index stream are stored as\n * wrapped per-component deltas from their predecessor, zigzag-mapped to unsigned (float32 vertices\n * are never filtered). Deltas of welded meshes concentrate near zero, which makes the SLVZ DEFLATE\n * pass compress far better. Decoding reverses the filter with a running prefix sum.\n */\nexport const FLAG_DELTA_ENCODED = 0x4;\n/**\n * Bit 3 of the geometry flags word: a UV chunk trails the index block. Layout:\n * `uvFormat(u32: 0 = uint16 quantized, 1 = float32) | uvOrigin(2×f64) | uvScale(2×f64) | data`,\n * with the element count implied by vertexCount. Quantized UVs reconstruct as\n * `uv = origin + q * scale` (q unsigned in [0, 65535]) and are delta+zigzag filtered per component\n * (independent u/v predictors) iff FLAG_DELTA_ENCODED; float32 UVs are never filtered. Absent flag\n * = absent chunk, so untextured blobs are byte-identical to pre-chunk writers.\n */\nexport const FLAG_HAS_UVS = 0x8;\n/**\n * Bit 4 of the geometry flags word: a vertex-color chunk trails the index block (after the UV\n * chunk when both are present). Layout: `uint8 rgb[vertexCount*3]`, delta+zigzag filtered per\n * channel (wrapped 8-bit, independent r/g/b predictors) iff FLAG_DELTA_ENCODED.\n */\nexport const FLAG_HAS_VERTEX_COLORS = 0x10;\n\n/** uvFormat value inside the UV chunk: uint16 quantized. */\nexport const UV_FORMAT_UINT16 = 0;\n/** uvFormat value inside the UV chunk: raw float32. */\nexport const UV_FORMAT_FLOAT32 = 1;\n\nconst HEADER_PREAMBLE_BYTES = 4 /* magic */ + 4 /* version */ + 4; /* metadataLen */\nconst GEOMETRY_HEADER_BYTES =\n\t4 /* flags */ + 24 /* origin (3 x f64) */ + 24 /* scale (3 x f64) */ + 4; /* vertexCount */\n\n/**\n * The SLVA wire format is little-endian. Header fields use explicit-LE `DataView` reads, but the\n * zero-copy geometry readers below construct typed-array views in *host* byte order — a deliberate\n * trade: rewriting the hot geometry paths onto per-element DataView reads would cost far more than\n * it buys, since every mainstream JS target (x86, ARM, WASM) is little-endian. This one-time check\n * makes the assumption explicit: on a big-endian host the parser refuses to decode rather than\n * silently returning byte-swapped garbage.\n */\nconst HOST_IS_LITTLE_ENDIAN = new Uint16Array(new Uint8Array([1, 0]).buffer)[0] === 1;\n\n// ============================================================================\n// PARSED TYPES\n// ============================================================================\n\n/**\n * Metadata JSON embedded inside the binary blob.\n *\n * This is the mesh-blob subset of a `DisplayBatch` minus the `compressedData` field (the blob is\n * opaque to its own metadata header). Kept separate from the public `DisplayBatch` type because the\n * blob's metadata never carries `compressedData` itself — it would be circular.\n */\nexport interface BinaryMeshMetadata {\n\tmaterials: SerializableMaterial[];\n\tgroups: MaterialGroup[];\n\tsourceComponentId?: string;\n}\n\n/**\n * Result of parsing a binary mesh blob.\n *\n * `vertices` and `indices` hold absolute (unfiltered) values. For pre-v3 blobs they are typed-array\n * views over the original `ArrayBuffer` — zero copies; the consumer is responsible for not mutating\n * the underlying buffer if it cares about safety, or for calling `.slice()` to detach. Delta-encoded\n * blobs (FLAG_DELTA_ENCODED) decode into freshly allocated arrays instead.\n *\n * `uvs` / `colors` are the optional trailing chunks (FLAG_HAS_UVS / FLAG_HAS_VERTEX_COLORS), null\n * when the blob doesn't carry them. UVs are returned dequantized to absolute Float32 values (u,v\n * per vertex), so consumers can hand them straight to a `BufferAttribute(uvs, 2)`. Colors are raw\n * r,g,b bytes per vertex for a normalized `BufferAttribute(colors, 3, true)`.\n */\nexport interface ParsedBinaryMeshBatch {\n\tmetadata: BinaryMeshMetadata;\n\tflags: number;\n\tvertices: Int16Array | Float32Array;\n\tindices: Uint16Array | Uint32Array;\n\torigin: [number, number, number];\n\tscale: [number, number, number];\n\tuvs: Float32Array | null;\n\tcolors: Uint8Array | null;\n}\n\n// ============================================================================\n// PARSER\n// ============================================================================\n\n/**\n * Parses a binary mesh batch blob in the SLVA wire format.\n *\n * The blob layout is:\n * ```\n * [4] magic = \"SLVA\" (0x53 0x4C 0x56 0x41)\n * [4] version = uint32 (currently 3)\n * [4] metadataLen = uint32 byte length of UTF-8 metadata JSON\n * [N] metadata = UTF-8 JSON (materials, groups, sourceComponentId, ...)\n * [4] flags = uint32 (bit 0: 0 = int16 quantized, 1 = float32 raw;\n * bit 1: 0 = uint32 indices, 1 = uint16 indices;\n * bit 2: 1 = delta+zigzag filtered)\n * [24] origin = 3 x float64\n * [24] scale = 3 x float64 (step per int16 unit; identity for float32)\n * [4] vertexCount = uint32 number of vertices (positions = vertexCount * 3 components)\n * [V] vertices = int16[vertexCount*3] OR float32[vertexCount*3]\n * [4] indexCount = uint32 number of indices\n * [I] indices = uint32[indexCount] OR uint16[indexCount]\n * ```\n *\n * For int16 vertices: world position = `origin + (q + 32767) * scale`. This matches Three.js\n * `BufferAttribute(arr, 3, true)` (`normalized: true`) semantics when the per-mesh transform\n * encodes `origin + scale`.\n *\n * For float32: `origin = (0, 0, 0)`, `scale = (1, 1, 1)`, vertices are raw world positions.\n *\n * With FLAG_DELTA_ENCODED (v3), the stored int16 vertex components and indices are wrapped\n * differences from their predecessor, zigzag-mapped — see the flag's doc. The parser returns the\n * reconstructed absolute values, so consumers never see the filter.\n *\n * @param input - The blob, as either an `ArrayBuffer`/`Uint8Array` (binary transport) or a\n * base64-encoded string (today's JSON-envelope transport).\n * @returns Decoded metadata plus typed-array views into the geometry payload.\n * @throws {RhinoComputeError} On invalid magic, unknown version, or truncated input.\n */\nexport function parseBinaryMeshBatch(\n\tinput: ArrayBuffer | Uint8Array | string\n): ParsedBinaryMeshBatch {\n\tif (!HOST_IS_LITTLE_ENDIAN) {\n\t\tthrow new RhinoComputeError(\n\t\t\t'SLVA parsing requires a little-endian host: the zero-copy geometry readers view the wire bytes in host byte order.',\n\t\t\tErrorCodes.ENVIRONMENT_ERROR\n\t\t);\n\t}\n\n\tconst bytes = maybeDecompress(toUint8Array(input));\n\tconst view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n\n\tif (bytes.byteLength < HEADER_PREAMBLE_BYTES) {\n\t\tthrow fail('Blob too small to contain SLVA header.', {\n\t\t\texpectedBytes: HEADER_PREAMBLE_BYTES,\n\t\t\tavailableBytes: bytes.byteLength\n\t\t});\n\t}\n\n\tlet offset = 0;\n\n\tconst magic = view.getUint32(offset, true);\n\toffset += 4;\n\tif (magic !== BINARY_MESH_MAGIC) {\n\t\tthrow fail(`Invalid SLVA magic: 0x${magic.toString(16)}`, {\n\t\t\texpectedMagic: `0x${BINARY_MESH_MAGIC.toString(16)}`,\n\t\t\tactualMagic: `0x${magic.toString(16)}`\n\t\t});\n\t}\n\n\tconst version = view.getUint32(offset, true);\n\toffset += 4;\n\tif (version < MIN_SUPPORTED_VERSION || version > BINARY_MESH_VERSION) {\n\t\tthrow fail(`Unsupported SLVA version: ${version}`, {\n\t\t\tminSupportedVersion: MIN_SUPPORTED_VERSION,\n\t\t\tmaxSupportedVersion: BINARY_MESH_VERSION,\n\t\t\tactualVersion: version\n\t\t});\n\t}\n\n\tconst metadataLen = view.getUint32(offset, true);\n\toffset += 4;\n\tif (offset + metadataLen > bytes.byteLength) {\n\t\tthrow fail('Insufficient data to read metadata JSON.', {\n\t\t\texpectedBytes: metadataLen,\n\t\t\tavailableBytes: bytes.byteLength - offset,\n\t\t\toffset\n\t\t});\n\t}\n\n\tconst metadataBytes = bytes.subarray(offset, offset + metadataLen);\n\toffset += metadataLen;\n\n\tlet metadata: BinaryMeshMetadata;\n\ttry {\n\t\tmetadata = JSON.parse(decodeUtf8(metadataBytes)) as BinaryMeshMetadata;\n\t} catch (error) {\n\t\tthrow fail(\n\t\t\t`Failed to parse metadata JSON: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t{ metadataLen }\n\t\t);\n\t}\n\n\tif (offset + GEOMETRY_HEADER_BYTES > bytes.byteLength) {\n\t\tthrow fail('Insufficient data to read geometry header.', {\n\t\t\texpectedBytes: GEOMETRY_HEADER_BYTES,\n\t\t\tavailableBytes: bytes.byteLength - offset,\n\t\t\toffset\n\t\t});\n\t}\n\n\tconst flags = view.getUint32(offset, true);\n\toffset += 4;\n\n\tconst originX = view.getFloat64(offset, true);\n\toffset += 8;\n\tconst originY = view.getFloat64(offset, true);\n\toffset += 8;\n\tconst originZ = view.getFloat64(offset, true);\n\toffset += 8;\n\n\tconst scaleX = view.getFloat64(offset, true);\n\toffset += 8;\n\tconst scaleY = view.getFloat64(offset, true);\n\toffset += 8;\n\tconst scaleZ = view.getFloat64(offset, true);\n\toffset += 8;\n\n\tconst vertexCount = view.getUint32(offset, true);\n\toffset += 4;\n\n\tconst useFloat32 = (flags & FLAG_FLOAT32) !== 0;\n\tconst deltaEncoded = (flags & FLAG_DELTA_ENCODED) !== 0;\n\tconst componentCount = vertexCount * 3;\n\tconst bytesPerComponent = useFloat32 ? 4 : 2;\n\tconst verticesByteLength = componentCount * bytesPerComponent;\n\n\tif (offset + verticesByteLength > bytes.byteLength) {\n\t\tthrow fail('Insufficient data to read vertices.', {\n\t\t\texpectedBytes: verticesByteLength,\n\t\t\tavailableBytes: bytes.byteLength - offset,\n\t\t\toffset,\n\t\t\tuseFloat32,\n\t\t\tvertexCount\n\t\t});\n\t}\n\n\t// Typed-array views require alignment to the element size. The header lays out the geometry\n\t// block such that the vertex byte offset is always 4-aligned (preamble 12 + metadataLen + 4 +\n\t// 48 + 4). float32 needs 4-byte alignment (satisfied), int16 needs 2-byte alignment\n\t// (satisfied). We can take a zero-copy view as long as `bytes.byteOffset + offset` agrees with\n\t// that alignment in the underlying buffer — a wrapper Uint8Array could violate it. Fall back\n\t// to a fresh copy if so.\n\tconst absoluteOffset = bytes.byteOffset + offset;\n\tlet verticesView: Int16Array | Float32Array;\n\tif (useFloat32) {\n\t\tverticesView = readFloat32Vertices(bytes.buffer, absoluteOffset, componentCount);\n\t} else if (deltaEncoded) {\n\t\t// The raw stream holds zigzag-mapped deltas (unsigned); prefix-sum into absolute int16.\n\t\tverticesView = decodeDeltaVertices(\n\t\t\treadUint16Array(bytes.buffer, absoluteOffset, componentCount)\n\t\t);\n\t} else {\n\t\tverticesView = readInt16Vertices(bytes.buffer, absoluteOffset, componentCount);\n\t}\n\toffset += verticesByteLength;\n\n\tif (offset + 4 > bytes.byteLength) {\n\t\tthrow fail('Insufficient data to read index count.', {\n\t\t\texpectedBytes: 4,\n\t\t\tavailableBytes: bytes.byteLength - offset,\n\t\t\toffset\n\t\t});\n\t}\n\tconst indexCount = view.getUint32(offset, true);\n\toffset += 4;\n\n\tconst useUint16Indices = (flags & FLAG_UINT16_INDICES) !== 0;\n\tconst bytesPerIndex = useUint16Indices ? 2 : 4;\n\tconst indicesByteLength = indexCount * bytesPerIndex;\n\tif (offset + indicesByteLength > bytes.byteLength) {\n\t\tthrow fail('Insufficient data to read indices.', {\n\t\t\texpectedBytes: indicesByteLength,\n\t\t\tavailableBytes: bytes.byteLength - offset,\n\t\t\toffset,\n\t\t\tindexCount,\n\t\t\tuseUint16Indices\n\t\t});\n\t}\n\n\tlet indicesView = useUint16Indices\n\t\t? readUint16Array(bytes.buffer, bytes.byteOffset + offset, indexCount)\n\t\t: readUint32Array(bytes.buffer, bytes.byteOffset + offset, indexCount);\n\tif (deltaEncoded) {\n\t\tindicesView =\n\t\t\tindicesView instanceof Uint16Array\n\t\t\t\t? decodeDeltaIndices16(indicesView)\n\t\t\t\t: decodeDeltaIndices32(indicesView);\n\t}\n\tvalidateIndicesInRange(indicesView, vertexCount);\n\toffset += indicesByteLength;\n\n\t// Optional trailing chunks (UV first, then colors). Blobs from pre-chunk writers simply end\n\t// here; the flags gate every read, so nothing is consumed when the chunks are absent.\n\tlet uvs: Float32Array | null = null;\n\tif ((flags & FLAG_HAS_UVS) !== 0) {\n\t\tconst parsed = parseUvChunk(bytes, view, offset, vertexCount, deltaEncoded);\n\t\tuvs = parsed.uvs;\n\t\toffset = parsed.offset;\n\t}\n\n\tlet colors: Uint8Array | null = null;\n\tif ((flags & FLAG_HAS_VERTEX_COLORS) !== 0) {\n\t\tcolors = parseColorChunk(bytes, offset, vertexCount, deltaEncoded);\n\t}\n\n\treturn {\n\t\tmetadata,\n\t\tflags,\n\t\tvertices: verticesView,\n\t\tindices: indicesView,\n\t\torigin: [originX, originY, originZ],\n\t\tscale: [scaleX, scaleY, scaleZ],\n\t\tuvs,\n\t\tcolors\n\t};\n}\n\n/** Byte size of the UV chunk header: uvFormat(u32) + uvOrigin(2×f64) + uvScale(2×f64). */\nconst UV_CHUNK_HEADER_BYTES = 4 + 16 + 16;\n\n/**\n * Parses the trailing UV chunk into absolute Float32 u,v pairs. Quantized UVs reconstruct as\n * `origin + q * scale` with an unsigned q, undoing the per-component delta+zigzag filter when the\n * blob-wide delta flag is set; float32 UVs are copied out as-is (never filtered).\n */\nfunction parseUvChunk(\n\tbytes: Uint8Array,\n\tview: DataView,\n\toffset: number,\n\tvertexCount: number,\n\tdeltaEncoded: boolean\n): { uvs: Float32Array; offset: number } {\n\tif (offset + UV_CHUNK_HEADER_BYTES > bytes.byteLength) {\n\t\tthrow fail('Insufficient data to read UV chunk header.', {\n\t\t\texpectedBytes: UV_CHUNK_HEADER_BYTES,\n\t\t\tavailableBytes: bytes.byteLength - offset,\n\t\t\toffset\n\t\t});\n\t}\n\n\tconst uvFormat = view.getUint32(offset, true);\n\toffset += 4;\n\tconst originU = view.getFloat64(offset, true);\n\toffset += 8;\n\tconst originV = view.getFloat64(offset, true);\n\toffset += 8;\n\tconst scaleU = view.getFloat64(offset, true);\n\toffset += 8;\n\tconst scaleV = view.getFloat64(offset, true);\n\toffset += 8;\n\n\tconst componentCount = vertexCount * 2;\n\tconst useFloat32 = uvFormat === UV_FORMAT_FLOAT32;\n\tconst dataByteLength = componentCount * (useFloat32 ? 4 : 2);\n\tif (offset + dataByteLength > bytes.byteLength) {\n\t\tthrow fail('Insufficient data to read UV chunk.', {\n\t\t\texpectedBytes: dataByteLength,\n\t\t\tavailableBytes: bytes.byteLength - offset,\n\t\t\toffset,\n\t\t\tuvFormat,\n\t\t\tvertexCount\n\t\t});\n\t}\n\n\tconst absoluteOffset = bytes.byteOffset + offset;\n\tlet uvs: Float32Array;\n\tif (useFloat32) {\n\t\t// Copy (not view) so the attribute owns its memory like the quantized path.\n\t\tuvs = readFloat32Vertices(bytes.buffer, absoluteOffset, componentCount).slice();\n\t} else {\n\t\tconst raw = readUint16Array(bytes.buffer, absoluteOffset, componentCount);\n\t\tuvs = new Float32Array(componentCount);\n\t\tlet qu = 0;\n\t\tlet qv = 0;\n\t\tfor (let i = 0; i < componentCount; i += 2) {\n\t\t\tif (deltaEncoded) {\n\t\t\t\tqu = (qu + unzigzag(raw[i]!)) & 0xffff;\n\t\t\t\tqv = (qv + unzigzag(raw[i + 1]!)) & 0xffff;\n\t\t\t} else {\n\t\t\t\tqu = raw[i]!;\n\t\t\t\tqv = raw[i + 1]!;\n\t\t\t}\n\t\t\tuvs[i] = originU + qu * scaleU;\n\t\t\tuvs[i + 1] = originV + qv * scaleV;\n\t\t}\n\t}\n\n\treturn { uvs, offset: offset + dataByteLength };\n}\n\n/**\n * Parses the trailing vertex-color chunk into raw r,g,b bytes, undoing the per-channel wrapped\n * 8-bit delta+zigzag filter when the blob-wide delta flag is set.\n */\nfunction parseColorChunk(\n\tbytes: Uint8Array,\n\toffset: number,\n\tvertexCount: number,\n\tdeltaEncoded: boolean\n): Uint8Array {\n\tconst byteLength = vertexCount * 3;\n\tif (offset + byteLength > bytes.byteLength) {\n\t\tthrow fail('Insufficient data to read vertex-color chunk.', {\n\t\t\texpectedBytes: byteLength,\n\t\t\tavailableBytes: bytes.byteLength - offset,\n\t\t\toffset,\n\t\t\tvertexCount\n\t\t});\n\t}\n\n\tconst raw = bytes.subarray(offset, offset + byteLength);\n\tif (!deltaEncoded) {\n\t\treturn raw.slice();\n\t}\n\n\tconst colors = new Uint8Array(byteLength);\n\tlet r = 0;\n\tlet g = 0;\n\tlet b = 0;\n\tfor (let i = 0; i < byteLength; i += 3) {\n\t\tr = (r + unzigzag(raw[i]!)) & 0xff;\n\t\tg = (g + unzigzag(raw[i + 1]!)) & 0xff;\n\t\tb = (b + unzigzag(raw[i + 2]!)) & 0xff;\n\t\tcolors[i] = r;\n\t\tcolors[i + 1] = g;\n\t\tcolors[i + 2] = b;\n\t}\n\treturn colors;\n}\n\n// ============================================================================\n// HELPERS\n// ============================================================================\n\nfunction toUint8Array(input: ArrayBuffer | Uint8Array | string): Uint8Array {\n\tif (typeof input === 'string') {\n\t\treturn decodeBase64ToBinary(input);\n\t}\n\tif (input instanceof Uint8Array) {\n\t\treturn input;\n\t}\n\treturn new Uint8Array(input);\n}\n\n/**\n * If the blob is a SLVZ compressed container, inflate it back to the raw SLVA bytes; otherwise\n * return the input untouched. Detection is by the leading 4-byte magic, so an uncompressed SLVA\n * blob (or any pre-v3 payload) flows through unchanged.\n */\nfunction maybeDecompress(bytes: Uint8Array): Uint8Array {\n\tif (bytes.byteLength < 8) {\n\t\treturn bytes;\n\t}\n\n\tconst view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n\tif (view.getUint32(0, true) !== COMPRESSED_MESH_MAGIC) {\n\t\treturn bytes;\n\t}\n\n\tconst uncompressedLen = view.getUint32(4, true);\n\tconst deflated = bytes.subarray(8);\n\n\t// Bound the wire-supplied length before allocating — a corrupt header could\n\t// otherwise request ~4 GB. DEFLATE won't expand past ~1000×.\n\tconst maxPlausibleLen = Math.max(deflated.byteLength * 1032 + 1024, 1 << 20);\n\tif (uncompressedLen > maxPlausibleLen) {\n\t\tthrow fail('SLVZ header declares an implausible uncompressed length', {\n\t\t\tuncompressedLen,\n\t\t\tdeflatedBytes: deflated.byteLength,\n\t\t\tmaxPlausibleLen\n\t\t});\n\t}\n\n\tlet out: Uint8Array;\n\ttry {\n\t\t// One byte of slack past the declared length: fflate returns a subarray trimmed to the byte\n\t\t// count actually written, so an understating header (stream longer than declared) lands on\n\t\t// length uncompressedLen + 1 and an overstating one (stream shorter) below uncompressedLen —\n\t\t// either way the check below catches the mismatch instead of a zero-padded/truncated tail\n\t\t// silently decoding as geometry.\n\t\tout = inflateSync(deflated, { out: new Uint8Array(uncompressedLen + 1) });\n\t} catch (error) {\n\t\tthrow fail(\n\t\t\t`Failed to inflate SLVZ blob: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t{ uncompressedLen, deflatedBytes: deflated.byteLength }\n\t\t);\n\t}\n\n\tif (out.byteLength !== uncompressedLen) {\n\t\tthrow fail('SLVZ payload inflated to a different size than the header declares.', {\n\t\t\tdeclaredLen: uncompressedLen,\n\t\t\tactualLen: out.byteLength,\n\t\t\tdeflatedBytes: deflated.byteLength\n\t\t});\n\t}\n\n\treturn out;\n}\n\nfunction decodeUtf8(bytes: Uint8Array): string {\n\tif (typeof TextDecoder !== 'undefined') {\n\t\treturn new TextDecoder('utf-8').decode(bytes);\n\t}\n\t// Node fallback (Buffer is utf-8 by default).\n\tif (\n\t\ttypeof (globalThis as { Buffer?: { from(b: Uint8Array): { toString(enc: string): string } } })\n\t\t\t.Buffer !== 'undefined'\n\t) {\n\t\treturn (\n\t\t\tglobalThis as { Buffer: { from(b: Uint8Array): { toString(enc: string): string } } }\n\t\t).Buffer.from(bytes).toString('utf-8');\n\t}\n\tthrow new RhinoComputeError(\n\t\t'No UTF-8 decoder available in this environment.',\n\t\tErrorCodes.INVALID_STATE\n\t);\n}\n\nfunction readInt16Vertices(buffer: ArrayBufferLike, byteOffset: number, count: number): Int16Array {\n\tif (count === 0) return new Int16Array(0);\n\tif (byteOffset % 2 === 0) {\n\t\treturn new Int16Array(buffer, byteOffset, count);\n\t}\n\t// Misaligned (rare — would require a wrapper Uint8Array with odd byteOffset).\n\tconst copy = new Uint8Array(count * 2);\n\tcopy.set(new Uint8Array(buffer, byteOffset, count * 2));\n\treturn new Int16Array(copy.buffer);\n}\n\nfunction readFloat32Vertices(\n\tbuffer: ArrayBufferLike,\n\tbyteOffset: number,\n\tcount: number\n): Float32Array {\n\tif (count === 0) return new Float32Array(0);\n\tif (byteOffset % 4 === 0) {\n\t\treturn new Float32Array(buffer, byteOffset, count);\n\t}\n\tconst copy = new Uint8Array(count * 4);\n\tcopy.set(new Uint8Array(buffer, byteOffset, count * 4));\n\treturn new Float32Array(copy.buffer);\n}\n\nfunction readUint16Array(buffer: ArrayBufferLike, byteOffset: number, count: number): Uint16Array {\n\tif (count === 0) return new Uint16Array(0);\n\tif (byteOffset % 2 === 0) {\n\t\treturn new Uint16Array(buffer, byteOffset, count);\n\t}\n\tconst copy = new Uint8Array(count * 2);\n\tcopy.set(new Uint8Array(buffer, byteOffset, count * 2));\n\treturn new Uint16Array(copy.buffer);\n}\n\nfunction readUint32Array(buffer: ArrayBufferLike, byteOffset: number, count: number): Uint32Array {\n\tif (count === 0) return new Uint32Array(0);\n\tif (byteOffset % 4 === 0) {\n\t\treturn new Uint32Array(buffer, byteOffset, count);\n\t}\n\tconst copy = new Uint8Array(count * 4);\n\tcopy.set(new Uint8Array(buffer, byteOffset, count * 4));\n\treturn new Uint32Array(copy.buffer);\n}\n\n/**\n * Rejects blobs whose index stream references vertices past `vertexCount`. Downstream mesh\n * assembly trusts indices arithmetically (rebasing, `subarray` slicing), so an out-of-range index\n * would otherwise corrupt geometry silently instead of failing the parse. A uint16 index stream\n * can't exceed a vertex count above 65535, so that case skips the scan.\n */\nfunction validateIndicesInRange(indices: Uint16Array | Uint32Array, vertexCount: number): void {\n\tif (indices.length === 0) return;\n\tif (indices instanceof Uint16Array && vertexCount > 0xffff) return;\n\tfor (let i = 0; i < indices.length; i++) {\n\t\tif (indices[i]! >= vertexCount) {\n\t\t\tthrow fail('Index out of range of vertexCount.', {\n\t\t\t\tindexPosition: i,\n\t\t\t\tindexValue: indices[i],\n\t\t\t\tvertexCount\n\t\t\t});\n\t\t}\n\t}\n}\n\n/** Inverse of the writer's zigzag map: 0,1,2,3 → 0,-1,1,-2. */\nfunction unzigzag(zz: number): number {\n\treturn (zz >>> 1) ^ -(zz & 1);\n}\n\n/**\n * Undoes the v3 delta filter on the quantized vertex stream: each component is a zigzag-mapped,\n * wrapped 16-bit difference from the previous vertex's same component (independent x/y/z running\n * sums). `(x << 16) >> 16` reproduces the writer's int16 wrapping.\n */\nfunction decodeDeltaVertices(zigzagged: Uint16Array): Int16Array {\n\tconst out = new Int16Array(zigzagged.length);\n\tlet px = 0;\n\tlet py = 0;\n\tlet pz = 0;\n\tfor (let i = 0; i < zigzagged.length; i += 3) {\n\t\tpx = ((px + unzigzag(zigzagged[i]!)) << 16) >> 16;\n\t\tpy = ((py + unzigzag(zigzagged[i + 1]!)) << 16) >> 16;\n\t\tpz = ((pz + unzigzag(zigzagged[i + 2]!)) << 16) >> 16;\n\t\tout[i] = px;\n\t\tout[i + 1] = py;\n\t\tout[i + 2] = pz;\n\t}\n\treturn out;\n}\n\nfunction decodeDeltaIndices16(zigzagged: Uint16Array): Uint16Array {\n\tconst out = new Uint16Array(zigzagged.length);\n\tlet prev = 0;\n\tfor (let i = 0; i < zigzagged.length; i++) {\n\t\tprev = (prev + unzigzag(zigzagged[i]!)) & 0xffff;\n\t\tout[i] = prev;\n\t}\n\treturn out;\n}\n\nfunction decodeDeltaIndices32(zigzagged: Uint32Array): Uint32Array {\n\tconst out = new Uint32Array(zigzagged.length);\n\tlet prev = 0;\n\tfor (let i = 0; i < zigzagged.length; i++) {\n\t\tprev = (prev + unzigzag(zigzagged[i]!)) >>> 0;\n\t\tout[i] = prev;\n\t}\n\treturn out;\n}\n\nfunction fail(message: string, context: Record<string, unknown>): RhinoComputeError {\n\treturn new RhinoComputeError(message, ErrorCodes.VALIDATION_ERROR, { context });\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/** Internal telemetry only (not exposed in public options). */\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\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 * 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"],"mappings":"wEAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,uBAAAE,GAAA,sBAAAC,GAAA,mBAAAC,GAAA,mBAAAC,GAAA,qBAAAC,GAAA,oBAAAC,GAAA,qBAAAC,GAAA,kBAAAC,KAAA,UAAYC,MAAW,QAEhB,IAAMP,GAAoB,IAAU,uBAAqB,CAC/D,MAAO,EACP,SAAU,IAAU,QAAM,QAAQ,EAClC,kBAAmB,EACnB,UAAW,EACX,UAAW,GACX,UAAW,GACX,mBAAoB,GACpB,WAAY,GACZ,UAAW,GACX,YAAa,GACb,UAAW,EACX,cAAe,GACf,oBAAqB,EACrB,mBAAoB,EACpB,KAAY,YACZ,UAAW,EACZ,CAAC,EAEYE,GAAiB,IAAU,uBAAqB,CAC5D,MAAO,IAAU,QAAM,CAAQ,EAC/B,UAAW,GACX,UAAW,GACX,gBAAiB,IACjB,UAAW,GACX,mBAAoB,GACpB,aAAc,EACd,IAAK,IACL,UAAW,EACX,WAAY,GACZ,YAAa,GACb,UAAW,EACX,UAAW,GACX,cAAe,GACf,oBAAqB,EACrB,mBAAoB,EACpB,KAAY,YACZ,UAAW,EACZ,CAAC,EAEYH,GAAoB,IAAU,uBAAqB,CAC/D,MAAO,IAAU,QAAM,QAAQ,EAC/B,UAAW,EACX,UAAW,IACX,gBAAiB,IACjB,UAAW,IACX,mBAAoB,GACpB,aAAc,IACd,aAAc,EACd,IAAK,KACL,UAAW,EACX,WAAY,GACZ,YAAa,GAGb,UAAW,EACX,UAAW,GACX,cAAe,GACf,oBAAqB,EACrB,mB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AAK,UACRA,EAAK,SAAS,QAAQ,EAGnBA,EAAK,WACJ,MAAM,QAAQA,EAAK,QAAQ,EAC9BA,EAAK,SAAS,QAASC,GAAaA,EAAS,QAAQ,CAAC,EAEtDD,EAAK,SAAS,QAAQ,EAGzB,CACD,CAKA,SAAS1B,GAAkBb,EAAyB,CACnD,IAAMyC,EAAU,YAAY,IAAI,EAAIzC,EACpCgB,EAAU,EAAE,KAAK,0BAA2B,GAAGyB,EAAQ,QAAQ,CAAC,CAAC,IAAI,CACtE","names":["three_materials_exports","__export","CONCRETE_MATERIAL","EMISSIVE_MATERIAL","GLASS_MATERIAL","METAL_MATERIAL","PLASTIC_MATERIAL","RUBBER_MATERIAL","SHARED_MATERIALS","WOOD_MATERIAL","THREE","THREE","CAMERA_CONFIG","updateScene","scene","meshes","camera","controls","initialPositionSet","clearScene","mesh","unionBoundingBox","computeCombinedBoundingBox","center","size","maxDim","distance","parseColor","colorString","getLogger","trimmed","hex","rgb","c","n","named","applyOffset","offset","axis","combinedBoundingBox","bbox","VIEWER_AID_IDS","isViewerAid","object","current","computeContentBounds","box","renderable","PERSISTENT_SCENE_IDS","child","material","SHARED_MATERIALS","value","THREE","buildViewDirections","up","u","worldZ","worldY","seed","right","forward","createCameraController","deps","scene","perspective","controls","onActiveCameraChange","VIEW_DIRECTIONS","ortho","projection","aspect","active","activeTween","cancelTween","syncOrthoFrustum","halfH","halfW","setProjection","next","distance","direction","frame","center","maxDim","animate","fov","dir","nudgeOffPole","toPosition","cam","animateMove","setViewDirection","box","computeContentBounds","size","preset","enabled","width","height","d","inPlane","tilt","easeOut","t","camera","toTarget","onTick","durationMs","fromPosition","fromTarget","startTime","rafId","tick","THREE","GRID_VERTEX","GRID_FRAGMENT","createGrid","options","cellSize","majorEvery","cellColor","majorColor","fadeDistance","plane","axes","size","geometry","material","mesh","center","cameraPosition","visible","THREE","ViewHelper","createViewGizmo","deps","camera","domElement","controller","helper","visible","DIM","raycaster","gizmoCamera","AXIS_DIRECTIONS","pickAxis","event","rect","offsetX","offsetY","mouse","hits","hit","type","renderer","prevAutoClear","axis","value","THREE","LineSegmentsGeometry","LineSegments2","LineMaterial","EDGE_USERDATA_KIND","DEFAULT_EDGE_COLOR","DEFAULT_EDGE_WIDTH","DEFAULT_THRESHOLD_ANGLE","edgeGeometryCache","addEdges","root","options","color","width","thresholdAngle","created","object","c","overlay","buildEdgeOverlay","acquireEdgeGeometry","geometry","byAngle","entry","edges","lineGeometry","releaseEdgeGeometry","userData","material","isEdgeOverlay","removeEdges","overlays","EffectComposer","RenderPass","GTAOPass","SMAAPass","OutputPass","createRenderPipeline","renderer","scene","camera","width","height","options","composer","renderPass","gtaoPass","smaaPass","outputPass","aoPixelRatioCap","deltaTime","w","h","pixelRatio","cam","isPerspective","THREE","CSS2DRenderer","CSS2DObject","createLabelLayer","container","scene","renderer","dom","size","group","labels","text","position","className","el","object","p","t","camera","width","height","THREE","Line2","LineGeometry","LineMaterial","DEFAULT_SNAP_PIXELS","DEFAULT_COLOR","LINE_PICK_FRACTION","UNIT_DISPLAY","makeFormatter","displayUnit","unit","meters","pickThreshold","camera","viewTarget","ortho","snapCandidateIndices","hit","obj","index","snapToVertex","screenSize","snapPixels","raw","indices","pos","toScreen","worldP","ndc","rawScreen","best","bestPx","idx","world","px","createMeasureTool","deps","canvas","scene","getActiveCamera","getViewTarget","labelLayer","options","color","fmt","defaultFormat","d","delta","format","raycaster","pointer","enabled","points","markers","line","label","markerMaterial","hoverMaterial","hoverMarker","showHover","p","geometry","makeMarker","marker","clear","m","drawMeasurement","a","b","material","mid","pickPoint","event","rect","threshold","hits","i","pendingMove","moveRaf","cancelPendingMove","value","point","latest","THREE","TEXTURE_CACHE_MAX_ENTRIES","MAX_KEY_LENGTH","textureCache","inFlight","cacheGeneration","StaleTextureLoadError","url","maxAnisotropy","setTextureAnisotropy","value","texture","applyTextureMap","material","key","cacheKeyFor","cached","loadTexture","error","getLogger","clearTextureCache","fnv1aString","s","hash","i","storeTexture","oldestKey","evicted","pending","generation","resolve","reject","THREE","OrbitControls","HDRLoader","defaultUp","DEFAULT_LOOK","LOOK_PRESETS","materialAppearanceForLook","look","preset","upToGroundPlane","up","ax","ay","az","initThree","canvas","options","config","applyDefaults","sceneUp","pixelRatio","scene","createScene","camera","createCamera","renderer","setupRenderer","setTextureAnisotropy","controls","setupControls","cameraController","createCameraController","getActiveCamera","disposed","setupEnvironment","lights","setupLighting","sunlight","updateShadowBounds","fitShadowToContent","computeContentBounds","addFloor","grid","createGrid","gizmo","createViewGizmo","labelContainer","labelLayer","createLabelLayer","measureTool","createMeasureTool","eventHandlers","setupEventHandlers","DRAG_SLOP_PX","pressX","pressY","handlePointerDown","event","wasDrag","handleToolClick","handleToolMove","applyEdges","root","addEdges","parent","getCanvasSize","renderPipeline","buildPipeline","width","height","pipeline","createRenderPipeline","setAmbientOcclusion","enabled","setFillLights","opts","setEnvironmentIntensity","intensity","setToneMappingExposure","exposure","setAoIntensity","setLook","activeLook","object","mesh","materials","material","getMaterialAppearance","animate","disposeAnimation","createAnimationLoop","disposeObjectTree","renderable","disposeMaterialWithTextures","addUserGeometry","removeUserGeometry","clearUserGeometry","child","scale","defaults","value","light","bounds","center","radius","cam","lightDistance","bgColor","onFrame","getRenderPipeline","animationId","lastTime","checkResize","newW","newH","now","delta","activeCamera","isDisposed","HDRLoader","envMap","getLogger","error","ambient","hemisphere","pos","floorSize","floorGeometry","floorColor","floorMaterial","floor","selectedObjects","originalMaterials","raycaster","mouse","mouseDownPosition","isFullyVisible","current","fitToView","box","selectionColorObj","clearSelection","obj","restorable","original","clone","m","applyHighlight","target","updatePickThresholds","diagonal","handleMouseDown","handleCanvasClick","currentMousePosition","rect","intersects","i","clickedObject","handleDoubleClick","handleKeydown","OrbitControls","THREE","Line2","LineGeometry","LineMaterial","rhinoToThree","x","y","z","_apply","DEFAULT_COLOR","CURVE_INITIAL_SEGMENTS","CURVE_CHORD_TOLERANCE_RATIO","CURVE_MAX_SUBDIVISION_DEPTH","CURVE_MAX_TURN_RADIANS","parseDisplayItems","items","options","rhino","applyTransforms","objects","item","line","buildCurveLine","point","buildPoint","unknown","getLogger","DEFAULT_LINE_WIDTH","curve","decodeCurve","points","tessellate","error","deleteRhinoObject","positions","p","geometry","LineGeometry","params","materialParams","material","LineMaterial","styled","Line2","position","x","y","z","rhinoToThree","obj","json","parsed","exact","tryPolylineVertices","sampleUniform","result","polyline","out","i","domain","t0","span","evalAt","t","tolerance","chordTolerance","ta","pa","tb","pb","subdivide","depth","tm","pm","deviation","distanceToSegment","turn","turnAngle","box","min","max","diagonal","a","b","c","abx","aby","abz","bcx","bcy","bcz","lenAb","lenBc","dot","cos","lengthSq","apx","apy","apz","dx","dy","dz","color","opacity","resolved","inflateSync","BINARY_MESH_MAGIC","COMPRESSED_MESH_MAGIC","BINARY_MESH_VERSION","MIN_SUPPORTED_VERSION","FLAG_FLOAT32","FLAG_UINT16_INDICES","FLAG_DELTA_ENCODED","FLAG_HAS_UVS","FLAG_HAS_VERTEX_COLORS","UV_FORMAT_UINT16","UV_FORMAT_FLOAT32","HEADER_PREAMBLE_BYTES","GEOMETRY_HEADER_BYTES","HOST_IS_LITTLE_ENDIAN","parseBinaryMeshBatch","input","RhinoComputeError","ErrorCodes","bytes","maybeDecompress","toUint8Array","view","fail","offset","magic","version","metadataLen","metadataBytes","metadata","decodeUtf8","error","flags","originX","originY","originZ","scaleX","scaleY","scaleZ","vertexCount","useFloat32","deltaEncoded","componentCount","verticesByteLength","absoluteOffset","verticesView","readFloat32Vertices","decodeDeltaVertices","readUint16Array","readInt16Vertices","indexCount","useUint16Indices","indicesByteLength","indicesView","readUint32Array","decodeDeltaIndices16","decodeDeltaIndices32","validateIndicesInRange","uvs","parsed","parseUvChunk","colors","parseColorChunk","UV_CHUNK_HEADER_BYTES","uvFormat","originU","originV","scaleU","scaleV","dataByteLength","raw","qu","qv","i","unzigzag","byteLength","r","g","b","decodeBase64ToBinary","uncompressedLen","deflated","maxPlausibleLen","out","inflateSync","buffer","byteOffset","count","copy","indices","zz","zigzagged","px","py","pz","prev","message","context","THREE","parseMeshBatch","batchJson","options","debug","perfStart","batch","parseStart","error","getLogger","parseTime","parseMeshBatchObject","telemetry","mergeByMaterial","applyTransforms","material","decodeStart","parsed","parseBinaryMeshBatch","decodeTime","blobBytes","approximateBase64DecodedBytes","buildMeshesFromParsed","parseMeshBatchBlob","blob","opts","materialAppearance","fallback","materialsSrc","groups","sourceComponentId","isFloat32","FLAG_FLOAT32","validateGroupMetadata","worldVertices","maybeRotateFloat32Vertices","dequantizeInt16","wireBytes","meshCreateStart","materials","m","createMaterial","meshes","group","mergedMesh","createMergedMesh","individualMeshes","createIndividualMeshes","mesh","meshCreateTime","totalTime","metadataFail","message","context","RhinoComputeError","ErrorCodes","materialCount","totalVertexCount","totalIndexCount","fields","field","value","assertIndexInWindow","indexValue","meshMeta","q","origin","scale","_applyCoordinateTransform","out","ox","oy","oz","sx","sy","sz","i","vertices","matData","color","parseColor","vertexColors","appearance","applyVertexColorSRGBDecode","applyTextureMap","shader","allVertices","allIndices","allUvs","allColors","mergedVertices","mergedIndices","mergedUvs","mergedColors","vertexWriteCursor","indexWriteCursor","componentStart","componentLen","uvStart","indicesSlice","indexShift","geometry","threeMesh","firstMesh","meshNames","name","rebasedIndices","baseIndex","uvs","colors","base64","SCALE_FACTORS","DISPLAY_COMPONENT_TYPE","DISPLAY_BATCH_TYPE","isDisplayItemType","type","tokens","warnedUnknownUnits","getThreeMeshesFromComputeResponse","data","options","startTime","objects","allowScaling","allowAutoPosition","rhino","debug","parsingOptions","scaleFactor","getScaleFactor","extractDisplayFromData","applyGroundOffset","error","handleError","logProcessingTime","modelUnits","factor","getLogger","value","innerTree","path","branch","processDataBranch","item","mergedParsingOptions","batch","extractBatch","batchMeshes","parseMeshBatchObject","batchItems","parseDisplayItems","batchObjects","obj","safeParse","s","meshes","combinedBoundingBox","computeCombinedBoundingBox","applyOffset","disposeMeshes","mesh","material","elapsed"]}