@forgeax/engine-gltf 0.1.29 → 0.1.31
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 +1 -1
- package/dist/animated-bounds.d.ts +4 -0
- package/dist/animated-bounds.d.ts.map +1 -0
- package/dist/gltf-importer.d.ts.map +1 -1
- package/dist/importer-entry.mjs +114 -30
- package/dist/importer-entry.mjs.map +1 -1
- package/dist/index.mjs +114 -30
- package/dist/index.mjs.map +1 -1
- package/package.json +12 -12
- package/src/__tests__/gltf.unit.test.ts +67 -0
- package/src/animated-bounds.ts +94 -0
- package/src/gltf-importer.ts +2 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors.ts","../src/bridge.ts","../src/data-uri.ts","../src/parse-gltf-header.ts","../src/parse-glb-chunks.ts","../src/extract-image-bytes.ts","../src/image-color-space.ts","../src/accessor/decode-accessor.ts","../src/accessor/decode-color.ts","../src/check-extensions.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-skin.ts","../src/transform.ts","../src/parse-gltf.ts","../src/gltf-importer.ts","../src/importer-entry.ts"],"names":["AssetGuidCodec","err","mime","tuple3","vec3","quat","mat4","n","ImportError","IMPORT_ERROR_HINTS","reconcileMeshMaterialSlotTopology","res","textureInfo","textureValue","parsed","makeRef","skinGuidList","gltfImporter"],"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,y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A,IACxC,cAAc,EAAE,OAAA,EAAS,EAAE,OAAA,EAAS,yBAAwB;AAAE,GAChE;AACF;;;ACzlCA,MAAM,cAAA,CAAe,KAAA;AAGd,IAAM,cAAA,GAAiD;AAAA,EAC5D,MAAA,EAAQ,CAAC,EAAE,MAAA,EAAQ,OAAO,MAAA,EAAQ,IAAA,EAAM,QAAO,KAAM;AACnD,IAAA,MAAM,MAAA,GAAS,IAAI,UAAA,CAAW,KAAA,GAAQ,MAAM,CAAA;AAC5C,IAAA,cAAA,CAAe,iBAAiB,MAAA,EAAQ,KAAA,EAAO,MAAA,EAAQ,MAAA,EAAQ,MAAM,MAAM,CAAA;AAC3E,IAAA,OAAO,MAAA;AAAA,EACT;AACF;AAMO,IAAMC,gBAAe,kBAAA,CAAmB;AAAA,EAC7C,QAAQ,cAAA,CAAe;AACzB,CAAC","file":"importer-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","// bridge.ts - public gltfDocToSceneAsset SSOT (M3 w9 / feat-20260518).\n//\n// Excises the previously inline 80-line implementation in\n// apps/hello/gltf/src/main.ts. AI users get a single import path:\n//\n// ```ts\n// import { gltfDocToSceneAsset, toMaterialAsset } from '@forgeax/engine-gltf';\n// const scene = gltfDocToSceneAsset(doc, { meshHandles, materialHandles });\n// ```\n//\n// Pure function: no fs, no fetch, no throw. Walks the default scene's\n// node graph depth-first, accumulating world transforms for children (B3).\n// Handles for mesh / material come from caller-supplied Map lookups so the\n// bridge stays runtime-agnostic.\n//\n// feat-20260608-mesh-multi-section-primitive-multi-material-slot M3 / w13+w15:\n// (B1) N prim per glTF mesh merged into 1 entity with MeshRenderer.materials[]\n// (B2) visit recursively walks ir.children\n// (B3) child world pos accumulates parent transform\n// (B6) camera detection via GltfNodeIr.camera field (not legacy nodes[1] heuristic)\n\nimport { computeTangentVec4, packInterleavedVertexAttributes } from '@forgeax/engine-geometry';\nimport type { Mat4 } from '@forgeax/engine-math';\nimport { box3, mat4, quat, vec3 } from '@forgeax/engine-math';\nimport { AssetGuid as AssetGuidCodec } from '@forgeax/engine-pack/guid';\nimport type {\n AssetGuid,\n Handle,\n LocalEntityId,\n MaterialAsset,\n MaterialError,\n MaterialTextureValue,\n MeshAsset,\n MeshMaterialSlot,\n MorphTarget,\n RenderQueue,\n Result,\n SceneAsset,\n Submesh,\n VertexAttributeMap,\n} from '@forgeax/engine-types';\nimport {\n STANDARD_LAYER_PARAMETER_GROUPS,\n STANDARD_MATERIAL_PARAM_SCHEMA,\n STANDARD_PHYSICAL_PARAMETER_NAMES,\n STANDARD_TRANSMISSION_PARAMETER_NAMES,\n standardMaterialParameters,\n} from '@forgeax/engine-types';\nimport { createMaterialError, err, type GltfError, gltfErr, ok } from './errors.js';\nimport type {\n GltfDoc,\n GltfMaterialIr,\n GltfMeshIr,\n GltfNodeIr,\n GltfPunctualLightIr,\n GltfTextureInfoIr,\n} from './parse-gltf.js';\n\n/**\n * Convert one or more parsed `GltfMeshIr` primitives sharing the same glTF\n * mesh-index into a single runtime `MeshAsset` POD. Each primitive becomes one\n * `Submesh` row; per-primitive vertex data is concatenated into one big\n * interleaved vertex buffer (12 floats / vertex for unskinned meshes; 18 floats\n * / vertex when any primitive carries `joints0` + `weights0`), and per-primitive\n * index buffers are concatenated into one big index buffer. Each submesh's\n * indices are biased by the running vertex offset so they reference vertices\n * within the merged buffer.\n *\n * Per-MeshAsset stride decision (D-2): if any primitive contains skin\n * attributes, the entire MeshAsset is promoted to 18-float stride and\n * unskinned primitives' skin slots are zero-filled (joints {0,0,0,0} +\n * weights {0,0,0,0}). This avoids splitting one glTF mesh into multiple\n * MeshAsset rows when a model mixes skinned and unskinned primitives.\n *\n * AI users get a 1-to-1 mapping with `MeshRenderer.materials[]`: the i-th\n * submesh is the i-th primitive of the i-th material slot.\n *\n * Pure function (no fs / fetch / registry). Missing attributes fall back to\n * identity defaults per primitive: normal -> +Y, uv -> 0, tangent -> +X with\n * w=1.\n *\n * Invalid source data is returned as a typed `GltfError`; callers must branch\n * on `Result.ok` before publishing a MeshAsset. Caller (gltfImporter / smoke\n * driver) is responsible for grouping by `meshIr.meshIndex` before calling.\n */\nexport function meshIrToMeshAsset(\n prims: readonly GltfMeshIr[],\n materials: {\n readonly guidByIndex?: ReadonlyMap<number, string>;\n readonly nameByIndex?: ReadonlyMap<number, string>;\n readonly sourceKeyByIndex?: ReadonlyMap<number, string>;\n } = {},\n): Result<MeshAsset, GltfError> {\n if (prims.length === 0) {\n return err(\n gltfErr('gltf-mesh-bridge-invalid', {\n reason: 'empty-input',\n primitiveCount: 0,\n }),\n );\n }\n let totalVertexCount = 0;\n let totalIndexCount = 0;\n let hasAnySkin = false;\n const hasAnyColor = prims.some((p) => p.colors0 !== undefined);\n let hasAnyIndices = false;\n // feat-20260629-multi-uv-set-support m1-w3: derive the widest canonical UV\n // key list across all primitives so the geometry projection accommodates it.\n let widestUvIndex = 0;\n const morphTargetCount = prims[0]?.morphTargets?.length ?? 0;\n for (const p of prims) {\n const primVc = p.positions.length / 3;\n totalVertexCount += primVc;\n if (p.indices !== undefined) {\n totalIndexCount += p.indices.length;\n hasAnyIndices = true;\n } else {\n totalIndexCount += primVc;\n }\n if (p.joints0 !== undefined && p.weights0 !== undefined) hasAnySkin = true;\n if ((p.morphTargets?.length ?? 0) !== morphTargetCount) {\n return err(\n gltfErr('gltf-mesh-bridge-invalid', {\n meshIndex: p.meshIndex,\n primitiveIndex: prims.indexOf(p),\n reason: 'morph-count-mismatch',\n expectedTargetCount: morphTargetCount,\n actualTargetCount: p.morphTargets?.length ?? 0,\n }),\n );\n }\n // Count present UV sets in this primitive.\n for (let k = 7; k >= 1; k--) {\n const key = `texcoord${k}` as keyof GltfMeshIr;\n if (p[key] !== undefined) {\n widestUvIndex = Math.max(widestUvIndex, k);\n break;\n }\n }\n }\n\n const uvKeys = Array.from({ length: widestUvIndex }, (_, index) => `uv${index + 1}`);\n\n const positionsCat = new Float32Array(totalVertexCount * 3);\n const normalsCat = new Float32Array(totalVertexCount * 3);\n const uvsCat = new Float32Array(totalVertexCount * 2);\n const tangentsCat = new Float32Array(totalVertexCount * 4);\n const colorsCat = hasAnyColor ? new Float32Array(totalVertexCount * 4) : undefined;\n const morphTargets: MorphTarget[] = Array.from({ length: morphTargetCount }, (_, targetIndex) => {\n const source = prims[0]?.morphTargets?.[targetIndex];\n return {\n ...(source?.position === undefined\n ? {}\n : { position: new Float32Array(totalVertexCount * 3) }),\n ...(source?.normal === undefined ? {} : { normal: new Float32Array(totalVertexCount * 3) }),\n ...(source?.tangent === undefined ? {} : { tangent: new Float32Array(totalVertexCount * 4) }),\n };\n });\n // feat-20260629-multi-uv-set-support m1-w3: per-UV-set standalone typed arrays\n // for MeshAsset.attributes (uv1..uvK). Allocated only for imported sets.\n const uvCats = uvKeys.map(() => new Float32Array(totalVertexCount * 2));\n // D-2 / w8: when promoted to a skinned projection, retain canonical\n // standalone arrays; the geometry packer owns the interleaved GPU bytes.\n const skinIndicesCat = hasAnySkin ? new Uint16Array(totalVertexCount * 4) : undefined;\n const skinWeightsCat = hasAnySkin ? new Float32Array(totalVertexCount * 4) : undefined;\n // Multi-primitive merge biases each primitive's index range by the running\n // vertex offset, so the merged max index is `totalVertexCount - 1`. When a\n // glTF mesh has > 65535 vertices across all primitives (common for\n // moderately complex scenes like Sponza at ~192k verts), Uint16 overflows\n // and we must widen to Uint32. WebGPU's setIndexBuffer takes 'uint16' or\n // 'uint32' (auto-selected by the runtime via TypedArray.constructor); both\n // are supported by every WebGPU device.\n // bug-20260612 hello-skin visual layered gate: when no primitive carries\n // indices (glTF non-indexed geometry per spec — primitive.indices optional),\n // route MeshAsset.indices to undefined so the runtime takes the\n // pass.draw(vertexCount) non-indexed path. Mixed bags (some prims indexed,\n // some not) synthesize identity indices for the non-indexed prims so the\n // merged MeshAsset stays single-index-buffer. hasAnyIndices === false\n // skips the index buffer allocation entirely.\n const useUint32 = totalVertexCount > 0xffff;\n const indices: Uint16Array | Uint32Array | undefined = !hasAnyIndices\n ? undefined\n : useUint32\n ? new Uint32Array(totalIndexCount)\n : new Uint16Array(totalIndexCount);\n const submeshes: Submesh[] = [];\n const materialSlots: MeshMaterialSlot[] = [];\n const slotByMaterial = new Map<number | null, number>();\n const usedNames = new Set<string>();\n const uniqueSlotName = (base: string): string => {\n let candidate = base.trim() || 'Material';\n let suffix = 2;\n while (usedNames.has(candidate)) candidate = `${base}_${suffix++}`;\n usedNames.add(candidate);\n return candidate;\n };\n const slotFor = (materialIndex: number | null): number => {\n const existing = slotByMaterial.get(materialIndex);\n if (existing !== undefined) return existing;\n const slotIndex = materialSlots.length;\n const guid = materialIndex === null ? undefined : materials.guidByIndex?.get(materialIndex);\n const parsed = guid === undefined ? undefined : AssetGuidCodec.parse(guid);\n materialSlots.push({\n slotName: uniqueSlotName(\n materialIndex === null\n ? 'Default'\n : (materials.nameByIndex?.get(materialIndex) ?? `Material_${materialIndex}`),\n ),\n sourceKey:\n materialIndex === null\n ? 'gltf:default'\n : (materials.sourceKeyByIndex?.get(materialIndex) ?? `gltf:material:${materialIndex}`),\n ...(parsed?.ok ? { defaultMaterial: parsed.value } : {}),\n });\n slotByMaterial.set(materialIndex, slotIndex);\n return slotIndex;\n };\n\n let vertexCursor = 0;\n let indexCursor = 0;\n for (const mesh of prims) {\n const materialSlot = slotFor(mesh.materialIndex);\n const primVertexCount = mesh.positions.length / 3;\n const primIndexCount = mesh.indices === undefined ? 0 : mesh.indices.length;\n // A tangent admission check may already have computed a valid frame for a\n // physical glTF material. Persist that producer result into the canonical\n // MeshAsset instead of silently replacing it with the historical identity\n // tangent. Non-physical meshes keep the identity fallback when the source\n // lacks the inputs required by the tangent producer.\n let generatedTangents: Float32Array | undefined;\n if (mesh.tangents === undefined && mesh.normals !== undefined && mesh.texcoord0 !== undefined) {\n const generated = computeTangentVec4(\n mesh.positions,\n mesh.normals,\n mesh.texcoord0,\n mesh.indices,\n );\n if (generated.ok) generatedTangents = generated.value;\n }\n if (mesh.colors0 !== undefined && mesh.colors0.length !== primVertexCount * 4) {\n return err(\n gltfErr('gltf-mesh-bridge-invalid', {\n meshIndex: mesh.meshIndex,\n primitiveIndex: prims.indexOf(mesh),\n reason: 'color-cardinality',\n semantic: 'COLOR_0',\n vertexCount: primVertexCount,\n expectedLength: primVertexCount * 4,\n actualLength: mesh.colors0.length,\n }),\n );\n }\n for (let i = 0; i < primVertexCount; i++) {\n const p = i * 3;\n positionsCat[(vertexCursor + i) * 3 + 0] = mesh.positions[p + 0] as number;\n positionsCat[(vertexCursor + i) * 3 + 1] = mesh.positions[p + 1] as number;\n positionsCat[(vertexCursor + i) * 3 + 2] = mesh.positions[p + 2] as number;\n if (mesh.normals !== undefined) {\n const n = i * 3;\n normalsCat[(vertexCursor + i) * 3 + 0] = mesh.normals[n + 0] as number;\n normalsCat[(vertexCursor + i) * 3 + 1] = mesh.normals[n + 1] as number;\n normalsCat[(vertexCursor + i) * 3 + 2] = mesh.normals[n + 2] as number;\n } else {\n normalsCat[(vertexCursor + i) * 3 + 1] = 1;\n }\n if (mesh.texcoord0 !== undefined) {\n const t = i * 2;\n uvsCat[(vertexCursor + i) * 2 + 0] = mesh.texcoord0[t + 0] as number;\n uvsCat[(vertexCursor + i) * 2 + 1] = mesh.texcoord0[t + 1] as number;\n }\n const sourceTangents = mesh.tangents ?? generatedTangents;\n if (sourceTangents !== undefined) {\n const g = i * 4;\n tangentsCat[(vertexCursor + i) * 4 + 0] = sourceTangents[g + 0] as number;\n tangentsCat[(vertexCursor + i) * 4 + 1] = sourceTangents[g + 1] as number;\n tangentsCat[(vertexCursor + i) * 4 + 2] = sourceTangents[g + 2] as number;\n tangentsCat[(vertexCursor + i) * 4 + 3] = sourceTangents[g + 3] as number;\n } else {\n tangentsCat[(vertexCursor + i) * 4 + 0] = 1;\n tangentsCat[(vertexCursor + i) * 4 + 3] = 1;\n }\n if (colorsCat !== undefined) {\n const colorDst = (vertexCursor + i) * 4;\n const colorSrc = i * 4;\n if (mesh.colors0 === undefined) {\n colorsCat[colorDst + 0] = 1;\n colorsCat[colorDst + 1] = 1;\n colorsCat[colorDst + 2] = 1;\n colorsCat[colorDst + 3] = 1;\n } else {\n colorsCat[colorDst + 0] = mesh.colors0[colorSrc + 0] as number;\n colorsCat[colorDst + 1] = mesh.colors0[colorSrc + 1] as number;\n colorsCat[colorDst + 2] = mesh.colors0[colorSrc + 2] as number;\n colorsCat[colorDst + 3] = mesh.colors0[colorSrc + 3] as number;\n }\n }\n for (let targetIndex = 0; targetIndex < morphTargetCount; targetIndex++) {\n const source = mesh.morphTargets?.[targetIndex];\n const target = morphTargets[targetIndex] as MorphTarget;\n const vertex = vertexCursor + i;\n if (source?.position !== undefined && target.position !== undefined) {\n target.position.set(source.position.subarray(i * 3, i * 3 + 3), vertex * 3);\n }\n if (source?.normal !== undefined && target.normal !== undefined) {\n target.normal.set(source.normal.subarray(i * 3, i * 3 + 3), vertex * 3);\n }\n if (source?.tangent !== undefined && target.tangent !== undefined) {\n target.tangent.set(source.tangent.subarray(i * 4, i * 4 + 4), vertex * 4);\n }\n }\n // D-2 / w8: when the MeshAsset is promoted to a skinned projection,\n // retain both canonical standalone arrays. The geometry packer writes\n // their typed values into the canonical interleaved byte layout once.\n if (hasAnySkin && skinIndicesCat !== undefined && skinWeightsCat !== undefined) {\n const skinDst = (vertexCursor + i) * 4;\n if (mesh.joints0 !== undefined && mesh.weights0 !== undefined) {\n const j = i * 4;\n const j0 = mesh.joints0[j + 0] as number;\n const j1 = mesh.joints0[j + 1] as number;\n const j2 = mesh.joints0[j + 2] as number;\n const j3 = mesh.joints0[j + 3] as number;\n skinIndicesCat[skinDst + 0] = j0;\n skinIndicesCat[skinDst + 1] = j1;\n skinIndicesCat[skinDst + 2] = j2;\n skinIndicesCat[skinDst + 3] = j3;\n const w0 = mesh.weights0[j + 0] as number;\n const w1 = mesh.weights0[j + 1] as number;\n const w2 = mesh.weights0[j + 2] as number;\n const w3 = mesh.weights0[j + 3] as number;\n skinWeightsCat[skinDst + 0] = w0;\n skinWeightsCat[skinDst + 1] = w1;\n skinWeightsCat[skinDst + 2] = w2;\n skinWeightsCat[skinDst + 3] = w3;\n }\n // else: unskinned primitive in a mixed MeshAsset; typed arrays remain\n // zero-filled, which is the canonical fallback.\n }\n // feat-20260629-multi-uv-set-support m1-w3: write uv1..uvK after skin data.\n // Canonical interleaved order: position/normal/uv/tangent/skinIndex/skinWeight/uv1..uv7.\n // UV1 starts at offset UV1_OFFSET (12 for unskinned, 18 for skinned) in float slots.\n // Each additional UV set 2F. Missing texcoordK → zero-fill (plan-strategy M1).\n for (let k = 1; k <= uvKeys.length; k++) {\n const uvKey = `texcoord${k}` as keyof GltfMeshIr;\n const catIdx = k - 1;\n const cat = uvCats[catIdx] as Float32Array;\n const catDst = (vertexCursor + i) * 2;\n const srcArr = mesh[uvKey] as Float32Array | undefined;\n if (srcArr !== undefined) {\n const t = i * 2;\n cat[catDst + 0] = srcArr[t + 0] as number;\n cat[catDst + 1] = srcArr[t + 1] as number;\n }\n // else: zero-fill (implicit — Float32Array defaults to 0)\n }\n }\n // Bias each submesh's indices by the running vertex offset so they\n // reference into the merged vertex buffer rather than the per-primitive\n // local 0-base. When the merged MeshAsset is non-indexed (hasAnyIndices\n // === false → `indices` is undefined here), skip the bias loop and\n // emit a vertex-only submesh (indexCount=0; runtime dispatches via\n // `pass.draw(vertexCount)`). When mixed (some prims indexed, this one\n // not), synthesize identity indices [vertexCursor..+primVertexCount-1]\n // so the merged single-index-buffer contract holds.\n if (indices !== undefined) {\n if (mesh.indices !== undefined) {\n for (let i = 0; i < primIndexCount; i++) {\n const src = mesh.indices[i] as number;\n indices[indexCursor + i] = src + vertexCursor;\n }\n submeshes.push({\n indexOffset: indexCursor,\n indexCount: primIndexCount,\n vertexCount: primVertexCount,\n topology: 'triangle-list',\n materialSlot,\n });\n indexCursor += primIndexCount;\n } else {\n // mixed bag: synthesize identity indices for this non-indexed prim\n for (let i = 0; i < primVertexCount; i++) {\n indices[indexCursor + i] = vertexCursor + i;\n }\n submeshes.push({\n indexOffset: indexCursor,\n indexCount: primVertexCount,\n vertexCount: primVertexCount,\n topology: 'triangle-list',\n materialSlot,\n });\n indexCursor += primVertexCount;\n }\n } else {\n // pure non-indexed mesh: indexCount=0, vertexCount carries draw count.\n submeshes.push({\n indexOffset: 0,\n indexCount: 0,\n vertexCount: primVertexCount,\n topology: 'triangle-list',\n materialSlot,\n });\n }\n vertexCursor += primVertexCount;\n }\n\n const attributes: VertexAttributeMap = {\n position: positionsCat,\n normal: normalsCat,\n uv: uvsCat,\n tangent: tangentsCat,\n ...(colorsCat === undefined ? {} : { color: colorsCat }),\n ...(skinIndicesCat === undefined ? {} : { skinIndex: skinIndicesCat }),\n ...(skinWeightsCat === undefined ? {} : { skinWeight: skinWeightsCat }),\n ...Object.fromEntries(uvCats.map((cat, idx) => [`uv${idx + 1}`, cat])),\n };\n const packed = packInterleavedVertexAttributes(attributes, totalVertexCount);\n if (!packed.ok) {\n return err(\n gltfErr('gltf-mesh-bridge-invalid', {\n meshIndex: prims[0]?.meshIndex ?? -1,\n reason: 'layout-invalid',\n cause: packed.error.detail,\n }),\n );\n }\n\n return ok({\n kind: 'mesh',\n vertices: packed.value.vertices,\n ...(indices === undefined ? {} : { indices }),\n submeshes,\n materialSlots,\n aabb: box3.fromPositions(box3.create(), positionsCat),\n attributes,\n ...(morphTargetCount === 0 ? {} : { morphTargets }),\n ...(prims[0]?.morphWeights === undefined\n ? {}\n : { morphWeights: new Float32Array(prims[0].morphWeights) }),\n });\n}\n\nexport interface GltfBridgeContext {\n /** glTF mesh index -> registry MeshAsset handle (multi-submesh). */\n readonly meshHandles: ReadonlyMap<number, Handle<'MeshAsset', 'shared'>>;\n /** glTF material index -> registry MaterialAsset handle. */\n readonly materialHandles: ReadonlyMap<number, Handle<'MaterialAsset', 'shared'>>;\n /**\n * glTF skin index -> SkeletonAsset GUID (string form). When a GltfNodeIr carries\n * a skin reference, the bridge emits `Skin: { skeleton: <guid-string> }` on\n * that node's entity; AssetRegistry._resolveSceneGuids resolves the GUID to\n * a runtime Handle at instantiate time (same protocol as MeshFilter and\n * MeshRenderer.materials[]). Optional — skinless glTFs pass an empty Map\n * (or omit the field) and the bridge does not emit Skin.\n *\n * tweak-20260611 M6 / D-7: emitting Skin from the bridge means the standard\n * loadByGuid<SceneAsset> + instantiate path Just Works for skinned glTF;\n * demos no longer need to runtime-parseGlb + post-load patch the SceneAsset.\n * postSpawnResolveJoints (called from AssetRegistry.instantiate) walks the\n * matching SkinAsset.jointPaths against the spawn subtree to fill Skin.joints[].\n */\n readonly skeletonGuidBySkinIndex?: ReadonlyMap<number, string>;\n /**\n * glTF node index -> a live renderer-owned instance collection identity.\n * The bridge is intentionally pure and cannot mint collection ids or copy\n * matrix bytes into ECS. Runtime consumers create collections through their\n * Renderer first, then provide this map when lowering the SceneAsset.\n */\n readonly instanceCollectionIdsByNodeIndex?: ReadonlyMap<number, number>;\n}\n\ninterface MutableSceneEntity {\n localId: LocalEntityId;\n components: Record<string, Record<string, unknown>>;\n /** Index into the external `nodes` array, set after push for ChildOf wiring. */\n localIdx: number;\n}\n\nfunction lightDirection(currentWorld: Mat4): readonly [number, number, number] {\n const direction = mat4.getForward(vec3.create(), currentWorld);\n return [direction[0] ?? 0, direction[1] ?? 0, direction[2] ?? -1];\n}\n\nfunction lightComponent(\n light: GltfPunctualLightIr,\n direction: readonly [number, number, number],\n): Record<string, unknown> {\n const range = light.range ?? Number.POSITIVE_INFINITY;\n if (light.type === 'directional') {\n return { direction, color: light.color, intensity: light.intensity };\n }\n if (light.type === 'point') {\n return { color: light.color, intensity: light.intensity, range };\n }\n return {\n direction,\n color: light.color,\n intensity: light.intensity,\n range,\n innerConeDeg: ((light.spot?.innerConeAngle ?? 0) * 180) / Math.PI,\n outerConeDeg: ((light.spot?.outerConeAngle ?? Math.PI / 4) * 180) / Math.PI,\n castShadow: false,\n };\n}\n\n/**\n * Convert a local TRS (translation, rotation quat, scale) into a Mat4.\n * Uses @forgeax/engine-math out-param style. `out` is mutated in place.\n */\nfunction composeMat4(\n out: Mat4,\n tx: number,\n ty: number,\n tz: number,\n qx: number,\n qy: number,\n qz: number,\n qw: number,\n sx: number,\n sy: number,\n sz: number,\n): void {\n const t = vec3.create(tx, ty, tz);\n const r = quat.create();\n r[0] = qx;\n r[1] = qy;\n r[2] = qz;\n r[3] = qw;\n const s = vec3.create(sx, sy, sz);\n mat4.compose(out, t, r, s);\n}\n\n/**\n * Convert a parsed GltfDoc into a SceneAsset POD. Caller supplies registry\n * handles via `ctx`; the bridge does no registration of its own.\n *\n * Visits the default scene's nodes depth-first, accumulating world-space\n * transforms from parent to child (B3). Assigns sequential LocalEntityId in\n * document order for reimport-stable identity. Camera nodes are detected by\n * GltfNodeIr.camera (B6 fix).\n *\n * B1: each glTF mesh's N primitives are merged into a single entity.\n * The caller provides `ctx.meshHandles` keyed by glTF mesh index, where each\n * handle points to a MeshAsset whose `submeshes` already span all primitives.\n * `ctx.materialHandles` is keyed by glTF material index; the bridge assembles a\n * `MeshRenderer.materials[]` array from the primitives' materialIndex values\n * in the order they appear in `doc.meshes`.\n *\n * B2: visit recursively walks `ir.children`.\n *\n * D-2 (empty container): transform-only nodes (no mesh, no camera) produce\n * an entity with just Transform + optionally a Name component, preserving the\n * hierarchy for animation/picking hooks.\n */\nexport function gltfDocToSceneAsset(doc: GltfDoc, ctx: GltfBridgeContext): SceneAsset {\n const sceneIr = doc.scenes[doc.defaultSceneIndex];\n const resultNodes: MutableSceneEntity[] = [];\n if (sceneIr === undefined) return { kind: 'scene', entities: {} } as unknown as SceneAsset;\n const importedLights = doc.lights ?? doc.extensions?.KHR_lights_punctual?.lights ?? [];\n const animationTargetIds = new Map<number, string>();\n for (const clip of doc.animationClips) {\n for (const channel of clip.channels) {\n animationTargetIds.set(channel.targetNodeIndex, channel.targetId);\n }\n }\n\n // Per-node world matrix accumulator (B3 fix).\n const parentWorld = mat4.create();\n mat4.identity(parentWorld);\n const currentWorld = mat4.create();\n const localMat = mat4.create();\n\n // bug-20260613: SceneAsset entities also emit ChildOf when a glTF node has a\n // parent (line 547 below). Runtime propagateTransforms then derives\n // GlobalTransform.world via `parent.world * compose(child.local TRS)`. If we\n // wrote the *world* TRS into Transform here, every child node would get\n // baked twice -- once at importer time and again at propagate time --\n // collapsing the skin so vertices fly to (parent.world)^2 space and the\n // mesh appears as a scrambled silhouette. Mirror GltfNodeIr.transform's local\n // TRS verbatim; propagateTransforms is the single accumulation path.\n const pushLocalTransform = (\n transform: import('./transform.js').DecomposedTransform,\n ): Record<string, unknown> => ({\n pos: [\n transform.translation[0] ?? 0,\n transform.translation[1] ?? 0,\n transform.translation[2] ?? 0,\n ],\n // Quaternion component order [x, y, z, w] (glTF-aligned; E6).\n quat: [\n transform.rotation[0] ?? 0,\n transform.rotation[1] ?? 0,\n transform.rotation[2] ?? 0,\n transform.rotation[3] ?? 1,\n ],\n scale: [transform.scale[0] ?? 1, transform.scale[1] ?? 1, transform.scale[2] ?? 1],\n });\n\n const visit = (gltfNodeIdx: number, parentLocalIdx: number | null): void => {\n const ir = doc.nodes[gltfNodeIdx];\n if (ir === undefined) return;\n\n // Compute local transform matrix\n composeMat4(\n localMat,\n ir.transform.translation[0] ?? 0,\n ir.transform.translation[1] ?? 0,\n ir.transform.translation[2] ?? 0,\n ir.transform.rotation[0] ?? 0,\n ir.transform.rotation[1] ?? 0,\n ir.transform.rotation[2] ?? 0,\n ir.transform.rotation[3] ?? 1,\n ir.transform.scale[0] ?? 1,\n ir.transform.scale[1] ?? 1,\n ir.transform.scale[2] ?? 1,\n );\n\n // Accumulate world transform (B3: parent * local)\n if (parentLocalIdx === null) {\n // Root node: world = local\n for (let i = 0; i < 16; i++) {\n currentWorld[i] = localMat[i] ?? 0;\n }\n } else {\n mat4.multiply(currentWorld, parentWorld, localMat);\n }\n\n // B6: detect camera via GltfNodeIr.camera field (not legacy heuristic)\n const isCamera = ir.camera !== null;\n\n // D-2: empty container rule\n // - mesh node: MeshFilter + MeshRenderer\n // - camera node: Camera (standalone entity)\n // - transform-only node (no mesh, no camera): Transform-only entity to preserve hierarchy\n const hasMesh = ir.meshIndex !== null;\n\n // Always produce a node for every glTF node (preserves hierarchy).\n // Transform-only nodes carry just Transform + optionally Name.\n const components: Record<string, Record<string, unknown>> = {\n Transform: pushLocalTransform(ir.transform),\n };\n\n const importedLight = importedLights[ir.lightIndex ?? -1];\n if (importedLight !== undefined) {\n const componentName =\n importedLight.type === 'directional'\n ? 'DirectionalLight'\n : importedLight.type === 'point'\n ? 'PointLight'\n : 'SpotLight';\n components[componentName] = lightComponent(\n importedLight,\n lightDirection(currentWorld),\n ) as Record<string, unknown>;\n }\n\n if (ir.name !== undefined && ir.name !== '') {\n components.Name = { value: ir.name };\n }\n const animationTargetId = animationTargetIds.get(gltfNodeIdx);\n if (animationTargetId !== undefined) {\n components.AnimationTargetId = { value: animationTargetId };\n }\n\n if (hasMesh) {\n const meshHandle = ctx.meshHandles.get(ir.meshIndex as number);\n if (meshHandle !== undefined) {\n components.MeshFilter = { assetHandle: meshHandle };\n }\n const meshMorph = doc.meshes.find((mesh) => mesh.meshIndex === ir.meshIndex);\n const morphCount = meshMorph?.morphTargets?.length ?? 0;\n if (morphCount > 0) {\n const weights = ir.morphWeights ?? meshMorph?.morphWeights ?? new Float32Array(morphCount);\n if (weights.length !== morphCount) {\n throw new Error('gltfDocToSceneAsset: MorphWeights length does not match morph targets');\n }\n components.MorphWeights = { weights: new Float32Array(weights) };\n }\n // tweak-20260611 M6: when this node references a glTF skin, stamp a\n // Skin component carrying the SkeletonAsset GUID as a string. The\n // runtime AssetRegistry._resolveSceneGuids resolves the string to a\n // Handle at instantiate time (same protocol as MeshFilter/MeshRenderer).\n // postSpawnResolveJoints (called from AssetRegistry.instantiate) then\n // fills Skin.joints[] by walking the matching SkinAsset.jointPaths\n // against the spawn subtree's Name index.\n if (ir.skinIndex !== null && ctx.skeletonGuidBySkinIndex !== undefined) {\n const skeletonGuid = ctx.skeletonGuidBySkinIndex.get(ir.skinIndex);\n if (skeletonGuid !== undefined) {\n components.Skin = { skeleton: skeletonGuid };\n }\n }\n // B1: collect one material handle per primitive belonging to THIS\n // node's glTF mesh (filter by meshIr.meshIndex === ir.meshIndex), in\n // the same order primitives are emitted in `doc.meshes`. The merged\n // MeshAsset built by `meshIrToMeshAsset` walks the same filter in the\n // same order to produce one Submesh per primitive, so submeshes[i]\n // pairs with materials[i] positionally (AGENTS.md §Component naming\n // \"positional materials[i] <-> submeshes[i]\" + #317 multi-material\n // contract).\n //\n // A primitive with materialIndex===null (or one whose ctx.materialHandles\n // lookup misses) gets a synthetic missing-handle entry: dropping it\n // would desynchronise materials[].length vs submeshes[].length and\n // trigger the fail-fast `mesh-renderer-material-count-mismatch` at\n // register time. Falling back to the first available material handle\n // for the same mesh keeps the count alignment without inventing a\n // shared default-material handle (Tier-B scope; Sponza / BoxTextured\n // every primitive carries an explicit material so this fallback path\n // is exercised only by under-specified glTFs).\n // Mesh-owned slots carry imported defaults. Scene nodes persist only\n // true instance differences, so the canonical imported node starts with\n // an empty per-slot override vector.\n components.MeshRenderer = { materials: [] };\n }\n\n // Instances on the same entity as MeshFilter/MeshRenderer. The bridge\n // only carries the renderer-owned identity; IR matrix bytes stay in the\n // caller's collection and never become an ECS managed array. Build-time\n // consumers that do not have a Renderer omit this optional association and\n // must materialise the collection at their runtime boundary.\n if (ir.instancing !== undefined) {\n const collectionId = ctx.instanceCollectionIdsByNodeIndex?.get(gltfNodeIdx);\n if (collectionId !== undefined) {\n components.Instances = { collectionId };\n }\n }\n\n if (isCamera) {\n // B6: camera node detected via GltfNodeIr.camera (not heuristic).\n // Camera component sits alongside Transform (and Name if present).\n components.Camera = {\n fov: 0.7853981633974483,\n aspect: 1.7777777777777777,\n near: 0.1,\n far: 100,\n };\n }\n\n const localIdx = resultNodes.length;\n const node: MutableSceneEntity = {\n localId: localIdx as LocalEntityId,\n components,\n localIdx,\n };\n\n // ChildOf wiring: if this node has a parent, add ChildOf component\n if (parentLocalIdx !== null) {\n node.components.ChildOf = { parent: parentLocalIdx as LocalEntityId };\n }\n\n resultNodes.push(node);\n\n // B2: recursively visit children with accumulated world matrix.\n // B3: set parentWorld to this node's world matrix so children multiply\n // correctly (parent * childLocal = childWorld).\n const savedParent = mat4.clone(parentWorld);\n for (let i = 0; i < 16; i++) parentWorld[i] = currentWorld[i] ?? 0;\n\n for (const childIdx of ir.children) {\n visit(childIdx, localIdx);\n }\n\n // Restore parent world after visiting all children\n for (let i = 0; i < 16; i++) parentWorld[i] = savedParent[i] ?? 0;\n };\n\n for (const rootIdx of sceneIr.nodes) visit(rootIdx, null);\n\n const keyByLocalId = new Map<number, string>();\n for (const node of resultNodes) keyByLocalId.set(node.localIdx, `node-${node.localIdx}`);\n const entities: Record<string, { readonly components: Record<string, Record<string, unknown>> }> =\n {};\n for (const node of resultNodes) {\n const components = { ...node.components };\n const childOf = components.ChildOf;\n if (childOf !== undefined && typeof childOf.parent === 'number') {\n const parentKey = keyByLocalId.get(childOf.parent);\n if (parentKey === undefined)\n throw new Error(`gltfDocToSceneAsset: missing parent node ${childOf.parent}`);\n components.ChildOf = { ...childOf, parent: parentKey };\n }\n entities[`node-${node.localIdx}`] = { components };\n }\n const lightFacts = importedLights.map((light) => ({\n kind: light.type,\n intensity: light.intensity,\n ...(light.range === undefined ? {} : { range: light.range }),\n ...(light.spot === undefined ? {} : { spot: light.spot }),\n }));\n return {\n kind: 'scene',\n entities,\n ...(lightFacts.length === 0 ? {} : { lights: lightFacts }),\n } as unknown as SceneAsset;\n}\n\n/** Internal helper: mark GltfNodeIr usable so future surface evolutions stay typed. */\nexport type _NodeIrAlias = GltfNodeIr;\n\nexport interface MaterialBridgeContext {\n /** glTF texture index -> registry TextureAsset handle. */\n readonly textureHandles?: ReadonlyMap<number, Handle<'TextureAsset', 'shared'>>;\n /** glTF sampler index -> registry SamplerAsset handle. */\n readonly samplerHandles?: ReadonlyMap<number, Handle<'SamplerAsset', 'shared'>>;\n /** Built-in standard MaterialAsset GUID supplied by the importing project. */\n readonly standardRootGuid?: AssetGuid;\n /**\n * feat-20260611 w17-a: when any primitive consuming this material carries\n * JOINTS_0 + WEIGHTS_0, the cooker passes `skinned: true` so the emitted\n * MaterialAsset's pass[0].program.module is `forgeax::pbr-skin` instead of\n * `forgeax::default-standard-pbr`. The cooker (gltf-importer) is the only\n * site with full mesh<->material wiring info; routing here keeps shader\n * choice content-driven (not user-driven, per Q4 — runtime fail-fast in\n * render-system-extract remains the reverse-direction safety net).\n */\n readonly skinned?: boolean;\n}\n\nfunction textureInfo(info: GltfTextureInfoIr | number | undefined): GltfTextureInfoIr | undefined {\n return info === undefined ? undefined : typeof info === 'number' ? { texture: info } : info;\n}\n\ntype MaterialTextureSlot =\n | 'baseColorTexture'\n | 'metallicRoughnessTexture'\n | 'normalTexture'\n | 'occlusionTexture'\n | 'emissiveTexture'\n | 'transmissionTexture'\n | 'thicknessTexture'\n | 'clearcoatTexture'\n | 'clearcoatRoughnessTexture'\n | 'clearcoatNormalTexture'\n | 'anisotropyTexture'\n | 'sheenColorTexture'\n | 'sheenRoughnessTexture'\n | 'iridescenceTexture'\n | 'iridescenceThicknessTexture'\n | 'specularTexture'\n | 'specularColorTexture';\n\nfunction textureValue(\n info: GltfTextureInfoIr | number | undefined,\n slot: MaterialTextureSlot,\n ctx: MaterialBridgeContext | undefined,\n): MaterialTextureValue | undefined {\n const binding = textureInfo(info);\n if (binding === undefined || ctx?.textureHandles === undefined) return undefined;\n const textureHandle = ctx.textureHandles.get(binding.texture);\n if (textureHandle === undefined) return undefined;\n const samplerHandle =\n binding.sampler === undefined ? undefined : ctx.samplerHandles?.get(binding.sampler);\n const coordinates =\n binding.texCoord === undefined && binding.transform === undefined\n ? undefined\n : {\n ...(binding.texCoord === undefined ? {} : { set: binding.texCoord }),\n ...(binding.transform === undefined ? {} : { transform: binding.transform }),\n };\n const value = {\n texture: textureHandle as unknown as MaterialTextureValue['texture'],\n ...(samplerHandle === undefined\n ? {}\n : { sampler: samplerHandle as unknown as NonNullable<MaterialTextureValue['sampler']> }),\n ...(coordinates === undefined ? {} : { coordinates }),\n };\n if (slot === 'normalTexture') {\n const normal = info as GltfMaterialIr['normalTexture'];\n if (typeof normal === 'object' && normal?.scale !== undefined) {\n return { ...value, normalScale: normal.scale };\n }\n }\n if (slot === 'clearcoatNormalTexture') {\n const normal = info as GltfMaterialIr['clearcoatNormalTexture'];\n if (typeof normal === 'object' && normal?.scale !== undefined) {\n return { ...value, normalScale: normal.scale };\n }\n }\n if (slot === 'occlusionTexture') {\n const occlusion = info as GltfMaterialIr['occlusionTexture'];\n if (typeof occlusion === 'object' && occlusion?.strength !== undefined) {\n return { ...value, occlusionStrength: occlusion.strength };\n }\n }\n return value;\n}\n\n/**\n * Select the exact Standard root contract emitted by the glTF producer.\n * Numeric/base fields come from the shared schema; physical texture slots are\n * admitted only when the source actually declares them. A parent root is\n * retained for the legacy base-only path, while an extended glTF material\n * becomes its own root so its extension declarations own cook/ABI identity.\n */\nfunction standardRootParameterNames(mat: GltfMaterialIr): {\n readonly names: ReadonlySet<string>;\n readonly extended: boolean;\n} {\n const names = new Set(\n STANDARD_MATERIAL_PARAM_SCHEMA.filter(\n (entry) =>\n !STANDARD_PHYSICAL_PARAMETER_NAMES.has(entry.name) &&\n !STANDARD_TRANSMISSION_PARAMETER_NAMES.has(entry.name),\n ).map((entry) => entry.name),\n );\n // IOR is consumed for the base dielectric F0 fallback even when the\n // transmission/volume extension is absent.\n names.add('ior');\n\n const addLayer = (layer: keyof typeof STANDARD_LAYER_PARAMETER_GROUPS): void => {\n for (const name of STANDARD_LAYER_PARAMETER_GROUPS[layer]) names.add(name);\n };\n const addTexture = (name: string, info: GltfTextureInfoIr | number | undefined): void => {\n if (info !== undefined) names.add(name);\n };\n\n const clearcoat =\n mat.clearcoatFactor !== undefined ||\n mat.clearcoatRoughnessFactor !== undefined ||\n mat.clearcoatNormalTexture !== undefined ||\n mat.clearcoatTexture !== undefined ||\n mat.clearcoatRoughnessTexture !== undefined;\n const anisotropy =\n mat.anisotropyStrength !== undefined ||\n mat.anisotropyRotation !== undefined ||\n mat.anisotropyTexture !== undefined;\n const sheen =\n mat.sheenColorFactor !== undefined ||\n mat.sheenRoughnessFactor !== undefined ||\n mat.sheenColorTexture !== undefined ||\n mat.sheenRoughnessTexture !== undefined;\n const iridescence =\n mat.iridescenceFactor !== undefined ||\n mat.iridescenceIor !== undefined ||\n mat.iridescenceThicknessMinimum !== undefined ||\n mat.iridescenceThicknessMaximum !== undefined ||\n mat.iridescenceTexture !== undefined ||\n mat.iridescenceThicknessTexture !== undefined;\n if (clearcoat) addLayer('clearcoat');\n if (anisotropy) addLayer('anisotropy');\n if (sheen) addLayer('sheen');\n if (iridescence) addLayer('iridescence');\n if (clearcoat && mat.clearcoatNormalTexture !== undefined) names.add('clearcoatNormalScale');\n\n addTexture('clearcoatTexture', mat.clearcoatTexture);\n addTexture('clearcoatRoughnessTexture', mat.clearcoatRoughnessTexture);\n addTexture('clearcoatNormalTexture', mat.clearcoatNormalTexture);\n addTexture('anisotropyTexture', mat.anisotropyTexture);\n addTexture('sheenColorTexture', mat.sheenColorTexture);\n addTexture('sheenRoughnessTexture', mat.sheenRoughnessTexture);\n addTexture('iridescenceTexture', mat.iridescenceTexture);\n addTexture('iridescenceThicknessTexture', mat.iridescenceThicknessTexture);\n addTexture('specularTexture', mat.specularTexture);\n addTexture('specularColorTexture', mat.specularColorTexture);\n\n const transmission =\n mat.transmissionFactor !== undefined ||\n mat.transmissionTexture !== undefined ||\n mat.ior !== undefined ||\n mat.thicknessFactor !== undefined ||\n mat.thicknessTexture !== undefined ||\n mat.attenuationColor !== undefined ||\n mat.attenuationDistance !== undefined;\n if (transmission) {\n // Transmission/volume keeps its existing paired backdrop ABI. The\n // producer may leave either value at its neutral fallback, but the pair\n // remains part of the pre-existing transmission root contract.\n for (const name of STANDARD_TRANSMISSION_PARAMETER_NAMES) names.add(name);\n }\n\n return {\n names,\n extended:\n clearcoat ||\n anisotropy ||\n sheen ||\n iridescence ||\n transmission ||\n mat.specularTexture !== undefined ||\n mat.specularColorTexture !== undefined,\n };\n}\n\nexport function validateMaterialUvSets(\n mat: GltfMaterialIr,\n primitive: string,\n availableSets: readonly number[],\n): Result<void, MaterialError> {\n const available = new Set(availableSets);\n const slots: readonly [MaterialTextureSlot, GltfTextureInfoIr | number | undefined][] = [\n ['baseColorTexture', mat.baseColorTexture],\n ['metallicRoughnessTexture', mat.metallicRoughnessTexture],\n ['normalTexture', mat.normalTexture],\n ['occlusionTexture', mat.occlusionTexture],\n ['emissiveTexture', mat.emissiveTexture],\n ['transmissionTexture', mat.transmissionTexture],\n ['thicknessTexture', mat.thicknessTexture],\n ['clearcoatTexture', mat.clearcoatTexture],\n ['clearcoatRoughnessTexture', mat.clearcoatRoughnessTexture],\n ['clearcoatNormalTexture', mat.clearcoatNormalTexture],\n ['anisotropyTexture', mat.anisotropyTexture],\n ['sheenColorTexture', mat.sheenColorTexture],\n ['sheenRoughnessTexture', mat.sheenRoughnessTexture],\n ['iridescenceTexture', mat.iridescenceTexture],\n ['iridescenceThicknessTexture', mat.iridescenceThicknessTexture],\n ['specularTexture', mat.specularTexture],\n ['specularColorTexture', mat.specularColorTexture],\n ];\n for (const [slot, rawBinding] of slots) {\n const binding = textureInfo(rawBinding);\n if (binding === undefined) continue;\n const requestedSet = binding.texCoord ?? 0;\n if (!available.has(requestedSet)) {\n return err(\n createMaterialError('gltf-material-uv-set-missing', {\n material: mat.name ?? '<unnamed>',\n primitive,\n slot,\n requestedSet,\n availableSets,\n }),\n );\n }\n }\n return ok(undefined);\n}\n\nexport function validateMaterialTangentInputs(\n mat: GltfMaterialIr,\n mesh: GltfMeshIr,\n layer = 'clearcoat',\n): Result<void, MaterialError> {\n // Anisotropy changes the base GGX lobe even when it has no texture map, so\n // its tangent direction is part of the scalar layer contract. Select UV 0\n // for the scalar-only form; a mapped form keeps the map's explicit UV set.\n const anisotropyDeclared =\n mat.anisotropyStrength !== undefined ||\n mat.anisotropyRotation !== undefined ||\n mat.anisotropyTexture !== undefined;\n const tangentSlot = anisotropyDeclared\n ? { layer: 'anisotropy', info: mat.anisotropyTexture }\n : mat.clearcoatNormalTexture !== undefined\n ? { layer: 'clearcoat', info: mat.clearcoatNormalTexture }\n : undefined;\n if (tangentSlot === undefined) return ok(undefined);\n const selected = textureInfo(tangentSlot.info);\n const uvSet = selected?.texCoord ?? 0;\n const uv = mesh[`texcoord${uvSet === 0 ? '0' : uvSet}` as keyof GltfMeshIr];\n const attributes = ['NORMAL', `TEXCOORD_${uvSet}`, 'TANGENT'];\n const fail = (reason: string): Result<void, MaterialError> =>\n err(\n createMaterialError('material-tangent-required', {\n code: 'material-tangent-required',\n material: mat.name ?? '<unnamed>',\n mesh: mesh.name ?? '<unnamed>',\n layer: tangentSlot.layer ?? layer,\n uv: `TEXCOORD_${uvSet}`,\n attributes,\n reason,\n }),\n );\n if (mesh.tangents !== undefined) {\n if (\n mesh.tangents.length !== (mesh.positions.length / 3) * 4 ||\n mesh.tangents.some((value) => !Number.isFinite(value))\n ) {\n return fail('imported TANGENT must be finite vec4 per vertex');\n }\n return ok(undefined);\n }\n if (mesh.normals === undefined) return fail('NORMAL is required to generate tangent');\n if (!(uv instanceof Float32Array))\n return fail('the selected UV set is required to generate tangent');\n const generated = computeTangentVec4(mesh.positions, mesh.normals, uv, mesh.indices);\n if (!generated.ok) {\n const detail = generated.error.detail;\n const reason =\n detail !== undefined && 'reason' in detail\n ? String(detail.reason)\n : 'tangent producer rejected topology';\n return fail(reason);\n }\n return ok(undefined);\n}\n\n/** Convert a parsed GltfMaterialIr into a standard-root derived MaterialAsset. */\nexport function toMaterialAsset(mat: GltfMaterialIr, ctx?: MaterialBridgeContext): MaterialAsset {\n const rootContract = standardRootParameterNames(mat);\n const values: Record<string, NonNullable<MaterialAsset['values']>[string]> = {\n baseColor: mat.baseColorFactor,\n metallic: mat.metallicFactor,\n roughness: mat.roughnessFactor,\n };\n if (mat.emissiveFactor !== undefined) {\n values.emissive = mat.emissiveFactor;\n values.emissiveIntensity = 1;\n }\n const textureSlots: readonly [MaterialTextureSlot, GltfTextureInfoIr | number | undefined][] = [\n ['baseColorTexture', mat.baseColorTexture],\n ['metallicRoughnessTexture', mat.metallicRoughnessTexture],\n ['normalTexture', mat.normalTexture],\n ['occlusionTexture', mat.occlusionTexture],\n ['emissiveTexture', mat.emissiveTexture],\n ['transmissionTexture', mat.transmissionTexture],\n ['thicknessTexture', mat.thicknessTexture],\n ['clearcoatTexture', mat.clearcoatTexture],\n ['clearcoatRoughnessTexture', mat.clearcoatRoughnessTexture],\n ['clearcoatNormalTexture', mat.clearcoatNormalTexture],\n ['anisotropyTexture', mat.anisotropyTexture],\n ['sheenColorTexture', mat.sheenColorTexture],\n ['sheenRoughnessTexture', mat.sheenRoughnessTexture],\n ['iridescenceTexture', mat.iridescenceTexture],\n ['iridescenceThicknessTexture', mat.iridescenceThicknessTexture],\n ['specularTexture', mat.specularTexture],\n ['specularColorTexture', mat.specularColorTexture],\n ];\n for (const [slot, info] of textureSlots) {\n const value = textureValue(info, slot, ctx);\n if (value !== undefined) values[slot] = value;\n }\n if (mat.occlusionTexture !== undefined && values.occlusionStrength === undefined) {\n values.occlusionStrength = 1;\n }\n if (rootContract.extended && rootContract.names.has('transmission')) {\n values.transmission = mat.transmissionFactor ?? 0;\n values.ior = mat.ior ?? 1.5;\n values.thickness = mat.thicknessFactor ?? 0;\n values.attenuationColor = mat.attenuationColor ?? [1, 1, 1];\n if (mat.attenuationDistance !== undefined) values.attenuationDistance = mat.attenuationDistance;\n }\n if (rootContract.names.has('clearcoat')) {\n values.clearcoat = mat.clearcoatFactor ?? 0;\n values.clearcoatRoughness = mat.clearcoatRoughnessFactor ?? 0;\n }\n const clearcoatNormal = textureInfo(mat.clearcoatNormalTexture) as\n | (GltfTextureInfoIr & { readonly scale?: number })\n | undefined;\n if (clearcoatNormal?.scale !== undefined) values.clearcoatNormalScale = clearcoatNormal.scale;\n if (rootContract.names.has('anisotropyStrength')) {\n values.anisotropyStrength = mat.anisotropyStrength ?? 0;\n values.anisotropyRotation = mat.anisotropyRotation ?? 0;\n }\n if (rootContract.names.has('sheenColor')) {\n values.sheenColor = mat.sheenColorFactor ?? [0, 0, 0];\n values.sheenRoughness = mat.sheenRoughnessFactor ?? 0;\n }\n if (rootContract.names.has('iridescence')) {\n values.iridescence = mat.iridescenceFactor ?? 0;\n values.iridescenceIor = mat.iridescenceIor ?? 1.3;\n values.iridescenceThicknessMinimum = mat.iridescenceThicknessMinimum ?? 100;\n values.iridescenceThicknessMaximum = mat.iridescenceThicknessMaximum ?? 400;\n }\n if (mat.specularFactor !== undefined) values.specular = mat.specularFactor;\n if (mat.specularColorFactor !== undefined) values.specularColor = mat.specularColorFactor;\n\n const module = ctx?.skinned === true ? 'forgeax::pbr-skin' : 'forgeax::default-standard-pbr';\n\n const isMask = mat.alphaMode === 'MASK';\n const alphaCutoff = isMask ? (mat.alphaCutoff ?? 0.5) : undefined;\n if (alphaCutoff !== undefined) values.alphaCutoff = alphaCutoff;\n\n // glTF BLEND uses straight alpha and does not write depth.\n const isBlend = mat.alphaMode === 'BLEND';\n const straightAlphaBlend = {\n color: {\n srcFactor: 'src-alpha' as const,\n dstFactor: 'one-minus-src-alpha' as const,\n operation: 'add' as const,\n },\n alpha: {\n srcFactor: 'one' as const,\n dstFactor: 'one-minus-src-alpha' as const,\n operation: 'add' as const,\n },\n };\n\n // feat-city-glb Bug 5: transparent (BLEND) materials read but do NOT write\n // depth (`depthWriteEnabled: false`), matching the engine's own transparent\n // convention (learn-render 4.3 blending window material). glTF decals are\n // frequently coplanar with the opaque surface they overlay (e.g. a crosswalk\n // decal on the road); writing depth would z-fight / self-occlude. Back-to-\n // front ordering is handled by the Transparent queue + transparent sort.\n const pass = {\n name: 'Forward',\n program: { module },\n renderState: {\n tags: { LightMode: 'Forward' },\n queue: (isBlend ? 3000 : isMask ? 2450 : 2000) as RenderQueue,\n ...(isBlend || isMask || mat.doubleSided === true\n ? {\n ...(isBlend ? { blend: straightAlphaBlend, depthWriteEnabled: false } : {}),\n ...(mat.doubleSided === true ? { cullMode: 'none' as const } : {}),\n }\n : {}),\n },\n };\n\n const child = !rootContract.extended && ctx?.standardRootGuid !== undefined;\n return {\n kind: 'material',\n ...(child\n ? { parent: ctx.standardRootGuid }\n : {\n colorSpace: 'linear' as const,\n passes: [pass] as [typeof pass, ...(typeof pass)[]],\n parameters: standardMaterialParameters(rootContract.names),\n }),\n values,\n };\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","// 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","// extract-image-bytes.ts - resolve glTF `images[<imageIndex>]` into raw\n// PNG / JPEG bytes (feat-20260608 M3 D-6 / requirements AC-08 + AC-09 + AC-10).\n//\n// The gltfImporter walks `images[]` and funnels three image source paths\n// through a single decode seam:\n// (a) bufferView : slice the named buffer at the bufferView range\n// (b) data: URI : base64-decode the URI payload\n// (c) external URI : ctx.readSibling(uri) reads the file co-located\n// with the .gltf source\n//\n// This module owns the byte-extraction (no decoding); decoding is the job of\n// ctx.decodeImage (D-1 seam: gltfImporter never imports\n// `@forgeax/engine-image` directly). On any failure the caller produces a\n// `gltf-image-extract-failed` GltfError carrying { imageIndex, source,\n// reason }.\n//\n// Why not reuse parse-gltf.ts's buffer resolution? parseGltf.ts encapsulates\n// buffer / bufferView decoding inside `parseGltfWithBin` and never surfaces\n// the byte arrays. Re-running that machinery for image extraction would\n// double the work; instead the gltfImporter parses the doc twice (parseGltf\n// for the IR, this helper for the raw bytes) — both passes are O(file\n// size) and the importer only runs at build time.\n\nimport type { ImportContext, ImportError as ImportErrorType } from '@forgeax/engine-types';\nimport { dataUriBase64Payload, decodeBase64 } from './data-uri.js';\nimport { parseGlbChunks } from './parse-glb-chunks.js';\n\n/** Source of an image: matches `GltfImageExtractFailedDetail.source`. */\nexport type ImageSourceKind = 'bufferView' | 'data-uri' | 'external-uri';\n\n/** One extracted image: bytes + the source kind that produced them. */\nexport interface ExtractedImage {\n readonly bytes: Uint8Array;\n readonly mimeType: 'image/png' | 'image/jpeg';\n readonly source: ImageSourceKind;\n}\n\n/**\n * Failure shape — the importer wraps this in a `gltf-image-extract-failed`\n * GltfError. `source` may be undefined when the image row is malformed\n * (no uri / no bufferView), so the importer can name 'bufferView' (most\n * common) by default.\n */\nexport interface ExtractFailure {\n readonly imageIndex: number;\n readonly source: ImageSourceKind;\n readonly reason: string;\n}\n\nconst DATA_URI_MIME_RE = /^data:([^;,]+)(?:;[^,;]+)*;base64,/;\n\n/** Pull the source-read-failed reason out of an ImportError without\n * widening the discriminated union — the caller only ever sees\n * source-read-failed here (readSibling's only failure shape). The\n * ImportError class carries a structurally typed `.detail` field that does\n * not auto-narrow on the `.code` discriminator, so we read `.message`\n * which the class composes from `expected: ...; reason: ...`. */\nfunction describeImportError(err: ImportErrorType): string {\n return err.message;\n}\n\n/** Pick PNG vs JPEG from declared mimeType + magic-byte fallback. */\nfunction classifyMime(\n declaredMime: string | undefined,\n bytes: Uint8Array,\n): 'image/png' | 'image/jpeg' | undefined {\n if (declaredMime === 'image/png' || declaredMime === 'image/jpeg') return declaredMime;\n if (\n bytes.length >= 8 &&\n bytes[0] === 0x89 &&\n bytes[1] === 0x50 &&\n bytes[2] === 0x4e &&\n bytes[3] === 0x47\n ) {\n return 'image/png';\n }\n if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) {\n return 'image/jpeg';\n }\n return undefined;\n}\n\ninterface BufferViewJsonSlim {\n readonly buffer: number;\n readonly byteOffset?: number;\n readonly byteLength: number;\n}\n\ninterface ImageJsonSlim {\n readonly uri?: string;\n readonly mimeType?: string;\n readonly bufferView?: number;\n}\n\ninterface BufferJsonSlim {\n readonly uri?: string;\n readonly byteLength: number;\n}\n\ninterface RootJsonSlim {\n readonly images?: readonly ImageJsonSlim[];\n readonly bufferViews?: readonly BufferViewJsonSlim[];\n readonly buffers?: readonly BufferJsonSlim[];\n}\n\n/**\n * Extract raw image bytes for every `images[]` row in the parsed glTF doc.\n *\n * @param sourceBytes the original .glb / .gltf file bytes (the GLB BIN\n * chunk is reconstructed from these for buffer-0 lookups).\n * @param sourcePath the meta.source path; used only for diagnostics\n * (parseGlbChunks errors carry it through).\n * @param ctx the ImportContext — reused for `readSibling` (external\n * buffer .bin / external image .png/.jpg). data: URIs do not call ctx.\n *\n * Returns a Map<imageIndex, ExtractedImage> with one entry per resolved\n * image. Rows that fail to extract are returned in `failures[]` so the\n * caller can emit one `gltf-image-extract-failed` per failure (single\n * failure does not abort the whole importer — the runner's GUID iron-law\n * check then surfaces missing image GUIDs as a structured outage instead\n * of the silent white-box render).\n */\nexport async function extractImageBytes(\n sourceBytes: Uint8Array,\n sourcePath: string,\n ctx: ImportContext,\n): Promise<{\n readonly extracted: ReadonlyMap<number, ExtractedImage>;\n readonly failures: readonly ExtractFailure[];\n}> {\n const isGlb = sourcePath.toLowerCase().endsWith('.glb');\n let json: RootJsonSlim;\n let glbBin: Uint8Array | undefined;\n\n if (isGlb) {\n const ab = sourceBytes.buffer.slice(\n sourceBytes.byteOffset,\n sourceBytes.byteOffset + sourceBytes.byteLength,\n ) as ArrayBuffer;\n const chunks = parseGlbChunks(ab, sourcePath);\n if (!chunks.ok) {\n return {\n extracted: new Map(),\n failures: [\n {\n imageIndex: -1,\n source: 'bufferView',\n reason: `GLB chunk parse failed: ${chunks.error.code}`,\n },\n ],\n };\n }\n try {\n json = JSON.parse(new TextDecoder().decode(chunks.value.jsonChunk)) as RootJsonSlim;\n } catch (e) {\n return {\n extracted: new Map(),\n failures: [\n {\n imageIndex: -1,\n source: 'bufferView',\n reason: `GLB JSON parse failed: ${e instanceof Error ? e.message : String(e)}`,\n },\n ],\n };\n }\n glbBin = chunks.value.binChunk;\n } else {\n try {\n json = JSON.parse(new TextDecoder().decode(sourceBytes)) as RootJsonSlim;\n } catch (e) {\n return {\n extracted: new Map(),\n failures: [\n {\n imageIndex: -1,\n source: 'bufferView',\n reason: `gltf JSON parse failed: ${e instanceof Error ? e.message : String(e)}`,\n },\n ],\n };\n }\n }\n\n const images = json.images ?? [];\n const bufferViews = json.bufferViews ?? [];\n const buffersJson = json.buffers ?? [];\n const extracted = new Map<number, ExtractedImage>();\n const failures: ExtractFailure[] = [];\n\n // Resolve buffers (lazy: only buffers actually referenced by images get fetched).\n const buffersCache = new Map<number, Uint8Array | { readonly error: ImportErrorType | string }>();\n async function getBuffer(bufferIndex: number): Promise<Uint8Array | { readonly error: string }> {\n const cached = buffersCache.get(bufferIndex);\n if (cached !== undefined) {\n if (cached instanceof Uint8Array) return cached;\n const e = cached.error;\n return { error: typeof e === 'string' ? e : e.message };\n }\n const bufJson = buffersJson[bufferIndex];\n if (bufJson === undefined) {\n const reason = `buffer index ${bufferIndex} out of range (have ${buffersJson.length})`;\n buffersCache.set(bufferIndex, { error: reason });\n return { error: reason };\n }\n if (bufJson.uri === undefined) {\n // GLB BIN chunk slot — buffer-0.\n if (glbBin === undefined) {\n const reason = `buffer ${bufferIndex} has no uri and no GLB BIN chunk available`;\n buffersCache.set(bufferIndex, { error: reason });\n return { error: reason };\n }\n buffersCache.set(bufferIndex, glbBin);\n return glbBin;\n }\n const dataPayload = dataUriBase64Payload(bufJson.uri);\n if (dataPayload !== undefined) {\n try {\n const bytes = decodeBase64(dataPayload);\n buffersCache.set(bufferIndex, bytes);\n return bytes;\n } catch (e) {\n const reason = `buffer ${bufferIndex} data URI base64 decode failed: ${e instanceof Error ? e.message : String(e)}`;\n buffersCache.set(bufferIndex, { error: reason });\n return { error: reason };\n }\n }\n const sib = await ctx.readSibling(bufJson.uri);\n if (!sib.ok) {\n const reason = `external buffer \"${bufJson.uri}\" read failed: ${describeImportError(sib.error)}`;\n buffersCache.set(bufferIndex, { error: reason });\n return { error: reason };\n }\n buffersCache.set(bufferIndex, sib.value);\n return sib.value;\n }\n\n for (let i = 0; i < images.length; i++) {\n const img = images[i];\n if (img === undefined) continue;\n\n if (img.bufferView !== undefined) {\n const bv = bufferViews[img.bufferView];\n if (bv === undefined) {\n failures.push({\n imageIndex: i,\n source: 'bufferView',\n reason: `bufferView index ${img.bufferView} out of range`,\n });\n continue;\n }\n const buf = await getBuffer(bv.buffer);\n if (!(buf instanceof Uint8Array)) {\n failures.push({ imageIndex: i, source: 'bufferView', reason: buf.error });\n continue;\n }\n const off = bv.byteOffset ?? 0;\n const len = bv.byteLength;\n if (off + len > buf.byteLength) {\n failures.push({\n imageIndex: i,\n source: 'bufferView',\n reason: `bufferView ${img.bufferView} byte range [${off}..${off + len}) exceeds buffer ${bv.buffer} length ${buf.byteLength}`,\n });\n continue;\n }\n const bytes = buf.subarray(off, off + len);\n const mime = classifyMime(img.mimeType, bytes);\n if (mime === undefined) {\n failures.push({\n imageIndex: i,\n source: 'bufferView',\n reason: `unsupported / unrecognised mime (declared \"${img.mimeType ?? '<absent>'}\", magic byte sniff failed)`,\n });\n continue;\n }\n extracted.set(i, { bytes: new Uint8Array(bytes), mimeType: mime, source: 'bufferView' });\n continue;\n }\n\n if (img.uri !== undefined) {\n const dataPayload = dataUriBase64Payload(img.uri);\n if (dataPayload !== undefined) {\n let bytes: Uint8Array;\n try {\n bytes = decodeBase64(dataPayload);\n } catch (e) {\n failures.push({\n imageIndex: i,\n source: 'data-uri',\n reason: `base64 decode failed: ${e instanceof Error ? e.message : String(e)}`,\n });\n continue;\n }\n const mimeMatch = DATA_URI_MIME_RE.exec(img.uri);\n const declaredMime = mimeMatch?.[1] ?? img.mimeType;\n const mime = classifyMime(declaredMime, bytes);\n if (mime === undefined) {\n failures.push({\n imageIndex: i,\n source: 'data-uri',\n reason: `data: URI mime \"${declaredMime ?? '<absent>'}\" not png/jpeg`,\n });\n continue;\n }\n extracted.set(i, { bytes, mimeType: mime, source: 'data-uri' });\n continue;\n }\n const sib = await ctx.readSibling(img.uri);\n if (!sib.ok) {\n failures.push({\n imageIndex: i,\n source: 'external-uri',\n reason: `external URI \"${img.uri}\" read failed: ${describeImportError(sib.error)}`,\n });\n continue;\n }\n const mime = classifyMime(img.mimeType, sib.value);\n if (mime === undefined) {\n failures.push({\n imageIndex: i,\n source: 'external-uri',\n reason: `external URI \"${img.uri}\" mime not png/jpeg (declared \"${img.mimeType ?? '<absent>'}\", magic byte sniff failed)`,\n });\n continue;\n }\n extracted.set(i, {\n bytes: new Uint8Array(sib.value),\n mimeType: mime,\n source: 'external-uri',\n });\n continue;\n }\n\n failures.push({\n imageIndex: i,\n source: 'bufferView',\n reason: 'image row has neither bufferView nor uri',\n });\n }\n\n return { extracted, failures };\n}\n","// image-color-space.ts - sRGB / linear classifier for glTF images\n// (feat-20260608 M3 D-3 / requirements AC-08 + AC-13 + C-3).\n//\n// glTF 2.0 spec section 6.2 (\"Material → Texture and Sampler\") names which\n// texture slots are colour-encoded vs data-encoded:\n// - sRGB : baseColorTexture, emissiveTexture, sheenColorTexture,\n// specularColorTexture\n// - linear : metallicRoughnessTexture, normalTexture, occlusionTexture,\n// transmission/volume/clearcoat/anisotropy/sheen-roughness/\n// iridescence/specular-weight data textures\n// We pre-scan the doc so the gltfImporter knows each `images[]` row's\n// colorSpace before decoding (TextureAsset.colorSpace + .format derive\n// from this).\n//\n// Conflict resolution (requirements section 8 edge cases): when the same\n// glTF image is bound to multiple textures whose colour expectations\n// disagree, sRGB wins. baseColor leakage into a normal slot is far worse\n// than the inverse, and bevy_gltf takes the same stance (knowledge-base /\n// research finding §5.6).\n//\n// Orphan images (declared in `images[]` but unreferenced by any\n// `textures[]` entry) default to linear (no colour-encoded purpose\n// inferable; AC-13).\n//\n// Pure function, no I/O. Input = the parts of the parsed GltfDoc that\n// matter (images count, textures, materials); output = a Map keyed by\n// the image array index.\n\nexport type ImageColorSpaceSrgbOrLinear = 'srgb' | 'linear';\n\ntype TextureBinding = number | { readonly texture: number };\n\n/** Slim view of a parsed material the classifier reads (subset of MaterialIr). */\nexport interface MaterialColorSpaceInput {\n readonly baseColorTexture?: TextureBinding;\n readonly metallicRoughnessTexture?: TextureBinding;\n readonly normalTexture?: TextureBinding;\n readonly emissiveTexture?: TextureBinding;\n readonly occlusionTexture?: TextureBinding;\n readonly transmissionTexture?: TextureBinding;\n readonly thicknessTexture?: TextureBinding;\n readonly clearcoatTexture?: TextureBinding;\n readonly clearcoatRoughnessTexture?: TextureBinding;\n readonly clearcoatNormalTexture?: TextureBinding;\n readonly anisotropyTexture?: TextureBinding;\n readonly sheenColorTexture?: TextureBinding;\n readonly sheenRoughnessTexture?: TextureBinding;\n readonly iridescenceTexture?: TextureBinding;\n readonly iridescenceThicknessTexture?: TextureBinding;\n readonly specularTexture?: TextureBinding;\n readonly specularColorTexture?: TextureBinding;\n}\n\n/** Slim view of a parsed `textures[]` row. */\nexport interface TextureColorSpaceInput {\n readonly source: number;\n}\n\n/**\n * Inputs for {@link deriveTextureColorSpace}: just the parts of the parsed\n * doc that the classifier reads. Decoupled from `GltfDoc` so the helper is\n * trivially testable without building a full doc.\n */\nexport interface DeriveTextureColorSpaceInput {\n readonly imageCount: number;\n readonly textures: readonly TextureColorSpaceInput[] | undefined;\n readonly materials: readonly MaterialColorSpaceInput[];\n}\n\n/**\n * Walk the materials, follow each texture-slot binding back to the image\n * it references, and produce `Map<imageIndex, 'srgb' | 'linear'>`. Slots\n * disagreeing on the same image resolve to sRGB (see module header for\n * the rationale). Orphan images default to linear.\n */\nexport function deriveTextureColorSpace(\n input: DeriveTextureColorSpaceInput,\n): Map<number, ImageColorSpaceSrgbOrLinear> {\n const result = new Map<number, ImageColorSpaceSrgbOrLinear>();\n const textures = input.textures ?? [];\n\n function imageOfTexture(binding: TextureBinding | undefined): number | undefined {\n if (binding === undefined) return undefined;\n const textureIndex = typeof binding === 'number' ? binding : binding.texture;\n const tex = textures[textureIndex];\n if (tex === undefined) return undefined;\n return tex.source;\n }\n\n function record(imageIndex: number | undefined, colorSpace: ImageColorSpaceSrgbOrLinear): void {\n if (imageIndex === undefined) return;\n const prior = result.get(imageIndex);\n if (prior === undefined) {\n result.set(imageIndex, colorSpace);\n return;\n }\n if (prior === 'srgb' || colorSpace === 'srgb') {\n result.set(imageIndex, 'srgb');\n }\n }\n\n for (const mat of input.materials) {\n record(imageOfTexture(mat.baseColorTexture), 'srgb');\n record(imageOfTexture(mat.emissiveTexture), 'srgb');\n record(imageOfTexture(mat.sheenColorTexture), 'srgb');\n record(imageOfTexture(mat.specularColorTexture), 'srgb');\n record(imageOfTexture(mat.metallicRoughnessTexture), 'linear');\n record(imageOfTexture(mat.normalTexture), 'linear');\n record(imageOfTexture(mat.occlusionTexture), 'linear');\n record(imageOfTexture(mat.transmissionTexture), 'linear');\n record(imageOfTexture(mat.thicknessTexture), 'linear');\n record(imageOfTexture(mat.clearcoatTexture), 'linear');\n record(imageOfTexture(mat.clearcoatRoughnessTexture), 'linear');\n record(imageOfTexture(mat.clearcoatNormalTexture), 'linear');\n record(imageOfTexture(mat.anisotropyTexture), 'linear');\n record(imageOfTexture(mat.sheenRoughnessTexture), 'linear');\n record(imageOfTexture(mat.iridescenceTexture), 'linear');\n record(imageOfTexture(mat.iridescenceThicknessTexture), 'linear');\n record(imageOfTexture(mat.specularTexture), 'linear');\n }\n\n for (let i = 0; i < input.imageCount; i++) {\n if (!result.has(i)) {\n result.set(i, 'linear');\n }\n }\n\n return result;\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","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-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)\n// - charter P3 (fail-fast on invalid data)\n\nimport { parseConservativeAnimatedBounds } 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/** 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 /** Producer-authored conservative animated local bounds when supplied. */\n readonly bounds?: Float32Array;\n}\n\ninterface SkinJson {\n readonly name?: string;\n readonly joints: readonly number[];\n readonly inverseBindMatrices?: number;\n /** glTF source metadata authored by the ForgeaX asset producer. */\n readonly extras?: {\n readonly forgeax?: {\n readonly conservativeAnimatedBounds?: unknown;\n };\n };\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 const bounds = parseConservativeAnimatedBounds(\n skin.extras?.forgeax?.conservativeAnimatedBounds,\n );\n records.push({\n jointCount: joints.length,\n inverseBindMatrices: ibm,\n jointPaths,\n ...(bounds === undefined ? {} : { bounds }),\n });\n }\n\n return ok(records);\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 readonly extras?: {\n readonly forgeax?: {\n readonly conservativeAnimatedBounds?: unknown;\n };\n };\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","// gltf-importer.ts - the build-time gltfImporter (feat-20260603-asset-import-loader-injection M2 / w19,\n// extended in feat-20260608 M3 w14 with the texture pipeline: three image\n// source paths funnelled through the ImportContext decodeImage seam).\n//\n// The `{ key: 'gltf', import }` Importer the @forgeax/engine-import runner\n// dispatches a `*.meta.json` with `importer: 'gltf'` to. It reads the source\n// bytes via `ctx.readSource()`, parses them to a `GltfDoc` (parseGltf / parseGlb),\n// and converts each declared sub-asset (mesh / material / scene / texture /\n// skin / animation-clip) into an `ImportedAsset` POD stamped with the\n// meta-declared GUID (GUID import-stable iron law: GUIDs come from\n// `ctx.subAssets[]`, never minted here).\n//\n// Texture pipeline (M3 D-1 / D-3 / D-6, requirements AC-08 / 09 / 10 / 11 /\n// 12 / 13): for every glTF `images[]` row the importer extracts the raw\n// PNG / JPEG bytes from one of three sources (bufferView slice in\n// .glb / data: URI in .gltf / external URI sibling read), funnels them\n// through `ctx.decodeImage` (the only seam to @forgeax/engine-image — a\n// grep gate enforces zero static `from '@forgeax/engine-image'` lines in\n// this package), and emits a `kind: 'texture'` ImportedAsset stamped with\n// the meta-declared GUID. The colorSpace is pre-derived per-image by\n// `deriveTextureColorSpace` (D-3 walk of material slot bindings).\n//\n// Material refs[]: each material's emitted ImportedAsset carries the GUIDs\n// of every texture sub-asset its slots reference, so the runner builds the\n// scene/material -> texture cross-edge needed by AC-11 / AC-19.\n//\n// Sub-asset -> GUID mapping: `ctx.subAssets[]` carries one entry per declared\n// sub-asset with `{ guid, sourceIndex, kind }`. The importer indexes into the\n// parsed doc by (kind, sourceIndex) and emits the corresponding POD under the\n// declared GUID. A sub-asset kind with no doc counterpart (or a sourceIndex out\n// of range) is skipped; the runner's GUID iron-law check then surfaces the\n// gap as `import-produced-no-assets`. A texture sub-asset that fails byte\n// extraction surfaces as `gltf-image-extract-failed` (D-6).\n\nimport { deriveDefaultLodScreenCoverages } from '@forgeax/engine-import';\nimport { packMeshBinV4 } from '@forgeax/engine-import/mesh-bin';\nimport { AssetGuid as AssetGuidCodec } from '@forgeax/engine-pack/guid';\nimport type {\n AssetGuid,\n AssetRef,\n Handle,\n ImportContext,\n ImportedAsset,\n Importer,\n ImportResult,\n MaterialTextureValue,\n MaterialValue,\n MeshAsset,\n MeshMaterialSlotTopologyEntry,\n} from '@forgeax/engine-types';\nimport {\n IMPORT_ERROR_HINTS,\n ImportError,\n readConservativeAnimatedBounds,\n reconcileMeshMaterialSlotTopology,\n resolveMeshMaterialSlotDefaultGuid,\n toShared,\n} from '@forgeax/engine-types';\nimport {\n gltfDocToSceneAsset,\n meshIrToMeshAsset,\n toMaterialAsset,\n validateMaterialTangentInputs,\n validateMaterialUvSets,\n} from './bridge.js';\nimport { gltfErr } from './errors.js';\nimport { extractImageBytes } from './extract-image-bytes.js';\nimport { deriveTextureColorSpace } from './image-color-space.js';\nimport type { GltfBufferViewDecodeCapability } from './meshopt-decode.js';\nimport type { GltfDoc, GltfMaterialIr, GltfTextureInfoIr } from './parse-gltf.js';\nimport { parseGlbForImporter, parseGltfForImporter } from './parse-gltf.js';\n\ntype ParseDocResult =\n | { readonly ok: true; readonly value: GltfDoc }\n | { readonly ok: false; readonly error: ImportError };\nfunction isGlbBytes(source: string): boolean {\n return source.toLowerCase().endsWith('.glb');\n}\n\nfunction publishesCatalogProduct(input: {\n readonly importSettings: Readonly<Record<string, unknown>>;\n}): boolean {\n return input.importSettings.geometry !== 'procedural';\n}\n\nfunction applyImportSettingsBounds(\n doc: GltfDoc,\n importSettings: Readonly<Record<string, unknown>>,\n): GltfDoc {\n let changed = false;\n const skeletons = doc.skeletons.map((record, sourceIndex) => {\n // Source extras are the primary producer path. The sidecar row is an\n // explicit external-producer override for sources whose authoring tool\n // cannot carry ForgeaX extras; neither path derives a bind-pose AABB.\n const bounds = readConservativeAnimatedBounds(importSettings, sourceIndex);\n if (bounds === undefined || record.bounds !== undefined) return record;\n changed = true;\n return { ...record, bounds };\n });\n return changed ? { ...doc, skeletons } : doc;\n}\n\nfunction previousMaterialSlotTopology(\n ctx: ImportContext,\n meshSourceKey: string | undefined,\n): readonly MeshMaterialSlotTopologyEntry[] | undefined {\n if (meshSourceKey === undefined) return undefined;\n const value = ctx.sourceOverrides?.[meshSourceKey]?.materialSlots;\n if (value === undefined) return undefined;\n if (!Array.isArray(value)) {\n throw new ImportError({\n code: 'invalid-source-override-payload',\n expected: `${meshSourceKey}.materialSlots to be an array`,\n hint: IMPORT_ERROR_HINTS['invalid-source-override-payload'],\n detail: {\n sourceKey: meshSourceKey,\n declaredSourceKeys: ctx.subAssets.flatMap((entry) => entry.sourceKey ?? []),\n reason: 'materialSlots is not an array',\n },\n });\n }\n const slots: MeshMaterialSlotTopologyEntry[] = [];\n for (const [index, raw] of value.entries()) {\n if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {\n throw new ImportError({\n code: 'invalid-source-override-payload',\n expected: `${meshSourceKey}.materialSlots[${index}] to be an object`,\n hint: IMPORT_ERROR_HINTS['invalid-source-override-payload'],\n detail: {\n sourceKey: meshSourceKey,\n declaredSourceKeys: ctx.subAssets.flatMap((entry) => entry.sourceKey ?? []),\n reason: `materialSlots[${index}] is not an object`,\n },\n });\n }\n const slot = raw as Record<string, unknown>;\n if (typeof slot.slotName !== 'string' || slot.slotName.trim().length === 0) {\n throw new ImportError({\n code: 'invalid-source-override-payload',\n expected: `${meshSourceKey}.materialSlots[${index}].slotName to be non-empty`,\n hint: IMPORT_ERROR_HINTS['invalid-source-override-payload'],\n detail: {\n sourceKey: meshSourceKey,\n declaredSourceKeys: ctx.subAssets.flatMap((entry) => entry.sourceKey ?? []),\n reason: `materialSlots[${index}].slotName is invalid`,\n },\n });\n }\n slots.push({\n slotName: slot.slotName,\n ...(typeof slot.sourceKey === 'string' ? { sourceKey: slot.sourceKey } : {}),\n ...(typeof slot.defaultMaterialGuid === 'string'\n ? { defaultMaterialGuid: slot.defaultMaterialGuid }\n : {}),\n });\n }\n return slots;\n}\n\nfunction stabilizeMeshMaterialSlots(\n mesh: MeshAsset,\n ctx: ImportContext,\n meshGuid: string,\n meshSourceKey: string | undefined,\n): MeshAsset {\n const current = mesh.materialSlots.map(\n (slot): MeshMaterialSlotTopologyEntry => ({\n slotName: slot.slotName,\n ...(slot.sourceKey === undefined ? {} : { sourceKey: slot.sourceKey }),\n ...(slot.defaultMaterial === undefined\n ? {}\n : { defaultMaterialGuid: AssetGuidCodec.format(slot.defaultMaterial) }),\n }),\n );\n const reconciled = reconcileMeshMaterialSlotTopology(\n current,\n previousMaterialSlotTopology(ctx, meshSourceKey),\n );\n if (!reconciled.ok) {\n throw new ImportError({\n code: 'mesh-material-slot-topology-change',\n expected: `unambiguous material slot identity for mesh ${meshGuid}`,\n hint: IMPORT_ERROR_HINTS['mesh-material-slot-topology-change'],\n detail: {\n meshGuid,\n ...(meshSourceKey === undefined ? {} : { meshSourceKey }),\n previousIndices: reconciled.error.previousIndices,\n nextIndices: reconciled.error.nextIndices,\n },\n });\n }\n const authoredDefaults =\n meshSourceKey === undefined\n ? undefined\n : ctx.sourceOverrides?.[meshSourceKey]?.materialSlotDefaultOverrides;\n if (\n authoredDefaults !== undefined &&\n (authoredDefaults === null ||\n typeof authoredDefaults !== 'object' ||\n Array.isArray(authoredDefaults))\n ) {\n throw new ImportError({\n code: 'invalid-source-override-payload',\n expected: `${meshSourceKey}.materialSlotDefaultOverrides to be an object`,\n hint: IMPORT_ERROR_HINTS['invalid-source-override-payload'],\n detail: {\n sourceKey: meshSourceKey,\n declaredSourceKeys: [],\n reason: 'materialSlotDefaultOverrides is invalid',\n },\n });\n }\n const authoredBySlot = authoredDefaults as Readonly<Record<string, unknown>> | undefined;\n const activeStableSlots = new Set(reconciled.currentToStableSlot);\n return {\n ...mesh,\n submeshes: mesh.submeshes.map((submesh) => ({\n ...submesh,\n materialSlot: reconciled.currentToStableSlot[submesh.materialSlot] as number,\n })),\n materialSlots: reconciled.slots.map((slot, stableIndex) => {\n const active = activeStableSlots.has(stableIndex);\n const authored = authoredBySlot?.[slot.sourceKey ?? slot.slotName];\n const effectiveDefault = resolveMeshMaterialSlotDefaultGuid(\n slot,\n active && (typeof authored === 'string' || authored === null) ? authored : undefined,\n );\n const parsed =\n effectiveDefault === undefined ? undefined : AssetGuidCodec.parse(effectiveDefault);\n return {\n slotName: slot.slotName,\n ...(slot.sourceKey === undefined ? {} : { sourceKey: slot.sourceKey }),\n ...(active && parsed?.ok ? { defaultMaterial: parsed.value } : {}),\n };\n }),\n };\n}\n\nasync function parseDoc(\n source: string,\n bytes: Uint8Array,\n ctx: ImportContext,\n meshopt?: GltfBufferViewDecodeCapability,\n): Promise<ParseDocResult> {\n const ab = bytes.buffer.slice(\n bytes.byteOffset,\n bytes.byteOffset + bytes.byteLength,\n ) as ArrayBuffer;\n if (isGlbBytes(source)) {\n const res = await parseGlbForImporter(ab, source, meshopt === undefined ? {} : { meshopt });\n if (!res.ok) {\n if (res.error instanceof ImportError) return { ok: false, error: res.error };\n throw new Error(`parseGlb failed: ${res.error.code} ${res.error.expected}`);\n }\n return { ok: true, value: res.value };\n }\n let json: unknown;\n try {\n json = JSON.parse(new TextDecoder().decode(bytes));\n } catch (e) {\n throw new Error(`gltf JSON parse failed: ${e instanceof Error ? e.message : String(e)}`);\n }\n // External buffers: read sibling files relative to meta.source. data: URIs\n // are decoded inline by parseGltf; only external URIs reach the loader.\n const externalLoader = async (uri: string): Promise<ArrayBuffer> => {\n const sib = await ctx.readSibling(uri);\n if (!sib.ok) {\n throw new Error(`gltfImporter: external buffer \"${uri}\" read failed: ${sib.error.code}`);\n }\n return sib.value.buffer.slice(\n sib.value.byteOffset,\n sib.value.byteOffset + sib.value.byteLength,\n ) as ArrayBuffer;\n };\n const res = await parseGltfForImporter(\n json,\n externalLoader,\n source,\n meshopt === undefined ? {} : { meshopt },\n );\n if (!res.ok) {\n if (res.error instanceof ImportError) return { ok: false, error: res.error };\n throw new Error(`parseGltf failed: ${res.error.code} ${res.error.expected}`);\n }\n return { ok: true, value: res.value };\n}\n\ninterface HandleMaps {\n readonly meshHandles: Map<number, Handle<'MeshAsset', 'shared'>>;\n readonly materialHandles: Map<number, Handle<'MaterialAsset', 'shared'>>;\n readonly textureHandles: Map<number, Handle<'TextureAsset', 'shared'>>;\n readonly samplerHandles: Map<number, Handle<'SamplerAsset', 'shared'>>;\n readonly meshGuidByIndex: Map<number, string>;\n readonly materialGuidByIndex: Map<number, string>;\n readonly textureGuidByIndex: Map<number, string>;\n readonly samplerGuidByIndex: Map<number, string>;\n}\n\n/**\n * Build the gltf-index -> declared-GUID maps so scene refs resolve to the\n * sub-asset GUIDs (not runtime handles, which do not exist at import time).\n * The scene POD therefore carries deterministic synthetic handle slots; the\n * GUID cross-references are recorded on the ImportedAsset `refs[]`.\n *\n * Texture handles are seeded from `subAssets[]` of kind 'texture'; their\n * sourceIndex is the glTF `images[]` row (toAssetPack emits one texture\n * sub-asset per image row, so the mapping is image-index keyed even though\n * the field is named textureHandles for material binding readability).\n * GltfMaterialIr's `*Texture` fields hold glTF `textures[]` indices; the\n * importer dereferences `textures[i].source` to convert that into an image\n * index when stamping material handles.\n */\nfunction buildHandleMaps(\n subAssets: readonly { guid: string; sourceIndex: number; kind: string }[],\n doc: GltfDoc,\n): HandleMaps {\n const meshHandles = new Map<number, Handle<'MeshAsset', 'shared'>>();\n const materialHandles = new Map<number, Handle<'MaterialAsset', 'shared'>>();\n const textureHandles = new Map<number, Handle<'TextureAsset', 'shared'>>();\n const samplerHandles = new Map<number, Handle<'SamplerAsset', 'shared'>>();\n const meshGuidByIndex = new Map<number, string>();\n const materialGuidByIndex = new Map<number, string>();\n const textureGuidByIndex = new Map<number, string>();\n const samplerGuidByIndex = new Map<number, string>();\n // bug-20260610 layer 7c-2: scene's `refs[]` is concatenated in the order\n // [mesh sub-assets..., material sub-assets..., texture sub-assets...] (see\n // gltf-importer scene branch). The synthetic handle values stamped here\n // travel through `MeshFilter.assetHandle` / `MeshRenderer.materials[*]` and\n // are decoded at runtime as **refs[] indices** by parseScenePayload. So the\n // handle value MUST equal the slot offset in the eventual concat, NOT the\n // gltf source-index. The previous keying-by-sourceIndex worked accidentally\n // when there was exactly one mesh + N <= meshCount materials; it broke as\n // soon as materialIndex landed past the mesh-section boundary (Sponza:\n // materials[0]=0 -> refs[0] = mesh GUID, every submesh sampled the mesh\n // asset as its material -> single fallback unlit dispatch entry, no per-\n // primitive draws).\n let meshCursor = 0;\n let materialCursor = 0;\n for (const sub of subAssets) {\n if (sub.kind === 'mesh') {\n meshHandles.set(sub.sourceIndex, toShared<'MeshAsset'>(meshCursor));\n meshGuidByIndex.set(sub.sourceIndex, sub.guid);\n meshCursor += 1;\n } else if (sub.kind === 'material') {\n // material handles come AFTER all mesh refs in the concat.\n // The actual offset (= meshCount + materialCursor) is back-patched\n // below once we know meshCount.\n materialHandles.set(sub.sourceIndex, toShared<'MaterialAsset'>(materialCursor));\n materialGuidByIndex.set(sub.sourceIndex, sub.guid);\n materialCursor += 1;\n } else if (sub.kind === 'texture') {\n textureGuidByIndex.set(sub.sourceIndex, sub.guid);\n } else if (sub.kind === 'sampler') {\n samplerGuidByIndex.set(sub.sourceIndex, sub.guid);\n }\n }\n const meshCount = meshCursor;\n if (meshCount > 0) {\n for (const [k, v] of materialHandles) {\n const local = v as unknown as number;\n materialHandles.set(k, toShared<'MaterialAsset'>(local + meshCount));\n }\n }\n // For material binding (toMaterialAsset / values.<X>Texture) the handle\n // value is the texture's slot offset within the SAME asset's `refs[]` (which\n // is `materialTextureRefs` order, not the scene-level refs concat).\n // toMaterialAsset only consumes textureHandles to copy a number into the\n // values; the gltf-importer's later 7a fix-up rewrites those values\n // into refs[] indices for the runtime materialLoader. Keying by texIndex\n // and storing `tex.source` here matches the existing 7a path.\n const textures = doc.textures ?? [];\n for (let texIndex = 0; texIndex < textures.length; texIndex++) {\n const tex = textures[texIndex];\n if (tex === undefined) continue;\n if (textureGuidByIndex.has(tex.source)) {\n textureHandles.set(texIndex, toShared<'TextureAsset'>(tex.source));\n }\n }\n for (const [samplerIndex] of samplerGuidByIndex) {\n samplerHandles.set(samplerIndex, toShared<'SamplerAsset'>(samplerIndex));\n }\n return {\n meshHandles,\n materialHandles,\n textureHandles,\n samplerHandles,\n meshGuidByIndex,\n materialGuidByIndex,\n textureGuidByIndex,\n samplerGuidByIndex,\n };\n}\n\nfunction textureInfo(info: GltfTextureInfoIr | number | undefined): GltfTextureInfoIr | undefined {\n return info === undefined ? undefined : typeof info === 'number' ? { texture: info } : info;\n}\n\n/** Collect texture and sampler GUID refs for one material (AC-11 cross-edge). */\nexport function materialRefsForPack(\n mat: GltfMaterialIr,\n doc: GltfDoc,\n textureGuidByIndex: ReadonlyMap<number, string>,\n samplerGuidByIndex: ReadonlyMap<number, string> = new Map(),\n): readonly AssetRef[] {\n const refs: AssetRef[] = [];\n const textures = doc.textures ?? [];\n function pushRefsForSlot(info: GltfTextureInfoIr | number | undefined, fieldName: string): void {\n const binding = textureInfo(info);\n if (binding === undefined) return;\n const tex = textures[binding.texture];\n if (tex === undefined) return;\n const guid = textureGuidByIndex.get(tex.source);\n if (guid !== undefined) {\n refs.push({\n guid,\n sourceField: { componentName: '<material>', fieldName },\n });\n }\n if (binding.sampler !== undefined) {\n const samplerGuid = samplerGuidByIndex.get(binding.sampler);\n if (samplerGuid !== undefined) {\n refs.push({\n guid: samplerGuid,\n sourceField: { componentName: '<material>', fieldName: `${fieldName}.sampler` },\n });\n }\n }\n }\n pushRefsForSlot(mat.baseColorTexture, 'baseColorTexture');\n pushRefsForSlot(mat.metallicRoughnessTexture, 'metallicRoughnessTexture');\n pushRefsForSlot(mat.normalTexture, 'normalTexture');\n pushRefsForSlot(mat.occlusionTexture, 'occlusionTexture');\n pushRefsForSlot(mat.emissiveTexture, 'emissiveTexture');\n pushRefsForSlot(mat.transmissionTexture, 'transmissionTexture');\n pushRefsForSlot(mat.thicknessTexture, 'thicknessTexture');\n pushRefsForSlot(mat.clearcoatTexture, 'clearcoatTexture');\n pushRefsForSlot(mat.clearcoatRoughnessTexture, 'clearcoatRoughnessTexture');\n pushRefsForSlot(mat.clearcoatNormalTexture, 'clearcoatNormalTexture');\n pushRefsForSlot(mat.anisotropyTexture, 'anisotropyTexture');\n pushRefsForSlot(mat.sheenColorTexture, 'sheenColorTexture');\n pushRefsForSlot(mat.sheenRoughnessTexture, 'sheenRoughnessTexture');\n pushRefsForSlot(mat.iridescenceTexture, 'iridescenceTexture');\n pushRefsForSlot(mat.iridescenceThicknessTexture, 'iridescenceThicknessTexture');\n pushRefsForSlot(mat.specularTexture, 'specularTexture');\n pushRefsForSlot(mat.specularColorTexture, 'specularColorTexture');\n return refs;\n}\n\nfunction availableUvSets(mesh: GltfDoc['meshes'][number]): readonly number[] {\n const sets: number[] = [];\n for (let set = 0; set <= 7; set++) {\n const field = `texcoord${set}` as keyof typeof mesh;\n if (mesh[field] !== undefined) sets.push(set);\n }\n return sets;\n}\n\nfunction rewriteMaterialAssetRefs(\n matAsset: ReturnType<typeof toMaterialAsset>,\n mat: GltfMaterialIr,\n doc: GltfDoc,\n maps: HandleMaps,\n): ReturnType<typeof toMaterialAsset> {\n const values = { ...(matAsset.values ?? {}) } as Record<string, MaterialValue | null>;\n const textures = doc.textures ?? [];\n const slots: readonly [\n (\n | 'baseColorTexture'\n | 'metallicRoughnessTexture'\n | 'normalTexture'\n | 'occlusionTexture'\n | 'emissiveTexture'\n | 'transmissionTexture'\n | 'thicknessTexture'\n | 'clearcoatTexture'\n | 'clearcoatRoughnessTexture'\n | 'clearcoatNormalTexture'\n | 'anisotropyTexture'\n | 'sheenColorTexture'\n | 'sheenRoughnessTexture'\n | 'iridescenceTexture'\n | 'iridescenceThicknessTexture'\n | 'specularTexture'\n | 'specularColorTexture'\n ),\n GltfTextureInfoIr | number | undefined,\n ][] = [\n ['baseColorTexture', mat.baseColorTexture],\n ['metallicRoughnessTexture', mat.metallicRoughnessTexture],\n ['normalTexture', mat.normalTexture],\n ['occlusionTexture', mat.occlusionTexture],\n ['emissiveTexture', mat.emissiveTexture],\n ['transmissionTexture', mat.transmissionTexture],\n ['thicknessTexture', mat.thicknessTexture],\n ['clearcoatTexture', mat.clearcoatTexture],\n ['clearcoatRoughnessTexture', mat.clearcoatRoughnessTexture],\n ['clearcoatNormalTexture', mat.clearcoatNormalTexture],\n ['anisotropyTexture', mat.anisotropyTexture],\n ['sheenColorTexture', mat.sheenColorTexture],\n ['sheenRoughnessTexture', mat.sheenRoughnessTexture],\n ['iridescenceTexture', mat.iridescenceTexture],\n ['iridescenceThicknessTexture', mat.iridescenceThicknessTexture],\n ['specularTexture', mat.specularTexture],\n ['specularColorTexture', mat.specularColorTexture],\n ];\n let cursor = 0;\n for (const [slot, rawBinding] of slots) {\n const binding = textureInfo(rawBinding);\n if (binding === undefined) continue;\n const texture = textures[binding.texture];\n const textureGuid =\n texture === undefined ? undefined : maps.textureGuidByIndex.get(texture.source);\n const value = values[slot];\n if (textureGuid === undefined || typeof value !== 'object' || value === null) {\n delete values[slot];\n continue;\n }\n const textureValue = value as MaterialTextureValue;\n const textureRef = cursor as unknown as MaterialTextureValue['texture'];\n cursor++;\n const rewritten =\n binding.sampler !== undefined && maps.samplerGuidByIndex.has(binding.sampler)\n ? {\n ...textureValue,\n texture: textureRef,\n sampler: cursor as unknown as NonNullable<MaterialTextureValue['sampler']>,\n }\n : { ...textureValue, texture: textureRef };\n if (binding.sampler !== undefined && maps.samplerGuidByIndex.has(binding.sampler)) cursor++;\n values[slot] = rewritten;\n }\n return { ...matAsset, values };\n}\n\nasync function importGltf(\n ctx: ImportContext,\n meshopt?: GltfBufferViewDecodeCapability,\n): Promise<ImportResult> {\n const read = await ctx.readSource();\n if (!read.ok) {\n throw new Error(\n `gltfImporter: readSource failed: ${read.error instanceof Error ? read.error.message : String(read.error)}`,\n );\n }\n const parsed = await parseDoc(ctx.source, read.value, ctx, meshopt);\n if (!parsed.ok) return parsed;\n const doc = applyImportSettingsBounds(parsed.value, ctx.importSettings);\n const maps = buildHandleMaps(ctx.subAssets, doc);\n\n // Pre-derive each images[] row's colorSpace from material slot bindings\n // (D-3 / AC-08). orphan images default to 'linear' (AC-13).\n const imageColorSpaces = deriveTextureColorSpace({\n imageCount: (doc.images ?? []).length,\n textures: doc.textures,\n materials: doc.materials,\n });\n\n // Extract image bytes (3 source paths) once. Failures here are surfaced\n // per-image so a single bad row does not abort the whole importer.\n const declaredImageIndices = new Set<number>();\n for (const sub of ctx.subAssets) {\n if (sub.kind === 'texture') declaredImageIndices.add(sub.sourceIndex);\n }\n const extraction =\n declaredImageIndices.size > 0\n ? await extractImageBytes(read.value, ctx.source, ctx)\n : {\n extracted: new Map(),\n failures: [] as readonly {\n imageIndex: number;\n source: 'bufferView' | 'data-uri' | 'external-uri';\n reason: string;\n }[],\n };\n\n // M4 (tweak-20260611-skin-fox-3clip-and-kb-sample-assets): SkinAsset.refs[]\n // carries the skeleton GUID (each skin binds 1:1 to a SkeletonAsset; the\n // skeletonGuid field is the on-asset cross-reference; refs[] is the runner-\n // visible cross-edge used for pack-index ordering and integrity checks).\n // Build the index now so the skin emit branch below can stamp it.\n const skeletonGuidBySourceIndex = new Map<number, string>();\n for (const sub of ctx.subAssets) {\n if (sub.kind === 'skeleton') skeletonGuidBySourceIndex.set(sub.sourceIndex, sub.guid);\n }\n // feat-20260612 M2 fixup: parallel skin GUID index. Skins and skeletons\n // share `sourceIndex` (toAssetPack emits 1:1 per GltfSkeletonRecord) but live\n // as distinct `kind` sub-assets, so the SkinAsset GUIDs differ from the\n // SkeletonAsset GUIDs. The scene branch below appends these GUIDs to both\n // its refs[] (the runtime recursion source: loadByGuid<SceneAsset> walks\n // envelope.refs to recursively pull every SkinAsset before instantiate) and\n // its payload.skinGuids (the reverse-decode hint) -- without the refs[] edge,\n // browser-async-pack-fetch never loads SkinAssets and Skin.joints stays\n // length=0).\n const skinGuidBySourceIndex = new Map<number, string>();\n for (const sub of ctx.subAssets) {\n if (sub.kind === 'skin') skinGuidBySourceIndex.set(sub.sourceIndex, sub.guid);\n }\n\n const out: ImportedAsset[] = [];\n const isMultiAsset = ctx.subAssets.length > 1;\n for (const sub of ctx.subAssets) {\n if (sub.kind === 'mesh') {\n // sub.sourceIndex now indexes glTF mesh-index (not flat GltfMeshIr index).\n // parseGltf flattens N glTF meshes with M_i primitives into sum(M_i)\n // GltfMeshIr rows, all sharing meshIndex; gather all rows whose\n // meshIndex === sub.sourceIndex (preserving doc.meshes order so the\n // bridge's positional materials[i] <-> submeshes[i] pairing aligns)\n // and let meshIrToMeshAsset interleave them into one MeshAsset with\n // N Submesh entries.\n const prims = doc.meshes.filter((m) => m.meshIndex === sub.sourceIndex);\n if (prims.length === 0) continue;\n const meshName = isMultiAsset ? prims[0]?.name : undefined;\n const materialNameByIndex = new Map<number, string>();\n const materialSourceKeyByIndex = new Map<number, string>();\n for (let materialIndex = 0; materialIndex < doc.materials.length; materialIndex++) {\n const name = doc.materials[materialIndex]?.name;\n if (typeof name === 'string') materialNameByIndex.set(materialIndex, name);\n }\n for (const material of ctx.subAssets) {\n if (material.kind === 'material' && material.sourceKey !== undefined) {\n materialSourceKeyByIndex.set(material.sourceIndex, material.sourceKey);\n }\n }\n const bridged = meshIrToMeshAsset(prims, {\n guidByIndex: maps.materialGuidByIndex,\n nameByIndex: materialNameByIndex,\n sourceKeyByIndex: materialSourceKeyByIndex,\n });\n if (!bridged.ok) {\n return {\n ok: false,\n error: new ImportError({\n code: 'import-internal-error',\n expected: 'gltf mesh bridge to produce a canonical MeshAsset',\n actual: bridged.error.code,\n hint: 'repair the source primitive and re-run the glTF importer',\n detail: {\n reason: `gltf mesh bridge rejected mesh ${sub.sourceIndex}; inspect the bridge error detail`,\n },\n }),\n };\n }\n const stabilizedMesh = stabilizeMeshMaterialSlots(\n bridged.value,\n ctx,\n sub.guid,\n sub.sourceKey,\n );\n const lodGroup =\n doc.lod?.groups?.find(\n (group) => doc.nodes[group.rootNode]?.meshIndex === sub.sourceIndex,\n ) ??\n (doc.lod?.rootNode !== undefined &&\n doc.nodes[doc.lod.rootNode]?.meshIndex === sub.sourceIndex\n ? doc.lod\n : undefined);\n const rootMeshIndex = lodGroup === undefined ? undefined : sub.sourceIndex;\n if (lodGroup !== undefined) {\n const referencedMeshIndices = [\n sub.sourceIndex,\n ...lodGroup.lodNodeIds.map((nodeIndex) => doc.nodes[nodeIndex]?.meshIndex),\n ];\n const missingMeshIndex = referencedMeshIndices.find(\n (meshIndex) =>\n !Number.isInteger(meshIndex) ||\n meshIndex === null ||\n meshIndex === undefined ||\n maps.meshGuidByIndex.get(meshIndex as number) === undefined,\n );\n if (missingMeshIndex !== undefined) {\n return {\n ok: false,\n error: new ImportError({\n code: 'import-internal-error',\n expected: 'every MSFT_lod node to resolve a cooked mesh sub-asset',\n actual: String(missingMeshIndex),\n hint: 'repair the referenced glTF mesh primitives and re-run the importer',\n detail: {\n reason: `MSFT_lod group for mesh ${sub.sourceIndex} references an unprojected mesh`,\n },\n }),\n };\n }\n }\n const authoredLods =\n sub.sourceKey === undefined ? undefined : ctx.sourceOverrides?.[sub.sourceKey]?.lods;\n const lodEntries = Array.isArray(authoredLods) ? authoredLods : [];\n const lodLevels =\n rootMeshIndex === sub.sourceIndex && lodGroup !== undefined\n ? lodGroup.lodNodeIds.flatMap((nodeIndex, index) => {\n const meshIndex = doc.nodes[nodeIndex]?.meshIndex;\n const guid =\n meshIndex === undefined || meshIndex === null\n ? undefined\n : maps.meshGuidByIndex.get(meshIndex);\n if (guid === undefined) return [];\n const authored = lodEntries[index];\n const authoredCoverage =\n authored !== null && typeof authored === 'object'\n ? (authored as { readonly screenCoverage?: unknown }).screenCoverage\n : undefined;\n const coverage =\n typeof authoredCoverage === 'number'\n ? authoredCoverage\n : (lodGroup.screenCoverages[index] ??\n deriveDefaultLodScreenCoverages(lodGroup.lodNodeIds.length + 1)[index]);\n const parsed = AssetGuidCodec.parse(guid);\n return parsed.ok && coverage !== undefined\n ? [{ mesh: parsed.value, screenCoverage: coverage, guid }]\n : [];\n })\n : [];\n const meshPayload: MeshAsset =\n lodLevels.length === 0\n ? stabilizedMesh\n : {\n ...stabilizedMesh,\n lods: lodLevels.map(({ mesh, screenCoverage }) => ({ mesh, screenCoverage })),\n };\n const materialRefs: AssetRef[] = [];\n const seenMaterialGuids = new Set<string>();\n for (let slotIndex = 0; slotIndex < meshPayload.materialSlots.length; slotIndex++) {\n const defaultMaterial = meshPayload.materialSlots[slotIndex]?.defaultMaterial;\n const guid =\n defaultMaterial === undefined ? undefined : AssetGuidCodec.format(defaultMaterial);\n if (guid !== undefined && !seenMaterialGuids.has(guid.toLowerCase())) {\n seenMaterialGuids.add(guid.toLowerCase());\n materialRefs.push({\n guid,\n sourceField: { fieldName: 'materialSlots', arrayIndex: slotIndex },\n });\n }\n }\n for (const [lodIndex, level] of lodLevels.entries()) {\n if (!seenMaterialGuids.has(level.guid.toLowerCase())) {\n seenMaterialGuids.add(level.guid.toLowerCase());\n materialRefs.push({\n guid: level.guid,\n sourceField: { fieldName: 'lods', arrayIndex: lodIndex },\n });\n }\n }\n out.push({\n guid: sub.guid,\n kind: 'mesh',\n ...(meshName !== undefined ? { name: meshName } : {}),\n payload: meshPayload,\n refs: materialRefs,\n artifacts: {\n body: {\n mediaType: 'application/x-forgeax-mesh',\n assetCodec: { name: 'mesh-binary', version: '4' },\n bytes: (() => {\n const packed = packMeshBinV4(\n meshPayload as never,\n sub.sourceKey ?? ctx.source,\n materialRefs.map((ref) => ref.guid),\n );\n if (!packed.ok) {\n throw new ImportError({\n code: 'import-internal-error',\n expected: 'mesh-bin v4 producer to accept the canonical mesh projection',\n hint: 're-cook the source with its Meta sidecar after fixing the mesh payload',\n detail: { reason: `${packed.error.code}: ${packed.error.actual}` },\n });\n }\n return packed.value;\n })(),\n },\n },\n });\n } else if (sub.kind === 'material') {\n const mat = doc.materials[sub.sourceIndex];\n if (mat === undefined) continue;\n // feat-20260611 w17-a: scan doc.meshes[] for any primitive that (a)\n // references this material and (b) carries JOINTS_0 + WEIGHTS_0. If\n // found, route the emitted MaterialAsset to `forgeax::pbr-skin`.\n // Mirrors the per-MeshAsset 18F-stride decision in meshIrToMeshAsset\n // (D-2): a material consumed by any skinned primitive must use the\n // skin shader so the runtime PSO chain (LayoutKind='pbr-skin' +\n // 6-attribute deriveVertexBufferLayout) is exercised.\n let skinned = false;\n for (const meshIr of doc.meshes) {\n if (meshIr.materialIndex !== sub.sourceIndex) continue;\n if (meshIr.joints0 !== undefined && meshIr.weights0 !== undefined) {\n skinned = true;\n break;\n }\n }\n for (let primitiveIndex = 0; primitiveIndex < doc.meshes.length; primitiveIndex++) {\n const meshIr = doc.meshes[primitiveIndex];\n if (meshIr?.materialIndex !== sub.sourceIndex) continue;\n const uvResult = validateMaterialUvSets(\n mat,\n `primitive-${primitiveIndex}`,\n availableUvSets(meshIr),\n );\n if (!uvResult.ok) {\n throw Object.assign(new Error(uvResult.error.message), uvResult.error);\n }\n const tangentResult = validateMaterialTangentInputs(mat, meshIr);\n if (!tangentResult.ok) {\n throw Object.assign(new Error(tangentResult.error.message), tangentResult.error);\n }\n }\n const matAsset = toMaterialAsset(mat, {\n textureHandles: maps.textureHandles,\n samplerHandles: maps.samplerHandles,\n skinned,\n ...(typeof ctx.importSettings.standardMaterialGuid === 'string'\n ? { standardRootGuid: ctx.importSettings.standardMaterialGuid as unknown as AssetGuid }\n : {}),\n });\n const refs = materialRefsForPack(mat, doc, maps.textureGuidByIndex, maps.samplerGuidByIndex);\n // D-8: if material has a parent, add parent edge to refs\n const materialRefs: AssetRef[] = [...refs];\n if (matAsset.parent !== undefined) {\n materialRefs.push({\n guid: matAsset.parent as unknown as string,\n sourceField: { fieldName: 'parent' },\n });\n }\n const rewrittenAsset = rewriteMaterialAssetRefs(matAsset, mat, doc, maps);\n const matName = isMultiAsset ? mat.name : undefined;\n out.push({\n guid: sub.guid,\n kind: 'material',\n ...(matName !== undefined ? { name: matName } : {}),\n payload: rewrittenAsset,\n refs: materialRefs,\n artifacts: {},\n });\n } else if (sub.kind === 'texture') {\n const imageIndex = sub.sourceIndex;\n const extracted = extraction.extracted.get(imageIndex);\n if (extracted === undefined) {\n const failure = extraction.failures.find((f) => f.imageIndex === imageIndex);\n const detail = failure ?? {\n imageIndex,\n source: 'bufferView' as const,\n reason: 'image row missing from extraction map (no images[] entry?)',\n };\n const error = gltfErr('gltf-image-extract-failed', detail);\n throw new Error(\n `gltfImporter: ${error.code} on image ${imageIndex} (${detail.source}): ${detail.reason}`,\n );\n }\n const colorSpace = imageColorSpaces.get(imageIndex) ?? 'linear';\n // Carry colorSpace + mipmap settings into decodeImage via a per-image\n // settings record (mirror of importImageSettings — but here the importer\n // owns the decision because the seam is in-bounds for AC-12 (c)).\n const decodeSettings = {\n ...ctx.importSettings,\n colorSpace,\n mipmap: ctx.importSettings.mipmap ?? true,\n };\n const decoded = await ctx.decodeImage(extracted.bytes, extracted.mimeType, decodeSettings);\n if (!decoded.ok) {\n const reason = `decodeImage failed: ${decoded.error.code}`;\n const error = gltfErr('gltf-image-extract-failed', {\n imageIndex,\n source: extracted.source,\n reason,\n });\n throw new Error(\n `gltfImporter: ${error.code} on image ${imageIndex} (${extracted.source}): ${reason}`,\n );\n }\n const imageItem = (doc.images ?? [])[imageIndex];\n const texName = isMultiAsset ? imageItem?.name : undefined;\n out.push({\n guid: sub.guid,\n kind: 'texture',\n ...(texName !== undefined ? { name: texName } : {}),\n payload: decoded.value.texture,\n refs: [],\n artifacts: {\n body: {\n mediaType: decoded.value.mediaType ?? extracted.mimeType,\n assetCodec: decoded.value.assetCodec ?? { name: 'rgba8', version: '1' },\n bytes: decoded.value.bytes,\n },\n },\n });\n } else if (sub.kind === 'sampler') {\n const sampler = doc.samplers?.[sub.sourceIndex];\n if (sampler === undefined) continue;\n const filter = (value: number | undefined): 'nearest' | 'linear' | undefined => {\n if (value === undefined) return undefined;\n return value === 9728 || value === 9984 || value === 9986 || value === 9988\n ? 'nearest'\n : 'linear';\n };\n const mipmapFilter = (value: number | undefined): 'nearest' | 'linear' | undefined => {\n if (value === undefined) return undefined;\n return value === 9984 || value === 9985 ? 'nearest' : 'linear';\n };\n const addressMode = (value: number): 'repeat' | 'mirror-repeat' | 'clamp-to-edge' => {\n if (value === 33071) return 'clamp-to-edge';\n if (value === 33648) return 'mirror-repeat';\n return 'repeat';\n };\n const magFilter = filter(sampler.magFilter);\n const minFilter = filter(sampler.minFilter);\n const mipmap = mipmapFilter(sampler.minFilter);\n const payload = {\n kind: 'sampler' as const,\n ...(magFilter === undefined ? {} : { magFilter }),\n ...(minFilter === undefined ? {} : { minFilter }),\n ...(mipmap === undefined ? {} : { mipmapFilter: mipmap }),\n addressModeU: addressMode(sampler.wrapS),\n addressModeV: addressMode(sampler.wrapT),\n };\n out.push({ guid: sub.guid, kind: 'sampler', payload, refs: [], artifacts: {} });\n } else if (sub.kind === 'scene') {\n // #317 multi-material design: bridge accepts glTF mesh-index keyed\n // meshHandles + materialHandles only; primitive merge happens via\n // doc.meshes[] filtering on meshIndex inside the bridge.\n // tweak-20260611 M6: also pass skeletonGuidBySkinIndex so the bridge\n // can stamp Skin component (skeleton GUID string) onto skinned mesh\n // entities. Skins are 1:1 with skeletons in toAssetPack so the same\n // sourceIndex map serves both purposes (the field name says\n // \"BySkinIndex\" because the bridge keys by GltfNodeIr.skinIndex).\n const scene = gltfDocToSceneAsset(doc, {\n meshHandles: maps.meshHandles,\n materialHandles: maps.materialHandles,\n skeletonGuidBySkinIndex: skeletonGuidBySourceIndex,\n });\n // Scene refs contain only dependencies authored directly by the scene:\n // mesh, skeleton, and skin assets. Imported material defaults belong to\n // MeshAsset.materialSlots, and textures belong to MaterialAsset refs;\n // repeating either here would create a second dependency owner.\n // Skeleton GUIDs are appended so the runtime asset graph sees the\n // cross-edge when a skinned mesh node carries Skin { skeleton:\n // <guid-string> }; skin GUIDs (feat-20260612 M2 fixup) carry the\n // SkinAsset cross-edge that has no entity-component representation but\n // is required for postSpawnResolveJoints to resolve Skin.joints[] via\n // SkinAsset.jointPaths.\n //\n // D-2 / D-3: refs carries structured edge metadata (AssetRef[]).\n // Walk keyed scene entities to build a handle-value -> (entityKey,\n // componentName, fieldName, arrayIndex?) provenance map, then\n // produce AssetRef[] with sourceField / sceneEntityKey filled for mesh\n // handle-field edges. Skeleton edges: sourceField from Skin.skeleton if entity\n // carries that GUID. Skin edges: sourceField=undefined (cross-edge\n // with no entity-component representation).\n const handleValueProvenance = new Map<\n number,\n { sceneEntityKey: string; componentName: string; fieldName: string; arrayIndex?: number }\n >();\n const skeletonGuidProvenance = new Map<string, { sceneEntityKey: string }>();\n for (const [sceneEntityKey, entity] of Object.entries(scene.entities)) {\n const comps = entity.components as Record<string, Record<string, unknown>>;\n const mf = comps.MeshFilter;\n if (mf !== undefined && typeof mf.assetHandle === 'number') {\n handleValueProvenance.set(mf.assetHandle, {\n sceneEntityKey,\n componentName: 'MeshFilter',\n fieldName: 'assetHandle',\n });\n }\n const skin = comps.Skin;\n if (skin !== undefined && typeof skin.skeleton === 'string') {\n skeletonGuidProvenance.set(skin.skeleton, { sceneEntityKey });\n }\n }\n\n const meshGuidList = [...maps.meshGuidByIndex.values()];\n\n function makeRef(guid: string, idx: number): AssetRef {\n const prov = handleValueProvenance.get(idx);\n if (prov !== undefined) {\n return {\n guid,\n sourceField: {\n componentName: prov.componentName,\n fieldName: prov.fieldName,\n ...(prov.arrayIndex !== undefined ? { arrayIndex: prov.arrayIndex } : {}),\n },\n sceneEntityKey: prov.sceneEntityKey,\n };\n }\n return { guid };\n }\n\n const refs: AssetRef[] = [];\n let cursor = 0;\n for (const guid of meshGuidList) {\n refs.push(makeRef(guid, cursor));\n cursor++;\n }\n {\n const skeletonGuidList = [...skeletonGuidBySourceIndex.values()];\n for (const guid of skeletonGuidList) {\n const skProv = skeletonGuidProvenance.get(guid);\n refs.push(\n skProv !== undefined\n ? {\n guid,\n sourceField: { componentName: 'Skin', fieldName: 'skeleton' },\n sceneEntityKey: skProv.sceneEntityKey,\n }\n : { guid },\n );\n cursor++;\n }\n }\n {\n const skinGuidList = [...skinGuidBySourceIndex.values()];\n for (const guid of skinGuidList) {\n refs.push({ guid });\n cursor++;\n }\n }\n // Inject skinGuids into the scene payload as the reverse-decode hint; the\n // SkinAsset GUIDs are already in the scene envelope's refs[] above, which\n // is the runtime recursion source for the browser-async-pack-fetch path.\n // Stored as inline GUID strings (in-memory dawn smoke path); the on-disk\n // .pack.json round-trip preserves them as strings -- parseScenePayload's\n // resolveSkinGuids accepts both string and refs[]-index shapes.\n const skinGuidList = [...skinGuidBySourceIndex.values()];\n const sceneWithSkinGuids =\n skinGuidList.length > 0 ? { ...scene, skinGuids: skinGuidList } : scene;\n const sceneName = isMultiAsset ? doc.scenes[sub.sourceIndex]?.name : undefined;\n out.push({\n guid: sub.guid,\n kind: 'scene',\n ...(sceneName !== undefined ? { name: sceneName } : {}),\n payload: sceneWithSkinGuids,\n refs,\n artifacts: {},\n });\n } else if (sub.kind === 'skeleton') {\n // tweak-20260611 M4: skeleton sub-asset POD emit. GltfSkeletonRecord (the\n // gltf IR shape from parse-skin) carries inverseBindMatrices + jointCount\n // + jointPaths; SkeletonAsset (the runtime POD) carries IBM + jointCount\n // only — jointPaths live on the parallel SkinAsset (1:1 mapping per\n // toAssetPack's emit policy). refs[] is empty (skeleton is leaf data).\n const rec = doc.skeletons[sub.sourceIndex];\n if (rec === undefined) continue;\n const payload = {\n kind: 'skeleton' as const,\n inverseBindMatrices: rec.inverseBindMatrices,\n jointCount: rec.jointCount,\n ...(rec.bounds === undefined ? {} : { bounds: rec.bounds }),\n };\n out.push({ guid: sub.guid, kind: 'skeleton', payload, refs: [], artifacts: {} });\n } else if (sub.kind === 'skin') {\n // tweak-20260611 M4: skin sub-asset POD emit. The 1:1 mapping with\n // skeleton (toAssetPack emits one skin per GltfSkeletonRecord at the same\n // sourceIndex) lets us pull the skeleton GUID out of the pre-built\n // skeletonGuidBySourceIndex map. SkinAsset is the runtime POD, distinct\n // from GltfSkeletonRecord: skeletonGuid + jointPaths only (zero entity refs\n // at the asset layer per AC-06). refs[] carries the skeletonGuid so the\n // runner sees the cross-edge.\n const rec = doc.skeletons[sub.sourceIndex];\n if (rec === undefined) continue;\n const skeletonGuid = skeletonGuidBySourceIndex.get(sub.sourceIndex);\n if (skeletonGuid === undefined) continue;\n const payload = {\n kind: 'skin' as const,\n skeletonGuid,\n jointPaths: rec.jointPaths,\n };\n out.push({\n guid: sub.guid,\n kind: 'skin',\n payload,\n refs: [{ guid: skeletonGuid, sourceField: { fieldName: 'skeleton' } }],\n artifacts: {},\n });\n } else if (sub.kind === 'animation-clip') {\n // tweak-20260611 M4: animation-clip sub-asset POD emit. GltfAnimationClipRecord\n // (gltf IR) and AnimationClip (runtime POD) are structurally compatible\n // — both carry duration + channels[]; channels' inner shape matches\n // (targetId / property / sampler). property is narrowed to the runtime\n // closed union by the parser. refs[] is empty (animation clips reference joints by name path\n // resolved at post-spawn time, not by sub-asset cross-edge).\n const rec = doc.animationClips[sub.sourceIndex];\n if (rec === undefined) continue;\n const payload = {\n kind: 'animation-clip' as const,\n duration: rec.duration,\n channels: rec.channels.map((ch) => ({\n targetId: ch.targetId,\n property: ch.property,\n sampler: {\n input: ch.sampler.input,\n output: ch.sampler.output,\n interpolation: ch.sampler.interpolation,\n },\n })),\n };\n out.push({ guid: sub.guid, kind: 'animation-clip', payload, refs: [], artifacts: {} });\n }\n }\n return { ok: true, value: { assets: out, sourceDependencies: [] } };\n}\n\n/**\n * The gltf {@link Importer}. Register it into an `ImporterRegistry` so the\n * import runner dispatches `meta.importer === 'gltf'` sidecars here.\n *\n * @example\n * ```ts\n * import { ImporterRegistry } from '@forgeax/engine-import';\n * import { gltfImporter } from '@forgeax/engine-gltf';\n * const importers = new ImporterRegistry();\n * importers.register(gltfImporter);\n * ```\n */\nexport function createGltfImporter(meshopt?: GltfBufferViewDecodeCapability): Importer {\n return {\n key: 'gltf',\n import: (ctx) => importGltf(ctx, meshopt),\n capabilities: { catalog: { publish: publishesCatalogProduct } },\n };\n}\n\n/** Importer for hosts that provide an optional build-only Meshopt decoder. */\nexport const gltfImporter: Importer = createGltfImporter();\n","import { MeshoptDecoder } from 'meshoptimizer';\nimport { createGltfImporter } from './gltf-importer.js';\nimport type { GltfBufferViewDecodeCapability } from './meshopt-decode.js';\n\nawait MeshoptDecoder.ready;\n\n/** Browser/build consumer capability for EXT_meshopt_compression. */\nexport const meshoptDecoder: GltfBufferViewDecodeCapability = {\n decode: ({ source, count, stride, mode, filter }) => {\n const target = new Uint8Array(count * stride);\n MeshoptDecoder.decodeGltfBuffer(target, count, stride, source, mode, filter);\n return target;\n },\n};\n\n/**\n * Build-only glTF importer entry. The player-facing package remains free of\n * the Meshopt WASM dependency; hosts opt into this entry when importing files.\n */\nexport const gltfImporter = createGltfImporter({\n decode: meshoptDecoder.decode,\n});\n\nexport { createGltfImporter } from './gltf-importer.js';\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/node-path.ts","../src/animated-bounds.ts","../src/errors.ts","../src/bridge.ts","../src/data-uri.ts","../src/parse-gltf-header.ts","../src/parse-glb-chunks.ts","../src/extract-image-bytes.ts","../src/image-color-space.ts","../src/accessor/decode-accessor.ts","../src/accessor/decode-color.ts","../src/check-extensions.ts","../src/lod/parse-lod.ts","../src/material/parse-material.ts","../src/meshopt-decode.ts","../src/parse-animation.ts","../src/parse-skin.ts","../src/transform.ts","../src/parse-gltf.ts","../src/gltf-importer.ts","../src/importer-entry.ts"],"names":["AssetGuidCodec","err","mime","tuple3","vec3","quat","mat4","n","ImportError","IMPORT_ERROR_HINTS","reconcileMeshMaterialSlotTopology","res","textureInfo","textureValue","parsed","makeRef","skinGuidList","gltfImporter"],"mappings":";;;;;;;;;;;;;AAKO,SAAS,mBAAmB,KAAA,EAA0D;AAC3F,EAAA,MAAM,OAA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OAAA,CAAQ;AAAA;AAC5B,SACF,CAAE;AAAA,OACJ;AACA,MAAA,GAAA,CAAI,IAAA,CAAK,EAAE,IAAA,EAAM,GAAA,CAAI,MAAM,IAAA,EAAM,gBAAA,EAAkB,OAAA,EAAS,IAAA,EAAM,EAAC,EAAG,SAAA,EAAW,IAAI,CAAA;AAAA,IACvF;AAAA,EACF;AACA,EAAA,OAAO,EAAE,EAAA,EAAI,IAAA,EAAM,KAAA,EAAO,EAAE,QAAQ,GAAA,EAAK,kBAAA,EAAoB,EAAC,EAAE,EAAE;AACpE;AAcO,SAAS,mBAAmB,OAAA,EAAoD;AACrF,EAAA,OAAO;AAAA,IACL,GAAA,EAAK,MAAA;AAAA,IACL,MAAA,EAAQ,CAAC,GAAA,KAAQ,UAAA,CAAW,KAAK,OAAO,CAAA;AAAA,IACxC,cAAc,EAAE,OAAA,EAAS,EAAE,OAAA,EAAS,yBAAwB;AAAE,GAChE;AACF;;;AC1lCA,MAAM,cAAA,CAAe,KAAA;AAGd,IAAM,cAAA,GAAiD;AAAA,EAC5D,MAAA,EAAQ,CAAC,EAAE,MAAA,EAAQ,OAAO,MAAA,EAAQ,IAAA,EAAM,QAAO,KAAM;AACnD,IAAA,MAAM,MAAA,GAAS,IAAI,UAAA,CAAW,KAAA,GAAQ,MAAM,CAAA;AAC5C,IAAA,cAAA,CAAe,iBAAiB,MAAA,EAAQ,KAAA,EAAO,MAAA,EAAQ,MAAA,EAAQ,MAAM,MAAM,CAAA;AAC3E,IAAA,OAAO,MAAA;AAAA,EACT;AACF;AAMO,IAAMC,gBAAe,kBAAA,CAAmB;AAAA,EAC7C,QAAQ,cAAA,CAAe;AACzB,CAAC","file":"importer-entry.mjs","sourcesContent":["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","import {\n type AnimatedBoundsMesh,\n deriveConservativeAnimatedBounds,\n} from '@forgeax/engine-animation/animated-bounds';\nimport { buildNodeParentMap, resolveNamedNodePath } from './node-path';\nimport type { GltfDoc } from './parse-gltf';\n\n/** Source extras and sidecar bounds have already been applied before this producer runs. */\nexport function deriveGltfAnimatedBounds(doc: GltfDoc): GltfDoc {\n const parents = buildNodeParentMap(doc.nodes);\n const paths = doc.nodes.map((_, index) => {\n const path = resolveNamedNodePath(doc.nodes, parents, index);\n return path.ok ? path.value.join('/') : undefined;\n });\n const nodes = doc.nodes.map((node, index) => ({\n ...node.transform,\n parent: parents.get(index) ?? null,\n }));\n const channels = doc.animationClips.flatMap((clip) =>\n clip.channels.flatMap((channel) =>\n channel.property === 'weights'\n ? []\n : [\n {\n node: channel.targetNodeIndex,\n property: channel.property,\n values: channel.sampler.output,\n interpolation: channel.sampler.interpolation,\n },\n ],\n ),\n );\n const primitiveStarts: number[] = [];\n let offset = 0;\n for (const count of doc.meshPrimitiveCount?.values() ?? doc.meshes.map(() => 1)) {\n primitiveStarts.push(offset);\n offset += count;\n }\n const skeletons = doc.skeletons.map((skeleton, skinIndex) => {\n if (skeleton.bounds !== undefined) return skeleton;\n const meshes: AnimatedBoundsMesh[] = [];\n for (let index = 0; index < doc.nodes.length; index++) {\n const node = doc.nodes[index];\n if (node === undefined) return skeleton;\n if (node.skinIndex !== skinIndex || node.meshIndex === null) continue;\n const start = primitiveStarts[node.meshIndex];\n if (start === undefined) return skeleton;\n for (const mesh of doc.meshes.slice(\n start,\n start + (doc.meshPrimitiveCount?.get(node.meshIndex) ?? 1),\n )) {\n if (mesh.joints0 === undefined || mesh.weights0 === undefined) return skeleton;\n let maxMorphWeight = Math.max(\n 0,\n ...Array.from(node.morphWeights ?? mesh.morphWeights ?? [], Math.abs),\n );\n for (const clip of doc.animationClips)\n for (const channel of clip.channels)\n if (channel.targetNodeIndex === index && channel.property === 'weights')\n for (const weight of channel.sampler.output)\n maxMorphWeight = Math.max(maxMorphWeight, Math.abs(weight));\n const morphExtent = Float32Array.from(mesh.positions, (_, component) =>\n (mesh.morphTargets ?? []).reduce(\n (sum, target) => sum + Math.abs(target.position?.[component] ?? 0) * maxMorphWeight,\n 0,\n ),\n );\n meshes.push({\n node: index,\n positions: mesh.positions,\n joints: mesh.joints0,\n weights: mesh.weights0,\n morphExtent,\n });\n }\n }\n const jointNodes = skeleton.jointPaths.map((path) => paths.indexOf(path));\n if (\n jointNodes.some(\n (node, index) => node < 0 || paths.lastIndexOf(skeleton.jointPaths[index]) !== node,\n )\n )\n return skeleton;\n const bounds = deriveConservativeAnimatedBounds({\n nodes,\n channels,\n jointNodes,\n inverseBindMatrices: skeleton.inverseBindMatrices,\n meshes,\n });\n return bounds === undefined ? skeleton : { ...skeleton, bounds };\n });\n return { ...doc, skeletons };\n}\n","// 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","// bridge.ts - public gltfDocToSceneAsset SSOT (M3 w9 / feat-20260518).\n//\n// Excises the previously inline 80-line implementation in\n// apps/hello/gltf/src/main.ts. AI users get a single import path:\n//\n// ```ts\n// import { gltfDocToSceneAsset, toMaterialAsset } from '@forgeax/engine-gltf';\n// const scene = gltfDocToSceneAsset(doc, { meshHandles, materialHandles });\n// ```\n//\n// Pure function: no fs, no fetch, no throw. Walks the default scene's\n// node graph depth-first, accumulating world transforms for children (B3).\n// Handles for mesh / material come from caller-supplied Map lookups so the\n// bridge stays runtime-agnostic.\n//\n// feat-20260608-mesh-multi-section-primitive-multi-material-slot M3 / w13+w15:\n// (B1) N prim per glTF mesh merged into 1 entity with MeshRenderer.materials[]\n// (B2) visit recursively walks ir.children\n// (B3) child world pos accumulates parent transform\n// (B6) camera detection via GltfNodeIr.camera field (not legacy nodes[1] heuristic)\n\nimport { computeTangentVec4, packInterleavedVertexAttributes } from '@forgeax/engine-geometry';\nimport type { Mat4 } from '@forgeax/engine-math';\nimport { box3, mat4, quat, vec3 } from '@forgeax/engine-math';\nimport { AssetGuid as AssetGuidCodec } from '@forgeax/engine-pack/guid';\nimport type {\n AssetGuid,\n Handle,\n LocalEntityId,\n MaterialAsset,\n MaterialError,\n MaterialTextureValue,\n MeshAsset,\n MeshMaterialSlot,\n MorphTarget,\n RenderQueue,\n Result,\n SceneAsset,\n Submesh,\n VertexAttributeMap,\n} from '@forgeax/engine-types';\nimport {\n STANDARD_LAYER_PARAMETER_GROUPS,\n STANDARD_MATERIAL_PARAM_SCHEMA,\n STANDARD_PHYSICAL_PARAMETER_NAMES,\n STANDARD_TRANSMISSION_PARAMETER_NAMES,\n standardMaterialParameters,\n} from '@forgeax/engine-types';\nimport { createMaterialError, err, type GltfError, gltfErr, ok } from './errors.js';\nimport type {\n GltfDoc,\n GltfMaterialIr,\n GltfMeshIr,\n GltfNodeIr,\n GltfPunctualLightIr,\n GltfTextureInfoIr,\n} from './parse-gltf.js';\n\n/**\n * Convert one or more parsed `GltfMeshIr` primitives sharing the same glTF\n * mesh-index into a single runtime `MeshAsset` POD. Each primitive becomes one\n * `Submesh` row; per-primitive vertex data is concatenated into one big\n * interleaved vertex buffer (12 floats / vertex for unskinned meshes; 18 floats\n * / vertex when any primitive carries `joints0` + `weights0`), and per-primitive\n * index buffers are concatenated into one big index buffer. Each submesh's\n * indices are biased by the running vertex offset so they reference vertices\n * within the merged buffer.\n *\n * Per-MeshAsset stride decision (D-2): if any primitive contains skin\n * attributes, the entire MeshAsset is promoted to 18-float stride and\n * unskinned primitives' skin slots are zero-filled (joints {0,0,0,0} +\n * weights {0,0,0,0}). This avoids splitting one glTF mesh into multiple\n * MeshAsset rows when a model mixes skinned and unskinned primitives.\n *\n * AI users get a 1-to-1 mapping with `MeshRenderer.materials[]`: the i-th\n * submesh is the i-th primitive of the i-th material slot.\n *\n * Pure function (no fs / fetch / registry). Missing attributes fall back to\n * identity defaults per primitive: normal -> +Y, uv -> 0, tangent -> +X with\n * w=1.\n *\n * Invalid source data is returned as a typed `GltfError`; callers must branch\n * on `Result.ok` before publishing a MeshAsset. Caller (gltfImporter / smoke\n * driver) is responsible for grouping by `meshIr.meshIndex` before calling.\n */\nexport function meshIrToMeshAsset(\n prims: readonly GltfMeshIr[],\n materials: {\n readonly guidByIndex?: ReadonlyMap<number, string>;\n readonly nameByIndex?: ReadonlyMap<number, string>;\n readonly sourceKeyByIndex?: ReadonlyMap<number, string>;\n } = {},\n): Result<MeshAsset, GltfError> {\n if (prims.length === 0) {\n return err(\n gltfErr('gltf-mesh-bridge-invalid', {\n reason: 'empty-input',\n primitiveCount: 0,\n }),\n );\n }\n let totalVertexCount = 0;\n let totalIndexCount = 0;\n let hasAnySkin = false;\n const hasAnyColor = prims.some((p) => p.colors0 !== undefined);\n let hasAnyIndices = false;\n // feat-20260629-multi-uv-set-support m1-w3: derive the widest canonical UV\n // key list across all primitives so the geometry projection accommodates it.\n let widestUvIndex = 0;\n const morphTargetCount = prims[0]?.morphTargets?.length ?? 0;\n for (const p of prims) {\n const primVc = p.positions.length / 3;\n totalVertexCount += primVc;\n if (p.indices !== undefined) {\n totalIndexCount += p.indices.length;\n hasAnyIndices = true;\n } else {\n totalIndexCount += primVc;\n }\n if (p.joints0 !== undefined && p.weights0 !== undefined) hasAnySkin = true;\n if ((p.morphTargets?.length ?? 0) !== morphTargetCount) {\n return err(\n gltfErr('gltf-mesh-bridge-invalid', {\n meshIndex: p.meshIndex,\n primitiveIndex: prims.indexOf(p),\n reason: 'morph-count-mismatch',\n expectedTargetCount: morphTargetCount,\n actualTargetCount: p.morphTargets?.length ?? 0,\n }),\n );\n }\n // Count present UV sets in this primitive.\n for (let k = 7; k >= 1; k--) {\n const key = `texcoord${k}` as keyof GltfMeshIr;\n if (p[key] !== undefined) {\n widestUvIndex = Math.max(widestUvIndex, k);\n break;\n }\n }\n }\n\n const uvKeys = Array.from({ length: widestUvIndex }, (_, index) => `uv${index + 1}`);\n\n const positionsCat = new Float32Array(totalVertexCount * 3);\n const normalsCat = new Float32Array(totalVertexCount * 3);\n const uvsCat = new Float32Array(totalVertexCount * 2);\n const tangentsCat = new Float32Array(totalVertexCount * 4);\n const colorsCat = hasAnyColor ? new Float32Array(totalVertexCount * 4) : undefined;\n const morphTargets: MorphTarget[] = Array.from({ length: morphTargetCount }, (_, targetIndex) => {\n const source = prims[0]?.morphTargets?.[targetIndex];\n return {\n ...(source?.position === undefined\n ? {}\n : { position: new Float32Array(totalVertexCount * 3) }),\n ...(source?.normal === undefined ? {} : { normal: new Float32Array(totalVertexCount * 3) }),\n ...(source?.tangent === undefined ? {} : { tangent: new Float32Array(totalVertexCount * 4) }),\n };\n });\n // feat-20260629-multi-uv-set-support m1-w3: per-UV-set standalone typed arrays\n // for MeshAsset.attributes (uv1..uvK). Allocated only for imported sets.\n const uvCats = uvKeys.map(() => new Float32Array(totalVertexCount * 2));\n // D-2 / w8: when promoted to a skinned projection, retain canonical\n // standalone arrays; the geometry packer owns the interleaved GPU bytes.\n const skinIndicesCat = hasAnySkin ? new Uint16Array(totalVertexCount * 4) : undefined;\n const skinWeightsCat = hasAnySkin ? new Float32Array(totalVertexCount * 4) : undefined;\n // Multi-primitive merge biases each primitive's index range by the running\n // vertex offset, so the merged max index is `totalVertexCount - 1`. When a\n // glTF mesh has > 65535 vertices across all primitives (common for\n // moderately complex scenes like Sponza at ~192k verts), Uint16 overflows\n // and we must widen to Uint32. WebGPU's setIndexBuffer takes 'uint16' or\n // 'uint32' (auto-selected by the runtime via TypedArray.constructor); both\n // are supported by every WebGPU device.\n // bug-20260612 hello-skin visual layered gate: when no primitive carries\n // indices (glTF non-indexed geometry per spec — primitive.indices optional),\n // route MeshAsset.indices to undefined so the runtime takes the\n // pass.draw(vertexCount) non-indexed path. Mixed bags (some prims indexed,\n // some not) synthesize identity indices for the non-indexed prims so the\n // merged MeshAsset stays single-index-buffer. hasAnyIndices === false\n // skips the index buffer allocation entirely.\n const useUint32 = totalVertexCount > 0xffff;\n const indices: Uint16Array | Uint32Array | undefined = !hasAnyIndices\n ? undefined\n : useUint32\n ? new Uint32Array(totalIndexCount)\n : new Uint16Array(totalIndexCount);\n const submeshes: Submesh[] = [];\n const materialSlots: MeshMaterialSlot[] = [];\n const slotByMaterial = new Map<number | null, number>();\n const usedNames = new Set<string>();\n const uniqueSlotName = (base: string): string => {\n let candidate = base.trim() || 'Material';\n let suffix = 2;\n while (usedNames.has(candidate)) candidate = `${base}_${suffix++}`;\n usedNames.add(candidate);\n return candidate;\n };\n const slotFor = (materialIndex: number | null): number => {\n const existing = slotByMaterial.get(materialIndex);\n if (existing !== undefined) return existing;\n const slotIndex = materialSlots.length;\n const guid = materialIndex === null ? undefined : materials.guidByIndex?.get(materialIndex);\n const parsed = guid === undefined ? undefined : AssetGuidCodec.parse(guid);\n materialSlots.push({\n slotName: uniqueSlotName(\n materialIndex === null\n ? 'Default'\n : (materials.nameByIndex?.get(materialIndex) ?? `Material_${materialIndex}`),\n ),\n sourceKey:\n materialIndex === null\n ? 'gltf:default'\n : (materials.sourceKeyByIndex?.get(materialIndex) ?? `gltf:material:${materialIndex}`),\n ...(parsed?.ok ? { defaultMaterial: parsed.value } : {}),\n });\n slotByMaterial.set(materialIndex, slotIndex);\n return slotIndex;\n };\n\n let vertexCursor = 0;\n let indexCursor = 0;\n for (const mesh of prims) {\n const materialSlot = slotFor(mesh.materialIndex);\n const primVertexCount = mesh.positions.length / 3;\n const primIndexCount = mesh.indices === undefined ? 0 : mesh.indices.length;\n // A tangent admission check may already have computed a valid frame for a\n // physical glTF material. Persist that producer result into the canonical\n // MeshAsset instead of silently replacing it with the historical identity\n // tangent. Non-physical meshes keep the identity fallback when the source\n // lacks the inputs required by the tangent producer.\n let generatedTangents: Float32Array | undefined;\n if (mesh.tangents === undefined && mesh.normals !== undefined && mesh.texcoord0 !== undefined) {\n const generated = computeTangentVec4(\n mesh.positions,\n mesh.normals,\n mesh.texcoord0,\n mesh.indices,\n );\n if (generated.ok) generatedTangents = generated.value;\n }\n if (mesh.colors0 !== undefined && mesh.colors0.length !== primVertexCount * 4) {\n return err(\n gltfErr('gltf-mesh-bridge-invalid', {\n meshIndex: mesh.meshIndex,\n primitiveIndex: prims.indexOf(mesh),\n reason: 'color-cardinality',\n semantic: 'COLOR_0',\n vertexCount: primVertexCount,\n expectedLength: primVertexCount * 4,\n actualLength: mesh.colors0.length,\n }),\n );\n }\n for (let i = 0; i < primVertexCount; i++) {\n const p = i * 3;\n positionsCat[(vertexCursor + i) * 3 + 0] = mesh.positions[p + 0] as number;\n positionsCat[(vertexCursor + i) * 3 + 1] = mesh.positions[p + 1] as number;\n positionsCat[(vertexCursor + i) * 3 + 2] = mesh.positions[p + 2] as number;\n if (mesh.normals !== undefined) {\n const n = i * 3;\n normalsCat[(vertexCursor + i) * 3 + 0] = mesh.normals[n + 0] as number;\n normalsCat[(vertexCursor + i) * 3 + 1] = mesh.normals[n + 1] as number;\n normalsCat[(vertexCursor + i) * 3 + 2] = mesh.normals[n + 2] as number;\n } else {\n normalsCat[(vertexCursor + i) * 3 + 1] = 1;\n }\n if (mesh.texcoord0 !== undefined) {\n const t = i * 2;\n uvsCat[(vertexCursor + i) * 2 + 0] = mesh.texcoord0[t + 0] as number;\n uvsCat[(vertexCursor + i) * 2 + 1] = mesh.texcoord0[t + 1] as number;\n }\n const sourceTangents = mesh.tangents ?? generatedTangents;\n if (sourceTangents !== undefined) {\n const g = i * 4;\n tangentsCat[(vertexCursor + i) * 4 + 0] = sourceTangents[g + 0] as number;\n tangentsCat[(vertexCursor + i) * 4 + 1] = sourceTangents[g + 1] as number;\n tangentsCat[(vertexCursor + i) * 4 + 2] = sourceTangents[g + 2] as number;\n tangentsCat[(vertexCursor + i) * 4 + 3] = sourceTangents[g + 3] as number;\n } else {\n tangentsCat[(vertexCursor + i) * 4 + 0] = 1;\n tangentsCat[(vertexCursor + i) * 4 + 3] = 1;\n }\n if (colorsCat !== undefined) {\n const colorDst = (vertexCursor + i) * 4;\n const colorSrc = i * 4;\n if (mesh.colors0 === undefined) {\n colorsCat[colorDst + 0] = 1;\n colorsCat[colorDst + 1] = 1;\n colorsCat[colorDst + 2] = 1;\n colorsCat[colorDst + 3] = 1;\n } else {\n colorsCat[colorDst + 0] = mesh.colors0[colorSrc + 0] as number;\n colorsCat[colorDst + 1] = mesh.colors0[colorSrc + 1] as number;\n colorsCat[colorDst + 2] = mesh.colors0[colorSrc + 2] as number;\n colorsCat[colorDst + 3] = mesh.colors0[colorSrc + 3] as number;\n }\n }\n for (let targetIndex = 0; targetIndex < morphTargetCount; targetIndex++) {\n const source = mesh.morphTargets?.[targetIndex];\n const target = morphTargets[targetIndex] as MorphTarget;\n const vertex = vertexCursor + i;\n if (source?.position !== undefined && target.position !== undefined) {\n target.position.set(source.position.subarray(i * 3, i * 3 + 3), vertex * 3);\n }\n if (source?.normal !== undefined && target.normal !== undefined) {\n target.normal.set(source.normal.subarray(i * 3, i * 3 + 3), vertex * 3);\n }\n if (source?.tangent !== undefined && target.tangent !== undefined) {\n target.tangent.set(source.tangent.subarray(i * 4, i * 4 + 4), vertex * 4);\n }\n }\n // D-2 / w8: when the MeshAsset is promoted to a skinned projection,\n // retain both canonical standalone arrays. The geometry packer writes\n // their typed values into the canonical interleaved byte layout once.\n if (hasAnySkin && skinIndicesCat !== undefined && skinWeightsCat !== undefined) {\n const skinDst = (vertexCursor + i) * 4;\n if (mesh.joints0 !== undefined && mesh.weights0 !== undefined) {\n const j = i * 4;\n const j0 = mesh.joints0[j + 0] as number;\n const j1 = mesh.joints0[j + 1] as number;\n const j2 = mesh.joints0[j + 2] as number;\n const j3 = mesh.joints0[j + 3] as number;\n skinIndicesCat[skinDst + 0] = j0;\n skinIndicesCat[skinDst + 1] = j1;\n skinIndicesCat[skinDst + 2] = j2;\n skinIndicesCat[skinDst + 3] = j3;\n const w0 = mesh.weights0[j + 0] as number;\n const w1 = mesh.weights0[j + 1] as number;\n const w2 = mesh.weights0[j + 2] as number;\n const w3 = mesh.weights0[j + 3] as number;\n skinWeightsCat[skinDst + 0] = w0;\n skinWeightsCat[skinDst + 1] = w1;\n skinWeightsCat[skinDst + 2] = w2;\n skinWeightsCat[skinDst + 3] = w3;\n }\n // else: unskinned primitive in a mixed MeshAsset; typed arrays remain\n // zero-filled, which is the canonical fallback.\n }\n // feat-20260629-multi-uv-set-support m1-w3: write uv1..uvK after skin data.\n // Canonical interleaved order: position/normal/uv/tangent/skinIndex/skinWeight/uv1..uv7.\n // UV1 starts at offset UV1_OFFSET (12 for unskinned, 18 for skinned) in float slots.\n // Each additional UV set 2F. Missing texcoordK → zero-fill (plan-strategy M1).\n for (let k = 1; k <= uvKeys.length; k++) {\n const uvKey = `texcoord${k}` as keyof GltfMeshIr;\n const catIdx = k - 1;\n const cat = uvCats[catIdx] as Float32Array;\n const catDst = (vertexCursor + i) * 2;\n const srcArr = mesh[uvKey] as Float32Array | undefined;\n if (srcArr !== undefined) {\n const t = i * 2;\n cat[catDst + 0] = srcArr[t + 0] as number;\n cat[catDst + 1] = srcArr[t + 1] as number;\n }\n // else: zero-fill (implicit — Float32Array defaults to 0)\n }\n }\n // Bias each submesh's indices by the running vertex offset so they\n // reference into the merged vertex buffer rather than the per-primitive\n // local 0-base. When the merged MeshAsset is non-indexed (hasAnyIndices\n // === false → `indices` is undefined here), skip the bias loop and\n // emit a vertex-only submesh (indexCount=0; runtime dispatches via\n // `pass.draw(vertexCount)`). When mixed (some prims indexed, this one\n // not), synthesize identity indices [vertexCursor..+primVertexCount-1]\n // so the merged single-index-buffer contract holds.\n if (indices !== undefined) {\n if (mesh.indices !== undefined) {\n for (let i = 0; i < primIndexCount; i++) {\n const src = mesh.indices[i] as number;\n indices[indexCursor + i] = src + vertexCursor;\n }\n submeshes.push({\n indexOffset: indexCursor,\n indexCount: primIndexCount,\n vertexCount: primVertexCount,\n topology: 'triangle-list',\n materialSlot,\n });\n indexCursor += primIndexCount;\n } else {\n // mixed bag: synthesize identity indices for this non-indexed prim\n for (let i = 0; i < primVertexCount; i++) {\n indices[indexCursor + i] = vertexCursor + i;\n }\n submeshes.push({\n indexOffset: indexCursor,\n indexCount: primVertexCount,\n vertexCount: primVertexCount,\n topology: 'triangle-list',\n materialSlot,\n });\n indexCursor += primVertexCount;\n }\n } else {\n // pure non-indexed mesh: indexCount=0, vertexCount carries draw count.\n submeshes.push({\n indexOffset: 0,\n indexCount: 0,\n vertexCount: primVertexCount,\n topology: 'triangle-list',\n materialSlot,\n });\n }\n vertexCursor += primVertexCount;\n }\n\n const attributes: VertexAttributeMap = {\n position: positionsCat,\n normal: normalsCat,\n uv: uvsCat,\n tangent: tangentsCat,\n ...(colorsCat === undefined ? {} : { color: colorsCat }),\n ...(skinIndicesCat === undefined ? {} : { skinIndex: skinIndicesCat }),\n ...(skinWeightsCat === undefined ? {} : { skinWeight: skinWeightsCat }),\n ...Object.fromEntries(uvCats.map((cat, idx) => [`uv${idx + 1}`, cat])),\n };\n const packed = packInterleavedVertexAttributes(attributes, totalVertexCount);\n if (!packed.ok) {\n return err(\n gltfErr('gltf-mesh-bridge-invalid', {\n meshIndex: prims[0]?.meshIndex ?? -1,\n reason: 'layout-invalid',\n cause: packed.error.detail,\n }),\n );\n }\n\n return ok({\n kind: 'mesh',\n vertices: packed.value.vertices,\n ...(indices === undefined ? {} : { indices }),\n submeshes,\n materialSlots,\n aabb: box3.fromPositions(box3.create(), positionsCat),\n attributes,\n ...(morphTargetCount === 0 ? {} : { morphTargets }),\n ...(prims[0]?.morphWeights === undefined\n ? {}\n : { morphWeights: new Float32Array(prims[0].morphWeights) }),\n });\n}\n\nexport interface GltfBridgeContext {\n /** glTF mesh index -> registry MeshAsset handle (multi-submesh). */\n readonly meshHandles: ReadonlyMap<number, Handle<'MeshAsset', 'shared'>>;\n /** glTF material index -> registry MaterialAsset handle. */\n readonly materialHandles: ReadonlyMap<number, Handle<'MaterialAsset', 'shared'>>;\n /**\n * glTF skin index -> SkeletonAsset GUID (string form). When a GltfNodeIr carries\n * a skin reference, the bridge emits `Skin: { skeleton: <guid-string> }` on\n * that node's entity; AssetRegistry._resolveSceneGuids resolves the GUID to\n * a runtime Handle at instantiate time (same protocol as MeshFilter and\n * MeshRenderer.materials[]). Optional — skinless glTFs pass an empty Map\n * (or omit the field) and the bridge does not emit Skin.\n *\n * tweak-20260611 M6 / D-7: emitting Skin from the bridge means the standard\n * loadByGuid<SceneAsset> + instantiate path Just Works for skinned glTF;\n * demos no longer need to runtime-parseGlb + post-load patch the SceneAsset.\n * postSpawnResolveJoints (called from AssetRegistry.instantiate) walks the\n * matching SkinAsset.jointPaths against the spawn subtree to fill Skin.joints[].\n */\n readonly skeletonGuidBySkinIndex?: ReadonlyMap<number, string>;\n /**\n * glTF node index -> a live renderer-owned instance collection identity.\n * The bridge is intentionally pure and cannot mint collection ids or copy\n * matrix bytes into ECS. Runtime consumers create collections through their\n * Renderer first, then provide this map when lowering the SceneAsset.\n */\n readonly instanceCollectionIdsByNodeIndex?: ReadonlyMap<number, number>;\n}\n\ninterface MutableSceneEntity {\n localId: LocalEntityId;\n components: Record<string, Record<string, unknown>>;\n /** Index into the external `nodes` array, set after push for ChildOf wiring. */\n localIdx: number;\n}\n\nfunction lightDirection(currentWorld: Mat4): readonly [number, number, number] {\n const direction = mat4.getForward(vec3.create(), currentWorld);\n return [direction[0] ?? 0, direction[1] ?? 0, direction[2] ?? -1];\n}\n\nfunction lightComponent(\n light: GltfPunctualLightIr,\n direction: readonly [number, number, number],\n): Record<string, unknown> {\n const range = light.range ?? Number.POSITIVE_INFINITY;\n if (light.type === 'directional') {\n return { direction, color: light.color, intensity: light.intensity };\n }\n if (light.type === 'point') {\n return { color: light.color, intensity: light.intensity, range };\n }\n return {\n direction,\n color: light.color,\n intensity: light.intensity,\n range,\n innerConeDeg: ((light.spot?.innerConeAngle ?? 0) * 180) / Math.PI,\n outerConeDeg: ((light.spot?.outerConeAngle ?? Math.PI / 4) * 180) / Math.PI,\n castShadow: false,\n };\n}\n\n/**\n * Convert a local TRS (translation, rotation quat, scale) into a Mat4.\n * Uses @forgeax/engine-math out-param style. `out` is mutated in place.\n */\nfunction composeMat4(\n out: Mat4,\n tx: number,\n ty: number,\n tz: number,\n qx: number,\n qy: number,\n qz: number,\n qw: number,\n sx: number,\n sy: number,\n sz: number,\n): void {\n const t = vec3.create(tx, ty, tz);\n const r = quat.create();\n r[0] = qx;\n r[1] = qy;\n r[2] = qz;\n r[3] = qw;\n const s = vec3.create(sx, sy, sz);\n mat4.compose(out, t, r, s);\n}\n\n/**\n * Convert a parsed GltfDoc into a SceneAsset POD. Caller supplies registry\n * handles via `ctx`; the bridge does no registration of its own.\n *\n * Visits the default scene's nodes depth-first, accumulating world-space\n * transforms from parent to child (B3). Assigns sequential LocalEntityId in\n * document order for reimport-stable identity. Camera nodes are detected by\n * GltfNodeIr.camera (B6 fix).\n *\n * B1: each glTF mesh's N primitives are merged into a single entity.\n * The caller provides `ctx.meshHandles` keyed by glTF mesh index, where each\n * handle points to a MeshAsset whose `submeshes` already span all primitives.\n * `ctx.materialHandles` is keyed by glTF material index; the bridge assembles a\n * `MeshRenderer.materials[]` array from the primitives' materialIndex values\n * in the order they appear in `doc.meshes`.\n *\n * B2: visit recursively walks `ir.children`.\n *\n * D-2 (empty container): transform-only nodes (no mesh, no camera) produce\n * an entity with just Transform + optionally a Name component, preserving the\n * hierarchy for animation/picking hooks.\n */\nexport function gltfDocToSceneAsset(doc: GltfDoc, ctx: GltfBridgeContext): SceneAsset {\n const sceneIr = doc.scenes[doc.defaultSceneIndex];\n const resultNodes: MutableSceneEntity[] = [];\n if (sceneIr === undefined) return { kind: 'scene', entities: {} } as unknown as SceneAsset;\n const importedLights = doc.lights ?? doc.extensions?.KHR_lights_punctual?.lights ?? [];\n const animationTargetIds = new Map<number, string>();\n for (const clip of doc.animationClips) {\n for (const channel of clip.channels) {\n animationTargetIds.set(channel.targetNodeIndex, channel.targetId);\n }\n }\n\n // Per-node world matrix accumulator (B3 fix).\n const parentWorld = mat4.create();\n mat4.identity(parentWorld);\n const currentWorld = mat4.create();\n const localMat = mat4.create();\n\n // bug-20260613: SceneAsset entities also emit ChildOf when a glTF node has a\n // parent (line 547 below). Runtime propagateTransforms then derives\n // GlobalTransform.world via `parent.world * compose(child.local TRS)`. If we\n // wrote the *world* TRS into Transform here, every child node would get\n // baked twice -- once at importer time and again at propagate time --\n // collapsing the skin so vertices fly to (parent.world)^2 space and the\n // mesh appears as a scrambled silhouette. Mirror GltfNodeIr.transform's local\n // TRS verbatim; propagateTransforms is the single accumulation path.\n const pushLocalTransform = (\n transform: import('./transform.js').DecomposedTransform,\n ): Record<string, unknown> => ({\n pos: [\n transform.translation[0] ?? 0,\n transform.translation[1] ?? 0,\n transform.translation[2] ?? 0,\n ],\n // Quaternion component order [x, y, z, w] (glTF-aligned; E6).\n quat: [\n transform.rotation[0] ?? 0,\n transform.rotation[1] ?? 0,\n transform.rotation[2] ?? 0,\n transform.rotation[3] ?? 1,\n ],\n scale: [transform.scale[0] ?? 1, transform.scale[1] ?? 1, transform.scale[2] ?? 1],\n });\n\n const visit = (gltfNodeIdx: number, parentLocalIdx: number | null): void => {\n const ir = doc.nodes[gltfNodeIdx];\n if (ir === undefined) return;\n\n // Compute local transform matrix\n composeMat4(\n localMat,\n ir.transform.translation[0] ?? 0,\n ir.transform.translation[1] ?? 0,\n ir.transform.translation[2] ?? 0,\n ir.transform.rotation[0] ?? 0,\n ir.transform.rotation[1] ?? 0,\n ir.transform.rotation[2] ?? 0,\n ir.transform.rotation[3] ?? 1,\n ir.transform.scale[0] ?? 1,\n ir.transform.scale[1] ?? 1,\n ir.transform.scale[2] ?? 1,\n );\n\n // Accumulate world transform (B3: parent * local)\n if (parentLocalIdx === null) {\n // Root node: world = local\n for (let i = 0; i < 16; i++) {\n currentWorld[i] = localMat[i] ?? 0;\n }\n } else {\n mat4.multiply(currentWorld, parentWorld, localMat);\n }\n\n // B6: detect camera via GltfNodeIr.camera field (not legacy heuristic)\n const isCamera = ir.camera !== null;\n\n // D-2: empty container rule\n // - mesh node: MeshFilter + MeshRenderer\n // - camera node: Camera (standalone entity)\n // - transform-only node (no mesh, no camera): Transform-only entity to preserve hierarchy\n const hasMesh = ir.meshIndex !== null;\n\n // Always produce a node for every glTF node (preserves hierarchy).\n // Transform-only nodes carry just Transform + optionally Name.\n const components: Record<string, Record<string, unknown>> = {\n Transform: pushLocalTransform(ir.transform),\n };\n\n const importedLight = importedLights[ir.lightIndex ?? -1];\n if (importedLight !== undefined) {\n const componentName =\n importedLight.type === 'directional'\n ? 'DirectionalLight'\n : importedLight.type === 'point'\n ? 'PointLight'\n : 'SpotLight';\n components[componentName] = lightComponent(\n importedLight,\n lightDirection(currentWorld),\n ) as Record<string, unknown>;\n }\n\n if (ir.name !== undefined && ir.name !== '') {\n components.Name = { value: ir.name };\n }\n const animationTargetId = animationTargetIds.get(gltfNodeIdx);\n if (animationTargetId !== undefined) {\n components.AnimationTargetId = { value: animationTargetId };\n }\n\n if (hasMesh) {\n const meshHandle = ctx.meshHandles.get(ir.meshIndex as number);\n if (meshHandle !== undefined) {\n components.MeshFilter = { assetHandle: meshHandle };\n }\n const meshMorph = doc.meshes.find((mesh) => mesh.meshIndex === ir.meshIndex);\n const morphCount = meshMorph?.morphTargets?.length ?? 0;\n if (morphCount > 0) {\n const weights = ir.morphWeights ?? meshMorph?.morphWeights ?? new Float32Array(morphCount);\n if (weights.length !== morphCount) {\n throw new Error('gltfDocToSceneAsset: MorphWeights length does not match morph targets');\n }\n components.MorphWeights = { weights: new Float32Array(weights) };\n }\n // tweak-20260611 M6: when this node references a glTF skin, stamp a\n // Skin component carrying the SkeletonAsset GUID as a string. The\n // runtime AssetRegistry._resolveSceneGuids resolves the string to a\n // Handle at instantiate time (same protocol as MeshFilter/MeshRenderer).\n // postSpawnResolveJoints (called from AssetRegistry.instantiate) then\n // fills Skin.joints[] by walking the matching SkinAsset.jointPaths\n // against the spawn subtree's Name index.\n if (ir.skinIndex !== null && ctx.skeletonGuidBySkinIndex !== undefined) {\n const skeletonGuid = ctx.skeletonGuidBySkinIndex.get(ir.skinIndex);\n if (skeletonGuid !== undefined) {\n components.Skin = { skeleton: skeletonGuid };\n }\n }\n // B1: collect one material handle per primitive belonging to THIS\n // node's glTF mesh (filter by meshIr.meshIndex === ir.meshIndex), in\n // the same order primitives are emitted in `doc.meshes`. The merged\n // MeshAsset built by `meshIrToMeshAsset` walks the same filter in the\n // same order to produce one Submesh per primitive, so submeshes[i]\n // pairs with materials[i] positionally (AGENTS.md §Component naming\n // \"positional materials[i] <-> submeshes[i]\" + #317 multi-material\n // contract).\n //\n // A primitive with materialIndex===null (or one whose ctx.materialHandles\n // lookup misses) gets a synthetic missing-handle entry: dropping it\n // would desynchronise materials[].length vs submeshes[].length and\n // trigger the fail-fast `mesh-renderer-material-count-mismatch` at\n // register time. Falling back to the first available material handle\n // for the same mesh keeps the count alignment without inventing a\n // shared default-material handle (Tier-B scope; Sponza / BoxTextured\n // every primitive carries an explicit material so this fallback path\n // is exercised only by under-specified glTFs).\n // Mesh-owned slots carry imported defaults. Scene nodes persist only\n // true instance differences, so the canonical imported node starts with\n // an empty per-slot override vector.\n components.MeshRenderer = { materials: [] };\n }\n\n // Instances on the same entity as MeshFilter/MeshRenderer. The bridge\n // only carries the renderer-owned identity; IR matrix bytes stay in the\n // caller's collection and never become an ECS managed array. Build-time\n // consumers that do not have a Renderer omit this optional association and\n // must materialise the collection at their runtime boundary.\n if (ir.instancing !== undefined) {\n const collectionId = ctx.instanceCollectionIdsByNodeIndex?.get(gltfNodeIdx);\n if (collectionId !== undefined) {\n components.Instances = { collectionId };\n }\n }\n\n if (isCamera) {\n // B6: camera node detected via GltfNodeIr.camera (not heuristic).\n // Camera component sits alongside Transform (and Name if present).\n components.Camera = {\n fov: 0.7853981633974483,\n aspect: 1.7777777777777777,\n near: 0.1,\n far: 100,\n };\n }\n\n const localIdx = resultNodes.length;\n const node: MutableSceneEntity = {\n localId: localIdx as LocalEntityId,\n components,\n localIdx,\n };\n\n // ChildOf wiring: if this node has a parent, add ChildOf component\n if (parentLocalIdx !== null) {\n node.components.ChildOf = { parent: parentLocalIdx as LocalEntityId };\n }\n\n resultNodes.push(node);\n\n // B2: recursively visit children with accumulated world matrix.\n // B3: set parentWorld to this node's world matrix so children multiply\n // correctly (parent * childLocal = childWorld).\n const savedParent = mat4.clone(parentWorld);\n for (let i = 0; i < 16; i++) parentWorld[i] = currentWorld[i] ?? 0;\n\n for (const childIdx of ir.children) {\n visit(childIdx, localIdx);\n }\n\n // Restore parent world after visiting all children\n for (let i = 0; i < 16; i++) parentWorld[i] = savedParent[i] ?? 0;\n };\n\n for (const rootIdx of sceneIr.nodes) visit(rootIdx, null);\n\n const keyByLocalId = new Map<number, string>();\n for (const node of resultNodes) keyByLocalId.set(node.localIdx, `node-${node.localIdx}`);\n const entities: Record<string, { readonly components: Record<string, Record<string, unknown>> }> =\n {};\n for (const node of resultNodes) {\n const components = { ...node.components };\n const childOf = components.ChildOf;\n if (childOf !== undefined && typeof childOf.parent === 'number') {\n const parentKey = keyByLocalId.get(childOf.parent);\n if (parentKey === undefined)\n throw new Error(`gltfDocToSceneAsset: missing parent node ${childOf.parent}`);\n components.ChildOf = { ...childOf, parent: parentKey };\n }\n entities[`node-${node.localIdx}`] = { components };\n }\n const lightFacts = importedLights.map((light) => ({\n kind: light.type,\n intensity: light.intensity,\n ...(light.range === undefined ? {} : { range: light.range }),\n ...(light.spot === undefined ? {} : { spot: light.spot }),\n }));\n return {\n kind: 'scene',\n entities,\n ...(lightFacts.length === 0 ? {} : { lights: lightFacts }),\n } as unknown as SceneAsset;\n}\n\n/** Internal helper: mark GltfNodeIr usable so future surface evolutions stay typed. */\nexport type _NodeIrAlias = GltfNodeIr;\n\nexport interface MaterialBridgeContext {\n /** glTF texture index -> registry TextureAsset handle. */\n readonly textureHandles?: ReadonlyMap<number, Handle<'TextureAsset', 'shared'>>;\n /** glTF sampler index -> registry SamplerAsset handle. */\n readonly samplerHandles?: ReadonlyMap<number, Handle<'SamplerAsset', 'shared'>>;\n /** Built-in standard MaterialAsset GUID supplied by the importing project. */\n readonly standardRootGuid?: AssetGuid;\n /**\n * feat-20260611 w17-a: when any primitive consuming this material carries\n * JOINTS_0 + WEIGHTS_0, the cooker passes `skinned: true` so the emitted\n * MaterialAsset's pass[0].program.module is `forgeax::pbr-skin` instead of\n * `forgeax::default-standard-pbr`. The cooker (gltf-importer) is the only\n * site with full mesh<->material wiring info; routing here keeps shader\n * choice content-driven (not user-driven, per Q4 — runtime fail-fast in\n * render-system-extract remains the reverse-direction safety net).\n */\n readonly skinned?: boolean;\n}\n\nfunction textureInfo(info: GltfTextureInfoIr | number | undefined): GltfTextureInfoIr | undefined {\n return info === undefined ? undefined : typeof info === 'number' ? { texture: info } : info;\n}\n\ntype MaterialTextureSlot =\n | 'baseColorTexture'\n | 'metallicRoughnessTexture'\n | 'normalTexture'\n | 'occlusionTexture'\n | 'emissiveTexture'\n | 'transmissionTexture'\n | 'thicknessTexture'\n | 'clearcoatTexture'\n | 'clearcoatRoughnessTexture'\n | 'clearcoatNormalTexture'\n | 'anisotropyTexture'\n | 'sheenColorTexture'\n | 'sheenRoughnessTexture'\n | 'iridescenceTexture'\n | 'iridescenceThicknessTexture'\n | 'specularTexture'\n | 'specularColorTexture';\n\nfunction textureValue(\n info: GltfTextureInfoIr | number | undefined,\n slot: MaterialTextureSlot,\n ctx: MaterialBridgeContext | undefined,\n): MaterialTextureValue | undefined {\n const binding = textureInfo(info);\n if (binding === undefined || ctx?.textureHandles === undefined) return undefined;\n const textureHandle = ctx.textureHandles.get(binding.texture);\n if (textureHandle === undefined) return undefined;\n const samplerHandle =\n binding.sampler === undefined ? undefined : ctx.samplerHandles?.get(binding.sampler);\n const coordinates =\n binding.texCoord === undefined && binding.transform === undefined\n ? undefined\n : {\n ...(binding.texCoord === undefined ? {} : { set: binding.texCoord }),\n ...(binding.transform === undefined ? {} : { transform: binding.transform }),\n };\n const value = {\n texture: textureHandle as unknown as MaterialTextureValue['texture'],\n ...(samplerHandle === undefined\n ? {}\n : { sampler: samplerHandle as unknown as NonNullable<MaterialTextureValue['sampler']> }),\n ...(coordinates === undefined ? {} : { coordinates }),\n };\n if (slot === 'normalTexture') {\n const normal = info as GltfMaterialIr['normalTexture'];\n if (typeof normal === 'object' && normal?.scale !== undefined) {\n return { ...value, normalScale: normal.scale };\n }\n }\n if (slot === 'clearcoatNormalTexture') {\n const normal = info as GltfMaterialIr['clearcoatNormalTexture'];\n if (typeof normal === 'object' && normal?.scale !== undefined) {\n return { ...value, normalScale: normal.scale };\n }\n }\n if (slot === 'occlusionTexture') {\n const occlusion = info as GltfMaterialIr['occlusionTexture'];\n if (typeof occlusion === 'object' && occlusion?.strength !== undefined) {\n return { ...value, occlusionStrength: occlusion.strength };\n }\n }\n return value;\n}\n\n/**\n * Select the exact Standard root contract emitted by the glTF producer.\n * Numeric/base fields come from the shared schema; physical texture slots are\n * admitted only when the source actually declares them. A parent root is\n * retained for the legacy base-only path, while an extended glTF material\n * becomes its own root so its extension declarations own cook/ABI identity.\n */\nfunction standardRootParameterNames(mat: GltfMaterialIr): {\n readonly names: ReadonlySet<string>;\n readonly extended: boolean;\n} {\n const names = new Set(\n STANDARD_MATERIAL_PARAM_SCHEMA.filter(\n (entry) =>\n !STANDARD_PHYSICAL_PARAMETER_NAMES.has(entry.name) &&\n !STANDARD_TRANSMISSION_PARAMETER_NAMES.has(entry.name),\n ).map((entry) => entry.name),\n );\n // IOR is consumed for the base dielectric F0 fallback even when the\n // transmission/volume extension is absent.\n names.add('ior');\n\n const addLayer = (layer: keyof typeof STANDARD_LAYER_PARAMETER_GROUPS): void => {\n for (const name of STANDARD_LAYER_PARAMETER_GROUPS[layer]) names.add(name);\n };\n const addTexture = (name: string, info: GltfTextureInfoIr | number | undefined): void => {\n if (info !== undefined) names.add(name);\n };\n\n const clearcoat =\n mat.clearcoatFactor !== undefined ||\n mat.clearcoatRoughnessFactor !== undefined ||\n mat.clearcoatNormalTexture !== undefined ||\n mat.clearcoatTexture !== undefined ||\n mat.clearcoatRoughnessTexture !== undefined;\n const anisotropy =\n mat.anisotropyStrength !== undefined ||\n mat.anisotropyRotation !== undefined ||\n mat.anisotropyTexture !== undefined;\n const sheen =\n mat.sheenColorFactor !== undefined ||\n mat.sheenRoughnessFactor !== undefined ||\n mat.sheenColorTexture !== undefined ||\n mat.sheenRoughnessTexture !== undefined;\n const iridescence =\n mat.iridescenceFactor !== undefined ||\n mat.iridescenceIor !== undefined ||\n mat.iridescenceThicknessMinimum !== undefined ||\n mat.iridescenceThicknessMaximum !== undefined ||\n mat.iridescenceTexture !== undefined ||\n mat.iridescenceThicknessTexture !== undefined;\n if (clearcoat) addLayer('clearcoat');\n if (anisotropy) addLayer('anisotropy');\n if (sheen) addLayer('sheen');\n if (iridescence) addLayer('iridescence');\n if (clearcoat && mat.clearcoatNormalTexture !== undefined) names.add('clearcoatNormalScale');\n\n addTexture('clearcoatTexture', mat.clearcoatTexture);\n addTexture('clearcoatRoughnessTexture', mat.clearcoatRoughnessTexture);\n addTexture('clearcoatNormalTexture', mat.clearcoatNormalTexture);\n addTexture('anisotropyTexture', mat.anisotropyTexture);\n addTexture('sheenColorTexture', mat.sheenColorTexture);\n addTexture('sheenRoughnessTexture', mat.sheenRoughnessTexture);\n addTexture('iridescenceTexture', mat.iridescenceTexture);\n addTexture('iridescenceThicknessTexture', mat.iridescenceThicknessTexture);\n addTexture('specularTexture', mat.specularTexture);\n addTexture('specularColorTexture', mat.specularColorTexture);\n\n const transmission =\n mat.transmissionFactor !== undefined ||\n mat.transmissionTexture !== undefined ||\n mat.ior !== undefined ||\n mat.thicknessFactor !== undefined ||\n mat.thicknessTexture !== undefined ||\n mat.attenuationColor !== undefined ||\n mat.attenuationDistance !== undefined;\n if (transmission) {\n // Transmission/volume keeps its existing paired backdrop ABI. The\n // producer may leave either value at its neutral fallback, but the pair\n // remains part of the pre-existing transmission root contract.\n for (const name of STANDARD_TRANSMISSION_PARAMETER_NAMES) names.add(name);\n }\n\n return {\n names,\n extended:\n clearcoat ||\n anisotropy ||\n sheen ||\n iridescence ||\n transmission ||\n mat.specularTexture !== undefined ||\n mat.specularColorTexture !== undefined,\n };\n}\n\nexport function validateMaterialUvSets(\n mat: GltfMaterialIr,\n primitive: string,\n availableSets: readonly number[],\n): Result<void, MaterialError> {\n const available = new Set(availableSets);\n const slots: readonly [MaterialTextureSlot, GltfTextureInfoIr | number | undefined][] = [\n ['baseColorTexture', mat.baseColorTexture],\n ['metallicRoughnessTexture', mat.metallicRoughnessTexture],\n ['normalTexture', mat.normalTexture],\n ['occlusionTexture', mat.occlusionTexture],\n ['emissiveTexture', mat.emissiveTexture],\n ['transmissionTexture', mat.transmissionTexture],\n ['thicknessTexture', mat.thicknessTexture],\n ['clearcoatTexture', mat.clearcoatTexture],\n ['clearcoatRoughnessTexture', mat.clearcoatRoughnessTexture],\n ['clearcoatNormalTexture', mat.clearcoatNormalTexture],\n ['anisotropyTexture', mat.anisotropyTexture],\n ['sheenColorTexture', mat.sheenColorTexture],\n ['sheenRoughnessTexture', mat.sheenRoughnessTexture],\n ['iridescenceTexture', mat.iridescenceTexture],\n ['iridescenceThicknessTexture', mat.iridescenceThicknessTexture],\n ['specularTexture', mat.specularTexture],\n ['specularColorTexture', mat.specularColorTexture],\n ];\n for (const [slot, rawBinding] of slots) {\n const binding = textureInfo(rawBinding);\n if (binding === undefined) continue;\n const requestedSet = binding.texCoord ?? 0;\n if (!available.has(requestedSet)) {\n return err(\n createMaterialError('gltf-material-uv-set-missing', {\n material: mat.name ?? '<unnamed>',\n primitive,\n slot,\n requestedSet,\n availableSets,\n }),\n );\n }\n }\n return ok(undefined);\n}\n\nexport function validateMaterialTangentInputs(\n mat: GltfMaterialIr,\n mesh: GltfMeshIr,\n layer = 'clearcoat',\n): Result<void, MaterialError> {\n // Anisotropy changes the base GGX lobe even when it has no texture map, so\n // its tangent direction is part of the scalar layer contract. Select UV 0\n // for the scalar-only form; a mapped form keeps the map's explicit UV set.\n const anisotropyDeclared =\n mat.anisotropyStrength !== undefined ||\n mat.anisotropyRotation !== undefined ||\n mat.anisotropyTexture !== undefined;\n const tangentSlot = anisotropyDeclared\n ? { layer: 'anisotropy', info: mat.anisotropyTexture }\n : mat.clearcoatNormalTexture !== undefined\n ? { layer: 'clearcoat', info: mat.clearcoatNormalTexture }\n : undefined;\n if (tangentSlot === undefined) return ok(undefined);\n const selected = textureInfo(tangentSlot.info);\n const uvSet = selected?.texCoord ?? 0;\n const uv = mesh[`texcoord${uvSet === 0 ? '0' : uvSet}` as keyof GltfMeshIr];\n const attributes = ['NORMAL', `TEXCOORD_${uvSet}`, 'TANGENT'];\n const fail = (reason: string): Result<void, MaterialError> =>\n err(\n createMaterialError('material-tangent-required', {\n code: 'material-tangent-required',\n material: mat.name ?? '<unnamed>',\n mesh: mesh.name ?? '<unnamed>',\n layer: tangentSlot.layer ?? layer,\n uv: `TEXCOORD_${uvSet}`,\n attributes,\n reason,\n }),\n );\n if (mesh.tangents !== undefined) {\n if (\n mesh.tangents.length !== (mesh.positions.length / 3) * 4 ||\n mesh.tangents.some((value) => !Number.isFinite(value))\n ) {\n return fail('imported TANGENT must be finite vec4 per vertex');\n }\n return ok(undefined);\n }\n if (mesh.normals === undefined) return fail('NORMAL is required to generate tangent');\n if (!(uv instanceof Float32Array))\n return fail('the selected UV set is required to generate tangent');\n const generated = computeTangentVec4(mesh.positions, mesh.normals, uv, mesh.indices);\n if (!generated.ok) {\n const detail = generated.error.detail;\n const reason =\n detail !== undefined && 'reason' in detail\n ? String(detail.reason)\n : 'tangent producer rejected topology';\n return fail(reason);\n }\n return ok(undefined);\n}\n\n/** Convert a parsed GltfMaterialIr into a standard-root derived MaterialAsset. */\nexport function toMaterialAsset(mat: GltfMaterialIr, ctx?: MaterialBridgeContext): MaterialAsset {\n const rootContract = standardRootParameterNames(mat);\n const values: Record<string, NonNullable<MaterialAsset['values']>[string]> = {\n baseColor: mat.baseColorFactor,\n metallic: mat.metallicFactor,\n roughness: mat.roughnessFactor,\n };\n if (mat.emissiveFactor !== undefined) {\n values.emissive = mat.emissiveFactor;\n values.emissiveIntensity = 1;\n }\n const textureSlots: readonly [MaterialTextureSlot, GltfTextureInfoIr | number | undefined][] = [\n ['baseColorTexture', mat.baseColorTexture],\n ['metallicRoughnessTexture', mat.metallicRoughnessTexture],\n ['normalTexture', mat.normalTexture],\n ['occlusionTexture', mat.occlusionTexture],\n ['emissiveTexture', mat.emissiveTexture],\n ['transmissionTexture', mat.transmissionTexture],\n ['thicknessTexture', mat.thicknessTexture],\n ['clearcoatTexture', mat.clearcoatTexture],\n ['clearcoatRoughnessTexture', mat.clearcoatRoughnessTexture],\n ['clearcoatNormalTexture', mat.clearcoatNormalTexture],\n ['anisotropyTexture', mat.anisotropyTexture],\n ['sheenColorTexture', mat.sheenColorTexture],\n ['sheenRoughnessTexture', mat.sheenRoughnessTexture],\n ['iridescenceTexture', mat.iridescenceTexture],\n ['iridescenceThicknessTexture', mat.iridescenceThicknessTexture],\n ['specularTexture', mat.specularTexture],\n ['specularColorTexture', mat.specularColorTexture],\n ];\n for (const [slot, info] of textureSlots) {\n const value = textureValue(info, slot, ctx);\n if (value !== undefined) values[slot] = value;\n }\n if (mat.occlusionTexture !== undefined && values.occlusionStrength === undefined) {\n values.occlusionStrength = 1;\n }\n if (rootContract.extended && rootContract.names.has('transmission')) {\n values.transmission = mat.transmissionFactor ?? 0;\n values.ior = mat.ior ?? 1.5;\n values.thickness = mat.thicknessFactor ?? 0;\n values.attenuationColor = mat.attenuationColor ?? [1, 1, 1];\n if (mat.attenuationDistance !== undefined) values.attenuationDistance = mat.attenuationDistance;\n }\n if (rootContract.names.has('clearcoat')) {\n values.clearcoat = mat.clearcoatFactor ?? 0;\n values.clearcoatRoughness = mat.clearcoatRoughnessFactor ?? 0;\n }\n const clearcoatNormal = textureInfo(mat.clearcoatNormalTexture) as\n | (GltfTextureInfoIr & { readonly scale?: number })\n | undefined;\n if (clearcoatNormal?.scale !== undefined) values.clearcoatNormalScale = clearcoatNormal.scale;\n if (rootContract.names.has('anisotropyStrength')) {\n values.anisotropyStrength = mat.anisotropyStrength ?? 0;\n values.anisotropyRotation = mat.anisotropyRotation ?? 0;\n }\n if (rootContract.names.has('sheenColor')) {\n values.sheenColor = mat.sheenColorFactor ?? [0, 0, 0];\n values.sheenRoughness = mat.sheenRoughnessFactor ?? 0;\n }\n if (rootContract.names.has('iridescence')) {\n values.iridescence = mat.iridescenceFactor ?? 0;\n values.iridescenceIor = mat.iridescenceIor ?? 1.3;\n values.iridescenceThicknessMinimum = mat.iridescenceThicknessMinimum ?? 100;\n values.iridescenceThicknessMaximum = mat.iridescenceThicknessMaximum ?? 400;\n }\n if (mat.specularFactor !== undefined) values.specular = mat.specularFactor;\n if (mat.specularColorFactor !== undefined) values.specularColor = mat.specularColorFactor;\n\n const module = ctx?.skinned === true ? 'forgeax::pbr-skin' : 'forgeax::default-standard-pbr';\n\n const isMask = mat.alphaMode === 'MASK';\n const alphaCutoff = isMask ? (mat.alphaCutoff ?? 0.5) : undefined;\n if (alphaCutoff !== undefined) values.alphaCutoff = alphaCutoff;\n\n // glTF BLEND uses straight alpha and does not write depth.\n const isBlend = mat.alphaMode === 'BLEND';\n const straightAlphaBlend = {\n color: {\n srcFactor: 'src-alpha' as const,\n dstFactor: 'one-minus-src-alpha' as const,\n operation: 'add' as const,\n },\n alpha: {\n srcFactor: 'one' as const,\n dstFactor: 'one-minus-src-alpha' as const,\n operation: 'add' as const,\n },\n };\n\n // feat-city-glb Bug 5: transparent (BLEND) materials read but do NOT write\n // depth (`depthWriteEnabled: false`), matching the engine's own transparent\n // convention (learn-render 4.3 blending window material). glTF decals are\n // frequently coplanar with the opaque surface they overlay (e.g. a crosswalk\n // decal on the road); writing depth would z-fight / self-occlude. Back-to-\n // front ordering is handled by the Transparent queue + transparent sort.\n const pass = {\n name: 'Forward',\n program: { module },\n renderState: {\n tags: { LightMode: 'Forward' },\n queue: (isBlend ? 3000 : isMask ? 2450 : 2000) as RenderQueue,\n ...(isBlend || isMask || mat.doubleSided === true\n ? {\n ...(isBlend ? { blend: straightAlphaBlend, depthWriteEnabled: false } : {}),\n ...(mat.doubleSided === true ? { cullMode: 'none' as const } : {}),\n }\n : {}),\n },\n };\n\n const child = !rootContract.extended && ctx?.standardRootGuid !== undefined;\n return {\n kind: 'material',\n ...(child\n ? { parent: ctx.standardRootGuid }\n : {\n colorSpace: 'linear' as const,\n passes: [pass] as [typeof pass, ...(typeof pass)[]],\n parameters: standardMaterialParameters(rootContract.names),\n }),\n values,\n };\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","// 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","// extract-image-bytes.ts - resolve glTF `images[<imageIndex>]` into raw\n// PNG / JPEG bytes (feat-20260608 M3 D-6 / requirements AC-08 + AC-09 + AC-10).\n//\n// The gltfImporter walks `images[]` and funnels three image source paths\n// through a single decode seam:\n// (a) bufferView : slice the named buffer at the bufferView range\n// (b) data: URI : base64-decode the URI payload\n// (c) external URI : ctx.readSibling(uri) reads the file co-located\n// with the .gltf source\n//\n// This module owns the byte-extraction (no decoding); decoding is the job of\n// ctx.decodeImage (D-1 seam: gltfImporter never imports\n// `@forgeax/engine-image` directly). On any failure the caller produces a\n// `gltf-image-extract-failed` GltfError carrying { imageIndex, source,\n// reason }.\n//\n// Why not reuse parse-gltf.ts's buffer resolution? parseGltf.ts encapsulates\n// buffer / bufferView decoding inside `parseGltfWithBin` and never surfaces\n// the byte arrays. Re-running that machinery for image extraction would\n// double the work; instead the gltfImporter parses the doc twice (parseGltf\n// for the IR, this helper for the raw bytes) — both passes are O(file\n// size) and the importer only runs at build time.\n\nimport type { ImportContext, ImportError as ImportErrorType } from '@forgeax/engine-types';\nimport { dataUriBase64Payload, decodeBase64 } from './data-uri.js';\nimport { parseGlbChunks } from './parse-glb-chunks.js';\n\n/** Source of an image: matches `GltfImageExtractFailedDetail.source`. */\nexport type ImageSourceKind = 'bufferView' | 'data-uri' | 'external-uri';\n\n/** One extracted image: bytes + the source kind that produced them. */\nexport interface ExtractedImage {\n readonly bytes: Uint8Array;\n readonly mimeType: 'image/png' | 'image/jpeg';\n readonly source: ImageSourceKind;\n}\n\n/**\n * Failure shape — the importer wraps this in a `gltf-image-extract-failed`\n * GltfError. `source` may be undefined when the image row is malformed\n * (no uri / no bufferView), so the importer can name 'bufferView' (most\n * common) by default.\n */\nexport interface ExtractFailure {\n readonly imageIndex: number;\n readonly source: ImageSourceKind;\n readonly reason: string;\n}\n\nconst DATA_URI_MIME_RE = /^data:([^;,]+)(?:;[^,;]+)*;base64,/;\n\n/** Pull the source-read-failed reason out of an ImportError without\n * widening the discriminated union — the caller only ever sees\n * source-read-failed here (readSibling's only failure shape). The\n * ImportError class carries a structurally typed `.detail` field that does\n * not auto-narrow on the `.code` discriminator, so we read `.message`\n * which the class composes from `expected: ...; reason: ...`. */\nfunction describeImportError(err: ImportErrorType): string {\n return err.message;\n}\n\n/** Pick PNG vs JPEG from declared mimeType + magic-byte fallback. */\nfunction classifyMime(\n declaredMime: string | undefined,\n bytes: Uint8Array,\n): 'image/png' | 'image/jpeg' | undefined {\n if (declaredMime === 'image/png' || declaredMime === 'image/jpeg') return declaredMime;\n if (\n bytes.length >= 8 &&\n bytes[0] === 0x89 &&\n bytes[1] === 0x50 &&\n bytes[2] === 0x4e &&\n bytes[3] === 0x47\n ) {\n return 'image/png';\n }\n if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) {\n return 'image/jpeg';\n }\n return undefined;\n}\n\ninterface BufferViewJsonSlim {\n readonly buffer: number;\n readonly byteOffset?: number;\n readonly byteLength: number;\n}\n\ninterface ImageJsonSlim {\n readonly uri?: string;\n readonly mimeType?: string;\n readonly bufferView?: number;\n}\n\ninterface BufferJsonSlim {\n readonly uri?: string;\n readonly byteLength: number;\n}\n\ninterface RootJsonSlim {\n readonly images?: readonly ImageJsonSlim[];\n readonly bufferViews?: readonly BufferViewJsonSlim[];\n readonly buffers?: readonly BufferJsonSlim[];\n}\n\n/**\n * Extract raw image bytes for every `images[]` row in the parsed glTF doc.\n *\n * @param sourceBytes the original .glb / .gltf file bytes (the GLB BIN\n * chunk is reconstructed from these for buffer-0 lookups).\n * @param sourcePath the meta.source path; used only for diagnostics\n * (parseGlbChunks errors carry it through).\n * @param ctx the ImportContext — reused for `readSibling` (external\n * buffer .bin / external image .png/.jpg). data: URIs do not call ctx.\n *\n * Returns a Map<imageIndex, ExtractedImage> with one entry per resolved\n * image. Rows that fail to extract are returned in `failures[]` so the\n * caller can emit one `gltf-image-extract-failed` per failure (single\n * failure does not abort the whole importer — the runner's GUID iron-law\n * check then surfaces missing image GUIDs as a structured outage instead\n * of the silent white-box render).\n */\nexport async function extractImageBytes(\n sourceBytes: Uint8Array,\n sourcePath: string,\n ctx: ImportContext,\n): Promise<{\n readonly extracted: ReadonlyMap<number, ExtractedImage>;\n readonly failures: readonly ExtractFailure[];\n}> {\n const isGlb = sourcePath.toLowerCase().endsWith('.glb');\n let json: RootJsonSlim;\n let glbBin: Uint8Array | undefined;\n\n if (isGlb) {\n const ab = sourceBytes.buffer.slice(\n sourceBytes.byteOffset,\n sourceBytes.byteOffset + sourceBytes.byteLength,\n ) as ArrayBuffer;\n const chunks = parseGlbChunks(ab, sourcePath);\n if (!chunks.ok) {\n return {\n extracted: new Map(),\n failures: [\n {\n imageIndex: -1,\n source: 'bufferView',\n reason: `GLB chunk parse failed: ${chunks.error.code}`,\n },\n ],\n };\n }\n try {\n json = JSON.parse(new TextDecoder().decode(chunks.value.jsonChunk)) as RootJsonSlim;\n } catch (e) {\n return {\n extracted: new Map(),\n failures: [\n {\n imageIndex: -1,\n source: 'bufferView',\n reason: `GLB JSON parse failed: ${e instanceof Error ? e.message : String(e)}`,\n },\n ],\n };\n }\n glbBin = chunks.value.binChunk;\n } else {\n try {\n json = JSON.parse(new TextDecoder().decode(sourceBytes)) as RootJsonSlim;\n } catch (e) {\n return {\n extracted: new Map(),\n failures: [\n {\n imageIndex: -1,\n source: 'bufferView',\n reason: `gltf JSON parse failed: ${e instanceof Error ? e.message : String(e)}`,\n },\n ],\n };\n }\n }\n\n const images = json.images ?? [];\n const bufferViews = json.bufferViews ?? [];\n const buffersJson = json.buffers ?? [];\n const extracted = new Map<number, ExtractedImage>();\n const failures: ExtractFailure[] = [];\n\n // Resolve buffers (lazy: only buffers actually referenced by images get fetched).\n const buffersCache = new Map<number, Uint8Array | { readonly error: ImportErrorType | string }>();\n async function getBuffer(bufferIndex: number): Promise<Uint8Array | { readonly error: string }> {\n const cached = buffersCache.get(bufferIndex);\n if (cached !== undefined) {\n if (cached instanceof Uint8Array) return cached;\n const e = cached.error;\n return { error: typeof e === 'string' ? e : e.message };\n }\n const bufJson = buffersJson[bufferIndex];\n if (bufJson === undefined) {\n const reason = `buffer index ${bufferIndex} out of range (have ${buffersJson.length})`;\n buffersCache.set(bufferIndex, { error: reason });\n return { error: reason };\n }\n if (bufJson.uri === undefined) {\n // GLB BIN chunk slot — buffer-0.\n if (glbBin === undefined) {\n const reason = `buffer ${bufferIndex} has no uri and no GLB BIN chunk available`;\n buffersCache.set(bufferIndex, { error: reason });\n return { error: reason };\n }\n buffersCache.set(bufferIndex, glbBin);\n return glbBin;\n }\n const dataPayload = dataUriBase64Payload(bufJson.uri);\n if (dataPayload !== undefined) {\n try {\n const bytes = decodeBase64(dataPayload);\n buffersCache.set(bufferIndex, bytes);\n return bytes;\n } catch (e) {\n const reason = `buffer ${bufferIndex} data URI base64 decode failed: ${e instanceof Error ? e.message : String(e)}`;\n buffersCache.set(bufferIndex, { error: reason });\n return { error: reason };\n }\n }\n const sib = await ctx.readSibling(bufJson.uri);\n if (!sib.ok) {\n const reason = `external buffer \"${bufJson.uri}\" read failed: ${describeImportError(sib.error)}`;\n buffersCache.set(bufferIndex, { error: reason });\n return { error: reason };\n }\n buffersCache.set(bufferIndex, sib.value);\n return sib.value;\n }\n\n for (let i = 0; i < images.length; i++) {\n const img = images[i];\n if (img === undefined) continue;\n\n if (img.bufferView !== undefined) {\n const bv = bufferViews[img.bufferView];\n if (bv === undefined) {\n failures.push({\n imageIndex: i,\n source: 'bufferView',\n reason: `bufferView index ${img.bufferView} out of range`,\n });\n continue;\n }\n const buf = await getBuffer(bv.buffer);\n if (!(buf instanceof Uint8Array)) {\n failures.push({ imageIndex: i, source: 'bufferView', reason: buf.error });\n continue;\n }\n const off = bv.byteOffset ?? 0;\n const len = bv.byteLength;\n if (off + len > buf.byteLength) {\n failures.push({\n imageIndex: i,\n source: 'bufferView',\n reason: `bufferView ${img.bufferView} byte range [${off}..${off + len}) exceeds buffer ${bv.buffer} length ${buf.byteLength}`,\n });\n continue;\n }\n const bytes = buf.subarray(off, off + len);\n const mime = classifyMime(img.mimeType, bytes);\n if (mime === undefined) {\n failures.push({\n imageIndex: i,\n source: 'bufferView',\n reason: `unsupported / unrecognised mime (declared \"${img.mimeType ?? '<absent>'}\", magic byte sniff failed)`,\n });\n continue;\n }\n extracted.set(i, { bytes: new Uint8Array(bytes), mimeType: mime, source: 'bufferView' });\n continue;\n }\n\n if (img.uri !== undefined) {\n const dataPayload = dataUriBase64Payload(img.uri);\n if (dataPayload !== undefined) {\n let bytes: Uint8Array;\n try {\n bytes = decodeBase64(dataPayload);\n } catch (e) {\n failures.push({\n imageIndex: i,\n source: 'data-uri',\n reason: `base64 decode failed: ${e instanceof Error ? e.message : String(e)}`,\n });\n continue;\n }\n const mimeMatch = DATA_URI_MIME_RE.exec(img.uri);\n const declaredMime = mimeMatch?.[1] ?? img.mimeType;\n const mime = classifyMime(declaredMime, bytes);\n if (mime === undefined) {\n failures.push({\n imageIndex: i,\n source: 'data-uri',\n reason: `data: URI mime \"${declaredMime ?? '<absent>'}\" not png/jpeg`,\n });\n continue;\n }\n extracted.set(i, { bytes, mimeType: mime, source: 'data-uri' });\n continue;\n }\n const sib = await ctx.readSibling(img.uri);\n if (!sib.ok) {\n failures.push({\n imageIndex: i,\n source: 'external-uri',\n reason: `external URI \"${img.uri}\" read failed: ${describeImportError(sib.error)}`,\n });\n continue;\n }\n const mime = classifyMime(img.mimeType, sib.value);\n if (mime === undefined) {\n failures.push({\n imageIndex: i,\n source: 'external-uri',\n reason: `external URI \"${img.uri}\" mime not png/jpeg (declared \"${img.mimeType ?? '<absent>'}\", magic byte sniff failed)`,\n });\n continue;\n }\n extracted.set(i, {\n bytes: new Uint8Array(sib.value),\n mimeType: mime,\n source: 'external-uri',\n });\n continue;\n }\n\n failures.push({\n imageIndex: i,\n source: 'bufferView',\n reason: 'image row has neither bufferView nor uri',\n });\n }\n\n return { extracted, failures };\n}\n","// image-color-space.ts - sRGB / linear classifier for glTF images\n// (feat-20260608 M3 D-3 / requirements AC-08 + AC-13 + C-3).\n//\n// glTF 2.0 spec section 6.2 (\"Material → Texture and Sampler\") names which\n// texture slots are colour-encoded vs data-encoded:\n// - sRGB : baseColorTexture, emissiveTexture, sheenColorTexture,\n// specularColorTexture\n// - linear : metallicRoughnessTexture, normalTexture, occlusionTexture,\n// transmission/volume/clearcoat/anisotropy/sheen-roughness/\n// iridescence/specular-weight data textures\n// We pre-scan the doc so the gltfImporter knows each `images[]` row's\n// colorSpace before decoding (TextureAsset.colorSpace + .format derive\n// from this).\n//\n// Conflict resolution (requirements section 8 edge cases): when the same\n// glTF image is bound to multiple textures whose colour expectations\n// disagree, sRGB wins. baseColor leakage into a normal slot is far worse\n// than the inverse, and bevy_gltf takes the same stance (knowledge-base /\n// research finding §5.6).\n//\n// Orphan images (declared in `images[]` but unreferenced by any\n// `textures[]` entry) default to linear (no colour-encoded purpose\n// inferable; AC-13).\n//\n// Pure function, no I/O. Input = the parts of the parsed GltfDoc that\n// matter (images count, textures, materials); output = a Map keyed by\n// the image array index.\n\nexport type ImageColorSpaceSrgbOrLinear = 'srgb' | 'linear';\n\ntype TextureBinding = number | { readonly texture: number };\n\n/** Slim view of a parsed material the classifier reads (subset of MaterialIr). */\nexport interface MaterialColorSpaceInput {\n readonly baseColorTexture?: TextureBinding;\n readonly metallicRoughnessTexture?: TextureBinding;\n readonly normalTexture?: TextureBinding;\n readonly emissiveTexture?: TextureBinding;\n readonly occlusionTexture?: TextureBinding;\n readonly transmissionTexture?: TextureBinding;\n readonly thicknessTexture?: TextureBinding;\n readonly clearcoatTexture?: TextureBinding;\n readonly clearcoatRoughnessTexture?: TextureBinding;\n readonly clearcoatNormalTexture?: TextureBinding;\n readonly anisotropyTexture?: TextureBinding;\n readonly sheenColorTexture?: TextureBinding;\n readonly sheenRoughnessTexture?: TextureBinding;\n readonly iridescenceTexture?: TextureBinding;\n readonly iridescenceThicknessTexture?: TextureBinding;\n readonly specularTexture?: TextureBinding;\n readonly specularColorTexture?: TextureBinding;\n}\n\n/** Slim view of a parsed `textures[]` row. */\nexport interface TextureColorSpaceInput {\n readonly source: number;\n}\n\n/**\n * Inputs for {@link deriveTextureColorSpace}: just the parts of the parsed\n * doc that the classifier reads. Decoupled from `GltfDoc` so the helper is\n * trivially testable without building a full doc.\n */\nexport interface DeriveTextureColorSpaceInput {\n readonly imageCount: number;\n readonly textures: readonly TextureColorSpaceInput[] | undefined;\n readonly materials: readonly MaterialColorSpaceInput[];\n}\n\n/**\n * Walk the materials, follow each texture-slot binding back to the image\n * it references, and produce `Map<imageIndex, 'srgb' | 'linear'>`. Slots\n * disagreeing on the same image resolve to sRGB (see module header for\n * the rationale). Orphan images default to linear.\n */\nexport function deriveTextureColorSpace(\n input: DeriveTextureColorSpaceInput,\n): Map<number, ImageColorSpaceSrgbOrLinear> {\n const result = new Map<number, ImageColorSpaceSrgbOrLinear>();\n const textures = input.textures ?? [];\n\n function imageOfTexture(binding: TextureBinding | undefined): number | undefined {\n if (binding === undefined) return undefined;\n const textureIndex = typeof binding === 'number' ? binding : binding.texture;\n const tex = textures[textureIndex];\n if (tex === undefined) return undefined;\n return tex.source;\n }\n\n function record(imageIndex: number | undefined, colorSpace: ImageColorSpaceSrgbOrLinear): void {\n if (imageIndex === undefined) return;\n const prior = result.get(imageIndex);\n if (prior === undefined) {\n result.set(imageIndex, colorSpace);\n return;\n }\n if (prior === 'srgb' || colorSpace === 'srgb') {\n result.set(imageIndex, 'srgb');\n }\n }\n\n for (const mat of input.materials) {\n record(imageOfTexture(mat.baseColorTexture), 'srgb');\n record(imageOfTexture(mat.emissiveTexture), 'srgb');\n record(imageOfTexture(mat.sheenColorTexture), 'srgb');\n record(imageOfTexture(mat.specularColorTexture), 'srgb');\n record(imageOfTexture(mat.metallicRoughnessTexture), 'linear');\n record(imageOfTexture(mat.normalTexture), 'linear');\n record(imageOfTexture(mat.occlusionTexture), 'linear');\n record(imageOfTexture(mat.transmissionTexture), 'linear');\n record(imageOfTexture(mat.thicknessTexture), 'linear');\n record(imageOfTexture(mat.clearcoatTexture), 'linear');\n record(imageOfTexture(mat.clearcoatRoughnessTexture), 'linear');\n record(imageOfTexture(mat.clearcoatNormalTexture), 'linear');\n record(imageOfTexture(mat.anisotropyTexture), 'linear');\n record(imageOfTexture(mat.sheenRoughnessTexture), 'linear');\n record(imageOfTexture(mat.iridescenceTexture), 'linear');\n record(imageOfTexture(mat.iridescenceThicknessTexture), 'linear');\n record(imageOfTexture(mat.specularTexture), 'linear');\n }\n\n for (let i = 0; i < input.imageCount; i++) {\n if (!result.has(i)) {\n result.set(i, 'linear');\n }\n }\n\n return result;\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","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","// 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-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)\n// - charter P3 (fail-fast on invalid data)\n\nimport { parseConservativeAnimatedBounds } 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/** 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 /** Producer-authored conservative animated local bounds when supplied. */\n readonly bounds?: Float32Array;\n}\n\ninterface SkinJson {\n readonly name?: string;\n readonly joints: readonly number[];\n readonly inverseBindMatrices?: number;\n /** glTF source metadata authored by the ForgeaX asset producer. */\n readonly extras?: {\n readonly forgeax?: {\n readonly conservativeAnimatedBounds?: unknown;\n };\n };\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 const bounds = parseConservativeAnimatedBounds(\n skin.extras?.forgeax?.conservativeAnimatedBounds,\n );\n records.push({\n jointCount: joints.length,\n inverseBindMatrices: ibm,\n jointPaths,\n ...(bounds === undefined ? {} : { bounds }),\n });\n }\n\n return ok(records);\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 readonly extras?: {\n readonly forgeax?: {\n readonly conservativeAnimatedBounds?: unknown;\n };\n };\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","// gltf-importer.ts - the build-time gltfImporter (feat-20260603-asset-import-loader-injection M2 / w19,\n// extended in feat-20260608 M3 w14 with the texture pipeline: three image\n// source paths funnelled through the ImportContext decodeImage seam).\n//\n// The `{ key: 'gltf', import }` Importer the @forgeax/engine-import runner\n// dispatches a `*.meta.json` with `importer: 'gltf'` to. It reads the source\n// bytes via `ctx.readSource()`, parses them to a `GltfDoc` (parseGltf / parseGlb),\n// and converts each declared sub-asset (mesh / material / scene / texture /\n// skin / animation-clip) into an `ImportedAsset` POD stamped with the\n// meta-declared GUID (GUID import-stable iron law: GUIDs come from\n// `ctx.subAssets[]`, never minted here).\n//\n// Texture pipeline (M3 D-1 / D-3 / D-6, requirements AC-08 / 09 / 10 / 11 /\n// 12 / 13): for every glTF `images[]` row the importer extracts the raw\n// PNG / JPEG bytes from one of three sources (bufferView slice in\n// .glb / data: URI in .gltf / external URI sibling read), funnels them\n// through `ctx.decodeImage` (the only seam to @forgeax/engine-image — a\n// grep gate enforces zero static `from '@forgeax/engine-image'` lines in\n// this package), and emits a `kind: 'texture'` ImportedAsset stamped with\n// the meta-declared GUID. The colorSpace is pre-derived per-image by\n// `deriveTextureColorSpace` (D-3 walk of material slot bindings).\n//\n// Material refs[]: each material's emitted ImportedAsset carries the GUIDs\n// of every texture sub-asset its slots reference, so the runner builds the\n// scene/material -> texture cross-edge needed by AC-11 / AC-19.\n//\n// Sub-asset -> GUID mapping: `ctx.subAssets[]` carries one entry per declared\n// sub-asset with `{ guid, sourceIndex, kind }`. The importer indexes into the\n// parsed doc by (kind, sourceIndex) and emits the corresponding POD under the\n// declared GUID. A sub-asset kind with no doc counterpart (or a sourceIndex out\n// of range) is skipped; the runner's GUID iron-law check then surfaces the\n// gap as `import-produced-no-assets`. A texture sub-asset that fails byte\n// extraction surfaces as `gltf-image-extract-failed` (D-6).\n\nimport { deriveDefaultLodScreenCoverages } from '@forgeax/engine-import';\nimport { packMeshBinV4 } from '@forgeax/engine-import/mesh-bin';\nimport { AssetGuid as AssetGuidCodec } from '@forgeax/engine-pack/guid';\nimport type {\n AssetGuid,\n AssetRef,\n Handle,\n ImportContext,\n ImportedAsset,\n Importer,\n ImportResult,\n MaterialTextureValue,\n MaterialValue,\n MeshAsset,\n MeshMaterialSlotTopologyEntry,\n} from '@forgeax/engine-types';\nimport {\n IMPORT_ERROR_HINTS,\n ImportError,\n readConservativeAnimatedBounds,\n reconcileMeshMaterialSlotTopology,\n resolveMeshMaterialSlotDefaultGuid,\n toShared,\n} from '@forgeax/engine-types';\nimport { deriveGltfAnimatedBounds } from './animated-bounds';\nimport {\n gltfDocToSceneAsset,\n meshIrToMeshAsset,\n toMaterialAsset,\n validateMaterialTangentInputs,\n validateMaterialUvSets,\n} from './bridge.js';\nimport { gltfErr } from './errors.js';\nimport { extractImageBytes } from './extract-image-bytes.js';\nimport { deriveTextureColorSpace } from './image-color-space.js';\nimport type { GltfBufferViewDecodeCapability } from './meshopt-decode.js';\nimport type { GltfDoc, GltfMaterialIr, GltfTextureInfoIr } from './parse-gltf.js';\nimport { parseGlbForImporter, parseGltfForImporter } from './parse-gltf.js';\n\ntype ParseDocResult =\n | { readonly ok: true; readonly value: GltfDoc }\n | { readonly ok: false; readonly error: ImportError };\nfunction isGlbBytes(source: string): boolean {\n return source.toLowerCase().endsWith('.glb');\n}\n\nfunction publishesCatalogProduct(input: {\n readonly importSettings: Readonly<Record<string, unknown>>;\n}): boolean {\n return input.importSettings.geometry !== 'procedural';\n}\n\nfunction applyImportSettingsBounds(\n doc: GltfDoc,\n importSettings: Readonly<Record<string, unknown>>,\n): GltfDoc {\n let changed = false;\n const skeletons = doc.skeletons.map((record, sourceIndex) => {\n // Source extras are the primary producer path. The sidecar row is an\n // explicit external-producer override for sources whose authoring tool\n // cannot carry ForgeaX extras; neither path derives a bind-pose AABB.\n const bounds = readConservativeAnimatedBounds(importSettings, sourceIndex);\n if (bounds === undefined || record.bounds !== undefined) return record;\n changed = true;\n return { ...record, bounds };\n });\n return changed ? { ...doc, skeletons } : doc;\n}\n\nfunction previousMaterialSlotTopology(\n ctx: ImportContext,\n meshSourceKey: string | undefined,\n): readonly MeshMaterialSlotTopologyEntry[] | undefined {\n if (meshSourceKey === undefined) return undefined;\n const value = ctx.sourceOverrides?.[meshSourceKey]?.materialSlots;\n if (value === undefined) return undefined;\n if (!Array.isArray(value)) {\n throw new ImportError({\n code: 'invalid-source-override-payload',\n expected: `${meshSourceKey}.materialSlots to be an array`,\n hint: IMPORT_ERROR_HINTS['invalid-source-override-payload'],\n detail: {\n sourceKey: meshSourceKey,\n declaredSourceKeys: ctx.subAssets.flatMap((entry) => entry.sourceKey ?? []),\n reason: 'materialSlots is not an array',\n },\n });\n }\n const slots: MeshMaterialSlotTopologyEntry[] = [];\n for (const [index, raw] of value.entries()) {\n if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {\n throw new ImportError({\n code: 'invalid-source-override-payload',\n expected: `${meshSourceKey}.materialSlots[${index}] to be an object`,\n hint: IMPORT_ERROR_HINTS['invalid-source-override-payload'],\n detail: {\n sourceKey: meshSourceKey,\n declaredSourceKeys: ctx.subAssets.flatMap((entry) => entry.sourceKey ?? []),\n reason: `materialSlots[${index}] is not an object`,\n },\n });\n }\n const slot = raw as Record<string, unknown>;\n if (typeof slot.slotName !== 'string' || slot.slotName.trim().length === 0) {\n throw new ImportError({\n code: 'invalid-source-override-payload',\n expected: `${meshSourceKey}.materialSlots[${index}].slotName to be non-empty`,\n hint: IMPORT_ERROR_HINTS['invalid-source-override-payload'],\n detail: {\n sourceKey: meshSourceKey,\n declaredSourceKeys: ctx.subAssets.flatMap((entry) => entry.sourceKey ?? []),\n reason: `materialSlots[${index}].slotName is invalid`,\n },\n });\n }\n slots.push({\n slotName: slot.slotName,\n ...(typeof slot.sourceKey === 'string' ? { sourceKey: slot.sourceKey } : {}),\n ...(typeof slot.defaultMaterialGuid === 'string'\n ? { defaultMaterialGuid: slot.defaultMaterialGuid }\n : {}),\n });\n }\n return slots;\n}\n\nfunction stabilizeMeshMaterialSlots(\n mesh: MeshAsset,\n ctx: ImportContext,\n meshGuid: string,\n meshSourceKey: string | undefined,\n): MeshAsset {\n const current = mesh.materialSlots.map(\n (slot): MeshMaterialSlotTopologyEntry => ({\n slotName: slot.slotName,\n ...(slot.sourceKey === undefined ? {} : { sourceKey: slot.sourceKey }),\n ...(slot.defaultMaterial === undefined\n ? {}\n : { defaultMaterialGuid: AssetGuidCodec.format(slot.defaultMaterial) }),\n }),\n );\n const reconciled = reconcileMeshMaterialSlotTopology(\n current,\n previousMaterialSlotTopology(ctx, meshSourceKey),\n );\n if (!reconciled.ok) {\n throw new ImportError({\n code: 'mesh-material-slot-topology-change',\n expected: `unambiguous material slot identity for mesh ${meshGuid}`,\n hint: IMPORT_ERROR_HINTS['mesh-material-slot-topology-change'],\n detail: {\n meshGuid,\n ...(meshSourceKey === undefined ? {} : { meshSourceKey }),\n previousIndices: reconciled.error.previousIndices,\n nextIndices: reconciled.error.nextIndices,\n },\n });\n }\n const authoredDefaults =\n meshSourceKey === undefined\n ? undefined\n : ctx.sourceOverrides?.[meshSourceKey]?.materialSlotDefaultOverrides;\n if (\n authoredDefaults !== undefined &&\n (authoredDefaults === null ||\n typeof authoredDefaults !== 'object' ||\n Array.isArray(authoredDefaults))\n ) {\n throw new ImportError({\n code: 'invalid-source-override-payload',\n expected: `${meshSourceKey}.materialSlotDefaultOverrides to be an object`,\n hint: IMPORT_ERROR_HINTS['invalid-source-override-payload'],\n detail: {\n sourceKey: meshSourceKey,\n declaredSourceKeys: [],\n reason: 'materialSlotDefaultOverrides is invalid',\n },\n });\n }\n const authoredBySlot = authoredDefaults as Readonly<Record<string, unknown>> | undefined;\n const activeStableSlots = new Set(reconciled.currentToStableSlot);\n return {\n ...mesh,\n submeshes: mesh.submeshes.map((submesh) => ({\n ...submesh,\n materialSlot: reconciled.currentToStableSlot[submesh.materialSlot] as number,\n })),\n materialSlots: reconciled.slots.map((slot, stableIndex) => {\n const active = activeStableSlots.has(stableIndex);\n const authored = authoredBySlot?.[slot.sourceKey ?? slot.slotName];\n const effectiveDefault = resolveMeshMaterialSlotDefaultGuid(\n slot,\n active && (typeof authored === 'string' || authored === null) ? authored : undefined,\n );\n const parsed =\n effectiveDefault === undefined ? undefined : AssetGuidCodec.parse(effectiveDefault);\n return {\n slotName: slot.slotName,\n ...(slot.sourceKey === undefined ? {} : { sourceKey: slot.sourceKey }),\n ...(active && parsed?.ok ? { defaultMaterial: parsed.value } : {}),\n };\n }),\n };\n}\n\nasync function parseDoc(\n source: string,\n bytes: Uint8Array,\n ctx: ImportContext,\n meshopt?: GltfBufferViewDecodeCapability,\n): Promise<ParseDocResult> {\n const ab = bytes.buffer.slice(\n bytes.byteOffset,\n bytes.byteOffset + bytes.byteLength,\n ) as ArrayBuffer;\n if (isGlbBytes(source)) {\n const res = await parseGlbForImporter(ab, source, meshopt === undefined ? {} : { meshopt });\n if (!res.ok) {\n if (res.error instanceof ImportError) return { ok: false, error: res.error };\n throw new Error(`parseGlb failed: ${res.error.code} ${res.error.expected}`);\n }\n return { ok: true, value: res.value };\n }\n let json: unknown;\n try {\n json = JSON.parse(new TextDecoder().decode(bytes));\n } catch (e) {\n throw new Error(`gltf JSON parse failed: ${e instanceof Error ? e.message : String(e)}`);\n }\n // External buffers: read sibling files relative to meta.source. data: URIs\n // are decoded inline by parseGltf; only external URIs reach the loader.\n const externalLoader = async (uri: string): Promise<ArrayBuffer> => {\n const sib = await ctx.readSibling(uri);\n if (!sib.ok) {\n throw new Error(`gltfImporter: external buffer \"${uri}\" read failed: ${sib.error.code}`);\n }\n return sib.value.buffer.slice(\n sib.value.byteOffset,\n sib.value.byteOffset + sib.value.byteLength,\n ) as ArrayBuffer;\n };\n const res = await parseGltfForImporter(\n json,\n externalLoader,\n source,\n meshopt === undefined ? {} : { meshopt },\n );\n if (!res.ok) {\n if (res.error instanceof ImportError) return { ok: false, error: res.error };\n throw new Error(`parseGltf failed: ${res.error.code} ${res.error.expected}`);\n }\n return { ok: true, value: res.value };\n}\n\ninterface HandleMaps {\n readonly meshHandles: Map<number, Handle<'MeshAsset', 'shared'>>;\n readonly materialHandles: Map<number, Handle<'MaterialAsset', 'shared'>>;\n readonly textureHandles: Map<number, Handle<'TextureAsset', 'shared'>>;\n readonly samplerHandles: Map<number, Handle<'SamplerAsset', 'shared'>>;\n readonly meshGuidByIndex: Map<number, string>;\n readonly materialGuidByIndex: Map<number, string>;\n readonly textureGuidByIndex: Map<number, string>;\n readonly samplerGuidByIndex: Map<number, string>;\n}\n\n/**\n * Build the gltf-index -> declared-GUID maps so scene refs resolve to the\n * sub-asset GUIDs (not runtime handles, which do not exist at import time).\n * The scene POD therefore carries deterministic synthetic handle slots; the\n * GUID cross-references are recorded on the ImportedAsset `refs[]`.\n *\n * Texture handles are seeded from `subAssets[]` of kind 'texture'; their\n * sourceIndex is the glTF `images[]` row (toAssetPack emits one texture\n * sub-asset per image row, so the mapping is image-index keyed even though\n * the field is named textureHandles for material binding readability).\n * GltfMaterialIr's `*Texture` fields hold glTF `textures[]` indices; the\n * importer dereferences `textures[i].source` to convert that into an image\n * index when stamping material handles.\n */\nfunction buildHandleMaps(\n subAssets: readonly { guid: string; sourceIndex: number; kind: string }[],\n doc: GltfDoc,\n): HandleMaps {\n const meshHandles = new Map<number, Handle<'MeshAsset', 'shared'>>();\n const materialHandles = new Map<number, Handle<'MaterialAsset', 'shared'>>();\n const textureHandles = new Map<number, Handle<'TextureAsset', 'shared'>>();\n const samplerHandles = new Map<number, Handle<'SamplerAsset', 'shared'>>();\n const meshGuidByIndex = new Map<number, string>();\n const materialGuidByIndex = new Map<number, string>();\n const textureGuidByIndex = new Map<number, string>();\n const samplerGuidByIndex = new Map<number, string>();\n // bug-20260610 layer 7c-2: scene's `refs[]` is concatenated in the order\n // [mesh sub-assets..., material sub-assets..., texture sub-assets...] (see\n // gltf-importer scene branch). The synthetic handle values stamped here\n // travel through `MeshFilter.assetHandle` / `MeshRenderer.materials[*]` and\n // are decoded at runtime as **refs[] indices** by parseScenePayload. So the\n // handle value MUST equal the slot offset in the eventual concat, NOT the\n // gltf source-index. The previous keying-by-sourceIndex worked accidentally\n // when there was exactly one mesh + N <= meshCount materials; it broke as\n // soon as materialIndex landed past the mesh-section boundary (Sponza:\n // materials[0]=0 -> refs[0] = mesh GUID, every submesh sampled the mesh\n // asset as its material -> single fallback unlit dispatch entry, no per-\n // primitive draws).\n let meshCursor = 0;\n let materialCursor = 0;\n for (const sub of subAssets) {\n if (sub.kind === 'mesh') {\n meshHandles.set(sub.sourceIndex, toShared<'MeshAsset'>(meshCursor));\n meshGuidByIndex.set(sub.sourceIndex, sub.guid);\n meshCursor += 1;\n } else if (sub.kind === 'material') {\n // material handles come AFTER all mesh refs in the concat.\n // The actual offset (= meshCount + materialCursor) is back-patched\n // below once we know meshCount.\n materialHandles.set(sub.sourceIndex, toShared<'MaterialAsset'>(materialCursor));\n materialGuidByIndex.set(sub.sourceIndex, sub.guid);\n materialCursor += 1;\n } else if (sub.kind === 'texture') {\n textureGuidByIndex.set(sub.sourceIndex, sub.guid);\n } else if (sub.kind === 'sampler') {\n samplerGuidByIndex.set(sub.sourceIndex, sub.guid);\n }\n }\n const meshCount = meshCursor;\n if (meshCount > 0) {\n for (const [k, v] of materialHandles) {\n const local = v as unknown as number;\n materialHandles.set(k, toShared<'MaterialAsset'>(local + meshCount));\n }\n }\n // For material binding (toMaterialAsset / values.<X>Texture) the handle\n // value is the texture's slot offset within the SAME asset's `refs[]` (which\n // is `materialTextureRefs` order, not the scene-level refs concat).\n // toMaterialAsset only consumes textureHandles to copy a number into the\n // values; the gltf-importer's later 7a fix-up rewrites those values\n // into refs[] indices for the runtime materialLoader. Keying by texIndex\n // and storing `tex.source` here matches the existing 7a path.\n const textures = doc.textures ?? [];\n for (let texIndex = 0; texIndex < textures.length; texIndex++) {\n const tex = textures[texIndex];\n if (tex === undefined) continue;\n if (textureGuidByIndex.has(tex.source)) {\n textureHandles.set(texIndex, toShared<'TextureAsset'>(tex.source));\n }\n }\n for (const [samplerIndex] of samplerGuidByIndex) {\n samplerHandles.set(samplerIndex, toShared<'SamplerAsset'>(samplerIndex));\n }\n return {\n meshHandles,\n materialHandles,\n textureHandles,\n samplerHandles,\n meshGuidByIndex,\n materialGuidByIndex,\n textureGuidByIndex,\n samplerGuidByIndex,\n };\n}\n\nfunction textureInfo(info: GltfTextureInfoIr | number | undefined): GltfTextureInfoIr | undefined {\n return info === undefined ? undefined : typeof info === 'number' ? { texture: info } : info;\n}\n\n/** Collect texture and sampler GUID refs for one material (AC-11 cross-edge). */\nexport function materialRefsForPack(\n mat: GltfMaterialIr,\n doc: GltfDoc,\n textureGuidByIndex: ReadonlyMap<number, string>,\n samplerGuidByIndex: ReadonlyMap<number, string> = new Map(),\n): readonly AssetRef[] {\n const refs: AssetRef[] = [];\n const textures = doc.textures ?? [];\n function pushRefsForSlot(info: GltfTextureInfoIr | number | undefined, fieldName: string): void {\n const binding = textureInfo(info);\n if (binding === undefined) return;\n const tex = textures[binding.texture];\n if (tex === undefined) return;\n const guid = textureGuidByIndex.get(tex.source);\n if (guid !== undefined) {\n refs.push({\n guid,\n sourceField: { componentName: '<material>', fieldName },\n });\n }\n if (binding.sampler !== undefined) {\n const samplerGuid = samplerGuidByIndex.get(binding.sampler);\n if (samplerGuid !== undefined) {\n refs.push({\n guid: samplerGuid,\n sourceField: { componentName: '<material>', fieldName: `${fieldName}.sampler` },\n });\n }\n }\n }\n pushRefsForSlot(mat.baseColorTexture, 'baseColorTexture');\n pushRefsForSlot(mat.metallicRoughnessTexture, 'metallicRoughnessTexture');\n pushRefsForSlot(mat.normalTexture, 'normalTexture');\n pushRefsForSlot(mat.occlusionTexture, 'occlusionTexture');\n pushRefsForSlot(mat.emissiveTexture, 'emissiveTexture');\n pushRefsForSlot(mat.transmissionTexture, 'transmissionTexture');\n pushRefsForSlot(mat.thicknessTexture, 'thicknessTexture');\n pushRefsForSlot(mat.clearcoatTexture, 'clearcoatTexture');\n pushRefsForSlot(mat.clearcoatRoughnessTexture, 'clearcoatRoughnessTexture');\n pushRefsForSlot(mat.clearcoatNormalTexture, 'clearcoatNormalTexture');\n pushRefsForSlot(mat.anisotropyTexture, 'anisotropyTexture');\n pushRefsForSlot(mat.sheenColorTexture, 'sheenColorTexture');\n pushRefsForSlot(mat.sheenRoughnessTexture, 'sheenRoughnessTexture');\n pushRefsForSlot(mat.iridescenceTexture, 'iridescenceTexture');\n pushRefsForSlot(mat.iridescenceThicknessTexture, 'iridescenceThicknessTexture');\n pushRefsForSlot(mat.specularTexture, 'specularTexture');\n pushRefsForSlot(mat.specularColorTexture, 'specularColorTexture');\n return refs;\n}\n\nfunction availableUvSets(mesh: GltfDoc['meshes'][number]): readonly number[] {\n const sets: number[] = [];\n for (let set = 0; set <= 7; set++) {\n const field = `texcoord${set}` as keyof typeof mesh;\n if (mesh[field] !== undefined) sets.push(set);\n }\n return sets;\n}\n\nfunction rewriteMaterialAssetRefs(\n matAsset: ReturnType<typeof toMaterialAsset>,\n mat: GltfMaterialIr,\n doc: GltfDoc,\n maps: HandleMaps,\n): ReturnType<typeof toMaterialAsset> {\n const values = { ...(matAsset.values ?? {}) } as Record<string, MaterialValue | null>;\n const textures = doc.textures ?? [];\n const slots: readonly [\n (\n | 'baseColorTexture'\n | 'metallicRoughnessTexture'\n | 'normalTexture'\n | 'occlusionTexture'\n | 'emissiveTexture'\n | 'transmissionTexture'\n | 'thicknessTexture'\n | 'clearcoatTexture'\n | 'clearcoatRoughnessTexture'\n | 'clearcoatNormalTexture'\n | 'anisotropyTexture'\n | 'sheenColorTexture'\n | 'sheenRoughnessTexture'\n | 'iridescenceTexture'\n | 'iridescenceThicknessTexture'\n | 'specularTexture'\n | 'specularColorTexture'\n ),\n GltfTextureInfoIr | number | undefined,\n ][] = [\n ['baseColorTexture', mat.baseColorTexture],\n ['metallicRoughnessTexture', mat.metallicRoughnessTexture],\n ['normalTexture', mat.normalTexture],\n ['occlusionTexture', mat.occlusionTexture],\n ['emissiveTexture', mat.emissiveTexture],\n ['transmissionTexture', mat.transmissionTexture],\n ['thicknessTexture', mat.thicknessTexture],\n ['clearcoatTexture', mat.clearcoatTexture],\n ['clearcoatRoughnessTexture', mat.clearcoatRoughnessTexture],\n ['clearcoatNormalTexture', mat.clearcoatNormalTexture],\n ['anisotropyTexture', mat.anisotropyTexture],\n ['sheenColorTexture', mat.sheenColorTexture],\n ['sheenRoughnessTexture', mat.sheenRoughnessTexture],\n ['iridescenceTexture', mat.iridescenceTexture],\n ['iridescenceThicknessTexture', mat.iridescenceThicknessTexture],\n ['specularTexture', mat.specularTexture],\n ['specularColorTexture', mat.specularColorTexture],\n ];\n let cursor = 0;\n for (const [slot, rawBinding] of slots) {\n const binding = textureInfo(rawBinding);\n if (binding === undefined) continue;\n const texture = textures[binding.texture];\n const textureGuid =\n texture === undefined ? undefined : maps.textureGuidByIndex.get(texture.source);\n const value = values[slot];\n if (textureGuid === undefined || typeof value !== 'object' || value === null) {\n delete values[slot];\n continue;\n }\n const textureValue = value as MaterialTextureValue;\n const textureRef = cursor as unknown as MaterialTextureValue['texture'];\n cursor++;\n const rewritten =\n binding.sampler !== undefined && maps.samplerGuidByIndex.has(binding.sampler)\n ? {\n ...textureValue,\n texture: textureRef,\n sampler: cursor as unknown as NonNullable<MaterialTextureValue['sampler']>,\n }\n : { ...textureValue, texture: textureRef };\n if (binding.sampler !== undefined && maps.samplerGuidByIndex.has(binding.sampler)) cursor++;\n values[slot] = rewritten;\n }\n return { ...matAsset, values };\n}\n\nasync function importGltf(\n ctx: ImportContext,\n meshopt?: GltfBufferViewDecodeCapability,\n): Promise<ImportResult> {\n const read = await ctx.readSource();\n if (!read.ok) {\n throw new Error(\n `gltfImporter: readSource failed: ${read.error instanceof Error ? read.error.message : String(read.error)}`,\n );\n }\n const parsed = await parseDoc(ctx.source, read.value, ctx, meshopt);\n if (!parsed.ok) return parsed;\n const doc = deriveGltfAnimatedBounds(applyImportSettingsBounds(parsed.value, ctx.importSettings));\n const maps = buildHandleMaps(ctx.subAssets, doc);\n\n // Pre-derive each images[] row's colorSpace from material slot bindings\n // (D-3 / AC-08). orphan images default to 'linear' (AC-13).\n const imageColorSpaces = deriveTextureColorSpace({\n imageCount: (doc.images ?? []).length,\n textures: doc.textures,\n materials: doc.materials,\n });\n\n // Extract image bytes (3 source paths) once. Failures here are surfaced\n // per-image so a single bad row does not abort the whole importer.\n const declaredImageIndices = new Set<number>();\n for (const sub of ctx.subAssets) {\n if (sub.kind === 'texture') declaredImageIndices.add(sub.sourceIndex);\n }\n const extraction =\n declaredImageIndices.size > 0\n ? await extractImageBytes(read.value, ctx.source, ctx)\n : {\n extracted: new Map(),\n failures: [] as readonly {\n imageIndex: number;\n source: 'bufferView' | 'data-uri' | 'external-uri';\n reason: string;\n }[],\n };\n\n // M4 (tweak-20260611-skin-fox-3clip-and-kb-sample-assets): SkinAsset.refs[]\n // carries the skeleton GUID (each skin binds 1:1 to a SkeletonAsset; the\n // skeletonGuid field is the on-asset cross-reference; refs[] is the runner-\n // visible cross-edge used for pack-index ordering and integrity checks).\n // Build the index now so the skin emit branch below can stamp it.\n const skeletonGuidBySourceIndex = new Map<number, string>();\n for (const sub of ctx.subAssets) {\n if (sub.kind === 'skeleton') skeletonGuidBySourceIndex.set(sub.sourceIndex, sub.guid);\n }\n // feat-20260612 M2 fixup: parallel skin GUID index. Skins and skeletons\n // share `sourceIndex` (toAssetPack emits 1:1 per GltfSkeletonRecord) but live\n // as distinct `kind` sub-assets, so the SkinAsset GUIDs differ from the\n // SkeletonAsset GUIDs. The scene branch below appends these GUIDs to both\n // its refs[] (the runtime recursion source: loadByGuid<SceneAsset> walks\n // envelope.refs to recursively pull every SkinAsset before instantiate) and\n // its payload.skinGuids (the reverse-decode hint) -- without the refs[] edge,\n // browser-async-pack-fetch never loads SkinAssets and Skin.joints stays\n // length=0).\n const skinGuidBySourceIndex = new Map<number, string>();\n for (const sub of ctx.subAssets) {\n if (sub.kind === 'skin') skinGuidBySourceIndex.set(sub.sourceIndex, sub.guid);\n }\n\n const out: ImportedAsset[] = [];\n const isMultiAsset = ctx.subAssets.length > 1;\n for (const sub of ctx.subAssets) {\n if (sub.kind === 'mesh') {\n // sub.sourceIndex now indexes glTF mesh-index (not flat GltfMeshIr index).\n // parseGltf flattens N glTF meshes with M_i primitives into sum(M_i)\n // GltfMeshIr rows, all sharing meshIndex; gather all rows whose\n // meshIndex === sub.sourceIndex (preserving doc.meshes order so the\n // bridge's positional materials[i] <-> submeshes[i] pairing aligns)\n // and let meshIrToMeshAsset interleave them into one MeshAsset with\n // N Submesh entries.\n const prims = doc.meshes.filter((m) => m.meshIndex === sub.sourceIndex);\n if (prims.length === 0) continue;\n const meshName = isMultiAsset ? prims[0]?.name : undefined;\n const materialNameByIndex = new Map<number, string>();\n const materialSourceKeyByIndex = new Map<number, string>();\n for (let materialIndex = 0; materialIndex < doc.materials.length; materialIndex++) {\n const name = doc.materials[materialIndex]?.name;\n if (typeof name === 'string') materialNameByIndex.set(materialIndex, name);\n }\n for (const material of ctx.subAssets) {\n if (material.kind === 'material' && material.sourceKey !== undefined) {\n materialSourceKeyByIndex.set(material.sourceIndex, material.sourceKey);\n }\n }\n const bridged = meshIrToMeshAsset(prims, {\n guidByIndex: maps.materialGuidByIndex,\n nameByIndex: materialNameByIndex,\n sourceKeyByIndex: materialSourceKeyByIndex,\n });\n if (!bridged.ok) {\n return {\n ok: false,\n error: new ImportError({\n code: 'import-internal-error',\n expected: 'gltf mesh bridge to produce a canonical MeshAsset',\n actual: bridged.error.code,\n hint: 'repair the source primitive and re-run the glTF importer',\n detail: {\n reason: `gltf mesh bridge rejected mesh ${sub.sourceIndex}; inspect the bridge error detail`,\n },\n }),\n };\n }\n const stabilizedMesh = stabilizeMeshMaterialSlots(\n bridged.value,\n ctx,\n sub.guid,\n sub.sourceKey,\n );\n const lodGroup =\n doc.lod?.groups?.find(\n (group) => doc.nodes[group.rootNode]?.meshIndex === sub.sourceIndex,\n ) ??\n (doc.lod?.rootNode !== undefined &&\n doc.nodes[doc.lod.rootNode]?.meshIndex === sub.sourceIndex\n ? doc.lod\n : undefined);\n const rootMeshIndex = lodGroup === undefined ? undefined : sub.sourceIndex;\n if (lodGroup !== undefined) {\n const referencedMeshIndices = [\n sub.sourceIndex,\n ...lodGroup.lodNodeIds.map((nodeIndex) => doc.nodes[nodeIndex]?.meshIndex),\n ];\n const missingMeshIndex = referencedMeshIndices.find(\n (meshIndex) =>\n !Number.isInteger(meshIndex) ||\n meshIndex === null ||\n meshIndex === undefined ||\n maps.meshGuidByIndex.get(meshIndex as number) === undefined,\n );\n if (missingMeshIndex !== undefined) {\n return {\n ok: false,\n error: new ImportError({\n code: 'import-internal-error',\n expected: 'every MSFT_lod node to resolve a cooked mesh sub-asset',\n actual: String(missingMeshIndex),\n hint: 'repair the referenced glTF mesh primitives and re-run the importer',\n detail: {\n reason: `MSFT_lod group for mesh ${sub.sourceIndex} references an unprojected mesh`,\n },\n }),\n };\n }\n }\n const authoredLods =\n sub.sourceKey === undefined ? undefined : ctx.sourceOverrides?.[sub.sourceKey]?.lods;\n const lodEntries = Array.isArray(authoredLods) ? authoredLods : [];\n const lodLevels =\n rootMeshIndex === sub.sourceIndex && lodGroup !== undefined\n ? lodGroup.lodNodeIds.flatMap((nodeIndex, index) => {\n const meshIndex = doc.nodes[nodeIndex]?.meshIndex;\n const guid =\n meshIndex === undefined || meshIndex === null\n ? undefined\n : maps.meshGuidByIndex.get(meshIndex);\n if (guid === undefined) return [];\n const authored = lodEntries[index];\n const authoredCoverage =\n authored !== null && typeof authored === 'object'\n ? (authored as { readonly screenCoverage?: unknown }).screenCoverage\n : undefined;\n const coverage =\n typeof authoredCoverage === 'number'\n ? authoredCoverage\n : (lodGroup.screenCoverages[index] ??\n deriveDefaultLodScreenCoverages(lodGroup.lodNodeIds.length + 1)[index]);\n const parsed = AssetGuidCodec.parse(guid);\n return parsed.ok && coverage !== undefined\n ? [{ mesh: parsed.value, screenCoverage: coverage, guid }]\n : [];\n })\n : [];\n const meshPayload: MeshAsset =\n lodLevels.length === 0\n ? stabilizedMesh\n : {\n ...stabilizedMesh,\n lods: lodLevels.map(({ mesh, screenCoverage }) => ({ mesh, screenCoverage })),\n };\n const materialRefs: AssetRef[] = [];\n const seenMaterialGuids = new Set<string>();\n for (let slotIndex = 0; slotIndex < meshPayload.materialSlots.length; slotIndex++) {\n const defaultMaterial = meshPayload.materialSlots[slotIndex]?.defaultMaterial;\n const guid =\n defaultMaterial === undefined ? undefined : AssetGuidCodec.format(defaultMaterial);\n if (guid !== undefined && !seenMaterialGuids.has(guid.toLowerCase())) {\n seenMaterialGuids.add(guid.toLowerCase());\n materialRefs.push({\n guid,\n sourceField: { fieldName: 'materialSlots', arrayIndex: slotIndex },\n });\n }\n }\n for (const [lodIndex, level] of lodLevels.entries()) {\n if (!seenMaterialGuids.has(level.guid.toLowerCase())) {\n seenMaterialGuids.add(level.guid.toLowerCase());\n materialRefs.push({\n guid: level.guid,\n sourceField: { fieldName: 'lods', arrayIndex: lodIndex },\n });\n }\n }\n out.push({\n guid: sub.guid,\n kind: 'mesh',\n ...(meshName !== undefined ? { name: meshName } : {}),\n payload: meshPayload,\n refs: materialRefs,\n artifacts: {\n body: {\n mediaType: 'application/x-forgeax-mesh',\n assetCodec: { name: 'mesh-binary', version: '4' },\n bytes: (() => {\n const packed = packMeshBinV4(\n meshPayload as never,\n sub.sourceKey ?? ctx.source,\n materialRefs.map((ref) => ref.guid),\n );\n if (!packed.ok) {\n throw new ImportError({\n code: 'import-internal-error',\n expected: 'mesh-bin v4 producer to accept the canonical mesh projection',\n hint: 're-cook the source with its Meta sidecar after fixing the mesh payload',\n detail: { reason: `${packed.error.code}: ${packed.error.actual}` },\n });\n }\n return packed.value;\n })(),\n },\n },\n });\n } else if (sub.kind === 'material') {\n const mat = doc.materials[sub.sourceIndex];\n if (mat === undefined) continue;\n // feat-20260611 w17-a: scan doc.meshes[] for any primitive that (a)\n // references this material and (b) carries JOINTS_0 + WEIGHTS_0. If\n // found, route the emitted MaterialAsset to `forgeax::pbr-skin`.\n // Mirrors the per-MeshAsset 18F-stride decision in meshIrToMeshAsset\n // (D-2): a material consumed by any skinned primitive must use the\n // skin shader so the runtime PSO chain (LayoutKind='pbr-skin' +\n // 6-attribute deriveVertexBufferLayout) is exercised.\n let skinned = false;\n for (const meshIr of doc.meshes) {\n if (meshIr.materialIndex !== sub.sourceIndex) continue;\n if (meshIr.joints0 !== undefined && meshIr.weights0 !== undefined) {\n skinned = true;\n break;\n }\n }\n for (let primitiveIndex = 0; primitiveIndex < doc.meshes.length; primitiveIndex++) {\n const meshIr = doc.meshes[primitiveIndex];\n if (meshIr?.materialIndex !== sub.sourceIndex) continue;\n const uvResult = validateMaterialUvSets(\n mat,\n `primitive-${primitiveIndex}`,\n availableUvSets(meshIr),\n );\n if (!uvResult.ok) {\n throw Object.assign(new Error(uvResult.error.message), uvResult.error);\n }\n const tangentResult = validateMaterialTangentInputs(mat, meshIr);\n if (!tangentResult.ok) {\n throw Object.assign(new Error(tangentResult.error.message), tangentResult.error);\n }\n }\n const matAsset = toMaterialAsset(mat, {\n textureHandles: maps.textureHandles,\n samplerHandles: maps.samplerHandles,\n skinned,\n ...(typeof ctx.importSettings.standardMaterialGuid === 'string'\n ? { standardRootGuid: ctx.importSettings.standardMaterialGuid as unknown as AssetGuid }\n : {}),\n });\n const refs = materialRefsForPack(mat, doc, maps.textureGuidByIndex, maps.samplerGuidByIndex);\n // D-8: if material has a parent, add parent edge to refs\n const materialRefs: AssetRef[] = [...refs];\n if (matAsset.parent !== undefined) {\n materialRefs.push({\n guid: matAsset.parent as unknown as string,\n sourceField: { fieldName: 'parent' },\n });\n }\n const rewrittenAsset = rewriteMaterialAssetRefs(matAsset, mat, doc, maps);\n const matName = isMultiAsset ? mat.name : undefined;\n out.push({\n guid: sub.guid,\n kind: 'material',\n ...(matName !== undefined ? { name: matName } : {}),\n payload: rewrittenAsset,\n refs: materialRefs,\n artifacts: {},\n });\n } else if (sub.kind === 'texture') {\n const imageIndex = sub.sourceIndex;\n const extracted = extraction.extracted.get(imageIndex);\n if (extracted === undefined) {\n const failure = extraction.failures.find((f) => f.imageIndex === imageIndex);\n const detail = failure ?? {\n imageIndex,\n source: 'bufferView' as const,\n reason: 'image row missing from extraction map (no images[] entry?)',\n };\n const error = gltfErr('gltf-image-extract-failed', detail);\n throw new Error(\n `gltfImporter: ${error.code} on image ${imageIndex} (${detail.source}): ${detail.reason}`,\n );\n }\n const colorSpace = imageColorSpaces.get(imageIndex) ?? 'linear';\n // Carry colorSpace + mipmap settings into decodeImage via a per-image\n // settings record (mirror of importImageSettings — but here the importer\n // owns the decision because the seam is in-bounds for AC-12 (c)).\n const decodeSettings = {\n ...ctx.importSettings,\n colorSpace,\n mipmap: ctx.importSettings.mipmap ?? true,\n };\n const decoded = await ctx.decodeImage(extracted.bytes, extracted.mimeType, decodeSettings);\n if (!decoded.ok) {\n const reason = `decodeImage failed: ${decoded.error.code}`;\n const error = gltfErr('gltf-image-extract-failed', {\n imageIndex,\n source: extracted.source,\n reason,\n });\n throw new Error(\n `gltfImporter: ${error.code} on image ${imageIndex} (${extracted.source}): ${reason}`,\n );\n }\n const imageItem = (doc.images ?? [])[imageIndex];\n const texName = isMultiAsset ? imageItem?.name : undefined;\n out.push({\n guid: sub.guid,\n kind: 'texture',\n ...(texName !== undefined ? { name: texName } : {}),\n payload: decoded.value.texture,\n refs: [],\n artifacts: {\n body: {\n mediaType: decoded.value.mediaType ?? extracted.mimeType,\n assetCodec: decoded.value.assetCodec ?? { name: 'rgba8', version: '1' },\n bytes: decoded.value.bytes,\n },\n },\n });\n } else if (sub.kind === 'sampler') {\n const sampler = doc.samplers?.[sub.sourceIndex];\n if (sampler === undefined) continue;\n const filter = (value: number | undefined): 'nearest' | 'linear' | undefined => {\n if (value === undefined) return undefined;\n return value === 9728 || value === 9984 || value === 9986 || value === 9988\n ? 'nearest'\n : 'linear';\n };\n const mipmapFilter = (value: number | undefined): 'nearest' | 'linear' | undefined => {\n if (value === undefined) return undefined;\n return value === 9984 || value === 9985 ? 'nearest' : 'linear';\n };\n const addressMode = (value: number): 'repeat' | 'mirror-repeat' | 'clamp-to-edge' => {\n if (value === 33071) return 'clamp-to-edge';\n if (value === 33648) return 'mirror-repeat';\n return 'repeat';\n };\n const magFilter = filter(sampler.magFilter);\n const minFilter = filter(sampler.minFilter);\n const mipmap = mipmapFilter(sampler.minFilter);\n const payload = {\n kind: 'sampler' as const,\n ...(magFilter === undefined ? {} : { magFilter }),\n ...(minFilter === undefined ? {} : { minFilter }),\n ...(mipmap === undefined ? {} : { mipmapFilter: mipmap }),\n addressModeU: addressMode(sampler.wrapS),\n addressModeV: addressMode(sampler.wrapT),\n };\n out.push({ guid: sub.guid, kind: 'sampler', payload, refs: [], artifacts: {} });\n } else if (sub.kind === 'scene') {\n // #317 multi-material design: bridge accepts glTF mesh-index keyed\n // meshHandles + materialHandles only; primitive merge happens via\n // doc.meshes[] filtering on meshIndex inside the bridge.\n // tweak-20260611 M6: also pass skeletonGuidBySkinIndex so the bridge\n // can stamp Skin component (skeleton GUID string) onto skinned mesh\n // entities. Skins are 1:1 with skeletons in toAssetPack so the same\n // sourceIndex map serves both purposes (the field name says\n // \"BySkinIndex\" because the bridge keys by GltfNodeIr.skinIndex).\n const scene = gltfDocToSceneAsset(doc, {\n meshHandles: maps.meshHandles,\n materialHandles: maps.materialHandles,\n skeletonGuidBySkinIndex: skeletonGuidBySourceIndex,\n });\n // Scene refs contain only dependencies authored directly by the scene:\n // mesh, skeleton, and skin assets. Imported material defaults belong to\n // MeshAsset.materialSlots, and textures belong to MaterialAsset refs;\n // repeating either here would create a second dependency owner.\n // Skeleton GUIDs are appended so the runtime asset graph sees the\n // cross-edge when a skinned mesh node carries Skin { skeleton:\n // <guid-string> }; skin GUIDs (feat-20260612 M2 fixup) carry the\n // SkinAsset cross-edge that has no entity-component representation but\n // is required for postSpawnResolveJoints to resolve Skin.joints[] via\n // SkinAsset.jointPaths.\n //\n // D-2 / D-3: refs carries structured edge metadata (AssetRef[]).\n // Walk keyed scene entities to build a handle-value -> (entityKey,\n // componentName, fieldName, arrayIndex?) provenance map, then\n // produce AssetRef[] with sourceField / sceneEntityKey filled for mesh\n // handle-field edges. Skeleton edges: sourceField from Skin.skeleton if entity\n // carries that GUID. Skin edges: sourceField=undefined (cross-edge\n // with no entity-component representation).\n const handleValueProvenance = new Map<\n number,\n { sceneEntityKey: string; componentName: string; fieldName: string; arrayIndex?: number }\n >();\n const skeletonGuidProvenance = new Map<string, { sceneEntityKey: string }>();\n for (const [sceneEntityKey, entity] of Object.entries(scene.entities)) {\n const comps = entity.components as Record<string, Record<string, unknown>>;\n const mf = comps.MeshFilter;\n if (mf !== undefined && typeof mf.assetHandle === 'number') {\n handleValueProvenance.set(mf.assetHandle, {\n sceneEntityKey,\n componentName: 'MeshFilter',\n fieldName: 'assetHandle',\n });\n }\n const skin = comps.Skin;\n if (skin !== undefined && typeof skin.skeleton === 'string') {\n skeletonGuidProvenance.set(skin.skeleton, { sceneEntityKey });\n }\n }\n\n const meshGuidList = [...maps.meshGuidByIndex.values()];\n\n function makeRef(guid: string, idx: number): AssetRef {\n const prov = handleValueProvenance.get(idx);\n if (prov !== undefined) {\n return {\n guid,\n sourceField: {\n componentName: prov.componentName,\n fieldName: prov.fieldName,\n ...(prov.arrayIndex !== undefined ? { arrayIndex: prov.arrayIndex } : {}),\n },\n sceneEntityKey: prov.sceneEntityKey,\n };\n }\n return { guid };\n }\n\n const refs: AssetRef[] = [];\n let cursor = 0;\n for (const guid of meshGuidList) {\n refs.push(makeRef(guid, cursor));\n cursor++;\n }\n {\n const skeletonGuidList = [...skeletonGuidBySourceIndex.values()];\n for (const guid of skeletonGuidList) {\n const skProv = skeletonGuidProvenance.get(guid);\n refs.push(\n skProv !== undefined\n ? {\n guid,\n sourceField: { componentName: 'Skin', fieldName: 'skeleton' },\n sceneEntityKey: skProv.sceneEntityKey,\n }\n : { guid },\n );\n cursor++;\n }\n }\n {\n const skinGuidList = [...skinGuidBySourceIndex.values()];\n for (const guid of skinGuidList) {\n refs.push({ guid });\n cursor++;\n }\n }\n // Inject skinGuids into the scene payload as the reverse-decode hint; the\n // SkinAsset GUIDs are already in the scene envelope's refs[] above, which\n // is the runtime recursion source for the browser-async-pack-fetch path.\n // Stored as inline GUID strings (in-memory dawn smoke path); the on-disk\n // .pack.json round-trip preserves them as strings -- parseScenePayload's\n // resolveSkinGuids accepts both string and refs[]-index shapes.\n const skinGuidList = [...skinGuidBySourceIndex.values()];\n const sceneWithSkinGuids =\n skinGuidList.length > 0 ? { ...scene, skinGuids: skinGuidList } : scene;\n const sceneName = isMultiAsset ? doc.scenes[sub.sourceIndex]?.name : undefined;\n out.push({\n guid: sub.guid,\n kind: 'scene',\n ...(sceneName !== undefined ? { name: sceneName } : {}),\n payload: sceneWithSkinGuids,\n refs,\n artifacts: {},\n });\n } else if (sub.kind === 'skeleton') {\n // tweak-20260611 M4: skeleton sub-asset POD emit. GltfSkeletonRecord (the\n // gltf IR shape from parse-skin) carries inverseBindMatrices + jointCount\n // + jointPaths; SkeletonAsset (the runtime POD) carries IBM + jointCount\n // only — jointPaths live on the parallel SkinAsset (1:1 mapping per\n // toAssetPack's emit policy). refs[] is empty (skeleton is leaf data).\n const rec = doc.skeletons[sub.sourceIndex];\n if (rec === undefined) continue;\n const payload = {\n kind: 'skeleton' as const,\n inverseBindMatrices: rec.inverseBindMatrices,\n jointCount: rec.jointCount,\n ...(rec.bounds === undefined ? {} : { bounds: rec.bounds }),\n };\n out.push({ guid: sub.guid, kind: 'skeleton', payload, refs: [], artifacts: {} });\n } else if (sub.kind === 'skin') {\n // tweak-20260611 M4: skin sub-asset POD emit. The 1:1 mapping with\n // skeleton (toAssetPack emits one skin per GltfSkeletonRecord at the same\n // sourceIndex) lets us pull the skeleton GUID out of the pre-built\n // skeletonGuidBySourceIndex map. SkinAsset is the runtime POD, distinct\n // from GltfSkeletonRecord: skeletonGuid + jointPaths only (zero entity refs\n // at the asset layer per AC-06). refs[] carries the skeletonGuid so the\n // runner sees the cross-edge.\n const rec = doc.skeletons[sub.sourceIndex];\n if (rec === undefined) continue;\n const skeletonGuid = skeletonGuidBySourceIndex.get(sub.sourceIndex);\n if (skeletonGuid === undefined) continue;\n const payload = {\n kind: 'skin' as const,\n skeletonGuid,\n jointPaths: rec.jointPaths,\n };\n out.push({\n guid: sub.guid,\n kind: 'skin',\n payload,\n refs: [{ guid: skeletonGuid, sourceField: { fieldName: 'skeleton' } }],\n artifacts: {},\n });\n } else if (sub.kind === 'animation-clip') {\n // tweak-20260611 M4: animation-clip sub-asset POD emit. GltfAnimationClipRecord\n // (gltf IR) and AnimationClip (runtime POD) are structurally compatible\n // — both carry duration + channels[]; channels' inner shape matches\n // (targetId / property / sampler). property is narrowed to the runtime\n // closed union by the parser. refs[] is empty (animation clips reference joints by name path\n // resolved at post-spawn time, not by sub-asset cross-edge).\n const rec = doc.animationClips[sub.sourceIndex];\n if (rec === undefined) continue;\n const payload = {\n kind: 'animation-clip' as const,\n duration: rec.duration,\n channels: rec.channels.map((ch) => ({\n targetId: ch.targetId,\n property: ch.property,\n sampler: {\n input: ch.sampler.input,\n output: ch.sampler.output,\n interpolation: ch.sampler.interpolation,\n },\n })),\n };\n out.push({ guid: sub.guid, kind: 'animation-clip', payload, refs: [], artifacts: {} });\n }\n }\n return { ok: true, value: { assets: out, sourceDependencies: [] } };\n}\n\n/**\n * The gltf {@link Importer}. Register it into an `ImporterRegistry` so the\n * import runner dispatches `meta.importer === 'gltf'` sidecars here.\n *\n * @example\n * ```ts\n * import { ImporterRegistry } from '@forgeax/engine-import';\n * import { gltfImporter } from '@forgeax/engine-gltf';\n * const importers = new ImporterRegistry();\n * importers.register(gltfImporter);\n * ```\n */\nexport function createGltfImporter(meshopt?: GltfBufferViewDecodeCapability): Importer {\n return {\n key: 'gltf',\n import: (ctx) => importGltf(ctx, meshopt),\n capabilities: { catalog: { publish: publishesCatalogProduct } },\n };\n}\n\n/** Importer for hosts that provide an optional build-only Meshopt decoder. */\nexport const gltfImporter: Importer = createGltfImporter();\n","import { MeshoptDecoder } from 'meshoptimizer';\nimport { createGltfImporter } from './gltf-importer.js';\nimport type { GltfBufferViewDecodeCapability } from './meshopt-decode.js';\n\nawait MeshoptDecoder.ready;\n\n/** Browser/build consumer capability for EXT_meshopt_compression. */\nexport const meshoptDecoder: GltfBufferViewDecodeCapability = {\n decode: ({ source, count, stride, mode, filter }) => {\n const target = new Uint8Array(count * stride);\n MeshoptDecoder.decodeGltfBuffer(target, count, stride, source, mode, filter);\n return target;\n },\n};\n\n/**\n * Build-only glTF importer entry. The player-facing package remains free of\n * the Meshopt WASM dependency; hosts opt into this entry when importing files.\n */\nexport const gltfImporter = createGltfImporter({\n decode: meshoptDecoder.decode,\n});\n\nexport { createGltfImporter } from './gltf-importer.js';\n"]}
|