@selvajs/compute 1.5.2-beta.2 → 1.5.2-beta.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-6VF4VVLW.cjs → chunk-C2VFZAMO.cjs} +2 -2
- package/dist/{chunk-6VF4VVLW.cjs.map → chunk-C2VFZAMO.cjs.map} +1 -1
- package/dist/chunk-DM7RXPP6.js +2 -0
- package/dist/chunk-DM7RXPP6.js.map +1 -0
- package/dist/chunk-DSI6FKBA.cjs +2 -0
- package/dist/chunk-DSI6FKBA.cjs.map +1 -0
- package/dist/{chunk-RILJ3IA7.js → chunk-R7E2XNH4.js} +2 -2
- package/dist/core.d.cts +3 -2
- package/dist/core.d.ts +3 -2
- package/dist/errors-CEy4nM1J.d.cts +149 -0
- package/dist/errors-CEy4nM1J.d.ts +149 -0
- package/dist/grasshopper.cjs +1 -1
- package/dist/grasshopper.d.cts +4 -27
- package/dist/grasshopper.d.ts +4 -27
- package/dist/grasshopper.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +3 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.js +1 -1
- package/dist/types-COCuQEMk.d.cts +93 -0
- package/dist/types-COCuQEMk.d.ts +93 -0
- package/dist/{errors-CiA83qw2.d.cts → types-Dfeei0dD.d.cts} +1 -149
- package/dist/{errors-CiA83qw2.d.ts → types-Dfeei0dD.d.ts} +1 -149
- package/dist/visualization-HV5EMX2F.cjs +2 -0
- package/dist/visualization-HV5EMX2F.cjs.map +1 -0
- package/dist/visualization-S47O7BLV.js +2 -0
- package/dist/visualization-S47O7BLV.js.map +1 -0
- package/dist/visualization.cjs +1 -1
- package/dist/visualization.cjs.map +1 -1
- package/dist/visualization.d.cts +75 -1
- package/dist/visualization.d.ts +75 -1
- package/dist/visualization.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-5465MDT4.cjs +0 -2
- package/dist/chunk-5465MDT4.cjs.map +0 -1
- package/dist/chunk-DADFXYBV.js +0 -2
- package/dist/chunk-DADFXYBV.js.map +0 -1
- package/dist/visualization-7TK4UEZL.js +0 -2
- package/dist/visualization-7TK4UEZL.js.map +0 -1
- package/dist/visualization-JYNKROSH.cjs +0 -2
- package/dist/visualization-JYNKROSH.cjs.map +0 -1
- /package/dist/{chunk-RILJ3IA7.js.map → chunk-R7E2XNH4.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/features/visualization/webdisplay/batch-parser.ts","../src/features/visualization/webdisplay/binary-parser.ts","../src/features/visualization/webdisplay/webdisplay-parser.ts"],"sourcesContent":["import * as THREE from 'three';\n\nimport { parseColor } from '../threejs/three-helpers';\nimport { getLogger } from '@/core';\n\nimport { FLAG_FLOAT32, parseBinaryMeshBatch } from './binary-parser';\n\nimport type { MeshBatch, MaterialGroup, SerializableMaterial } from './types';\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 * @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 */\nexport async function parseMeshBatch(\n\tbatchJson: string,\n\toptions?: {\n\t\t/** Merge meshes with same material into single geometry*/\n\t\tmergeByMaterial?: boolean;\n\t\t/** Apply coordinate system transformations */\n\t\tapplyTransforms?: boolean;\n\t\t/** Enable performance monitoring */\n\t\tdebug?: boolean;\n\t}\n): Promise<THREE.Mesh[]> {\n\tconst { mergeByMaterial = true, applyTransforms = true, debug = false } = options ?? {};\n\n\tconst perfStart = debug ? performance.now() : 0;\n\tlet parseTime = 0;\n\n\ttry {\n\t\tconst parseStart = performance.now();\n\t\tconst batch: MeshBatch = JSON.parse(batchJson);\n\t\tparseTime = performance.now() - parseStart;\n\n\t\treturn await parseMeshBatchObject(batch, {\n\t\t\tmergeByMaterial,\n\t\t\tapplyTransforms,\n\t\t\tdebug,\n\t\t\tparseTime,\n\t\t\tperfStart\n\t\t});\n\t} catch (error) {\n\t\tgetLogger().error('Error parsing mesh batch:', error);\n\t\treturn [];\n\t}\n}\n\n/**\n * Parses a MeshBatch object and creates Three.js meshes.\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 * @param batch - MeshBatch object\n * @param options - Rendering options\n * @returns Promise resolving to array of Three.js mesh objects\n */\nexport async function parseMeshBatchObject(\n\tbatch: MeshBatch,\n\toptions?: {\n\t\t/** Merge meshes with same material into single geometry*/\n\t\tmergeByMaterial?: boolean;\n\t\t/** Apply coordinate system transformations */\n\t\tapplyTransforms?: boolean;\n\t\t/** Scale factor to apply to meshes (e.g., for unit conversion) */\n\t\tscaleFactor?: number;\n\t\t/** Enable performance monitoring */\n\t\tdebug?: boolean;\n\t\t/** Parse time (optional, for debugging) */\n\t\tparseTime?: number;\n\t\t/** Performance start time (optional, for debugging) */\n\t\tperfStart?: number;\n\t}\n): Promise<THREE.Mesh[]> {\n\tconst {\n\t\tmergeByMaterial = true,\n\t\tapplyTransforms = true,\n\t\tscaleFactor = 1,\n\t\tdebug = false,\n\t\tparseTime = 0,\n\t\tperfStart = debug ? performance.now() : 0\n\t} = options ?? {};\n\n\tlet decodeTime = 0;\n\tlet meshCreateTime = 0;\n\n\ttry {\n\t\tconst decodeStart = performance.now();\n\t\tconst parsed = parseBinaryMeshBatch(batch.compressedData);\n\t\tdecodeTime = performance.now() - decodeStart;\n\n\t\t// Prefer materials/groups from the blob's embedded metadata — that's the source of truth\n\t\t// the C# writer emits. Fall back to the outer envelope for resilience (e.g. if a future\n\t\t// transport drops them from the blob's metadata to save bytes).\n\t\tconst materialsSrc = parsed.metadata.materials ?? batch.materials;\n\t\tconst groups = parsed.metadata.groups ?? batch.groups;\n\t\tconst sourceComponentId = parsed.metadata.sourceComponentId ?? batch.sourceComponentId;\n\n\t\tconst isFloat32 = (parsed.flags & FLAG_FLOAT32) !== 0;\n\n\t\t// Dequantize once up-front into a single Float32Array. Downstream code (per-group merging,\n\t\t// computeVertexNormals, ground-offset, scaleFactor) all expect world-unit floats, and a\n\t\t// single linear pass over the int16 buffer is far cheaper than the legacy gunzip + base64\n\t\t// path. The Z-up -> Y-up rotation, when requested, is folded into the same pass.\n\t\tconst worldVertices = isFloat32\n\t\t\t? maybeRotateFloat32Vertices(parsed.vertices as Float32Array, applyTransforms)\n\t\t\t: dequantizeInt16(\n\t\t\t\t\tparsed.vertices as Int16Array,\n\t\t\t\t\tparsed.origin,\n\t\t\t\t\tparsed.scale,\n\t\t\t\t\tapplyTransforms\n\t\t\t\t);\n\n\t\tif (debug) {\n\t\t\tconst blobBytes = approximateBase64DecodedBytes(batch.compressedData);\n\t\t\tconst wireBytes = parsed.vertices.byteLength + parsed.indices.byteLength;\n\t\t\tgetLogger().debug('Mesh Batch Stats:');\n\t\t\tgetLogger().debug(` Materials: ${materialsSrc.length} | Groups: ${groups.length}`);\n\t\t\tgetLogger().debug(\n\t\t\t\t` Vertices: ${parsed.vertices.length / 3} | Indices: ${parsed.indices.length}`\n\t\t\t);\n\t\t\tgetLogger().debug(` Format: ${isFloat32 ? 'float32' : 'int16 quantized'}`);\n\t\t\tgetLogger().debug(\n\t\t\t\t` Blob: ${(blobBytes / 1024 / 1024).toFixed(2)} MB | Geometry on wire: ${(wireBytes / 1024 / 1024).toFixed(2)} MB`\n\t\t\t);\n\t\t}\n\n\t\tconst meshCreateStart = performance.now();\n\t\tconst materials = materialsSrc.map(createMaterial);\n\n\t\tconst meshes: THREE.Mesh[] = [];\n\n\t\tfor (const group of groups) {\n\t\t\tif (mergeByMaterial && group.meshes.length > 1) {\n\t\t\t\tconst mergedMesh = createMergedMesh(group, worldVertices, parsed.indices, materials);\n\t\t\t\tmergedMesh.userData.sourceComponentId = sourceComponentId ?? null;\n\t\t\t\tmeshes.push(mergedMesh);\n\t\t\t} else {\n\t\t\t\tconst individualMeshes = createIndividualMeshes(\n\t\t\t\t\tgroup,\n\t\t\t\t\tworldVertices,\n\t\t\t\t\tparsed.indices,\n\t\t\t\t\tmaterials\n\t\t\t\t);\n\t\t\t\tfor (const mesh of individualMeshes) {\n\t\t\t\t\tmesh.userData.sourceComponentId = sourceComponentId ?? null;\n\t\t\t\t}\n\t\t\t\tmeshes.push(...individualMeshes);\n\t\t\t}\n\t\t}\n\n\t\tif (scaleFactor !== 1) {\n\t\t\tfor (const mesh of meshes) {\n\t\t\t\tmesh.scale.set(scaleFactor, scaleFactor, scaleFactor);\n\t\t\t}\n\t\t}\n\n\t\tmeshCreateTime = performance.now() - meshCreateStart;\n\n\t\tif (debug) {\n\t\t\tconst totalTime = performance.now() - perfStart;\n\t\t\tgetLogger().debug('Performance:');\n\t\t\tif (parseTime > 0) getLogger().debug(` Parse JSON: ${parseTime.toFixed(2)}ms`);\n\t\t\tgetLogger().debug(` Decode binary: ${decodeTime.toFixed(2)}ms`);\n\t\t\tgetLogger().debug(` Create Meshes: ${meshCreateTime.toFixed(2)}ms`);\n\t\t\tgetLogger().debug(` Total: ${totalTime.toFixed(2)}ms`);\n\t\t}\n\n\t\treturn meshes;\n\t} catch (error) {\n\t\tgetLogger().error('Error parsing mesh batch object:', error);\n\t\treturn [];\n\t}\n}\n\n// ============================================================================\n// DEQUANTIZATION\n// ============================================================================\n\n/**\n * Reconstructs world-unit float32 positions from int16 quantized values.\n *\n * Mirrors the encoder formula: `world = origin + (q + 32767) * scale`. When\n * `applyCoordinateTransform=true` we fold the Rhino Z-up -> Three Y-up shuffle into the same pass\n * (`(x, y, z) -> (x, z, -y)`), saving a second walk over the buffer.\n */\nfunction dequantizeInt16(\n\tq: Int16Array,\n\torigin: [number, number, number],\n\tscale: [number, number, number],\n\tapplyCoordinateTransform: 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\tif (applyCoordinateTransform) {\n\t\t// Rotate -90 deg around X: (x, y, z) -> (x, z, -y)\n\t\tfor (let i = 0; i < q.length; i += 3) {\n\t\t\tconst wx = ox + (q[i]! + 32767) * sx;\n\t\t\tconst wy = oy + (q[i + 1]! + 32767) * sy;\n\t\t\tconst wz = oz + (q[i + 2]! + 32767) * sz;\n\t\t\tout[i] = wx;\n\t\t\tout[i + 1] = wz;\n\t\t\tout[i + 2] = -wy;\n\t\t}\n\t} else {\n\t\tfor (let i = 0; i < q.length; i += 3) {\n\t\t\tout[i] = ox + (q[i]! + 32767) * sx;\n\t\t\tout[i + 1] = oy + (q[i + 1]! + 32767) * sy;\n\t\t\tout[i + 2] = oz + (q[i + 2]! + 32767) * sz;\n\t\t}\n\t}\n\n\treturn out;\n}\n\n/**\n * For float32 batches: when no transform is needed we can pass through the parser's view; the\n * caller doesn't mutate it. When the rotation is needed we have to allocate.\n */\nfunction maybeRotateFloat32Vertices(\n\tvertices: Float32Array,\n\tapplyCoordinateTransform: boolean\n): Float32Array {\n\tif (!applyCoordinateTransform) return vertices;\n\n\tconst out = new Float32Array(vertices.length);\n\tfor (let i = 0; i < vertices.length; i += 3) {\n\t\tconst x = vertices[i]!;\n\t\tconst y = vertices[i + 1]!;\n\t\tconst z = vertices[i + 2]!;\n\t\tout[i] = x;\n\t\tout[i + 1] = z;\n\t\tout[i + 2] = -y;\n\t}\n\treturn out;\n}\n\n// ============================================================================\n// MATERIAL CONSTRUCTION\n// ============================================================================\n\nfunction createMaterial(matData: SerializableMaterial): THREE.MeshPhysicalMaterial {\n\tconst color = parseColor(matData.color);\n\n\treturn 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\tside: 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\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: Uint32Array,\n\tmaterials: THREE.Material[]\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\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\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\tif (indexShift === 0) {\n\t\t\tmergedIndices.set(indicesSlice, indexWriteCursor);\n\t\t} else {\n\t\t\tfor (let i = 0; i < indicesSlice.length; i++) {\n\t\t\t\tmergedIndices[indexWriteCursor + i] = indicesSlice[i]! + indexShift;\n\t\t\t}\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\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\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: Uint32Array,\n\tmaterials: THREE.Material[]\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\trebasedIndices[i] = indicesSlice[i]! - 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\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\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 { decodeBase64ToBinary } from '@/core/utils/encoding';\nimport { RhinoComputeError, ErrorCodes } from '@/core/errors';\n\nimport type { MaterialGroup, SerializableMaterial } from './types';\n\n// ============================================================================\n// WIRE FORMAT CONSTANTS\n// ============================================================================\n\n/** \"SLVA\" little-endian. */\nexport const BINARY_MESH_MAGIC = 0x41564c53;\n/** Bumped on any wire-layout change. */\nexport const BINARY_MESH_VERSION = 1;\n/** Bit 0 of the geometry flags word: 0 = int16 quantized, 1 = float32 raw. */\nexport const FLAG_FLOAT32 = 0x1;\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// PARSED TYPES\n// ============================================================================\n\n/**\n * Metadata JSON embedded inside the binary blob.\n *\n * This is the same shape as a `MeshBatch` minus the `compressedData` field (the blob is opaque to\n * its own metadata header). Kept separate from the public `MeshBatch` type because the blob's\n * 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` are typed-array views over the original `ArrayBuffer` — zero copies.\n * The consumer is responsible for not mutating the underlying buffer if it cares about safety,\n * or for calling `.slice()` to detach.\n */\nexport interface ParsedBinaryMeshBatch {\n\tmetadata: BinaryMeshMetadata;\n\tflags: number;\n\tvertices: Int16Array | Float32Array;\n\tindices: Uint32Array;\n\torigin: [number, number, number];\n\tscale: [number, number, number];\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 1)\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 * [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]\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 * @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\tconst bytes = 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 !== BINARY_MESH_VERSION) {\n\t\tthrow fail(`Unsupported SLVA version: ${version}`, {\n\t\t\texpectedVersion: 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 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\tconst verticesView = useFloat32\n\t\t? readFloat32Vertices(bytes.buffer, absoluteOffset, componentCount)\n\t\t: readInt16Vertices(bytes.buffer, absoluteOffset, componentCount);\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 indicesByteLength = indexCount * 4;\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});\n\t}\n\n\tconst indicesView = readUint32Indices(bytes.buffer, bytes.byteOffset + offset, indexCount);\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};\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\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 readUint32Indices(\n\tbuffer: ArrayBufferLike,\n\tbyteOffset: number,\n\tcount: number\n): 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\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 { applyOffset, computeCombinedBoundingBox } from '../threejs/three-helpers.js';\nimport { getLogger } from '@/core';\n\nimport { parseMeshBatch } from './batch-parser';\n\nimport type { DataItem, GrasshopperComputeResponse } from '@/features/grasshopper/types';\nimport type { MeshExtractionOptions, MeshBatchParsingOptions } from './types';\n\n// Constants\nexport const SCALE_FACTORS: Record<string, number> = {\n\tMillimeters: 1 / 1000,\n\tCentimeters: 1 / 100,\n\tMeters: 1,\n\tInches: 1 / 39.37,\n\tFeet: 1 / 3.28084\n};\n\nconst DISPLAY_COMPONENT_TYPE = 'Display';\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:** Mesh decompression happens asynchronously in a Web Worker to prevent UI blocking.\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 * - Decompression is performed in a Web Worker for non-blocking UI updates.\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.Mesh[]> {\n\tconst startTime = performance.now();\n\tconst meshes: THREE.Mesh[] = [];\n\n\tconst {\n\t\tallowScaling = true,\n\t\tallowAutoPosition = true,\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 extractMeshesFromData(data, meshes, scaleFactor, parsingOptions, debug);\n\n\t\tif (allowAutoPosition) {\n\t\t\tapplyGroundOffset(meshes);\n\t\t}\n\n\t\treturn meshes;\n\t} catch (error) {\n\t\thandleError(error, meshes);\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 scale factor for the given unit type.\n */\nfunction getScaleFactor(modelUnits: string): number {\n\treturn SCALE_FACTORS[modelUnits] ?? 1;\n}\n\n/**\n * Extracts meshes from compute response data.\n */\nasync function extractMeshesFromData(\n\tdata: GrasshopperComputeResponse,\n\tmeshes: THREE.Mesh[],\n\tscaleFactor: number,\n\tparsingOptions: MeshBatchParsingOptions,\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, meshes, scaleFactor, parsingOptions, debug);\n\t\t}\n\t}\n}\n\n/**\n * Processes a single data branch to extract MeshBatch display meshes.\n */\nasync function processDataBranch(\n\tbranch: DataItem[],\n\tmeshes: THREE.Mesh[],\n\tscaleFactor: number,\n\tparsingOptions: MeshBatchParsingOptions,\n\tdebug: boolean\n): Promise<void> {\n\tfor (const item of branch) {\n\t\tif (item.type.includes(DISPLAY_COMPONENT_TYPE)) {\n\t\t\tconst mergedParsingOptions = {\n\t\t\t\tmergeByMaterial: true,\n\t\t\t\tapplyTransforms: true,\n\t\t\t\tdebug: false,\n\t\t\t\t...parsingOptions\n\t\t\t};\n\n\t\t\tconst batchMeshes = await parseMeshBatch(item.data, mergedParsingOptions);\n\n\t\t\tif (scaleFactor !== 1) {\n\t\t\t\tfor (const mesh of batchMeshes) {\n\t\t\t\t\tmesh.scale.set(scaleFactor, scaleFactor, scaleFactor);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tmeshes.push(...batchMeshes);\n\n\t\t\tif (debug) {\n\t\t\t\tgetLogger().debug(`Extracted ${batchMeshes.length} meshes from batch`);\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Applies vertical offset to position meshes on the Z=0 plane.\n */\nfunction applyGroundOffset(meshes: THREE.Mesh[]): void {\n\tif (meshes.length === 0) return;\n\n\tconst combinedBoundingBox = computeCombinedBoundingBox(meshes);\n\tconst offsetY = combinedBoundingBox.min.y;\n\tapplyOffset(meshes, offsetY);\n}\n\n/**\n * Handles errors by disposing created meshes and logging.\n */\nfunction handleError(error: unknown, meshes: THREE.Mesh[]): void {\n\tgetLogger().error('An unexpected error occurred:', error);\n\tdisposeMeshes(meshes);\n}\n\n/**\n * Disposes of all meshes and their associated resources.\n */\nfunction disposeMeshes(meshes: THREE.Mesh[]): void {\n\tfor (const mesh of meshes) {\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":"yKAAA,UAAYA,MAAW,QCUhB,IAAMC,EAAoB,WAEpBC,EAAsB,EAEtBC,EAAe,EAEtBC,EAAwB,GACxBC,EACL,GAoEM,SAASC,EACfC,EACwB,CACxB,IAAMC,EAAQC,EAAaF,CAAK,EAC1BG,EAAO,IAAI,SAASF,EAAM,OAAQA,EAAM,WAAYA,E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AAiCd,CAAK,EACxDkB,GAAc3B,CAAM,CACrB,CAKA,SAAS2B,GAAc3B,EAA4B,CAClD,QAAWsB,KAAQtB,EACdsB,EAAK,UACRA,EAAK,SAAS,QAAQ,EAGnBA,EAAK,WACJ,MAAM,QAAQA,EAAK,QAAQ,EAC9BA,EAAK,SAAS,QAASM,GAAaA,EAAS,QAAQ,CAAC,EAEtDN,EAAK,SAAS,QAAQ,EAI1B,CAKA,SAASX,GAAkBZ,EAAyB,CACnD,IAAM8B,EAAU,YAAY,IAAI,EAAI9B,EACpCwB,EAAU,EAAE,KAAK,0BAA2B,GAAGM,EAAQ,QAAQ,CAAC,CAAC,IAAI,CACtE","names":["THREE","BINARY_MESH_MAGIC","BINARY_MESH_VERSION","FLAG_FLOAT32","HEADER_PREAMBLE_BYTES","GEOMETRY_HEADER_BYTES","parseBinaryMeshBatch","input","bytes","toUint8Array","view","fail","offset","magic","version","metadataLen","metadataBytes","metadata","decodeUtf8","error","flags","originX","originY","originZ","scaleX","scaleY","scaleZ","vertexCount","useFloat32","componentCount","verticesByteLength","absoluteOffset","verticesView","readFloat32Vertices","readInt16Vertices","indexCount","indicesByteLength","indicesView","readUint32Indices","decodeBase64ToBinary","RhinoComputeError","ErrorCodes","buffer","byteOffset","count","copy","message","context","parseMeshBatch","batchJson","options","mergeByMaterial","applyTransforms","debug","perfStart","parseTime","parseStart","batch","parseMeshBatchObject","error","getLogger","scaleFactor","decodeTime","meshCreateTime","decodeStart","parsed","parseBinaryMeshBatch","materialsSrc","groups","sourceComponentId","isFloat32","FLAG_FLOAT32","worldVertices","maybeRotateFloat32Vertices","dequantizeInt16","blobBytes","approximateBase64DecodedBytes","wireBytes","meshCreateStart","materials","createMaterial","meshes","group","mergedMesh","createMergedMesh","individualMeshes","createIndividualMeshes","mesh","totalTime","q","origin","scale","applyCoordinateTransform","out","ox","oy","oz","sx","sy","sz","i","wx","wy","wz","vertices","x","y","z","matData","color","parseColor","allVertices","allIndices","totalVertexCount","totalIndexCount","meshMeta","mergedVertices","mergedIndices","vertexWriteCursor","indexWriteCursor","componentStart","componentLen","indicesSlice","indexShift","geometry","threeMesh","firstMesh","meshNames","m","name","rebasedIndices","baseIndex","base64","SCALE_FACTORS","DISPLAY_COMPONENT_TYPE","getThreeMeshesFromComputeResponse","data","options","startTime","meshes","allowScaling","allowAutoPosition","debug","parsingOptions","scaleFactor","getScaleFactor","extractMeshesFromData","applyGroundOffset","error","handleError","logProcessingTime","modelUnits","value","innerTree","path","branch","processDataBranch","item","mergedParsingOptions","batchMeshes","parseMeshBatch","mesh","getLogger","offsetY","computeCombinedBoundingBox","applyOffset","disposeMeshes","material","elapsed"]}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkMZGKJZVPcjs = require('./chunk-MZGKJZVP.cjs');var _chunk5465MDT4cjs = require('./chunk-5465MDT4.cjs');var _chunkVWOEUM7Ccjs = require('./chunk-VWOEUM7C.cjs');var _three = require('three'); var y = _interopRequireWildcard(_three);var H=1096174675,O= exports.BINARY_MESH_VERSION =1,T= exports.FLAG_FLOAT32 =1,G=12,N=56;function P(e){let r=W(e),n=new DataView(r.buffer,r.byteOffset,r.byteLength);if(r.byteLength<G)throw x("Blob too small to contain SLVA header.",{expectedBytes:G,availableBytes:r.byteLength});let t=0,s=n.getUint32(t,!0);if(t+=4,s!==H)throw x(`Invalid SLVA magic: 0x${s.toString(16)}`,{expectedMagic:`0x${H.toString(16)}`,actualMagic:`0x${s.toString(16)}`});let a=n.getUint32(t,!0);if(t+=4,a!==O)throw x(`Unsupported SLVA version: ${a}`,{expectedVersion:O,actualVersion:a});let c=n.getUint32(t,!0);if(t+=4,t+c>r.byteLength)throw x("Insufficient data to read metadata JSON.",{expectedBytes:c,availableBytes:r.byteLength-t,offset:t});let l=r.subarray(t,t+c);t+=c;let m;try{m=JSON.parse(X(l))}catch(C){throw x(`Failed to parse metadata JSON: ${C instanceof Error?C.message:String(C)}`,{metadataLen:c})}if(t+N>r.byteLength)throw x("Insufficient data to read geometry header.",{expectedBytes:N,availableBytes:r.byteLength-t,offset:t});let f=n.getUint32(t,!0);t+=4;let p=n.getFloat64(t,!0);t+=8;let o=n.getFloat64(t,!0);t+=8;let d=n.getFloat64(t,!0);t+=8;let h=n.getFloat64(t,!0);t+=8;let i=n.getFloat64(t,!0);t+=8;let A=n.getFloat64(t,!0);t+=8;let w=n.getUint32(t,!0);t+=4;let B=(f&T)!==0,E=w*3,g=E*(B?4:2);if(t+g>r.byteLength)throw x("Insufficient data to read vertices.",{expectedBytes:g,availableBytes:r.byteLength-t,offset:t,useFloat32:B,vertexCount:w});let M=r.byteOffset+t,S=B?K(r.buffer,M,E):Z(r.buffer,M,E);if(t+=g,t+4>r.byteLength)throw x("Insufficient data to read index count.",{expectedBytes:4,availableBytes:r.byteLength-t,offset:t});let I=n.getUint32(t,!0);t+=4;let D=I*4;if(t+D>r.byteLength)throw x("Insufficient data to read indices.",{expectedBytes:D,availableBytes:r.byteLength-t,offset:t,indexCount:I});let Y=Q(r.buffer,r.byteOffset+t,I);return{metadata:m,flags:f,vertices:S,indices:Y,origin:[p,o,d],scale:[h,i,A]}}function W(e){return typeof e=="string"?_chunkMZGKJZVPcjs.c.call(void 0, e):e instanceof Uint8Array?e:new Uint8Array(e)}function X(e){if(typeof TextDecoder<"u")return new TextDecoder("utf-8").decode(e);if(typeof globalThis.Buffer<"u")return globalThis.Buffer.from(e).toString("utf-8");throw new (0, _chunkVWOEUM7Ccjs.d)("No UTF-8 decoder available in this environment.",_chunkVWOEUM7Ccjs.c.INVALID_STATE)}function Z(e,r,n){if(n===0)return new Int16Array(0);if(r%2===0)return new Int16Array(e,r,n);let t=new Uint8Array(n*2);return t.set(new Uint8Array(e,r,n*2)),new Int16Array(t.buffer)}function K(e,r,n){if(n===0)return new Float32Array(0);if(r%4===0)return new Float32Array(e,r,n);let t=new Uint8Array(n*4);return t.set(new Uint8Array(e,r,n*4)),new Float32Array(t.buffer)}function Q(e,r,n){if(n===0)return new Uint32Array(0);if(r%4===0)return new Uint32Array(e,r,n);let t=new Uint8Array(n*4);return t.set(new Uint8Array(e,r,n*4)),new Uint32Array(t.buffer)}function x(e,r){return new (0, _chunkVWOEUM7Ccjs.d)(e,_chunkVWOEUM7Ccjs.c.VALIDATION_ERROR,{context:r})}async function _(e,r){let{mergeByMaterial:n=!0,applyTransforms:t=!0,debug:s=!1}=_nullishCoalesce(r, () => ({})),a=s?performance.now():0,c=0;try{let l=performance.now(),m=JSON.parse(e);return c=performance.now()-l,await $(m,{mergeByMaterial:n,applyTransforms:t,debug:s,parseTime:c,perfStart:a})}catch(l){return _chunkVWOEUM7Ccjs.e.call(void 0, ).error("Error parsing mesh batch:",l),[]}}async function $(e,r){let{mergeByMaterial:n=!0,applyTransforms:t=!0,scaleFactor:s=1,debug:a=!1,parseTime:c=0,perfStart:l=a?performance.now():0}=_nullishCoalesce(r, () => ({})),m=0,f=0;try{let p=performance.now(),o=P(e.compressedData);m=performance.now()-p;let d=_nullishCoalesce(o.metadata.materials, () => (e.materials)),h=_nullishCoalesce(o.metadata.groups, () => (e.groups)),i=_nullishCoalesce(o.metadata.sourceComponentId, () => (e.sourceComponentId)),A=(o.flags&T)!==0,w=A?ee(o.vertices,t):q(o.vertices,o.origin,o.scale,t);if(a){let g=oe(e.compressedData),M=o.vertices.byteLength+o.indices.byteLength;_chunkVWOEUM7Ccjs.e.call(void 0, ).debug("Mesh Batch Stats:"),_chunkVWOEUM7Ccjs.e.call(void 0, ).debug(` Materials: ${d.length} | Groups: ${h.length}`),_chunkVWOEUM7Ccjs.e.call(void 0, ).debug(` Vertices: ${o.vertices.length/3} | Indices: ${o.indices.length}`),_chunkVWOEUM7Ccjs.e.call(void 0, ).debug(` Format: ${A?"float32":"int16 quantized"}`),_chunkVWOEUM7Ccjs.e.call(void 0, ).debug(` Blob: ${(g/1024/1024).toFixed(2)} MB | Geometry on wire: ${(M/1024/1024).toFixed(2)} MB`)}let B=performance.now(),E=d.map(te),b=[];for(let g of h)if(n&&g.meshes.length>1){let M=re(g,w,o.indices,E);M.userData.sourceComponentId=_nullishCoalesce(i, () => (null)),b.push(M)}else{let M=ne(g,w,o.indices,E);for(let S of M)S.userData.sourceComponentId=_nullishCoalesce(i, () => (null));b.push(...M)}if(s!==1)for(let g of b)g.scale.set(s,s,s);if(f=performance.now()-B,a){let g=performance.now()-l;_chunkVWOEUM7Ccjs.e.call(void 0, ).debug("Performance:"),c>0&&_chunkVWOEUM7Ccjs.e.call(void 0, ).debug(` Parse JSON: ${c.toFixed(2)}ms`),_chunkVWOEUM7Ccjs.e.call(void 0, ).debug(` Decode binary: ${m.toFixed(2)}ms`),_chunkVWOEUM7Ccjs.e.call(void 0, ).debug(` Create Meshes: ${f.toFixed(2)}ms`),_chunkVWOEUM7Ccjs.e.call(void 0, ).debug(` Total: ${g.toFixed(2)}ms`)}return b}catch(p){return _chunkVWOEUM7Ccjs.e.call(void 0, ).error("Error parsing mesh batch object:",p),[]}}function q(e,r,n,t){let s=new Float32Array(e.length),a=r[0],c=r[1],l=r[2],m=n[0],f=n[1],p=n[2];if(t)for(let o=0;o<e.length;o+=3){let d=a+(e[o]+32767)*m,h=c+(e[o+1]+32767)*f,i=l+(e[o+2]+32767)*p;s[o]=d,s[o+1]=i,s[o+2]=-h}else for(let o=0;o<e.length;o+=3)s[o]=a+(e[o]+32767)*m,s[o+1]=c+(e[o+1]+32767)*f,s[o+2]=l+(e[o+2]+32767)*p;return s}function ee(e,r){if(!r)return e;let n=new Float32Array(e.length);for(let t=0;t<e.length;t+=3){let s=e[t],a=e[t+1],c=e[t+2];n[t]=s,n[t+1]=c,n[t+2]=-a}return n}function te(e){let r=_chunk5465MDT4cjs.c.call(void 0, e.color);return new y.MeshPhysicalMaterial({color:r,metalness:e.metalness,roughness:e.roughness,opacity:e.opacity,transparent:e.transparent,side:y.DoubleSide,polygonOffset:!0,polygonOffsetFactor:.5,polygonOffsetUnits:.5,depthWrite:!0,depthTest:!0})}function re(e,r,n,t){let s=0,a=0;for(let i of e.meshes)s+=i.vertexCount,a+=i.indexCount;let c=new Float32Array(s*3),l=new Uint32Array(a),m=0,f=0;for(let i of e.meshes){let A=i.vertexStart*3,w=i.vertexCount*3;c.set(r.subarray(A,A+w),m*3);let B=n.subarray(i.indexStart,i.indexStart+i.indexCount),E=m-i.vertexStart;if(E===0)l.set(B,f);else for(let b=0;b<B.length;b++)l[f+b]=B[b]+E;m+=i.vertexCount,f+=i.indexCount}let p=new y.BufferGeometry;p.setAttribute("position",new y.BufferAttribute(c,3)),p.setIndex(new y.BufferAttribute(l,1)),p.computeVertexNormals();let o=new y.Mesh(p,t[e.materialId]),d=e.meshes[0],h=e.meshes.map(i=>i.name).filter(i=>i&&i.length>0);return o.name=h.length>0?h[0]:`merged_material_${e.materialId}`,o.castShadow=!0,o.receiveShadow=!0,o.userData={name:o.name,layer:_nullishCoalesce(_optionalChain([d, 'optionalAccess', _2 => _2.layer]), () => ("")),originalIndex:_nullishCoalesce(_optionalChain([d, 'optionalAccess', _3 => _3.originalIndex]), () => (0)),metadata:_nullishCoalesce(_optionalChain([d, 'optionalAccess', _4 => _4.metadata]), () => ({})),mergedFrom:e.meshes.slice(1).map(i=>({name:i.name,layer:i.layer,originalIndex:i.originalIndex}))},o}function ne(e,r,n,t){let s=[];for(let a of e.meshes){let c=a.vertexStart*3,l=a.vertexCount*3,m=r.slice(c,c+l),f=n.subarray(a.indexStart,a.indexStart+a.indexCount),p=new Uint32Array(f.length),o=a.vertexStart;for(let i=0;i<f.length;i++)p[i]=f[i]-o;let d=new y.BufferGeometry;d.setAttribute("position",new y.BufferAttribute(m,3)),d.setIndex(new y.BufferAttribute(p,1)),d.computeVertexNormals();let h=new y.Mesh(d,t[e.materialId]);h.name=a.name,h.userData={name:a.name,layer:_nullishCoalesce(a.layer, () => ("")),originalIndex:a.originalIndex,metadata:_nullishCoalesce(a.metadata, () => ({}))},h.castShadow=!0,h.receiveShadow=!0,s.push(h)}return s}function oe(e){return Math.floor(e.length*3/4)}var z={Millimeters:1/1e3,Centimeters:1/100,Meters:1,Inches:1/39.37,Feet:1/3.28084},ae="Display";async function se(e,r){let n=performance.now(),t=[],{allowScaling:s=!0,allowAutoPosition:a=!0,debug:c=!1,parsing:l={}}=_nullishCoalesce(r, () => ({}));try{let m=s?ie(e.modelunits):1;return await ce(e,t,m,l,c),a&&le(t),t}catch(m){throw ue(m,t),m}finally{c&&pe(n)}}function ie(e){return _nullishCoalesce(z[e], () => (1))}async function ce(e,r,n,t,s){for(let a of e.values){let c=a.InnerTree;for(let l in c){let m=c[l];m&&await me(m,r,n,t,s)}}}async function me(e,r,n,t,s){for(let a of e)if(a.type.includes(ae)){let c={mergeByMaterial:!0,applyTransforms:!0,debug:!1,...t},l=await _(a.data,c);if(n!==1)for(let m of l)m.scale.set(n,n,n);r.push(...l),s&&_chunkVWOEUM7Ccjs.e.call(void 0, ).debug(`Extracted ${l.length} meshes from batch`)}}function le(e){if(e.length===0)return;let n=_chunk5465MDT4cjs.e.call(void 0, e).min.y;_chunk5465MDT4cjs.d.call(void 0, e,n)}function ue(e,r){_chunkVWOEUM7Ccjs.e.call(void 0, ).error("An unexpected error occurred:",e),fe(r)}function fe(e){for(let r of e)r.geometry&&r.geometry.dispose(),r.material&&(Array.isArray(r.material)?r.material.forEach(n=>n.dispose()):r.material.dispose())}function pe(e){let r=performance.now()-e;_chunkVWOEUM7Ccjs.e.call(void 0, ).info("Time to process meshes:",`${r.toFixed(2)}ms`)}exports.BINARY_MESH_MAGIC = H; exports.BINARY_MESH_VERSION = O; exports.FLAG_FLOAT32 = T; exports.Materials = _chunk5465MDT4cjs.f; exports.SCALE_FACTORS = z; exports.applyOffset = _chunk5465MDT4cjs.d; exports.computeCombinedBoundingBox = _chunk5465MDT4cjs.e; exports.getThreeMeshesFromComputeResponse = se; exports.initThree = _chunk5465MDT4cjs.a; exports.parseBinaryMeshBatch = P; exports.parseColor = _chunk5465MDT4cjs.c; exports.parseMeshBatch = _; exports.parseMeshBatchObject = $; exports.updateScene = _chunk5465MDT4cjs.b;
|
|
2
|
-
//# sourceMappingURL=visualization-JYNKROSH.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/selva-compute/selva-compute/dist/visualization-JYNKROSH.cjs","../src/features/visualization/webdisplay/batch-parser.ts","../src/features/visualization/webdisplay/binary-parser.ts"],"names":["BINARY_MESH_MAGIC","BINARY_MESH_VERSION","FLAG_FLOAT32","HEADER_PREAMBLE_BYTES","GEOMETRY_HEADER_BYTES","parseBinaryMeshBatch","input","bytes","toUint8Array","view","fail","offset","magic"],"mappings":"AAAA,2/BAAwC,wDAA4E,wDAAuD,uECApJ,ICUVA,CAAAA,CAAoB,UAAA,CAEpBC,CAAAA,+BAAsB,CAAA,CAEtBC,CAAAA,wBAAe,CAAA,CAEtBC,CAAAA,CAAwB,EAAA,CACxBC,CAAAA,CACL,EAAA,CAoEM,SAASC,CAAAA,CACfC,CAAAA,CACwB,CACxB,IAAMC,CAAAA,CAAQC,CAAAA,CAAaF,CAAK,CAAA,CAC1BG,CAAAA,CAAO,IAAI,QAAA,CAASF,CAAAA,CAAM,MAAA,CAAQA,CAAAA,CAAM,UAAA,CAAYA,CAAAA,CAAM,UAAU,CAAA,CAE1E,EAAA,CAAIA,CAAAA,CAAM,UAAA,CAAaJ,CAAAA,CACtB,MAAMO,CAAAA,CAAK,wCAAA,CAA0C,CACpD,aAAA,CAAeP,CAAAA,CACf,cAAA,CAAgBI,CAAAA,CAAM,UACvB,CAAC,CAAA,CAGF,IAAII,CAAAA,CAAS,CAAA,CAEPC,CAAAA,CAAQH,CAAAA,CAAK,SAAA,CAAUE,CAAAA,CAAQ,CAAA,CAAI,CAAA,CAEzC,EAAA,CADAA,CAAAA,EAAU,CAAA,CACNC,CAAAA,GAAUZ,CAAAA,CACb,MAAMU,CAAAA,CAAK,CAAA,sBAAA,EAAyBE,CAAAA,CAAM,QAAA,CAAS,EAAE,CAAC,CAAA,CAAA","file":"/home/runner/work/selva-compute/selva-compute/dist/visualization-JYNKROSH.cjs","sourcesContent":[null,"import * as THREE from 'three';\n\nimport { parseColor } from '../threejs/three-helpers';\nimport { getLogger } from '@/core';\n\nimport { FLAG_FLOAT32, parseBinaryMeshBatch } from './binary-parser';\n\nimport type { MeshBatch, MaterialGroup, SerializableMaterial } from './types';\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 * @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 */\nexport async function parseMeshBatch(\n\tbatchJson: string,\n\toptions?: {\n\t\t/** Merge meshes with same material into single geometry*/\n\t\tmergeByMaterial?: boolean;\n\t\t/** Apply coordinate system transformations */\n\t\tapplyTransforms?: boolean;\n\t\t/** Enable performance monitoring */\n\t\tdebug?: boolean;\n\t}\n): Promise<THREE.Mesh[]> {\n\tconst { mergeByMaterial = true, applyTransforms = true, debug = false } = options ?? {};\n\n\tconst perfStart = debug ? performance.now() : 0;\n\tlet parseTime = 0;\n\n\ttry {\n\t\tconst parseStart = performance.now();\n\t\tconst batch: MeshBatch = JSON.parse(batchJson);\n\t\tparseTime = performance.now() - parseStart;\n\n\t\treturn await parseMeshBatchObject(batch, {\n\t\t\tmergeByMaterial,\n\t\t\tapplyTransforms,\n\t\t\tdebug,\n\t\t\tparseTime,\n\t\t\tperfStart\n\t\t});\n\t} catch (error) {\n\t\tgetLogger().error('Error parsing mesh batch:', error);\n\t\treturn [];\n\t}\n}\n\n/**\n * Parses a MeshBatch object and creates Three.js meshes.\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 * @param batch - MeshBatch object\n * @param options - Rendering options\n * @returns Promise resolving to array of Three.js mesh objects\n */\nexport async function parseMeshBatchObject(\n\tbatch: MeshBatch,\n\toptions?: {\n\t\t/** Merge meshes with same material into single geometry*/\n\t\tmergeByMaterial?: boolean;\n\t\t/** Apply coordinate system transformations */\n\t\tapplyTransforms?: boolean;\n\t\t/** Scale factor to apply to meshes (e.g., for unit conversion) */\n\t\tscaleFactor?: number;\n\t\t/** Enable performance monitoring */\n\t\tdebug?: boolean;\n\t\t/** Parse time (optional, for debugging) */\n\t\tparseTime?: number;\n\t\t/** Performance start time (optional, for debugging) */\n\t\tperfStart?: number;\n\t}\n): Promise<THREE.Mesh[]> {\n\tconst {\n\t\tmergeByMaterial = true,\n\t\tapplyTransforms = true,\n\t\tscaleFactor = 1,\n\t\tdebug = false,\n\t\tparseTime = 0,\n\t\tperfStart = debug ? performance.now() : 0\n\t} = options ?? {};\n\n\tlet decodeTime = 0;\n\tlet meshCreateTime = 0;\n\n\ttry {\n\t\tconst decodeStart = performance.now();\n\t\tconst parsed = parseBinaryMeshBatch(batch.compressedData);\n\t\tdecodeTime = performance.now() - decodeStart;\n\n\t\t// Prefer materials/groups from the blob's embedded metadata — that's the source of truth\n\t\t// the C# writer emits. Fall back to the outer envelope for resilience (e.g. if a future\n\t\t// transport drops them from the blob's metadata to save bytes).\n\t\tconst materialsSrc = parsed.metadata.materials ?? batch.materials;\n\t\tconst groups = parsed.metadata.groups ?? batch.groups;\n\t\tconst sourceComponentId = parsed.metadata.sourceComponentId ?? batch.sourceComponentId;\n\n\t\tconst isFloat32 = (parsed.flags & FLAG_FLOAT32) !== 0;\n\n\t\t// Dequantize once up-front into a single Float32Array. Downstream code (per-group merging,\n\t\t// computeVertexNormals, ground-offset, scaleFactor) all expect world-unit floats, and a\n\t\t// single linear pass over the int16 buffer is far cheaper than the legacy gunzip + base64\n\t\t// path. The Z-up -> Y-up rotation, when requested, is folded into the same pass.\n\t\tconst worldVertices = isFloat32\n\t\t\t? maybeRotateFloat32Vertices(parsed.vertices as Float32Array, applyTransforms)\n\t\t\t: dequantizeInt16(\n\t\t\t\t\tparsed.vertices as Int16Array,\n\t\t\t\t\tparsed.origin,\n\t\t\t\t\tparsed.scale,\n\t\t\t\t\tapplyTransforms\n\t\t\t\t);\n\n\t\tif (debug) {\n\t\t\tconst blobBytes = approximateBase64DecodedBytes(batch.compressedData);\n\t\t\tconst wireBytes = parsed.vertices.byteLength + parsed.indices.byteLength;\n\t\t\tgetLogger().debug('Mesh Batch Stats:');\n\t\t\tgetLogger().debug(` Materials: ${materialsSrc.length} | Groups: ${groups.length}`);\n\t\t\tgetLogger().debug(\n\t\t\t\t` Vertices: ${parsed.vertices.length / 3} | Indices: ${parsed.indices.length}`\n\t\t\t);\n\t\t\tgetLogger().debug(` Format: ${isFloat32 ? 'float32' : 'int16 quantized'}`);\n\t\t\tgetLogger().debug(\n\t\t\t\t` Blob: ${(blobBytes / 1024 / 1024).toFixed(2)} MB | Geometry on wire: ${(wireBytes / 1024 / 1024).toFixed(2)} MB`\n\t\t\t);\n\t\t}\n\n\t\tconst meshCreateStart = performance.now();\n\t\tconst materials = materialsSrc.map(createMaterial);\n\n\t\tconst meshes: THREE.Mesh[] = [];\n\n\t\tfor (const group of groups) {\n\t\t\tif (mergeByMaterial && group.meshes.length > 1) {\n\t\t\t\tconst mergedMesh = createMergedMesh(group, worldVertices, parsed.indices, materials);\n\t\t\t\tmergedMesh.userData.sourceComponentId = sourceComponentId ?? null;\n\t\t\t\tmeshes.push(mergedMesh);\n\t\t\t} else {\n\t\t\t\tconst individualMeshes = createIndividualMeshes(\n\t\t\t\t\tgroup,\n\t\t\t\t\tworldVertices,\n\t\t\t\t\tparsed.indices,\n\t\t\t\t\tmaterials\n\t\t\t\t);\n\t\t\t\tfor (const mesh of individualMeshes) {\n\t\t\t\t\tmesh.userData.sourceComponentId = sourceComponentId ?? null;\n\t\t\t\t}\n\t\t\t\tmeshes.push(...individualMeshes);\n\t\t\t}\n\t\t}\n\n\t\tif (scaleFactor !== 1) {\n\t\t\tfor (const mesh of meshes) {\n\t\t\t\tmesh.scale.set(scaleFactor, scaleFactor, scaleFactor);\n\t\t\t}\n\t\t}\n\n\t\tmeshCreateTime = performance.now() - meshCreateStart;\n\n\t\tif (debug) {\n\t\t\tconst totalTime = performance.now() - perfStart;\n\t\t\tgetLogger().debug('Performance:');\n\t\t\tif (parseTime > 0) getLogger().debug(` Parse JSON: ${parseTime.toFixed(2)}ms`);\n\t\t\tgetLogger().debug(` Decode binary: ${decodeTime.toFixed(2)}ms`);\n\t\t\tgetLogger().debug(` Create Meshes: ${meshCreateTime.toFixed(2)}ms`);\n\t\t\tgetLogger().debug(` Total: ${totalTime.toFixed(2)}ms`);\n\t\t}\n\n\t\treturn meshes;\n\t} catch (error) {\n\t\tgetLogger().error('Error parsing mesh batch object:', error);\n\t\treturn [];\n\t}\n}\n\n// ============================================================================\n// DEQUANTIZATION\n// ============================================================================\n\n/**\n * Reconstructs world-unit float32 positions from int16 quantized values.\n *\n * Mirrors the encoder formula: `world = origin + (q + 32767) * scale`. When\n * `applyCoordinateTransform=true` we fold the Rhino Z-up -> Three Y-up shuffle into the same pass\n * (`(x, y, z) -> (x, z, -y)`), saving a second walk over the buffer.\n */\nfunction dequantizeInt16(\n\tq: Int16Array,\n\torigin: [number, number, number],\n\tscale: [number, number, number],\n\tapplyCoordinateTransform: 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\tif (applyCoordinateTransform) {\n\t\t// Rotate -90 deg around X: (x, y, z) -> (x, z, -y)\n\t\tfor (let i = 0; i < q.length; i += 3) {\n\t\t\tconst wx = ox + (q[i]! + 32767) * sx;\n\t\t\tconst wy = oy + (q[i + 1]! + 32767) * sy;\n\t\t\tconst wz = oz + (q[i + 2]! + 32767) * sz;\n\t\t\tout[i] = wx;\n\t\t\tout[i + 1] = wz;\n\t\t\tout[i + 2] = -wy;\n\t\t}\n\t} else {\n\t\tfor (let i = 0; i < q.length; i += 3) {\n\t\t\tout[i] = ox + (q[i]! + 32767) * sx;\n\t\t\tout[i + 1] = oy + (q[i + 1]! + 32767) * sy;\n\t\t\tout[i + 2] = oz + (q[i + 2]! + 32767) * sz;\n\t\t}\n\t}\n\n\treturn out;\n}\n\n/**\n * For float32 batches: when no transform is needed we can pass through the parser's view; the\n * caller doesn't mutate it. When the rotation is needed we have to allocate.\n */\nfunction maybeRotateFloat32Vertices(\n\tvertices: Float32Array,\n\tapplyCoordinateTransform: boolean\n): Float32Array {\n\tif (!applyCoordinateTransform) return vertices;\n\n\tconst out = new Float32Array(vertices.length);\n\tfor (let i = 0; i < vertices.length; i += 3) {\n\t\tconst x = vertices[i]!;\n\t\tconst y = vertices[i + 1]!;\n\t\tconst z = vertices[i + 2]!;\n\t\tout[i] = x;\n\t\tout[i + 1] = z;\n\t\tout[i + 2] = -y;\n\t}\n\treturn out;\n}\n\n// ============================================================================\n// MATERIAL CONSTRUCTION\n// ============================================================================\n\nfunction createMaterial(matData: SerializableMaterial): THREE.MeshPhysicalMaterial {\n\tconst color = parseColor(matData.color);\n\n\treturn 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\tside: 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\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: Uint32Array,\n\tmaterials: THREE.Material[]\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\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\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\tif (indexShift === 0) {\n\t\t\tmergedIndices.set(indicesSlice, indexWriteCursor);\n\t\t} else {\n\t\t\tfor (let i = 0; i < indicesSlice.length; i++) {\n\t\t\t\tmergedIndices[indexWriteCursor + i] = indicesSlice[i]! + indexShift;\n\t\t\t}\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\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\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: Uint32Array,\n\tmaterials: THREE.Material[]\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\trebasedIndices[i] = indicesSlice[i]! - 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\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\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 { decodeBase64ToBinary } from '@/core/utils/encoding';\nimport { RhinoComputeError, ErrorCodes } from '@/core/errors';\n\nimport type { MaterialGroup, SerializableMaterial } from './types';\n\n// ============================================================================\n// WIRE FORMAT CONSTANTS\n// ============================================================================\n\n/** \"SLVA\" little-endian. */\nexport const BINARY_MESH_MAGIC = 0x41564c53;\n/** Bumped on any wire-layout change. */\nexport const BINARY_MESH_VERSION = 1;\n/** Bit 0 of the geometry flags word: 0 = int16 quantized, 1 = float32 raw. */\nexport const FLAG_FLOAT32 = 0x1;\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// PARSED TYPES\n// ============================================================================\n\n/**\n * Metadata JSON embedded inside the binary blob.\n *\n * This is the same shape as a `MeshBatch` minus the `compressedData` field (the blob is opaque to\n * its own metadata header). Kept separate from the public `MeshBatch` type because the blob's\n * 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` are typed-array views over the original `ArrayBuffer` — zero copies.\n * The consumer is responsible for not mutating the underlying buffer if it cares about safety,\n * or for calling `.slice()` to detach.\n */\nexport interface ParsedBinaryMeshBatch {\n\tmetadata: BinaryMeshMetadata;\n\tflags: number;\n\tvertices: Int16Array | Float32Array;\n\tindices: Uint32Array;\n\torigin: [number, number, number];\n\tscale: [number, number, number];\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 1)\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 * [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]\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 * @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\tconst bytes = 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 !== BINARY_MESH_VERSION) {\n\t\tthrow fail(`Unsupported SLVA version: ${version}`, {\n\t\t\texpectedVersion: 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 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\tconst verticesView = useFloat32\n\t\t? readFloat32Vertices(bytes.buffer, absoluteOffset, componentCount)\n\t\t: readInt16Vertices(bytes.buffer, absoluteOffset, componentCount);\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 indicesByteLength = indexCount * 4;\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});\n\t}\n\n\tconst indicesView = readUint32Indices(bytes.buffer, bytes.byteOffset + offset, indexCount);\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};\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\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 readUint32Indices(\n\tbuffer: ArrayBufferLike,\n\tbyteOffset: number,\n\tcount: number\n): 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\nfunction fail(message: string, context: Record<string, unknown>): RhinoComputeError {\n\treturn new RhinoComputeError(message, ErrorCodes.VALIDATION_ERROR, { context });\n}\n"]}
|
|
File without changes
|