@forgeax/engine-gltf 0.1.27 → 0.1.28
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/README.md +12 -10
- package/dist/cli-gltf.d.ts.map +1 -1
- package/dist/cli-gltf.mjs +13 -13
- package/dist/cli-gltf.mjs.map +1 -1
- package/dist/importer-entry.mjs +3 -3
- package/dist/importer-entry.mjs.map +1 -1
- package/dist/index.mjs +3 -3
- package/dist/index.mjs.map +1 -1
- package/dist/node-file-entry.mjs +3 -3
- package/dist/node-file-entry.mjs.map +1 -1
- package/package.json +13 -16
- package/src/__tests__/cli-gltf.integration.test.ts +1 -1
- package/src/__tests__/gltf.unit.test.ts +1 -1
- package/src/cli-gltf.ts +16 -18
- package/src/errors.ts +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors.ts","../src/accessor/decode-accessor.ts","../src/accessor/decode-color.ts","../src/check-extensions.ts","../src/data-uri.ts","../src/lod/parse-lod.ts","../src/material/parse-material.ts","../src/meshopt-decode.ts","../src/node-path.ts","../src/parse-animation.ts","../src/parse-gltf-header.ts","../src/parse-glb-chunks.ts","../src/parse-skin.ts","../src/transform.ts","../src/parse-gltf.ts","../src/node-file-entry.ts"],"names":["tuple3","n","mat4","vec3","quat"],"mappings":";;;;;AA2BO,IAAM,kBAAA,GAAqB,CAAC,YAAA,EAAc,WAAA,EAAa,SAAS,CAAA;AAGhE,IAAM,oBAAA,GAAuB,CAAC,MAAA,EAAQ,YAAA,EAAc,cAAc,aAAa,CAAA;AA2OtF,IAAM,eAAA,GAAkB;AAAA,EACtB,uBAAA,EAAyB;AAAA,IACvB,QAAA,EACE,sFAAA;AAAA,IACF,IAAA,EAAM;AAAA,GACR;AAAA,EACA,0BAAA,EAA4B;AAAA,IAC1B,QAAA,EAAU,yBAAA;AAAA,IACV,IAAA,EAAM;AAAA,GACR;AAAA,EACA,2BAAA,EAA6B;AAAA,IAC3B,QAAA,EAAU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AQ,CAAA;AAC7C,EAAA,IAAI,CAAE,MAAM,UAAA,CAAW,EAAA,EAAI,gBAAgB,CAAA,EAAI;AAC7C,IAAA,OAAO,IAAI,OAAA,CAAQ,mBAAA,EAAqB,EAAE,QAAA,EAAU,gBAAA,EAAkB,CAAC,CAAA;AAAA,EACzE;AACA,EAAA,MAAM,GAAA,GAAM,MAAM,EAAA,CAAG,QAAA,CAAS,QAAQ,CAAA;AACtC,EAAA,MAAM,EAAA,GAAK,IAAI,MAAA,CAAO,KAAA,CAAM,IAAI,UAAA,EAAY,GAAA,CAAI,UAAA,GAAa,GAAA,CAAI,UAAU,CAAA;AAC3E,EAAA,OAAO,QAAA,CAAS,IAAI,QAAQ,CAAA;AAC9B","file":"node-file-entry.mjs","sourcesContent":["// errors.ts - GltfError definitions SSOT + factory.\n//\n// Per requirements AC-28 + plan-strategy D-5 (DIP), GltfErrorCode +\n// GltfErrorDetail + GltfError + GLTF_ERROR_HINTS are the glTF importer's\n// own error SSOT, local to this package. They were migrated here from\n// @forgeax/engine-types in feat-20260615-fbx-importer-via-sdk M1 (t7).\n//\n// Producers MUST go through `gltfErr` so any GltfErrorCode addition that\n// lacks a matching detail variant fails at the call site (TS exhaustive\n// per-arm).\n//\n// Result<T, E> + ok / err live in `@forgeax/engine-types` (tweak-20260612-result-\n// into-types) and are re-exported for ergonomic single-import from this module.\n\nexport {\n createMaterialError,\n err,\n type GltfMaterialUvSetMissingDetail,\n type MaterialError,\n ok,\n type Result,\n} from '@forgeax/engine-types';\n\nimport type { VertexAttributePackDetail } from '@forgeax/engine-types';\n\n// === Meshopt vocabulary owner ===\n\nexport const GLTF_MESHOPT_MODES = ['ATTRIBUTES', 'TRIANGLES', 'INDICES'] as const;\nexport type GltfMeshoptMode = (typeof GLTF_MESHOPT_MODES)[number];\n\nexport const GLTF_MESHOPT_FILTERS = ['NONE', 'OCTAHEDRAL', 'QUATERNION', 'EXPONENTIAL'] as const;\nexport type GltfMeshoptFilter = (typeof GLTF_MESHOPT_FILTERS)[number];\n\n// === Per-code detail shapes (22 interfaces, 1 discriminated union) ===\n\n/** `gltf-malformed-header` payload: GLB magic / chunk header surface. */\nexport interface GltfMalformedHeaderDetail {\n readonly filePath: string;\n readonly byteOffset: number;\n readonly magic?: number;\n}\n\n/** `gltf-version-unsupported` payload: surfaced asset.version literal. */\nexport interface GltfVersionUnsupportedDetail {\n readonly filePath: string;\n readonly actualVersion: string;\n}\n\n/** `gltf-buffer-out-of-bounds` payload: accessor + bufferView coordinates. */\nexport interface GltfBufferOutOfBoundsDetail {\n readonly accessor: number;\n readonly byteOffset: number;\n readonly byteLength: number;\n readonly bufferIndex: number;\n}\n\n/** `gltf-extension-unsupported` payload: extension name + which array it appeared in. */\nexport interface GltfExtensionUnsupportedDetail {\n readonly extension: string;\n readonly source: 'extensionsRequired' | 'extensionsUsed';\n}\n\nexport interface GltfLodInvalidDetail {\n readonly rootNode: number;\n readonly ids: readonly number[];\n readonly reason: 'missing-node' | 'duplicate-node' | 'not-integer' | 'coverage';\n}\n\nexport interface GltfMaterialTransmissionInvalidDetail {\n readonly extension: 'KHR_materials_transmission' | 'KHR_materials_ior' | 'KHR_materials_volume';\n readonly field: string;\n readonly reason: 'type' | 'range' | 'non-finite' | 'blend';\n readonly actual?: unknown;\n}\n\nexport interface GltfMaterialPhysicalInvalidDetail {\n readonly extension:\n | 'KHR_materials_clearcoat'\n | 'KHR_materials_anisotropy'\n | 'KHR_materials_sheen'\n | 'KHR_materials_iridescence'\n | 'KHR_materials_specular';\n readonly field: string;\n readonly reason: 'type' | 'range' | 'non-finite';\n readonly actual?: unknown;\n}\n\n/** `gltf-accessor-type-mismatch` payload: 4-member closed reason discriminator. */\nexport interface GltfAccessorTypeMismatchDetail {\n readonly accessorIndex: number;\n readonly reason: 'sparse' | 'morph' | 'interleaved' | 'unknownComponentType';\n}\n\n/** `gltf-texture-load-failed` payload: URI that failed to load. */\nexport interface GltfTextureLoadFailedDetail {\n readonly uri: string;\n}\n\n/** `gltf-meta-missing` payload: source path + expected sidecar path. */\nexport interface GltfMetaMissingDetail {\n readonly filePath: string;\n readonly expectedMetaPath: string;\n}\n\n/** `gltf-image-mime-unsupported` payload: rejected MIME type. */\nexport interface GltfImageMimeUnsupportedDetail {\n readonly mimeType: string;\n}\n\n/** `gltf-skin-joint-count-exceeded` payload: skin joint count exceeds MAX_JOINTS. */\nexport interface GltfSkinJointCountExceededDetail {\n readonly skinIndex: number;\n readonly jointCount: number;\n readonly maxJoints: number;\n}\n\n/** `gltf-animation-cubicspline-unsupported` payload: CUBICSPLINE sampler. */\nexport interface GltfAnimationCubicsplineUnsupportedDetail {\n readonly animationIndex: number;\n readonly samplerIndex: number;\n}\n\n/** `gltf-morph-unsupported` payload: channel targeting morph weights. */\nexport interface GltfMorphUnsupportedDetail {\n readonly animationIndex: number;\n readonly channelIndex: number;\n readonly nodeIndex: number;\n}\n\n/** `gltf-skin-joint-name-missing` payload: joint node has no name. */\nexport interface GltfSkinJointNameMissingDetail {\n readonly reason: 'name-missing' | 'hierarchy-cycle';\n readonly skinIndex: number;\n readonly jointPathIndex: number;\n readonly nodeIndex: number;\n}\n\n/** `gltf-image-extract-failed` payload: image bytes extraction failure. */\nexport interface GltfImageExtractFailedDetail {\n readonly imageIndex: number;\n readonly source: 'bufferView' | 'data-uri' | 'external-uri';\n readonly reason: string;\n}\n\n/** `gltf-instancing-count-mismatch` payload: TRS accessor count disagreement. */\nexport interface GltfInstancingCountMismatchDetail {\n readonly nodeIndex: number;\n readonly accessor: 'TRANSLATION' | 'ROTATION' | 'SCALE';\n readonly expectedCount: number;\n readonly actualCount: number;\n}\n\n/** `gltf-skin-attr-asymmetric` payload: JOINTS_0/WEIGHTS_0 paired-presence fail. */\nexport interface GltfSkinAttrAsymmetricDetail {\n readonly meshIndex: number;\n readonly primitiveIndex: number;\n readonly hasJoints: boolean;\n readonly hasWeights: boolean;\n}\n\nexport interface GltfAnimationTargetInvalidDetail {\n readonly reason:\n | 'name-missing'\n | 'path-invalid'\n | 'path-duplicate'\n | 'path-not-found'\n | 'hierarchy-cycle'\n | 'id-collision';\n readonly animationIndex: number;\n readonly channelIndex: number;\n readonly nodeIndex: number;\n}\n\nexport interface GltfMeshoptDecoderRequiredDetail {\n readonly bufferView: number;\n readonly actual: 'required' | 'compressed-only';\n readonly hasCoreFallback: boolean;\n}\n\nexport interface GltfMeshoptDecodeFailedDetail {\n readonly bufferView: number;\n readonly actual: string;\n readonly mode: GltfMeshoptMode;\n readonly filter: GltfMeshoptFilter;\n}\n\nexport interface GltfMorphInvalidDetail {\n readonly meshIndex: number;\n readonly primitiveIndex: number;\n readonly reason:\n | 'target-count-exceeded'\n | 'attribute-count-exceeded'\n | 'attribute-length-mismatch'\n | 'weights-length-mismatch'\n | 'sparse-or-unsupported-accessor';\n readonly targetCount: number;\n readonly attributeCount: number;\n readonly vertexCount: number;\n}\n\nexport interface GltfColorAccessorUnsupportedDetail {\n readonly semantic: 'COLOR_0';\n readonly accessorIndex: number;\n readonly reason: 'component' | 'type' | 'normalized' | 'sparse' | 'morph';\n readonly expectedType?: string;\n readonly expectedComponent?: string;\n readonly expectedNormalized?: boolean;\n}\n\nexport interface GltfColorAccessorMalformedDetail {\n readonly semantic: 'COLOR_0';\n readonly accessorIndex: number;\n readonly reason: 'count' | 'bounds' | 'finite' | 'range' | 'reference';\n readonly expectedCount?: string;\n readonly expectedRange?: string;\n}\n\n/** Bridge-side mesh merge failure after the parser has produced a GltfMeshIr. */\nexport type GltfMeshBridgeInvalidDetail =\n | {\n readonly reason: 'empty-input';\n readonly primitiveCount: 0;\n }\n | {\n readonly reason: 'morph-count-mismatch';\n readonly meshIndex: number;\n readonly primitiveIndex: number;\n readonly expectedTargetCount: number;\n readonly actualTargetCount: number;\n }\n | {\n readonly reason: 'color-cardinality';\n readonly semantic: 'COLOR_0';\n readonly meshIndex: number;\n readonly primitiveIndex: number;\n readonly vertexCount: number;\n readonly expectedLength: number;\n readonly actualLength: number;\n }\n | {\n readonly reason: 'layout-invalid';\n readonly meshIndex: number;\n readonly cause: VertexAttributePackDetail;\n };\n\n/** Discriminated detail family unifying all 19 GltfError variants. */\nexport type GltfErrorDetail = DetailFor[GltfErrorCode];\n\n// === GltfErrorCode and GltfError discriminated union ===\n\nexport type GltfErrorCode = keyof DetailFor;\n\nexport type GltfError = {\n readonly [C in GltfErrorCode]: {\n readonly code: C;\n readonly expected: string;\n readonly hint: string;\n readonly detail: DetailFor[C];\n };\n}[GltfErrorCode];\n\n// === Private per-code policy owner ===\n\ntype GltfErrorPolicy = { readonly expected: string; readonly hint: string };\n\nconst gltfErrorPolicy = {\n 'gltf-malformed-header': {\n expected:\n 'GLB 12-byte header (magic 0x46546C67 + version=2 + length) plus mandatory JSON chunk',\n hint: 'verify .glb is not truncated; rerun: forgeax-engine-remote-gltf import <path>',\n },\n 'gltf-version-unsupported': {\n expected: 'asset.version === \"2.0\"',\n hint: 'asset.version must be \"2.0\"; v1 or v3 not supported',\n },\n 'gltf-buffer-out-of-bounds': {\n expected: 'accessor byte range within bufferView.byteLength',\n hint: 'rebuild .gltf with valid bufferViews; check accessor index; ensure accessor.byteOffset + EFFECTIVE_STRIDE * (count - 1) + element_size <= bufferView.byteLength',\n },\n 'gltf-extension-unsupported': {\n expected:\n 'extension listed in the supported allowlist (see EXTENSION_ALLOWLIST in @forgeax/engine-gltf)',\n hint: 'remove the unsupported required extension or use a supported glTF extension; extensionsUsed-only entries remain diagnostic',\n },\n 'gltf-lod-invalid': {\n expected: 'MSFT_lod ids to reference unique existing node indices with valid coverage',\n hint: 'repair the MSFT_lod node relation or remove it from extensionsRequired before re-importing',\n },\n 'gltf-material-transmission-invalid': {\n expected: 'KHR transmission, IOR, and volume values are finite and within their glTF ranges',\n hint: 'repair the named glTF material extension value and re-import the source',\n },\n 'gltf-material-physical-invalid': {\n expected:\n 'KHR clearcoat, anisotropy, sheen, iridescence, and specular values are finite and within their glTF ranges',\n hint: 'repair the named physical material extension value and re-import the source',\n },\n 'gltf-accessor-type-mismatch': {\n expected: 'dense fixed-stride accessor with supported componentType',\n hint: 'sparse: see feat-future-gltf-sparse-accessor; morph: see feat-future-gltf-morph; interleaved: see feat-future-gltf-mesh-multi-section',\n },\n 'gltf-texture-load-failed': {\n expected: 'externalLoader resolved the URI into an ArrayBuffer without throwing',\n hint: 'check sidecar meta.json + textures/ directory + vite-plugin-pack /__pack/lookup route',\n },\n 'gltf-meta-missing': {\n expected: \"sidecar <source>.meta.json (importer: 'gltf') present in same directory\",\n hint: 'run: forgeax-engine-remote-gltf import <path>',\n },\n 'gltf-instancing-count-mismatch': {\n expected: 'all instance attribute accessors share the same count',\n hint: 'EXT_mesh_gpu_instancing requires TRANSLATION/ROTATION/SCALE accessors to share count; see https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/EXT_mesh_gpu_instancing/README.md#extending-nodes-with-instance-attributes',\n },\n 'gltf-image-mime-unsupported': {\n expected: 'image/mimeType is image/jpeg or image/png',\n hint: 'convert to JPG/PNG via external tool; only image/jpeg and image/png are supported',\n },\n 'gltf-skin-joint-count-exceeded': {\n expected: 'skin.joints.length <= MAX_JOINTS (256)',\n hint: 'reduce joint count below MAX_JOINTS (256) or see OOS-skin-max-joints',\n },\n 'gltf-animation-cubicspline-unsupported': {\n expected: 'animation sampler interpolation is LINEAR or STEP',\n hint: 'see OOS-skin-cubicspline; convert CUBICSPLINE to LINEAR/STEP in DCC tool',\n },\n 'gltf-morph-unsupported': {\n expected: 'animation channel target path is one of translation, rotation, scale, or weights',\n hint: 'animation target path must be translation, rotation, scale, or weights',\n },\n 'gltf-skin-joint-name-missing': {\n expected: 'every joint node has a non-empty name and belongs to an acyclic hierarchy',\n hint: 'ensure every joint node has a non-empty name and the node hierarchy is acyclic',\n },\n 'gltf-image-extract-failed': {\n expected:\n 'image bytes extractable from bufferView / data-URI / external URI without corruption',\n hint: 'verify the bufferView byte range / data: URI base64 / external URI sibling file is intact next to the .gltf source; rerun: forgeax-engine-remote-gltf import <path>',\n },\n 'gltf-skin-attr-asymmetric': {\n expected:\n 'mesh primitive declares JOINTS_0 and WEIGHTS_0 symmetrically (both present or both absent)',\n hint: 'glTF spec requires JOINTS_0 and WEIGHTS_0 to appear together for each skinned primitive; add the missing attribute or remove the present one in the DCC tool',\n },\n 'gltf-animation-target-invalid': {\n expected:\n 'every animation channel resolves to one uniquely named scene node and stable target ID',\n hint: 'name every node in the animated hierarchy and ensure each animated full path is unique',\n },\n 'gltf-meshopt-decoder-required': {\n expected:\n 'a required or compressed-only EXT_meshopt_compression bufferView has a ready decoder capability',\n hint: 'provide the build-only EXT_meshopt_compression decoder or author a valid core fallback bufferView',\n },\n 'gltf-meshopt-decode-failed': {\n expected: 'the EXT_meshopt_compression declaration and decoder output are structurally valid',\n hint: 'the meshopt decoder accepts the declared compressed range and produces the declared byte count',\n },\n 'gltf-morph-invalid': {\n expected:\n 'morph target and default-weight arrays are dense, bounded, and match the base vertex count',\n hint: 're-export dense morph targets with at most eight targets/attributes and matching vertex/default-weight lengths',\n },\n 'gltf-color-accessor-unsupported': {\n expected: 'COLOR_0 dense accessor uses VEC3/VEC4 FLOAT or normalized UBYTE/USHORT',\n hint: 're-export COLOR_0 with a supported type/component/normalized combination; morph and sparse COLOR_0 remain deferred',\n },\n 'gltf-color-accessor-malformed': {\n expected: 'COLOR_0 accessor is non-empty, finite, in range, and fully addressable',\n hint: 'repair the COLOR_0 accessor count, reference, range, or buffer bounds, then re-import the glTF source',\n },\n 'gltf-mesh-bridge-invalid': {\n expected: 'a non-empty merged mesh with consistent morph and COLOR_0 cardinality',\n hint: 'repair the source primitive and re-import; inspect detail.reason and its typed facts',\n },\n} satisfies Record<GltfErrorCode, GltfErrorPolicy>;\n\nexport const GLTF_ERROR_HINTS: Readonly<Record<GltfErrorCode, string>> = Object.fromEntries(\n Object.entries(gltfErrorPolicy).map(([code, policy]) => [code, policy.hint]),\n) as Readonly<Record<GltfErrorCode, string>>;\n\n// === DetailFor map + gltfErr factory ===\n\ninterface DetailFor {\n readonly 'gltf-malformed-header': GltfMalformedHeaderDetail;\n readonly 'gltf-version-unsupported': GltfVersionUnsupportedDetail;\n readonly 'gltf-buffer-out-of-bounds': GltfBufferOutOfBoundsDetail;\n readonly 'gltf-extension-unsupported': GltfExtensionUnsupportedDetail;\n readonly 'gltf-lod-invalid': GltfLodInvalidDetail;\n readonly 'gltf-accessor-type-mismatch': GltfAccessorTypeMismatchDetail;\n readonly 'gltf-texture-load-failed': GltfTextureLoadFailedDetail;\n readonly 'gltf-meta-missing': GltfMetaMissingDetail;\n readonly 'gltf-instancing-count-mismatch': GltfInstancingCountMismatchDetail;\n readonly 'gltf-image-mime-unsupported': GltfImageMimeUnsupportedDetail;\n readonly 'gltf-skin-joint-count-exceeded': GltfSkinJointCountExceededDetail;\n readonly 'gltf-animation-cubicspline-unsupported': GltfAnimationCubicsplineUnsupportedDetail;\n readonly 'gltf-morph-unsupported': GltfMorphUnsupportedDetail;\n readonly 'gltf-skin-joint-name-missing': GltfSkinJointNameMissingDetail;\n readonly 'gltf-image-extract-failed': GltfImageExtractFailedDetail;\n readonly 'gltf-skin-attr-asymmetric': GltfSkinAttrAsymmetricDetail;\n readonly 'gltf-animation-target-invalid': GltfAnimationTargetInvalidDetail;\n readonly 'gltf-meshopt-decoder-required': GltfMeshoptDecoderRequiredDetail;\n readonly 'gltf-meshopt-decode-failed': GltfMeshoptDecodeFailedDetail;\n readonly 'gltf-morph-invalid': GltfMorphInvalidDetail;\n readonly 'gltf-color-accessor-unsupported': GltfColorAccessorUnsupportedDetail;\n readonly 'gltf-color-accessor-malformed': GltfColorAccessorMalformedDetail;\n readonly 'gltf-mesh-bridge-invalid': GltfMeshBridgeInvalidDetail;\n readonly 'gltf-material-transmission-invalid': GltfMaterialTransmissionInvalidDetail;\n readonly 'gltf-material-physical-invalid': GltfMaterialPhysicalInvalidDetail;\n}\n\n/**\n * Build a fully-typed GltfError. The discriminated-union return type lets\n * call sites narrow with `switch (e.code)` on the result.\n *\n * Charter proposition 4 explicit-failure: `expected` + `hint` fields are\n * sourced from the SSOT tables - no producer can omit them.\n */\nexport function gltfErr<C extends GltfErrorCode>(\n code: C,\n detail: DetailFor[C],\n): Extract<GltfError, { readonly code: C }> {\n return {\n code,\n expected: gltfErrorPolicy[code].expected,\n hint: gltfErrorPolicy[code].hint,\n detail,\n } as Extract<GltfError, { readonly code: C }>;\n}\n","// decode-accessor.ts - glTF 2.0 accessor decoder (w9).\n//\n// Pure helper that walks one accessor and returns the typed array view of\n// its dense values. Tier-B v1 accepts only the dense, fixed-stride,\n// non-sparse, non-morph subset; everything else returns\n// `gltf-accessor-type-mismatch` with the reason discriminator.\n//\n// glTF 2.0 spec section 3.6 (accessor):\n// - componentType : 5120 I8 / 5121 U8 / 5122 I16 / 5123 U16 / 5125 U32 / 5126 F32\n// - type : 'SCALAR' / 'VEC2' / 'VEC3' / 'VEC4' / 'MAT2' / 'MAT3' / 'MAT4'\n// - bufferView : index into bufferViews[]\n// - byteOffset : within bufferView\n// - count : number of elements\n// - sparse : OOS (Tier-B v1 reject)\n// - bufferView.byteStride : when set and != element_size -> interleaved (OOS reject)\n//\n// The U8 -> U16 widening for INDICES is handled inline (a 1-byte index\n// stream is rewritten into a fresh Uint16Array). U16 and U32 index streams\n// pass through at their source width; `MeshAsset.indices` is\n// `Uint16Array | Uint32Array` end-to-end (mesh-bin serializes iwidth 2|4,\n// GPU runtime auto-selects the index format), and bridge.ts narrows U32 to\n// U16 losslessly when the merged mesh's maxIndex fits.\n//\n// Producers MUST use `decodeAccessor` rather than reading typed arrays\n// directly so the closed `GltfErrorCode` surface (charter proposition 4)\n// is the only public failure path.\n\nimport { err, type GltfError, gltfErr, ok, type Result } from '../errors.js';\n\n/** glTF 2.0 component-type IDs (KHR spec section 3.6 table 4). */\nexport const COMPONENT_TYPE = {\n I8: 5120,\n U8: 5121,\n I16: 5122,\n U16: 5123,\n U32: 5125,\n F32: 5126,\n} as const;\nexport type ComponentTypeId = (typeof COMPONENT_TYPE)[keyof typeof COMPONENT_TYPE];\n\n/** Number of components per element for each glTF accessor `type` literal. */\nconst TYPE_COMPONENT_COUNT: Readonly<Record<string, number>> = {\n SCALAR: 1,\n VEC2: 2,\n VEC3: 3,\n VEC4: 4,\n MAT2: 4,\n MAT3: 9,\n MAT4: 16,\n};\n\n/** Byte size of one component for each component type. */\nconst COMPONENT_BYTE_SIZE: Readonly<Record<number, number>> = {\n [COMPONENT_TYPE.I8]: 1,\n [COMPONENT_TYPE.U8]: 1,\n [COMPONENT_TYPE.I16]: 2,\n [COMPONENT_TYPE.U16]: 2,\n [COMPONENT_TYPE.U32]: 4,\n [COMPONENT_TYPE.F32]: 4,\n};\n\n/** Minimal accessor JSON shape touched by the decoder. */\nexport interface AccessorJson {\n readonly bufferView: number;\n readonly byteOffset?: number;\n readonly componentType: number;\n readonly count: number;\n readonly normalized?: boolean;\n readonly type: string;\n readonly sparse?: unknown;\n}\n\n/** Minimal bufferView JSON shape touched by the decoder. */\nexport interface BufferViewJson {\n readonly buffer: number;\n readonly byteOffset?: number;\n readonly byteLength: number;\n readonly byteStride?: number;\n}\n\n/**\n * Caller intent flag: when this accessor backs a mesh `INDICES` slot, U8\n * indices auto-widen to U16 (Tier-B v1 mesh asset stores U16 only).\n */\nexport type AccessorRole = 'attribute' | 'indices' | 'joints';\n\nexport interface DecodeAccessorInput {\n readonly accessorIndex: number;\n readonly accessor: AccessorJson;\n readonly bufferView: BufferViewJson;\n readonly buffer: Uint8Array;\n readonly role: AccessorRole;\n}\n\nexport type DecodedAccessor =\n | { readonly kind: 'f32'; readonly data: Float32Array }\n | { readonly kind: 'u16'; readonly data: Uint16Array }\n | { readonly kind: 'u32'; readonly data: Uint32Array };\n\ntype F32AccessorJson = Omit<AccessorJson, 'bufferView'> & {\n readonly bufferView?: number;\n};\n\n/**\n * Decode an F32 accessor for parser-owned type subsets without duplicating\n * buffer lookup and dense-range handling in each parser.\n */\nexport function decodeF32Accessor(\n accessorIndex: number,\n accessor: F32AccessorJson,\n allowedTypes: readonly string[],\n bufferViews: readonly BufferViewJson[],\n buffers: readonly Uint8Array[],\n): Result<Float32Array, GltfError> {\n if (accessor.componentType !== COMPONENT_TYPE.F32 || !allowedTypes.includes(accessor.type)) {\n return err(\n gltfErr('gltf-accessor-type-mismatch', { accessorIndex, reason: 'unknownComponentType' }),\n );\n }\n\n const bufferViewIndex = accessor.bufferView;\n if (bufferViewIndex === undefined) {\n return err(\n gltfErr('gltf-buffer-out-of-bounds', {\n accessor: accessorIndex,\n byteOffset: 0,\n byteLength: 0,\n bufferIndex: 0,\n }),\n );\n }\n const bufferView = bufferViews[bufferViewIndex];\n if (bufferView === undefined) {\n return err(\n gltfErr('gltf-buffer-out-of-bounds', {\n accessor: accessorIndex,\n byteOffset: 0,\n byteLength: 0,\n bufferIndex: bufferViewIndex,\n }),\n );\n }\n const buffer = buffers[bufferView.buffer];\n if (buffer === undefined) {\n return err(\n gltfErr('gltf-buffer-out-of-bounds', {\n accessor: accessorIndex,\n byteOffset: bufferView.byteOffset ?? 0,\n byteLength: bufferView.byteLength,\n bufferIndex: bufferView.buffer,\n }),\n );\n }\n\n const decoded = decodeAccessor({\n accessor: { ...accessor, bufferView: bufferViewIndex },\n bufferView,\n buffer,\n accessorIndex,\n role: 'attribute',\n });\n if (!decoded.ok) return decoded;\n if (decoded.value.kind !== 'f32') {\n return err(\n gltfErr('gltf-accessor-type-mismatch', { accessorIndex, reason: 'unknownComponentType' }),\n );\n }\n return ok(decoded.value.data);\n}\n\n/**\n * Decode a dense glTF accessor into the typed array view of its values.\n * Rejects sparse / morph / interleaved / unknown-componentType variants\n * with `gltf-accessor-type-mismatch`. Out-of-range byte slices return\n * `gltf-buffer-out-of-bounds`.\n *\n * `morph` is signalled by the caller (mesh primitive iteration in\n * parseGltf) by passing an accessor reached via a `targets[]` slot - the\n * decoder cannot infer it from the accessor JSON alone, so this function\n * surfaces the reason via the `morph` parameter when the caller has\n * already detected it.\n */\nexport function decodeAccessor(\n input: DecodeAccessorInput,\n flags: { readonly morph?: boolean } = {},\n): Result<DecodedAccessor, GltfError> {\n const { accessorIndex, accessor, bufferView, buffer, role } = input;\n\n if (flags.morph === true) {\n return err(\n gltfErr('gltf-accessor-type-mismatch', {\n accessorIndex,\n reason: 'morph',\n }),\n );\n }\n\n if ('sparse' in accessor && accessor.sparse !== undefined) {\n return err(\n gltfErr('gltf-accessor-type-mismatch', {\n accessorIndex,\n reason: 'sparse',\n }),\n );\n }\n\n const componentByteSize = COMPONENT_BYTE_SIZE[accessor.componentType];\n const componentCount = TYPE_COMPONENT_COUNT[accessor.type];\n if (componentByteSize === undefined || componentCount === undefined) {\n return err(\n gltfErr('gltf-accessor-type-mismatch', {\n accessorIndex,\n reason: 'unknownComponentType',\n }),\n );\n }\n const elementSize = componentByteSize * componentCount;\n const byteStride = bufferView.byteStride;\n if (byteStride !== undefined && byteStride !== elementSize) {\n return err(\n gltfErr('gltf-accessor-type-mismatch', {\n accessorIndex,\n reason: 'interleaved',\n }),\n );\n }\n\n const accessorByteOffset = accessor.byteOffset ?? 0;\n const bufferViewByteOffset = bufferView.byteOffset ?? 0;\n const totalByteLength = elementSize * accessor.count;\n if (accessorByteOffset + totalByteLength > bufferView.byteLength) {\n return err(\n gltfErr('gltf-buffer-out-of-bounds', {\n accessor: accessorIndex,\n byteOffset: bufferViewByteOffset + accessorByteOffset,\n byteLength: totalByteLength,\n bufferIndex: bufferView.buffer,\n }),\n );\n }\n const absoluteOffset = bufferViewByteOffset + accessorByteOffset;\n if (absoluteOffset + totalByteLength > buffer.byteLength) {\n return err(\n gltfErr('gltf-buffer-out-of-bounds', {\n accessor: accessorIndex,\n byteOffset: absoluteOffset,\n byteLength: totalByteLength,\n bufferIndex: bufferView.buffer,\n }),\n );\n }\n\n // U8 INDICES auto-widen to U16 (Tier-B v1 mesh asset stores U16 only).\n if (role === 'indices' && accessor.componentType === COMPONENT_TYPE.U8) {\n const widened = new Uint16Array(accessor.count);\n for (let i = 0; i < accessor.count; i++) {\n widened[i] = buffer[absoluteOffset + i] ?? 0;\n }\n return ok({ kind: 'u16', data: widened });\n }\n // U8 JOINTS auto-widen to U16 (Tier-B v1 mesh asset stores U16 only).\n // Reuses the indices widen pattern (E-5) but JOINTS_0 is VEC4 (componentCount=4),\n // not SCALAR like INDICES; total values = accessor.count * componentCount.\n if (role === 'joints' && accessor.componentType === COMPONENT_TYPE.U8) {\n const totalValues = accessor.count * componentCount;\n const widened = new Uint16Array(totalValues);\n for (let i = 0; i < totalValues; i++) {\n widened[i] = buffer[absoluteOffset + i] ?? 0;\n }\n return ok({ kind: 'u16', data: widened });\n }\n if (accessor.componentType === COMPONENT_TYPE.F32) {\n // Copy out (rather than alias) so callers may safely mutate / persist\n // the result independent of the underlying GLB BIN chunk lifetime.\n const out = new Float32Array(accessor.count * componentCount);\n const src = new Float32Array(buffer.buffer, buffer.byteOffset + absoluteOffset, out.length);\n out.set(src);\n return ok({ kind: 'f32', data: out });\n }\n if (accessor.componentType === COMPONENT_TYPE.U16) {\n const out = new Uint16Array(accessor.count * componentCount);\n const src = new Uint16Array(buffer.buffer, buffer.byteOffset + absoluteOffset, out.length);\n out.set(src);\n return ok({ kind: 'u16', data: out });\n }\n if (accessor.componentType === COMPONENT_TYPE.U32) {\n const out = new Uint32Array(accessor.count * componentCount);\n const src = new Uint32Array(buffer.buffer, buffer.byteOffset + absoluteOffset, out.length);\n out.set(src);\n return ok({ kind: 'u32', data: out });\n }\n if (accessor.componentType === COMPONENT_TYPE.I16) {\n const out = new Float32Array(accessor.count * componentCount);\n const src = new Int16Array(buffer.buffer, buffer.byteOffset + absoluteOffset, out.length);\n for (let index = 0; index < src.length; index++) {\n const value = src[index] ?? 0;\n out[index] = accessor.normalized === true ? Math.max(-1, value / 32767) : value;\n }\n return ok({ kind: 'f32', data: out });\n }\n // I8 remains outside the current attribute contract. Keep it rejected\n // rather than silently widening an unowned representation.\n return err(\n gltfErr('gltf-accessor-type-mismatch', {\n accessorIndex,\n reason: 'unknownComponentType',\n }),\n );\n}\n","import { err, gltfErr, ok, type Result } from '../errors.js';\nimport type { AccessorJson, BufferViewJson } from './decode-accessor.js';\n\nexport interface DecodeColorAccessorInput {\n readonly accessorIndex: number;\n readonly accessor: AccessorJson;\n readonly bufferView: BufferViewJson;\n readonly buffer: Uint8Array;\n readonly bufferIndex?: number;\n readonly semantic: 'COLOR_0';\n}\n\nconst FLOAT = 5126;\nconst UNSIGNED_BYTE = 5121;\nconst UNSIGNED_SHORT = 5123;\n\nfunction unsupported(\n input: DecodeColorAccessorInput,\n reason: 'component' | 'type' | 'normalized' | 'sparse' | 'morph',\n) {\n return err(\n gltfErr('gltf-color-accessor-unsupported', {\n semantic: input.semantic,\n accessorIndex: input.accessorIndex,\n reason,\n expectedType: 'VEC3 or VEC4',\n expectedComponent: 'FLOAT or normalized UNSIGNED_BYTE/UNSIGNED_SHORT',\n ...(reason === 'normalized' ? { expectedNormalized: true } : {}),\n }),\n );\n}\n\nfunction malformed(\n input: DecodeColorAccessorInput,\n reason: 'count' | 'bounds' | 'finite' | 'range' | 'reference',\n) {\n return err(\n gltfErr('gltf-color-accessor-malformed', {\n semantic: input.semantic,\n accessorIndex: input.accessorIndex,\n reason,\n ...(reason === 'count'\n ? { expectedCount: 'matches POSITION vertex count and is greater than zero' }\n : {}),\n ...(reason === 'range' || reason === 'finite'\n ? { expectedRange: '[0,1] finite linear values' }\n : {}),\n }),\n );\n}\n\n/** Decode one dense glTF COLOR_0 accessor into linear RGBA float values. */\nexport function decodeColorAccessor(\n input: DecodeColorAccessorInput,\n flags: { readonly morph?: boolean } = {},\n): Result<Float32Array, import('../errors.js').GltfError> {\n const { accessor, bufferView, buffer } = input;\n if (flags.morph === true) return unsupported(input, 'morph');\n if (accessor.sparse !== undefined) return unsupported(input, 'sparse');\n\n if (accessor.type !== 'VEC3' && accessor.type !== 'VEC4') return unsupported(input, 'type');\n if (!Number.isSafeInteger(accessor.count) || accessor.count <= 0)\n return malformed(input, 'count');\n\n let componentByteSize: 1 | 2 | 4;\n if (accessor.componentType === FLOAT) componentByteSize = 4;\n else if (accessor.componentType === UNSIGNED_BYTE) componentByteSize = 1;\n else if (accessor.componentType === UNSIGNED_SHORT) componentByteSize = 2;\n else return unsupported(input, 'component');\n\n if (accessor.componentType === FLOAT) {\n if (accessor.normalized !== undefined) return unsupported(input, 'normalized');\n } else if (accessor.normalized !== true) {\n return unsupported(input, 'normalized');\n }\n\n const componentCount = accessor.type === 'VEC3' ? 3 : 4;\n const elementByteLength = componentByteSize * componentCount;\n const byteStride = bufferView.byteStride ?? elementByteLength;\n if (\n !Number.isSafeInteger(byteStride) ||\n byteStride < elementByteLength ||\n byteStride % componentByteSize !== 0\n ) {\n return malformed(input, 'bounds');\n }\n if (input.bufferIndex !== undefined && bufferView.buffer !== input.bufferIndex) {\n return malformed(input, 'reference');\n }\n\n const accessorByteOffset = accessor.byteOffset ?? 0;\n const viewByteOffset = bufferView.byteOffset ?? 0;\n const lastElementEnd = accessorByteOffset + byteStride * (accessor.count - 1) + elementByteLength;\n if (\n !Number.isSafeInteger(accessorByteOffset) ||\n accessorByteOffset < 0 ||\n lastElementEnd > bufferView.byteLength\n ) {\n return malformed(input, 'bounds');\n }\n const absoluteLastElementEnd = viewByteOffset + lastElementEnd;\n if (\n !Number.isSafeInteger(viewByteOffset) ||\n viewByteOffset < 0 ||\n absoluteLastElementEnd > buffer.byteLength\n ) {\n return malformed(input, 'bounds');\n }\n\n const output = new Float32Array(accessor.count * 4);\n const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);\n const base = viewByteOffset + accessorByteOffset;\n for (let vertex = 0; vertex < accessor.count; vertex++) {\n const sourceOffset = base + vertex * byteStride;\n for (let component = 0; component < componentCount; component++) {\n const byteOffset = sourceOffset + component * componentByteSize;\n let value: number;\n if (accessor.componentType === FLOAT) value = view.getFloat32(byteOffset, true);\n else if (accessor.componentType === UNSIGNED_BYTE) value = view.getUint8(byteOffset) / 255;\n else value = view.getUint16(byteOffset, true) / 65535;\n if (!Number.isFinite(value)) return malformed(input, 'finite');\n if (value < 0 || value > 1) return malformed(input, 'range');\n output[vertex * 4 + component] = value;\n }\n if (componentCount === 3) output[vertex * 4 + 3] = 1;\n }\n return ok(output);\n}\n","// check-extensions.ts - KHR / vendor extension gate.\n//\n// Required-extension support contains EXT_mesh_gpu_instancing,\n// EXT_meshopt_compression, KHR_lights_punctual, KHR_texture_transform, and\n// the KHR material transmission/IOR/volume/clearcoat/anisotropy/sheen/\n// iridescence/specular extensions. The exported list is the public supported\n// extension surface consumed by both the required-extension gate and callers\n// that need to discover support.\n// (feat-20260518-gltf-instancing-and-name-component plan-strategy section\n// 2 D-1 / D-3). Any extension listed in `extensionsRequired[]` outside\n// the supported extension set triggers `gltf-extension-unsupported` (hard fail).\n// Extensions listed in `extensionsUsed[]` (but not required and not in\n// supported extension set) are recorded in `importSettings.diagnostics\n// .unsupportedExtensions` so AI users can observe them downstream — and\n// nothing else: `extensionsUsed` is purely informational per the glTF spec\n// (only `extensionsRequired` is binding), and exporters routinely\n// over-declare it (e.g. KHR_materials_unlit listed but referenced by no\n// material). A stderr warn for those would be a false positive, so the\n// diagnostics list is the single channel (no `console.error`).\n//\n// Future expansion (KHR_materials_unlit, ...) extends\n// `EXTENSION_ALLOWLIST` in place; each addition lands under its own feat-*\n// loop with breaking-change registry entry.\n\nimport { err, type GltfError, gltfErr, ok, type Result } from './errors.js';\n\n/** Public supported extension list used by the required/used declaration gate. */\nexport const EXTENSION_ALLOWLIST: readonly string[] = [\n 'EXT_mesh_gpu_instancing',\n 'EXT_meshopt_compression',\n 'KHR_lights_punctual',\n 'KHR_texture_transform',\n 'KHR_materials_transmission',\n 'KHR_materials_ior',\n 'KHR_materials_volume',\n 'KHR_materials_clearcoat',\n 'KHR_materials_anisotropy',\n 'KHR_materials_sheen',\n 'KHR_materials_iridescence',\n 'KHR_materials_specular',\n];\nconst SUPPORTED_EXTENSIONS: readonly string[] = [\n ...EXTENSION_ALLOWLIST,\n 'MSFT_lod',\n 'MSFT_screencoverage',\n];\n\nexport interface ExtensionsCheckResult {\n /** Names listed in extensionsUsed but not in the supported extension set. */\n readonly unsupportedUsed: readonly string[];\n}\n\nexport interface GltfExtensionsJson {\n readonly extensionsRequired?: readonly string[];\n readonly extensionsUsed?: readonly string[];\n}\n\n/**\n * Validate the glTF JSON's extension declarations against the supported set.\n *\n * Returns:\n * - `Result.err(gltf-extension-unsupported)` for the FIRST entry of\n * `extensionsRequired[]` that is not allowlisted (fail-fast; the\n * remaining required entries are not surfaced; first wins because the\n * diagnostic carries one extension name + source slot only).\n * - `Result.ok({ unsupportedUsed })` otherwise; the `unsupportedUsed`\n * array names every extensionsUsed entry not in the allowlist (used as\n * input for `importSettings.diagnostics.unsupportedExtensions`).\n * extensionsUsed entries never fail parsing and never write to stderr —\n * they are informational per the glTF spec and routinely over-declared.\n *\n * Pure function: no fs / network / stderr.\n */\nexport function checkExtensions(\n json: GltfExtensionsJson,\n): Result<ExtensionsCheckResult, GltfError> {\n const required = json.extensionsRequired ?? [];\n for (const ext of required) {\n if (!SUPPORTED_EXTENSIONS.includes(ext)) {\n return err(\n gltfErr('gltf-extension-unsupported', {\n extension: ext,\n source: 'extensionsRequired',\n }),\n );\n }\n }\n\n const used = json.extensionsUsed ?? [];\n const unsupportedUsed: string[] = [];\n for (const ext of used) {\n if (!SUPPORTED_EXTENSIONS.includes(ext)) {\n unsupportedUsed.push(ext);\n }\n }\n\n return ok({ unsupportedUsed });\n}\n","const DATA_URI_BASE64_RE = /^data:[^;,]*(?:;[^,;]+)*;base64,(.*)$/;\n\nexport class Base64DecodeError extends Error {\n constructor(cause: unknown) {\n super(\n `base64 payload decode failed: ${cause instanceof Error ? cause.message : String(cause)}`,\n );\n this.name = 'Base64DecodeError';\n }\n}\n\nexport function dataUriBase64Payload(uri: string): string | undefined {\n const match = DATA_URI_BASE64_RE.exec(uri);\n return match === null ? undefined : (match[1] ?? '');\n}\n\nexport function decodeBase64(b64: string): Uint8Array {\n let binary: string;\n try {\n binary = atob(b64);\n } catch (cause) {\n throw new Base64DecodeError(cause);\n }\n const out = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n out[i] = binary.charCodeAt(i);\n }\n return out;\n}\n","import { err, gltfErr, ok, type Result } from '../errors.js';\n\nexport interface GltfLodRelation {\n readonly rootNode: number;\n readonly lodNodeIds: readonly number[];\n readonly screenCoverages: readonly number[];\n /** All node-level MSFT_lod groups, retained for multi-root scenes. */\n readonly groups: readonly GltfLodGroup[];\n}\n\nexport interface GltfLodGroup {\n readonly rootNode: number;\n readonly lodNodeIds: readonly number[];\n readonly screenCoverages: readonly number[];\n}\n\ninterface RawNode {\n readonly mesh?: unknown;\n readonly extensions?: { readonly MSFT_lod?: { readonly ids?: unknown } };\n readonly extras?: { readonly MSFT_screencoverage?: unknown };\n}\n\ninterface RawMesh {\n readonly primitives?: unknown;\n}\n\ninterface RawGltf {\n readonly extensionsRequired?: readonly unknown[];\n readonly meshes?: readonly RawMesh[];\n readonly nodes?: readonly RawNode[];\n readonly extensions?: { readonly MSFT_screencoverage?: { readonly scales?: unknown } };\n}\n\nexport function parseGltfLodExtension(\n json: unknown,\n): Result<GltfLodRelation, ReturnType<typeof gltfErr<'gltf-lod-invalid'>>> {\n const doc = json as RawGltf;\n const nodes = doc.nodes ?? [];\n const rawCoverage = doc.extensions?.MSFT_screencoverage?.scales;\n const groups: GltfLodGroup[] = [];\n for (let rootNode = 0; rootNode < nodes.length; rootNode += 1) {\n if (nodes[rootNode]?.extensions?.MSFT_lod === undefined) continue;\n const idsRaw = nodes[rootNode]?.extensions?.MSFT_lod?.ids;\n if (!Array.isArray(idsRaw)) {\n return err(gltfErr('gltf-lod-invalid', { rootNode, ids: [], reason: 'not-integer' }));\n }\n const ids = idsRaw.filter((value): value is number => typeof value === 'number');\n if (\n ids.length !== idsRaw.length ||\n ids.some((id) => !Number.isInteger(id) || id < 0 || id >= nodes.length)\n ) {\n return err(gltfErr('gltf-lod-invalid', { rootNode, ids, reason: 'missing-node' }));\n }\n if (new Set(ids).size !== ids.length || ids.includes(rootNode)) {\n return err(gltfErr('gltf-lod-invalid', { rootNode, ids, reason: 'duplicate-node' }));\n }\n const hasMesh = (node: RawNode | undefined): boolean => {\n if (typeof node?.mesh !== 'number' || !Number.isInteger(node.mesh) || node.mesh < 0) {\n return false;\n }\n const mesh = doc.meshes?.[node.mesh];\n // An extension relation is publishable only when its target mesh has at\n // least one primitive. The parser normally receives the source mesh\n // table, so an empty table/primitive list is a source-contract failure;\n // treating it as a valid relation would let toAssetPack silently drop\n // the LOD level later.\n return mesh !== undefined && Array.isArray(mesh.primitives) && mesh.primitives.length > 0;\n };\n if (!hasMesh(nodes[rootNode]) || ids.some((id) => !hasMesh(nodes[id]))) {\n return err(gltfErr('gltf-lod-invalid', { rootNode, ids, reason: 'missing-node' }));\n }\n const nodeCoverage = nodes[rootNode]?.extras?.MSFT_screencoverage;\n const coverage = normalizeScreenCoverages(\n nodeCoverage === undefined ? rawCoverage : nodeCoverage,\n ids.length,\n nodeCoverage !== undefined,\n );\n if (coverage === 'invalid') {\n return err(gltfErr('gltf-lod-invalid', { rootNode, ids, reason: 'coverage' }));\n }\n groups.push({\n rootNode,\n lodNodeIds: ids,\n screenCoverages: coverage ?? [],\n });\n }\n const first = groups[0];\n if (first === undefined) {\n if (doc.extensionsRequired?.some((extension) => extension === 'MSFT_lod')) {\n return err(gltfErr('gltf-lod-invalid', { rootNode: 0, ids: [], reason: 'missing-node' }));\n }\n return ok({ rootNode: 0, lodNodeIds: [], screenCoverages: [], groups: [] });\n }\n return ok({\n rootNode: first.rootNode,\n lodNodeIds: first.lodNodeIds,\n screenCoverages: first.screenCoverages,\n groups,\n });\n}\n\n/**\n * Normalize the official node `extras.MSFT_screencoverage` form and the\n * historical ForgeaX document-extension adapter form. The official array\n * includes one terminal threshold for the discard range, while MeshAsset\n * stores only the thresholds that select lower geometry levels.\n */\nfunction normalizeScreenCoverages(\n raw: unknown,\n lodCount: number,\n officialNodeForm: boolean,\n): readonly number[] | undefined | 'invalid' {\n if (raw === undefined) return undefined;\n if (!Array.isArray(raw)) return 'invalid';\n if (\n raw.some(\n (value) => typeof value !== 'number' || !Number.isFinite(value) || value <= 0 || value > 1,\n )\n ) {\n return 'invalid';\n }\n const expectedLengths = officialNodeForm ? [lodCount + 1] : [lodCount, lodCount + 1];\n if (!expectedLengths.includes(raw.length)) return 'invalid';\n const values = raw.slice(0, lodCount) as number[];\n for (let index = 1; index < values.length; index += 1) {\n if ((values[index] as number) >= (values[index - 1] as number)) return 'invalid';\n }\n return values;\n}\n","export interface GltfTextureIr {\n readonly sampler?: number;\n readonly source: number;\n readonly name?: string;\n}\n\nexport interface GltfImageIr {\n readonly uri?: string;\n readonly mimeType?: string;\n readonly bufferView?: number;\n readonly name?: string;\n}\n\nexport interface GltfSamplerIr {\n readonly magFilter?: number;\n readonly minFilter?: number;\n readonly wrapS: number;\n readonly wrapT: number;\n readonly name?: string;\n}\n\nexport interface GltfTextureTransformIr {\n readonly offset?: readonly [number, number];\n readonly rotation?: number;\n readonly scale?: readonly [number, number];\n}\n\nexport interface GltfTextureInfoIr {\n readonly texture: number;\n readonly sampler?: number;\n readonly texCoord?: number;\n readonly transform?: GltfTextureTransformIr;\n}\n\nexport interface GltfNormalTextureInfoIr extends GltfTextureInfoIr {\n readonly scale?: number;\n}\n\nexport interface GltfOcclusionTextureInfoIr extends GltfTextureInfoIr {\n readonly strength?: number;\n}\n\nexport interface TextureTransformJson {\n readonly offset?: readonly number[];\n readonly rotation?: number;\n readonly scale?: readonly number[];\n readonly texCoord?: number;\n}\n\nexport interface TextureInfoJson {\n readonly index: number;\n readonly texCoord?: number;\n readonly extensions?: {\n readonly KHR_texture_transform?: TextureTransformJson;\n };\n}\n\nexport interface NormalTextureInfoJson extends TextureInfoJson {\n readonly scale?: number;\n}\n\nexport interface OcclusionTextureInfoJson extends TextureInfoJson {\n readonly strength?: number;\n}\n\nexport interface GltfMaterialJson {\n readonly name?: string;\n readonly pbrMetallicRoughness?: {\n readonly baseColorFactor?: readonly number[];\n readonly baseColorTexture?: TextureInfoJson;\n readonly metallicFactor?: number;\n readonly roughnessFactor?: number;\n readonly metallicRoughnessTexture?: TextureInfoJson;\n };\n readonly normalTexture?: NormalTextureInfoJson;\n readonly emissiveFactor?: readonly number[];\n readonly emissiveTexture?: TextureInfoJson;\n readonly occlusionTexture?: OcclusionTextureInfoJson;\n readonly alphaMode?: string;\n readonly alphaCutoff?: number;\n readonly doubleSided?: boolean;\n readonly extensions?: {\n readonly KHR_materials_transmission?: {\n readonly transmissionFactor?: number;\n readonly transmissionTexture?: TextureInfoJson;\n };\n readonly KHR_materials_ior?: {\n readonly ior?: number;\n };\n readonly KHR_materials_volume?: {\n readonly thicknessFactor?: number;\n readonly thicknessTexture?: TextureInfoJson;\n readonly attenuationColor?: readonly number[];\n readonly attenuationDistance?: number;\n };\n readonly KHR_materials_clearcoat?: {\n readonly clearcoatFactor?: number;\n readonly clearcoatTexture?: TextureInfoJson;\n readonly clearcoatRoughnessFactor?: number;\n readonly clearcoatRoughnessTexture?: TextureInfoJson;\n readonly clearcoatNormalTexture?: NormalTextureInfoJson;\n };\n readonly KHR_materials_anisotropy?: {\n readonly anisotropyStrength?: number;\n readonly anisotropyRotation?: number;\n readonly anisotropyTexture?: TextureInfoJson;\n };\n readonly KHR_materials_sheen?: {\n readonly sheenColorFactor?: readonly number[];\n readonly sheenColorTexture?: TextureInfoJson;\n readonly sheenRoughnessFactor?: number;\n readonly sheenRoughnessTexture?: TextureInfoJson;\n };\n readonly KHR_materials_iridescence?: {\n readonly iridescenceFactor?: number;\n readonly iridescenceIor?: number;\n readonly iridescenceThicknessMinimum?: number;\n readonly iridescenceThicknessMaximum?: number;\n readonly iridescenceTexture?: TextureInfoJson;\n readonly iridescenceThicknessTexture?: TextureInfoJson;\n };\n readonly KHR_materials_specular?: {\n readonly specularFactor?: number;\n readonly specularTexture?: TextureInfoJson;\n readonly specularColorFactor?: readonly number[];\n readonly specularColorTexture?: TextureInfoJson;\n };\n };\n}\n\nexport interface GltfMaterialIr {\n readonly name?: string;\n readonly baseColorFactor: readonly [number, number, number, number];\n /** glTF emissiveFactor; omitted means the glTF default [0, 0, 0]. */\n readonly emissiveFactor?: readonly [number, number, number];\n readonly baseColorTexture?: GltfTextureInfoIr | number;\n readonly emissiveTexture?: GltfTextureInfoIr | number;\n readonly metallicFactor: number;\n readonly roughnessFactor: number;\n readonly metallicRoughnessTexture?: GltfTextureInfoIr | number;\n readonly normalTexture?: GltfNormalTextureInfoIr | number;\n readonly occlusionTexture?: GltfOcclusionTextureInfoIr | number;\n readonly transmissionFactor?: number;\n readonly transmissionTexture?: GltfTextureInfoIr | number;\n /** KHR_materials_transmission uses the red texture channel. */\n readonly transmissionChannel?: number;\n readonly ior?: number;\n readonly thicknessFactor?: number;\n readonly thicknessTexture?: GltfTextureInfoIr | number;\n /** KHR_materials_volume uses the green texture channel. */\n readonly thicknessChannel?: number;\n readonly attenuationColor?: readonly [number, number, number];\n readonly attenuationDistance?: number;\n readonly clearcoatFactor?: number;\n readonly clearcoatChannel?: number;\n readonly clearcoatTexture?: GltfTextureInfoIr | number;\n readonly clearcoatRoughnessFactor?: number;\n readonly clearcoatRoughnessChannel?: number;\n readonly clearcoatRoughnessTexture?: GltfTextureInfoIr | number;\n readonly clearcoatNormalTexture?: GltfNormalTextureInfoIr | number;\n readonly clearcoatNormalChannel?: readonly [number, number];\n readonly anisotropyStrength?: number;\n readonly anisotropyRotation?: number;\n readonly anisotropyTexture?: GltfTextureInfoIr | number;\n /** KHR_materials_anisotropy uses RG direction and B strength. */\n readonly anisotropyChannel?: readonly [number, number, number];\n readonly sheenColorFactor?: readonly [number, number, number];\n readonly sheenColorTexture?: GltfTextureInfoIr | number;\n readonly sheenColorChannel?: readonly [number, number, number];\n readonly sheenRoughnessFactor?: number;\n readonly sheenRoughnessTexture?: GltfTextureInfoIr | number;\n readonly sheenRoughnessChannel?: number;\n readonly iridescenceFactor?: number;\n readonly iridescenceIor?: number;\n readonly iridescenceThicknessMinimum?: number;\n readonly iridescenceThicknessMaximum?: number;\n readonly iridescenceTexture?: GltfTextureInfoIr | number;\n readonly iridescenceChannel?: number;\n readonly iridescenceThicknessTexture?: GltfTextureInfoIr | number;\n readonly iridescenceThicknessChannel?: number;\n readonly specularFactor?: number;\n readonly specularTexture?: GltfTextureInfoIr | number;\n /** KHR_materials_specular specularTexture uses the alpha channel. */\n readonly specularChannel?: number;\n readonly specularColorFactor?: readonly [number, number, number];\n readonly specularColorTexture?: GltfTextureInfoIr | number;\n readonly specularColorChannel?: readonly [number, number, number];\n readonly alphaMode?: 'OPAQUE' | 'MASK' | 'BLEND';\n readonly alphaCutoff?: number;\n readonly doubleSided?: boolean;\n readonly baseColorTexCoord?: number;\n}\n\nfunction tuple2(values: readonly number[] | undefined): readonly [number, number] | undefined {\n if (values === undefined || values.length < 2) return undefined;\n return [values[0] ?? 0, values[1] ?? 0];\n}\n\nfunction tuple3(\n values: readonly number[] | undefined,\n): readonly [number, number, number] | undefined {\n if (values === undefined || values.length < 3) return undefined;\n return [values[0] ?? 0, values[1] ?? 0, values[2] ?? 0];\n}\n\nexport function parseTextureInfo(\n info: TextureInfoJson,\n textures: readonly GltfTextureIr[],\n): GltfTextureInfoIr {\n const transformJson = info.extensions?.KHR_texture_transform;\n const offset = tuple2(transformJson?.offset);\n const scale = tuple2(transformJson?.scale);\n const transform =\n offset === undefined && transformJson?.rotation === undefined && scale === undefined\n ? undefined\n : {\n ...(offset === undefined ? {} : { offset }),\n ...(transformJson?.rotation === undefined ? {} : { rotation: transformJson.rotation }),\n ...(scale === undefined ? {} : { scale }),\n };\n const sampler = textures[info.index]?.sampler;\n return {\n texture: info.index,\n ...(sampler === undefined ? {} : { sampler }),\n ...(info.texCoord === undefined && transformJson?.texCoord === undefined\n ? {}\n : { texCoord: transformJson?.texCoord ?? info.texCoord }),\n ...(transform === undefined ? {} : { transform }),\n };\n}\n\nfunction finiteOrUndefined(value: number | undefined): number | undefined {\n return value !== undefined && Number.isFinite(value) ? value : undefined;\n}\n\nexport function parseMaterial(\n matJson: GltfMaterialJson,\n textures: readonly GltfTextureIr[],\n): Result<GltfMaterialIr, GltfError> {\n const pbr = matJson.pbrMetallicRoughness;\n const baseColor = pbr?.baseColorFactor ?? [1, 1, 1, 1];\n const baseColor4: readonly [number, number, number, number] = [\n baseColor[0] ?? 1,\n baseColor[1] ?? 1,\n baseColor[2] ?? 1,\n baseColor[3] ?? 1,\n ];\n const alphaMode =\n matJson.alphaMode === 'MASK' || matJson.alphaMode === 'BLEND' ? matJson.alphaMode : undefined;\n const alphaCutoff = alphaMode === 'MASK' ? (matJson.alphaCutoff ?? 0.5) : undefined;\n const emissiveFactor = tuple3(matJson.emissiveFactor);\n const transmission = matJson.extensions?.KHR_materials_transmission;\n const ior = matJson.extensions?.KHR_materials_ior;\n const volume = matJson.extensions?.KHR_materials_volume;\n const clearcoat = matJson.extensions?.KHR_materials_clearcoat;\n const anisotropy = matJson.extensions?.KHR_materials_anisotropy;\n const sheen = matJson.extensions?.KHR_materials_sheen;\n const iridescence = matJson.extensions?.KHR_materials_iridescence;\n const specular = matJson.extensions?.KHR_materials_specular;\n const attenuationColor = tuple3(volume?.attenuationColor);\n const invalid = (\n extension: 'KHR_materials_transmission' | 'KHR_materials_ior' | 'KHR_materials_volume',\n field: string,\n reason: 'type' | 'range' | 'non-finite' | 'blend',\n actual?: unknown,\n ): Result<GltfMaterialIr, GltfError> =>\n err(\n gltfErr('gltf-material-transmission-invalid', {\n extension,\n field,\n reason,\n ...(actual === undefined ? {} : { actual }),\n }),\n );\n const physicalInvalid = (\n extension:\n | 'KHR_materials_clearcoat'\n | 'KHR_materials_anisotropy'\n | 'KHR_materials_sheen'\n | 'KHR_materials_iridescence'\n | 'KHR_materials_specular',\n field: string,\n reason: 'type' | 'range' | 'non-finite',\n actual?: unknown,\n ): Result<GltfMaterialIr, GltfError> =>\n err(\n gltfErr('gltf-material-physical-invalid', {\n extension,\n field,\n reason,\n ...(actual === undefined ? {} : { actual }),\n }),\n );\n if (\n transmission?.transmissionFactor !== undefined &&\n (typeof transmission.transmissionFactor !== 'number' ||\n !Number.isFinite(transmission.transmissionFactor))\n ) {\n return invalid(\n 'KHR_materials_transmission',\n 'transmissionFactor',\n 'non-finite',\n transmission.transmissionFactor,\n );\n }\n if (\n transmission?.transmissionFactor !== undefined &&\n (transmission.transmissionFactor < 0 || transmission.transmissionFactor > 1)\n ) {\n return invalid(\n 'KHR_materials_transmission',\n 'transmissionFactor',\n 'range',\n transmission.transmissionFactor,\n );\n }\n if (ior?.ior !== undefined && (typeof ior.ior !== 'number' || !Number.isFinite(ior.ior))) {\n return invalid('KHR_materials_ior', 'ior', 'non-finite', ior.ior);\n }\n if (ior?.ior !== undefined && ior.ior < 1) {\n return invalid('KHR_materials_ior', 'ior', 'range', ior.ior);\n }\n if (volume?.thicknessFactor !== undefined && !Number.isFinite(volume.thicknessFactor)) {\n return invalid('KHR_materials_volume', 'thicknessFactor', 'non-finite', volume.thicknessFactor);\n }\n if (volume?.thicknessFactor !== undefined && volume.thicknessFactor < 0) {\n return invalid('KHR_materials_volume', 'thicknessFactor', 'range', volume.thicknessFactor);\n }\n if (\n volume?.attenuationColor !== undefined &&\n (attenuationColor === undefined ||\n attenuationColor.some((value) => !Number.isFinite(value) || value < 0 || value > 1))\n ) {\n return invalid('KHR_materials_volume', 'attenuationColor', 'range', volume.attenuationColor);\n }\n if (\n volume?.attenuationDistance !== undefined &&\n !Number.isFinite(volume.attenuationDistance) &&\n volume.attenuationDistance !== Number.POSITIVE_INFINITY\n ) {\n return invalid(\n 'KHR_materials_volume',\n 'attenuationDistance',\n 'non-finite',\n volume.attenuationDistance,\n );\n }\n if (\n volume?.attenuationDistance !== undefined &&\n Number.isFinite(volume.attenuationDistance) &&\n volume.attenuationDistance <= 0\n ) {\n return invalid(\n 'KHR_materials_volume',\n 'attenuationDistance',\n 'range',\n volume.attenuationDistance,\n );\n }\n if (alphaMode === 'BLEND' && (transmission?.transmissionFactor ?? 0) > 0) {\n return invalid('KHR_materials_transmission', 'alphaMode', 'blend', alphaMode);\n }\n if (\n clearcoat?.clearcoatFactor !== undefined &&\n (typeof clearcoat.clearcoatFactor !== 'number' || !Number.isFinite(clearcoat.clearcoatFactor))\n ) {\n return physicalInvalid(\n 'KHR_materials_clearcoat',\n 'clearcoatFactor',\n 'non-finite',\n clearcoat.clearcoatFactor,\n );\n }\n if (\n clearcoat?.clearcoatFactor !== undefined &&\n (clearcoat.clearcoatFactor < 0 || clearcoat.clearcoatFactor > 1)\n ) {\n return physicalInvalid(\n 'KHR_materials_clearcoat',\n 'clearcoatFactor',\n 'range',\n clearcoat.clearcoatFactor,\n );\n }\n if (\n clearcoat?.clearcoatRoughnessFactor !== undefined &&\n (typeof clearcoat.clearcoatRoughnessFactor !== 'number' ||\n !Number.isFinite(clearcoat.clearcoatRoughnessFactor))\n ) {\n return physicalInvalid(\n 'KHR_materials_clearcoat',\n 'clearcoatRoughnessFactor',\n 'non-finite',\n clearcoat.clearcoatRoughnessFactor,\n );\n }\n if (\n clearcoat?.clearcoatRoughnessFactor !== undefined &&\n (clearcoat.clearcoatRoughnessFactor < 0 || clearcoat.clearcoatRoughnessFactor > 1)\n ) {\n return physicalInvalid(\n 'KHR_materials_clearcoat',\n 'clearcoatRoughnessFactor',\n 'range',\n clearcoat.clearcoatRoughnessFactor,\n );\n }\n if (\n clearcoat?.clearcoatNormalTexture?.scale !== undefined &&\n (typeof clearcoat.clearcoatNormalTexture.scale !== 'number' ||\n !Number.isFinite(clearcoat.clearcoatNormalTexture.scale) ||\n clearcoat.clearcoatNormalTexture.scale < 0)\n ) {\n return physicalInvalid(\n 'KHR_materials_clearcoat',\n 'clearcoatNormalTexture.scale',\n 'range',\n clearcoat.clearcoatNormalTexture.scale,\n );\n }\n const validateUnit = (\n extension: Parameters<typeof physicalInvalid>[0],\n field: string,\n value: number | undefined,\n ) => {\n if (value === undefined) return undefined;\n if (typeof value !== 'number' || !Number.isFinite(value))\n return physicalInvalid(extension, field, 'non-finite', value);\n if (value < 0 || value > 1) return physicalInvalid(extension, field, 'range', value);\n return undefined;\n };\n const validateFinite = (\n extension: Parameters<typeof physicalInvalid>[0],\n field: string,\n value: number | undefined,\n minimum?: number,\n ) => {\n if (value === undefined) return undefined;\n if (typeof value !== 'number' || !Number.isFinite(value))\n return physicalInvalid(extension, field, 'non-finite', value);\n if (minimum !== undefined && value < minimum)\n return physicalInvalid(extension, field, 'range', value);\n return undefined;\n };\n const validateColor = (\n extension: Parameters<typeof physicalInvalid>[0],\n field: string,\n value: readonly number[] | undefined,\n ) => {\n if (value === undefined) return undefined;\n if (\n value.length < 3 ||\n value.slice(0, 3).some((channel) => typeof channel !== 'number' || !Number.isFinite(channel))\n ) {\n return physicalInvalid(extension, field, 'type', value);\n }\n if (value.slice(0, 3).some((channel) => channel < 0 || channel > 1)) {\n return physicalInvalid(extension, field, 'range', value);\n }\n return undefined;\n };\n const physicalChecks = [\n validateUnit('KHR_materials_anisotropy', 'anisotropyStrength', anisotropy?.anisotropyStrength),\n validateFinite(\n 'KHR_materials_anisotropy',\n 'anisotropyRotation',\n anisotropy?.anisotropyRotation,\n ),\n validateUnit('KHR_materials_sheen', 'sheenRoughnessFactor', sheen?.sheenRoughnessFactor),\n validateColor('KHR_materials_sheen', 'sheenColorFactor', sheen?.sheenColorFactor),\n validateUnit('KHR_materials_iridescence', 'iridescenceFactor', iridescence?.iridescenceFactor),\n validateFinite('KHR_materials_iridescence', 'iridescenceIor', iridescence?.iridescenceIor, 1),\n validateFinite(\n 'KHR_materials_iridescence',\n 'iridescenceThicknessMinimum',\n iridescence?.iridescenceThicknessMinimum,\n 0,\n ),\n validateFinite(\n 'KHR_materials_iridescence',\n 'iridescenceThicknessMaximum',\n iridescence?.iridescenceThicknessMaximum,\n 0,\n ),\n validateUnit('KHR_materials_specular', 'specularFactor', specular?.specularFactor),\n validateColor('KHR_materials_specular', 'specularColorFactor', specular?.specularColorFactor),\n ];\n for (const check of physicalChecks) if (check !== undefined) return check;\n return ok({\n ...(matJson.name === undefined ? {} : { name: matJson.name }),\n baseColorFactor: baseColor4,\n ...(emissiveFactor === undefined ? {} : { emissiveFactor }),\n metallicFactor: pbr?.metallicFactor ?? 1.0,\n roughnessFactor: pbr?.roughnessFactor ?? 1.0,\n ...(pbr?.baseColorTexture === undefined\n ? {}\n : { baseColorTexture: parseTextureInfo(pbr.baseColorTexture, textures) }),\n ...(pbr?.metallicRoughnessTexture === undefined\n ? {}\n : { metallicRoughnessTexture: parseTextureInfo(pbr.metallicRoughnessTexture, textures) }),\n ...(matJson.normalTexture === undefined\n ? {}\n : {\n normalTexture: {\n ...parseTextureInfo(matJson.normalTexture, textures),\n ...(matJson.normalTexture.scale === undefined\n ? {}\n : { scale: matJson.normalTexture.scale }),\n },\n }),\n ...(matJson.occlusionTexture === undefined\n ? {}\n : {\n occlusionTexture: {\n ...parseTextureInfo(matJson.occlusionTexture, textures),\n ...(matJson.occlusionTexture.strength === undefined\n ? {}\n : { strength: matJson.occlusionTexture.strength }),\n },\n }),\n ...(matJson.emissiveTexture === undefined\n ? {}\n : { emissiveTexture: parseTextureInfo(matJson.emissiveTexture, textures) }),\n ...(transmission === undefined\n ? {}\n : {\n transmissionFactor: transmission.transmissionFactor ?? 0,\n transmissionChannel: 0,\n ...(transmission.transmissionTexture === undefined\n ? {}\n : {\n transmissionTexture: parseTextureInfo(transmission.transmissionTexture, textures),\n }),\n }),\n ...(ior === undefined ? {} : { ior: ior.ior ?? 1.5 }),\n ...(volume === undefined\n ? {}\n : {\n thicknessFactor: volume.thicknessFactor ?? 0,\n thicknessChannel: 1,\n ...(volume.thicknessTexture === undefined\n ? {}\n : { thicknessTexture: parseTextureInfo(volume.thicknessTexture, textures) }),\n ...(attenuationColor === undefined ? {} : { attenuationColor }),\n ...(finiteOrUndefined(volume.attenuationDistance) === undefined\n ? {}\n : { attenuationDistance: volume.attenuationDistance }),\n }),\n ...(clearcoat === undefined\n ? {}\n : {\n clearcoatFactor: clearcoat.clearcoatFactor ?? 0,\n clearcoatChannel: 0,\n clearcoatRoughnessFactor: clearcoat.clearcoatRoughnessFactor ?? 0,\n clearcoatRoughnessChannel: 1,\n clearcoatNormalChannel: [0, 1] as const,\n ...(clearcoat.clearcoatTexture === undefined\n ? {}\n : { clearcoatTexture: parseTextureInfo(clearcoat.clearcoatTexture, textures) }),\n ...(clearcoat.clearcoatRoughnessTexture === undefined\n ? {}\n : {\n clearcoatRoughnessTexture: parseTextureInfo(\n clearcoat.clearcoatRoughnessTexture,\n textures,\n ),\n }),\n ...(clearcoat.clearcoatNormalTexture === undefined\n ? {}\n : {\n clearcoatNormalTexture: {\n ...parseTextureInfo(clearcoat.clearcoatNormalTexture, textures),\n ...(clearcoat.clearcoatNormalTexture.scale === undefined\n ? {}\n : { scale: clearcoat.clearcoatNormalTexture.scale }),\n },\n }),\n }),\n ...(anisotropy === undefined\n ? {}\n : {\n anisotropyStrength: anisotropy.anisotropyStrength ?? 0,\n anisotropyRotation: anisotropy.anisotropyRotation ?? 0,\n anisotropyChannel: [0, 1, 2] as const,\n ...(anisotropy.anisotropyTexture === undefined\n ? {}\n : { anisotropyTexture: parseTextureInfo(anisotropy.anisotropyTexture, textures) }),\n }),\n ...(sheen === undefined\n ? {}\n : {\n sheenColorFactor: tuple3(sheen.sheenColorFactor) ?? [0, 0, 0],\n sheenColorChannel: [0, 1, 2] as const,\n sheenRoughnessFactor: sheen.sheenRoughnessFactor ?? 0,\n sheenRoughnessChannel: 3,\n ...(sheen.sheenColorTexture === undefined\n ? {}\n : { sheenColorTexture: parseTextureInfo(sheen.sheenColorTexture, textures) }),\n ...(sheen.sheenRoughnessTexture === undefined\n ? {}\n : { sheenRoughnessTexture: parseTextureInfo(sheen.sheenRoughnessTexture, textures) }),\n }),\n ...(iridescence === undefined\n ? {}\n : {\n iridescenceFactor: iridescence.iridescenceFactor ?? 0,\n iridescenceIor: iridescence.iridescenceIor ?? 1.3,\n iridescenceThicknessMinimum: iridescence.iridescenceThicknessMinimum ?? 100,\n iridescenceThicknessMaximum: iridescence.iridescenceThicknessMaximum ?? 400,\n iridescenceChannel: 0,\n iridescenceThicknessChannel: 1,\n ...(iridescence.iridescenceTexture === undefined\n ? {}\n : { iridescenceTexture: parseTextureInfo(iridescence.iridescenceTexture, textures) }),\n ...(iridescence.iridescenceThicknessTexture === undefined\n ? {}\n : {\n iridescenceThicknessTexture: parseTextureInfo(\n iridescence.iridescenceThicknessTexture,\n textures,\n ),\n }),\n }),\n ...(specular === undefined\n ? {}\n : {\n specularFactor: specular.specularFactor ?? 1,\n specularChannel: 3,\n specularColorFactor: tuple3(specular.specularColorFactor) ?? [1, 1, 1],\n specularColorChannel: [0, 1, 2] as const,\n ...(specular.specularTexture === undefined\n ? {}\n : { specularTexture: parseTextureInfo(specular.specularTexture, textures) }),\n ...(specular.specularColorTexture === undefined\n ? {}\n : {\n specularColorTexture: parseTextureInfo(specular.specularColorTexture, textures),\n }),\n }),\n ...(alphaMode === undefined ? {} : { alphaMode }),\n ...(alphaCutoff === undefined ? {} : { alphaCutoff }),\n ...(matJson.doubleSided === true ? { doubleSided: true } : {}),\n ...(pbr?.baseColorTexture?.texCoord === undefined || pbr.baseColorTexture.texCoord === 0\n ? {}\n : { baseColorTexCoord: pbr.baseColorTexture.texCoord }),\n });\n}\n\nimport { err, type GltfError, gltfErr, ok, type Result } from '../errors.js';\n","import type { BufferViewJson } from './accessor/decode-accessor.js';\nimport {\n err,\n GLTF_MESHOPT_FILTERS,\n GLTF_MESHOPT_MODES,\n type GltfError,\n type GltfMeshoptFilter,\n type GltfMeshoptMode,\n gltfErr,\n ok,\n type Result,\n} from './errors.js';\n\nexport type MeshoptMode = GltfMeshoptMode;\nexport type MeshoptFilter = GltfMeshoptFilter;\n\nexport interface MeshoptCompressionJson {\n readonly buffer: number;\n readonly byteOffset?: number;\n readonly byteLength: number;\n readonly byteStride: number;\n readonly count: number;\n readonly mode: MeshoptMode;\n readonly filter?: MeshoptFilter;\n}\n\nexport interface MeshoptBufferViewJson extends BufferViewJson {\n readonly extensions?: {\n readonly EXT_meshopt_compression?: MeshoptCompressionJson;\n };\n}\n\nexport interface GltfBufferViewDecodeCapability {\n readonly decode: (input: {\n readonly source: Uint8Array;\n readonly count: number;\n readonly stride: number;\n readonly mode: MeshoptMode;\n readonly filter: MeshoptFilter;\n }) => Uint8Array | Promise<Uint8Array>;\n}\n\nexport interface MeshoptProjection {\n readonly bufferViews: readonly MeshoptBufferViewJson[];\n readonly buffers: readonly Uint8Array[];\n readonly decodedCount: number;\n}\n\nfunction viewBytes(\n view: MeshoptBufferViewJson,\n buffers: readonly Uint8Array[],\n): Uint8Array | undefined {\n const buffer = buffers[view.buffer];\n const offset = view.byteOffset ?? 0;\n if (\n buffer === undefined ||\n view.byteLength <= 0 ||\n offset < 0 ||\n offset + view.byteLength > buffer.length\n ) {\n return undefined;\n }\n return buffer.subarray(offset, offset + view.byteLength);\n}\n\nfunction validMode(mode: string): mode is MeshoptMode {\n return GLTF_MESHOPT_MODES.some((candidate) => candidate === mode);\n}\n\nfunction validFilter(filter: string): filter is MeshoptFilter {\n return GLTF_MESHOPT_FILTERS.some((candidate) => candidate === filter);\n}\n\nfunction filterAllowed(mode: MeshoptMode, filter: MeshoptFilter): boolean {\n return mode === 'ATTRIBUTES' || filter === 'NONE';\n}\n\n/**\n * Resolve EXT_meshopt_compression bufferViews before any accessor consumer.\n * Optional assets keep a valid core bufferView fallback when no decoder is\n * installed; required or compressed-only assets fail with a structured error.\n */\nexport async function projectMeshoptBufferViews(\n inputViews: readonly MeshoptBufferViewJson[],\n inputBuffers: readonly Uint8Array[],\n extensionsRequired: readonly string[],\n capability?: GltfBufferViewDecodeCapability,\n): Promise<Result<MeshoptProjection, GltfError>> {\n const buffers = [...inputBuffers];\n const bufferViews = inputViews.map((view) => ({ ...view }));\n let decodedCount = 0;\n\n for (let index = 0; index < bufferViews.length; index++) {\n const view = bufferViews[index];\n if (view === undefined) continue;\n const extension = view.extensions?.EXT_meshopt_compression;\n if (extension === undefined) continue;\n\n const filter = extension.filter ?? 'NONE';\n if (\n !validMode(extension.mode) ||\n !validFilter(filter) ||\n !filterAllowed(extension.mode, filter) ||\n !Number.isInteger(extension.byteStride) ||\n extension.byteStride <= 0 ||\n !Number.isInteger(extension.count) ||\n extension.count <= 0 ||\n !Number.isInteger(extension.byteLength) ||\n extension.byteLength <= 0\n ) {\n return err(\n gltfErr('gltf-meshopt-decode-failed', {\n bufferView: index,\n actual: 'invalid mode/filter/stride/count/byteLength',\n mode: validMode(extension.mode) ? extension.mode : 'ATTRIBUTES',\n filter: validFilter(filter) ? filter : 'NONE',\n }),\n );\n }\n\n const fallback = viewBytes(view, buffers);\n const required = extensionsRequired.includes('EXT_meshopt_compression');\n if (capability === undefined && !required && fallback !== undefined) continue;\n if (capability === undefined) {\n return err(\n gltfErr('gltf-meshopt-decoder-required', {\n bufferView: index,\n actual: required ? 'required' : 'compressed-only',\n hasCoreFallback: fallback !== undefined,\n }),\n );\n }\n\n const compressedBuffer = buffers[extension.buffer];\n const compressedOffset = extension.byteOffset ?? 0;\n if (\n compressedBuffer === undefined ||\n !Number.isInteger(compressedOffset) ||\n compressedOffset < 0 ||\n compressedOffset + extension.byteLength > compressedBuffer.length\n ) {\n return err(\n gltfErr('gltf-meshopt-decode-failed', {\n bufferView: index,\n actual: 'compressed range out of bounds',\n mode: extension.mode,\n filter,\n }),\n );\n }\n\n let decoded: Uint8Array;\n try {\n decoded = await capability.decode({\n source: compressedBuffer.subarray(\n compressedOffset,\n compressedOffset + extension.byteLength,\n ),\n count: extension.count,\n stride: extension.byteStride,\n mode: extension.mode,\n filter,\n });\n } catch (cause) {\n return err(\n gltfErr('gltf-meshopt-decode-failed', {\n bufferView: index,\n actual: `decoder rejected compressed range: ${cause instanceof Error ? cause.message : String(cause)}`,\n mode: extension.mode,\n filter,\n }),\n );\n }\n\n const expectedLength = extension.count * extension.byteStride;\n if (!(decoded instanceof Uint8Array) || decoded.byteLength !== expectedLength) {\n return err(\n gltfErr('gltf-meshopt-decode-failed', {\n bufferView: index,\n actual: `decoded byteLength=${decoded?.byteLength ?? 'invalid'}, expected=${expectedLength}`,\n mode: extension.mode,\n filter,\n }),\n );\n }\n\n const decodedBufferIndex = buffers.length;\n buffers.push(decoded);\n const { extensions: _extensions, ...plainView } = view;\n bufferViews[index] = {\n ...plainView,\n buffer: decodedBufferIndex,\n byteOffset: 0,\n byteLength: expectedLength,\n };\n decodedCount++;\n }\n\n return ok({ bufferViews, buffers, decodedCount });\n}\n","export interface NamedNode {\n readonly name?: string;\n readonly children?: readonly number[];\n}\n\nexport function buildNodeParentMap(nodes: readonly NamedNode[]): ReadonlyMap<number, number> {\n const parents = new Map<number, number>();\n for (let index = 0; index < nodes.length; index++) {\n for (const child of nodes[index]?.children ?? []) parents.set(child, index);\n }\n return parents;\n}\n\nexport function resolveNamedNodePath(\n nodes: readonly NamedNode[],\n parents: ReadonlyMap<number, number>,\n nodeIndex: number,\n):\n | { readonly ok: true; readonly value: readonly string[] }\n | {\n readonly ok: false;\n readonly reason: 'name-missing' | 'hierarchy-cycle';\n readonly nodeIndex: number;\n } {\n const reversed: string[] = [];\n const visited = new Set<number>();\n let current: number | undefined = nodeIndex;\n while (current !== undefined) {\n if (visited.has(current)) {\n return { ok: false, reason: 'hierarchy-cycle', nodeIndex: current };\n }\n visited.add(current);\n const name = nodes[current]?.name;\n if (name === undefined || name.length === 0) {\n return { ok: false, reason: 'name-missing', nodeIndex: current };\n }\n reversed.push(name);\n current = parents.get(current);\n }\n return { ok: true, value: reversed.reverse() };\n}\n","// parse-animation.ts - glTF animation parser (feat-20260523-skin-skeleton-animation M0).\n//\n// Implements parseAnimation(): parses glTF `animations[]` array into\n// GltfAnimationClipRecord[] with duration, channels, and sampler data.\n// Used by parseGltfWithBin to populate GltfDoc.\n//\n// Decision anchors:\n// - plan-strategy D-1 (AnimationClip independent asset)\n// - requirements AC-07 (AnimationClip shape), AC-09 (CUBICSPLINE/morph fail-fast)\n// - requirements AC-10 (IR extension)\n// - charter P3 (fail-fast on unsupported interpolation/morph targets)\n\nimport { deriveAnimationTargetId } from '@forgeax/engine-animation/target-id';\nimport type { AnimationTargetIdValue } from '@forgeax/engine-types';\nimport { decodeF32Accessor } from './accessor/decode-accessor.js';\nimport { err, type GltfError, gltfErr, ok, type Result } from './errors.js';\nimport { buildNodeParentMap, resolveNamedNodePath } from './node-path.js';\n\n/** Supported interpolation modes (CUBICSPLINE is deferred to OOS-skin-cubicspline). */\ntype Interpolation = 'LINEAR' | 'STEP';\n\ninterface ChannelJson {\n readonly sampler: number;\n readonly target: {\n readonly node?: number;\n readonly path: string;\n };\n}\n\ninterface SamplerJson {\n readonly input: number;\n readonly output: number;\n readonly interpolation?: string;\n}\n\ninterface AnimationJson {\n readonly name?: string;\n readonly channels: readonly ChannelJson[];\n readonly samplers: readonly SamplerJson[];\n}\n\nconst ANIMATION_ACCESSOR_TYPES = ['SCALAR', 'VEC2', 'VEC3', 'VEC4'] as const;\n\ninterface AccessorJson {\n readonly bufferView?: number;\n readonly componentType: number;\n readonly type: string;\n readonly count: number;\n readonly byteOffset?: number;\n}\n\ninterface BufferViewJson {\n readonly buffer: number;\n readonly byteOffset?: number;\n readonly byteLength: number;\n}\n\nexport interface GltfAnimationChannelRecord {\n readonly targetId: AnimationTargetIdValue;\n readonly targetNodeIndex: number;\n /** 'translation' | 'rotation' | 'scale' | 'weights'. */\n readonly property: 'translation' | 'rotation' | 'scale' | 'weights';\n /** Sampler driving this channel. */\n readonly sampler: GltfAnimationSamplerRecord;\n}\n\nexport interface GltfAnimationSamplerRecord {\n /** Keyframe timestamp array (ascending). */\n readonly input: Float32Array;\n /** Keyframe value array per element size. */\n readonly output: Float32Array;\n /** 'LINEAR' | 'STEP'. */\n readonly interpolation: Interpolation;\n}\n\nexport interface GltfAnimationClipRecord {\n /** Producer-authored animation name, when the source provides one. */\n readonly name?: string;\n /** Clip duration = max(sampler.input[last]). */\n readonly duration: number;\n /** Per-joint-property channels. */\n readonly channels: readonly GltfAnimationChannelRecord[];\n}\n\n/**\n * Parse glTF animations[] array into GltfAnimationClipRecord[].\n *\n * Only LINEAR and STEP interpolation are supported. CUBICSPLINE triggers\n * fail-fast with 'gltf-animation-cubicspline-unsupported'. Channels targeting\n * morph weights preserve their element-major sampler output for playback.\n */\nexport function parseAnimation(\n animationsJson: readonly AnimationJson[] | undefined,\n nodesJson: readonly { readonly name?: string; readonly children?: readonly number[] }[],\n accessors: readonly AccessorJson[],\n bufferViews: readonly BufferViewJson[],\n buffers: readonly Uint8Array[],\n): Result<readonly GltfAnimationClipRecord[], GltfError> {\n if (animationsJson === undefined || animationsJson.length === 0) {\n return ok([]);\n }\n\n const clips: GltfAnimationClipRecord[] = [];\n const parentOf = buildNodeParentMap(nodesJson);\n const nodeByPath = new Map<string, number>();\n const pathById = new Map<AnimationTargetIdValue, string>();\n\n for (let animIdx = 0; animIdx < animationsJson.length; animIdx++) {\n const anim = animationsJson[animIdx];\n if (anim === undefined) continue;\n\n // Decode samplers first (shared across channels).\n const decodedSamplers: GltfAnimationSamplerRecord[] = [];\n for (let sampIdx = 0; sampIdx < anim.samplers.length; sampIdx++) {\n const sampler = anim.samplers[sampIdx];\n if (sampler === undefined) continue;\n\n const interpolation = (sampler.interpolation ?? 'LINEAR') as string;\n if (interpolation === 'CUBICSPLINE') {\n return err(\n gltfErr('gltf-animation-cubicspline-unsupported', {\n animationIndex: animIdx,\n samplerIndex: sampIdx,\n }),\n );\n }\n if (interpolation !== 'LINEAR' && interpolation !== 'STEP') {\n return err(\n gltfErr('gltf-animation-cubicspline-unsupported', {\n animationIndex: animIdx,\n samplerIndex: sampIdx,\n }),\n );\n }\n\n const inputAcc = accessors[sampler.input];\n if (inputAcc === undefined) {\n return err(\n gltfErr('gltf-buffer-out-of-bounds', {\n accessor: sampler.input,\n byteOffset: 0,\n byteLength: 0,\n bufferIndex: 0,\n }),\n );\n }\n const inputResult = decodeF32Accessor(\n sampler.input,\n inputAcc,\n ANIMATION_ACCESSOR_TYPES,\n bufferViews,\n buffers,\n );\n if (!inputResult.ok) return err(inputResult.error);\n\n const outputAcc = accessors[sampler.output];\n if (outputAcc === undefined) {\n return err(\n gltfErr('gltf-buffer-out-of-bounds', {\n accessor: sampler.output,\n byteOffset: 0,\n byteLength: 0,\n bufferIndex: 0,\n }),\n );\n }\n const outputResult = decodeF32Accessor(\n sampler.output,\n outputAcc,\n ANIMATION_ACCESSOR_TYPES,\n bufferViews,\n buffers,\n );\n if (!outputResult.ok) return err(outputResult.error);\n\n decodedSamplers.push({\n input: inputResult.value,\n output: outputResult.value,\n interpolation: interpolation as Interpolation,\n });\n }\n\n // Decode channels.\n const channels: GltfAnimationChannelRecord[] = [];\n for (let chIdx = 0; chIdx < anim.channels.length; chIdx++) {\n const ch = anim.channels[chIdx];\n if (ch === undefined) continue;\n\n const samplerRecord = decodedSamplers[ch.sampler];\n if (samplerRecord === undefined) {\n return err(\n gltfErr('gltf-buffer-out-of-bounds', {\n accessor: ch.sampler,\n byteOffset: 0,\n byteLength: 0,\n bufferIndex: 0,\n }),\n );\n }\n\n const targetNodeIdx = ch.target.node;\n const path =\n targetNodeIdx === undefined\n ? { ok: false as const, reason: 'name-missing' as const, nodeIndex: -1 }\n : resolveNamedNodePath(nodesJson, parentOf, targetNodeIdx);\n if (!path.ok) {\n return err(\n gltfErr('gltf-animation-target-invalid', {\n reason: path.reason,\n animationIndex: animIdx,\n channelIndex: chIdx,\n nodeIndex: path.nodeIndex,\n }),\n );\n }\n if (\n ch.target.path !== 'weights' &&\n ch.target.path !== 'translation' &&\n ch.target.path !== 'rotation' &&\n ch.target.path !== 'scale'\n ) {\n return err(\n gltfErr('gltf-morph-unsupported', {\n animationIndex: animIdx,\n channelIndex: chIdx,\n nodeIndex: ch.target.node ?? -1,\n }),\n );\n }\n const pathKey = JSON.stringify(path.value);\n const previousNode = nodeByPath.get(pathKey);\n if (previousNode !== undefined && previousNode !== targetNodeIdx) {\n return err(\n gltfErr('gltf-animation-target-invalid', {\n reason: 'path-duplicate',\n animationIndex: animIdx,\n channelIndex: chIdx,\n nodeIndex: targetNodeIdx as number,\n }),\n );\n }\n nodeByPath.set(pathKey, targetNodeIdx as number);\n const targetId = deriveAnimationTargetId(path.value);\n const previousPath = pathById.get(targetId);\n if (previousPath !== undefined && previousPath !== pathKey) {\n return err(\n gltfErr('gltf-animation-target-invalid', {\n reason: 'id-collision',\n animationIndex: animIdx,\n channelIndex: chIdx,\n nodeIndex: targetNodeIdx as number,\n }),\n );\n }\n pathById.set(targetId, pathKey);\n\n channels.push({\n targetId,\n targetNodeIndex: targetNodeIdx as number,\n property: ch.target.path,\n sampler: samplerRecord,\n });\n }\n\n // Compute duration = max(sampler.input[last]) across all channels.\n let duration = 0;\n for (const ch of channels) {\n const input = ch.sampler.input;\n if (input.length > 0) {\n const last = input[input.length - 1];\n if (last !== undefined && last > duration) {\n duration = last;\n }\n }\n }\n\n const name = anim.name?.trim();\n clips.push({\n ...(name === undefined || name.length === 0 ? {} : { name }),\n duration,\n channels,\n });\n }\n\n return ok(clips);\n}\n","// parse-gltf-header.ts - asset.version check for the parsed glTF JSON\n// document (w8). Pure function, no I/O.\n//\n// glTF 2.0 spec section 3.1: every glTF JSON document MUST carry an\n// `asset.version` literal. v1 / v3 are not parsed by this importer\n// (v3 does not exist; v1 is a different format). This step is the gate\n// before any deeper structural traversal.\n//\n// Producers route through `gltfErr` (errors.ts SSOT) so `expected` and\n// `hint` fields stay aligned with the GLTF_ERROR_HINTS table.\n\nimport type { GltfError } from './errors.js';\nimport { err, gltfErr, ok, type Result } from './errors.js';\n\n/** Minimal JSON shape touched by the version gate. */\nexport interface GltfHeaderJson {\n readonly asset?: { readonly version?: string };\n}\n\n/**\n * Validate the top-level `asset.version` field of a parsed glTF document.\n *\n * On success the JSON object is echoed back unchanged (caller already owns\n * the parsed representation). On failure, the closed `GltfErrorCode`\n * surface narrows to either `gltf-malformed-header` (asset block missing)\n * or `gltf-version-unsupported` (version != \"2.0\").\n */\nexport function parseGltfHeader(\n json: unknown,\n filePath: string,\n): Result<GltfHeaderJson, GltfError> {\n if (json === null || typeof json !== 'object' || !('asset' in json)) {\n return err(\n gltfErr('gltf-malformed-header', {\n filePath,\n byteOffset: 0,\n }),\n );\n }\n const asset = (json as GltfHeaderJson).asset;\n if (!asset || typeof asset !== 'object' || typeof asset.version !== 'string') {\n return err(\n gltfErr('gltf-malformed-header', {\n filePath,\n byteOffset: 0,\n }),\n );\n }\n if (asset.version !== '2.0') {\n return err(\n gltfErr('gltf-version-unsupported', {\n filePath,\n actualVersion: asset.version,\n }),\n );\n }\n return ok(json as GltfHeaderJson);\n}\n","// parse-glb-chunks.ts - GLB 2.0 binary container parser (w8).\n//\n// Pure function: ArrayBuffer in, Result<{version, length, jsonChunk, binChunk?}, GltfError> out.\n// No fs, no fetch, no global state. Caller owns I/O.\n//\n// GLB 2.0 layout (Khronos KHR glTF-2.0 GLB section):\n//\n// header (12 bytes, little-endian uint32 each):\n// magic = 0x46546C67 ('glTF')\n// version = 2\n// length = total byte length of the GLB container (header + chunks)\n//\n// chunk (variable):\n// chunkLength (uint32 LE)\n// chunkType (uint32 LE)\n// 0x4E4F534A = 'JSON' - exactly one, must be the first chunk\n// 0x004E4942 = 'BIN' - at most one, must be the second chunk\n// chunkData (chunkLength bytes; padded so chunkLength is a multiple of 4)\n//\n// `parseGltfHeader` (asset.version check) lives in parse-gltf-header.ts and\n// is re-exported here so call sites can grab both binary and JSON gates from\n// a single entry without walking module paths.\n\nimport { err, type GltfError, gltfErr, ok, type Result } from './errors.js';\nimport { parseGltfHeader } from './parse-gltf-header.js';\n\nexport type { GltfHeaderJson } from './parse-gltf-header.js';\nexport { parseGltfHeader };\n\nconst GLB_HEADER_SIZE = 12;\nconst GLB_MAGIC = 0x46546c67;\nconst CHUNK_HEADER_SIZE = 8;\nconst CHUNK_TYPE_JSON = 0x4e4f534a;\nconst CHUNK_TYPE_BIN = 0x004e4942;\n\n/** Result payload of {@link parseGlbChunks}. */\nexport interface GlbChunks {\n readonly version: number;\n readonly length: number;\n readonly jsonChunk: Uint8Array;\n readonly binChunk?: Uint8Array;\n}\n\n/**\n * Split a GLB 2.0 binary container into its `JSON` chunk and optional\n * `BIN` chunk. Returns the declared `version` and `length` for the caller\n * to surface in diagnostics.\n *\n * Failure path returns one of:\n * - `gltf-malformed-header` (magic / chunk shape / declared length / missing JSON)\n * - `gltf-version-unsupported` (version != 2)\n *\n * The function is pure: no fs / network access; the caller passes the\n * already-loaded ArrayBuffer.\n */\nexport function parseGlbChunks(\n buffer: ArrayBuffer,\n filePath: string,\n): Result<GlbChunks, GltfError> {\n if (buffer.byteLength < GLB_HEADER_SIZE) {\n return err(\n gltfErr('gltf-malformed-header', {\n filePath,\n byteOffset: 0,\n }),\n );\n }\n const view = new DataView(buffer);\n const magic = view.getUint32(0, true);\n if (magic !== GLB_MAGIC) {\n return err(\n gltfErr('gltf-malformed-header', {\n filePath,\n byteOffset: 0,\n magic,\n }),\n );\n }\n const version = view.getUint32(4, true);\n if (version !== 2) {\n return err(\n gltfErr('gltf-version-unsupported', {\n filePath,\n actualVersion: String(version),\n }),\n );\n }\n const declaredLength = view.getUint32(8, true);\n if (declaredLength !== buffer.byteLength) {\n return err(\n gltfErr('gltf-malformed-header', {\n filePath,\n byteOffset: 8,\n }),\n );\n }\n\n // First chunk MUST be JSON.\n let offset = GLB_HEADER_SIZE;\n if (offset + CHUNK_HEADER_SIZE > buffer.byteLength) {\n return err(\n gltfErr('gltf-malformed-header', {\n filePath,\n byteOffset: offset,\n }),\n );\n }\n const jsonChunkLength = view.getUint32(offset, true);\n const jsonChunkType = view.getUint32(offset + 4, true);\n if (jsonChunkType !== CHUNK_TYPE_JSON) {\n return err(\n gltfErr('gltf-malformed-header', {\n filePath,\n byteOffset: offset + 4,\n }),\n );\n }\n if (offset + CHUNK_HEADER_SIZE + jsonChunkLength > buffer.byteLength) {\n return err(\n gltfErr('gltf-malformed-header', {\n filePath,\n byteOffset: offset,\n }),\n );\n }\n const jsonChunk = new Uint8Array(buffer, offset + CHUNK_HEADER_SIZE, jsonChunkLength);\n offset += CHUNK_HEADER_SIZE + jsonChunkLength;\n\n // Optional BIN chunk follows JSON.\n let binChunk: Uint8Array | undefined;\n if (offset < buffer.byteLength) {\n if (offset + CHUNK_HEADER_SIZE > buffer.byteLength) {\n return err(\n gltfErr('gltf-malformed-header', {\n filePath,\n byteOffset: offset,\n }),\n );\n }\n const binChunkLength = view.getUint32(offset, true);\n const binChunkType = view.getUint32(offset + 4, true);\n if (binChunkType !== CHUNK_TYPE_BIN) {\n return err(\n gltfErr('gltf-malformed-header', {\n filePath,\n byteOffset: offset + 4,\n }),\n );\n }\n if (offset + CHUNK_HEADER_SIZE + binChunkLength > buffer.byteLength) {\n return err(\n gltfErr('gltf-malformed-header', {\n filePath,\n byteOffset: offset,\n }),\n );\n }\n binChunk = new Uint8Array(buffer, offset + CHUNK_HEADER_SIZE, binChunkLength);\n }\n\n return ok({\n version,\n length: declaredLength,\n jsonChunk,\n ...(binChunk === undefined ? {} : { binChunk }),\n });\n}\n","// parse-skin.ts - glTF skin parser (feat-20260523-skin-skeleton-animation M0).\n//\n// Implements parseSkin(): parses glTF `skins[]` array into GltfSkeletonRecord[]\n// with IBM (inverse bind matrices) and jointPaths (Name-component path from\n// scene root). Used by parseGltfWithBin to populate GltfDoc.\n//\n// Decision anchors:\n// - plan-strategy D-1 (3-asset separation: IBM / skin binding / animation clip)\n// - plan-strategy D-2 (skin index dedupe via reimport reuse managed by toAssetPack)\n// - requirements AC-03 (skin index dedupe), AC-05 (jointPaths + Name missing fail-fast)\n// - requirements AC-10 (IR extension), AC-27 (BindPose static AABB)\n// - plan-strategy D-11 (BindPose AABB importer-phase, per-frame zero cost)\n// - charter P3 (fail-fast on invalid data)\n\nimport { decodeF32Accessor } from './accessor/decode-accessor.js';\nimport { err, type GltfError, gltfErr, ok, type Result } from './errors.js';\nimport { buildNodeParentMap, resolveNamedNodePath } from './node-path.js';\n\n/** Maximum joints per skin (glTF spec practical limit). */\nconst MAX_JOINTS = 256;\n\n/**\n * Skeleton intermediate representation produced by parseSkin.\n *\n * Each entry corresponds to one glTF skin[] index. `jointPaths` is a\n * parallel array to the skeleton's joints; each path is the sequence of\n * Name-component values from the scene root to the joint node.\n */\nexport interface GltfSkeletonRecord {\n /** Number of joints in this skeleton (= IBM length / 16). */\n readonly jointCount: number;\n /** Inverse bind matrices, Float32Array of length jointCount * 16. */\n readonly inverseBindMatrices: Float32Array;\n /** Per-joint Name path from scene root (parallel to joints array). */\n readonly jointPaths: readonly string[];\n}\n\ninterface SkinJson {\n readonly name?: string;\n readonly joints: readonly number[];\n readonly inverseBindMatrices?: number;\n}\n\ninterface NodeJson {\n readonly name?: string;\n readonly mesh?: number;\n readonly children?: readonly number[];\n readonly skin?: number;\n}\n\ninterface AccessorJson {\n readonly bufferView?: number;\n readonly componentType: number;\n readonly type: string;\n readonly count: number;\n readonly byteOffset?: number;\n}\n\ninterface BufferViewJson {\n readonly buffer: number;\n readonly byteOffset?: number;\n readonly byteLength: number;\n readonly byteStride?: number;\n}\n\nconst SKIN_ACCESSOR_TYPES = ['MAT4'] as const;\n\n/** Build a column-major mat4 identity Float32Array (16 floats). */\nfunction identityMat4(): Float32Array {\n const m = new Float32Array(16);\n m[0] = 1;\n m[5] = 1;\n m[10] = 1;\n m[15] = 1;\n return m;\n}\n\n/**\n * Build the jointPath for a single joint: find the Name-component path from\n * the root of the scene graph to the joint node.\n *\n * Uses recursive BFS-like upward traversal: for each joint node index,\n * find the node's name and verify it's reachable from root.\n * Returns the sequence of names from root to joint.\n *\n * On first miss (node has no name), emits 'gltf-skin-joint-name-missing'.\n */\nfunction resolveJointPath(\n nodeIndex: number,\n nodes: readonly NodeJson[],\n parentOf: ReadonlyMap<number, number>,\n skinIndex: number,\n jointPathIndex: number,\n): Result<readonly string[], GltfError> {\n const path = resolveNamedNodePath(nodes, parentOf, nodeIndex);\n if (!path.ok) {\n return err(\n gltfErr('gltf-skin-joint-name-missing', {\n reason: path.reason,\n skinIndex,\n jointPathIndex,\n nodeIndex: path.nodeIndex,\n }),\n );\n }\n return ok(path.value);\n}\n\n/**\n * Parse glTF skins[] array into GltfSkeletonRecord[].\n *\n * For each skin:\n * 1. Decode IBM accessor (or fill identity if absent)\n * 2. Resolve jointPaths from scene node hierarchy\n * 3. Fail-fast on joint count > MAX_JOINTS or missing joint names\n */\nexport function parseSkin(\n skinsJson: readonly SkinJson[] | undefined,\n nodesJson: readonly NodeJson[],\n accessors: readonly AccessorJson[],\n bufferViews: readonly BufferViewJson[],\n buffers: readonly Uint8Array[],\n): Result<readonly GltfSkeletonRecord[], GltfError> {\n if (skinsJson === undefined || skinsJson.length === 0) {\n return ok([]);\n }\n\n const records: GltfSkeletonRecord[] = [];\n const parentOf = buildNodeParentMap(nodesJson);\n\n for (let skinIdx = 0; skinIdx < skinsJson.length; skinIdx++) {\n const skin = skinsJson[skinIdx];\n if (skin === undefined) continue;\n\n const joints = skin.joints;\n if (joints.length > MAX_JOINTS) {\n return err(\n gltfErr('gltf-skin-joint-count-exceeded', {\n skinIndex: skinIdx,\n jointCount: joints.length,\n maxJoints: MAX_JOINTS,\n }),\n );\n }\n\n // Decode IBM, or fill identity matrix.\n let ibm: Float32Array;\n if (skin.inverseBindMatrices !== undefined) {\n const ibmAccIdx = skin.inverseBindMatrices;\n const ibmAcc = accessors[ibmAccIdx];\n if (ibmAcc === undefined) {\n return err(\n gltfErr('gltf-buffer-out-of-bounds', {\n accessor: ibmAccIdx,\n byteOffset: 0,\n byteLength: 0,\n bufferIndex: 0,\n }),\n );\n }\n const ibmResult = decodeF32Accessor(\n ibmAccIdx,\n ibmAcc,\n SKIN_ACCESSOR_TYPES,\n bufferViews,\n buffers,\n );\n if (!ibmResult.ok) return err(ibmResult.error);\n ibm = ibmResult.value;\n } else {\n // Fill identity: each joint gets a 4x4 identity.\n ibm = new Float32Array(joints.length * 16);\n for (let j = 0; j < joints.length; j++) {\n ibm.set(identityMat4(), j * 16);\n }\n }\n\n // Resolve jointPaths.\n const jointPaths: string[] = [];\n for (let j = 0; j < joints.length; j++) {\n const jointNodeIndex = joints[j];\n if (jointNodeIndex === undefined) continue;\n const pathResult = resolveJointPath(jointNodeIndex, nodesJson, parentOf, skinIdx, j);\n if (!pathResult.ok) return err(pathResult.error);\n jointPaths.push(pathResult.value.join('/'));\n }\n\n records.push({\n jointCount: joints.length,\n inverseBindMatrices: ibm,\n jointPaths,\n });\n }\n\n return ok(records);\n}\n\n/**\n * Compute the BindPose static AABB for a skinned mesh's vertex positions.\n *\n * At bind pose, joint_bind = IBM^{-1}, so skinning collapses:\n * world_pos = Sum(w_i * joint_bind_i * IBM_i * local_pos) = local_pos\n * Therefore the BindPose AABB is simply the local position bounds.\n *\n * Per-frame zero cost: stored in mesh asset metadata at importer time.\n * Dynamic AABB for animated poses is deferred to OOS-skin-dyn-bounds.\n *\n * Returns { min: [x,y,z], max: [x,y,z] } or undefined if positions is empty.\n */\nexport function computeBindPoseAABB(positions: Float32Array):\n | {\n readonly min: readonly [number, number, number];\n readonly max: readonly [number, number, number];\n }\n | undefined {\n if (positions.length < 3) return undefined;\n let minX = positions[0] ?? 0;\n let minY = positions[1] ?? 0;\n let minZ = positions[2] ?? 0;\n let maxX = minX;\n let maxY = minY;\n let maxZ = minZ;\n for (let i = 3; i < positions.length; i += 3) {\n const x = positions[i] ?? 0;\n const y = positions[i + 1] ?? 0;\n const z = positions[i + 2] ?? 0;\n if (x < minX) minX = x;\n if (y < minY) minY = y;\n if (z < minZ) minZ = z;\n if (x > maxX) maxX = x;\n if (y > maxY) maxY = y;\n if (z > maxZ) maxZ = z;\n }\n return { min: [minX, minY, minZ], max: [maxX, maxY, maxZ] };\n}\n\n/** Re-export MAX_JOINTS for use by downstream modules. */\nexport { MAX_JOINTS };\n","// transform.ts - decomposeNodeTransform (w11).\n//\n// glTF 2.0 spec section 3.7 (node):\n// - node.matrix : 16 floats column-major (mutually exclusive with TRS,\n// per spec, but real-world DCC tools occasionally\n// export both - forgeax tolerates this with stderr\n// warn + diagnostics record per requirements section\n// boundary cases)\n// - node.translation: VEC3 (default identity translation)\n// - node.rotation : VEC4 quaternion (default identity rotation)\n// - node.scale : VEC3 (default identity scale)\n//\n// This wrapper hides the math package's in-place 3-arg `mat4.decompose`\n// signature behind a POD readonly tuple return so the importer surface\n// stays Vec3/Quat brand-free at the API boundary (charter proposition 5\n// consistent abstraction; plan-strategy decision section 2.7 / OQ-2).\n\nimport { mat4, quat, vec3 } from '@forgeax/engine-math';\n\n/** glTF VEC3 literal accepted by node.translation / node.scale. */\nexport type Vec3Tuple = readonly [number, number, number];\n/** glTF VEC4 quaternion literal accepted by node.rotation. */\nexport type Vec4Tuple = readonly [number, number, number, number];\n\n/** Minimal node JSON shape touched by the decomposer. */\nexport interface NodeTransformJson {\n readonly matrix?: readonly number[];\n readonly translation?: readonly number[];\n readonly rotation?: readonly number[];\n readonly scale?: readonly number[];\n}\n\n/** Mutable diagnostics accumulator (writes to .matrixTrsCoexistNodes only). */\nexport interface TransformDiagnostics {\n matrixTrsCoexistNodes: number[];\n}\n\nexport interface DecomposedTransform {\n readonly translation: Vec3Tuple;\n readonly rotation: Vec4Tuple;\n readonly scale: Vec3Tuple;\n}\n\nconst IDENTITY: DecomposedTransform = {\n translation: [0, 0, 0] as const,\n rotation: [0, 0, 0, 1] as const,\n scale: [1, 1, 1] as const,\n};\n\nfunction tuple3(arr: readonly number[] | undefined, fallback: Vec3Tuple): Vec3Tuple {\n if (arr === undefined || arr.length < 3) return fallback;\n return [arr[0] ?? fallback[0], arr[1] ?? fallback[1], arr[2] ?? fallback[2]];\n}\n\nfunction tuple4(arr: readonly number[] | undefined, fallback: Vec4Tuple): Vec4Tuple {\n if (arr === undefined || arr.length < 4) return fallback;\n return [\n arr[0] ?? fallback[0],\n arr[1] ?? fallback[1],\n arr[2] ?? fallback[2],\n arr[3] ?? fallback[3],\n ];\n}\n\n/**\n * Decompose a glTF node's transform into a POD readonly TRS triple.\n *\n * Decision tree:\n * 1. matrix present -> mat4.decompose 3-arg in-place; if\n * any TRS field is also present,\n * stderr warn + push nodeIndex into\n * diagnostics.matrixTrsCoexistNodes.\n * 2. only TRS fields present -> use them verbatim (defaults filled).\n * 3. nothing present -> identity (0/0/0, 0/0/0/1, 1/1/1).\n *\n * Return type is `readonly` POD tuple, deliberately not Vec3/Quat from\n * @forgeax/engine-math, so the importer's IR stays brand-free\n * (plan-strategy decision section 2.7 / OQ-2).\n */\nexport function decomposeNodeTransform(\n node: NodeTransformJson,\n nodeIndex: number,\n diagnostics: TransformDiagnostics,\n): DecomposedTransform {\n const hasMatrix = node.matrix !== undefined && node.matrix.length === 16;\n const hasTrs =\n node.translation !== undefined || node.rotation !== undefined || node.scale !== undefined;\n\n if (hasMatrix) {\n if (hasTrs) {\n console.error(`[warn] node[${nodeIndex}] has both matrix and TRS, matrix takes precedence`);\n diagnostics.matrixTrsCoexistNodes.push(nodeIndex);\n }\n const out_t = vec3.create();\n const out_r = quat.create();\n const out_s = vec3.create(1, 1, 1);\n // node.matrix is glTF column-major float[16]; mat4.decompose accepts\n // Mat4Like (any indexable [0..15] number container).\n const m = node.matrix as readonly number[];\n mat4.decompose(out_t, out_r, out_s, m as unknown as Parameters<typeof mat4.decompose>[3]);\n return {\n translation: [out_t[0] ?? 0, out_t[1] ?? 0, out_t[2] ?? 0] as const,\n rotation: [out_r[0] ?? 0, out_r[1] ?? 0, out_r[2] ?? 0, out_r[3] ?? 1] as const,\n scale: [out_s[0] ?? 1, out_s[1] ?? 1, out_s[2] ?? 1] as const,\n };\n }\n\n if (!hasTrs) {\n return IDENTITY;\n }\n\n return {\n translation: tuple3(node.translation, IDENTITY.translation),\n rotation: tuple4(node.rotation, IDENTITY.rotation),\n scale: tuple3(node.scale, IDENTITY.scale),\n };\n}\n","// parse-gltf.ts - JSON-side glTF importer entry.\n// The public parse, GLB, asset-pack, mesh, and scene helpers live here.\n\nimport { mat4, quat, vec3 } from '@forgeax/engine-math';\nimport {\n IMPORT_ERROR_HINTS,\n ImportError,\n MESH_MATERIAL_SLOT_SOURCE_OVERRIDE_PAYLOAD_SCHEMA,\n type MeshMaterialSlotTopologyEntry,\n reconcileMeshMaterialSlotTopology,\n} from '@forgeax/engine-types';\nimport {\n type AccessorJson,\n type BufferViewJson,\n COMPONENT_TYPE,\n decodeAccessor,\n} from './accessor/decode-accessor.js';\nimport { decodeColorAccessor } from './accessor/decode-color.js';\nimport { checkExtensions, type GltfExtensionsJson } from './check-extensions.js';\nimport { Base64DecodeError, dataUriBase64Payload, decodeBase64 } from './data-uri.js';\nimport { err, type GltfError, gltfErr, ok, type Result } from './errors.js';\nimport { type GltfLodRelation, parseGltfLodExtension } from './lod/parse-lod.js';\nimport { projectGltfLodMeta } from './lod/project-meta.js';\nimport {\n type GltfImageIr,\n type GltfMaterialIr,\n type GltfMaterialJson,\n type GltfSamplerIr,\n type GltfTextureIr,\n parseMaterial,\n} from './material/parse-material.js';\nimport {\n type GltfBufferViewDecodeCapability,\n type MeshoptBufferViewJson,\n projectMeshoptBufferViews,\n} from './meshopt-decode.js';\nimport { type GltfAnimationClipRecord, parseAnimation } from './parse-animation.js';\nimport { parseGlbChunks } from './parse-glb-chunks.js';\nimport { parseGltfHeader } from './parse-gltf-header.js';\nimport { type GltfSkeletonRecord, parseSkin } from './parse-skin.js';\nimport {\n type GltfDocItem,\n type GltfMetaJson,\n type GltfSubAssetEntry,\n reimportReuseMeta,\n} from './reimport-reuse-meta.js';\nimport type { GltfSourceKeyError } from './source-key.js';\nimport { type DecomposedTransform, decomposeNodeTransform } from './transform.js';\n\nexport type {\n GltfImageIr,\n GltfMaterialIr,\n GltfMaterialJson,\n GltfNormalTextureInfoIr,\n GltfOcclusionTextureInfoIr,\n GltfSamplerIr,\n GltfTextureInfoIr,\n GltfTextureIr,\n GltfTextureTransformIr,\n NormalTextureInfoJson,\n OcclusionTextureInfoJson,\n TextureInfoJson,\n} from './material/parse-material.js';\n\nexport interface MeshPrimitiveJson {\n readonly attributes?: Record<string, number>;\n readonly indices?: number;\n readonly material?: number;\n readonly mode?: number;\n readonly targets?: ReadonlyArray<Record<string, number>>;\n}\n\nexport interface MeshJson {\n readonly name?: string;\n readonly weights?: readonly number[];\n readonly primitives: readonly MeshPrimitiveJson[];\n}\n\n// Tier-B IR: validated glTF JSON projected into downstream POD records.\n\ninterface InstancingAttributes {\n readonly TRANSLATION?: number;\n readonly ROTATION?: number;\n readonly SCALE?: number;\n}\n\n/**\n * Decode EXT_mesh_gpu_instancing attributes for a single node.\n *\n * Cross-validates that all present TRS accessor counts agree (spec\n * MUST clause \"Extending nodes with instance attributes\"). Missing\n * accessors fall back to identity (translation=(0,0,0),\n * rotation=(0,0,0,1), scale=(1,1,1)). Composes N column-major mat4 via\n * @forgeax/engine-math `mat4.compose`, packing them into a single\n * Float32Array of length N*16. Pure function: no fs / fetch / throw.\n */\nfunction decodeNodeInstancing(\n nodeIndex: number,\n attributes: InstancingAttributes,\n accessors: readonly AccessorJson[],\n bufferViews: readonly BufferViewJson[],\n buffers: readonly Uint8Array[],\n): Result<NodeInstancingIr, GltfError> {\n const tIdx = attributes.TRANSLATION;\n const rIdx = attributes.ROTATION;\n const sIdx = attributes.SCALE;\n\n let count: number | undefined;\n const setOrCheck = (label: 'TRANSLATION' | 'ROTATION' | 'SCALE', n: number): GltfError | null => {\n if (count === undefined) {\n count = n;\n return null;\n }\n if (n !== count) {\n return gltfErr('gltf-instancing-count-mismatch', {\n nodeIndex,\n accessor: label,\n expectedCount: count,\n actualCount: n,\n });\n }\n return null;\n };\n\n let tValues: Float32Array | undefined;\n if (tIdx !== undefined) {\n const acc = accessors[tIdx];\n if (acc === undefined) return err(unknownAccessor(tIdx));\n const e = setOrCheck('TRANSLATION', acc.count);\n if (e !== null) return err(e);\n const decoded = decodeAttributeAccessor(tIdx, acc, bufferViews, buffers);\n if (!decoded.ok) return err(decoded.error);\n tValues = decoded.value;\n }\n let rValues: Float32Array | undefined;\n if (rIdx !== undefined) {\n const acc = accessors[rIdx];\n if (acc === undefined) return err(unknownAccessor(rIdx));\n const e = setOrCheck('ROTATION', acc.count);\n if (e !== null) return err(e);\n const decoded = decodeAttributeAccessor(rIdx, acc, bufferViews, buffers);\n if (!decoded.ok) return err(decoded.error);\n rValues = decoded.value;\n }\n let sValues: Float32Array | undefined;\n if (sIdx !== undefined) {\n const acc = accessors[sIdx];\n if (acc === undefined) return err(unknownAccessor(sIdx));\n const e = setOrCheck('SCALE', acc.count);\n if (e !== null) return err(e);\n const decoded = decodeAttributeAccessor(sIdx, acc, bufferViews, buffers);\n if (!decoded.ok) return err(decoded.error);\n sValues = decoded.value;\n }\n\n const n = count ?? 0;\n const transforms = new Float32Array(n * 16);\n const tmp = mat4.create();\n const tv = vec3.create();\n const rv = quat.create();\n rv[3] = 1;\n const sv = vec3.create(1, 1, 1);\n for (let i = 0; i < n; i++) {\n if (tValues !== undefined) {\n tv[0] = tValues[i * 3] ?? 0;\n tv[1] = tValues[i * 3 + 1] ?? 0;\n tv[2] = tValues[i * 3 + 2] ?? 0;\n } else {\n tv[0] = 0;\n tv[1] = 0;\n tv[2] = 0;\n }\n if (rValues !== undefined) {\n rv[0] = rValues[i * 4] ?? 0;\n rv[1] = rValues[i * 4 + 1] ?? 0;\n rv[2] = rValues[i * 4 + 2] ?? 0;\n rv[3] = rValues[i * 4 + 3] ?? 1;\n } else {\n rv[0] = 0;\n rv[1] = 0;\n rv[2] = 0;\n rv[3] = 1;\n }\n if (sValues !== undefined) {\n sv[0] = sValues[i * 3] ?? 1;\n sv[1] = sValues[i * 3 + 1] ?? 1;\n sv[2] = sValues[i * 3 + 2] ?? 1;\n } else {\n sv[0] = 1;\n sv[1] = 1;\n sv[2] = 1;\n }\n mat4.compose(tmp, tv, rv, sv);\n for (let k = 0; k < 16; k++) {\n transforms[i * 16 + k] = tmp[k] ?? 0;\n }\n }\n\n return ok({ count: n, transforms });\n}\n\nfunction unknownAccessor(accessorIndex: number): GltfError {\n return gltfErr('gltf-accessor-type-mismatch', {\n accessorIndex,\n reason: 'unknownComponentType',\n });\n}\n\nfunction decodeAttributeAccessor(\n accessorIndex: number,\n accessor: AccessorJson,\n bufferViews: readonly BufferViewJson[],\n buffers: readonly Uint8Array[],\n): Result<Float32Array, GltfError> {\n const view = bufferViews[accessor.bufferView ?? -1];\n if (view === undefined) return err(unknownAccessor(accessorIndex));\n const buf = buffers[view.buffer];\n if (buf === undefined) return err(unknownAccessor(accessorIndex));\n const decoded = decodeAccessor({\n accessorIndex,\n accessor,\n bufferView: view,\n buffer: buf,\n role: 'attribute',\n });\n if (!decoded.ok) return err(decoded.error);\n if (decoded.value.kind !== 'f32') return err(unknownAccessor(accessorIndex));\n return ok(decoded.value.data);\n}\n\nexport interface GltfMeshIr {\n readonly name?: string;\n readonly positions: Float32Array;\n readonly normals?: Float32Array;\n readonly texcoord0?: Float32Array;\n /** TEXCOORD_1 per-vertex UV set 1. */\n readonly texcoord1?: Float32Array;\n /** TEXCOORD_2 per-vertex UV set 2. */\n readonly texcoord2?: Float32Array;\n /** TEXCOORD_3 per-vertex UV set 3. */\n readonly texcoord3?: Float32Array;\n /** TEXCOORD_4 per-vertex UV set 4. */\n readonly texcoord4?: Float32Array;\n /** TEXCOORD_5 per-vertex UV set 5. */\n readonly texcoord5?: Float32Array;\n /** TEXCOORD_6 per-vertex UV set 6. */\n readonly texcoord6?: Float32Array;\n /** TEXCOORD_7 per-vertex UV set 7. */\n readonly texcoord7?: Float32Array;\n readonly tangents?: Float32Array;\n /** COLOR_0 importer carrier. */\n readonly colors0?: Float32Array;\n /** JOINTS_0 per-vertex joint indices. */\n readonly joints0?: Uint16Array;\n /** WEIGHTS_0 per-vertex skin weights. */\n readonly weights0?: Float32Array;\n readonly morphTargets?: readonly {\n readonly position?: Float32Array;\n readonly normal?: Float32Array;\n readonly tangent?: Float32Array;\n }[];\n readonly morphWeights?: Float32Array;\n /** Undefined means non-indexed; otherwise source width is preserved. */\n readonly indices?: Uint16Array | Uint32Array;\n readonly materialIndex: number | null;\n /** Owning glTF mesh index; multiple IR rows may share it after flattening. */\n readonly meshIndex: number;\n}\n\nexport interface NodeInstancingIr {\n /** Number of instances. */\n readonly count: number;\n /** Column-major transforms packed into one Float32Array. */\n readonly transforms: Float32Array;\n}\n\nexport type GltfPunctualLightType = 'directional' | 'point' | 'spot';\n\nexport interface GltfPunctualLightIr {\n readonly type: GltfPunctualLightType;\n readonly color: readonly [number, number, number];\n readonly intensity: number;\n readonly range?: number;\n readonly spot?: {\n readonly innerConeAngle: number;\n readonly outerConeAngle: number;\n };\n}\n\nexport interface GltfNodeIr {\n readonly name?: string;\n readonly transform: DecomposedTransform;\n readonly meshIndex: number | null;\n /** Node-authored morph weights override mesh defaults. */\n readonly morphWeights?: Float32Array;\n readonly skinIndex: number | null;\n readonly children: readonly number[];\n readonly instancing?: NodeInstancingIr;\n readonly camera: number | null;\n readonly lightIndex?: number | null;\n}\n\nexport interface GltfSceneIr {\n readonly name?: string;\n readonly nodes: readonly number[];\n}\n\nexport interface GltfDiagnosticsIr {\n readonly nodeNames: readonly string[];\n readonly unsupportedExtensions: readonly string[];\n readonly matrixTrsCoexistNodes: readonly number[];\n}\n\nexport interface GltfDoc {\n readonly meshes: readonly GltfMeshIr[];\n readonly materials: readonly GltfMaterialIr[];\n readonly nodes: readonly GltfNodeIr[];\n readonly scenes: readonly GltfSceneIr[];\n readonly textures: readonly GltfTextureIr[] | undefined;\n readonly images: readonly GltfImageIr[] | undefined;\n readonly samplers: readonly GltfSamplerIr[] | undefined;\n readonly skeletons: readonly GltfSkeletonRecord[];\n readonly animationClips: readonly GltfAnimationClipRecord[];\n readonly defaultSceneIndex: number;\n readonly diagnostics: GltfDiagnosticsIr;\n /** KHR_lights_punctual author facts, kept in source units for the bridge. */\n readonly lights?: readonly GltfPunctualLightIr[];\n /** Raw extension projection retained for bridge-only hand-constructed docs. */\n readonly extensions?: {\n readonly KHR_lights_punctual?: {\n readonly lights?: readonly GltfPunctualLightIr[];\n };\n };\n /**\n * Original glTF-mesh-index -> number of primitives that mesh expanded into\n * (feat-20260608 round-2). parseGltf flattens N glTF meshes with M_i\n * primitives into sum(M_i) GltfMeshIr entries; this map preserves the M_i so\n * downstream consumers (gltfDocToSceneAsset's `meshPrimitiveCount` param)\n * can map a glTF mesh index back to the flat-GltfMeshIr offset range without\n * re-parsing JSON.\n *\n * Optional for backwards compatibility with hand-constructed test\n * fixtures; producers from parseGltf / parseGlb always populate it.\n */\n readonly meshPrimitiveCount?: ReadonlyMap<number, number>;\n readonly lod?: GltfLodRelation;\n}\n\ninterface BuffersJson {\n readonly byteLength: number;\n readonly uri?: string;\n}\n\ninterface RootGltfJson extends GltfExtensionsJson {\n readonly asset?: { readonly version?: string };\n readonly scene?: number;\n readonly scenes?: ReadonlyArray<{ readonly name?: string; readonly nodes?: readonly number[] }>;\n readonly nodes?: ReadonlyArray<{\n readonly name?: string;\n readonly mesh?: number;\n readonly skin?: number;\n readonly camera?: number;\n readonly children?: readonly number[];\n readonly matrix?: readonly number[];\n readonly translation?: readonly number[];\n readonly rotation?: readonly number[];\n readonly scale?: readonly number[];\n readonly weights?: readonly number[];\n readonly extras?: { readonly MSFT_screencoverage?: readonly number[] };\n readonly extensions?: {\n readonly KHR_lights_punctual?: {\n readonly light?: number;\n };\n readonly EXT_mesh_gpu_instancing?: {\n readonly attributes?: {\n readonly TRANSLATION?: number;\n readonly ROTATION?: number;\n readonly SCALE?: number;\n };\n };\n readonly MSFT_lod?: { readonly ids?: readonly number[] };\n };\n }>;\n readonly extensions?: {\n readonly KHR_lights_punctual?: {\n readonly lights?: ReadonlyArray<{\n readonly type?: string;\n readonly color?: readonly number[];\n readonly intensity?: number;\n readonly range?: number;\n readonly spot?: {\n readonly innerConeAngle?: number;\n readonly outerConeAngle?: number;\n };\n }>;\n };\n readonly MSFT_screencoverage?: { readonly scales?: readonly number[] };\n };\n readonly skins?: ReadonlyArray<{\n readonly name?: string;\n readonly joints: readonly number[];\n readonly inverseBindMatrices?: number;\n }>;\n readonly meshes?: readonly MeshJson[];\n readonly materials?: ReadonlyArray<GltfMaterialJson>;\n readonly textures?: ReadonlyArray<{\n readonly sampler?: number;\n readonly source?: number;\n readonly name?: string;\n }>;\n readonly images?: ReadonlyArray<{\n readonly uri?: string;\n readonly mimeType?: string;\n readonly bufferView?: number;\n readonly name?: string;\n }>;\n readonly samplers?: ReadonlyArray<{\n readonly magFilter?: number;\n readonly minFilter?: number;\n readonly wrapS?: number;\n readonly wrapT?: number;\n readonly name?: string;\n }>;\n readonly accessors?: readonly AccessorJson[];\n readonly bufferViews?: readonly BufferViewJson[];\n readonly buffers?: readonly BuffersJson[];\n readonly animations?: ReadonlyArray<{\n readonly name?: string;\n readonly channels: ReadonlyArray<{\n readonly sampler: number;\n readonly target: {\n readonly node?: number;\n readonly path: string;\n };\n }>;\n readonly samplers: ReadonlyArray<{\n readonly input: number;\n readonly output: number;\n readonly interpolation?: string;\n }>;\n }>;\n}\n\nexport type ExternalLoader = (uri: string) => Promise<ArrayBuffer>;\n\nasync function resolveBuffer(\n buf: BuffersJson,\n externalLoader: ExternalLoader,\n binChunk: Uint8Array | undefined,\n): Promise<Uint8Array> {\n if (buf.uri === undefined) {\n // GLB BIN chunk slot.\n if (binChunk === undefined) {\n throw new Error('parseGltf: buffer 0 has no uri and no GLB BIN chunk available');\n }\n return binChunk;\n }\n const dataPayload = dataUriBase64Payload(buf.uri);\n if (dataPayload !== undefined) {\n return decodeBase64(dataPayload);\n }\n const arrayBuffer = await externalLoader(buf.uri);\n return new Uint8Array(arrayBuffer);\n}\n\ninterface ParseGltfInternalsContext {\n readonly externalLoader: ExternalLoader;\n readonly binChunk?: Uint8Array;\n readonly filePath: string;\n readonly meshopt?: GltfBufferViewDecodeCapability;\n}\n\ntype GltfParseError = GltfError | ImportError;\n\nfunction invalidBufferDataUriError(\n filePath: string,\n bufferIndex: number,\n cause: Base64DecodeError,\n): ImportError {\n return new ImportError({\n code: 'source-validation-failed',\n expected: `glTF buffer ${bufferIndex} data URI to contain a valid base64 payload`,\n hint: IMPORT_ERROR_HINTS['source-validation-failed'],\n detail: {\n diagnostics: [\n {\n code: 'gltf-buffer-data-uri-invalid',\n severity: 'error',\n sourcePath: filePath,\n sourceRange: { start: 0, end: 0, line: 1, column: 1 },\n rule: 'gltf-buffer-data-uri-base64',\n expected: 'a valid base64 payload after ;base64,',\n actual: `buffer ${bufferIndex}: ${cause.message}`,\n hint: 'repair the buffer data URI or provide a valid external .bin sibling',\n },\n ],\n },\n });\n}\n\nexport interface GltfParseOptions {\n readonly meshopt?: GltfBufferViewDecodeCapability;\n}\n\nfunction parsePunctualLights(\n json: RootGltfJson,\n filePath: string,\n): Result<readonly GltfPunctualLightIr[], GltfError> {\n const source = json.extensions?.KHR_lights_punctual?.lights ?? [];\n const lights: GltfPunctualLightIr[] = [];\n for (const light of source) {\n const type = light?.type;\n if (type !== 'directional' && type !== 'point' && type !== 'spot') {\n return err(gltfErr('gltf-malformed-header', { filePath, byteOffset: 0 }));\n }\n const color = light.color ?? [1, 1, 1];\n if (\n color.length < 3 ||\n color\n .slice(0, 3)\n .some(\n (value) => typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > 1,\n )\n ) {\n return err(gltfErr('gltf-malformed-header', { filePath, byteOffset: 0 }));\n }\n const intensity = light.intensity ?? 1;\n if (typeof intensity !== 'number' || !Number.isFinite(intensity) || intensity < 0) {\n return err(gltfErr('gltf-malformed-header', { filePath, byteOffset: 0 }));\n }\n const range = light.range;\n if (\n range !== undefined &&\n (typeof range !== 'number' || !Number.isFinite(range) || range < 0)\n ) {\n return err(gltfErr('gltf-malformed-header', { filePath, byteOffset: 0 }));\n }\n let spot: GltfPunctualLightIr['spot'];\n if (type === 'spot') {\n const innerConeAngle = light.spot?.innerConeAngle ?? 0;\n const outerConeAngle = light.spot?.outerConeAngle ?? Math.PI / 4;\n if (\n !Number.isFinite(innerConeAngle) ||\n !Number.isFinite(outerConeAngle) ||\n innerConeAngle < 0 ||\n innerConeAngle >= outerConeAngle ||\n outerConeAngle > Math.PI / 2\n ) {\n return err(gltfErr('gltf-malformed-header', { filePath, byteOffset: 0 }));\n }\n spot = { innerConeAngle, outerConeAngle };\n }\n lights.push({\n type,\n color: [color[0] ?? 1, color[1] ?? 1, color[2] ?? 1],\n intensity,\n ...(range === undefined || range === 0 ? {} : { range }),\n ...(spot === undefined ? {} : { spot }),\n });\n }\n return ok(lights);\n}\n\nasync function parseGltfWithBin(\n json: RootGltfJson,\n ctx: ParseGltfInternalsContext,\n): Promise<Result<GltfDoc, GltfParseError>> {\n const headerResult = parseGltfHeader(json, ctx.filePath);\n if (!headerResult.ok) return err(headerResult.error);\n\n const extResult = checkExtensions(json);\n if (!extResult.ok) return err(extResult.error);\n const unsupportedExtensions = extResult.value.unsupportedUsed;\n const lodResult = parseGltfLodExtension(json);\n if (!lodResult.ok) return err(lodResult.error);\n const lightsResult = parsePunctualLights(json, ctx.filePath);\n if (!lightsResult.ok) return err(lightsResult.error);\n\n const meshesJson = json.meshes ?? [];\n\n // Resolve buffers (data: URI / external / GLB BIN chunk).\n const buffersJson = json.buffers ?? [];\n const buffers: Uint8Array[] = [];\n for (let i = 0; i < buffersJson.length; i++) {\n const bufJson = buffersJson[i];\n if (bufJson === undefined) continue;\n try {\n const bytes = await resolveBuffer(bufJson, ctx.externalLoader, ctx.binChunk);\n buffers.push(bytes);\n } catch (e) {\n if (e instanceof Base64DecodeError) {\n return err(invalidBufferDataUriError(ctx.filePath, i, e));\n }\n return err(\n gltfErr('gltf-malformed-header', {\n filePath: ctx.filePath,\n byteOffset: 0,\n }),\n );\n }\n }\n\n const accessors = json.accessors ?? [];\n const rawBufferViews = json.bufferViews ?? [];\n const projected = await projectMeshoptBufferViews(\n rawBufferViews as readonly MeshoptBufferViewJson[],\n buffers,\n json.extensionsRequired ?? [],\n ctx.meshopt,\n );\n if (!projected.ok) return err(projected.error);\n const bufferViews = projected.value.bufferViews;\n buffers.splice(0, buffers.length, ...projected.value.buffers);\n\n const meshes: GltfMeshIr[] = [];\n // Preserve original mesh -> primitive counts for the flattened IR.\n const meshPrimitiveCount = new Map<number, number>();\n for (let meshIndex = 0; meshIndex < meshesJson.length; meshIndex++) {\n const meshJson = meshesJson[meshIndex];\n if (meshJson === undefined) continue;\n meshPrimitiveCount.set(meshIndex, meshJson.primitives.length);\n for (const prim of meshJson.primitives) {\n if (prim === undefined) continue;\n const positionAccessorIndex = prim.attributes?.POSITION;\n if (positionAccessorIndex === undefined) {\n return err(\n gltfErr('gltf-accessor-type-mismatch', {\n accessorIndex: -1,\n reason: 'unknownComponentType',\n }),\n );\n }\n const positionAccessor = accessors[positionAccessorIndex];\n const positionBufferView = bufferViews[positionAccessor?.bufferView ?? -1];\n if (positionAccessor === undefined || positionBufferView === undefined) {\n return err(\n gltfErr('gltf-buffer-out-of-bounds', {\n accessor: positionAccessorIndex,\n byteOffset: 0,\n byteLength: 0,\n bufferIndex: positionBufferView?.buffer ?? 0,\n }),\n );\n }\n const positionBuffer = buffers[positionBufferView.buffer];\n if (positionBuffer === undefined) {\n return err(\n gltfErr('gltf-buffer-out-of-bounds', {\n accessor: positionAccessorIndex,\n byteOffset: positionBufferView.byteOffset ?? 0,\n byteLength: positionBufferView.byteLength,\n bufferIndex: positionBufferView.buffer,\n }),\n );\n }\n const positionDecoded = decodeAccessor({\n accessorIndex: positionAccessorIndex,\n accessor: positionAccessor,\n bufferView: positionBufferView,\n buffer: positionBuffer,\n role: 'attribute',\n });\n if (!positionDecoded.ok) return err(positionDecoded.error);\n if (positionDecoded.value.kind !== 'f32') {\n return err(\n gltfErr('gltf-accessor-type-mismatch', {\n accessorIndex: positionAccessorIndex,\n reason: 'unknownComponentType',\n }),\n );\n }\n const positionsDecoded = positionDecoded.value.data;\n // Re-allocate over a fresh ArrayBuffer so the GltfMeshIr.positions type\n // (`Float32Array<ArrayBuffer>`) holds without ArrayBufferLike leakage.\n const positions = new Float32Array(positionsDecoded.length);\n positions.set(positionsDecoded);\n\n // Decode optional NORMAL, TEXCOORD_0, and TANGENT attributes.\n const attrs = prim.attributes ?? {};\n\n let colors0: Float32Array | undefined;\n const colorIdx = attrs.COLOR_0;\n if (colorIdx !== undefined) {\n const colorAccessor = accessors[colorIdx];\n const colorBufferView = bufferViews[colorAccessor?.bufferView ?? -1];\n if (colorAccessor === undefined || colorBufferView === undefined) {\n return err(\n gltfErr('gltf-color-accessor-malformed', {\n semantic: 'COLOR_0',\n accessorIndex: colorIdx,\n reason: 'reference',\n }),\n );\n }\n const colorBuffer = buffers[colorBufferView.buffer];\n if (colorBuffer === undefined) {\n return err(\n gltfErr('gltf-color-accessor-malformed', {\n semantic: 'COLOR_0',\n accessorIndex: colorIdx,\n reason: 'reference',\n }),\n );\n }\n const decoded = decodeColorAccessor({\n accessorIndex: colorIdx,\n accessor: colorAccessor,\n bufferView: colorBufferView,\n buffer: colorBuffer,\n bufferIndex: colorBufferView.buffer,\n semantic: 'COLOR_0',\n });\n if (!decoded.ok) return err(decoded.error);\n if (decoded.value.length !== (positions.length / 3) * 4) {\n return err(\n gltfErr('gltf-color-accessor-malformed', {\n semantic: 'COLOR_0',\n accessorIndex: colorIdx,\n reason: 'count',\n }),\n );\n }\n colors0 = decoded.value;\n }\n\n let normals: Float32Array | undefined;\n const normalIdx = attrs.NORMAL;\n if (normalIdx !== undefined) {\n const acc = accessors[normalIdx];\n if (acc !== undefined) {\n const decoded = decodeAttributeAccessor(normalIdx, acc, bufferViews, buffers);\n if (decoded.ok) {\n const src = decoded.value;\n const owned = new Float32Array(src.length);\n owned.set(src);\n normals = owned;\n }\n }\n }\n\n let texcoord0: Float32Array | undefined;\n const texIdx = attrs.TEXCOORD_0;\n if (texIdx !== undefined) {\n const acc = accessors[texIdx];\n if (acc !== undefined) {\n const decoded = decodeAttributeAccessor(texIdx, acc, bufferViews, buffers);\n if (decoded.ok) {\n const src = decoded.value;\n const owned = new Float32Array(src.length);\n owned.set(src);\n texcoord0 = owned;\n }\n }\n }\n\n // feat-20260629-multi-uv-set-support m1-w2: decode TEXCOORD_1..7\n // using the same decodeAttributeAccessor→Float32Array pattern.\n // Missing accessor → field stays undefined (no error, mirrors TEXCOORD_0).\n // componentType non-FLOAT → decodeAttributeAccessor returns error already.\n let texcoord1: Float32Array | undefined;\n let texcoord2: Float32Array | undefined;\n let texcoord3: Float32Array | undefined;\n let texcoord4: Float32Array | undefined;\n let texcoord5: Float32Array | undefined;\n let texcoord6: Float32Array | undefined;\n let texcoord7: Float32Array | undefined;\n for (let k = 1; k <= 7; k++) {\n const tcIdx = attrs[`TEXCOORD_${k}`];\n if (tcIdx === undefined) continue;\n const acc = accessors[tcIdx];\n if (acc !== undefined) {\n const decoded = decodeAttributeAccessor(tcIdx, acc, bufferViews, buffers);\n if (decoded.ok) {\n const src = decoded.value;\n const owned = new Float32Array(src.length);\n owned.set(src);\n if (k === 1) texcoord1 = owned;\n else if (k === 2) texcoord2 = owned;\n else if (k === 3) texcoord3 = owned;\n else if (k === 4) texcoord4 = owned;\n else if (k === 5) texcoord5 = owned;\n else if (k === 6) texcoord6 = owned;\n else texcoord7 = owned;\n }\n }\n }\n\n let tangents: Float32Array | undefined;\n const tanIdx = attrs.TANGENT;\n if (tanIdx !== undefined) {\n const acc = accessors[tanIdx];\n if (acc !== undefined) {\n const decoded = decodeAttributeAccessor(tanIdx, acc, bufferViews, buffers);\n if (decoded.ok) {\n const src = decoded.value;\n const owned = new Float32Array(src.length);\n owned.set(src);\n tangents = owned;\n }\n }\n }\n\n const rawTargets = prim.targets ?? [];\n for (const target of rawTargets) {\n const colorTarget = target.COLOR_0;\n if (colorTarget !== undefined) {\n return err(\n gltfErr('gltf-color-accessor-unsupported', {\n semantic: 'COLOR_0',\n accessorIndex: colorTarget,\n reason: 'morph',\n }),\n );\n }\n }\n const morphAttributeCount = rawTargets.reduce(\n (count, target) =>\n count +\n (target.POSITION === undefined ? 0 : 1) +\n (target.NORMAL === undefined ? 0 : 1) +\n (target.TANGENT === undefined ? 0 : 1),\n 0,\n );\n const morphError = (\n reason:\n | 'target-count-exceeded'\n | 'attribute-count-exceeded'\n | 'attribute-length-mismatch'\n | 'weights-length-mismatch'\n | 'sparse-or-unsupported-accessor',\n ) =>\n err(\n gltfErr('gltf-morph-invalid', {\n meshIndex,\n primitiveIndex: meshJson.primitives.indexOf(prim),\n reason,\n targetCount: rawTargets.length,\n attributeCount: morphAttributeCount,\n vertexCount: positions.length / 3,\n }),\n );\n if (rawTargets.length > 8) return morphError('target-count-exceeded');\n if (morphAttributeCount > 8) return morphError('attribute-count-exceeded');\n\n const morphTargets: {\n readonly position?: Float32Array;\n readonly normal?: Float32Array;\n readonly tangent?: Float32Array;\n }[] = [];\n for (const target of rawTargets) {\n const output: {\n position?: Float32Array;\n normal?: Float32Array;\n tangent?: Float32Array;\n } = {};\n for (const [key, accessorIndex] of Object.entries(target)) {\n if (key !== 'POSITION' && key !== 'NORMAL' && key !== 'TANGENT') continue;\n const targetAccessor = accessors[accessorIndex];\n if (targetAccessor === undefined) return morphError('attribute-length-mismatch');\n const decoded = decodeAttributeAccessor(\n accessorIndex,\n targetAccessor,\n bufferViews,\n buffers,\n );\n if (!decoded.ok) {\n return morphError(\n decoded.error.code === 'gltf-accessor-type-mismatch'\n ? 'sparse-or-unsupported-accessor'\n : 'attribute-length-mismatch',\n );\n }\n const expected = (positions.length / 3) * (key === 'TANGENT' ? 4 : 3);\n if (decoded.value.length !== expected) return morphError('attribute-length-mismatch');\n const owned = new Float32Array(decoded.value.length);\n owned.set(decoded.value);\n if (key === 'POSITION') output.position = owned;\n else if (key === 'NORMAL') output.normal = owned;\n else output.tangent = owned;\n }\n morphTargets.push(output);\n }\n const meshWeights = meshJson.weights;\n if (meshWeights !== undefined && meshWeights.length !== rawTargets.length) {\n return morphError('weights-length-mismatch');\n }\n\n // JOINTS_0 / WEIGHTS_0 (feat-20260611 M1 w1): paired skinning attributes.\n // glTF 2.0 spec section 3.7.2.1 requires the pair to appear together for\n // any skinned primitive; lone presence -> gltf-skin-attr-asymmetric.\n // JOINTS_0 componentType: UBYTE(5121) widen->U16 via decodeAccessor\n // role='joints' (D-3 width-convert at parse), or USHORT(5123) standard\n // U16 path. WEIGHTS_0 componentType: FLOAT(5126) standard F32 path.\n const jointsIdx = attrs.JOINTS_0;\n const weightsIdx = attrs.WEIGHTS_0;\n const hasJoints = jointsIdx !== undefined;\n const hasWeights = weightsIdx !== undefined;\n if (hasJoints !== hasWeights) {\n const primitiveIndex = meshJson.primitives.indexOf(prim);\n return err(\n gltfErr('gltf-skin-attr-asymmetric', {\n meshIndex,\n primitiveIndex,\n hasJoints,\n hasWeights,\n }),\n );\n }\n let joints0: Uint16Array | undefined;\n let weights0: Float32Array | undefined;\n if (hasJoints && hasWeights) {\n const jointsAccessor = accessors[jointsIdx as number];\n const jointsBufferView = bufferViews[jointsAccessor?.bufferView ?? -1];\n if (jointsAccessor === undefined || jointsBufferView === undefined) {\n return err(unknownAccessor(jointsIdx as number));\n }\n const jointsBuffer = buffers[jointsBufferView.buffer];\n if (jointsBuffer === undefined) return err(unknownAccessor(jointsIdx as number));\n const jointsDecoded = decodeAccessor({\n accessorIndex: jointsIdx as number,\n accessor: jointsAccessor,\n bufferView: jointsBufferView,\n buffer: jointsBuffer,\n role: 'joints',\n });\n if (!jointsDecoded.ok) return err(jointsDecoded.error);\n if (jointsDecoded.value.kind !== 'u16') {\n return err(\n gltfErr('gltf-accessor-type-mismatch', {\n accessorIndex: jointsIdx as number,\n reason: 'unknownComponentType',\n }),\n );\n }\n const src = jointsDecoded.value.data;\n const owned = new Uint16Array(src.length);\n owned.set(src);\n joints0 = owned;\n\n const weightsAccessor = accessors[weightsIdx as number];\n const weightsBufferView = bufferViews[weightsAccessor?.bufferView ?? -1];\n if (weightsAccessor === undefined || weightsBufferView === undefined) {\n return err(unknownAccessor(weightsIdx as number));\n }\n const weightsBuffer = buffers[weightsBufferView.buffer];\n if (weightsBuffer === undefined) return err(unknownAccessor(weightsIdx as number));\n const weightsDecoded = decodeAccessor({\n accessorIndex: weightsIdx as number,\n accessor: weightsAccessor,\n bufferView: weightsBufferView,\n buffer: weightsBuffer,\n role: 'attribute',\n });\n if (!weightsDecoded.ok) return err(weightsDecoded.error);\n if (weightsDecoded.value.kind !== 'f32') {\n return err(\n gltfErr('gltf-accessor-type-mismatch', {\n accessorIndex: weightsIdx as number,\n reason: 'unknownComponentType',\n }),\n );\n }\n const wsrc = weightsDecoded.value.data;\n const wowned = new Float32Array(wsrc.length);\n wowned.set(wsrc);\n weights0 = wowned;\n }\n\n // bug-20260612 hello-skin visual layered gate: glTF spec marks\n // primitive.indices optional; undefined means non-indexed geometry.\n // Leave indices undefined here; bridge.ts handles the non-indexed\n // path by routing MeshAsset.indices to undefined.\n let indices: Uint16Array | Uint32Array | undefined;\n if (prim.indices !== undefined) {\n const indexAccessor = accessors[prim.indices];\n const indexBufferView = bufferViews[indexAccessor?.bufferView ?? -1];\n if (indexAccessor === undefined || indexBufferView === undefined) {\n return err(\n gltfErr('gltf-buffer-out-of-bounds', {\n accessor: prim.indices,\n byteOffset: 0,\n byteLength: 0,\n bufferIndex: indexBufferView?.buffer ?? 0,\n }),\n );\n }\n const indexBuffer = buffers[indexBufferView.buffer];\n if (indexBuffer === undefined) {\n return err(\n gltfErr('gltf-buffer-out-of-bounds', {\n accessor: prim.indices,\n byteOffset: indexBufferView.byteOffset ?? 0,\n byteLength: indexBufferView.byteLength,\n bufferIndex: indexBufferView.buffer,\n }),\n );\n }\n const indexDecoded = decodeAccessor({\n accessorIndex: prim.indices,\n accessor: indexAccessor,\n bufferView: indexBufferView,\n buffer: indexBuffer,\n role: 'indices',\n });\n if (!indexDecoded.ok) return err(indexDecoded.error);\n if (indexDecoded.value.kind === 'u16') {\n // Re-allocate over a fresh ArrayBuffer so the GltfMeshIr.indices type\n // (`Uint16Array<ArrayBuffer>`) holds without the underlying\n // SharedArrayBuffer-friendly ArrayBufferLike slot leaking through.\n const src = indexDecoded.value.data;\n const owned = new Uint16Array(src.length);\n owned.set(src);\n indices = owned;\n } else if (indexDecoded.value.kind === 'u32') {\n const src = indexDecoded.value.data;\n const owned = new Uint32Array(src.length);\n owned.set(src);\n indices = owned;\n } else {\n return err(\n gltfErr('gltf-accessor-type-mismatch', {\n accessorIndex: prim.indices,\n reason: 'unknownComponentType',\n }),\n );\n }\n }\n\n const meshIr: GltfMeshIr = {\n ...(meshJson.name === undefined ? {} : { name: meshJson.name }),\n positions,\n ...(normals === undefined ? {} : { normals }),\n ...(texcoord0 === undefined ? {} : { texcoord0 }),\n ...(texcoord1 === undefined ? {} : { texcoord1 }),\n ...(texcoord2 === undefined ? {} : { texcoord2 }),\n ...(texcoord3 === undefined ? {} : { texcoord3 }),\n ...(texcoord4 === undefined ? {} : { texcoord4 }),\n ...(texcoord5 === undefined ? {} : { texcoord5 }),\n ...(texcoord6 === undefined ? {} : { texcoord6 }),\n ...(texcoord7 === undefined ? {} : { texcoord7 }),\n ...(tangents === undefined ? {} : { tangents }),\n ...(colors0 === undefined ? {} : { colors0 }),\n ...(joints0 === undefined ? {} : { joints0 }),\n ...(weights0 === undefined ? {} : { weights0 }),\n ...(morphTargets.length === 0 ? {} : { morphTargets }),\n ...(meshWeights === undefined ? {} : { morphWeights: new Float32Array(meshWeights) }),\n ...(indices === undefined ? {} : { indices }),\n materialIndex: prim.material ?? null,\n meshIndex,\n };\n meshes.push(meshIr);\n }\n }\n\n // Textures, images, samplers (Tier-C: parse top-level arrays).\n const texturesJson = json.textures ?? [];\n const textures: GltfTextureIr[] = [];\n for (const texJson of texturesJson) {\n const texIr: GltfTextureIr = {\n source: texJson.source ?? -1,\n ...(texJson.sampler === undefined ? {} : { sampler: texJson.sampler }),\n ...(texJson.name === undefined ? {} : { name: texJson.name }),\n };\n textures.push(texIr);\n }\n\n const imagesJson = json.images ?? [];\n const images: GltfImageIr[] = [];\n for (const imgJson of imagesJson) {\n const mimeType = imgJson.mimeType;\n if (mimeType !== undefined && mimeType !== 'image/jpeg' && mimeType !== 'image/png') {\n return err(gltfErr('gltf-image-mime-unsupported', { mimeType }));\n }\n const imgIr: GltfImageIr = {\n ...(imgJson.uri === undefined ? {} : { uri: imgJson.uri }),\n ...(imgJson.mimeType === undefined ? {} : { mimeType: imgJson.mimeType }),\n ...(imgJson.bufferView === undefined ? {} : { bufferView: imgJson.bufferView }),\n ...(imgJson.name === undefined ? {} : { name: imgJson.name }),\n };\n images.push(imgIr);\n }\n\n // Load external image URIs via externalLoader.\n for (const img of images) {\n if (img.uri !== undefined) {\n if (dataUriBase64Payload(img.uri) !== undefined) continue; // data: URI, skip external load\n try {\n await ctx.externalLoader(img.uri);\n } catch (_e) {\n return err(gltfErr('gltf-texture-load-failed', { uri: img.uri }));\n }\n }\n }\n\n const samplersJson = json.samplers ?? [];\n const samplers: GltfSamplerIr[] = [];\n for (const sampJson of samplersJson) {\n samplers.push({\n ...(sampJson.magFilter === undefined ? {} : { magFilter: sampJson.magFilter }),\n ...(sampJson.minFilter === undefined ? {} : { minFilter: sampJson.minFilter }),\n wrapS: sampJson.wrapS ?? 10497, // REPEAT (glTF default)\n wrapT: sampJson.wrapT ?? 10497,\n ...(sampJson.name === undefined ? {} : { name: sampJson.name }),\n });\n }\n\n // Materials are normalized by the material parser owner before entering the IR.\n const materials: GltfMaterialIr[] = [];\n for (const material of json.materials ?? []) {\n const parsedMaterial = parseMaterial(material, textures);\n if (!parsedMaterial.ok) return err(parsedMaterial.error);\n materials.push(parsedMaterial.value);\n }\n\n // Nodes + diagnostics.\n const diagnostics = {\n nodeNames: [] as string[],\n unsupportedExtensions: [...unsupportedExtensions] as string[],\n matrixTrsCoexistNodes: [] as number[],\n };\n const nodes: GltfNodeIr[] = [];\n const nodesJson = json.nodes ?? [];\n for (let nodeIndex = 0; nodeIndex < nodesJson.length; nodeIndex++) {\n const nodeJson = nodesJson[nodeIndex];\n if (nodeJson === undefined) continue;\n const transform = decomposeNodeTransform(nodeJson, nodeIndex, diagnostics);\n if (nodeJson.name !== undefined) diagnostics.nodeNames.push(nodeJson.name);\n const instancingExt = nodeJson.extensions?.EXT_mesh_gpu_instancing;\n let instancing: NodeInstancingIr | undefined;\n if (instancingExt !== undefined) {\n const instancingResult = decodeNodeInstancing(\n nodeIndex,\n instancingExt.attributes ?? {},\n accessors,\n bufferViews,\n buffers,\n );\n if (!instancingResult.ok) return err(instancingResult.error);\n instancing = instancingResult.value;\n }\n const nodeMorphWeights =\n nodeJson.weights === undefined ? undefined : new Float32Array(nodeJson.weights);\n nodes.push({\n ...(nodeJson.name === undefined ? {} : { name: nodeJson.name }),\n transform,\n meshIndex: nodeJson.mesh ?? null,\n skinIndex: nodeJson.skin ?? null,\n children: nodeJson.children ?? [],\n camera: nodeJson.camera ?? null,\n lightIndex: nodeJson.extensions?.KHR_lights_punctual?.light ?? null,\n ...(instancing === undefined ? {} : { instancing }),\n ...(nodeMorphWeights === undefined ? {} : { morphWeights: nodeMorphWeights }),\n });\n }\n\n // Scenes.\n const scenesJson = json.scenes ?? [];\n const scenes: GltfSceneIr[] = scenesJson.map((s) => ({\n ...(s.name === undefined ? {} : { name: s.name }),\n nodes: s.nodes ?? [],\n }));\n const defaultSceneIndex = json.scene ?? 0;\n\n // Skins (feat-20260523-skin-skeleton-animation M0).\n const skinsJson = json.skins;\n const skinResult = parseSkin(skinsJson, nodesJson, accessors, bufferViews, buffers);\n if (!skinResult.ok) return err(skinResult.error);\n const skeletons = skinResult.value;\n\n // Animations (feat-20260523-skin-skeleton-animation M0).\n const animationsJson = json.animations;\n const animResult = parseAnimation(animationsJson, nodesJson, accessors, bufferViews, buffers);\n if (!animResult.ok) return err(animResult.error);\n const animationClips = animResult.value;\n\n return ok({\n meshes,\n materials,\n nodes,\n scenes,\n skeletons,\n animationClips,\n textures: textures.length > 0 ? textures : undefined,\n images: images.length > 0 ? images : undefined,\n samplers: samplers.length > 0 ? samplers : undefined,\n defaultSceneIndex,\n diagnostics: {\n nodeNames: diagnostics.nodeNames,\n unsupportedExtensions: diagnostics.unsupportedExtensions,\n matrixTrsCoexistNodes: diagnostics.matrixTrsCoexistNodes,\n },\n meshPrimitiveCount,\n lights: lightsResult.value,\n ...(lodResult.value.lodNodeIds.length === 0 ? {} : { lod: lodResult.value }),\n });\n}\n\n/**\n * Parse a glTF 2.0 JSON document. The `externalLoader` resolves\n * `buffers[].uri` references that are NOT data: URIs (callers in Node\n * land typically wrap fs.readFile; browser callers wrap fetch).\n *\n * Pure function modulo `externalLoader` (caller-provided I/O is the\n * only side effect). No global state, no fs / network direct call.\n */\nexport async function parseGltfForImporter(\n json: unknown,\n externalLoader: ExternalLoader,\n filePath: string,\n options: GltfParseOptions = {},\n): Promise<Result<GltfDoc, GltfParseError>> {\n if (json === null || typeof json !== 'object') {\n return err(\n gltfErr('gltf-malformed-header', {\n filePath,\n byteOffset: 0,\n }),\n );\n }\n return parseGltfWithBin(json as RootGltfJson, {\n externalLoader,\n filePath,\n ...(options.meshopt === undefined ? {} : { meshopt: options.meshopt }),\n });\n}\n\nfunction legacyParseResult(\n result: Result<GltfDoc, GltfParseError>,\n filePath: string,\n byteOffset: number,\n): Result<GltfDoc, GltfError> {\n if (result.ok) return ok(result.value);\n if (result.error instanceof ImportError) {\n return err(gltfErr('gltf-malformed-header', { filePath, byteOffset }));\n }\n return err(result.error);\n}\n\nexport async function parseGltf(\n json: unknown,\n externalLoader: ExternalLoader,\n filePath: string,\n options: GltfParseOptions = {},\n): Promise<Result<GltfDoc, GltfError>> {\n const result = await parseGltfForImporter(json, externalLoader, filePath, options);\n return legacyParseResult(result, filePath, 0);\n}\n\n/**\n * Parse a GLB 2.0 binary container: split into JSON + BIN chunks via\n * `parseGlbChunks`, then run the JSON document through `parseGltf` with\n * the BIN chunk wired in as buffer-0 backing storage.\n */\nexport async function parseGlbForImporter(\n buffer: ArrayBuffer,\n filePath: string,\n options: GltfParseOptions = {},\n): Promise<Result<GltfDoc, GltfParseError>> {\n const chunksResult = parseGlbChunks(buffer, filePath);\n if (!chunksResult.ok) return err(chunksResult.error);\n let json: unknown;\n try {\n json = JSON.parse(new TextDecoder().decode(chunksResult.value.jsonChunk));\n } catch (_e) {\n return err(\n gltfErr('gltf-malformed-header', {\n filePath,\n byteOffset: 12,\n }),\n );\n }\n if (json === null || typeof json !== 'object') {\n return err(\n gltfErr('gltf-malformed-header', {\n filePath,\n byteOffset: 12,\n }),\n );\n }\n const externalLoader: ExternalLoader = async (uri: string) => {\n throw new Error(`parseGlb: GLB containers must not reference external URIs (got ${uri})`);\n };\n return parseGltfWithBin(json as RootGltfJson, {\n externalLoader,\n ...(chunksResult.value.binChunk === undefined ? {} : { binChunk: chunksResult.value.binChunk }),\n filePath,\n ...(options.meshopt === undefined ? {} : { meshopt: options.meshopt }),\n });\n}\n\nexport async function parseGlb(\n buffer: ArrayBuffer,\n filePath: string,\n options: GltfParseOptions = {},\n): Promise<Result<GltfDoc, GltfError>> {\n const result = await parseGlbForImporter(buffer, filePath, options);\n return legacyParseResult(result, filePath, 12);\n}\n\nexport interface GltfAssetPack {\n readonly meta: GltfMetaJson;\n readonly subAssets: readonly GltfSubAssetEntry[];\n}\n\nexport type GltfAssetPackResult = Result<GltfAssetPack, GltfSourceKeyError | GltfError>;\n\n/**\n * Project a parsed `GltfDoc` into the disk-shape `<source>.meta.json` plus\n * the freshly minted `subAssets[]` list (UUIDv7 + reimport-reuse-meta\n * two-stage match per plan-strategy section 2.4). Source-key conflicts are\n * returned before GUID minting or serialization.\n *\n * `existingMeta` is the previously-written `<source>.meta.json` parsed back\n * into memory (callers typically read + JSON.parse it before invoking).\n * `undefined` triggers first-pass full-fresh GUID minting.\n *\n * Sub-asset ordering: meshes first, then materials, then scenes - the\n * order is stable across reimports so AC-13 byte-identical holds when\n * source content does not change. Stable semantic sourceKey values are\n * assigned by the producer reuse boundary; sourceIndex remains a locator.\n */\nexport function toAssetPack(\n doc: GltfDoc,\n existingMeta: GltfMetaJson | undefined,\n source: string,\n): GltfAssetPackResult {\n const items: GltfDocItem[] = [];\n // Mesh sub-assets are keyed on the *original glTF mesh-index*, not on the\n // flat GltfMeshIr index. parseGltf flattens N glTF meshes with M_i primitives\n // into sum(M_i) GltfMeshIr rows (each carries its owning meshIndex). The\n // gltfImporter merges all primitives sharing a meshIndex into one MeshAsset\n // with M_i Submesh entries (one per primitive), so the meta sidecar must\n // emit exactly one `kind: 'mesh'` row per unique meshIndex — not one per\n // flat GltfMeshIr row, which would over-emit M_i sub-assets per glTF mesh and\n // desynchronise from runtime MeshRenderer.materials[].length.\n const seenMeshIndices = new Set<number>();\n for (const m of doc.meshes) {\n if (m === undefined) continue;\n if (seenMeshIndices.has(m.meshIndex)) continue;\n seenMeshIndices.add(m.meshIndex);\n items.push({\n kind: 'mesh',\n sourceIndex: m.meshIndex,\n ...(m.name === undefined ? {} : { name: m.name }),\n });\n }\n for (let i = 0; i < doc.materials.length; i++) {\n const m = doc.materials[i];\n if (m === undefined) continue;\n items.push({\n kind: 'material',\n sourceIndex: i,\n ...(m.name === undefined ? {} : { name: m.name }),\n });\n }\n for (let i = 0; i < doc.scenes.length; i++) {\n const s = doc.scenes[i];\n if (s === undefined) continue;\n items.push({\n kind: 'scene',\n sourceIndex: i,\n ...(s.name === undefined ? {} : { name: s.name }),\n });\n }\n // Texture sub-assets — one entry per `images[]` row (feat-20260608 M3 D-3,\n // requirements G-2 / AC-13). Orphan images (declared but unreferenced by\n // any `textures[]` row) still produce a sub-asset; the importer assigns\n // them colorSpace 'linear' (no colour-encoded purpose inferable). Without\n // this loop the meta carries no `kind: 'texture'` row, AssetRegistry\n // never imports the bytes, and the runtime renders a white box (G-2).\n const images = doc.images ?? [];\n for (let i = 0; i < images.length; i++) {\n const img = images[i];\n if (img === undefined) continue;\n items.push({\n kind: 'texture',\n sourceIndex: i,\n ...(img.name === undefined ? {} : { name: img.name }),\n });\n }\n const samplers = doc.samplers ?? [];\n for (let i = 0; i < samplers.length; i++) {\n const sampler = samplers[i];\n if (sampler === undefined) continue;\n items.push({\n kind: 'sampler',\n sourceIndex: i,\n ...(sampler.name === undefined ? {} : { name: sampler.name }),\n });\n }\n // Skeletons (feat-20260523-skin-skeleton-animation M0).\n for (let i = 0; i < doc.skeletons.length; i++) {\n items.push({ kind: 'skeleton', sourceIndex: i });\n }\n // Skin bindings (feat-20260523-skin-skeleton-animation M0).\n // Emit one skin sub-asset per GltfSkeletonRecord (1:1 mapping).\n for (let i = 0; i < doc.skeletons.length; i++) {\n items.push({ kind: 'skin', sourceIndex: i });\n }\n // Animation clips (feat-20260523-skin-skeleton-animation M0).\n for (let i = 0; i < doc.animationClips.length; i++) {\n const clip = doc.animationClips[i];\n if (clip === undefined) continue;\n items.push({\n kind: 'animation-clip',\n sourceIndex: i,\n ...(clip.name === undefined ? {} : { name: clip.name }),\n });\n }\n\n const reuse = reimportReuseMeta(items, existingMeta);\n if (!reuse.ok) return reuse;\n const subAssetByKindIndex = new Map(\n reuse.value.subAssets.map((entry) => [`${entry.kind}:${entry.sourceIndex}`, entry]),\n );\n const sourceOverrides: Record<string, Readonly<Record<string, unknown>>> = {\n ...(existingMeta?.sourceOverrides ?? {}),\n };\n const lodGroups =\n doc.lod === undefined ? [] : doc.lod.groups.length > 0 ? doc.lod.groups : [doc.lod];\n for (const lodGroup of lodGroups) {\n if (lodGroup.lodNodeIds.length === 0) continue;\n const rootMeshIndex = doc.nodes[lodGroup.rootNode]?.meshIndex;\n const referencedMeshIndices = [\n rootMeshIndex,\n ...lodGroup.lodNodeIds.map((nodeIndex) => doc.nodes[nodeIndex]?.meshIndex),\n ];\n if (\n referencedMeshIndices.some(\n (meshIndex) =>\n !Number.isInteger(meshIndex) ||\n meshIndex === null ||\n meshIndex === undefined ||\n !seenMeshIndices.has(meshIndex as number),\n )\n ) {\n return err(\n gltfErr('gltf-lod-invalid', {\n rootNode: lodGroup.rootNode,\n ids: lodGroup.lodNodeIds,\n reason: 'missing-node',\n }),\n );\n }\n const rootOutput =\n rootMeshIndex === undefined || rootMeshIndex === null\n ? undefined\n : subAssetByKindIndex.get(`mesh:${rootMeshIndex}`);\n const levels = lodGroup.lodNodeIds.map((nodeIndex, index) => {\n const meshIndex = doc.nodes[nodeIndex]?.meshIndex;\n const output =\n meshIndex === undefined || meshIndex === null\n ? undefined\n : subAssetByKindIndex.get(`mesh:${meshIndex}`);\n return {\n sourceKey: output?.sourceKey ?? `mesh:${meshIndex ?? nodeIndex}`,\n meshGuid: output?.guid ?? '',\n ...(lodGroup.screenCoverages[index] === undefined\n ? {}\n : { screenCoverage: lodGroup.screenCoverages[index] }),\n };\n });\n if (rootOutput?.sourceKey !== undefined && levels.every((level) => level.meshGuid !== '')) {\n const previousLodMeta = (() => {\n const raw = existingMeta?.sourceOverrides?.[rootOutput.sourceKey]?.lods;\n if (!Array.isArray(raw)) return undefined;\n return raw.flatMap((entry) => {\n if (entry === null || typeof entry !== 'object') return [];\n const value = entry as Record<string, unknown>;\n return typeof value.sourceKey === 'string' && typeof value.meshGuid === 'string'\n ? [\n {\n sourceKey: value.sourceKey,\n guid: value.meshGuid,\n ...(typeof value.screenCoverage === 'number'\n ? { screenCoverage: value.screenCoverage }\n : {}),\n },\n ]\n : [];\n });\n })();\n const projected = projectGltfLodMeta({\n rootSourceKey: rootOutput.sourceKey,\n levels: levels.map((level) => ({\n sourceKey: level.sourceKey,\n guid: level.meshGuid,\n ...(level.screenCoverage === undefined ? {} : { screenCoverage: level.screenCoverage }),\n })),\n ...(previousLodMeta === undefined ? {} : { previous: previousLodMeta }),\n });\n if (!projected.ok)\n return err(\n gltfErr('gltf-lod-invalid', {\n rootNode: lodGroup.rootNode,\n ids: lodGroup.lodNodeIds,\n reason: 'coverage',\n }),\n );\n sourceOverrides[rootOutput.sourceKey] = {\n ...(sourceOverrides[rootOutput.sourceKey] ?? {}),\n lods: projected.value.lods,\n };\n }\n }\n for (const meshIndex of seenMeshIndices) {\n const meshOutput = subAssetByKindIndex.get(`mesh:${meshIndex}`);\n if (meshOutput?.sourceKey === undefined) continue;\n const materialSlots: MeshMaterialSlotTopologyEntry[] = [];\n const slotByMaterial = new Map<number | null, number>();\n const usedNames = new Set<string>();\n const uniqueName = (raw: string): string => {\n const base = raw.trim() || 'Material';\n let candidate = base;\n let suffix = 2;\n while (usedNames.has(candidate)) candidate = `${base}_${suffix++}`;\n usedNames.add(candidate);\n return candidate;\n };\n for (const primitive of doc.meshes.filter((mesh) => mesh.meshIndex === meshIndex)) {\n const materialIndex = primitive.materialIndex;\n if (slotByMaterial.has(materialIndex)) continue;\n const materialOutput =\n materialIndex === null ? undefined : subAssetByKindIndex.get(`material:${materialIndex}`);\n slotByMaterial.set(materialIndex, materialSlots.length);\n materialSlots.push({\n slotName: uniqueName(\n materialIndex === null\n ? 'Default'\n : (doc.materials[materialIndex]?.name ?? `Material_${materialIndex}`),\n ),\n sourceKey:\n materialIndex === null\n ? 'gltf:default'\n : (materialOutput?.sourceKey ?? `gltf:material:${materialIndex}`),\n ...(materialOutput === undefined ? {} : { defaultMaterialGuid: materialOutput.guid }),\n });\n }\n const previousPayload = existingMeta?.sourceOverrides?.[meshOutput.sourceKey];\n const previousRaw = previousPayload?.materialSlots;\n const previous = Array.isArray(previousRaw)\n ? previousRaw.filter(\n (slot): slot is MeshMaterialSlotTopologyEntry =>\n slot !== null &&\n typeof slot === 'object' &&\n !Array.isArray(slot) &&\n typeof (slot as { slotName?: unknown }).slotName === 'string',\n )\n : [];\n const reconciled = reconcileMeshMaterialSlotTopology(materialSlots, previous);\n if (!reconciled.ok) {\n return err({\n code: 'mesh-material-slot-topology-change',\n expected: `unambiguous material slot identity for mesh ${meshOutput.guid}`,\n hint: reconciled.error.hint,\n detail: {\n sourceIndices: reconciled.error.nextIndices,\n previousIndices: reconciled.error.previousIndices,\n },\n });\n }\n sourceOverrides[meshOutput.sourceKey] = {\n ...(previousPayload ?? {}),\n materialSlots: reconciled.slots,\n };\n }\n const meta: GltfMetaJson = {\n schemaVersion: 1,\n kind: 'external-asset-package',\n importer: 'gltf',\n source,\n subAssets: reuse.value.subAssets,\n ...(Object.keys(sourceOverrides).length === 0 ? {} : { sourceOverrides }),\n sourceOverrideDescriptors: reuse.value.subAssets\n .filter((entry) => entry.kind === 'mesh' && entry.sourceKey !== undefined)\n .map((entry) => ({\n sourceKey: entry.sourceKey as string,\n semantic: 'mesh-material-slot-defaults' as const,\n payloadSchema: MESH_MATERIAL_SLOT_SOURCE_OVERRIDE_PAYLOAD_SCHEMA,\n })),\n importSettings: {\n defaultSceneIndex: doc.defaultSceneIndex,\n ...(typeof existingMeta?.importSettings.standardMaterialGuid === 'string'\n ? { standardMaterialGuid: existingMeta.importSettings.standardMaterialGuid }\n : {}),\n ...(existingMeta?.importSettings.downscaleMaxDimension !== undefined\n ? { downscaleMaxDimension: existingMeta.importSettings.downscaleMaxDimension }\n : {}),\n diagnostics: {\n nodeNames: doc.diagnostics.nodeNames,\n unsupportedExtensions: doc.diagnostics.unsupportedExtensions,\n matrixTrsCoexistNodes: doc.diagnostics.matrixTrsCoexistNodes,\n },\n },\n };\n return ok({ meta, subAssets: reuse.value.subAssets });\n}\n\n// Keep the component-type table available from this importer module.\nexport { COMPONENT_TYPE };\n","// File-entry wrappers (Node-only, dynamic-import isolated).\n//\n// `parseGltfFromFile` / `parseGlbFromFile` are the only members of this\n// package that touch the filesystem. They live in this dedicated module so\n// the main entry (`index.ts`) stays browser-clean: the `node:fs/promises`\n// and `node:path` dynamic imports below would otherwise trip vite's\n// \"module externalized for browser compatibility\" warning when the demo\n// bundles `@forgeax/engine-gltf` for the browser even though it never\n// calls these helpers.\n//\n// Sidecar policy (feat-20260521 unify-sidecar-meta-dispatch-by-content):\n// <name>.gltf -> <name>.gltf.meta.json\n// <name>.glb -> <name>.glb.meta.json\n//\n// Both wrappers add a single fail-fast pre-step: stat the sibling\n// `<source>.meta.json`; return `gltf-meta-missing` if absent (same code\n// surfaced by the vite-plugin and the console CLI dry-run, charter\n// proposition 5 consistent abstraction). Callers with an ArrayBuffer /\n// parsed JSON should keep using `parseGltf` / `parseGlb` directly.\n\nimport { err, type GltfError, gltfErr, type Result } from './errors.js';\nimport { type ExternalLoader, type GltfDoc, parseGlb, parseGltf } from './parse-gltf.js';\n\ninterface FsLike {\n readonly stat: (path: string) => Promise<unknown>;\n readonly readFile: (path: string) => Promise<Buffer>;\n}\n\ninterface PathLike {\n readonly dirname: (p: string) => string;\n readonly resolve: (...segments: string[]) => string;\n}\n\nasync function loadFsModule(): Promise<FsLike> {\n const mod = (await import('node:fs/promises')) as unknown as FsLike;\n return mod;\n}\n\nasync function loadPathModule(): Promise<PathLike> {\n const mod = (await import('node:path')) as unknown as PathLike;\n return mod;\n}\n\nasync function statExists(fs: FsLike, path: string): Promise<boolean> {\n try {\n await fs.stat(path);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction metaPathFor(filePath: string): string {\n return `${filePath}.meta.json`;\n}\n\n/**\n * Parse a `.gltf` file from disk. Pre-step: stat the sibling\n * `<source>.meta.json`; if missing, return `gltf-meta-missing` without\n * reading the source bytes.\n */\nexport async function parseGltfFromFile(filePath: string): Promise<Result<GltfDoc, GltfError>> {\n const fs = await loadFsModule();\n const path = await loadPathModule();\n const expectedMetaPath = metaPathFor(filePath);\n if (!(await statExists(fs, expectedMetaPath))) {\n return err(gltfErr('gltf-meta-missing', { filePath, expectedMetaPath }));\n }\n const text = (await fs.readFile(filePath)).toString('utf-8');\n let json: unknown;\n try {\n json = JSON.parse(text);\n } catch (_e) {\n return err(gltfErr('gltf-malformed-header', { filePath, byteOffset: 0 }));\n }\n const baseDir = path.dirname(filePath);\n const externalLoader: ExternalLoader = async (uri: string) => {\n const abs = path.resolve(baseDir, uri);\n const buf = await fs.readFile(abs);\n return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength) as ArrayBuffer;\n };\n return parseGltf(json, externalLoader, filePath);\n}\n\n/**\n * Parse a `.glb` file from disk. Same fail-fast meta-stat pre-step as\n * `parseGltfFromFile`.\n */\nexport async function parseGlbFromFile(filePath: string): Promise<Result<GltfDoc, GltfError>> {\n const fs = await loadFsModule();\n const expectedMetaPath = metaPathFor(filePath);\n if (!(await statExists(fs, expectedMetaPath))) {\n return err(gltfErr('gltf-meta-missing', { filePath, expectedMetaPath }));\n }\n const buf = await fs.readFile(filePath);\n const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength) as ArrayBuffer;\n return parseGlb(ab, filePath);\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/accessor/decode-accessor.ts","../src/accessor/decode-color.ts","../src/check-extensions.ts","../src/data-uri.ts","../src/lod/parse-lod.ts","../src/material/parse-material.ts","../src/meshopt-decode.ts","../src/node-path.ts","../src/parse-animation.ts","../src/parse-gltf-header.ts","../src/parse-glb-chunks.ts","../src/parse-skin.ts","../src/transform.ts","../src/parse-gltf.ts","../src/node-file-entry.ts"],"names":["tuple3","n","mat4","vec3","quat"],"mappings":";;;;;AA2BO,IAAM,kBAAA,GAAqB,CAAC,YAAA,EAAc,WAAA,EAAa,SAAS,CAAA;AAGhE,IAAM,oBAAA,GAAuB,CAAC,MAAA,EAAQ,YAAA,EAAc,cAAc,aAAa,CAAA;AA2OtF,IAAM,eAAA,GAAkB;AAAA,EACtB,uBAAA,EAAyB;AAAA,IACvB,QAAA,EACE,sFAAA;AAAA,IACF,IAAA,EAAM;AAAA,GACR;AAAA,EACA,0BAAA,EAA4B;AAAA,IAC1B,QAAA,EAAU,yBAAA;AAAA,IACV,IAAA,EAAM;AAAA,GACR;AAAA,EACA,2BAAA,EAA6B;AAAA,IAC3B,QAAA,EAAU,kDAAA;AAAA,IACV,IAAA,EAAM;AAAA,GACR;AAAA,EACA,4BAAA,EAA8B;AAAA,IAC5B,QAAA,EACE,+FAAA;AAAA,IACF,IAAA,EAAM;AAAA,GACR;AAAA,EACA,kBAAA,EAAoB;AAAA,IAClB,QAAA,EAAU,4EAAA;AAAA,IACV,IAAA,EAAM;AAAA,GACR;AAAA,EACA,oCAAA,EAAsC;AAAA,IACpC,QAAA,EAAU,kFAAA;AAAA,IACV,IAAA,EAAM;AAAA,GACR;AAAA,EACA,gCAAA,EAAkC;AAAA,IAChC,QAAA,EACE,4GAAA;AAAA,IACF,IAAA,EAAM;AA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;AAC3E,EAAA,OAAO,QAAA,CAAS,IAAI,QAAQ,CAAA;AAC9B","file":"node-file-entry.mjs","sourcesContent":["// errors.ts - GltfError definitions SSOT + factory.\n//\n// Per requirements AC-28 + plan-strategy D-5 (DIP), GltfErrorCode +\n// GltfErrorDetail + GltfError + GLTF_ERROR_HINTS are the glTF importer's\n// own error SSOT, local to this package. They were migrated here from\n// @forgeax/engine-types in feat-20260615-fbx-importer-via-sdk M1 (t7).\n//\n// Producers MUST go through `gltfErr` so any GltfErrorCode addition that\n// lacks a matching detail variant fails at the call site (TS exhaustive\n// per-arm).\n//\n// Result<T, E> + ok / err live in `@forgeax/engine-types` (tweak-20260612-result-\n// into-types) and are re-exported for ergonomic single-import from this module.\n\nexport {\n createMaterialError,\n err,\n type GltfMaterialUvSetMissingDetail,\n type MaterialError,\n ok,\n type Result,\n} from '@forgeax/engine-types';\n\nimport type { VertexAttributePackDetail } from '@forgeax/engine-types';\n\n// === Meshopt vocabulary owner ===\n\nexport const GLTF_MESHOPT_MODES = ['ATTRIBUTES', 'TRIANGLES', 'INDICES'] as const;\nexport type GltfMeshoptMode = (typeof GLTF_MESHOPT_MODES)[number];\n\nexport const GLTF_MESHOPT_FILTERS = ['NONE', 'OCTAHEDRAL', 'QUATERNION', 'EXPONENTIAL'] as const;\nexport type GltfMeshoptFilter = (typeof GLTF_MESHOPT_FILTERS)[number];\n\n// === Per-code detail shapes (22 interfaces, 1 discriminated union) ===\n\n/** `gltf-malformed-header` payload: GLB magic / chunk header surface. */\nexport interface GltfMalformedHeaderDetail {\n readonly filePath: string;\n readonly byteOffset: number;\n readonly magic?: number;\n}\n\n/** `gltf-version-unsupported` payload: surfaced asset.version literal. */\nexport interface GltfVersionUnsupportedDetail {\n readonly filePath: string;\n readonly actualVersion: string;\n}\n\n/** `gltf-buffer-out-of-bounds` payload: accessor + bufferView coordinates. */\nexport interface GltfBufferOutOfBoundsDetail {\n readonly accessor: number;\n readonly byteOffset: number;\n readonly byteLength: number;\n readonly bufferIndex: number;\n}\n\n/** `gltf-extension-unsupported` payload: extension name + which array it appeared in. */\nexport interface GltfExtensionUnsupportedDetail {\n readonly extension: string;\n readonly source: 'extensionsRequired' | 'extensionsUsed';\n}\n\nexport interface GltfLodInvalidDetail {\n readonly rootNode: number;\n readonly ids: readonly number[];\n readonly reason: 'missing-node' | 'duplicate-node' | 'not-integer' | 'coverage';\n}\n\nexport interface GltfMaterialTransmissionInvalidDetail {\n readonly extension: 'KHR_materials_transmission' | 'KHR_materials_ior' | 'KHR_materials_volume';\n readonly field: string;\n readonly reason: 'type' | 'range' | 'non-finite' | 'blend';\n readonly actual?: unknown;\n}\n\nexport interface GltfMaterialPhysicalInvalidDetail {\n readonly extension:\n | 'KHR_materials_clearcoat'\n | 'KHR_materials_anisotropy'\n | 'KHR_materials_sheen'\n | 'KHR_materials_iridescence'\n | 'KHR_materials_specular';\n readonly field: string;\n readonly reason: 'type' | 'range' | 'non-finite';\n readonly actual?: unknown;\n}\n\n/** `gltf-accessor-type-mismatch` payload: 4-member closed reason discriminator. */\nexport interface GltfAccessorTypeMismatchDetail {\n readonly accessorIndex: number;\n readonly reason: 'sparse' | 'morph' | 'interleaved' | 'unknownComponentType';\n}\n\n/** `gltf-texture-load-failed` payload: URI that failed to load. */\nexport interface GltfTextureLoadFailedDetail {\n readonly uri: string;\n}\n\n/** `gltf-meta-missing` payload: source path + expected sidecar path. */\nexport interface GltfMetaMissingDetail {\n readonly filePath: string;\n readonly expectedMetaPath: string;\n}\n\n/** `gltf-image-mime-unsupported` payload: rejected MIME type. */\nexport interface GltfImageMimeUnsupportedDetail {\n readonly mimeType: string;\n}\n\n/** `gltf-skin-joint-count-exceeded` payload: skin joint count exceeds MAX_JOINTS. */\nexport interface GltfSkinJointCountExceededDetail {\n readonly skinIndex: number;\n readonly jointCount: number;\n readonly maxJoints: number;\n}\n\n/** `gltf-animation-cubicspline-unsupported` payload: CUBICSPLINE sampler. */\nexport interface GltfAnimationCubicsplineUnsupportedDetail {\n readonly animationIndex: number;\n readonly samplerIndex: number;\n}\n\n/** `gltf-morph-unsupported` payload: channel targeting morph weights. */\nexport interface GltfMorphUnsupportedDetail {\n readonly animationIndex: number;\n readonly channelIndex: number;\n readonly nodeIndex: number;\n}\n\n/** `gltf-skin-joint-name-missing` payload: joint node has no name. */\nexport interface GltfSkinJointNameMissingDetail {\n readonly reason: 'name-missing' | 'hierarchy-cycle';\n readonly skinIndex: number;\n readonly jointPathIndex: number;\n readonly nodeIndex: number;\n}\n\n/** `gltf-image-extract-failed` payload: image bytes extraction failure. */\nexport interface GltfImageExtractFailedDetail {\n readonly imageIndex: number;\n readonly source: 'bufferView' | 'data-uri' | 'external-uri';\n readonly reason: string;\n}\n\n/** `gltf-instancing-count-mismatch` payload: TRS accessor count disagreement. */\nexport interface GltfInstancingCountMismatchDetail {\n readonly nodeIndex: number;\n readonly accessor: 'TRANSLATION' | 'ROTATION' | 'SCALE';\n readonly expectedCount: number;\n readonly actualCount: number;\n}\n\n/** `gltf-skin-attr-asymmetric` payload: JOINTS_0/WEIGHTS_0 paired-presence fail. */\nexport interface GltfSkinAttrAsymmetricDetail {\n readonly meshIndex: number;\n readonly primitiveIndex: number;\n readonly hasJoints: boolean;\n readonly hasWeights: boolean;\n}\n\nexport interface GltfAnimationTargetInvalidDetail {\n readonly reason:\n | 'name-missing'\n | 'path-invalid'\n | 'path-duplicate'\n | 'path-not-found'\n | 'hierarchy-cycle'\n | 'id-collision';\n readonly animationIndex: number;\n readonly channelIndex: number;\n readonly nodeIndex: number;\n}\n\nexport interface GltfMeshoptDecoderRequiredDetail {\n readonly bufferView: number;\n readonly actual: 'required' | 'compressed-only';\n readonly hasCoreFallback: boolean;\n}\n\nexport interface GltfMeshoptDecodeFailedDetail {\n readonly bufferView: number;\n readonly actual: string;\n readonly mode: GltfMeshoptMode;\n readonly filter: GltfMeshoptFilter;\n}\n\nexport interface GltfMorphInvalidDetail {\n readonly meshIndex: number;\n readonly primitiveIndex: number;\n readonly reason:\n | 'target-count-exceeded'\n | 'attribute-count-exceeded'\n | 'attribute-length-mismatch'\n | 'weights-length-mismatch'\n | 'sparse-or-unsupported-accessor';\n readonly targetCount: number;\n readonly attributeCount: number;\n readonly vertexCount: number;\n}\n\nexport interface GltfColorAccessorUnsupportedDetail {\n readonly semantic: 'COLOR_0';\n readonly accessorIndex: number;\n readonly reason: 'component' | 'type' | 'normalized' | 'sparse' | 'morph';\n readonly expectedType?: string;\n readonly expectedComponent?: string;\n readonly expectedNormalized?: boolean;\n}\n\nexport interface GltfColorAccessorMalformedDetail {\n readonly semantic: 'COLOR_0';\n readonly accessorIndex: number;\n readonly reason: 'count' | 'bounds' | 'finite' | 'range' | 'reference';\n readonly expectedCount?: string;\n readonly expectedRange?: string;\n}\n\n/** Bridge-side mesh merge failure after the parser has produced a GltfMeshIr. */\nexport type GltfMeshBridgeInvalidDetail =\n | {\n readonly reason: 'empty-input';\n readonly primitiveCount: 0;\n }\n | {\n readonly reason: 'morph-count-mismatch';\n readonly meshIndex: number;\n readonly primitiveIndex: number;\n readonly expectedTargetCount: number;\n readonly actualTargetCount: number;\n }\n | {\n readonly reason: 'color-cardinality';\n readonly semantic: 'COLOR_0';\n readonly meshIndex: number;\n readonly primitiveIndex: number;\n readonly vertexCount: number;\n readonly expectedLength: number;\n readonly actualLength: number;\n }\n | {\n readonly reason: 'layout-invalid';\n readonly meshIndex: number;\n readonly cause: VertexAttributePackDetail;\n };\n\n/** Discriminated detail family unifying all 19 GltfError variants. */\nexport type GltfErrorDetail = DetailFor[GltfErrorCode];\n\n// === GltfErrorCode and GltfError discriminated union ===\n\nexport type GltfErrorCode = keyof DetailFor;\n\nexport type GltfError = {\n readonly [C in GltfErrorCode]: {\n readonly code: C;\n readonly expected: string;\n readonly hint: string;\n readonly detail: DetailFor[C];\n };\n}[GltfErrorCode];\n\n// === Private per-code policy owner ===\n\ntype GltfErrorPolicy = { readonly expected: string; readonly hint: string };\n\nconst gltfErrorPolicy = {\n 'gltf-malformed-header': {\n expected:\n 'GLB 12-byte header (magic 0x46546C67 + version=2 + length) plus mandatory JSON chunk',\n hint: 'verify .glb is not truncated; rerun: forgeax asset import <path> --root <project> --json',\n },\n 'gltf-version-unsupported': {\n expected: 'asset.version === \"2.0\"',\n hint: 'asset.version must be \"2.0\"; v1 or v3 not supported',\n },\n 'gltf-buffer-out-of-bounds': {\n expected: 'accessor byte range within bufferView.byteLength',\n hint: 'rebuild .gltf with valid bufferViews; check accessor index; ensure accessor.byteOffset + EFFECTIVE_STRIDE * (count - 1) + element_size <= bufferView.byteLength',\n },\n 'gltf-extension-unsupported': {\n expected:\n 'extension listed in the supported allowlist (see EXTENSION_ALLOWLIST in @forgeax/engine-gltf)',\n hint: 'remove the unsupported required extension or use a supported glTF extension; extensionsUsed-only entries remain diagnostic',\n },\n 'gltf-lod-invalid': {\n expected: 'MSFT_lod ids to reference unique existing node indices with valid coverage',\n hint: 'repair the MSFT_lod node relation or remove it from extensionsRequired before re-importing',\n },\n 'gltf-material-transmission-invalid': {\n expected: 'KHR transmission, IOR, and volume values are finite and within their glTF ranges',\n hint: 'repair the named glTF material extension value and re-import the source',\n },\n 'gltf-material-physical-invalid': {\n expected:\n 'KHR clearcoat, anisotropy, sheen, iridescence, and specular values are finite and within their glTF ranges',\n hint: 'repair the named physical material extension value and re-import the source',\n },\n 'gltf-accessor-type-mismatch': {\n expected: 'dense fixed-stride accessor with supported componentType',\n hint: 'sparse: see feat-future-gltf-sparse-accessor; morph: see feat-future-gltf-morph; interleaved: see feat-future-gltf-mesh-multi-section',\n },\n 'gltf-texture-load-failed': {\n expected: 'externalLoader resolved the URI into an ArrayBuffer without throwing',\n hint: 'check sidecar meta.json + textures/ directory + vite-plugin-pack /__pack/lookup route',\n },\n 'gltf-meta-missing': {\n expected: \"sidecar <source>.meta.json (importer: 'gltf') present in same directory\",\n hint: 'run: forgeax asset import <path> --root <project> --json',\n },\n 'gltf-instancing-count-mismatch': {\n expected: 'all instance attribute accessors share the same count',\n hint: 'EXT_mesh_gpu_instancing requires TRANSLATION/ROTATION/SCALE accessors to share count; see https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/EXT_mesh_gpu_instancing/README.md#extending-nodes-with-instance-attributes',\n },\n 'gltf-image-mime-unsupported': {\n expected: 'image/mimeType is image/jpeg or image/png',\n hint: 'convert to JPG/PNG via external tool; only image/jpeg and image/png are supported',\n },\n 'gltf-skin-joint-count-exceeded': {\n expected: 'skin.joints.length <= MAX_JOINTS (256)',\n hint: 'reduce joint count below MAX_JOINTS (256) or see OOS-skin-max-joints',\n },\n 'gltf-animation-cubicspline-unsupported': {\n expected: 'animation sampler interpolation is LINEAR or STEP',\n hint: 'see OOS-skin-cubicspline; convert CUBICSPLINE to LINEAR/STEP in DCC tool',\n },\n 'gltf-morph-unsupported': {\n expected: 'animation channel target path is one of translation, rotation, scale, or weights',\n hint: 'animation target path must be translation, rotation, scale, or weights',\n },\n 'gltf-skin-joint-name-missing': {\n expected: 'every joint node has a non-empty name and belongs to an acyclic hierarchy',\n hint: 'ensure every joint node has a non-empty name and the node hierarchy is acyclic',\n },\n 'gltf-image-extract-failed': {\n expected:\n 'image bytes extractable from bufferView / data-URI / external URI without corruption',\n hint: 'verify the bufferView byte range / data: URI base64 / external URI sibling file is intact next to the .gltf source; rerun: forgeax asset import <path> --root <project> --json',\n },\n 'gltf-skin-attr-asymmetric': {\n expected:\n 'mesh primitive declares JOINTS_0 and WEIGHTS_0 symmetrically (both present or both absent)',\n hint: 'glTF spec requires JOINTS_0 and WEIGHTS_0 to appear together for each skinned primitive; add the missing attribute or remove the present one in the DCC tool',\n },\n 'gltf-animation-target-invalid': {\n expected:\n 'every animation channel resolves to one uniquely named scene node and stable target ID',\n hint: 'name every node in the animated hierarchy and ensure each animated full path is unique',\n },\n 'gltf-meshopt-decoder-required': {\n expected:\n 'a required or compressed-only EXT_meshopt_compression bufferView has a ready decoder capability',\n hint: 'provide the build-only EXT_meshopt_compression decoder or author a valid core fallback bufferView',\n },\n 'gltf-meshopt-decode-failed': {\n expected: 'the EXT_meshopt_compression declaration and decoder output are structurally valid',\n hint: 'the meshopt decoder accepts the declared compressed range and produces the declared byte count',\n },\n 'gltf-morph-invalid': {\n expected:\n 'morph target and default-weight arrays are dense, bounded, and match the base vertex count',\n hint: 're-export dense morph targets with at most eight targets/attributes and matching vertex/default-weight lengths',\n },\n 'gltf-color-accessor-unsupported': {\n expected: 'COLOR_0 dense accessor uses VEC3/VEC4 FLOAT or normalized UBYTE/USHORT',\n hint: 're-export COLOR_0 with a supported type/component/normalized combination; morph and sparse COLOR_0 remain deferred',\n },\n 'gltf-color-accessor-malformed': {\n expected: 'COLOR_0 accessor is non-empty, finite, in range, and fully addressable',\n hint: 'repair the COLOR_0 accessor count, reference, range, or buffer bounds, then re-import the glTF source',\n },\n 'gltf-mesh-bridge-invalid': {\n expected: 'a non-empty merged mesh with consistent morph and COLOR_0 cardinality',\n hint: 'repair the source primitive and re-import; inspect detail.reason and its typed facts',\n },\n} satisfies Record<GltfErrorCode, GltfErrorPolicy>;\n\nexport const GLTF_ERROR_HINTS: Readonly<Record<GltfErrorCode, string>> = Object.fromEntries(\n Object.entries(gltfErrorPolicy).map(([code, policy]) => [code, policy.hint]),\n) as Readonly<Record<GltfErrorCode, string>>;\n\n// === DetailFor map + gltfErr factory ===\n\ninterface DetailFor {\n readonly 'gltf-malformed-header': GltfMalformedHeaderDetail;\n readonly 'gltf-version-unsupported': GltfVersionUnsupportedDetail;\n readonly 'gltf-buffer-out-of-bounds': GltfBufferOutOfBoundsDetail;\n readonly 'gltf-extension-unsupported': GltfExtensionUnsupportedDetail;\n readonly 'gltf-lod-invalid': GltfLodInvalidDetail;\n readonly 'gltf-accessor-type-mismatch': GltfAccessorTypeMismatchDetail;\n readonly 'gltf-texture-load-failed': GltfTextureLoadFailedDetail;\n readonly 'gltf-meta-missing': GltfMetaMissingDetail;\n readonly 'gltf-instancing-count-mismatch': GltfInstancingCountMismatchDetail;\n readonly 'gltf-image-mime-unsupported': GltfImageMimeUnsupportedDetail;\n readonly 'gltf-skin-joint-count-exceeded': GltfSkinJointCountExceededDetail;\n readonly 'gltf-animation-cubicspline-unsupported': GltfAnimationCubicsplineUnsupportedDetail;\n readonly 'gltf-morph-unsupported': GltfMorphUnsupportedDetail;\n readonly 'gltf-skin-joint-name-missing': GltfSkinJointNameMissingDetail;\n readonly 'gltf-image-extract-failed': GltfImageExtractFailedDetail;\n readonly 'gltf-skin-attr-asymmetric': GltfSkinAttrAsymmetricDetail;\n readonly 'gltf-animation-target-invalid': GltfAnimationTargetInvalidDetail;\n readonly 'gltf-meshopt-decoder-required': GltfMeshoptDecoderRequiredDetail;\n readonly 'gltf-meshopt-decode-failed': GltfMeshoptDecodeFailedDetail;\n readonly 'gltf-morph-invalid': GltfMorphInvalidDetail;\n readonly 'gltf-color-accessor-unsupported': GltfColorAccessorUnsupportedDetail;\n readonly 'gltf-color-accessor-malformed': GltfColorAccessorMalformedDetail;\n readonly 'gltf-mesh-bridge-invalid': GltfMeshBridgeInvalidDetail;\n readonly 'gltf-material-transmission-invalid': GltfMaterialTransmissionInvalidDetail;\n readonly 'gltf-material-physical-invalid': GltfMaterialPhysicalInvalidDetail;\n}\n\n/**\n * Build a fully-typed GltfError. The discriminated-union return type lets\n * call sites narrow with `switch (e.code)` on the result.\n *\n * Charter proposition 4 explicit-failure: `expected` + `hint` fields are\n * sourced from the SSOT tables - no producer can omit them.\n */\nexport function gltfErr<C extends GltfErrorCode>(\n code: C,\n detail: DetailFor[C],\n): Extract<GltfError, { readonly code: C }> {\n return {\n code,\n expected: gltfErrorPolicy[code].expected,\n hint: gltfErrorPolicy[code].hint,\n detail,\n } as Extract<GltfError, { readonly code: C }>;\n}\n","// decode-accessor.ts - glTF 2.0 accessor decoder (w9).\n//\n// Pure helper that walks one accessor and returns the typed array view of\n// its dense values. Tier-B v1 accepts only the dense, fixed-stride,\n// non-sparse, non-morph subset; everything else returns\n// `gltf-accessor-type-mismatch` with the reason discriminator.\n//\n// glTF 2.0 spec section 3.6 (accessor):\n// - componentType : 5120 I8 / 5121 U8 / 5122 I16 / 5123 U16 / 5125 U32 / 5126 F32\n// - type : 'SCALAR' / 'VEC2' / 'VEC3' / 'VEC4' / 'MAT2' / 'MAT3' / 'MAT4'\n// - bufferView : index into bufferViews[]\n// - byteOffset : within bufferView\n// - count : number of elements\n// - sparse : OOS (Tier-B v1 reject)\n// - bufferView.byteStride : when set and != element_size -> interleaved (OOS reject)\n//\n// The U8 -> U16 widening for INDICES is handled inline (a 1-byte index\n// stream is rewritten into a fresh Uint16Array). U16 and U32 index streams\n// pass through at their source width; `MeshAsset.indices` is\n// `Uint16Array | Uint32Array` end-to-end (mesh-bin serializes iwidth 2|4,\n// GPU runtime auto-selects the index format), and bridge.ts narrows U32 to\n// U16 losslessly when the merged mesh's maxIndex fits.\n//\n// Producers MUST use `decodeAccessor` rather than reading typed arrays\n// directly so the closed `GltfErrorCode` surface (charter proposition 4)\n// is the only public failure path.\n\nimport { err, type GltfError, gltfErr, ok, type Result } from '../errors.js';\n\n/** glTF 2.0 component-type IDs (KHR spec section 3.6 table 4). */\nexport const COMPONENT_TYPE = {\n I8: 5120,\n U8: 5121,\n I16: 5122,\n U16: 5123,\n U32: 5125,\n F32: 5126,\n} as const;\nexport type ComponentTypeId = (typeof COMPONENT_TYPE)[keyof typeof COMPONENT_TYPE];\n\n/** Number of components per element for each glTF accessor `type` literal. */\nconst TYPE_COMPONENT_COUNT: Readonly<Record<string, number>> = {\n SCALAR: 1,\n VEC2: 2,\n VEC3: 3,\n VEC4: 4,\n MAT2: 4,\n MAT3: 9,\n MAT4: 16,\n};\n\n/** Byte size of one component for each component type. */\nconst COMPONENT_BYTE_SIZE: Readonly<Record<number, number>> = {\n [COMPONENT_TYPE.I8]: 1,\n [COMPONENT_TYPE.U8]: 1,\n [COMPONENT_TYPE.I16]: 2,\n [COMPONENT_TYPE.U16]: 2,\n [COMPONENT_TYPE.U32]: 4,\n [COMPONENT_TYPE.F32]: 4,\n};\n\n/** Minimal accessor JSON shape touched by the decoder. */\nexport interface AccessorJson {\n readonly bufferView: number;\n readonly byteOffset?: number;\n readonly componentType: number;\n readonly count: number;\n readonly normalized?: boolean;\n readonly type: string;\n readonly sparse?: unknown;\n}\n\n/** Minimal bufferView JSON shape touched by the decoder. */\nexport interface BufferViewJson {\n readonly buffer: number;\n readonly byteOffset?: number;\n readonly byteLength: number;\n readonly byteStride?: number;\n}\n\n/**\n * Caller intent flag: when this accessor backs a mesh `INDICES` slot, U8\n * indices auto-widen to U16 (Tier-B v1 mesh asset stores U16 only).\n */\nexport type AccessorRole = 'attribute' | 'indices' | 'joints';\n\nexport interface DecodeAccessorInput {\n readonly accessorIndex: number;\n readonly accessor: AccessorJson;\n readonly bufferView: BufferViewJson;\n readonly buffer: Uint8Array;\n readonly role: AccessorRole;\n}\n\nexport type DecodedAccessor =\n | { readonly kind: 'f32'; readonly data: Float32Array }\n | { readonly kind: 'u16'; readonly data: Uint16Array }\n | { readonly kind: 'u32'; readonly data: Uint32Array };\n\ntype F32AccessorJson = Omit<AccessorJson, 'bufferView'> & {\n readonly bufferView?: number;\n};\n\n/**\n * Decode an F32 accessor for parser-owned type subsets without duplicating\n * buffer lookup and dense-range handling in each parser.\n */\nexport function decodeF32Accessor(\n accessorIndex: number,\n accessor: F32AccessorJson,\n allowedTypes: readonly string[],\n bufferViews: readonly BufferViewJson[],\n buffers: readonly Uint8Array[],\n): Result<Float32Array, GltfError> {\n if (accessor.componentType !== COMPONENT_TYPE.F32 || !allowedTypes.includes(accessor.type)) {\n return err(\n gltfErr('gltf-accessor-type-mismatch', { accessorIndex, reason: 'unknownComponentType' }),\n );\n }\n\n const bufferViewIndex = accessor.bufferView;\n if (bufferViewIndex === undefined) {\n return err(\n gltfErr('gltf-buffer-out-of-bounds', {\n accessor: accessorIndex,\n byteOffset: 0,\n byteLength: 0,\n bufferIndex: 0,\n }),\n );\n }\n const bufferView = bufferViews[bufferViewIndex];\n if (bufferView === undefined) {\n return err(\n gltfErr('gltf-buffer-out-of-bounds', {\n accessor: accessorIndex,\n byteOffset: 0,\n byteLength: 0,\n bufferIndex: bufferViewIndex,\n }),\n );\n }\n const buffer = buffers[bufferView.buffer];\n if (buffer === undefined) {\n return err(\n gltfErr('gltf-buffer-out-of-bounds', {\n accessor: accessorIndex,\n byteOffset: bufferView.byteOffset ?? 0,\n byteLength: bufferView.byteLength,\n bufferIndex: bufferView.buffer,\n }),\n );\n }\n\n const decoded = decodeAccessor({\n accessor: { ...accessor, bufferView: bufferViewIndex },\n bufferView,\n buffer,\n accessorIndex,\n role: 'attribute',\n });\n if (!decoded.ok) return decoded;\n if (decoded.value.kind !== 'f32') {\n return err(\n gltfErr('gltf-accessor-type-mismatch', { accessorIndex, reason: 'unknownComponentType' }),\n );\n }\n return ok(decoded.value.data);\n}\n\n/**\n * Decode a dense glTF accessor into the typed array view of its values.\n * Rejects sparse / morph / interleaved / unknown-componentType variants\n * with `gltf-accessor-type-mismatch`. Out-of-range byte slices return\n * `gltf-buffer-out-of-bounds`.\n *\n * `morph` is signalled by the caller (mesh primitive iteration in\n * parseGltf) by passing an accessor reached via a `targets[]` slot - the\n * decoder cannot infer it from the accessor JSON alone, so this function\n * surfaces the reason via the `morph` parameter when the caller has\n * already detected it.\n */\nexport function decodeAccessor(\n input: DecodeAccessorInput,\n flags: { readonly morph?: boolean } = {},\n): Result<DecodedAccessor, GltfError> {\n const { accessorIndex, accessor, bufferView, buffer, role } = input;\n\n if (flags.morph === true) {\n return err(\n gltfErr('gltf-accessor-type-mismatch', {\n accessorIndex,\n reason: 'morph',\n }),\n );\n }\n\n if ('sparse' in accessor && accessor.sparse !== undefined) {\n return err(\n gltfErr('gltf-accessor-type-mismatch', {\n accessorIndex,\n reason: 'sparse',\n }),\n );\n }\n\n const componentByteSize = COMPONENT_BYTE_SIZE[accessor.componentType];\n const componentCount = TYPE_COMPONENT_COUNT[accessor.type];\n if (componentByteSize === undefined || componentCount === undefined) {\n return err(\n gltfErr('gltf-accessor-type-mismatch', {\n accessorIndex,\n reason: 'unknownComponentType',\n }),\n );\n }\n const elementSize = componentByteSize * componentCount;\n const byteStride = bufferView.byteStride;\n if (byteStride !== undefined && byteStride !== elementSize) {\n return err(\n gltfErr('gltf-accessor-type-mismatch', {\n accessorIndex,\n reason: 'interleaved',\n }),\n );\n }\n\n const accessorByteOffset = accessor.byteOffset ?? 0;\n const bufferViewByteOffset = bufferView.byteOffset ?? 0;\n const totalByteLength = elementSize * accessor.count;\n if (accessorByteOffset + totalByteLength > bufferView.byteLength) {\n return err(\n gltfErr('gltf-buffer-out-of-bounds', {\n accessor: accessorIndex,\n byteOffset: bufferViewByteOffset + accessorByteOffset,\n byteLength: totalByteLength,\n bufferIndex: bufferView.buffer,\n }),\n );\n }\n const absoluteOffset = bufferViewByteOffset + accessorByteOffset;\n if (absoluteOffset + totalByteLength > buffer.byteLength) {\n return err(\n gltfErr('gltf-buffer-out-of-bounds', {\n accessor: accessorIndex,\n byteOffset: absoluteOffset,\n byteLength: totalByteLength,\n bufferIndex: bufferView.buffer,\n }),\n );\n }\n\n // U8 INDICES auto-widen to U16 (Tier-B v1 mesh asset stores U16 only).\n if (role === 'indices' && accessor.componentType === COMPONENT_TYPE.U8) {\n const widened = new Uint16Array(accessor.count);\n for (let i = 0; i < accessor.count; i++) {\n widened[i] = buffer[absoluteOffset + i] ?? 0;\n }\n return ok({ kind: 'u16', data: widened });\n }\n // U8 JOINTS auto-widen to U16 (Tier-B v1 mesh asset stores U16 only).\n // Reuses the indices widen pattern (E-5) but JOINTS_0 is VEC4 (componentCount=4),\n // not SCALAR like INDICES; total values = accessor.count * componentCount.\n if (role === 'joints' && accessor.componentType === COMPONENT_TYPE.U8) {\n const totalValues = accessor.count * componentCount;\n const widened = new Uint16Array(totalValues);\n for (let i = 0; i < totalValues; i++) {\n widened[i] = buffer[absoluteOffset + i] ?? 0;\n }\n return ok({ kind: 'u16', data: widened });\n }\n if (accessor.componentType === COMPONENT_TYPE.F32) {\n // Copy out (rather than alias) so callers may safely mutate / persist\n // the result independent of the underlying GLB BIN chunk lifetime.\n const out = new Float32Array(accessor.count * componentCount);\n const src = new Float32Array(buffer.buffer, buffer.byteOffset + absoluteOffset, out.length);\n out.set(src);\n return ok({ kind: 'f32', data: out });\n }\n if (accessor.componentType === COMPONENT_TYPE.U16) {\n const out = new Uint16Array(accessor.count * componentCount);\n const src = new Uint16Array(buffer.buffer, buffer.byteOffset + absoluteOffset, out.length);\n out.set(src);\n return ok({ kind: 'u16', data: out });\n }\n if (accessor.componentType === COMPONENT_TYPE.U32) {\n const out = new Uint32Array(accessor.count * componentCount);\n const src = new Uint32Array(buffer.buffer, buffer.byteOffset + absoluteOffset, out.length);\n out.set(src);\n return ok({ kind: 'u32', data: out });\n }\n if (accessor.componentType === COMPONENT_TYPE.I16) {\n const out = new Float32Array(accessor.count * componentCount);\n const src = new Int16Array(buffer.buffer, buffer.byteOffset + absoluteOffset, out.length);\n for (let index = 0; index < src.length; index++) {\n const value = src[index] ?? 0;\n out[index] = accessor.normalized === true ? Math.max(-1, value / 32767) : value;\n }\n return ok({ kind: 'f32', data: out });\n }\n // I8 remains outside the current attribute contract. Keep it rejected\n // rather than silently widening an unowned representation.\n return err(\n gltfErr('gltf-accessor-type-mismatch', {\n accessorIndex,\n reason: 'unknownComponentType',\n }),\n );\n}\n","import { err, gltfErr, ok, type Result } from '../errors.js';\nimport type { AccessorJson, BufferViewJson } from './decode-accessor.js';\n\nexport interface DecodeColorAccessorInput {\n readonly accessorIndex: number;\n readonly accessor: AccessorJson;\n readonly bufferView: BufferViewJson;\n readonly buffer: Uint8Array;\n readonly bufferIndex?: number;\n readonly semantic: 'COLOR_0';\n}\n\nconst FLOAT = 5126;\nconst UNSIGNED_BYTE = 5121;\nconst UNSIGNED_SHORT = 5123;\n\nfunction unsupported(\n input: DecodeColorAccessorInput,\n reason: 'component' | 'type' | 'normalized' | 'sparse' | 'morph',\n) {\n return err(\n gltfErr('gltf-color-accessor-unsupported', {\n semantic: input.semantic,\n accessorIndex: input.accessorIndex,\n reason,\n expectedType: 'VEC3 or VEC4',\n expectedComponent: 'FLOAT or normalized UNSIGNED_BYTE/UNSIGNED_SHORT',\n ...(reason === 'normalized' ? { expectedNormalized: true } : {}),\n }),\n );\n}\n\nfunction malformed(\n input: DecodeColorAccessorInput,\n reason: 'count' | 'bounds' | 'finite' | 'range' | 'reference',\n) {\n return err(\n gltfErr('gltf-color-accessor-malformed', {\n semantic: input.semantic,\n accessorIndex: input.accessorIndex,\n reason,\n ...(reason === 'count'\n ? { expectedCount: 'matches POSITION vertex count and is greater than zero' }\n : {}),\n ...(reason === 'range' || reason === 'finite'\n ? { expectedRange: '[0,1] finite linear values' }\n : {}),\n }),\n );\n}\n\n/** Decode one dense glTF COLOR_0 accessor into linear RGBA float values. */\nexport function decodeColorAccessor(\n input: DecodeColorAccessorInput,\n flags: { readonly morph?: boolean } = {},\n): Result<Float32Array, import('../errors.js').GltfError> {\n const { accessor, bufferView, buffer } = input;\n if (flags.morph === true) return unsupported(input, 'morph');\n if (accessor.sparse !== undefined) return unsupported(input, 'sparse');\n\n if (accessor.type !== 'VEC3' && accessor.type !== 'VEC4') return unsupported(input, 'type');\n if (!Number.isSafeInteger(accessor.count) || accessor.count <= 0)\n return malformed(input, 'count');\n\n let componentByteSize: 1 | 2 | 4;\n if (accessor.componentType === FLOAT) componentByteSize = 4;\n else if (accessor.componentType === UNSIGNED_BYTE) componentByteSize = 1;\n else if (accessor.componentType === UNSIGNED_SHORT) componentByteSize = 2;\n else return unsupported(input, 'component');\n\n if (accessor.componentType === FLOAT) {\n if (accessor.normalized !== undefined) return unsupported(input, 'normalized');\n } else if (accessor.normalized !== true) {\n return unsupported(input, 'normalized');\n }\n\n const componentCount = accessor.type === 'VEC3' ? 3 : 4;\n const elementByteLength = componentByteSize * componentCount;\n const byteStride = bufferView.byteStride ?? elementByteLength;\n if (\n !Number.isSafeInteger(byteStride) ||\n byteStride < elementByteLength ||\n byteStride % componentByteSize !== 0\n ) {\n return malformed(input, 'bounds');\n }\n if (input.bufferIndex !== undefined && bufferView.buffer !== input.bufferIndex) {\n return malformed(input, 'reference');\n }\n\n const accessorByteOffset = accessor.byteOffset ?? 0;\n const viewByteOffset = bufferView.byteOffset ?? 0;\n const lastElementEnd = accessorByteOffset + byteStride * (accessor.count - 1) + elementByteLength;\n if (\n !Number.isSafeInteger(accessorByteOffset) ||\n accessorByteOffset < 0 ||\n lastElementEnd > bufferView.byteLength\n ) {\n return malformed(input, 'bounds');\n }\n const absoluteLastElementEnd = viewByteOffset + lastElementEnd;\n if (\n !Number.isSafeInteger(viewByteOffset) ||\n viewByteOffset < 0 ||\n absoluteLastElementEnd > buffer.byteLength\n ) {\n return malformed(input, 'bounds');\n }\n\n const output = new Float32Array(accessor.count * 4);\n const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);\n const base = viewByteOffset + accessorByteOffset;\n for (let vertex = 0; vertex < accessor.count; vertex++) {\n const sourceOffset = base + vertex * byteStride;\n for (let component = 0; component < componentCount; component++) {\n const byteOffset = sourceOffset + component * componentByteSize;\n let value: number;\n if (accessor.componentType === FLOAT) value = view.getFloat32(byteOffset, true);\n else if (accessor.componentType === UNSIGNED_BYTE) value = view.getUint8(byteOffset) / 255;\n else value = view.getUint16(byteOffset, true) / 65535;\n if (!Number.isFinite(value)) return malformed(input, 'finite');\n if (value < 0 || value > 1) return malformed(input, 'range');\n output[vertex * 4 + component] = value;\n }\n if (componentCount === 3) output[vertex * 4 + 3] = 1;\n }\n return ok(output);\n}\n","// check-extensions.ts - KHR / vendor extension gate.\n//\n// Required-extension support contains EXT_mesh_gpu_instancing,\n// EXT_meshopt_compression, KHR_lights_punctual, KHR_texture_transform, and\n// the KHR material transmission/IOR/volume/clearcoat/anisotropy/sheen/\n// iridescence/specular extensions. The exported list is the public supported\n// extension surface consumed by both the required-extension gate and callers\n// that need to discover support.\n// (feat-20260518-gltf-instancing-and-name-component plan-strategy section\n// 2 D-1 / D-3). Any extension listed in `extensionsRequired[]` outside\n// the supported extension set triggers `gltf-extension-unsupported` (hard fail).\n// Extensions listed in `extensionsUsed[]` (but not required and not in\n// supported extension set) are recorded in `importSettings.diagnostics\n// .unsupportedExtensions` so AI users can observe them downstream — and\n// nothing else: `extensionsUsed` is purely informational per the glTF spec\n// (only `extensionsRequired` is binding), and exporters routinely\n// over-declare it (e.g. KHR_materials_unlit listed but referenced by no\n// material). A stderr warn for those would be a false positive, so the\n// diagnostics list is the single channel (no `console.error`).\n//\n// Future expansion (KHR_materials_unlit, ...) extends\n// `EXTENSION_ALLOWLIST` in place; each addition lands under its own feat-*\n// loop with breaking-change registry entry.\n\nimport { err, type GltfError, gltfErr, ok, type Result } from './errors.js';\n\n/** Public supported extension list used by the required/used declaration gate. */\nexport const EXTENSION_ALLOWLIST: readonly string[] = [\n 'EXT_mesh_gpu_instancing',\n 'EXT_meshopt_compression',\n 'KHR_lights_punctual',\n 'KHR_texture_transform',\n 'KHR_materials_transmission',\n 'KHR_materials_ior',\n 'KHR_materials_volume',\n 'KHR_materials_clearcoat',\n 'KHR_materials_anisotropy',\n 'KHR_materials_sheen',\n 'KHR_materials_iridescence',\n 'KHR_materials_specular',\n];\nconst SUPPORTED_EXTENSIONS: readonly string[] = [\n ...EXTENSION_ALLOWLIST,\n 'MSFT_lod',\n 'MSFT_screencoverage',\n];\n\nexport interface ExtensionsCheckResult {\n /** Names listed in extensionsUsed but not in the supported extension set. */\n readonly unsupportedUsed: readonly string[];\n}\n\nexport interface GltfExtensionsJson {\n readonly extensionsRequired?: readonly string[];\n readonly extensionsUsed?: readonly string[];\n}\n\n/**\n * Validate the glTF JSON's extension declarations against the supported set.\n *\n * Returns:\n * - `Result.err(gltf-extension-unsupported)` for the FIRST entry of\n * `extensionsRequired[]` that is not allowlisted (fail-fast; the\n * remaining required entries are not surfaced; first wins because the\n * diagnostic carries one extension name + source slot only).\n * - `Result.ok({ unsupportedUsed })` otherwise; the `unsupportedUsed`\n * array names every extensionsUsed entry not in the allowlist (used as\n * input for `importSettings.diagnostics.unsupportedExtensions`).\n * extensionsUsed entries never fail parsing and never write to stderr —\n * they are informational per the glTF spec and routinely over-declared.\n *\n * Pure function: no fs / network / stderr.\n */\nexport function checkExtensions(\n json: GltfExtensionsJson,\n): Result<ExtensionsCheckResult, GltfError> {\n const required = json.extensionsRequired ?? [];\n for (const ext of required) {\n if (!SUPPORTED_EXTENSIONS.includes(ext)) {\n return err(\n gltfErr('gltf-extension-unsupported', {\n extension: ext,\n source: 'extensionsRequired',\n }),\n );\n }\n }\n\n const used = json.extensionsUsed ?? [];\n const unsupportedUsed: string[] = [];\n for (const ext of used) {\n if (!SUPPORTED_EXTENSIONS.includes(ext)) {\n unsupportedUsed.push(ext);\n }\n }\n\n return ok({ unsupportedUsed });\n}\n","const DATA_URI_BASE64_RE = /^data:[^;,]*(?:;[^,;]+)*;base64,(.*)$/;\n\nexport class Base64DecodeError extends Error {\n constructor(cause: unknown) {\n super(\n `base64 payload decode failed: ${cause instanceof Error ? cause.message : String(cause)}`,\n );\n this.name = 'Base64DecodeError';\n }\n}\n\nexport function dataUriBase64Payload(uri: string): string | undefined {\n const match = DATA_URI_BASE64_RE.exec(uri);\n return match === null ? undefined : (match[1] ?? '');\n}\n\nexport function decodeBase64(b64: string): Uint8Array {\n let binary: string;\n try {\n binary = atob(b64);\n } catch (cause) {\n throw new Base64DecodeError(cause);\n }\n const out = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n out[i] = binary.charCodeAt(i);\n }\n return out;\n}\n","import { err, gltfErr, ok, type Result } from '../errors.js';\n\nexport interface GltfLodRelation {\n readonly rootNode: number;\n readonly lodNodeIds: readonly number[];\n readonly screenCoverages: readonly number[];\n /** All node-level MSFT_lod groups, retained for multi-root scenes. */\n readonly groups: readonly GltfLodGroup[];\n}\n\nexport interface GltfLodGroup {\n readonly rootNode: number;\n readonly lodNodeIds: readonly number[];\n readonly screenCoverages: readonly number[];\n}\n\ninterface RawNode {\n readonly mesh?: unknown;\n readonly extensions?: { readonly MSFT_lod?: { readonly ids?: unknown } };\n readonly extras?: { readonly MSFT_screencoverage?: unknown };\n}\n\ninterface RawMesh {\n readonly primitives?: unknown;\n}\n\ninterface RawGltf {\n readonly extensionsRequired?: readonly unknown[];\n readonly meshes?: readonly RawMesh[];\n readonly nodes?: readonly RawNode[];\n readonly extensions?: { readonly MSFT_screencoverage?: { readonly scales?: unknown } };\n}\n\nexport function parseGltfLodExtension(\n json: unknown,\n): Result<GltfLodRelation, ReturnType<typeof gltfErr<'gltf-lod-invalid'>>> {\n const doc = json as RawGltf;\n const nodes = doc.nodes ?? [];\n const rawCoverage = doc.extensions?.MSFT_screencoverage?.scales;\n const groups: GltfLodGroup[] = [];\n for (let rootNode = 0; rootNode < nodes.length; rootNode += 1) {\n if (nodes[rootNode]?.extensions?.MSFT_lod === undefined) continue;\n const idsRaw = nodes[rootNode]?.extensions?.MSFT_lod?.ids;\n if (!Array.isArray(idsRaw)) {\n return err(gltfErr('gltf-lod-invalid', { rootNode, ids: [], reason: 'not-integer' }));\n }\n const ids = idsRaw.filter((value): value is number => typeof value === 'number');\n if (\n ids.length !== idsRaw.length ||\n ids.some((id) => !Number.isInteger(id) || id < 0 || id >= nodes.length)\n ) {\n return err(gltfErr('gltf-lod-invalid', { rootNode, ids, reason: 'missing-node' }));\n }\n if (new Set(ids).size !== ids.length || ids.includes(rootNode)) {\n return err(gltfErr('gltf-lod-invalid', { rootNode, ids, reason: 'duplicate-node' }));\n }\n const hasMesh = (node: RawNode | undefined): boolean => {\n if (typeof node?.mesh !== 'number' || !Number.isInteger(node.mesh) || node.mesh < 0) {\n return false;\n }\n const mesh = doc.meshes?.[node.mesh];\n // An extension relation is publishable only when its target mesh has at\n // least one primitive. The parser normally receives the source mesh\n // table, so an empty table/primitive list is a source-contract failure;\n // treating it as a valid relation would let toAssetPack silently drop\n // the LOD level later.\n return mesh !== undefined && Array.isArray(mesh.primitives) && mesh.primitives.length > 0;\n };\n if (!hasMesh(nodes[rootNode]) || ids.some((id) => !hasMesh(nodes[id]))) {\n return err(gltfErr('gltf-lod-invalid', { rootNode, ids, reason: 'missing-node' }));\n }\n const nodeCoverage = nodes[rootNode]?.extras?.MSFT_screencoverage;\n const coverage = normalizeScreenCoverages(\n nodeCoverage === undefined ? rawCoverage : nodeCoverage,\n ids.length,\n nodeCoverage !== undefined,\n );\n if (coverage === 'invalid') {\n return err(gltfErr('gltf-lod-invalid', { rootNode, ids, reason: 'coverage' }));\n }\n groups.push({\n rootNode,\n lodNodeIds: ids,\n screenCoverages: coverage ?? [],\n });\n }\n const first = groups[0];\n if (first === undefined) {\n if (doc.extensionsRequired?.some((extension) => extension === 'MSFT_lod')) {\n return err(gltfErr('gltf-lod-invalid', { rootNode: 0, ids: [], reason: 'missing-node' }));\n }\n return ok({ rootNode: 0, lodNodeIds: [], screenCoverages: [], groups: [] });\n }\n return ok({\n rootNode: first.rootNode,\n lodNodeIds: first.lodNodeIds,\n screenCoverages: first.screenCoverages,\n groups,\n });\n}\n\n/**\n * Normalize the official node `extras.MSFT_screencoverage` form and the\n * historical ForgeaX document-extension adapter form. The official array\n * includes one terminal threshold for the discard range, while MeshAsset\n * stores only the thresholds that select lower geometry levels.\n */\nfunction normalizeScreenCoverages(\n raw: unknown,\n lodCount: number,\n officialNodeForm: boolean,\n): readonly number[] | undefined | 'invalid' {\n if (raw === undefined) return undefined;\n if (!Array.isArray(raw)) return 'invalid';\n if (\n raw.some(\n (value) => typeof value !== 'number' || !Number.isFinite(value) || value <= 0 || value > 1,\n )\n ) {\n return 'invalid';\n }\n const expectedLengths = officialNodeForm ? [lodCount + 1] : [lodCount, lodCount + 1];\n if (!expectedLengths.includes(raw.length)) return 'invalid';\n const values = raw.slice(0, lodCount) as number[];\n for (let index = 1; index < values.length; index += 1) {\n if ((values[index] as number) >= (values[index - 1] as number)) return 'invalid';\n }\n return values;\n}\n","export interface GltfTextureIr {\n readonly sampler?: number;\n readonly source: number;\n readonly name?: string;\n}\n\nexport interface GltfImageIr {\n readonly uri?: string;\n readonly mimeType?: string;\n readonly bufferView?: number;\n readonly name?: string;\n}\n\nexport interface GltfSamplerIr {\n readonly magFilter?: number;\n readonly minFilter?: number;\n readonly wrapS: number;\n readonly wrapT: number;\n readonly name?: string;\n}\n\nexport interface GltfTextureTransformIr {\n readonly offset?: readonly [number, number];\n readonly rotation?: number;\n readonly scale?: readonly [number, number];\n}\n\nexport interface GltfTextureInfoIr {\n readonly texture: number;\n readonly sampler?: number;\n readonly texCoord?: number;\n readonly transform?: GltfTextureTransformIr;\n}\n\nexport interface GltfNormalTextureInfoIr extends GltfTextureInfoIr {\n readonly scale?: number;\n}\n\nexport interface GltfOcclusionTextureInfoIr extends GltfTextureInfoIr {\n readonly strength?: number;\n}\n\nexport interface TextureTransformJson {\n readonly offset?: readonly number[];\n readonly rotation?: number;\n readonly scale?: readonly number[];\n readonly texCoord?: number;\n}\n\nexport interface TextureInfoJson {\n readonly index: number;\n readonly texCoord?: number;\n readonly extensions?: {\n readonly KHR_texture_transform?: TextureTransformJson;\n };\n}\n\nexport interface NormalTextureInfoJson extends TextureInfoJson {\n readonly scale?: number;\n}\n\nexport interface OcclusionTextureInfoJson extends TextureInfoJson {\n readonly strength?: number;\n}\n\nexport interface GltfMaterialJson {\n readonly name?: string;\n readonly pbrMetallicRoughness?: {\n readonly baseColorFactor?: readonly number[];\n readonly baseColorTexture?: TextureInfoJson;\n readonly metallicFactor?: number;\n readonly roughnessFactor?: number;\n readonly metallicRoughnessTexture?: TextureInfoJson;\n };\n readonly normalTexture?: NormalTextureInfoJson;\n readonly emissiveFactor?: readonly number[];\n readonly emissiveTexture?: TextureInfoJson;\n readonly occlusionTexture?: OcclusionTextureInfoJson;\n readonly alphaMode?: string;\n readonly alphaCutoff?: number;\n readonly doubleSided?: boolean;\n readonly extensions?: {\n readonly KHR_materials_transmission?: {\n readonly transmissionFactor?: number;\n readonly transmissionTexture?: TextureInfoJson;\n };\n readonly KHR_materials_ior?: {\n readonly ior?: number;\n };\n readonly KHR_materials_volume?: {\n readonly thicknessFactor?: number;\n readonly thicknessTexture?: TextureInfoJson;\n readonly attenuationColor?: readonly number[];\n readonly attenuationDistance?: number;\n };\n readonly KHR_materials_clearcoat?: {\n readonly clearcoatFactor?: number;\n readonly clearcoatTexture?: TextureInfoJson;\n readonly clearcoatRoughnessFactor?: number;\n readonly clearcoatRoughnessTexture?: TextureInfoJson;\n readonly clearcoatNormalTexture?: NormalTextureInfoJson;\n };\n readonly KHR_materials_anisotropy?: {\n readonly anisotropyStrength?: number;\n readonly anisotropyRotation?: number;\n readonly anisotropyTexture?: TextureInfoJson;\n };\n readonly KHR_materials_sheen?: {\n readonly sheenColorFactor?: readonly number[];\n readonly sheenColorTexture?: TextureInfoJson;\n readonly sheenRoughnessFactor?: number;\n readonly sheenRoughnessTexture?: TextureInfoJson;\n };\n readonly KHR_materials_iridescence?: {\n readonly iridescenceFactor?: number;\n readonly iridescenceIor?: number;\n readonly iridescenceThicknessMinimum?: number;\n readonly iridescenceThicknessMaximum?: number;\n readonly iridescenceTexture?: TextureInfoJson;\n readonly iridescenceThicknessTexture?: TextureInfoJson;\n };\n readonly KHR_materials_specular?: {\n readonly specularFactor?: number;\n readonly specularTexture?: TextureInfoJson;\n readonly specularColorFactor?: readonly number[];\n readonly specularColorTexture?: TextureInfoJson;\n };\n };\n}\n\nexport interface GltfMaterialIr {\n readonly name?: string;\n readonly baseColorFactor: readonly [number, number, number, number];\n /** glTF emissiveFactor; omitted means the glTF default [0, 0, 0]. */\n readonly emissiveFactor?: readonly [number, number, number];\n readonly baseColorTexture?: GltfTextureInfoIr | number;\n readonly emissiveTexture?: GltfTextureInfoIr | number;\n readonly metallicFactor: number;\n readonly roughnessFactor: number;\n readonly metallicRoughnessTexture?: GltfTextureInfoIr | number;\n readonly normalTexture?: GltfNormalTextureInfoIr | number;\n readonly occlusionTexture?: GltfOcclusionTextureInfoIr | number;\n readonly transmissionFactor?: number;\n readonly transmissionTexture?: GltfTextureInfoIr | number;\n /** KHR_materials_transmission uses the red texture channel. */\n readonly transmissionChannel?: number;\n readonly ior?: number;\n readonly thicknessFactor?: number;\n readonly thicknessTexture?: GltfTextureInfoIr | number;\n /** KHR_materials_volume uses the green texture channel. */\n readonly thicknessChannel?: number;\n readonly attenuationColor?: readonly [number, number, number];\n readonly attenuationDistance?: number;\n readonly clearcoatFactor?: number;\n readonly clearcoatChannel?: number;\n readonly clearcoatTexture?: GltfTextureInfoIr | number;\n readonly clearcoatRoughnessFactor?: number;\n readonly clearcoatRoughnessChannel?: number;\n readonly clearcoatRoughnessTexture?: GltfTextureInfoIr | number;\n readonly clearcoatNormalTexture?: GltfNormalTextureInfoIr | number;\n readonly clearcoatNormalChannel?: readonly [number, number];\n readonly anisotropyStrength?: number;\n readonly anisotropyRotation?: number;\n readonly anisotropyTexture?: GltfTextureInfoIr | number;\n /** KHR_materials_anisotropy uses RG direction and B strength. */\n readonly anisotropyChannel?: readonly [number, number, number];\n readonly sheenColorFactor?: readonly [number, number, number];\n readonly sheenColorTexture?: GltfTextureInfoIr | number;\n readonly sheenColorChannel?: readonly [number, number, number];\n readonly sheenRoughnessFactor?: number;\n readonly sheenRoughnessTexture?: GltfTextureInfoIr | number;\n readonly sheenRoughnessChannel?: number;\n readonly iridescenceFactor?: number;\n readonly iridescenceIor?: number;\n readonly iridescenceThicknessMinimum?: number;\n readonly iridescenceThicknessMaximum?: number;\n readonly iridescenceTexture?: GltfTextureInfoIr | number;\n readonly iridescenceChannel?: number;\n readonly iridescenceThicknessTexture?: GltfTextureInfoIr | number;\n readonly iridescenceThicknessChannel?: number;\n readonly specularFactor?: number;\n readonly specularTexture?: GltfTextureInfoIr | number;\n /** KHR_materials_specular specularTexture uses the alpha channel. */\n readonly specularChannel?: number;\n readonly specularColorFactor?: readonly [number, number, number];\n readonly specularColorTexture?: GltfTextureInfoIr | number;\n readonly specularColorChannel?: readonly [number, number, number];\n readonly alphaMode?: 'OPAQUE' | 'MASK' | 'BLEND';\n readonly alphaCutoff?: number;\n readonly doubleSided?: boolean;\n readonly baseColorTexCoord?: number;\n}\n\nfunction tuple2(values: readonly number[] | undefined): readonly [number, number] | undefined {\n if (values === undefined || values.length < 2) return undefined;\n return [values[0] ?? 0, values[1] ?? 0];\n}\n\nfunction tuple3(\n values: readonly number[] | undefined,\n): readonly [number, number, number] | undefined {\n if (values === undefined || values.length < 3) return undefined;\n return [values[0] ?? 0, values[1] ?? 0, values[2] ?? 0];\n}\n\nexport function parseTextureInfo(\n info: TextureInfoJson,\n textures: readonly GltfTextureIr[],\n): GltfTextureInfoIr {\n const transformJson = info.extensions?.KHR_texture_transform;\n const offset = tuple2(transformJson?.offset);\n const scale = tuple2(transformJson?.scale);\n const transform =\n offset === undefined && transformJson?.rotation === undefined && scale === undefined\n ? undefined\n : {\n ...(offset === undefined ? {} : { offset }),\n ...(transformJson?.rotation === undefined ? {} : { rotation: transformJson.rotation }),\n ...(scale === undefined ? {} : { scale }),\n };\n const sampler = textures[info.index]?.sampler;\n return {\n texture: info.index,\n ...(sampler === undefined ? {} : { sampler }),\n ...(info.texCoord === undefined && transformJson?.texCoord === undefined\n ? {}\n : { texCoord: transformJson?.texCoord ?? info.texCoord }),\n ...(transform === undefined ? {} : { transform }),\n };\n}\n\nfunction finiteOrUndefined(value: number | undefined): number | undefined {\n return value !== undefined && Number.isFinite(value) ? value : undefined;\n}\n\nexport function parseMaterial(\n matJson: GltfMaterialJson,\n textures: readonly GltfTextureIr[],\n): Result<GltfMaterialIr, GltfError> {\n const pbr = matJson.pbrMetallicRoughness;\n const baseColor = pbr?.baseColorFactor ?? [1, 1, 1, 1];\n const baseColor4: readonly [number, number, number, number] = [\n baseColor[0] ?? 1,\n baseColor[1] ?? 1,\n baseColor[2] ?? 1,\n baseColor[3] ?? 1,\n ];\n const alphaMode =\n matJson.alphaMode === 'MASK' || matJson.alphaMode === 'BLEND' ? matJson.alphaMode : undefined;\n const alphaCutoff = alphaMode === 'MASK' ? (matJson.alphaCutoff ?? 0.5) : undefined;\n const emissiveFactor = tuple3(matJson.emissiveFactor);\n const transmission = matJson.extensions?.KHR_materials_transmission;\n const ior = matJson.extensions?.KHR_materials_ior;\n const volume = matJson.extensions?.KHR_materials_volume;\n const clearcoat = matJson.extensions?.KHR_materials_clearcoat;\n const anisotropy = matJson.extensions?.KHR_materials_anisotropy;\n const sheen = matJson.extensions?.KHR_materials_sheen;\n const iridescence = matJson.extensions?.KHR_materials_iridescence;\n const specular = matJson.extensions?.KHR_materials_specular;\n const attenuationColor = tuple3(volume?.attenuationColor);\n const invalid = (\n extension: 'KHR_materials_transmission' | 'KHR_materials_ior' | 'KHR_materials_volume',\n field: string,\n reason: 'type' | 'range' | 'non-finite' | 'blend',\n actual?: unknown,\n ): Result<GltfMaterialIr, GltfError> =>\n err(\n gltfErr('gltf-material-transmission-invalid', {\n extension,\n field,\n reason,\n ...(actual === undefined ? {} : { actual }),\n }),\n );\n const physicalInvalid = (\n extension:\n | 'KHR_materials_clearcoat'\n | 'KHR_materials_anisotropy'\n | 'KHR_materials_sheen'\n | 'KHR_materials_iridescence'\n | 'KHR_materials_specular',\n field: string,\n reason: 'type' | 'range' | 'non-finite',\n actual?: unknown,\n ): Result<GltfMaterialIr, GltfError> =>\n err(\n gltfErr('gltf-material-physical-invalid', {\n extension,\n field,\n reason,\n ...(actual === undefined ? {} : { actual }),\n }),\n );\n if (\n transmission?.transmissionFactor !== undefined &&\n (typeof transmission.transmissionFactor !== 'number' ||\n !Number.isFinite(transmission.transmissionFactor))\n ) {\n return invalid(\n 'KHR_materials_transmission',\n 'transmissionFactor',\n 'non-finite',\n transmission.transmissionFactor,\n );\n }\n if (\n transmission?.transmissionFactor !== undefined &&\n (transmission.transmissionFactor < 0 || transmission.transmissionFactor > 1)\n ) {\n return invalid(\n 'KHR_materials_transmission',\n 'transmissionFactor',\n 'range',\n transmission.transmissionFactor,\n );\n }\n if (ior?.ior !== undefined && (typeof ior.ior !== 'number' || !Number.isFinite(ior.ior))) {\n return invalid('KHR_materials_ior', 'ior', 'non-finite', ior.ior);\n }\n if (ior?.ior !== undefined && ior.ior < 1) {\n return invalid('KHR_materials_ior', 'ior', 'range', ior.ior);\n }\n if (volume?.thicknessFactor !== undefined && !Number.isFinite(volume.thicknessFactor)) {\n return invalid('KHR_materials_volume', 'thicknessFactor', 'non-finite', volume.thicknessFactor);\n }\n if (volume?.thicknessFactor !== undefined && volume.thicknessFactor < 0) {\n return invalid('KHR_materials_volume', 'thicknessFactor', 'range', volume.thicknessFactor);\n }\n if (\n volume?.attenuationColor !== undefined &&\n (attenuationColor === undefined ||\n attenuationColor.some((value) => !Number.isFinite(value) || value < 0 || value > 1))\n ) {\n return invalid('KHR_materials_volume', 'attenuationColor', 'range', volume.attenuationColor);\n }\n if (\n volume?.attenuationDistance !== undefined &&\n !Number.isFinite(volume.attenuationDistance) &&\n volume.attenuationDistance !== Number.POSITIVE_INFINITY\n ) {\n return invalid(\n 'KHR_materials_volume',\n 'attenuationDistance',\n 'non-finite',\n volume.attenuationDistance,\n );\n }\n if (\n volume?.attenuationDistance !== undefined &&\n Number.isFinite(volume.attenuationDistance) &&\n volume.attenuationDistance <= 0\n ) {\n return invalid(\n 'KHR_materials_volume',\n 'attenuationDistance',\n 'range',\n volume.attenuationDistance,\n );\n }\n if (alphaMode === 'BLEND' && (transmission?.transmissionFactor ?? 0) > 0) {\n return invalid('KHR_materials_transmission', 'alphaMode', 'blend', alphaMode);\n }\n if (\n clearcoat?.clearcoatFactor !== undefined &&\n (typeof clearcoat.clearcoatFactor !== 'number' || !Number.isFinite(clearcoat.clearcoatFactor))\n ) {\n return physicalInvalid(\n 'KHR_materials_clearcoat',\n 'clearcoatFactor',\n 'non-finite',\n clearcoat.clearcoatFactor,\n );\n }\n if (\n clearcoat?.clearcoatFactor !== undefined &&\n (clearcoat.clearcoatFactor < 0 || clearcoat.clearcoatFactor > 1)\n ) {\n return physicalInvalid(\n 'KHR_materials_clearcoat',\n 'clearcoatFactor',\n 'range',\n clearcoat.clearcoatFactor,\n );\n }\n if (\n clearcoat?.clearcoatRoughnessFactor !== undefined &&\n (typeof clearcoat.clearcoatRoughnessFactor !== 'number' ||\n !Number.isFinite(clearcoat.clearcoatRoughnessFactor))\n ) {\n return physicalInvalid(\n 'KHR_materials_clearcoat',\n 'clearcoatRoughnessFactor',\n 'non-finite',\n clearcoat.clearcoatRoughnessFactor,\n );\n }\n if (\n clearcoat?.clearcoatRoughnessFactor !== undefined &&\n (clearcoat.clearcoatRoughnessFactor < 0 || clearcoat.clearcoatRoughnessFactor > 1)\n ) {\n return physicalInvalid(\n 'KHR_materials_clearcoat',\n 'clearcoatRoughnessFactor',\n 'range',\n clearcoat.clearcoatRoughnessFactor,\n );\n }\n if (\n clearcoat?.clearcoatNormalTexture?.scale !== undefined &&\n (typeof clearcoat.clearcoatNormalTexture.scale !== 'number' ||\n !Number.isFinite(clearcoat.clearcoatNormalTexture.scale) ||\n clearcoat.clearcoatNormalTexture.scale < 0)\n ) {\n return physicalInvalid(\n 'KHR_materials_clearcoat',\n 'clearcoatNormalTexture.scale',\n 'range',\n clearcoat.clearcoatNormalTexture.scale,\n );\n }\n const validateUnit = (\n extension: Parameters<typeof physicalInvalid>[0],\n field: string,\n value: number | undefined,\n ) => {\n if (value === undefined) return undefined;\n if (typeof value !== 'number' || !Number.isFinite(value))\n return physicalInvalid(extension, field, 'non-finite', value);\n if (value < 0 || value > 1) return physicalInvalid(extension, field, 'range', value);\n return undefined;\n };\n const validateFinite = (\n extension: Parameters<typeof physicalInvalid>[0],\n field: string,\n value: number | undefined,\n minimum?: number,\n ) => {\n if (value === undefined) return undefined;\n if (typeof value !== 'number' || !Number.isFinite(value))\n return physicalInvalid(extension, field, 'non-finite', value);\n if (minimum !== undefined && value < minimum)\n return physicalInvalid(extension, field, 'range', value);\n return undefined;\n };\n const validateColor = (\n extension: Parameters<typeof physicalInvalid>[0],\n field: string,\n value: readonly number[] | undefined,\n ) => {\n if (value === undefined) return undefined;\n if (\n value.length < 3 ||\n value.slice(0, 3).some((channel) => typeof channel !== 'number' || !Number.isFinite(channel))\n ) {\n return physicalInvalid(extension, field, 'type', value);\n }\n if (value.slice(0, 3).some((channel) => channel < 0 || channel > 1)) {\n return physicalInvalid(extension, field, 'range', value);\n }\n return undefined;\n };\n const physicalChecks = [\n validateUnit('KHR_materials_anisotropy', 'anisotropyStrength', anisotropy?.anisotropyStrength),\n validateFinite(\n 'KHR_materials_anisotropy',\n 'anisotropyRotation',\n anisotropy?.anisotropyRotation,\n ),\n validateUnit('KHR_materials_sheen', 'sheenRoughnessFactor', sheen?.sheenRoughnessFactor),\n validateColor('KHR_materials_sheen', 'sheenColorFactor', sheen?.sheenColorFactor),\n validateUnit('KHR_materials_iridescence', 'iridescenceFactor', iridescence?.iridescenceFactor),\n validateFinite('KHR_materials_iridescence', 'iridescenceIor', iridescence?.iridescenceIor, 1),\n validateFinite(\n 'KHR_materials_iridescence',\n 'iridescenceThicknessMinimum',\n iridescence?.iridescenceThicknessMinimum,\n 0,\n ),\n validateFinite(\n 'KHR_materials_iridescence',\n 'iridescenceThicknessMaximum',\n iridescence?.iridescenceThicknessMaximum,\n 0,\n ),\n validateUnit('KHR_materials_specular', 'specularFactor', specular?.specularFactor),\n validateColor('KHR_materials_specular', 'specularColorFactor', specular?.specularColorFactor),\n ];\n for (const check of physicalChecks) if (check !== undefined) return check;\n return ok({\n ...(matJson.name === undefined ? {} : { name: matJson.name }),\n baseColorFactor: baseColor4,\n ...(emissiveFactor === undefined ? {} : { emissiveFactor }),\n metallicFactor: pbr?.metallicFactor ?? 1.0,\n roughnessFactor: pbr?.roughnessFactor ?? 1.0,\n ...(pbr?.baseColorTexture === undefined\n ? {}\n : { baseColorTexture: parseTextureInfo(pbr.baseColorTexture, textures) }),\n ...(pbr?.metallicRoughnessTexture === undefined\n ? {}\n : { metallicRoughnessTexture: parseTextureInfo(pbr.metallicRoughnessTexture, textures) }),\n ...(matJson.normalTexture === undefined\n ? {}\n : {\n normalTexture: {\n ...parseTextureInfo(matJson.normalTexture, textures),\n ...(matJson.normalTexture.scale === undefined\n ? {}\n : { scale: matJson.normalTexture.scale }),\n },\n }),\n ...(matJson.occlusionTexture === undefined\n ? {}\n : {\n occlusionTexture: {\n ...parseTextureInfo(matJson.occlusionTexture, textures),\n ...(matJson.occlusionTexture.strength === undefined\n ? {}\n : { strength: matJson.occlusionTexture.strength }),\n },\n }),\n ...(matJson.emissiveTexture === undefined\n ? {}\n : { emissiveTexture: parseTextureInfo(matJson.emissiveTexture, textures) }),\n ...(transmission === undefined\n ? {}\n : {\n transmissionFactor: transmission.transmissionFactor ?? 0,\n transmissionChannel: 0,\n ...(transmission.transmissionTexture === undefined\n ? {}\n : {\n transmissionTexture: parseTextureInfo(transmission.transmissionTexture, textures),\n }),\n }),\n ...(ior === undefined ? {} : { ior: ior.ior ?? 1.5 }),\n ...(volume === undefined\n ? {}\n : {\n thicknessFactor: volume.thicknessFactor ?? 0,\n thicknessChannel: 1,\n ...(volume.thicknessTexture === undefined\n ? {}\n : { thicknessTexture: parseTextureInfo(volume.thicknessTexture, textures) }),\n ...(attenuationColor === undefined ? {} : { attenuationColor }),\n ...(finiteOrUndefined(volume.attenuationDistance) === undefined\n ? {}\n : { attenuationDistance: volume.attenuationDistance }),\n }),\n ...(clearcoat === undefined\n ? {}\n : {\n clearcoatFactor: clearcoat.clearcoatFactor ?? 0,\n clearcoatChannel: 0,\n clearcoatRoughnessFactor: clearcoat.clearcoatRoughnessFactor ?? 0,\n clearcoatRoughnessChannel: 1,\n clearcoatNormalChannel: [0, 1] as const,\n ...(clearcoat.clearcoatTexture === undefined\n ? {}\n : { clearcoatTexture: parseTextureInfo(clearcoat.clearcoatTexture, textures) }),\n ...(clearcoat.clearcoatRoughnessTexture === undefined\n ? {}\n : {\n clearcoatRoughnessTexture: parseTextureInfo(\n clearcoat.clearcoatRoughnessTexture,\n textures,\n ),\n }),\n ...(clearcoat.clearcoatNormalTexture === undefined\n ? {}\n : {\n clearcoatNormalTexture: {\n ...parseTextureInfo(clearcoat.clearcoatNormalTexture, textures),\n ...(clearcoat.clearcoatNormalTexture.scale === undefined\n ? {}\n : { scale: clearcoat.clearcoatNormalTexture.scale }),\n },\n }),\n }),\n ...(anisotropy === undefined\n ? {}\n : {\n anisotropyStrength: anisotropy.anisotropyStrength ?? 0,\n anisotropyRotation: anisotropy.anisotropyRotation ?? 0,\n anisotropyChannel: [0, 1, 2] as const,\n ...(anisotropy.anisotropyTexture === undefined\n ? {}\n : { anisotropyTexture: parseTextureInfo(anisotropy.anisotropyTexture, textures) }),\n }),\n ...(sheen === undefined\n ? {}\n : {\n sheenColorFactor: tuple3(sheen.sheenColorFactor) ?? [0, 0, 0],\n sheenColorChannel: [0, 1, 2] as const,\n sheenRoughnessFactor: sheen.sheenRoughnessFactor ?? 0,\n sheenRoughnessChannel: 3,\n ...(sheen.sheenColorTexture === undefined\n ? {}\n : { sheenColorTexture: parseTextureInfo(sheen.sheenColorTexture, textures) }),\n ...(sheen.sheenRoughnessTexture === undefined\n ? {}\n : { sheenRoughnessTexture: parseTextureInfo(sheen.sheenRoughnessTexture, textures) }),\n }),\n ...(iridescence === undefined\n ? {}\n : {\n iridescenceFactor: iridescence.iridescenceFactor ?? 0,\n iridescenceIor: iridescence.iridescenceIor ?? 1.3,\n iridescenceThicknessMinimum: iridescence.iridescenceThicknessMinimum ?? 100,\n iridescenceThicknessMaximum: iridescence.iridescenceThicknessMaximum ?? 400,\n iridescenceChannel: 0,\n iridescenceThicknessChannel: 1,\n ...(iridescence.iridescenceTexture === undefined\n ? {}\n : { iridescenceTexture: parseTextureInfo(iridescence.iridescenceTexture, textures) }),\n ...(iridescence.iridescenceThicknessTexture === undefined\n ? {}\n : {\n iridescenceThicknessTexture: parseTextureInfo(\n iridescence.iridescenceThicknessTexture,\n textures,\n ),\n }),\n }),\n ...(specular === undefined\n ? {}\n : {\n specularFactor: specular.specularFactor ?? 1,\n specularChannel: 3,\n specularColorFactor: tuple3(specular.specularColorFactor) ?? [1, 1, 1],\n specularColorChannel: [0, 1, 2] as const,\n ...(specular.specularTexture === undefined\n ? {}\n : { specularTexture: parseTextureInfo(specular.specularTexture, textures) }),\n ...(specular.specularColorTexture === undefined\n ? {}\n : {\n specularColorTexture: parseTextureInfo(specular.specularColorTexture, textures),\n }),\n }),\n ...(alphaMode === undefined ? {} : { alphaMode }),\n ...(alphaCutoff === undefined ? {} : { alphaCutoff }),\n ...(matJson.doubleSided === true ? { doubleSided: true } : {}),\n ...(pbr?.baseColorTexture?.texCoord === undefined || pbr.baseColorTexture.texCoord === 0\n ? {}\n : { baseColorTexCoord: pbr.baseColorTexture.texCoord }),\n });\n}\n\nimport { err, type GltfError, gltfErr, ok, type Result } from '../errors.js';\n","import type { BufferViewJson } from './accessor/decode-accessor.js';\nimport {\n err,\n GLTF_MESHOPT_FILTERS,\n GLTF_MESHOPT_MODES,\n type GltfError,\n type GltfMeshoptFilter,\n type GltfMeshoptMode,\n gltfErr,\n ok,\n type Result,\n} from './errors.js';\n\nexport type MeshoptMode = GltfMeshoptMode;\nexport type MeshoptFilter = GltfMeshoptFilter;\n\nexport interface MeshoptCompressionJson {\n readonly buffer: number;\n readonly byteOffset?: number;\n readonly byteLength: number;\n readonly byteStride: number;\n readonly count: number;\n readonly mode: MeshoptMode;\n readonly filter?: MeshoptFilter;\n}\n\nexport interface MeshoptBufferViewJson extends BufferViewJson {\n readonly extensions?: {\n readonly EXT_meshopt_compression?: MeshoptCompressionJson;\n };\n}\n\nexport interface GltfBufferViewDecodeCapability {\n readonly decode: (input: {\n readonly source: Uint8Array;\n readonly count: number;\n readonly stride: number;\n readonly mode: MeshoptMode;\n readonly filter: MeshoptFilter;\n }) => Uint8Array | Promise<Uint8Array>;\n}\n\nexport interface MeshoptProjection {\n readonly bufferViews: readonly MeshoptBufferViewJson[];\n readonly buffers: readonly Uint8Array[];\n readonly decodedCount: number;\n}\n\nfunction viewBytes(\n view: MeshoptBufferViewJson,\n buffers: readonly Uint8Array[],\n): Uint8Array | undefined {\n const buffer = buffers[view.buffer];\n const offset = view.byteOffset ?? 0;\n if (\n buffer === undefined ||\n view.byteLength <= 0 ||\n offset < 0 ||\n offset + view.byteLength > buffer.length\n ) {\n return undefined;\n }\n return buffer.subarray(offset, offset + view.byteLength);\n}\n\nfunction validMode(mode: string): mode is MeshoptMode {\n return GLTF_MESHOPT_MODES.some((candidate) => candidate === mode);\n}\n\nfunction validFilter(filter: string): filter is MeshoptFilter {\n return GLTF_MESHOPT_FILTERS.some((candidate) => candidate === filter);\n}\n\nfunction filterAllowed(mode: MeshoptMode, filter: MeshoptFilter): boolean {\n return mode === 'ATTRIBUTES' || filter === 'NONE';\n}\n\n/**\n * Resolve EXT_meshopt_compression bufferViews before any accessor consumer.\n * Optional assets keep a valid core bufferView fallback when no decoder is\n * installed; required or compressed-only assets fail with a structured error.\n */\nexport async function projectMeshoptBufferViews(\n inputViews: readonly MeshoptBufferViewJson[],\n inputBuffers: readonly Uint8Array[],\n extensionsRequired: readonly string[],\n capability?: GltfBufferViewDecodeCapability,\n): Promise<Result<MeshoptProjection, GltfError>> {\n const buffers = [...inputBuffers];\n const bufferViews = inputViews.map((view) => ({ ...view }));\n let decodedCount = 0;\n\n for (let index = 0; index < bufferViews.length; index++) {\n const view = bufferViews[index];\n if (view === undefined) continue;\n const extension = view.extensions?.EXT_meshopt_compression;\n if (extension === undefined) continue;\n\n const filter = extension.filter ?? 'NONE';\n if (\n !validMode(extension.mode) ||\n !validFilter(filter) ||\n !filterAllowed(extension.mode, filter) ||\n !Number.isInteger(extension.byteStride) ||\n extension.byteStride <= 0 ||\n !Number.isInteger(extension.count) ||\n extension.count <= 0 ||\n !Number.isInteger(extension.byteLength) ||\n extension.byteLength <= 0\n ) {\n return err(\n gltfErr('gltf-meshopt-decode-failed', {\n bufferView: index,\n actual: 'invalid mode/filter/stride/count/byteLength',\n mode: validMode(extension.mode) ? extension.mode : 'ATTRIBUTES',\n filter: validFilter(filter) ? filter : 'NONE',\n }),\n );\n }\n\n const fallback = viewBytes(view, buffers);\n const required = extensionsRequired.includes('EXT_meshopt_compression');\n if (capability === undefined && !required && fallback !== undefined) continue;\n if (capability === undefined) {\n return err(\n gltfErr('gltf-meshopt-decoder-required', {\n bufferView: index,\n actual: required ? 'required' : 'compressed-only',\n hasCoreFallback: fallback !== undefined,\n }),\n );\n }\n\n const compressedBuffer = buffers[extension.buffer];\n const compressedOffset = extension.byteOffset ?? 0;\n if (\n compressedBuffer === undefined ||\n !Number.isInteger(compressedOffset) ||\n compressedOffset < 0 ||\n compressedOffset + extension.byteLength > compressedBuffer.length\n ) {\n return err(\n gltfErr('gltf-meshopt-decode-failed', {\n bufferView: index,\n actual: 'compressed range out of bounds',\n mode: extension.mode,\n filter,\n }),\n );\n }\n\n let decoded: Uint8Array;\n try {\n decoded = await capability.decode({\n source: compressedBuffer.subarray(\n compressedOffset,\n compressedOffset + extension.byteLength,\n ),\n count: extension.count,\n stride: extension.byteStride,\n mode: extension.mode,\n filter,\n });\n } catch (cause) {\n return err(\n gltfErr('gltf-meshopt-decode-failed', {\n bufferView: index,\n actual: `decoder rejected compressed range: ${cause instanceof Error ? cause.message : String(cause)}`,\n mode: extension.mode,\n filter,\n }),\n );\n }\n\n const expectedLength = extension.count * extension.byteStride;\n if (!(decoded instanceof Uint8Array) || decoded.byteLength !== expectedLength) {\n return err(\n gltfErr('gltf-meshopt-decode-failed', {\n bufferView: index,\n actual: `decoded byteLength=${decoded?.byteLength ?? 'invalid'}, expected=${expectedLength}`,\n mode: extension.mode,\n filter,\n }),\n );\n }\n\n const decodedBufferIndex = buffers.length;\n buffers.push(decoded);\n const { extensions: _extensions, ...plainView } = view;\n bufferViews[index] = {\n ...plainView,\n buffer: decodedBufferIndex,\n byteOffset: 0,\n byteLength: expectedLength,\n };\n decodedCount++;\n }\n\n return ok({ bufferViews, buffers, decodedCount });\n}\n","export interface NamedNode {\n readonly name?: string;\n readonly children?: readonly number[];\n}\n\nexport function buildNodeParentMap(nodes: readonly NamedNode[]): ReadonlyMap<number, number> {\n const parents = new Map<number, number>();\n for (let index = 0; index < nodes.length; index++) {\n for (const child of nodes[index]?.children ?? []) parents.set(child, index);\n }\n return parents;\n}\n\nexport function resolveNamedNodePath(\n nodes: readonly NamedNode[],\n parents: ReadonlyMap<number, number>,\n nodeIndex: number,\n):\n | { readonly ok: true; readonly value: readonly string[] }\n | {\n readonly ok: false;\n readonly reason: 'name-missing' | 'hierarchy-cycle';\n readonly nodeIndex: number;\n } {\n const reversed: string[] = [];\n const visited = new Set<number>();\n let current: number | undefined = nodeIndex;\n while (current !== undefined) {\n if (visited.has(current)) {\n return { ok: false, reason: 'hierarchy-cycle', nodeIndex: current };\n }\n visited.add(current);\n const name = nodes[current]?.name;\n if (name === undefined || name.length === 0) {\n return { ok: false, reason: 'name-missing', nodeIndex: current };\n }\n reversed.push(name);\n current = parents.get(current);\n }\n return { ok: true, value: reversed.reverse() };\n}\n","// parse-animation.ts - glTF animation parser (feat-20260523-skin-skeleton-animation M0).\n//\n// Implements parseAnimation(): parses glTF `animations[]` array into\n// GltfAnimationClipRecord[] with duration, channels, and sampler data.\n// Used by parseGltfWithBin to populate GltfDoc.\n//\n// Decision anchors:\n// - plan-strategy D-1 (AnimationClip independent asset)\n// - requirements AC-07 (AnimationClip shape), AC-09 (CUBICSPLINE/morph fail-fast)\n// - requirements AC-10 (IR extension)\n// - charter P3 (fail-fast on unsupported interpolation/morph targets)\n\nimport { deriveAnimationTargetId } from '@forgeax/engine-animation/target-id';\nimport type { AnimationTargetIdValue } from '@forgeax/engine-types';\nimport { decodeF32Accessor } from './accessor/decode-accessor.js';\nimport { err, type GltfError, gltfErr, ok, type Result } from './errors.js';\nimport { buildNodeParentMap, resolveNamedNodePath } from './node-path.js';\n\n/** Supported interpolation modes (CUBICSPLINE is deferred to OOS-skin-cubicspline). */\ntype Interpolation = 'LINEAR' | 'STEP';\n\ninterface ChannelJson {\n readonly sampler: number;\n readonly target: {\n readonly node?: number;\n readonly path: string;\n };\n}\n\ninterface SamplerJson {\n readonly input: number;\n readonly output: number;\n readonly interpolation?: string;\n}\n\ninterface AnimationJson {\n readonly name?: string;\n readonly channels: readonly ChannelJson[];\n readonly samplers: readonly SamplerJson[];\n}\n\nconst ANIMATION_ACCESSOR_TYPES = ['SCALAR', 'VEC2', 'VEC3', 'VEC4'] as const;\n\ninterface AccessorJson {\n readonly bufferView?: number;\n readonly componentType: number;\n readonly type: string;\n readonly count: number;\n readonly byteOffset?: number;\n}\n\ninterface BufferViewJson {\n readonly buffer: number;\n readonly byteOffset?: number;\n readonly byteLength: number;\n}\n\nexport interface GltfAnimationChannelRecord {\n readonly targetId: AnimationTargetIdValue;\n readonly targetNodeIndex: number;\n /** 'translation' | 'rotation' | 'scale' | 'weights'. */\n readonly property: 'translation' | 'rotation' | 'scale' | 'weights';\n /** Sampler driving this channel. */\n readonly sampler: GltfAnimationSamplerRecord;\n}\n\nexport interface GltfAnimationSamplerRecord {\n /** Keyframe timestamp array (ascending). */\n readonly input: Float32Array;\n /** Keyframe value array per element size. */\n readonly output: Float32Array;\n /** 'LINEAR' | 'STEP'. */\n readonly interpolation: Interpolation;\n}\n\nexport interface GltfAnimationClipRecord {\n /** Producer-authored animation name, when the source provides one. */\n readonly name?: string;\n /** Clip duration = max(sampler.input[last]). */\n readonly duration: number;\n /** Per-joint-property channels. */\n readonly channels: readonly GltfAnimationChannelRecord[];\n}\n\n/**\n * Parse glTF animations[] array into GltfAnimationClipRecord[].\n *\n * Only LINEAR and STEP interpolation are supported. CUBICSPLINE triggers\n * fail-fast with 'gltf-animation-cubicspline-unsupported'. Channels targeting\n * morph weights preserve their element-major sampler output for playback.\n */\nexport function parseAnimation(\n animationsJson: readonly AnimationJson[] | undefined,\n nodesJson: readonly { readonly name?: string; readonly children?: readonly number[] }[],\n accessors: readonly AccessorJson[],\n bufferViews: readonly BufferViewJson[],\n buffers: readonly Uint8Array[],\n): Result<readonly GltfAnimationClipRecord[], GltfError> {\n if (animationsJson === undefined || animationsJson.length === 0) {\n return ok([]);\n }\n\n const clips: GltfAnimationClipRecord[] = [];\n const parentOf = buildNodeParentMap(nodesJson);\n const nodeByPath = new Map<string, number>();\n const pathById = new Map<AnimationTargetIdValue, string>();\n\n for (let animIdx = 0; animIdx < animationsJson.length; animIdx++) {\n const anim = animationsJson[animIdx];\n if (anim === undefined) continue;\n\n // Decode samplers first (shared across channels).\n const decodedSamplers: GltfAnimationSamplerRecord[] = [];\n for (let sampIdx = 0; sampIdx < anim.samplers.length; sampIdx++) {\n const sampler = anim.samplers[sampIdx];\n if (sampler === undefined) continue;\n\n const interpolation = (sampler.interpolation ?? 'LINEAR') as string;\n if (interpolation === 'CUBICSPLINE') {\n return err(\n gltfErr('gltf-animation-cubicspline-unsupported', {\n animationIndex: animIdx,\n samplerIndex: sampIdx,\n }),\n );\n }\n if (interpolation !== 'LINEAR' && interpolation !== 'STEP') {\n return err(\n gltfErr('gltf-animation-cubicspline-unsupported', {\n animationIndex: animIdx,\n samplerIndex: sampIdx,\n }),\n );\n }\n\n const inputAcc = accessors[sampler.input];\n if (inputAcc === undefined) {\n return err(\n gltfErr('gltf-buffer-out-of-bounds', {\n accessor: sampler.input,\n byteOffset: 0,\n byteLength: 0,\n bufferIndex: 0,\n }),\n );\n }\n const inputResult = decodeF32Accessor(\n sampler.input,\n inputAcc,\n ANIMATION_ACCESSOR_TYPES,\n bufferViews,\n buffers,\n );\n if (!inputResult.ok) return err(inputResult.error);\n\n const outputAcc = accessors[sampler.output];\n if (outputAcc === undefined) {\n return err(\n gltfErr('gltf-buffer-out-of-bounds', {\n accessor: sampler.output,\n byteOffset: 0,\n byteLength: 0,\n bufferIndex: 0,\n }),\n );\n }\n const outputResult = decodeF32Accessor(\n sampler.output,\n outputAcc,\n ANIMATION_ACCESSOR_TYPES,\n bufferViews,\n buffers,\n );\n if (!outputResult.ok) return err(outputResult.error);\n\n decodedSamplers.push({\n input: inputResult.value,\n output: outputResult.value,\n interpolation: interpolation as Interpolation,\n });\n }\n\n // Decode channels.\n const channels: GltfAnimationChannelRecord[] = [];\n for (let chIdx = 0; chIdx < anim.channels.length; chIdx++) {\n const ch = anim.channels[chIdx];\n if (ch === undefined) continue;\n\n const samplerRecord = decodedSamplers[ch.sampler];\n if (samplerRecord === undefined) {\n return err(\n gltfErr('gltf-buffer-out-of-bounds', {\n accessor: ch.sampler,\n byteOffset: 0,\n byteLength: 0,\n bufferIndex: 0,\n }),\n );\n }\n\n const targetNodeIdx = ch.target.node;\n const path =\n targetNodeIdx === undefined\n ? { ok: false as const, reason: 'name-missing' as const, nodeIndex: -1 }\n : resolveNamedNodePath(nodesJson, parentOf, targetNodeIdx);\n if (!path.ok) {\n return err(\n gltfErr('gltf-animation-target-invalid', {\n reason: path.reason,\n animationIndex: animIdx,\n channelIndex: chIdx,\n nodeIndex: path.nodeIndex,\n }),\n );\n }\n if (\n ch.target.path !== 'weights' &&\n ch.target.path !== 'translation' &&\n ch.target.path !== 'rotation' &&\n ch.target.path !== 'scale'\n ) {\n return err(\n gltfErr('gltf-morph-unsupported', {\n animationIndex: animIdx,\n channelIndex: chIdx,\n nodeIndex: ch.target.node ?? -1,\n }),\n );\n }\n const pathKey = JSON.stringify(path.value);\n const previousNode = nodeByPath.get(pathKey);\n if (previousNode !== undefined && previousNode !== targetNodeIdx) {\n return err(\n gltfErr('gltf-animation-target-invalid', {\n reason: 'path-duplicate',\n animationIndex: animIdx,\n channelIndex: chIdx,\n nodeIndex: targetNodeIdx as number,\n }),\n );\n }\n nodeByPath.set(pathKey, targetNodeIdx as number);\n const targetId = deriveAnimationTargetId(path.value);\n const previousPath = pathById.get(targetId);\n if (previousPath !== undefined && previousPath !== pathKey) {\n return err(\n gltfErr('gltf-animation-target-invalid', {\n reason: 'id-collision',\n animationIndex: animIdx,\n channelIndex: chIdx,\n nodeIndex: targetNodeIdx as number,\n }),\n );\n }\n pathById.set(targetId, pathKey);\n\n channels.push({\n targetId,\n targetNodeIndex: targetNodeIdx as number,\n property: ch.target.path,\n sampler: samplerRecord,\n });\n }\n\n // Compute duration = max(sampler.input[last]) across all channels.\n let duration = 0;\n for (const ch of channels) {\n const input = ch.sampler.input;\n if (input.length > 0) {\n const last = input[input.length - 1];\n if (last !== undefined && last > duration) {\n duration = last;\n }\n }\n }\n\n const name = anim.name?.trim();\n clips.push({\n ...(name === undefined || name.length === 0 ? {} : { name }),\n duration,\n channels,\n });\n }\n\n return ok(clips);\n}\n","// parse-gltf-header.ts - asset.version check for the parsed glTF JSON\n// document (w8). Pure function, no I/O.\n//\n// glTF 2.0 spec section 3.1: every glTF JSON document MUST carry an\n// `asset.version` literal. v1 / v3 are not parsed by this importer\n// (v3 does not exist; v1 is a different format). This step is the gate\n// before any deeper structural traversal.\n//\n// Producers route through `gltfErr` (errors.ts SSOT) so `expected` and\n// `hint` fields stay aligned with the GLTF_ERROR_HINTS table.\n\nimport type { GltfError } from './errors.js';\nimport { err, gltfErr, ok, type Result } from './errors.js';\n\n/** Minimal JSON shape touched by the version gate. */\nexport interface GltfHeaderJson {\n readonly asset?: { readonly version?: string };\n}\n\n/**\n * Validate the top-level `asset.version` field of a parsed glTF document.\n *\n * On success the JSON object is echoed back unchanged (caller already owns\n * the parsed representation). On failure, the closed `GltfErrorCode`\n * surface narrows to either `gltf-malformed-header` (asset block missing)\n * or `gltf-version-unsupported` (version != \"2.0\").\n */\nexport function parseGltfHeader(\n json: unknown,\n filePath: string,\n): Result<GltfHeaderJson, GltfError> {\n if (json === null || typeof json !== 'object' || !('asset' in json)) {\n return err(\n gltfErr('gltf-malformed-header', {\n filePath,\n byteOffset: 0,\n }),\n );\n }\n const asset = (json as GltfHeaderJson).asset;\n if (!asset || typeof asset !== 'object' || typeof asset.version !== 'string') {\n return err(\n gltfErr('gltf-malformed-header', {\n filePath,\n byteOffset: 0,\n }),\n );\n }\n if (asset.version !== '2.0') {\n return err(\n gltfErr('gltf-version-unsupported', {\n filePath,\n actualVersion: asset.version,\n }),\n );\n }\n return ok(json as GltfHeaderJson);\n}\n","// parse-glb-chunks.ts - GLB 2.0 binary container parser (w8).\n//\n// Pure function: ArrayBuffer in, Result<{version, length, jsonChunk, binChunk?}, GltfError> out.\n// No fs, no fetch, no global state. Caller owns I/O.\n//\n// GLB 2.0 layout (Khronos KHR glTF-2.0 GLB section):\n//\n// header (12 bytes, little-endian uint32 each):\n// magic = 0x46546C67 ('glTF')\n// version = 2\n// length = total byte length of the GLB container (header + chunks)\n//\n// chunk (variable):\n// chunkLength (uint32 LE)\n// chunkType (uint32 LE)\n// 0x4E4F534A = 'JSON' - exactly one, must be the first chunk\n// 0x004E4942 = 'BIN' - at most one, must be the second chunk\n// chunkData (chunkLength bytes; padded so chunkLength is a multiple of 4)\n//\n// `parseGltfHeader` (asset.version check) lives in parse-gltf-header.ts and\n// is re-exported here so call sites can grab both binary and JSON gates from\n// a single entry without walking module paths.\n\nimport { err, type GltfError, gltfErr, ok, type Result } from './errors.js';\nimport { parseGltfHeader } from './parse-gltf-header.js';\n\nexport type { GltfHeaderJson } from './parse-gltf-header.js';\nexport { parseGltfHeader };\n\nconst GLB_HEADER_SIZE = 12;\nconst GLB_MAGIC = 0x46546c67;\nconst CHUNK_HEADER_SIZE = 8;\nconst CHUNK_TYPE_JSON = 0x4e4f534a;\nconst CHUNK_TYPE_BIN = 0x004e4942;\n\n/** Result payload of {@link parseGlbChunks}. */\nexport interface GlbChunks {\n readonly version: number;\n readonly length: number;\n readonly jsonChunk: Uint8Array;\n readonly binChunk?: Uint8Array;\n}\n\n/**\n * Split a GLB 2.0 binary container into its `JSON` chunk and optional\n * `BIN` chunk. Returns the declared `version` and `length` for the caller\n * to surface in diagnostics.\n *\n * Failure path returns one of:\n * - `gltf-malformed-header` (magic / chunk shape / declared length / missing JSON)\n * - `gltf-version-unsupported` (version != 2)\n *\n * The function is pure: no fs / network access; the caller passes the\n * already-loaded ArrayBuffer.\n */\nexport function parseGlbChunks(\n buffer: ArrayBuffer,\n filePath: string,\n): Result<GlbChunks, GltfError> {\n if (buffer.byteLength < GLB_HEADER_SIZE) {\n return err(\n gltfErr('gltf-malformed-header', {\n filePath,\n byteOffset: 0,\n }),\n );\n }\n const view = new DataView(buffer);\n const magic = view.getUint32(0, true);\n if (magic !== GLB_MAGIC) {\n return err(\n gltfErr('gltf-malformed-header', {\n filePath,\n byteOffset: 0,\n magic,\n }),\n );\n }\n const version = view.getUint32(4, true);\n if (version !== 2) {\n return err(\n gltfErr('gltf-version-unsupported', {\n filePath,\n actualVersion: String(version),\n }),\n );\n }\n const declaredLength = view.getUint32(8, true);\n if (declaredLength !== buffer.byteLength) {\n return err(\n gltfErr('gltf-malformed-header', {\n filePath,\n byteOffset: 8,\n }),\n );\n }\n\n // First chunk MUST be JSON.\n let offset = GLB_HEADER_SIZE;\n if (offset + CHUNK_HEADER_SIZE > buffer.byteLength) {\n return err(\n gltfErr('gltf-malformed-header', {\n filePath,\n byteOffset: offset,\n }),\n );\n }\n const jsonChunkLength = view.getUint32(offset, true);\n const jsonChunkType = view.getUint32(offset + 4, true);\n if (jsonChunkType !== CHUNK_TYPE_JSON) {\n return err(\n gltfErr('gltf-malformed-header', {\n filePath,\n byteOffset: offset + 4,\n }),\n );\n }\n if (offset + CHUNK_HEADER_SIZE + jsonChunkLength > buffer.byteLength) {\n return err(\n gltfErr('gltf-malformed-header', {\n filePath,\n byteOffset: offset,\n }),\n );\n }\n const jsonChunk = new Uint8Array(buffer, offset + CHUNK_HEADER_SIZE, jsonChunkLength);\n offset += CHUNK_HEADER_SIZE + jsonChunkLength;\n\n // Optional BIN chunk follows JSON.\n let binChunk: Uint8Array | undefined;\n if (offset < buffer.byteLength) {\n if (offset + CHUNK_HEADER_SIZE > buffer.byteLength) {\n return err(\n gltfErr('gltf-malformed-header', {\n filePath,\n byteOffset: offset,\n }),\n );\n }\n const binChunkLength = view.getUint32(offset, true);\n const binChunkType = view.getUint32(offset + 4, true);\n if (binChunkType !== CHUNK_TYPE_BIN) {\n return err(\n gltfErr('gltf-malformed-header', {\n filePath,\n byteOffset: offset + 4,\n }),\n );\n }\n if (offset + CHUNK_HEADER_SIZE + binChunkLength > buffer.byteLength) {\n return err(\n gltfErr('gltf-malformed-header', {\n filePath,\n byteOffset: offset,\n }),\n );\n }\n binChunk = new Uint8Array(buffer, offset + CHUNK_HEADER_SIZE, binChunkLength);\n }\n\n return ok({\n version,\n length: declaredLength,\n jsonChunk,\n ...(binChunk === undefined ? {} : { binChunk }),\n });\n}\n","// parse-skin.ts - glTF skin parser (feat-20260523-skin-skeleton-animation M0).\n//\n// Implements parseSkin(): parses glTF `skins[]` array into GltfSkeletonRecord[]\n// with IBM (inverse bind matrices) and jointPaths (Name-component path from\n// scene root). Used by parseGltfWithBin to populate GltfDoc.\n//\n// Decision anchors:\n// - plan-strategy D-1 (3-asset separation: IBM / skin binding / animation clip)\n// - plan-strategy D-2 (skin index dedupe via reimport reuse managed by toAssetPack)\n// - requirements AC-03 (skin index dedupe), AC-05 (jointPaths + Name missing fail-fast)\n// - requirements AC-10 (IR extension), AC-27 (BindPose static AABB)\n// - plan-strategy D-11 (BindPose AABB importer-phase, per-frame zero cost)\n// - charter P3 (fail-fast on invalid data)\n\nimport { decodeF32Accessor } from './accessor/decode-accessor.js';\nimport { err, type GltfError, gltfErr, ok, type Result } from './errors.js';\nimport { buildNodeParentMap, resolveNamedNodePath } from './node-path.js';\n\n/** Maximum joints per skin (glTF spec practical limit). */\nconst MAX_JOINTS = 256;\n\n/**\n * Skeleton intermediate representation produced by parseSkin.\n *\n * Each entry corresponds to one glTF skin[] index. `jointPaths` is a\n * parallel array to the skeleton's joints; each path is the sequence of\n * Name-component values from the scene root to the joint node.\n */\nexport interface GltfSkeletonRecord {\n /** Number of joints in this skeleton (= IBM length / 16). */\n readonly jointCount: number;\n /** Inverse bind matrices, Float32Array of length jointCount * 16. */\n readonly inverseBindMatrices: Float32Array;\n /** Per-joint Name path from scene root (parallel to joints array). */\n readonly jointPaths: readonly string[];\n}\n\ninterface SkinJson {\n readonly name?: string;\n readonly joints: readonly number[];\n readonly inverseBindMatrices?: number;\n}\n\ninterface NodeJson {\n readonly name?: string;\n readonly mesh?: number;\n readonly children?: readonly number[];\n readonly skin?: number;\n}\n\ninterface AccessorJson {\n readonly bufferView?: number;\n readonly componentType: number;\n readonly type: string;\n readonly count: number;\n readonly byteOffset?: number;\n}\n\ninterface BufferViewJson {\n readonly buffer: number;\n readonly byteOffset?: number;\n readonly byteLength: number;\n readonly byteStride?: number;\n}\n\nconst SKIN_ACCESSOR_TYPES = ['MAT4'] as const;\n\n/** Build a column-major mat4 identity Float32Array (16 floats). */\nfunction identityMat4(): Float32Array {\n const m = new Float32Array(16);\n m[0] = 1;\n m[5] = 1;\n m[10] = 1;\n m[15] = 1;\n return m;\n}\n\n/**\n * Build the jointPath for a single joint: find the Name-component path from\n * the root of the scene graph to the joint node.\n *\n * Uses recursive BFS-like upward traversal: for each joint node index,\n * find the node's name and verify it's reachable from root.\n * Returns the sequence of names from root to joint.\n *\n * On first miss (node has no name), emits 'gltf-skin-joint-name-missing'.\n */\nfunction resolveJointPath(\n nodeIndex: number,\n nodes: readonly NodeJson[],\n parentOf: ReadonlyMap<number, number>,\n skinIndex: number,\n jointPathIndex: number,\n): Result<readonly string[], GltfError> {\n const path = resolveNamedNodePath(nodes, parentOf, nodeIndex);\n if (!path.ok) {\n return err(\n gltfErr('gltf-skin-joint-name-missing', {\n reason: path.reason,\n skinIndex,\n jointPathIndex,\n nodeIndex: path.nodeIndex,\n }),\n );\n }\n return ok(path.value);\n}\n\n/**\n * Parse glTF skins[] array into GltfSkeletonRecord[].\n *\n * For each skin:\n * 1. Decode IBM accessor (or fill identity if absent)\n * 2. Resolve jointPaths from scene node hierarchy\n * 3. Fail-fast on joint count > MAX_JOINTS or missing joint names\n */\nexport function parseSkin(\n skinsJson: readonly SkinJson[] | undefined,\n nodesJson: readonly NodeJson[],\n accessors: readonly AccessorJson[],\n bufferViews: readonly BufferViewJson[],\n buffers: readonly Uint8Array[],\n): Result<readonly GltfSkeletonRecord[], GltfError> {\n if (skinsJson === undefined || skinsJson.length === 0) {\n return ok([]);\n }\n\n const records: GltfSkeletonRecord[] = [];\n const parentOf = buildNodeParentMap(nodesJson);\n\n for (let skinIdx = 0; skinIdx < skinsJson.length; skinIdx++) {\n const skin = skinsJson[skinIdx];\n if (skin === undefined) continue;\n\n const joints = skin.joints;\n if (joints.length > MAX_JOINTS) {\n return err(\n gltfErr('gltf-skin-joint-count-exceeded', {\n skinIndex: skinIdx,\n jointCount: joints.length,\n maxJoints: MAX_JOINTS,\n }),\n );\n }\n\n // Decode IBM, or fill identity matrix.\n let ibm: Float32Array;\n if (skin.inverseBindMatrices !== undefined) {\n const ibmAccIdx = skin.inverseBindMatrices;\n const ibmAcc = accessors[ibmAccIdx];\n if (ibmAcc === undefined) {\n return err(\n gltfErr('gltf-buffer-out-of-bounds', {\n accessor: ibmAccIdx,\n byteOffset: 0,\n byteLength: 0,\n bufferIndex: 0,\n }),\n );\n }\n const ibmResult = decodeF32Accessor(\n ibmAccIdx,\n ibmAcc,\n SKIN_ACCESSOR_TYPES,\n bufferViews,\n buffers,\n );\n if (!ibmResult.ok) return err(ibmResult.error);\n ibm = ibmResult.value;\n } else {\n // Fill identity: each joint gets a 4x4 identity.\n ibm = new Float32Array(joints.length * 16);\n for (let j = 0; j < joints.length; j++) {\n ibm.set(identityMat4(), j * 16);\n }\n }\n\n // Resolve jointPaths.\n const jointPaths: string[] = [];\n for (let j = 0; j < joints.length; j++) {\n const jointNodeIndex = joints[j];\n if (jointNodeIndex === undefined) continue;\n const pathResult = resolveJointPath(jointNodeIndex, nodesJson, parentOf, skinIdx, j);\n if (!pathResult.ok) return err(pathResult.error);\n jointPaths.push(pathResult.value.join('/'));\n }\n\n records.push({\n jointCount: joints.length,\n inverseBindMatrices: ibm,\n jointPaths,\n });\n }\n\n return ok(records);\n}\n\n/**\n * Compute the BindPose static AABB for a skinned mesh's vertex positions.\n *\n * At bind pose, joint_bind = IBM^{-1}, so skinning collapses:\n * world_pos = Sum(w_i * joint_bind_i * IBM_i * local_pos) = local_pos\n * Therefore the BindPose AABB is simply the local position bounds.\n *\n * Per-frame zero cost: stored in mesh asset metadata at importer time.\n * Dynamic AABB for animated poses is deferred to OOS-skin-dyn-bounds.\n *\n * Returns { min: [x,y,z], max: [x,y,z] } or undefined if positions is empty.\n */\nexport function computeBindPoseAABB(positions: Float32Array):\n | {\n readonly min: readonly [number, number, number];\n readonly max: readonly [number, number, number];\n }\n | undefined {\n if (positions.length < 3) return undefined;\n let minX = positions[0] ?? 0;\n let minY = positions[1] ?? 0;\n let minZ = positions[2] ?? 0;\n let maxX = minX;\n let maxY = minY;\n let maxZ = minZ;\n for (let i = 3; i < positions.length; i += 3) {\n const x = positions[i] ?? 0;\n const y = positions[i + 1] ?? 0;\n const z = positions[i + 2] ?? 0;\n if (x < minX) minX = x;\n if (y < minY) minY = y;\n if (z < minZ) minZ = z;\n if (x > maxX) maxX = x;\n if (y > maxY) maxY = y;\n if (z > maxZ) maxZ = z;\n }\n return { min: [minX, minY, minZ], max: [maxX, maxY, maxZ] };\n}\n\n/** Re-export MAX_JOINTS for use by downstream modules. */\nexport { MAX_JOINTS };\n","// transform.ts - decomposeNodeTransform (w11).\n//\n// glTF 2.0 spec section 3.7 (node):\n// - node.matrix : 16 floats column-major (mutually exclusive with TRS,\n// per spec, but real-world DCC tools occasionally\n// export both - forgeax tolerates this with stderr\n// warn + diagnostics record per requirements section\n// boundary cases)\n// - node.translation: VEC3 (default identity translation)\n// - node.rotation : VEC4 quaternion (default identity rotation)\n// - node.scale : VEC3 (default identity scale)\n//\n// This wrapper hides the math package's in-place 3-arg `mat4.decompose`\n// signature behind a POD readonly tuple return so the importer surface\n// stays Vec3/Quat brand-free at the API boundary (charter proposition 5\n// consistent abstraction; plan-strategy decision section 2.7 / OQ-2).\n\nimport { mat4, quat, vec3 } from '@forgeax/engine-math';\n\n/** glTF VEC3 literal accepted by node.translation / node.scale. */\nexport type Vec3Tuple = readonly [number, number, number];\n/** glTF VEC4 quaternion literal accepted by node.rotation. */\nexport type Vec4Tuple = readonly [number, number, number, number];\n\n/** Minimal node JSON shape touched by the decomposer. */\nexport interface NodeTransformJson {\n readonly matrix?: readonly number[];\n readonly translation?: readonly number[];\n readonly rotation?: readonly number[];\n readonly scale?: readonly number[];\n}\n\n/** Mutable diagnostics accumulator (writes to .matrixTrsCoexistNodes only). */\nexport interface TransformDiagnostics {\n matrixTrsCoexistNodes: number[];\n}\n\nexport interface DecomposedTransform {\n readonly translation: Vec3Tuple;\n readonly rotation: Vec4Tuple;\n readonly scale: Vec3Tuple;\n}\n\nconst IDENTITY: DecomposedTransform = {\n translation: [0, 0, 0] as const,\n rotation: [0, 0, 0, 1] as const,\n scale: [1, 1, 1] as const,\n};\n\nfunction tuple3(arr: readonly number[] | undefined, fallback: Vec3Tuple): Vec3Tuple {\n if (arr === undefined || arr.length < 3) return fallback;\n return [arr[0] ?? fallback[0], arr[1] ?? fallback[1], arr[2] ?? fallback[2]];\n}\n\nfunction tuple4(arr: readonly number[] | undefined, fallback: Vec4Tuple): Vec4Tuple {\n if (arr === undefined || arr.length < 4) return fallback;\n return [\n arr[0] ?? fallback[0],\n arr[1] ?? fallback[1],\n arr[2] ?? fallback[2],\n arr[3] ?? fallback[3],\n ];\n}\n\n/**\n * Decompose a glTF node's transform into a POD readonly TRS triple.\n *\n * Decision tree:\n * 1. matrix present -> mat4.decompose 3-arg in-place; if\n * any TRS field is also present,\n * stderr warn + push nodeIndex into\n * diagnostics.matrixTrsCoexistNodes.\n * 2. only TRS fields present -> use them verbatim (defaults filled).\n * 3. nothing present -> identity (0/0/0, 0/0/0/1, 1/1/1).\n *\n * Return type is `readonly` POD tuple, deliberately not Vec3/Quat from\n * @forgeax/engine-math, so the importer's IR stays brand-free\n * (plan-strategy decision section 2.7 / OQ-2).\n */\nexport function decomposeNodeTransform(\n node: NodeTransformJson,\n nodeIndex: number,\n diagnostics: TransformDiagnostics,\n): DecomposedTransform {\n const hasMatrix = node.matrix !== undefined && node.matrix.length === 16;\n const hasTrs =\n node.translation !== undefined || node.rotation !== undefined || node.scale !== undefined;\n\n if (hasMatrix) {\n if (hasTrs) {\n console.error(`[warn] node[${nodeIndex}] has both matrix and TRS, matrix takes precedence`);\n diagnostics.matrixTrsCoexistNodes.push(nodeIndex);\n }\n const out_t = vec3.create();\n const out_r = quat.create();\n const out_s = vec3.create(1, 1, 1);\n // node.matrix is glTF column-major float[16]; mat4.decompose accepts\n // Mat4Like (any indexable [0..15] number container).\n const m = node.matrix as readonly number[];\n mat4.decompose(out_t, out_r, out_s, m as unknown as Parameters<typeof mat4.decompose>[3]);\n return {\n translation: [out_t[0] ?? 0, out_t[1] ?? 0, out_t[2] ?? 0] as const,\n rotation: [out_r[0] ?? 0, out_r[1] ?? 0, out_r[2] ?? 0, out_r[3] ?? 1] as const,\n scale: [out_s[0] ?? 1, out_s[1] ?? 1, out_s[2] ?? 1] as const,\n };\n }\n\n if (!hasTrs) {\n return IDENTITY;\n }\n\n return {\n translation: tuple3(node.translation, IDENTITY.translation),\n rotation: tuple4(node.rotation, IDENTITY.rotation),\n scale: tuple3(node.scale, IDENTITY.scale),\n };\n}\n","// parse-gltf.ts - JSON-side glTF importer entry.\n// The public parse, GLB, asset-pack, mesh, and scene helpers live here.\n\nimport { mat4, quat, vec3 } from '@forgeax/engine-math';\nimport {\n IMPORT_ERROR_HINTS,\n ImportError,\n MESH_MATERIAL_SLOT_SOURCE_OVERRIDE_PAYLOAD_SCHEMA,\n type MeshMaterialSlotTopologyEntry,\n reconcileMeshMaterialSlotTopology,\n} from '@forgeax/engine-types';\nimport {\n type AccessorJson,\n type BufferViewJson,\n COMPONENT_TYPE,\n decodeAccessor,\n} from './accessor/decode-accessor.js';\nimport { decodeColorAccessor } from './accessor/decode-color.js';\nimport { checkExtensions, type GltfExtensionsJson } from './check-extensions.js';\nimport { Base64DecodeError, dataUriBase64Payload, decodeBase64 } from './data-uri.js';\nimport { err, type GltfError, gltfErr, ok, type Result } from './errors.js';\nimport { type GltfLodRelation, parseGltfLodExtension } from './lod/parse-lod.js';\nimport { projectGltfLodMeta } from './lod/project-meta.js';\nimport {\n type GltfImageIr,\n type GltfMaterialIr,\n type GltfMaterialJson,\n type GltfSamplerIr,\n type GltfTextureIr,\n parseMaterial,\n} from './material/parse-material.js';\nimport {\n type GltfBufferViewDecodeCapability,\n type MeshoptBufferViewJson,\n projectMeshoptBufferViews,\n} from './meshopt-decode.js';\nimport { type GltfAnimationClipRecord, parseAnimation } from './parse-animation.js';\nimport { parseGlbChunks } from './parse-glb-chunks.js';\nimport { parseGltfHeader } from './parse-gltf-header.js';\nimport { type GltfSkeletonRecord, parseSkin } from './parse-skin.js';\nimport {\n type GltfDocItem,\n type GltfMetaJson,\n type GltfSubAssetEntry,\n reimportReuseMeta,\n} from './reimport-reuse-meta.js';\nimport type { GltfSourceKeyError } from './source-key.js';\nimport { type DecomposedTransform, decomposeNodeTransform } from './transform.js';\n\nexport type {\n GltfImageIr,\n GltfMaterialIr,\n GltfMaterialJson,\n GltfNormalTextureInfoIr,\n GltfOcclusionTextureInfoIr,\n GltfSamplerIr,\n GltfTextureInfoIr,\n GltfTextureIr,\n GltfTextureTransformIr,\n NormalTextureInfoJson,\n OcclusionTextureInfoJson,\n TextureInfoJson,\n} from './material/parse-material.js';\n\nexport interface MeshPrimitiveJson {\n readonly attributes?: Record<string, number>;\n readonly indices?: number;\n readonly material?: number;\n readonly mode?: number;\n readonly targets?: ReadonlyArray<Record<string, number>>;\n}\n\nexport interface MeshJson {\n readonly name?: string;\n readonly weights?: readonly number[];\n readonly primitives: readonly MeshPrimitiveJson[];\n}\n\n// Tier-B IR: validated glTF JSON projected into downstream POD records.\n\ninterface InstancingAttributes {\n readonly TRANSLATION?: number;\n readonly ROTATION?: number;\n readonly SCALE?: number;\n}\n\n/**\n * Decode EXT_mesh_gpu_instancing attributes for a single node.\n *\n * Cross-validates that all present TRS accessor counts agree (spec\n * MUST clause \"Extending nodes with instance attributes\"). Missing\n * accessors fall back to identity (translation=(0,0,0),\n * rotation=(0,0,0,1), scale=(1,1,1)). Composes N column-major mat4 via\n * @forgeax/engine-math `mat4.compose`, packing them into a single\n * Float32Array of length N*16. Pure function: no fs / fetch / throw.\n */\nfunction decodeNodeInstancing(\n nodeIndex: number,\n attributes: InstancingAttributes,\n accessors: readonly AccessorJson[],\n bufferViews: readonly BufferViewJson[],\n buffers: readonly Uint8Array[],\n): Result<NodeInstancingIr, GltfError> {\n const tIdx = attributes.TRANSLATION;\n const rIdx = attributes.ROTATION;\n const sIdx = attributes.SCALE;\n\n let count: number | undefined;\n const setOrCheck = (label: 'TRANSLATION' | 'ROTATION' | 'SCALE', n: number): GltfError | null => {\n if (count === undefined) {\n count = n;\n return null;\n }\n if (n !== count) {\n return gltfErr('gltf-instancing-count-mismatch', {\n nodeIndex,\n accessor: label,\n expectedCount: count,\n actualCount: n,\n });\n }\n return null;\n };\n\n let tValues: Float32Array | undefined;\n if (tIdx !== undefined) {\n const acc = accessors[tIdx];\n if (acc === undefined) return err(unknownAccessor(tIdx));\n const e = setOrCheck('TRANSLATION', acc.count);\n if (e !== null) return err(e);\n const decoded = decodeAttributeAccessor(tIdx, acc, bufferViews, buffers);\n if (!decoded.ok) return err(decoded.error);\n tValues = decoded.value;\n }\n let rValues: Float32Array | undefined;\n if (rIdx !== undefined) {\n const acc = accessors[rIdx];\n if (acc === undefined) return err(unknownAccessor(rIdx));\n const e = setOrCheck('ROTATION', acc.count);\n if (e !== null) return err(e);\n const decoded = decodeAttributeAccessor(rIdx, acc, bufferViews, buffers);\n if (!decoded.ok) return err(decoded.error);\n rValues = decoded.value;\n }\n let sValues: Float32Array | undefined;\n if (sIdx !== undefined) {\n const acc = accessors[sIdx];\n if (acc === undefined) return err(unknownAccessor(sIdx));\n const e = setOrCheck('SCALE', acc.count);\n if (e !== null) return err(e);\n const decoded = decodeAttributeAccessor(sIdx, acc, bufferViews, buffers);\n if (!decoded.ok) return err(decoded.error);\n sValues = decoded.value;\n }\n\n const n = count ?? 0;\n const transforms = new Float32Array(n * 16);\n const tmp = mat4.create();\n const tv = vec3.create();\n const rv = quat.create();\n rv[3] = 1;\n const sv = vec3.create(1, 1, 1);\n for (let i = 0; i < n; i++) {\n if (tValues !== undefined) {\n tv[0] = tValues[i * 3] ?? 0;\n tv[1] = tValues[i * 3 + 1] ?? 0;\n tv[2] = tValues[i * 3 + 2] ?? 0;\n } else {\n tv[0] = 0;\n tv[1] = 0;\n tv[2] = 0;\n }\n if (rValues !== undefined) {\n rv[0] = rValues[i * 4] ?? 0;\n rv[1] = rValues[i * 4 + 1] ?? 0;\n rv[2] = rValues[i * 4 + 2] ?? 0;\n rv[3] = rValues[i * 4 + 3] ?? 1;\n } else {\n rv[0] = 0;\n rv[1] = 0;\n rv[2] = 0;\n rv[3] = 1;\n }\n if (sValues !== undefined) {\n sv[0] = sValues[i * 3] ?? 1;\n sv[1] = sValues[i * 3 + 1] ?? 1;\n sv[2] = sValues[i * 3 + 2] ?? 1;\n } else {\n sv[0] = 1;\n sv[1] = 1;\n sv[2] = 1;\n }\n mat4.compose(tmp, tv, rv, sv);\n for (let k = 0; k < 16; k++) {\n transforms[i * 16 + k] = tmp[k] ?? 0;\n }\n }\n\n return ok({ count: n, transforms });\n}\n\nfunction unknownAccessor(accessorIndex: number): GltfError {\n return gltfErr('gltf-accessor-type-mismatch', {\n accessorIndex,\n reason: 'unknownComponentType',\n });\n}\n\nfunction decodeAttributeAccessor(\n accessorIndex: number,\n accessor: AccessorJson,\n bufferViews: readonly BufferViewJson[],\n buffers: readonly Uint8Array[],\n): Result<Float32Array, GltfError> {\n const view = bufferViews[accessor.bufferView ?? -1];\n if (view === undefined) return err(unknownAccessor(accessorIndex));\n const buf = buffers[view.buffer];\n if (buf === undefined) return err(unknownAccessor(accessorIndex));\n const decoded = decodeAccessor({\n accessorIndex,\n accessor,\n bufferView: view,\n buffer: buf,\n role: 'attribute',\n });\n if (!decoded.ok) return err(decoded.error);\n if (decoded.value.kind !== 'f32') return err(unknownAccessor(accessorIndex));\n return ok(decoded.value.data);\n}\n\nexport interface GltfMeshIr {\n readonly name?: string;\n readonly positions: Float32Array;\n readonly normals?: Float32Array;\n readonly texcoord0?: Float32Array;\n /** TEXCOORD_1 per-vertex UV set 1. */\n readonly texcoord1?: Float32Array;\n /** TEXCOORD_2 per-vertex UV set 2. */\n readonly texcoord2?: Float32Array;\n /** TEXCOORD_3 per-vertex UV set 3. */\n readonly texcoord3?: Float32Array;\n /** TEXCOORD_4 per-vertex UV set 4. */\n readonly texcoord4?: Float32Array;\n /** TEXCOORD_5 per-vertex UV set 5. */\n readonly texcoord5?: Float32Array;\n /** TEXCOORD_6 per-vertex UV set 6. */\n readonly texcoord6?: Float32Array;\n /** TEXCOORD_7 per-vertex UV set 7. */\n readonly texcoord7?: Float32Array;\n readonly tangents?: Float32Array;\n /** COLOR_0 importer carrier. */\n readonly colors0?: Float32Array;\n /** JOINTS_0 per-vertex joint indices. */\n readonly joints0?: Uint16Array;\n /** WEIGHTS_0 per-vertex skin weights. */\n readonly weights0?: Float32Array;\n readonly morphTargets?: readonly {\n readonly position?: Float32Array;\n readonly normal?: Float32Array;\n readonly tangent?: Float32Array;\n }[];\n readonly morphWeights?: Float32Array;\n /** Undefined means non-indexed; otherwise source width is preserved. */\n readonly indices?: Uint16Array | Uint32Array;\n readonly materialIndex: number | null;\n /** Owning glTF mesh index; multiple IR rows may share it after flattening. */\n readonly meshIndex: number;\n}\n\nexport interface NodeInstancingIr {\n /** Number of instances. */\n readonly count: number;\n /** Column-major transforms packed into one Float32Array. */\n readonly transforms: Float32Array;\n}\n\nexport type GltfPunctualLightType = 'directional' | 'point' | 'spot';\n\nexport interface GltfPunctualLightIr {\n readonly type: GltfPunctualLightType;\n readonly color: readonly [number, number, number];\n readonly intensity: number;\n readonly range?: number;\n readonly spot?: {\n readonly innerConeAngle: number;\n readonly outerConeAngle: number;\n };\n}\n\nexport interface GltfNodeIr {\n readonly name?: string;\n readonly transform: DecomposedTransform;\n readonly meshIndex: number | null;\n /** Node-authored morph weights override mesh defaults. */\n readonly morphWeights?: Float32Array;\n readonly skinIndex: number | null;\n readonly children: readonly number[];\n readonly instancing?: NodeInstancingIr;\n readonly camera: number | null;\n readonly lightIndex?: number | null;\n}\n\nexport interface GltfSceneIr {\n readonly name?: string;\n readonly nodes: readonly number[];\n}\n\nexport interface GltfDiagnosticsIr {\n readonly nodeNames: readonly string[];\n readonly unsupportedExtensions: readonly string[];\n readonly matrixTrsCoexistNodes: readonly number[];\n}\n\nexport interface GltfDoc {\n readonly meshes: readonly GltfMeshIr[];\n readonly materials: readonly GltfMaterialIr[];\n readonly nodes: readonly GltfNodeIr[];\n readonly scenes: readonly GltfSceneIr[];\n readonly textures: readonly GltfTextureIr[] | undefined;\n readonly images: readonly GltfImageIr[] | undefined;\n readonly samplers: readonly GltfSamplerIr[] | undefined;\n readonly skeletons: readonly GltfSkeletonRecord[];\n readonly animationClips: readonly GltfAnimationClipRecord[];\n readonly defaultSceneIndex: number;\n readonly diagnostics: GltfDiagnosticsIr;\n /** KHR_lights_punctual author facts, kept in source units for the bridge. */\n readonly lights?: readonly GltfPunctualLightIr[];\n /** Raw extension projection retained for bridge-only hand-constructed docs. */\n readonly extensions?: {\n readonly KHR_lights_punctual?: {\n readonly lights?: readonly GltfPunctualLightIr[];\n };\n };\n /**\n * Original glTF-mesh-index -> number of primitives that mesh expanded into\n * (feat-20260608 round-2). parseGltf flattens N glTF meshes with M_i\n * primitives into sum(M_i) GltfMeshIr entries; this map preserves the M_i so\n * downstream consumers (gltfDocToSceneAsset's `meshPrimitiveCount` param)\n * can map a glTF mesh index back to the flat-GltfMeshIr offset range without\n * re-parsing JSON.\n *\n * Optional for backwards compatibility with hand-constructed test\n * fixtures; producers from parseGltf / parseGlb always populate it.\n */\n readonly meshPrimitiveCount?: ReadonlyMap<number, number>;\n readonly lod?: GltfLodRelation;\n}\n\ninterface BuffersJson {\n readonly byteLength: number;\n readonly uri?: string;\n}\n\ninterface RootGltfJson extends GltfExtensionsJson {\n readonly asset?: { readonly version?: string };\n readonly scene?: number;\n readonly scenes?: ReadonlyArray<{ readonly name?: string; readonly nodes?: readonly number[] }>;\n readonly nodes?: ReadonlyArray<{\n readonly name?: string;\n readonly mesh?: number;\n readonly skin?: number;\n readonly camera?: number;\n readonly children?: readonly number[];\n readonly matrix?: readonly number[];\n readonly translation?: readonly number[];\n readonly rotation?: readonly number[];\n readonly scale?: readonly number[];\n readonly weights?: readonly number[];\n readonly extras?: { readonly MSFT_screencoverage?: readonly number[] };\n readonly extensions?: {\n readonly KHR_lights_punctual?: {\n readonly light?: number;\n };\n readonly EXT_mesh_gpu_instancing?: {\n readonly attributes?: {\n readonly TRANSLATION?: number;\n readonly ROTATION?: number;\n readonly SCALE?: number;\n };\n };\n readonly MSFT_lod?: { readonly ids?: readonly number[] };\n };\n }>;\n readonly extensions?: {\n readonly KHR_lights_punctual?: {\n readonly lights?: ReadonlyArray<{\n readonly type?: string;\n readonly color?: readonly number[];\n readonly intensity?: number;\n readonly range?: number;\n readonly spot?: {\n readonly innerConeAngle?: number;\n readonly outerConeAngle?: number;\n };\n }>;\n };\n readonly MSFT_screencoverage?: { readonly scales?: readonly number[] };\n };\n readonly skins?: ReadonlyArray<{\n readonly name?: string;\n readonly joints: readonly number[];\n readonly inverseBindMatrices?: number;\n }>;\n readonly meshes?: readonly MeshJson[];\n readonly materials?: ReadonlyArray<GltfMaterialJson>;\n readonly textures?: ReadonlyArray<{\n readonly sampler?: number;\n readonly source?: number;\n readonly name?: string;\n }>;\n readonly images?: ReadonlyArray<{\n readonly uri?: string;\n readonly mimeType?: string;\n readonly bufferView?: number;\n readonly name?: string;\n }>;\n readonly samplers?: ReadonlyArray<{\n readonly magFilter?: number;\n readonly minFilter?: number;\n readonly wrapS?: number;\n readonly wrapT?: number;\n readonly name?: string;\n }>;\n readonly accessors?: readonly AccessorJson[];\n readonly bufferViews?: readonly BufferViewJson[];\n readonly buffers?: readonly BuffersJson[];\n readonly animations?: ReadonlyArray<{\n readonly name?: string;\n readonly channels: ReadonlyArray<{\n readonly sampler: number;\n readonly target: {\n readonly node?: number;\n readonly path: string;\n };\n }>;\n readonly samplers: ReadonlyArray<{\n readonly input: number;\n readonly output: number;\n readonly interpolation?: string;\n }>;\n }>;\n}\n\nexport type ExternalLoader = (uri: string) => Promise<ArrayBuffer>;\n\nasync function resolveBuffer(\n buf: BuffersJson,\n externalLoader: ExternalLoader,\n binChunk: Uint8Array | undefined,\n): Promise<Uint8Array> {\n if (buf.uri === undefined) {\n // GLB BIN chunk slot.\n if (binChunk === undefined) {\n throw new Error('parseGltf: buffer 0 has no uri and no GLB BIN chunk available');\n }\n return binChunk;\n }\n const dataPayload = dataUriBase64Payload(buf.uri);\n if (dataPayload !== undefined) {\n return decodeBase64(dataPayload);\n }\n const arrayBuffer = await externalLoader(buf.uri);\n return new Uint8Array(arrayBuffer);\n}\n\ninterface ParseGltfInternalsContext {\n readonly externalLoader: ExternalLoader;\n readonly binChunk?: Uint8Array;\n readonly filePath: string;\n readonly meshopt?: GltfBufferViewDecodeCapability;\n}\n\ntype GltfParseError = GltfError | ImportError;\n\nfunction invalidBufferDataUriError(\n filePath: string,\n bufferIndex: number,\n cause: Base64DecodeError,\n): ImportError {\n return new ImportError({\n code: 'source-validation-failed',\n expected: `glTF buffer ${bufferIndex} data URI to contain a valid base64 payload`,\n hint: IMPORT_ERROR_HINTS['source-validation-failed'],\n detail: {\n diagnostics: [\n {\n code: 'gltf-buffer-data-uri-invalid',\n severity: 'error',\n sourcePath: filePath,\n sourceRange: { start: 0, end: 0, line: 1, column: 1 },\n rule: 'gltf-buffer-data-uri-base64',\n expected: 'a valid base64 payload after ;base64,',\n actual: `buffer ${bufferIndex}: ${cause.message}`,\n hint: 'repair the buffer data URI or provide a valid external .bin sibling',\n },\n ],\n },\n });\n}\n\nexport interface GltfParseOptions {\n readonly meshopt?: GltfBufferViewDecodeCapability;\n}\n\nfunction parsePunctualLights(\n json: RootGltfJson,\n filePath: string,\n): Result<readonly GltfPunctualLightIr[], GltfError> {\n const source = json.extensions?.KHR_lights_punctual?.lights ?? [];\n const lights: GltfPunctualLightIr[] = [];\n for (const light of source) {\n const type = light?.type;\n if (type !== 'directional' && type !== 'point' && type !== 'spot') {\n return err(gltfErr('gltf-malformed-header', { filePath, byteOffset: 0 }));\n }\n const color = light.color ?? [1, 1, 1];\n if (\n color.length < 3 ||\n color\n .slice(0, 3)\n .some(\n (value) => typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > 1,\n )\n ) {\n return err(gltfErr('gltf-malformed-header', { filePath, byteOffset: 0 }));\n }\n const intensity = light.intensity ?? 1;\n if (typeof intensity !== 'number' || !Number.isFinite(intensity) || intensity < 0) {\n return err(gltfErr('gltf-malformed-header', { filePath, byteOffset: 0 }));\n }\n const range = light.range;\n if (\n range !== undefined &&\n (typeof range !== 'number' || !Number.isFinite(range) || range < 0)\n ) {\n return err(gltfErr('gltf-malformed-header', { filePath, byteOffset: 0 }));\n }\n let spot: GltfPunctualLightIr['spot'];\n if (type === 'spot') {\n const innerConeAngle = light.spot?.innerConeAngle ?? 0;\n const outerConeAngle = light.spot?.outerConeAngle ?? Math.PI / 4;\n if (\n !Number.isFinite(innerConeAngle) ||\n !Number.isFinite(outerConeAngle) ||\n innerConeAngle < 0 ||\n innerConeAngle >= outerConeAngle ||\n outerConeAngle > Math.PI / 2\n ) {\n return err(gltfErr('gltf-malformed-header', { filePath, byteOffset: 0 }));\n }\n spot = { innerConeAngle, outerConeAngle };\n }\n lights.push({\n type,\n color: [color[0] ?? 1, color[1] ?? 1, color[2] ?? 1],\n intensity,\n ...(range === undefined || range === 0 ? {} : { range }),\n ...(spot === undefined ? {} : { spot }),\n });\n }\n return ok(lights);\n}\n\nasync function parseGltfWithBin(\n json: RootGltfJson,\n ctx: ParseGltfInternalsContext,\n): Promise<Result<GltfDoc, GltfParseError>> {\n const headerResult = parseGltfHeader(json, ctx.filePath);\n if (!headerResult.ok) return err(headerResult.error);\n\n const extResult = checkExtensions(json);\n if (!extResult.ok) return err(extResult.error);\n const unsupportedExtensions = extResult.value.unsupportedUsed;\n const lodResult = parseGltfLodExtension(json);\n if (!lodResult.ok) return err(lodResult.error);\n const lightsResult = parsePunctualLights(json, ctx.filePath);\n if (!lightsResult.ok) return err(lightsResult.error);\n\n const meshesJson = json.meshes ?? [];\n\n // Resolve buffers (data: URI / external / GLB BIN chunk).\n const buffersJson = json.buffers ?? [];\n const buffers: Uint8Array[] = [];\n for (let i = 0; i < buffersJson.length; i++) {\n const bufJson = buffersJson[i];\n if (bufJson === undefined) continue;\n try {\n const bytes = await resolveBuffer(bufJson, ctx.externalLoader, ctx.binChunk);\n buffers.push(bytes);\n } catch (e) {\n if (e instanceof Base64DecodeError) {\n return err(invalidBufferDataUriError(ctx.filePath, i, e));\n }\n return err(\n gltfErr('gltf-malformed-header', {\n filePath: ctx.filePath,\n byteOffset: 0,\n }),\n );\n }\n }\n\n const accessors = json.accessors ?? [];\n const rawBufferViews = json.bufferViews ?? [];\n const projected = await projectMeshoptBufferViews(\n rawBufferViews as readonly MeshoptBufferViewJson[],\n buffers,\n json.extensionsRequired ?? [],\n ctx.meshopt,\n );\n if (!projected.ok) return err(projected.error);\n const bufferViews = projected.value.bufferViews;\n buffers.splice(0, buffers.length, ...projected.value.buffers);\n\n const meshes: GltfMeshIr[] = [];\n // Preserve original mesh -> primitive counts for the flattened IR.\n const meshPrimitiveCount = new Map<number, number>();\n for (let meshIndex = 0; meshIndex < meshesJson.length; meshIndex++) {\n const meshJson = meshesJson[meshIndex];\n if (meshJson === undefined) continue;\n meshPrimitiveCount.set(meshIndex, meshJson.primitives.length);\n for (const prim of meshJson.primitives) {\n if (prim === undefined) continue;\n const positionAccessorIndex = prim.attributes?.POSITION;\n if (positionAccessorIndex === undefined) {\n return err(\n gltfErr('gltf-accessor-type-mismatch', {\n accessorIndex: -1,\n reason: 'unknownComponentType',\n }),\n );\n }\n const positionAccessor = accessors[positionAccessorIndex];\n const positionBufferView = bufferViews[positionAccessor?.bufferView ?? -1];\n if (positionAccessor === undefined || positionBufferView === undefined) {\n return err(\n gltfErr('gltf-buffer-out-of-bounds', {\n accessor: positionAccessorIndex,\n byteOffset: 0,\n byteLength: 0,\n bufferIndex: positionBufferView?.buffer ?? 0,\n }),\n );\n }\n const positionBuffer = buffers[positionBufferView.buffer];\n if (positionBuffer === undefined) {\n return err(\n gltfErr('gltf-buffer-out-of-bounds', {\n accessor: positionAccessorIndex,\n byteOffset: positionBufferView.byteOffset ?? 0,\n byteLength: positionBufferView.byteLength,\n bufferIndex: positionBufferView.buffer,\n }),\n );\n }\n const positionDecoded = decodeAccessor({\n accessorIndex: positionAccessorIndex,\n accessor: positionAccessor,\n bufferView: positionBufferView,\n buffer: positionBuffer,\n role: 'attribute',\n });\n if (!positionDecoded.ok) return err(positionDecoded.error);\n if (positionDecoded.value.kind !== 'f32') {\n return err(\n gltfErr('gltf-accessor-type-mismatch', {\n accessorIndex: positionAccessorIndex,\n reason: 'unknownComponentType',\n }),\n );\n }\n const positionsDecoded = positionDecoded.value.data;\n // Re-allocate over a fresh ArrayBuffer so the GltfMeshIr.positions type\n // (`Float32Array<ArrayBuffer>`) holds without ArrayBufferLike leakage.\n const positions = new Float32Array(positionsDecoded.length);\n positions.set(positionsDecoded);\n\n // Decode optional NORMAL, TEXCOORD_0, and TANGENT attributes.\n const attrs = prim.attributes ?? {};\n\n let colors0: Float32Array | undefined;\n const colorIdx = attrs.COLOR_0;\n if (colorIdx !== undefined) {\n const colorAccessor = accessors[colorIdx];\n const colorBufferView = bufferViews[colorAccessor?.bufferView ?? -1];\n if (colorAccessor === undefined || colorBufferView === undefined) {\n return err(\n gltfErr('gltf-color-accessor-malformed', {\n semantic: 'COLOR_0',\n accessorIndex: colorIdx,\n reason: 'reference',\n }),\n );\n }\n const colorBuffer = buffers[colorBufferView.buffer];\n if (colorBuffer === undefined) {\n return err(\n gltfErr('gltf-color-accessor-malformed', {\n semantic: 'COLOR_0',\n accessorIndex: colorIdx,\n reason: 'reference',\n }),\n );\n }\n const decoded = decodeColorAccessor({\n accessorIndex: colorIdx,\n accessor: colorAccessor,\n bufferView: colorBufferView,\n buffer: colorBuffer,\n bufferIndex: colorBufferView.buffer,\n semantic: 'COLOR_0',\n });\n if (!decoded.ok) return err(decoded.error);\n if (decoded.value.length !== (positions.length / 3) * 4) {\n return err(\n gltfErr('gltf-color-accessor-malformed', {\n semantic: 'COLOR_0',\n accessorIndex: colorIdx,\n reason: 'count',\n }),\n );\n }\n colors0 = decoded.value;\n }\n\n let normals: Float32Array | undefined;\n const normalIdx = attrs.NORMAL;\n if (normalIdx !== undefined) {\n const acc = accessors[normalIdx];\n if (acc !== undefined) {\n const decoded = decodeAttributeAccessor(normalIdx, acc, bufferViews, buffers);\n if (decoded.ok) {\n const src = decoded.value;\n const owned = new Float32Array(src.length);\n owned.set(src);\n normals = owned;\n }\n }\n }\n\n let texcoord0: Float32Array | undefined;\n const texIdx = attrs.TEXCOORD_0;\n if (texIdx !== undefined) {\n const acc = accessors[texIdx];\n if (acc !== undefined) {\n const decoded = decodeAttributeAccessor(texIdx, acc, bufferViews, buffers);\n if (decoded.ok) {\n const src = decoded.value;\n const owned = new Float32Array(src.length);\n owned.set(src);\n texcoord0 = owned;\n }\n }\n }\n\n // feat-20260629-multi-uv-set-support m1-w2: decode TEXCOORD_1..7\n // using the same decodeAttributeAccessor→Float32Array pattern.\n // Missing accessor → field stays undefined (no error, mirrors TEXCOORD_0).\n // componentType non-FLOAT → decodeAttributeAccessor returns error already.\n let texcoord1: Float32Array | undefined;\n let texcoord2: Float32Array | undefined;\n let texcoord3: Float32Array | undefined;\n let texcoord4: Float32Array | undefined;\n let texcoord5: Float32Array | undefined;\n let texcoord6: Float32Array | undefined;\n let texcoord7: Float32Array | undefined;\n for (let k = 1; k <= 7; k++) {\n const tcIdx = attrs[`TEXCOORD_${k}`];\n if (tcIdx === undefined) continue;\n const acc = accessors[tcIdx];\n if (acc !== undefined) {\n const decoded = decodeAttributeAccessor(tcIdx, acc, bufferViews, buffers);\n if (decoded.ok) {\n const src = decoded.value;\n const owned = new Float32Array(src.length);\n owned.set(src);\n if (k === 1) texcoord1 = owned;\n else if (k === 2) texcoord2 = owned;\n else if (k === 3) texcoord3 = owned;\n else if (k === 4) texcoord4 = owned;\n else if (k === 5) texcoord5 = owned;\n else if (k === 6) texcoord6 = owned;\n else texcoord7 = owned;\n }\n }\n }\n\n let tangents: Float32Array | undefined;\n const tanIdx = attrs.TANGENT;\n if (tanIdx !== undefined) {\n const acc = accessors[tanIdx];\n if (acc !== undefined) {\n const decoded = decodeAttributeAccessor(tanIdx, acc, bufferViews, buffers);\n if (decoded.ok) {\n const src = decoded.value;\n const owned = new Float32Array(src.length);\n owned.set(src);\n tangents = owned;\n }\n }\n }\n\n const rawTargets = prim.targets ?? [];\n for (const target of rawTargets) {\n const colorTarget = target.COLOR_0;\n if (colorTarget !== undefined) {\n return err(\n gltfErr('gltf-color-accessor-unsupported', {\n semantic: 'COLOR_0',\n accessorIndex: colorTarget,\n reason: 'morph',\n }),\n );\n }\n }\n const morphAttributeCount = rawTargets.reduce(\n (count, target) =>\n count +\n (target.POSITION === undefined ? 0 : 1) +\n (target.NORMAL === undefined ? 0 : 1) +\n (target.TANGENT === undefined ? 0 : 1),\n 0,\n );\n const morphError = (\n reason:\n | 'target-count-exceeded'\n | 'attribute-count-exceeded'\n | 'attribute-length-mismatch'\n | 'weights-length-mismatch'\n | 'sparse-or-unsupported-accessor',\n ) =>\n err(\n gltfErr('gltf-morph-invalid', {\n meshIndex,\n primitiveIndex: meshJson.primitives.indexOf(prim),\n reason,\n targetCount: rawTargets.length,\n attributeCount: morphAttributeCount,\n vertexCount: positions.length / 3,\n }),\n );\n if (rawTargets.length > 8) return morphError('target-count-exceeded');\n if (morphAttributeCount > 8) return morphError('attribute-count-exceeded');\n\n const morphTargets: {\n readonly position?: Float32Array;\n readonly normal?: Float32Array;\n readonly tangent?: Float32Array;\n }[] = [];\n for (const target of rawTargets) {\n const output: {\n position?: Float32Array;\n normal?: Float32Array;\n tangent?: Float32Array;\n } = {};\n for (const [key, accessorIndex] of Object.entries(target)) {\n if (key !== 'POSITION' && key !== 'NORMAL' && key !== 'TANGENT') continue;\n const targetAccessor = accessors[accessorIndex];\n if (targetAccessor === undefined) return morphError('attribute-length-mismatch');\n const decoded = decodeAttributeAccessor(\n accessorIndex,\n targetAccessor,\n bufferViews,\n buffers,\n );\n if (!decoded.ok) {\n return morphError(\n decoded.error.code === 'gltf-accessor-type-mismatch'\n ? 'sparse-or-unsupported-accessor'\n : 'attribute-length-mismatch',\n );\n }\n const expected = (positions.length / 3) * (key === 'TANGENT' ? 4 : 3);\n if (decoded.value.length !== expected) return morphError('attribute-length-mismatch');\n const owned = new Float32Array(decoded.value.length);\n owned.set(decoded.value);\n if (key === 'POSITION') output.position = owned;\n else if (key === 'NORMAL') output.normal = owned;\n else output.tangent = owned;\n }\n morphTargets.push(output);\n }\n const meshWeights = meshJson.weights;\n if (meshWeights !== undefined && meshWeights.length !== rawTargets.length) {\n return morphError('weights-length-mismatch');\n }\n\n // JOINTS_0 / WEIGHTS_0 (feat-20260611 M1 w1): paired skinning attributes.\n // glTF 2.0 spec section 3.7.2.1 requires the pair to appear together for\n // any skinned primitive; lone presence -> gltf-skin-attr-asymmetric.\n // JOINTS_0 componentType: UBYTE(5121) widen->U16 via decodeAccessor\n // role='joints' (D-3 width-convert at parse), or USHORT(5123) standard\n // U16 path. WEIGHTS_0 componentType: FLOAT(5126) standard F32 path.\n const jointsIdx = attrs.JOINTS_0;\n const weightsIdx = attrs.WEIGHTS_0;\n const hasJoints = jointsIdx !== undefined;\n const hasWeights = weightsIdx !== undefined;\n if (hasJoints !== hasWeights) {\n const primitiveIndex = meshJson.primitives.indexOf(prim);\n return err(\n gltfErr('gltf-skin-attr-asymmetric', {\n meshIndex,\n primitiveIndex,\n hasJoints,\n hasWeights,\n }),\n );\n }\n let joints0: Uint16Array | undefined;\n let weights0: Float32Array | undefined;\n if (hasJoints && hasWeights) {\n const jointsAccessor = accessors[jointsIdx as number];\n const jointsBufferView = bufferViews[jointsAccessor?.bufferView ?? -1];\n if (jointsAccessor === undefined || jointsBufferView === undefined) {\n return err(unknownAccessor(jointsIdx as number));\n }\n const jointsBuffer = buffers[jointsBufferView.buffer];\n if (jointsBuffer === undefined) return err(unknownAccessor(jointsIdx as number));\n const jointsDecoded = decodeAccessor({\n accessorIndex: jointsIdx as number,\n accessor: jointsAccessor,\n bufferView: jointsBufferView,\n buffer: jointsBuffer,\n role: 'joints',\n });\n if (!jointsDecoded.ok) return err(jointsDecoded.error);\n if (jointsDecoded.value.kind !== 'u16') {\n return err(\n gltfErr('gltf-accessor-type-mismatch', {\n accessorIndex: jointsIdx as number,\n reason: 'unknownComponentType',\n }),\n );\n }\n const src = jointsDecoded.value.data;\n const owned = new Uint16Array(src.length);\n owned.set(src);\n joints0 = owned;\n\n const weightsAccessor = accessors[weightsIdx as number];\n const weightsBufferView = bufferViews[weightsAccessor?.bufferView ?? -1];\n if (weightsAccessor === undefined || weightsBufferView === undefined) {\n return err(unknownAccessor(weightsIdx as number));\n }\n const weightsBuffer = buffers[weightsBufferView.buffer];\n if (weightsBuffer === undefined) return err(unknownAccessor(weightsIdx as number));\n const weightsDecoded = decodeAccessor({\n accessorIndex: weightsIdx as number,\n accessor: weightsAccessor,\n bufferView: weightsBufferView,\n buffer: weightsBuffer,\n role: 'attribute',\n });\n if (!weightsDecoded.ok) return err(weightsDecoded.error);\n if (weightsDecoded.value.kind !== 'f32') {\n return err(\n gltfErr('gltf-accessor-type-mismatch', {\n accessorIndex: weightsIdx as number,\n reason: 'unknownComponentType',\n }),\n );\n }\n const wsrc = weightsDecoded.value.data;\n const wowned = new Float32Array(wsrc.length);\n wowned.set(wsrc);\n weights0 = wowned;\n }\n\n // bug-20260612 hello-skin visual layered gate: glTF spec marks\n // primitive.indices optional; undefined means non-indexed geometry.\n // Leave indices undefined here; bridge.ts handles the non-indexed\n // path by routing MeshAsset.indices to undefined.\n let indices: Uint16Array | Uint32Array | undefined;\n if (prim.indices !== undefined) {\n const indexAccessor = accessors[prim.indices];\n const indexBufferView = bufferViews[indexAccessor?.bufferView ?? -1];\n if (indexAccessor === undefined || indexBufferView === undefined) {\n return err(\n gltfErr('gltf-buffer-out-of-bounds', {\n accessor: prim.indices,\n byteOffset: 0,\n byteLength: 0,\n bufferIndex: indexBufferView?.buffer ?? 0,\n }),\n );\n }\n const indexBuffer = buffers[indexBufferView.buffer];\n if (indexBuffer === undefined) {\n return err(\n gltfErr('gltf-buffer-out-of-bounds', {\n accessor: prim.indices,\n byteOffset: indexBufferView.byteOffset ?? 0,\n byteLength: indexBufferView.byteLength,\n bufferIndex: indexBufferView.buffer,\n }),\n );\n }\n const indexDecoded = decodeAccessor({\n accessorIndex: prim.indices,\n accessor: indexAccessor,\n bufferView: indexBufferView,\n buffer: indexBuffer,\n role: 'indices',\n });\n if (!indexDecoded.ok) return err(indexDecoded.error);\n if (indexDecoded.value.kind === 'u16') {\n // Re-allocate over a fresh ArrayBuffer so the GltfMeshIr.indices type\n // (`Uint16Array<ArrayBuffer>`) holds without the underlying\n // SharedArrayBuffer-friendly ArrayBufferLike slot leaking through.\n const src = indexDecoded.value.data;\n const owned = new Uint16Array(src.length);\n owned.set(src);\n indices = owned;\n } else if (indexDecoded.value.kind === 'u32') {\n const src = indexDecoded.value.data;\n const owned = new Uint32Array(src.length);\n owned.set(src);\n indices = owned;\n } else {\n return err(\n gltfErr('gltf-accessor-type-mismatch', {\n accessorIndex: prim.indices,\n reason: 'unknownComponentType',\n }),\n );\n }\n }\n\n const meshIr: GltfMeshIr = {\n ...(meshJson.name === undefined ? {} : { name: meshJson.name }),\n positions,\n ...(normals === undefined ? {} : { normals }),\n ...(texcoord0 === undefined ? {} : { texcoord0 }),\n ...(texcoord1 === undefined ? {} : { texcoord1 }),\n ...(texcoord2 === undefined ? {} : { texcoord2 }),\n ...(texcoord3 === undefined ? {} : { texcoord3 }),\n ...(texcoord4 === undefined ? {} : { texcoord4 }),\n ...(texcoord5 === undefined ? {} : { texcoord5 }),\n ...(texcoord6 === undefined ? {} : { texcoord6 }),\n ...(texcoord7 === undefined ? {} : { texcoord7 }),\n ...(tangents === undefined ? {} : { tangents }),\n ...(colors0 === undefined ? {} : { colors0 }),\n ...(joints0 === undefined ? {} : { joints0 }),\n ...(weights0 === undefined ? {} : { weights0 }),\n ...(morphTargets.length === 0 ? {} : { morphTargets }),\n ...(meshWeights === undefined ? {} : { morphWeights: new Float32Array(meshWeights) }),\n ...(indices === undefined ? {} : { indices }),\n materialIndex: prim.material ?? null,\n meshIndex,\n };\n meshes.push(meshIr);\n }\n }\n\n // Textures, images, samplers (Tier-C: parse top-level arrays).\n const texturesJson = json.textures ?? [];\n const textures: GltfTextureIr[] = [];\n for (const texJson of texturesJson) {\n const texIr: GltfTextureIr = {\n source: texJson.source ?? -1,\n ...(texJson.sampler === undefined ? {} : { sampler: texJson.sampler }),\n ...(texJson.name === undefined ? {} : { name: texJson.name }),\n };\n textures.push(texIr);\n }\n\n const imagesJson = json.images ?? [];\n const images: GltfImageIr[] = [];\n for (const imgJson of imagesJson) {\n const mimeType = imgJson.mimeType;\n if (mimeType !== undefined && mimeType !== 'image/jpeg' && mimeType !== 'image/png') {\n return err(gltfErr('gltf-image-mime-unsupported', { mimeType }));\n }\n const imgIr: GltfImageIr = {\n ...(imgJson.uri === undefined ? {} : { uri: imgJson.uri }),\n ...(imgJson.mimeType === undefined ? {} : { mimeType: imgJson.mimeType }),\n ...(imgJson.bufferView === undefined ? {} : { bufferView: imgJson.bufferView }),\n ...(imgJson.name === undefined ? {} : { name: imgJson.name }),\n };\n images.push(imgIr);\n }\n\n // Load external image URIs via externalLoader.\n for (const img of images) {\n if (img.uri !== undefined) {\n if (dataUriBase64Payload(img.uri) !== undefined) continue; // data: URI, skip external load\n try {\n await ctx.externalLoader(img.uri);\n } catch (_e) {\n return err(gltfErr('gltf-texture-load-failed', { uri: img.uri }));\n }\n }\n }\n\n const samplersJson = json.samplers ?? [];\n const samplers: GltfSamplerIr[] = [];\n for (const sampJson of samplersJson) {\n samplers.push({\n ...(sampJson.magFilter === undefined ? {} : { magFilter: sampJson.magFilter }),\n ...(sampJson.minFilter === undefined ? {} : { minFilter: sampJson.minFilter }),\n wrapS: sampJson.wrapS ?? 10497, // REPEAT (glTF default)\n wrapT: sampJson.wrapT ?? 10497,\n ...(sampJson.name === undefined ? {} : { name: sampJson.name }),\n });\n }\n\n // Materials are normalized by the material parser owner before entering the IR.\n const materials: GltfMaterialIr[] = [];\n for (const material of json.materials ?? []) {\n const parsedMaterial = parseMaterial(material, textures);\n if (!parsedMaterial.ok) return err(parsedMaterial.error);\n materials.push(parsedMaterial.value);\n }\n\n // Nodes + diagnostics.\n const diagnostics = {\n nodeNames: [] as string[],\n unsupportedExtensions: [...unsupportedExtensions] as string[],\n matrixTrsCoexistNodes: [] as number[],\n };\n const nodes: GltfNodeIr[] = [];\n const nodesJson = json.nodes ?? [];\n for (let nodeIndex = 0; nodeIndex < nodesJson.length; nodeIndex++) {\n const nodeJson = nodesJson[nodeIndex];\n if (nodeJson === undefined) continue;\n const transform = decomposeNodeTransform(nodeJson, nodeIndex, diagnostics);\n if (nodeJson.name !== undefined) diagnostics.nodeNames.push(nodeJson.name);\n const instancingExt = nodeJson.extensions?.EXT_mesh_gpu_instancing;\n let instancing: NodeInstancingIr | undefined;\n if (instancingExt !== undefined) {\n const instancingResult = decodeNodeInstancing(\n nodeIndex,\n instancingExt.attributes ?? {},\n accessors,\n bufferViews,\n buffers,\n );\n if (!instancingResult.ok) return err(instancingResult.error);\n instancing = instancingResult.value;\n }\n const nodeMorphWeights =\n nodeJson.weights === undefined ? undefined : new Float32Array(nodeJson.weights);\n nodes.push({\n ...(nodeJson.name === undefined ? {} : { name: nodeJson.name }),\n transform,\n meshIndex: nodeJson.mesh ?? null,\n skinIndex: nodeJson.skin ?? null,\n children: nodeJson.children ?? [],\n camera: nodeJson.camera ?? null,\n lightIndex: nodeJson.extensions?.KHR_lights_punctual?.light ?? null,\n ...(instancing === undefined ? {} : { instancing }),\n ...(nodeMorphWeights === undefined ? {} : { morphWeights: nodeMorphWeights }),\n });\n }\n\n // Scenes.\n const scenesJson = json.scenes ?? [];\n const scenes: GltfSceneIr[] = scenesJson.map((s) => ({\n ...(s.name === undefined ? {} : { name: s.name }),\n nodes: s.nodes ?? [],\n }));\n const defaultSceneIndex = json.scene ?? 0;\n\n // Skins (feat-20260523-skin-skeleton-animation M0).\n const skinsJson = json.skins;\n const skinResult = parseSkin(skinsJson, nodesJson, accessors, bufferViews, buffers);\n if (!skinResult.ok) return err(skinResult.error);\n const skeletons = skinResult.value;\n\n // Animations (feat-20260523-skin-skeleton-animation M0).\n const animationsJson = json.animations;\n const animResult = parseAnimation(animationsJson, nodesJson, accessors, bufferViews, buffers);\n if (!animResult.ok) return err(animResult.error);\n const animationClips = animResult.value;\n\n return ok({\n meshes,\n materials,\n nodes,\n scenes,\n skeletons,\n animationClips,\n textures: textures.length > 0 ? textures : undefined,\n images: images.length > 0 ? images : undefined,\n samplers: samplers.length > 0 ? samplers : undefined,\n defaultSceneIndex,\n diagnostics: {\n nodeNames: diagnostics.nodeNames,\n unsupportedExtensions: diagnostics.unsupportedExtensions,\n matrixTrsCoexistNodes: diagnostics.matrixTrsCoexistNodes,\n },\n meshPrimitiveCount,\n lights: lightsResult.value,\n ...(lodResult.value.lodNodeIds.length === 0 ? {} : { lod: lodResult.value }),\n });\n}\n\n/**\n * Parse a glTF 2.0 JSON document. The `externalLoader` resolves\n * `buffers[].uri` references that are NOT data: URIs (callers in Node\n * land typically wrap fs.readFile; browser callers wrap fetch).\n *\n * Pure function modulo `externalLoader` (caller-provided I/O is the\n * only side effect). No global state, no fs / network direct call.\n */\nexport async function parseGltfForImporter(\n json: unknown,\n externalLoader: ExternalLoader,\n filePath: string,\n options: GltfParseOptions = {},\n): Promise<Result<GltfDoc, GltfParseError>> {\n if (json === null || typeof json !== 'object') {\n return err(\n gltfErr('gltf-malformed-header', {\n filePath,\n byteOffset: 0,\n }),\n );\n }\n return parseGltfWithBin(json as RootGltfJson, {\n externalLoader,\n filePath,\n ...(options.meshopt === undefined ? {} : { meshopt: options.meshopt }),\n });\n}\n\nfunction legacyParseResult(\n result: Result<GltfDoc, GltfParseError>,\n filePath: string,\n byteOffset: number,\n): Result<GltfDoc, GltfError> {\n if (result.ok) return ok(result.value);\n if (result.error instanceof ImportError) {\n return err(gltfErr('gltf-malformed-header', { filePath, byteOffset }));\n }\n return err(result.error);\n}\n\nexport async function parseGltf(\n json: unknown,\n externalLoader: ExternalLoader,\n filePath: string,\n options: GltfParseOptions = {},\n): Promise<Result<GltfDoc, GltfError>> {\n const result = await parseGltfForImporter(json, externalLoader, filePath, options);\n return legacyParseResult(result, filePath, 0);\n}\n\n/**\n * Parse a GLB 2.0 binary container: split into JSON + BIN chunks via\n * `parseGlbChunks`, then run the JSON document through `parseGltf` with\n * the BIN chunk wired in as buffer-0 backing storage.\n */\nexport async function parseGlbForImporter(\n buffer: ArrayBuffer,\n filePath: string,\n options: GltfParseOptions = {},\n): Promise<Result<GltfDoc, GltfParseError>> {\n const chunksResult = parseGlbChunks(buffer, filePath);\n if (!chunksResult.ok) return err(chunksResult.error);\n let json: unknown;\n try {\n json = JSON.parse(new TextDecoder().decode(chunksResult.value.jsonChunk));\n } catch (_e) {\n return err(\n gltfErr('gltf-malformed-header', {\n filePath,\n byteOffset: 12,\n }),\n );\n }\n if (json === null || typeof json !== 'object') {\n return err(\n gltfErr('gltf-malformed-header', {\n filePath,\n byteOffset: 12,\n }),\n );\n }\n const externalLoader: ExternalLoader = async (uri: string) => {\n throw new Error(`parseGlb: GLB containers must not reference external URIs (got ${uri})`);\n };\n return parseGltfWithBin(json as RootGltfJson, {\n externalLoader,\n ...(chunksResult.value.binChunk === undefined ? {} : { binChunk: chunksResult.value.binChunk }),\n filePath,\n ...(options.meshopt === undefined ? {} : { meshopt: options.meshopt }),\n });\n}\n\nexport async function parseGlb(\n buffer: ArrayBuffer,\n filePath: string,\n options: GltfParseOptions = {},\n): Promise<Result<GltfDoc, GltfError>> {\n const result = await parseGlbForImporter(buffer, filePath, options);\n return legacyParseResult(result, filePath, 12);\n}\n\nexport interface GltfAssetPack {\n readonly meta: GltfMetaJson;\n readonly subAssets: readonly GltfSubAssetEntry[];\n}\n\nexport type GltfAssetPackResult = Result<GltfAssetPack, GltfSourceKeyError | GltfError>;\n\n/**\n * Project a parsed `GltfDoc` into the disk-shape `<source>.meta.json` plus\n * the freshly minted `subAssets[]` list (UUIDv7 + reimport-reuse-meta\n * two-stage match per plan-strategy section 2.4). Source-key conflicts are\n * returned before GUID minting or serialization.\n *\n * `existingMeta` is the previously-written `<source>.meta.json` parsed back\n * into memory (callers typically read + JSON.parse it before invoking).\n * `undefined` triggers first-pass full-fresh GUID minting.\n *\n * Sub-asset ordering: meshes first, then materials, then scenes - the\n * order is stable across reimports so AC-13 byte-identical holds when\n * source content does not change. Stable semantic sourceKey values are\n * assigned by the producer reuse boundary; sourceIndex remains a locator.\n */\nexport function toAssetPack(\n doc: GltfDoc,\n existingMeta: GltfMetaJson | undefined,\n source: string,\n): GltfAssetPackResult {\n const items: GltfDocItem[] = [];\n // Mesh sub-assets are keyed on the *original glTF mesh-index*, not on the\n // flat GltfMeshIr index. parseGltf flattens N glTF meshes with M_i primitives\n // into sum(M_i) GltfMeshIr rows (each carries its owning meshIndex). The\n // gltfImporter merges all primitives sharing a meshIndex into one MeshAsset\n // with M_i Submesh entries (one per primitive), so the meta sidecar must\n // emit exactly one `kind: 'mesh'` row per unique meshIndex — not one per\n // flat GltfMeshIr row, which would over-emit M_i sub-assets per glTF mesh and\n // desynchronise from runtime MeshRenderer.materials[].length.\n const seenMeshIndices = new Set<number>();\n for (const m of doc.meshes) {\n if (m === undefined) continue;\n if (seenMeshIndices.has(m.meshIndex)) continue;\n seenMeshIndices.add(m.meshIndex);\n items.push({\n kind: 'mesh',\n sourceIndex: m.meshIndex,\n ...(m.name === undefined ? {} : { name: m.name }),\n });\n }\n for (let i = 0; i < doc.materials.length; i++) {\n const m = doc.materials[i];\n if (m === undefined) continue;\n items.push({\n kind: 'material',\n sourceIndex: i,\n ...(m.name === undefined ? {} : { name: m.name }),\n });\n }\n for (let i = 0; i < doc.scenes.length; i++) {\n const s = doc.scenes[i];\n if (s === undefined) continue;\n items.push({\n kind: 'scene',\n sourceIndex: i,\n ...(s.name === undefined ? {} : { name: s.name }),\n });\n }\n // Texture sub-assets — one entry per `images[]` row (feat-20260608 M3 D-3,\n // requirements G-2 / AC-13). Orphan images (declared but unreferenced by\n // any `textures[]` row) still produce a sub-asset; the importer assigns\n // them colorSpace 'linear' (no colour-encoded purpose inferable). Without\n // this loop the meta carries no `kind: 'texture'` row, AssetRegistry\n // never imports the bytes, and the runtime renders a white box (G-2).\n const images = doc.images ?? [];\n for (let i = 0; i < images.length; i++) {\n const img = images[i];\n if (img === undefined) continue;\n items.push({\n kind: 'texture',\n sourceIndex: i,\n ...(img.name === undefined ? {} : { name: img.name }),\n });\n }\n const samplers = doc.samplers ?? [];\n for (let i = 0; i < samplers.length; i++) {\n const sampler = samplers[i];\n if (sampler === undefined) continue;\n items.push({\n kind: 'sampler',\n sourceIndex: i,\n ...(sampler.name === undefined ? {} : { name: sampler.name }),\n });\n }\n // Skeletons (feat-20260523-skin-skeleton-animation M0).\n for (let i = 0; i < doc.skeletons.length; i++) {\n items.push({ kind: 'skeleton', sourceIndex: i });\n }\n // Skin bindings (feat-20260523-skin-skeleton-animation M0).\n // Emit one skin sub-asset per GltfSkeletonRecord (1:1 mapping).\n for (let i = 0; i < doc.skeletons.length; i++) {\n items.push({ kind: 'skin', sourceIndex: i });\n }\n // Animation clips (feat-20260523-skin-skeleton-animation M0).\n for (let i = 0; i < doc.animationClips.length; i++) {\n const clip = doc.animationClips[i];\n if (clip === undefined) continue;\n items.push({\n kind: 'animation-clip',\n sourceIndex: i,\n ...(clip.name === undefined ? {} : { name: clip.name }),\n });\n }\n\n const reuse = reimportReuseMeta(items, existingMeta);\n if (!reuse.ok) return reuse;\n const subAssetByKindIndex = new Map(\n reuse.value.subAssets.map((entry) => [`${entry.kind}:${entry.sourceIndex}`, entry]),\n );\n const sourceOverrides: Record<string, Readonly<Record<string, unknown>>> = {\n ...(existingMeta?.sourceOverrides ?? {}),\n };\n const lodGroups =\n doc.lod === undefined ? [] : doc.lod.groups.length > 0 ? doc.lod.groups : [doc.lod];\n for (const lodGroup of lodGroups) {\n if (lodGroup.lodNodeIds.length === 0) continue;\n const rootMeshIndex = doc.nodes[lodGroup.rootNode]?.meshIndex;\n const referencedMeshIndices = [\n rootMeshIndex,\n ...lodGroup.lodNodeIds.map((nodeIndex) => doc.nodes[nodeIndex]?.meshIndex),\n ];\n if (\n referencedMeshIndices.some(\n (meshIndex) =>\n !Number.isInteger(meshIndex) ||\n meshIndex === null ||\n meshIndex === undefined ||\n !seenMeshIndices.has(meshIndex as number),\n )\n ) {\n return err(\n gltfErr('gltf-lod-invalid', {\n rootNode: lodGroup.rootNode,\n ids: lodGroup.lodNodeIds,\n reason: 'missing-node',\n }),\n );\n }\n const rootOutput =\n rootMeshIndex === undefined || rootMeshIndex === null\n ? undefined\n : subAssetByKindIndex.get(`mesh:${rootMeshIndex}`);\n const levels = lodGroup.lodNodeIds.map((nodeIndex, index) => {\n const meshIndex = doc.nodes[nodeIndex]?.meshIndex;\n const output =\n meshIndex === undefined || meshIndex === null\n ? undefined\n : subAssetByKindIndex.get(`mesh:${meshIndex}`);\n return {\n sourceKey: output?.sourceKey ?? `mesh:${meshIndex ?? nodeIndex}`,\n meshGuid: output?.guid ?? '',\n ...(lodGroup.screenCoverages[index] === undefined\n ? {}\n : { screenCoverage: lodGroup.screenCoverages[index] }),\n };\n });\n if (rootOutput?.sourceKey !== undefined && levels.every((level) => level.meshGuid !== '')) {\n const previousLodMeta = (() => {\n const raw = existingMeta?.sourceOverrides?.[rootOutput.sourceKey]?.lods;\n if (!Array.isArray(raw)) return undefined;\n return raw.flatMap((entry) => {\n if (entry === null || typeof entry !== 'object') return [];\n const value = entry as Record<string, unknown>;\n return typeof value.sourceKey === 'string' && typeof value.meshGuid === 'string'\n ? [\n {\n sourceKey: value.sourceKey,\n guid: value.meshGuid,\n ...(typeof value.screenCoverage === 'number'\n ? { screenCoverage: value.screenCoverage }\n : {}),\n },\n ]\n : [];\n });\n })();\n const projected = projectGltfLodMeta({\n rootSourceKey: rootOutput.sourceKey,\n levels: levels.map((level) => ({\n sourceKey: level.sourceKey,\n guid: level.meshGuid,\n ...(level.screenCoverage === undefined ? {} : { screenCoverage: level.screenCoverage }),\n })),\n ...(previousLodMeta === undefined ? {} : { previous: previousLodMeta }),\n });\n if (!projected.ok)\n return err(\n gltfErr('gltf-lod-invalid', {\n rootNode: lodGroup.rootNode,\n ids: lodGroup.lodNodeIds,\n reason: 'coverage',\n }),\n );\n sourceOverrides[rootOutput.sourceKey] = {\n ...(sourceOverrides[rootOutput.sourceKey] ?? {}),\n lods: projected.value.lods,\n };\n }\n }\n for (const meshIndex of seenMeshIndices) {\n const meshOutput = subAssetByKindIndex.get(`mesh:${meshIndex}`);\n if (meshOutput?.sourceKey === undefined) continue;\n const materialSlots: MeshMaterialSlotTopologyEntry[] = [];\n const slotByMaterial = new Map<number | null, number>();\n const usedNames = new Set<string>();\n const uniqueName = (raw: string): string => {\n const base = raw.trim() || 'Material';\n let candidate = base;\n let suffix = 2;\n while (usedNames.has(candidate)) candidate = `${base}_${suffix++}`;\n usedNames.add(candidate);\n return candidate;\n };\n for (const primitive of doc.meshes.filter((mesh) => mesh.meshIndex === meshIndex)) {\n const materialIndex = primitive.materialIndex;\n if (slotByMaterial.has(materialIndex)) continue;\n const materialOutput =\n materialIndex === null ? undefined : subAssetByKindIndex.get(`material:${materialIndex}`);\n slotByMaterial.set(materialIndex, materialSlots.length);\n materialSlots.push({\n slotName: uniqueName(\n materialIndex === null\n ? 'Default'\n : (doc.materials[materialIndex]?.name ?? `Material_${materialIndex}`),\n ),\n sourceKey:\n materialIndex === null\n ? 'gltf:default'\n : (materialOutput?.sourceKey ?? `gltf:material:${materialIndex}`),\n ...(materialOutput === undefined ? {} : { defaultMaterialGuid: materialOutput.guid }),\n });\n }\n const previousPayload = existingMeta?.sourceOverrides?.[meshOutput.sourceKey];\n const previousRaw = previousPayload?.materialSlots;\n const previous = Array.isArray(previousRaw)\n ? previousRaw.filter(\n (slot): slot is MeshMaterialSlotTopologyEntry =>\n slot !== null &&\n typeof slot === 'object' &&\n !Array.isArray(slot) &&\n typeof (slot as { slotName?: unknown }).slotName === 'string',\n )\n : [];\n const reconciled = reconcileMeshMaterialSlotTopology(materialSlots, previous);\n if (!reconciled.ok) {\n return err({\n code: 'mesh-material-slot-topology-change',\n expected: `unambiguous material slot identity for mesh ${meshOutput.guid}`,\n hint: reconciled.error.hint,\n detail: {\n sourceIndices: reconciled.error.nextIndices,\n previousIndices: reconciled.error.previousIndices,\n },\n });\n }\n sourceOverrides[meshOutput.sourceKey] = {\n ...(previousPayload ?? {}),\n materialSlots: reconciled.slots,\n };\n }\n const meta: GltfMetaJson = {\n schemaVersion: 1,\n kind: 'external-asset-package',\n importer: 'gltf',\n source,\n subAssets: reuse.value.subAssets,\n ...(Object.keys(sourceOverrides).length === 0 ? {} : { sourceOverrides }),\n sourceOverrideDescriptors: reuse.value.subAssets\n .filter((entry) => entry.kind === 'mesh' && entry.sourceKey !== undefined)\n .map((entry) => ({\n sourceKey: entry.sourceKey as string,\n semantic: 'mesh-material-slot-defaults' as const,\n payloadSchema: MESH_MATERIAL_SLOT_SOURCE_OVERRIDE_PAYLOAD_SCHEMA,\n })),\n importSettings: {\n defaultSceneIndex: doc.defaultSceneIndex,\n ...(typeof existingMeta?.importSettings.standardMaterialGuid === 'string'\n ? { standardMaterialGuid: existingMeta.importSettings.standardMaterialGuid }\n : {}),\n ...(existingMeta?.importSettings.downscaleMaxDimension !== undefined\n ? { downscaleMaxDimension: existingMeta.importSettings.downscaleMaxDimension }\n : {}),\n diagnostics: {\n nodeNames: doc.diagnostics.nodeNames,\n unsupportedExtensions: doc.diagnostics.unsupportedExtensions,\n matrixTrsCoexistNodes: doc.diagnostics.matrixTrsCoexistNodes,\n },\n },\n };\n return ok({ meta, subAssets: reuse.value.subAssets });\n}\n\n// Keep the component-type table available from this importer module.\nexport { COMPONENT_TYPE };\n","// File-entry wrappers (Node-only, dynamic-import isolated).\n//\n// `parseGltfFromFile` / `parseGlbFromFile` are the only members of this\n// package that touch the filesystem. They live in this dedicated module so\n// the main entry (`index.ts`) stays browser-clean: the `node:fs/promises`\n// and `node:path` dynamic imports below would otherwise trip vite's\n// \"module externalized for browser compatibility\" warning when the demo\n// bundles `@forgeax/engine-gltf` for the browser even though it never\n// calls these helpers.\n//\n// Sidecar policy (feat-20260521 unify-sidecar-meta-dispatch-by-content):\n// <name>.gltf -> <name>.gltf.meta.json\n// <name>.glb -> <name>.glb.meta.json\n//\n// Both wrappers add a single fail-fast pre-step: stat the sibling\n// `<source>.meta.json`; return `gltf-meta-missing` if absent (same code\n// surfaced by the vite-plugin and the console CLI dry-run, charter\n// proposition 5 consistent abstraction). Callers with an ArrayBuffer /\n// parsed JSON should keep using `parseGltf` / `parseGlb` directly.\n\nimport { err, type GltfError, gltfErr, type Result } from './errors.js';\nimport { type ExternalLoader, type GltfDoc, parseGlb, parseGltf } from './parse-gltf.js';\n\ninterface FsLike {\n readonly stat: (path: string) => Promise<unknown>;\n readonly readFile: (path: string) => Promise<Buffer>;\n}\n\ninterface PathLike {\n readonly dirname: (p: string) => string;\n readonly resolve: (...segments: string[]) => string;\n}\n\nasync function loadFsModule(): Promise<FsLike> {\n const mod = (await import('node:fs/promises')) as unknown as FsLike;\n return mod;\n}\n\nasync function loadPathModule(): Promise<PathLike> {\n const mod = (await import('node:path')) as unknown as PathLike;\n return mod;\n}\n\nasync function statExists(fs: FsLike, path: string): Promise<boolean> {\n try {\n await fs.stat(path);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction metaPathFor(filePath: string): string {\n return `${filePath}.meta.json`;\n}\n\n/**\n * Parse a `.gltf` file from disk. Pre-step: stat the sibling\n * `<source>.meta.json`; if missing, return `gltf-meta-missing` without\n * reading the source bytes.\n */\nexport async function parseGltfFromFile(filePath: string): Promise<Result<GltfDoc, GltfError>> {\n const fs = await loadFsModule();\n const path = await loadPathModule();\n const expectedMetaPath = metaPathFor(filePath);\n if (!(await statExists(fs, expectedMetaPath))) {\n return err(gltfErr('gltf-meta-missing', { filePath, expectedMetaPath }));\n }\n const text = (await fs.readFile(filePath)).toString('utf-8');\n let json: unknown;\n try {\n json = JSON.parse(text);\n } catch (_e) {\n return err(gltfErr('gltf-malformed-header', { filePath, byteOffset: 0 }));\n }\n const baseDir = path.dirname(filePath);\n const externalLoader: ExternalLoader = async (uri: string) => {\n const abs = path.resolve(baseDir, uri);\n const buf = await fs.readFile(abs);\n return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength) as ArrayBuffer;\n };\n return parseGltf(json, externalLoader, filePath);\n}\n\n/**\n * Parse a `.glb` file from disk. Same fail-fast meta-stat pre-step as\n * `parseGltfFromFile`.\n */\nexport async function parseGlbFromFile(filePath: string): Promise<Result<GltfDoc, GltfError>> {\n const fs = await loadFsModule();\n const expectedMetaPath = metaPathFor(filePath);\n if (!(await statExists(fs, expectedMetaPath))) {\n return err(gltfErr('gltf-meta-missing', { filePath, expectedMetaPath }));\n }\n const buf = await fs.readFile(filePath);\n const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength) as ArrayBuffer;\n return parseGlb(ab, filePath);\n}\n"]}
|