@forgeax/engine-image 0.1.19 → 0.1.21

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.
Files changed (42) hide show
  1. package/README.md +61 -0
  2. package/dist/.tsbuildinfo +1 -1
  3. package/dist/__tests__/pixel-surface.unit.test.d.ts +2 -0
  4. package/dist/__tests__/pixel-surface.unit.test.d.ts.map +1 -0
  5. package/dist/__tests__/texture-source-descriptor.integration.test.d.ts +2 -0
  6. package/dist/__tests__/texture-source-descriptor.integration.test.d.ts.map +1 -0
  7. package/dist/decode-image-from-file.mjs +2 -1
  8. package/dist/decode-image-from-file.mjs.map +1 -1
  9. package/dist/errors.d.ts.map +1 -1
  10. package/dist/hdr-decoder.mjs +2 -1
  11. package/dist/hdr-decoder.mjs.map +1 -1
  12. package/dist/image-importer.d.ts.map +1 -1
  13. package/dist/image-importer.mjs +222 -16
  14. package/dist/image-importer.mjs.map +1 -1
  15. package/dist/index.d.ts +1 -0
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.mjs +341 -43
  18. package/dist/index.mjs.map +1 -1
  19. package/dist/parse-image.mjs +2 -1
  20. package/dist/parse-image.mjs.map +1 -1
  21. package/dist/pixel-surface.d.ts +53 -0
  22. package/dist/pixel-surface.d.ts.map +1 -0
  23. package/dist/runtime/asset-decoders.d.ts.map +1 -1
  24. package/dist/texture/importer.d.ts +42 -0
  25. package/dist/texture/importer.d.ts.map +1 -0
  26. package/dist/texture/source-descriptor.d.ts +24 -0
  27. package/dist/texture/source-descriptor.d.ts.map +1 -0
  28. package/package.json +6 -6
  29. package/src/__tests__/errors.test-d.ts +11 -3
  30. package/src/__tests__/image-importer-conversion-failure.unit.test.ts +31 -2
  31. package/src/__tests__/image-importer-topology.unit.test.ts +2 -2
  32. package/src/__tests__/image.unit.test.ts +2 -4
  33. package/src/__tests__/ktx2-basis-importer.unit.test.ts +2 -3
  34. package/src/__tests__/pixel-surface.unit.test.ts +94 -0
  35. package/src/__tests__/texture-source-descriptor.integration.test.ts +117 -0
  36. package/src/errors.ts +2 -0
  37. package/src/image-importer.ts +24 -14
  38. package/src/index.ts +8 -0
  39. package/src/pixel-surface.ts +428 -0
  40. package/src/runtime/asset-decoders.ts +40 -11
  41. package/src/texture/importer.ts +198 -0
  42. package/src/texture/source-descriptor.ts +123 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors.ts","../src/result.ts","../src/hdr-decoder.ts","../src/ktx2-encode.ts","../src/parse-image.ts","../src/resize-image.ts","../src/image-importer.ts"],"names":["decodeHdr","decoded","dec","out"],"mappings":";;;;;;;;;;;;;;;AAqDO,SAAS,WACd,MAAA,EACkB;AAClB,EAAA,OAAO,IAAI,eAAkB,MAAM,CAAA;AACrC;AAzDA,IAOM,oBAAA,EAuBO,cAAA;AA9Bb,IAAA,WAAA,GAAA,KAAA,CAAA;AAAA,EAAA,eAAA,GAAA;AAOA,IAAM,oBAAA,GAAiE;AAAA,MACrE,qBAAA,EAAuB,4CAAA;AAAA,MACvB,0BAAA,EACE,+FAAA;AAAA,MACF,+BAAA,EACE,mFAAA;AAAA,MACF,oBAAA,EACE,6EAAA;AAAA,MACF,yBAAA,EAA2B,mEAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAQ3B,mBAAA,EAAqB,oBAAA;AAAA,MACrB,qBAAA,EACE,mFAAA;AAAA,MACF,uBAAA,EAAyB;AAAA,KAC3B;AAGO,IAAM,cAAA,GAAN,cACG,KAAA,CAEV;AAAA,MACW,IAAA;AAAA,MACA,QAAA;AAAA,MACA,IAAA;AAAA,MACA,MAAA;AAAA,MAET,YAAY,MAAA,EAAgC;AAC1C,QAAA,MAAM,OAAO,MAAA,CAAO,IAAA;AACpB,QAAA,MAAM,QAAA,GAAW,qBAAqB,IAAI,CAAA;AAC1C,QAAA,MAAM,IAAA,GAAO,kBAAkB,IAAI,CAAA;AACnC,QAAA,KAAA,CAAM,eAAe,IAAI,CAAA,YAAA,EAA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AA,CAAI,KAAA;AAAA,QACX,QAAQ,GAAA,CAAI,MAAA;AAAA,QACZ,MAAA,EAAQ,mBAAmB,UAAU,CAAA;AAAA,QACrC,UAAA;AAAA,QACA;AAAA,OACF;AAAA,MACA,KAAA,EAAO,WAAA;AAAA,MACP,SAAA;AAAA,MACA;AAAA;AACF,GACF;AACF;AAeO,IAAM,aAAA,GAA0B;AAAA,EACrC,GAAA,EAAK,OAAA;AAAA,EACL,MAAA,EAAQ,WAAA;AAAA,EACR,YAAA,EAAc,EAAE,WAAA,EAAa,oBAAA;AAC/B","file":"image-importer.mjs","sourcesContent":["import type { ImageErrorCode, ImageErrorDetailFor, ImageErrorFor } from '@forgeax/engine-types';\nimport { IMAGE_ERROR_HINTS } from '@forgeax/engine-types';\n\n// Per-code .expected string literals SSOT.\n// Mirrors ASSET_ERROR_HINTS / IMAGE_ERROR_HINTS shape (charter P5 consistent\n// abstraction). AI users surface .expected when a structured error needs to\n// describe the precondition that was violated.\nconst IMAGE_ERROR_EXPECTED: Readonly<Record<ImageErrorCode, string>> = {\n 'image-decode-failed': 'PNG / JPG byte stream decodes successfully',\n 'image-format-unsupported':\n \"mime is one of ['image/png', 'image/jpeg']; uploadTexture format <-> colorSpace family agrees\",\n 'image-dimension-out-of-bounds':\n 'width and height fall under device caps maxTextureDimension2D (or 16384 hard cap)',\n 'image-meta-missing':\n \"<source>.meta.json sidecar (importer: 'image') exists in the same directory\",\n 'image-hdr-decode-failed': 'Radiance RGBE header is valid and pixel data decodes successfully',\n // feat-20260521-sprite-atlas-animation M1 T-03 — vite-plugin-image atlas\n // hook .expected literals (plan-strategy section 2 D-2 + AC-10 a/b/c).\n // ImageErrorImpl construction path is unchanged: the new atlas-* errors\n // flow through `new ImageErrorImpl({ code: 'atlas-...', ...detail })` and\n // pick the .expected string up from this Record at construction time\n // (charter P3 explicit failure SSOT — AI users surface .expected next to\n // .hint after switch (err.code) without parsing the message).\n 'atlas-empty-input': 'images.length >= 1',\n 'atlas-size-exceeded':\n 'image width x height <= maxAtlasSize^2 and each image fits in the atlas footprint',\n 'atlas-region-mismatch': 'sum(regions[i].w x regions[i].h) <= atlasWidth x atlasHeight',\n};\n\n/** Runtime implementation of the correlated `ImageErrorFor<C>` envelope. */\nexport class ImageErrorImpl<C extends ImageErrorCode = ImageErrorCode>\n extends Error\n implements ImageErrorFor<C>\n{\n readonly code: C;\n readonly expected: string;\n readonly hint: string;\n readonly detail: ImageErrorDetailFor<C>;\n\n constructor(detail: ImageErrorDetailFor<C>) {\n const code = detail.code;\n const expected = IMAGE_ERROR_EXPECTED[code];\n const hint = IMAGE_ERROR_HINTS[code];\n super(`[ImageError ${code}] expected: ${expected}; hint: ${hint}`);\n this.name = 'ImageError';\n this.code = code;\n this.expected = expected;\n this.hint = hint;\n this.detail = detail;\n }\n}\n\n/** Construct a structured image error while preserving its code/detail pair. */\nexport function imageError<C extends ImageErrorCode>(\n detail: ImageErrorDetailFor<C>,\n): ImageErrorFor<C> {\n return new ImageErrorImpl<C>(detail);\n}\n\nexport { IMAGE_ERROR_EXPECTED };\n","// Result<T, E> + ok / err live in `@forgeax/engine-types` (tweak-20260612-result-\n// into-types). They were duplicated here as a lite (plain-object, no `unwrap`)\n// variant; consolidated upstream into the same shape used by rhi / ecs / naga.\n// The barrel here re-exports them so existing\n// `import { err, ok, Result, ResultOk, ResultErr } from '@forgeax/engine-image'`\n// consumers (and intra-package `./result.js` imports) stay unchanged.\nexport {\n err,\n ok,\n type Result,\n type ResultErr,\n type ResultOk,\n} from '@forgeax/engine-types';\n","import type { ImageError } from '@forgeax/engine-types';\nimport { imageError } from './errors.js';\nimport type { Result } from './result.js';\nimport { err, ok } from './result.js';\n\n/**\n * Decoded HDR image POD.\n *\n * `data` is an interleaved RGBA Float32Array (4 floats per pixel, row-major).\n * Color space is always linear (RGBE is radiance).\n */\nexport interface HdrDecoded {\n readonly width: number;\n readonly height: number;\n readonly data: Float32Array;\n}\n\n// ASCII code points\nconst LF = 0x0a;\n\n/**\n * Decode a Radiance RGBE (.hdr) byte stream into linear RGBA float pixels.\n *\n * Steps per research F-6:\n * 1. Parse ASCII header: magic (#?RADIANCE), FORMAT=32-bit_rle_rgbe,\n * resolution line (-Y height +X width).\n * 2. Decode per-scanline new-RLE pixel data: 4 independent channel runs.\n * 3. Convert RGBE to float: if E==0 -> 0; else f=2^(E-136), R=(Rm+0.5)*f.\n * 4. Output as interleaved RGBA Float32Array (alpha=1.0).\n *\n * Old-RLE scanlines (prefix not matching 0x02,0x02,hi,lo with correct width)\n * return image-hdr-decode-failed.\n */\nexport function decodeHdr(bytes: Uint8Array): Result<HdrDecoded, ImageError> {\n let pos = 0;\n\n // Step 1a: magic -- must start with \"#?RADIANCE\" or \"#?RGBE\"\n if (bytes.length < 11) {\n return err(hdrDecodeError('file too short for Radiance HDR header'));\n }\n const magic = String.fromCharCode(...bytes.subarray(0, 11));\n if (magic !== '#?RADIANCE\\n' && magic !== '#?RGBE\\n') {\n return err(\n hdrDecodeError('missing or invalid Radiance HDR magic; expected #?RADIANCE or #?RGBE'),\n );\n }\n pos = 11;\n\n // Step 1b: key=value lines until empty line\n let formatFound = false;\n while (pos < bytes.length) {\n const lineEnd = findByte(bytes, LF, pos);\n if (lineEnd === -1) return err(hdrDecodeError('header truncated before empty line'));\n const line = asciiSubstring(bytes, pos, lineEnd);\n pos = lineEnd + 1;\n if (line === '') break;\n if (line.startsWith('FORMAT=')) {\n const val = line.slice(7);\n if (val === '32-bit_rle_rgbe') {\n formatFound = true;\n }\n }\n }\n if (!formatFound) {\n return err(hdrDecodeError('missing or unsupported FORMAT; expected FORMAT=32-bit_rle_rgbe'));\n }\n\n // Step 1c: resolution line (-Y height +X width)\n if (pos >= bytes.length) return err(hdrDecodeError('missing resolution line'));\n const resLineEnd = findByte(bytes, LF, pos);\n if (resLineEnd === -1) return err(hdrDecodeError('resolution line truncated'));\n const resLine = asciiSubstring(bytes, pos, resLineEnd);\n pos = resLineEnd + 1;\n const resMatch = /^-Y\\s+(\\d+)\\s+\\+X\\s+(\\d+)\\s*$/.exec(resLine);\n if (resMatch === null) {\n return err(\n hdrDecodeError(`unexpected resolution line format: \"${resLine}\"; expected \"-Y H +X W\"`),\n );\n }\n const height = Number(resMatch[1]);\n const width = Number(resMatch[2]);\n if (height === undefined || width === undefined || height <= 0 || width <= 0) {\n return err(hdrDecodeError(`invalid dimensions: ${width}x${height}`));\n }\n\n // Step 2: decode per-scanline new-RLE pixel data\n const pixelCount = width * height;\n const rgbe = new Uint8Array(pixelCount * 4);\n const scanlineBytes = width * 4;\n\n for (let y = 0; y < height; y++) {\n if (pos + 4 > bytes.length) {\n return err(hdrDecodeError(`truncated at scanline ${y}: expected 4-byte prefix`));\n }\n const p0 = bytes[pos];\n const p1 = bytes[pos + 1];\n const pHi = bytes[pos + 2];\n const pLo = bytes[pos + 3];\n if (p0 === undefined || p1 === undefined || pHi === undefined || pLo === undefined) {\n return err(hdrDecodeError(`truncated at scanline ${y}`));\n }\n // biome-ignore lint/style/noNonNullAssertion: checked above\n const prefixWidth = (pHi! << 8) | pLo!;\n\n if (p0 === 0x02 && p1 === 0x02 && prefixWidth === width && width >= 8 && width <= 32767) {\n // New-RLE: 4 channels independently RLE-encoded, then interleaved\n const decoded = decodeNewRleScanline(bytes, pos + 4, width);\n if (decoded === null) {\n return err(hdrDecodeError(`RLE decode failed at scanline ${y}`));\n }\n // Copy into rgbe interleaved buffer\n const base = y * scanlineBytes;\n const channels = [decoded[0], decoded[1], decoded[2], decoded[3]];\n for (let x = 0; x < width; x++) {\n for (let ch = 0; ch < 4; ch++) {\n // biome-ignore lint/style/noNonNullAssertion: checked at allocation\n rgbe[base + x * 4 + ch] = channels[ch]![x]!;\n }\n }\n // Advance pos past the 4-byte prefix + the total RLE bytes consumed\n pos += 4 + decoded.totalBytes;\n } else {\n // Old-RLE: not supported\n return err(\n hdrDecodeError(\n 'old-RLE format is not supported; only new-RLE (32-bit_rle_rgbe) is accepted',\n ),\n );\n }\n }\n\n // Step 3: RGBE to float\n const out = new Float32Array(pixelCount * 4);\n for (let i = 0; i < pixelCount; i++) {\n const base = i * 4;\n // biome-ignore lint/style/noNonNullAssertion: checked at allocation\n const r = rgbe[base]!;\n // biome-ignore lint/style/noNonNullAssertion: checked at allocation\n const g = rgbe[base + 1]!;\n // biome-ignore lint/style/noNonNullAssertion: checked at allocation\n const b = rgbe[base + 2]!;\n // biome-ignore lint/style/noNonNullAssertion: checked at allocation\n const e = rgbe[base + 3]!;\n out[base + 3] = 1.0;\n\n if (e === 0) {\n out[base] = 0;\n out[base + 1] = 0;\n out[base + 2] = 0;\n } else {\n // f = 2^(E - 136) = ldexp(1.0, E - 128 - 8)\n // Equivalent: ldexp(1.0 / 256.0, E - 128)\n // But simpler: const f = (1.0 / 256.0) * Math.pow(2, e - 128);\n // Using ldexp: Math.pow(2, e - 136)\n const f = 2 ** (e - 136);\n out[base] = (r + 0.5) * f;\n out[base + 1] = (g + 0.5) * f;\n out[base + 2] = (b + 0.5) * f;\n }\n }\n\n return ok({ width, height, data: out });\n}\n\ninterface DecodedScanline {\n /** 4 channels, each width bytes */\n readonly 0: Uint8Array;\n readonly 1: Uint8Array;\n readonly 2: Uint8Array;\n readonly 3: Uint8Array;\n readonly totalBytes: number;\n}\n\n/**\n * Decode one scanline of new-RLE data into 4 channel arrays.\n * Returns null on failure (data underrun).\n */\nfunction decodeNewRleScanline(\n bytes: Uint8Array,\n start: number,\n width: number,\n): DecodedScanline | null {\n const channels: Uint8Array[] = [];\n let cursor = start;\n\n for (let ch = 0; ch < 4; ch++) {\n const data = new Uint8Array(width);\n let x = 0;\n while (x < width) {\n if (cursor >= bytes.length) return null;\n // biome-ignore lint/style/noNonNullAssertion: checked above\n const code = bytes[cursor]!;\n cursor++;\n if (code > 128) {\n // RLE run: next byte repeated (code - 128) times\n const count = code - 128;\n if (cursor >= bytes.length || x + count > width) return null;\n // biome-ignore lint/style/noNonNullAssertion: checked above\n const val = bytes[cursor]!;\n cursor++;\n data.fill(val, x, x + count);\n x += count;\n } else {\n // Literal run: next `code` bytes copied verbatim\n if (code === 0) continue;\n if (cursor + code > bytes.length || x + code > width) return null;\n for (let k = 0; k < code; k++) {\n // biome-ignore lint/style/noNonNullAssertion: checked above\n data[x + k] = bytes[cursor + k]!;\n }\n cursor += code;\n x += code;\n }\n }\n channels.push(data);\n }\n\n const ch0 = channels[0];\n const ch1 = channels[1];\n const ch2 = channels[2];\n const ch3 = channels[3];\n if (ch0 === undefined || ch1 === undefined || ch2 === undefined || ch3 === undefined) {\n return null; // channels should always have 4 entries\n }\n return {\n 0: ch0,\n 1: ch1,\n 2: ch2,\n 3: ch3,\n totalBytes: cursor - start,\n };\n}\n\nfunction findByte(bytes: Uint8Array, target: number, start: number): number {\n for (let i = start; i < bytes.length; i++) {\n if (bytes[i] === target) return i;\n }\n return -1;\n}\n\nfunction asciiSubstring(bytes: Uint8Array, start: number, end: number): string {\n let s = '';\n for (let i = start; i < end; i++) {\n // biome-ignore lint/style/noNonNullAssertion: in bounds\n s += String.fromCharCode(bytes[i]!);\n }\n return s;\n}\n\nfunction hdrDecodeError(reason: string): ImageError {\n return imageError({\n code: 'image-hdr-decode-failed',\n reason,\n });\n}\n","// ktx2-encode.ts -- the image-side offline texture encode arm (M3 w18, D-5).\n//\n// This module is the image-semantic layer of the Basis encode path: it maps the\n// sidecar `compressionMode` control-plane value + the source's colorSpace / HDR\n// signal into a delivery encoding (D-12 'auto' derivation), maps that to the\n// encoder parameters, and drives the low-level `basisEncode` binding that lives\n// in `@forgeax/engine-codec/encode` (the WASM + enum plumbing stays in codec;\n// the image semantics stay here -- D-5 \"arm in image, binary in codec/encode\").\n//\n// It is a NODE-ONLY build-time module (consumed by imageImporter, itself a\n// node-only sub-export). It never touches GPU (isolation path b) and is never\n// bundled into the runtime (isolation path a/d: runtime does not import\n// @forgeax/engine-image nor @forgeax/engine-codec/encode).\n//\n// M3 sequencing constraint (plan R-9): the 'auto' derivation is implemented and\n// tested here, but the sidecar DEFAULT stays 'none'. The default flip to 'auto'\n// is M5 (w38); doing it here would make every existing texture encode to Basis\n// ahead of loader support and redden the whole fixture fleet.\n\nimport type { BasisEncodeMode } from '@forgeax/engine-codec/encode';\nimport { basisEncode } from '@forgeax/engine-codec/encode';\n\n/** The sidecar control-plane value (ImageMetadata.compressionMode). */\nexport type CompressionMode = 'auto' | 'etc1s' | 'uastc' | 'none';\n\n/** The resolved delivery encoding after 'auto' derivation. `'none'` = no encode. */\nexport type ResolvedEncodeMode = 'etc1s' | 'uastc' | 'uastc-hdr' | 'none';\n\n/** Source signals that drive 'auto' derivation (D-12) and encoder params. */\nexport interface EncodeSourceInfo {\n /** Color transfer of the source (from the sidecar importSettings). */\n readonly colorSpace: 'srgb' | 'linear';\n /** Whether the source is an HDR image (.hdr -> rgba16float). */\n readonly isHdr: boolean;\n}\n\n/**\n * Resolve the sidecar `compressionMode` into a concrete delivery encoding.\n *\n * D-12 'auto' derivation (zero new required inputs, derived from existing\n * sidecar signals):\n * - HDR source -> 'uastc-hdr' (BC6H target downstream)\n * - colorSpace 'srgb' -> 'etc1s' (albedo / UI color)\n * - colorSpace 'linear' -> 'uastc' (normals / ORM / data)\n *\n * Explicit modes pass through, except an explicit 'uastc' on an HDR source\n * resolves to 'uastc-hdr' (there is no LDR UASTC path for HDR pixels). 'none'\n * and 'etc1s' pass through verbatim.\n */\nexport function resolveEncodeMode(\n mode: CompressionMode,\n source: EncodeSourceInfo,\n): ResolvedEncodeMode {\n switch (mode) {\n case 'none':\n return 'none';\n case 'etc1s':\n return 'etc1s';\n case 'uastc':\n return source.isHdr ? 'uastc-hdr' : 'uastc';\n case 'auto':\n if (source.isHdr) return 'uastc-hdr';\n return source.colorSpace === 'srgb' ? 'etc1s' : 'uastc';\n }\n}\n\n/** Encoder parameters for a resolved delivery encoding. */\nexport interface BasisEncodeParams {\n /** The codec-side delivery encoding. */\n readonly mode: BasisEncodeMode;\n /** Write the sRGB transfer function (LDR color only). */\n readonly srgb: boolean;\n /** ETC1S perceptual (sRGB) metric. */\n readonly perceptual: boolean;\n /** Wrap the UASTC-LDR payload in KTX2 zstd supercompression. */\n readonly uastcSupercompression: boolean;\n /** Encoder-side mip generation. M3 keeps this false (offline mips land in M5). */\n readonly mipGen: boolean;\n}\n\n/**\n * Map the sidecar mode + source into encoder parameters. Returns `null` for the\n * 'none' path -- the caller keeps the uncompressed `.bin` path and never calls\n * the encoder.\n */\nexport function basisEncodeParamsFor(\n mode: CompressionMode,\n source: EncodeSourceInfo,\n): BasisEncodeParams | null {\n const resolved = resolveEncodeMode(mode, source);\n const srgbColor = source.colorSpace === 'srgb';\n switch (resolved) {\n case 'none':\n return null;\n case 'etc1s':\n return {\n mode: 'etc1s',\n srgb: srgbColor,\n perceptual: srgbColor,\n uastcSupercompression: false,\n mipGen: false,\n };\n case 'uastc':\n return {\n mode: 'uastc-ldr',\n srgb: srgbColor,\n perceptual: srgbColor,\n uastcSupercompression: true,\n mipGen: false,\n };\n case 'uastc-hdr':\n return {\n mode: 'uastc-hdr',\n srgb: false,\n perceptual: false,\n uastcSupercompression: false,\n mipGen: false,\n };\n }\n}\n\n/** A successful encode result: KTX2 bytes + the resolved delivery encoding. */\nexport interface EncodedTexture {\n readonly ktx2: Uint8Array;\n readonly mode: ResolvedEncodeMode;\n}\n\n/**\n * Maximum source pixels the wasm32 Basis encoder accepts (4096x4096 = 16.78 Mpx\n * = 1024*1024*16). This mirrors the raised `BASISU_ENCODER_MAX_SOURCE_IMAGE_PIXELS`\n * ceiling patched into the encoder WASM (packages/codec/scripts/build-wasm.mjs).\n * Sources above this are rejected fast with a structured `ktx2-encode-source-too-large`\n * error rather than reaching the encoder and getting a silent 0-byte failure.\n */\nexport const MAX_ENCODE_SOURCE_PIXELS = 4096 * 4096;\n\n/** Failure result carrying a short reason (encoder-side or invalid request). */\nexport interface EncodeFailure {\n readonly code: 'ktx2-encode-failed' | 'codec-init-failed' | 'ktx2-encode-source-too-large';\n readonly mode: ResolvedEncodeMode;\n readonly reason: string;\n}\n\nexport type EncodeTextureResult =\n | { readonly ok: true; readonly value: EncodedTexture }\n | { readonly ok: false; readonly error: EncodeFailure };\n\n/**\n * Encode source pixels into a Basis KTX2 texture per the sidecar mode.\n *\n * `pixels` is tight-packed RGBA: 8-bit RGBA for LDR sources, rgba16float bytes\n * for HDR sources. Returns `{ ok: false }` with `mode: 'none'` if the sidecar\n * mode resolves to 'none' -- the importer treats that as \"no encode, keep the\n * .bin path\" rather than an error (see importer callsite w18).\n */\nexport async function encodeTextureToKtx2(\n pixels: Uint8Array,\n width: number,\n height: number,\n mode: CompressionMode,\n source: EncodeSourceInfo,\n): Promise<EncodeTextureResult> {\n const params = basisEncodeParamsFor(mode, source);\n if (params === null) {\n return {\n ok: false,\n error: {\n code: 'ktx2-encode-failed',\n mode: 'none',\n reason: 'compressionMode resolved to none',\n },\n };\n }\n const resolved = resolveEncodeMode(mode, source);\n // Fail fast above the wasm32 encoder's source-pixel ceiling (4096^2). Above\n // this the encoder returns 0 bytes silently; surface a structured, actionable\n // error instead so the importer reports \"reduce resolution or set\n // compressionMode:'none'\" rather than an opaque encode failure.\n if (width * height > MAX_ENCODE_SOURCE_PIXELS) {\n return {\n ok: false,\n error: {\n code: 'ktx2-encode-source-too-large',\n mode: resolved,\n reason:\n `source ${width}x${height} (${width * height} px) exceeds the ${MAX_ENCODE_SOURCE_PIXELS} px ` +\n '(4096x4096) Basis encode ceiling; reduce the texture resolution to <=4096x4096 ' +\n \"or set compressionMode:'none' in the sidecar to keep it uncompressed\",\n },\n };\n }\n const result = await basisEncode(pixels, {\n mode: params.mode,\n width,\n height,\n srgb: params.srgb,\n perceptual: params.perceptual,\n uastcSupercompression: params.uastcSupercompression,\n mipGen: params.mipGen,\n });\n if (!result.ok) {\n const reason =\n result.error.detail !== undefined && 'reason' in result.error.detail\n ? String((result.error.detail as { reason: unknown }).reason)\n : result.error.code;\n return {\n ok: false,\n error: {\n code:\n result.error.code === 'codec-init-failed' ? 'codec-init-failed' : 'ktx2-encode-failed',\n mode: resolved,\n reason,\n },\n };\n }\n return { ok: true, value: { ktx2: result.value, mode: resolved } };\n}\n","import type { DecodedImage, ImageColorSpace, ImageError } from '@forgeax/engine-types';\nimport * as jpeg from 'jpeg-js';\n// Static imports of upng-js + jpeg-js. tsup external keeps both as runtime\n// require() calls so the browser bundle still tree-shakes them out when\n// only image-decoder-browser.ts (createImageBitmap) is reached at runtime.\n// Synchronous decode is required by the parseImage signature contract (see\n// plan-strategy section 3.3).\nimport * as UPNG from 'upng-js';\nimport { imageError } from './errors.js';\nimport { downscaleRgba } from './resize-image.js';\nimport type { Result } from './result.js';\nimport { err, ok } from './result.js';\n\nexport interface ParseImageOptions {\n /**\n * Maximum allowed dimension (width or height). Defaults to 16384 -- the\n * conservative WebGPU `maxTextureDimension2D` floor across desktop +\n * high-end mobile (research F-3 / spec). Test fixtures pass smaller\n * values to exercise the bounds-check code path with tiny fixtures.\n */\n readonly maxDimension?: number;\n\n /** Optional asset-owned cooked-payload target; source bytes remain unchanged. */\n readonly downscaleMaxDimension?: number;\n\n /**\n * Sidecar `colorSpace` carried over to the DecodedImage POD. Defaults to\n * 'srgb' (typical baseColor / albedo path; plan-strategy section 2.5).\n */\n readonly colorSpace?: ImageColorSpace;\n\n /**\n * Sidecar `mipmap` flag carried over to DecodedImage. Defaults to true\n * (auto-generate via runtime mipmap-generator; plan-strategy section 2.6).\n */\n readonly mipmap?: boolean;\n\n /**\n * Optional source path to embed in error.detail.path (decode-failed /\n * format-unsupported variants). decodeImageFromFile fills this in;\n * in-memory parseImage callers leave it empty.\n */\n readonly path?: string;\n}\n\nconst DEFAULT_MAX_DIMENSION = 16384;\n\nconst SUPPORTED_MIMES: readonly string[] = ['image/png', 'image/jpeg'];\n\ninterface UpngDecoded {\n readonly width: number;\n readonly height: number;\n readonly data: Uint8Array;\n}\n\ninterface JpegDecoded {\n readonly width: number;\n readonly height: number;\n readonly data: Uint8Array;\n}\n\n/**\n * Pure synchronous image decoder. Translates raw byte stream + mime hint\n * into a tight-packed RGBA `DecodedImage` POD. Surfaces all four\n * ImageErrorCode members through the structured `Result<DecodedImage,\n * ImageError>` return (charter P3 explicit failure; AGENTS.md \"Return\n * Result, never throw\").\n *\n * Decoder selection follows the mime hint:\n * - `image/png` -> upng-js `UPNG.decode` + `UPNG.toRGBA8`\n * - `image/jpeg` -> jpeg-js `decode` with `formatAsRGBA: true`\n * - other -> `image-format-unsupported`\n *\n * Decoded bytes are always tight-packed RGBA (`bytes.length === width *\n * height * 4`). `colorSpace` and `mipmap` are carried from the supplied\n * `ParseImageOptions` (decodeImageFromFile passes the sidecar settings).\n */\nexport function parseImage(\n bytes: Uint8Array,\n mime: string,\n opts: ParseImageOptions = {},\n): Result<DecodedImage, ImageError> {\n if (!SUPPORTED_MIMES.includes(mime)) {\n return err(\n imageError({\n code: 'image-format-unsupported',\n actualMime: mime,\n ...(opts.path !== undefined ? { path: opts.path } : {}),\n }),\n );\n }\n\n let width = 0;\n let height = 0;\n let rgba: Uint8Array;\n\n try {\n if (mime === 'image/png') {\n const upngMod: {\n decode: (b: Uint8Array | ArrayBuffer) => UpngDecoded;\n toRGBA8: (i: UpngDecoded) => ArrayBuffer[];\n } = ((UPNG as unknown as { default?: typeof UPNG }).default ?? UPNG) as unknown as {\n decode: (b: Uint8Array | ArrayBuffer) => UpngDecoded;\n toRGBA8: (i: UpngDecoded) => ArrayBuffer[];\n };\n const decoded = upngMod.decode(bytes);\n width = decoded.width;\n height = decoded.height;\n const frames = upngMod.toRGBA8(decoded);\n const first = frames[0];\n if (first === undefined) {\n return err(\n imageError({\n code: 'image-decode-failed',\n reason: 'UPNG.toRGBA8 returned no frames',\n ...(opts.path !== undefined ? { path: opts.path } : {}),\n }),\n );\n }\n rgba = new Uint8Array(first);\n } else {\n // image/jpeg\n const jpegMod: {\n decode: (\n b: Uint8Array | ArrayBuffer,\n o?: { useTArray?: boolean; formatAsRGBA?: boolean },\n ) => JpegDecoded;\n } = ((jpeg as unknown as { default?: typeof jpeg }).default ?? jpeg) as unknown as {\n decode: (\n b: Uint8Array | ArrayBuffer,\n o?: { useTArray?: boolean; formatAsRGBA?: boolean },\n ) => JpegDecoded;\n };\n const decoded = jpegMod.decode(bytes, { useTArray: true, formatAsRGBA: true });\n width = decoded.width;\n height = decoded.height;\n rgba = decoded.data;\n }\n } catch (e) {\n return err(\n imageError({\n code: 'image-decode-failed',\n reason: e instanceof Error ? e.message : String(e),\n ...(opts.path !== undefined ? { path: opts.path } : {}),\n }),\n );\n }\n\n const downscaleLimit = opts.downscaleMaxDimension;\n if (downscaleLimit !== undefined && Number.isInteger(downscaleLimit) && downscaleLimit > 0) {\n const downscaled = downscaleRgba(rgba, width, height, downscaleLimit);\n rgba = downscaled.bytes;\n width = downscaled.width;\n height = downscaled.height;\n }\n\n const limit = opts.maxDimension ?? DEFAULT_MAX_DIMENSION;\n if (width > limit || height > limit) {\n return err(\n imageError({\n code: 'image-dimension-out-of-bounds',\n requested: { width, height },\n limit,\n }),\n );\n }\n\n return ok({\n bytes: rgba,\n width,\n height,\n mime: mime as 'image/png' | 'image/jpeg',\n colorSpace: opts.colorSpace ?? 'srgb',\n mipmap: opts.mipmap ?? true,\n });\n}\n","/** Deterministically downscale tight-packed RGBA pixels with bilinear sampling. */\nexport function downscaleRgba(\n bytes: Uint8Array,\n width: number,\n height: number,\n maxDimension: number,\n): { readonly bytes: Uint8Array; readonly width: number; readonly height: number } {\n if (width <= maxDimension && height <= maxDimension) {\n return { bytes, width, height };\n }\n\n const scale = maxDimension / Math.max(width, height);\n const targetWidth = Math.max(1, Math.round(width * scale));\n const targetHeight = Math.max(1, Math.round(height * scale));\n const output = new Uint8Array(targetWidth * targetHeight * 4);\n const source = (x: number, y: number, channel: number): number =>\n bytes[(y * width + x) * 4 + channel] ?? 0;\n\n for (let y = 0; y < targetHeight; y += 1) {\n const sourceY = ((y + 0.5) * height) / targetHeight - 0.5;\n const y0 = Math.max(0, Math.floor(sourceY));\n const y1 = Math.min(height - 1, y0 + 1);\n const yWeight = Math.max(0, Math.min(1, sourceY - y0));\n for (let x = 0; x < targetWidth; x += 1) {\n const sourceX = ((x + 0.5) * width) / targetWidth - 0.5;\n const x0 = Math.max(0, Math.floor(sourceX));\n const x1 = Math.min(width - 1, x0 + 1);\n const xWeight = Math.max(0, Math.min(1, sourceX - x0));\n const outputOffset = (y * targetWidth + x) * 4;\n for (let channel = 0; channel < 4; channel += 1) {\n const top = source(x0, y0, channel) * (1 - xWeight) + source(x1, y0, channel) * xWeight;\n const bottom = source(x0, y1, channel) * (1 - xWeight) + source(x1, y1, channel) * xWeight;\n output[outputOffset + channel] = Math.round(top * (1 - yWeight) + bottom * yWeight);\n }\n }\n }\n\n return { bytes: output, width: targetWidth, height: targetHeight };\n}\n","// image-importer.ts - the build-time imageImporter (feat-20260603-asset-import-loader-injection M3 / w23).\n//\n// The `{ key: 'image', import }` Importer the @forgeax/engine-import runner\n// dispatches a `*.meta.json` with `importer: 'image'` to. It absorbs the\n// decode logic that previously lived inline in\n// `@forgeax/engine-vite-plugin-pack`'s generateBundle (research Finding 4,\n// vite-plugin-pack/src/index.ts:354-447): read the source bytes -> parseImage\n// -> tight-packed RGBA `DecodedImage` -> a `TextureAsset` POD whose `data`\n// column carries the imported RGBA bytes under the meta-declared GUID.\n//\n// Why image-importer lives in @forgeax/engine-image (D-9): the image domain\n// logic stays co-located with the package that already owns parseImage (a\n// node-only decoder). Splitting the import into a third package would fracture\n// the SSOT. This module is a NODE-ONLY sub-export\n// (`@forgeax/engine-image/image-importer`, `default: null` under browser\n// conditions) because it statically imports `./parse-image.js` (jpeg-js +\n// upng-js). The browser runtime never reaches it: the texture is decoded at\n// build time and the runtime loader reads the imported `.bin` (M3 strips the\n// runtime decoder edge, AC-15).\n//\n// importSettings folding (colorSpace / mipmap -> TextureAsset.format) mirrors\n// `build-catalog.ts` buildImageMetadata (D-5: `'auto'` -> true / `'none'` ->\n// false, `'srgb'` -> 'rgba8unorm-srgb' / `'linear'` -> 'rgba8unorm') so the\n// importer and the catalog builder derive the same texture metadata. The\n// imported RGBA bytes ride in `TextureAsset.data`; the generateBundle integration (w28)\n// extracts that buffer into a hashed `.bin` and folds width/height/format into\n// the pack-index row.\n//\n// GUID import-stable iron law: every produced `ImportedAsset.guid` comes from\n// `ctx.subAssets[]`, never minted here. A sub-asset of `kind: 'equirect'`\n// (HDR lat-long env map) IS folded by the .hdr arm into an EquirectAsset POD\n// (a single 2D rgba16float image); the cube-to-cube IBL projection is a runtime\n// GPU pass, not a build-time fold (feat-20260630).\n\nimport { type BasisSourceInspection, ktx2ColorSpace, parseKtx2 } from '@forgeax/engine-codec';\nimport type {\n EquirectAsset,\n ImageColorSpace,\n ImportContext,\n ImportedAsset,\n Importer,\n ImportResult,\n TextureAsset,\n} from '@forgeax/engine-types';\nimport { IMPORT_ERROR_HINTS, ImportError } from '@forgeax/engine-types';\nimport type { CompressionMode } from './ktx2-encode.js';\nimport { encodeTextureToKtx2, resolveEncodeMode } from './ktx2-encode.js';\nimport { parseImage } from './parse-image.js';\n\n/** Map a source path / mime hint to the parseImage mime literal. */\nfunction mimeFromSource(source: string): 'image/png' | 'image/jpeg' | undefined {\n const lower = source.toLowerCase();\n if (lower.endsWith('.png')) return 'image/png';\n if (lower.endsWith('.jpg') || lower.endsWith('.jpeg')) return 'image/jpeg';\n return undefined;\n}\n\ntype RequiredImageOutputKind = 'texture' | 'equirect';\n\nfunction requiredImageOutputKind(source: string): RequiredImageOutputKind | undefined {\n const lower = source.toLowerCase();\n if (lower.endsWith('.hdr')) return 'equirect';\n if (mimeFromSource(source) !== undefined || lower.endsWith('.basis') || lower.endsWith('.ktx2')) {\n return 'texture';\n }\n return undefined;\n}\n\nfunction imageOutputTopologyActual(ctx: ImportContext): string {\n if (ctx.subAssets.length === 0) return 'subAssets[] is empty';\n return ctx.subAssets\n .map(\n (sub, index) => `subAssets[${index}]=${sub.kind}:${sub.guid}:sourceIndex=${sub.sourceIndex}`,\n )\n .join(', ');\n}\n\ntype ImageConversionStage = 'decode' | 'inspect' | 'encode';\n\nfunction imageConversionFailure(\n ctx: ImportContext,\n stage: ImageConversionStage,\n ownerCode: string,\n sourcePath: string,\n expected: string,\n actual: string,\n hint: string,\n): ImportError {\n const diagnosticSourcePath = sourcePath.length === 0 ? ctx.source : sourcePath;\n return new ImportError({\n code: 'source-validation-failed',\n expected,\n actual,\n hint: IMPORT_ERROR_HINTS['source-validation-failed'],\n detail: {\n diagnostics: [\n {\n code: `image-conversion-${stage}-${ownerCode}`,\n severity: 'error',\n sourcePath: diagnosticSourcePath,\n sourceRange: { start: 0, end: 0, line: 1, column: 1 },\n rule: `image-conversion-${stage}`,\n expected,\n actual,\n hint,\n },\n ],\n },\n });\n}\n\nfunction validateImageOutputTopology(\n ctx: ImportContext,\n requiredKind: RequiredImageOutputKind,\n): ImportError | undefined {\n if (\n ctx.subAssets.length === 1 &&\n ctx.subAssets[0]?.kind === requiredKind &&\n ctx.subAssets[0]?.sourceIndex === 0\n ) {\n return undefined;\n }\n\n const expected = `exactly one subAssets[] entry with kind \"${requiredKind}\" and sourceIndex 0`;\n const actual = imageOutputTopologyActual(ctx);\n return new ImportError({\n code: 'source-validation-failed',\n expected,\n actual,\n hint: IMPORT_ERROR_HINTS['source-validation-failed'],\n detail: {\n diagnostics: [\n {\n code: 'image-subasset-topology',\n severity: 'error',\n sourcePath: `${ctx.source}#subAssets`,\n sourceRange: { start: 0, end: 0, line: 1, column: 1 },\n rule: 'image-required-single-output',\n expected,\n actual,\n hint: `declare exactly one ${requiredKind} sub-asset with sourceIndex 0 and remove foreign, duplicate, or misplaced entries`,\n },\n ],\n },\n });\n}\n\n/** D-5 mipmap token mapping (mirrors build-catalog mipmapTokenToBoolean). */\nfunction mipmapTokenToBoolean(token: unknown): boolean {\n return token === 'auto' || token === true;\n}\n\n/** colorSpace -> GPU format literal (mirrors build-catalog colorSpaceToFormat). */\nfunction colorSpaceToFormat(colorSpace: ImageColorSpace): GPUTextureFormat {\n return colorSpace === 'srgb' ? 'rgba8unorm-srgb' : 'rgba8unorm';\n}\n\ntype BasisProfile = 'etc1s' | 'uastc-ldr' | 'uastc-hdr';\n\nasync function inspectKtx2Source(\n ctx: ImportContext,\n bytes: Uint8Array,\n metaColorSpace: ImageColorSpace | undefined,\n): Promise<\n | {\n readonly colorSpace: ImageColorSpace;\n readonly profile: BasisProfile;\n readonly width: number;\n readonly height: number;\n readonly levelCount: number;\n }\n | ImportError\n> {\n const parsed = await parseKtx2(bytes);\n if (!parsed.ok) {\n return imageConversionFailure(\n ctx,\n 'inspect',\n 'ktx2-parse',\n ctx.source,\n 'a valid KTX2 container with a supported Basis profile',\n `codec:${parsed.error.code}`,\n 'repair the KTX2 container and retry the image import',\n );\n }\n const dfdColorSpace = ktx2ColorSpace(parsed.value);\n if (dfdColorSpace === undefined) {\n return imageConversionFailure(\n ctx,\n 'inspect',\n 'ktx2-color-space-missing',\n `${ctx.source}#DFD.transferFunction`,\n 'DFD transfer function to identify sRGB or linear color space',\n 'missing-or-unsupported-transfer-function',\n 'repair the KTX2 DFD color-space declaration before importing',\n );\n }\n if (metaColorSpace !== undefined && metaColorSpace !== dfdColorSpace) {\n return imageConversionFailure(\n ctx,\n 'inspect',\n 'ktx2-color-space-conflict',\n `${ctx.source}#importSettings.colorSpace`,\n 'Meta.colorSpace to match the KTX2 DFD transfer function',\n `meta=${metaColorSpace},dfd=${dfdColorSpace}`,\n 'repair Meta.colorSpace or re-encode the KTX2 source with matching color provenance',\n );\n }\n const { pixelDepth, layerCount, faceCount } = parsed.value.header;\n if (pixelDepth !== 0 || layerCount > 1 || faceCount !== 1) {\n return imageConversionFailure(\n ctx,\n 'inspect',\n 'ktx2-shape-unsupported',\n `${ctx.source}#header`,\n 'a 2D, single-layer, single-face KTX2 texture',\n `pixelDepth=${pixelDepth},layerCount=${layerCount},faceCount=${faceCount}`,\n 're-encode the source as one 2D Basis texture',\n );\n }\n const { initBasisTranscoder } = await import('@forgeax/engine-codec');\n const module = await initBasisTranscoder();\n let file: InstanceType<typeof module.KTX2File>;\n try {\n file = new module.KTX2File(bytes);\n } catch {\n return imageConversionFailure(\n ctx,\n 'inspect',\n 'ktx2-invalid',\n ctx.source,\n 'Basis KTX2File bytes to pass transcoder validation',\n 'basis-file-constructor-failed',\n 'repair or re-encode the KTX2 source before importing',\n );\n }\n try {\n try {\n if (!file.isValid()) {\n return imageConversionFailure(\n ctx,\n 'inspect',\n 'ktx2-invalid',\n ctx.source,\n 'Basis KTX2File bytes to pass transcoder validation',\n 'basis-file-invalid',\n 'repair or re-encode the KTX2 source before importing',\n );\n }\n const profile: BasisProfile | undefined = file.isETC1S()\n ? 'etc1s'\n : file.isHDR() || file.isHDR4x4()\n ? 'uastc-hdr'\n : file.isUASTC_LDR_4x4()\n ? 'uastc-ldr'\n : undefined;\n if (profile === undefined) {\n return imageConversionFailure(\n ctx,\n 'inspect',\n 'ktx2-profile-unsupported',\n `${ctx.source}#Basis.profile`,\n 'ETC1S, UASTC-LDR, or UASTC-HDR Basis profile',\n 'unsupported-basis-profile',\n 're-encode the source with ETC1S, UASTC-LDR, or UASTC-HDR',\n );\n }\n if (profile === 'uastc-hdr' && dfdColorSpace !== 'linear') {\n return imageConversionFailure(\n ctx,\n 'inspect',\n 'ktx2-hdr-color-space-invalid',\n `${ctx.source}#DFD.transferFunction`,\n 'UASTC-HDR source to use linear color space',\n `profile=${profile},dfd=${dfdColorSpace}`,\n 're-encode HDR data with a linear KTX2 DFD transfer function',\n );\n }\n return {\n colorSpace: dfdColorSpace,\n profile,\n width: file.getWidth(),\n height: file.getHeight(),\n levelCount: file.getLevels(),\n };\n } catch {\n return imageConversionFailure(\n ctx,\n 'inspect',\n 'ktx2-invalid',\n ctx.source,\n 'Basis KTX2File bytes to pass transcoder inspection',\n 'basis-inspection-threw',\n 'repair or re-encode the KTX2 source before importing',\n );\n }\n } finally {\n file.close();\n }\n}\n\nasync function importKtx2Source(ctx: ImportContext, bytes: Uint8Array): Promise<ImportResult> {\n const sourceKey = ctx.subAssets[0]?.sourceKey;\n const metaColorSpace =\n sourceKey === undefined\n ? ctx.importSettings.colorSpace\n : ctx.sourceOverrides?.[sourceKey]?.colorSpace;\n const inspection = await inspectKtx2Source(\n ctx,\n bytes,\n metaColorSpace === 'srgb' || metaColorSpace === 'linear' ? metaColorSpace : undefined,\n );\n if (inspection instanceof ImportError) return { ok: false, error: inspection };\n const out: ImportedAsset[] = [];\n for (const sub of ctx.subAssets) {\n if (sub.kind !== 'texture' || sub.sourceIndex !== 0) continue;\n out.push({\n guid: sub.guid,\n kind: 'texture',\n payload: {\n kind: 'texture',\n width: inspection.width,\n height: inspection.height,\n format: colorSpaceToFormat(inspection.colorSpace),\n data: bytes,\n colorSpace: inspection.colorSpace,\n mipmap: inspection.levelCount > 1,\n mipLevelCount: inspection.levelCount,\n },\n refs: [],\n artifacts: {\n body: {\n mediaType: 'image/ktx2',\n assetCodec: {\n name: 'basis',\n container: 'ktx2',\n profile: inspection.profile,\n version: '1',\n },\n bytes,\n },\n },\n });\n }\n return { ok: true, value: { assets: out, sourceDependencies: [] } };\n}\n\nfunction basisMetaColorSpace(ctx: ImportContext): ImageColorSpace | ImportError {\n const sourceKey = ctx.subAssets[0]?.sourceKey;\n const override = sourceKey === undefined ? undefined : ctx.sourceOverrides?.[sourceKey];\n const value = override?.colorSpace ?? ctx.importSettings.colorSpace;\n if (value !== 'srgb' && value !== 'linear') {\n return imageConversionFailure(\n ctx,\n 'inspect',\n 'basis-color-space-invalid',\n `${ctx.source}#Meta.colorSpace`,\n 'Meta.colorSpace to be srgb or linear for raw Basis',\n value === undefined ? 'missing' : `invalid:${String(value)}`,\n 'set Meta.colorSpace to srgb or linear before importing raw Basis bytes',\n );\n }\n return value;\n}\n\nasync function importBasisSource(ctx: ImportContext, bytes: Uint8Array): Promise<ImportResult> {\n const colorSpace = basisMetaColorSpace(ctx);\n if (colorSpace instanceof ImportError) return { ok: false, error: colorSpace };\n const { initBasisTranscoder, inspectBasisSource } = await import('@forgeax/engine-codec');\n const module = await initBasisTranscoder();\n if (module.BasisFile === undefined) {\n throw new Error('basis-source-inspection-unavailable: transcoder lacks BasisFile');\n }\n let file: InstanceType<typeof module.BasisFile>;\n try {\n file = new module.BasisFile(bytes);\n } catch {\n return {\n ok: false,\n error: imageConversionFailure(\n ctx,\n 'inspect',\n 'basis-source-invalid',\n ctx.source,\n 'raw Basis bytes to pass transcoder validation',\n 'basis-file-invalid',\n 'repair or re-encode the raw Basis source before importing',\n ),\n };\n }\n let inspection: BasisSourceInspection | undefined;\n try {\n try {\n const format = file.getBasisTexFormat();\n const profile =\n format === module.basis_tex_format.cETC1S.value\n ? 'etc1s'\n : format === module.basis_tex_format.cUASTC_LDR_4x4.value\n ? 'uastc-ldr'\n : undefined;\n if (profile === undefined) {\n return {\n ok: false,\n error: imageConversionFailure(\n ctx,\n 'inspect',\n 'basis-profile-unsupported',\n `${ctx.source}#Basis.profile`,\n 'ETC1S or UASTC-LDR raw Basis profile',\n 'unsupported-basis-profile',\n 're-encode the source with ETC1S or UASTC-LDR',\n ),\n };\n }\n const result = inspectBasisSource(file, { colorSpace }, profile);\n if (!result.ok) {\n return {\n ok: false,\n error: imageConversionFailure(\n ctx,\n 'inspect',\n 'basis-inspection-failed',\n ctx.source,\n 'raw Basis source metadata to pass codec inspection',\n `codec:${result.error.code}`,\n 'repair the raw Basis source metadata and retry the import',\n ),\n };\n }\n inspection = result.value;\n } catch {\n return {\n ok: false,\n error: imageConversionFailure(\n ctx,\n 'inspect',\n 'basis-source-invalid',\n ctx.source,\n 'raw Basis bytes to pass transcoder inspection',\n 'basis-inspection-threw',\n 'repair or re-encode the raw Basis source before importing',\n ),\n };\n }\n } finally {\n file.close();\n }\n if (inspection === undefined) {\n return {\n ok: false,\n error: imageConversionFailure(\n ctx,\n 'inspect',\n 'basis-inspection-failed',\n ctx.source,\n 'raw Basis source metadata to be available after codec inspection',\n 'missing-inspection-result',\n 'repair the raw Basis source and retry the import',\n ),\n };\n }\n const out: ImportedAsset[] = [];\n for (const sub of ctx.subAssets) {\n if (sub.kind !== 'texture') continue;\n if (sub.sourceIndex !== 0 || inspection.imageCount !== 1) {\n return {\n ok: false,\n error: imageConversionFailure(\n ctx,\n 'inspect',\n 'basis-image-shape-unsupported',\n `${ctx.source}#Basis.images`,\n 'one raw Basis image at sourceIndex 0',\n `imageCount=${inspection.imageCount},sourceIndex=${sub.sourceIndex}`,\n 're-encode the source as one raw Basis image',\n ),\n };\n }\n out.push({\n guid: sub.guid,\n kind: 'texture',\n payload: {\n kind: 'texture',\n width: inspection.width,\n height: inspection.height,\n format: colorSpaceToFormat(colorSpace),\n data: bytes,\n colorSpace,\n mipmap: inspection.levelCount > 1,\n mipLevelCount: inspection.levelCount,\n },\n refs: [],\n artifacts: {\n body: {\n mediaType: 'application/x-forgeax-basis',\n assetCodec: {\n name: 'basis',\n container: 'basis',\n profile: inspection.profile,\n version: '1',\n },\n bytes,\n },\n },\n });\n }\n return { ok: true, value: { assets: out, sourceDependencies: [] } };\n}\n\n/**\n * Read the sidecar compressionMode token (D-12 / M3 w18).\n *\n * M3 SEQUENCING CONSTRAINT (plan R-9): the default is hard-wired to `'none'`.\n * An absent / unrecognised token stays `'none'` so existing textures keep the\n * uncompressed `.bin` path -- flipping the default to `'auto'` is M5 (w38).\n */\nfunction compressionModeToken(token: unknown): CompressionMode {\n if (token === 'auto' || token === 'etc1s' || token === 'uastc' || token === 'none') {\n return token;\n }\n return 'none';\n}\n\n/**\n * Basis encode arm (D-5 / M3 w18; HDR arm feat-20260707): when the sidecar\n * requests a compressed delivery (mode resolves to non-'none'), encode the\n * decoded pixels into a Basis KTX2 and return those bytes; the catalog\n * `compression` discriminant is set by the vite-plugin-pack wiring (w20).\n * Returns `null` for the 'none' path so the caller keeps the uncompressed\n * `.bin` bytes unchanged (rgba8 for LDR, rgba16float for HDR).\n *\n * `pixels` is tight-packed RGBA: 8-bit RGBA for LDR (`isHdr: false`),\n * rgba16float bytes for HDR (`isHdr: true`). The `isHdr` signal drives both the\n * 'auto' derivation (-> 'uastc-hdr') and the encoder's HDR source path.\n */\nasync function maybeEncodeTextureBytes(\n ctx: ImportContext,\n pixels: Uint8Array,\n width: number,\n height: number,\n compressionMode: CompressionMode,\n colorSpace: ImageColorSpace,\n isHdr: boolean,\n): Promise<\n | { readonly ok: true; readonly value: Uint8Array | null }\n | { readonly ok: false; readonly error: ImportError }\n> {\n if (resolveEncodeMode(compressionMode, { colorSpace, isHdr }) === 'none') {\n return { ok: true, value: null };\n }\n const result = await encodeTextureToKtx2(pixels, width, height, compressionMode, {\n colorSpace,\n isHdr,\n });\n if (!result.ok) {\n return {\n ok: false,\n error: imageConversionFailure(\n ctx,\n 'encode',\n result.error.code === 'ktx2-encode-source-too-large'\n ? 'ktx2-source-too-large'\n : 'ktx2-encode-refused',\n `${ctx.source}#compressionMode`,\n 'the requested compression mode to accept the decoded image',\n `codec:${result.error.code},mode:${result.error.mode}`,\n result.error.code === 'ktx2-encode-source-too-large'\n ? 'reduce source dimensions or set compressionMode to none'\n : 'repair the source image or compression settings and retry the import',\n ),\n };\n }\n return { ok: true, value: result.value.ktx2 };\n}\n\nasync function importImage(ctx: ImportContext): Promise<ImportResult> {\n const requiredKind = requiredImageOutputKind(ctx.source);\n if (requiredKind !== undefined) {\n const topologyError = validateImageOutputTopology(ctx, requiredKind);\n if (topologyError !== undefined) return { ok: false, error: topologyError };\n }\n\n const read = await ctx.readSource();\n if (!read.ok) {\n return {\n ok: false,\n error: new ImportError({\n code: 'source-read-failed',\n expected: `readable source file at \"${ctx.source}\"`,\n hint: IMPORT_ERROR_HINTS['source-read-failed'],\n detail: {\n source: ctx.source,\n reason: read.error instanceof Error ? read.error.message : String(read.error),\n },\n }),\n };\n }\n const mime = mimeFromSource(ctx.source);\n\n if (ctx.source.toLowerCase().endsWith('.basis')) {\n return importBasisSource(ctx, read.value);\n }\n if (ctx.source.toLowerCase().endsWith('.ktx2')) {\n return importKtx2Source(ctx, read.value);\n }\n\n // --- HDR arm (D-6): .hdr equirect source is decoded via decodeHdr -> f16 ---\n if (mime === undefined && ctx.source.toLowerCase().endsWith('.hdr')) {\n const { decodeHdr } = await import('./hdr-decoder.js');\n const decoded = decodeHdr(read.value);\n if (!decoded.ok) {\n return {\n ok: false,\n error: imageConversionFailure(\n ctx,\n 'decode',\n 'hdr',\n ctx.source,\n 'valid Radiance RGBE bytes to decode into an equirect asset',\n `image:${decoded.error.code}`,\n 'repair the HDR header or pixel payload and retry the import',\n ),\n };\n }\n const dec = decoded.value;\n const { halfFloat } = await import('@forgeax/engine-math');\n const f16Bytes = halfFloat.f32ToF16Bytes(\n new Uint8Array(dec.data.buffer, dec.data.byteOffset, dec.data.byteLength),\n );\n\n // NO block-compression for equirect (feat-20260707 M5 fix). The .hdr arm\n // folds only `kind:'equirect'` sub-assets, and an equirect is ALWAYS an IBL /\n // skybox source: the runtime drives it through equirect-to-cube / irradiance /\n // prefilter / brdf-lut RENDER passes (Skylight.equirect / SkyboxBackground.\n // equirect). A BC6H (block-compressed) texture is sample-only, never a color-\n // renderable render target, so a BC6H equirect breaks cube projection with a\n // \"BC6HRGBUfloat is not color renderable\" WebGPU error. The equirect must stay\n // uncompressed rgba16float; the catalog `compression` discriminant is forced to\n // 'none' in import-texture.ts (compressionFor), so the two agree. A purely-\n // sampled HDR 2D texture (never folded by this arm) may still take the\n // UASTC-HDR path via the standard image arm below.\n const out: ImportedAsset[] = [];\n for (const sub of ctx.subAssets) {\n // The .hdr arm folds equirect sub-assets only: a single 2D rgba16float\n // image (the lat-long env map) with a disk identity. The cube-to-cube IBL\n // projection is a GPU-side pass driven by the runtime record arm, not a\n // build-time fold (feat-20260630 w5; orchestrator adjudication: equirect\n // produces a build .bin, unlike the retired cube-texture).\n if (sub.kind !== 'equirect') continue;\n const payload: EquirectAsset = {\n kind: 'equirect',\n width: dec.width,\n height: dec.height,\n format: 'rgba16float',\n data: f16Bytes,\n colorSpace: 'linear',\n };\n out.push({\n guid: sub.guid,\n kind: 'equirect',\n payload,\n refs: [],\n artifacts: {\n body: {\n mediaType: 'application/x-forgeax-rgba16f',\n assetCodec: { name: 'rgba16float' },\n bytes: f16Bytes,\n },\n },\n });\n }\n return { ok: true, value: { assets: out, sourceDependencies: [] } };\n }\n\n // --- Standard PNG/JPEG path ---\n if (mime === undefined) {\n throw new Error(\n `imageImporter: unsupported source extension for \"${ctx.source}\" (expected .png / .jpg / .jpeg / .hdr / .ktx2 / .basis)`,\n );\n }\n\n const colorSpace: ImageColorSpace = ctx.importSettings.colorSpace === 'srgb' ? 'srgb' : 'linear';\n const mipmap = mipmapTokenToBoolean(ctx.importSettings.mipmap);\n const compressionMode = compressionModeToken(ctx.importSettings.compressionMode);\n const downscaleMaxDimension =\n typeof ctx.importSettings.downscaleMaxDimension === 'number' &&\n Number.isInteger(ctx.importSettings.downscaleMaxDimension) &&\n ctx.importSettings.downscaleMaxDimension > 0\n ? ctx.importSettings.downscaleMaxDimension\n : undefined;\n\n const decoded = parseImage(read.value, mime, {\n colorSpace,\n mipmap,\n ...(downscaleMaxDimension !== undefined ? { downscaleMaxDimension } : {}),\n });\n if (!decoded.ok) {\n return {\n ok: false,\n error: imageConversionFailure(\n ctx,\n 'decode',\n 'ldr',\n ctx.source,\n 'valid PNG or JPEG bytes to decode into RGBA pixels',\n `image:${decoded.error.code}`,\n 'repair the source image bytes and retry the import',\n ),\n };\n }\n const dec = decoded.value;\n\n // Basis encode arm (M3 w18): null keeps the uncompressed rgba8 `.bin` path.\n const encoded = await maybeEncodeTextureBytes(\n ctx,\n dec.bytes,\n dec.width,\n dec.height,\n compressionMode,\n colorSpace,\n false,\n );\n if (!encoded.ok) return encoded;\n const encodedBytes = encoded.value;\n\n const out: ImportedAsset[] = [];\n for (const sub of ctx.subAssets) {\n // Only flat 2D image sub-assets are folded here; cube-texture sub-assets\n // ride the runtime IBL multi-face cook and are intentionally not produced.\n if (sub.kind !== 'texture') continue;\n const payload: TextureAsset = {\n kind: 'texture',\n width: dec.width,\n height: dec.height,\n format: colorSpaceToFormat(colorSpace),\n data: encodedBytes ?? dec.bytes,\n colorSpace,\n mipmap,\n };\n out.push({\n guid: sub.guid,\n kind: 'texture',\n payload,\n refs: [],\n artifacts: {\n body: {\n mediaType: encodedBytes === null ? 'application/x-forgeax-rgba8' : 'image/ktx2',\n assetCodec:\n encodedBytes === null\n ? { name: 'rgba8', version: '1' }\n : {\n name: 'basis',\n container: 'ktx2',\n profile: resolveEncodeMode(compressionMode, { colorSpace, isHdr: false }),\n },\n bytes: encodedBytes ?? dec.bytes,\n },\n },\n });\n }\n return { ok: true, value: { assets: out, sourceDependencies: [] } };\n}\n\n/** Bind the image producer to the generic importer runner's decode seam. */\nexport const decodeImageForImport: ImportContext['decodeImage'] = async (\n bytes,\n mimeType,\n importSettings,\n) => {\n const colorSpace =\n importSettings.colorSpace === 'srgb' || importSettings.colorSpace === 'linear'\n ? importSettings.colorSpace\n : 'linear';\n const mipmap = importSettings.mipmap === true;\n const downscaleMaxDimension =\n typeof importSettings.downscaleMaxDimension === 'number' &&\n Number.isInteger(importSettings.downscaleMaxDimension) &&\n importSettings.downscaleMaxDimension > 0\n ? importSettings.downscaleMaxDimension\n : undefined;\n const decoded = parseImage(bytes, mimeType, {\n colorSpace,\n mipmap,\n ...(downscaleMaxDimension === undefined ? {} : { downscaleMaxDimension }),\n });\n if (!decoded.ok) return decoded;\n const tex = decoded.value;\n const requestedCompression =\n importSettings.compressionMode === 'auto' ||\n importSettings.compressionMode === 'etc1s' ||\n importSettings.compressionMode === 'uastc' ||\n importSettings.compressionMode === 'none'\n ? importSettings.compressionMode\n : 'none';\n const resolvedCompression = resolveEncodeMode(requestedCompression, {\n colorSpace,\n isHdr: false,\n });\n let cookedBytes = tex.bytes;\n let mediaType: string = mimeType;\n let assetCodec: { name: string; profile?: string; version?: string } = {\n name: 'rgba8',\n version: '1',\n };\n if (resolvedCompression !== 'none') {\n const encoded = await encodeTextureToKtx2(\n tex.bytes,\n tex.width,\n tex.height,\n requestedCompression,\n { colorSpace, isHdr: false },\n );\n if (!encoded.ok) {\n throw new Error(\n `embedded texture compression failed (${encoded.error.code} / ${encoded.error.mode}): ${encoded.error.reason}`,\n );\n }\n cookedBytes = encoded.value.ktx2;\n mediaType = 'image/ktx2';\n assetCodec = { name: 'basis', profile: encoded.value.mode };\n }\n return {\n ok: true as const,\n value: {\n texture: {\n kind: 'texture' as const,\n data: cookedBytes,\n width: tex.width,\n height: tex.height,\n format: colorSpaceToFormat(colorSpace),\n colorSpace,\n mipmap,\n },\n bytes: cookedBytes,\n mediaType,\n assetCodec,\n },\n };\n};\n\n/**\n * The image {@link Importer}. Register it into an `ImporterRegistry` so the\n * import runner dispatches `meta.importer === 'image'` sidecars here and can\n * offer the same producer's decoder to importers with embedded images.\n *\n * @example\n * ```ts\n * import { ImporterRegistry } from '@forgeax/engine-import';\n * import { imageImporter } from '@forgeax/engine-image/image-importer';\n * const importers = new ImporterRegistry();\n * importers.register(imageImporter);\n * ```\n */\nexport const imageImporter: Importer = {\n key: 'image',\n import: importImage,\n capabilities: { decodeImage: decodeImageForImport },\n};\n"]}
1
+ {"version":3,"sources":["../src/errors.ts","../src/result.ts","../src/hdr-decoder.ts","../src/ktx2-encode.ts","../src/parse-image.ts","../src/resize-image.ts","../src/texture/source-descriptor.ts","../src/texture/importer.ts","../src/image-importer.ts"],"names":["err","ok","ImportError","decodeHdr","decoded","dec","out"],"mappings":";;;;;;;;;;;;;;;AAuDO,SAAS,WACd,MAAA,EACkB;AAClB,EAAA,OAAO,IAAI,eAAkB,MAAM,CAAA;AACrC;AA3DA,IAOM,oBAAA,EAyBO,cAAA;AAhCb,IAAA,WAAA,GAAA,KAAA,CAAA;AAAA,EAAA,eAAA,GAAA;AAOA,IAAM,oBAAA,GAAiE;AAAA,MACrE,qBAAA,EAAuB,4CAAA;AAAA,MACvB,0BAAA,EACE,+FAAA;AAAA,MACF,+BAAA,EACE,mFAAA;AAAA,MACF,oBAAA,EACE,6EAAA;AAAA,MACF,yBAAA,EAA2B,mEAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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M,IAAI,CAAA,GAAA,EAAM,OAAA,CAAQ,KAAA,CAAM,MAAM,CAAA;AAAA,OAC9G;AAAA,IACF;AACA,IAAA,WAAA,GAAc,QAAQ,KAAA,CAAM,IAAA;AAC5B,IAAA,SAAA,GAAY,YAAA;AACZ,IAAA,UAAA,GAAa,EAAE,IAAA,EAAM,OAAA,EAAS,OAAA,EAAS,OAAA,CAAQ,MAAM,IAAA,EAAK;AAAA,EAC5D;AACA,EAAA,OAAO;AAAA,IACL,EAAA,EAAI,IAAA;AAAA,IACJ,KAAA,EAAO;AAAA,MACL,OAAA,EAAS;AAAA,QACP,IAAA,EAAM,SAAA;AAAA,QACN,IAAA,EAAM,WAAA;AAAA,QACN,KAAA,EAAO,EAAE,aAAA,EAAe,IAAA,EAAM,MAAA,EAAQ,EAAE,KAAA,EAAO,GAAA,CAAI,KAAA,EAAO,MAAA,EAAQ,GAAA,CAAI,MAAA,EAAO,EAAE;AAAA,QAC/E,MAAA,EAAQ,mBAAmB,UAAU,CAAA;AAAA,QACrC,UAAA;AAAA,QACA,IAAA,EAAM,SAAS,EAAE,IAAA,EAAM,YAAoB,GAAI,EAAE,MAAM,MAAA;AAAgB,OACzE;AAAA,MACA,KAAA,EAAO,WAAA;AAAA,MACP,SAAA;AAAA,MACA;AAAA;AACF,GACF;AACF;AAeO,IAAM,aAAA,GAA0B;AAAA,EACrC,GAAA,EAAK,OAAA;AAAA,EACL,MAAA,EAAQ,WAAA;AAAA,EACR,YAAA,EAAc,EAAE,WAAA,EAAa,oBAAA;AAC/B","file":"image-importer.mjs","sourcesContent":["import type { ImageErrorCode, ImageErrorDetailFor, ImageErrorFor } from '@forgeax/engine-types';\nimport { IMAGE_ERROR_HINTS } from '@forgeax/engine-types';\n\n// Per-code .expected string literals SSOT.\n// Mirrors ASSET_ERROR_HINTS / IMAGE_ERROR_HINTS shape (charter P5 consistent\n// abstraction). AI users surface .expected when a structured error needs to\n// describe the precondition that was violated.\nconst IMAGE_ERROR_EXPECTED: Readonly<Record<ImageErrorCode, string>> = {\n 'image-decode-failed': 'PNG / JPG byte stream decodes successfully',\n 'image-format-unsupported':\n \"mime is one of ['image/png', 'image/jpeg']; uploadTexture format <-> colorSpace family agrees\",\n 'image-dimension-out-of-bounds':\n 'width and height fall under device caps maxTextureDimension2D (or 16384 hard cap)',\n 'image-meta-missing':\n \"<source>.meta.json sidecar (importer: 'image') exists in the same directory\",\n 'image-hdr-decode-failed': 'Radiance RGBE header is valid and pixel data decodes successfully',\n // feat-20260521-sprite-atlas-animation M1 T-03 — vite-plugin-image atlas\n // hook .expected literals (plan-strategy section 2 D-2 + AC-10 a/b/c).\n // ImageErrorImpl construction path is unchanged: the new atlas-* errors\n // flow through `new ImageErrorImpl({ code: 'atlas-...', ...detail })` and\n // pick the .expected string up from this Record at construction time\n // (charter P3 explicit failure SSOT — AI users surface .expected next to\n // .hint after switch (err.code) without parsing the message).\n 'atlas-empty-input': 'images.length >= 1',\n 'atlas-size-exceeded':\n 'image width x height <= maxAtlasSize^2 and each image fits in the atlas footprint',\n 'atlas-region-mismatch': 'sum(regions[i].w x regions[i].h) <= atlasWidth x atlasHeight',\n 'image-surface-invalid':\n 'PixelSurface dimensions and authoring inputs satisfy the RGBA8 contract',\n};\n\n/** Runtime implementation of the correlated `ImageErrorFor<C>` envelope. */\nexport class ImageErrorImpl<C extends ImageErrorCode = ImageErrorCode>\n extends Error\n implements ImageErrorFor<C>\n{\n readonly code: C;\n readonly expected: string;\n readonly hint: string;\n readonly detail: ImageErrorDetailFor<C>;\n\n constructor(detail: ImageErrorDetailFor<C>) {\n const code = detail.code;\n const expected = IMAGE_ERROR_EXPECTED[code];\n const hint = IMAGE_ERROR_HINTS[code];\n super(`[ImageError ${code}] expected: ${expected}; hint: ${hint}`);\n this.name = 'ImageError';\n this.code = code;\n this.expected = expected;\n this.hint = hint;\n this.detail = detail;\n }\n}\n\n/** Construct a structured image error while preserving its code/detail pair. */\nexport function imageError<C extends ImageErrorCode>(\n detail: ImageErrorDetailFor<C>,\n): ImageErrorFor<C> {\n return new ImageErrorImpl<C>(detail);\n}\n\nexport { IMAGE_ERROR_EXPECTED };\n","// Result<T, E> + ok / err live in `@forgeax/engine-types` (tweak-20260612-result-\n// into-types). They were duplicated here as a lite (plain-object, no `unwrap`)\n// variant; consolidated upstream into the same shape used by rhi / ecs / naga.\n// The barrel here re-exports them so existing\n// `import { err, ok, Result, ResultOk, ResultErr } from '@forgeax/engine-image'`\n// consumers (and intra-package `./result.js` imports) stay unchanged.\nexport {\n err,\n ok,\n type Result,\n type ResultErr,\n type ResultOk,\n} from '@forgeax/engine-types';\n","import type { ImageError } from '@forgeax/engine-types';\nimport { imageError } from './errors.js';\nimport type { Result } from './result.js';\nimport { err, ok } from './result.js';\n\n/**\n * Decoded HDR image POD.\n *\n * `data` is an interleaved RGBA Float32Array (4 floats per pixel, row-major).\n * Color space is always linear (RGBE is radiance).\n */\nexport interface HdrDecoded {\n readonly width: number;\n readonly height: number;\n readonly data: Float32Array;\n}\n\n// ASCII code points\nconst LF = 0x0a;\n\n/**\n * Decode a Radiance RGBE (.hdr) byte stream into linear RGBA float pixels.\n *\n * Steps per research F-6:\n * 1. Parse ASCII header: magic (#?RADIANCE), FORMAT=32-bit_rle_rgbe,\n * resolution line (-Y height +X width).\n * 2. Decode per-scanline new-RLE pixel data: 4 independent channel runs.\n * 3. Convert RGBE to float: if E==0 -> 0; else f=2^(E-136), R=(Rm+0.5)*f.\n * 4. Output as interleaved RGBA Float32Array (alpha=1.0).\n *\n * Old-RLE scanlines (prefix not matching 0x02,0x02,hi,lo with correct width)\n * return image-hdr-decode-failed.\n */\nexport function decodeHdr(bytes: Uint8Array): Result<HdrDecoded, ImageError> {\n let pos = 0;\n\n // Step 1a: magic -- must start with \"#?RADIANCE\" or \"#?RGBE\"\n if (bytes.length < 11) {\n return err(hdrDecodeError('file too short for Radiance HDR header'));\n }\n const magic = String.fromCharCode(...bytes.subarray(0, 11));\n if (magic !== '#?RADIANCE\\n' && magic !== '#?RGBE\\n') {\n return err(\n hdrDecodeError('missing or invalid Radiance HDR magic; expected #?RADIANCE or #?RGBE'),\n );\n }\n pos = 11;\n\n // Step 1b: key=value lines until empty line\n let formatFound = false;\n while (pos < bytes.length) {\n const lineEnd = findByte(bytes, LF, pos);\n if (lineEnd === -1) return err(hdrDecodeError('header truncated before empty line'));\n const line = asciiSubstring(bytes, pos, lineEnd);\n pos = lineEnd + 1;\n if (line === '') break;\n if (line.startsWith('FORMAT=')) {\n const val = line.slice(7);\n if (val === '32-bit_rle_rgbe') {\n formatFound = true;\n }\n }\n }\n if (!formatFound) {\n return err(hdrDecodeError('missing or unsupported FORMAT; expected FORMAT=32-bit_rle_rgbe'));\n }\n\n // Step 1c: resolution line (-Y height +X width)\n if (pos >= bytes.length) return err(hdrDecodeError('missing resolution line'));\n const resLineEnd = findByte(bytes, LF, pos);\n if (resLineEnd === -1) return err(hdrDecodeError('resolution line truncated'));\n const resLine = asciiSubstring(bytes, pos, resLineEnd);\n pos = resLineEnd + 1;\n const resMatch = /^-Y\\s+(\\d+)\\s+\\+X\\s+(\\d+)\\s*$/.exec(resLine);\n if (resMatch === null) {\n return err(\n hdrDecodeError(`unexpected resolution line format: \"${resLine}\"; expected \"-Y H +X W\"`),\n );\n }\n const height = Number(resMatch[1]);\n const width = Number(resMatch[2]);\n if (height === undefined || width === undefined || height <= 0 || width <= 0) {\n return err(hdrDecodeError(`invalid dimensions: ${width}x${height}`));\n }\n\n // Step 2: decode per-scanline new-RLE pixel data\n const pixelCount = width * height;\n const rgbe = new Uint8Array(pixelCount * 4);\n const scanlineBytes = width * 4;\n\n for (let y = 0; y < height; y++) {\n if (pos + 4 > bytes.length) {\n return err(hdrDecodeError(`truncated at scanline ${y}: expected 4-byte prefix`));\n }\n const p0 = bytes[pos];\n const p1 = bytes[pos + 1];\n const pHi = bytes[pos + 2];\n const pLo = bytes[pos + 3];\n if (p0 === undefined || p1 === undefined || pHi === undefined || pLo === undefined) {\n return err(hdrDecodeError(`truncated at scanline ${y}`));\n }\n // biome-ignore lint/style/noNonNullAssertion: checked above\n const prefixWidth = (pHi! << 8) | pLo!;\n\n if (p0 === 0x02 && p1 === 0x02 && prefixWidth === width && width >= 8 && width <= 32767) {\n // New-RLE: 4 channels independently RLE-encoded, then interleaved\n const decoded = decodeNewRleScanline(bytes, pos + 4, width);\n if (decoded === null) {\n return err(hdrDecodeError(`RLE decode failed at scanline ${y}`));\n }\n // Copy into rgbe interleaved buffer\n const base = y * scanlineBytes;\n const channels = [decoded[0], decoded[1], decoded[2], decoded[3]];\n for (let x = 0; x < width; x++) {\n for (let ch = 0; ch < 4; ch++) {\n // biome-ignore lint/style/noNonNullAssertion: checked at allocation\n rgbe[base + x * 4 + ch] = channels[ch]![x]!;\n }\n }\n // Advance pos past the 4-byte prefix + the total RLE bytes consumed\n pos += 4 + decoded.totalBytes;\n } else {\n // Old-RLE: not supported\n return err(\n hdrDecodeError(\n 'old-RLE format is not supported; only new-RLE (32-bit_rle_rgbe) is accepted',\n ),\n );\n }\n }\n\n // Step 3: RGBE to float\n const out = new Float32Array(pixelCount * 4);\n for (let i = 0; i < pixelCount; i++) {\n const base = i * 4;\n // biome-ignore lint/style/noNonNullAssertion: checked at allocation\n const r = rgbe[base]!;\n // biome-ignore lint/style/noNonNullAssertion: checked at allocation\n const g = rgbe[base + 1]!;\n // biome-ignore lint/style/noNonNullAssertion: checked at allocation\n const b = rgbe[base + 2]!;\n // biome-ignore lint/style/noNonNullAssertion: checked at allocation\n const e = rgbe[base + 3]!;\n out[base + 3] = 1.0;\n\n if (e === 0) {\n out[base] = 0;\n out[base + 1] = 0;\n out[base + 2] = 0;\n } else {\n // f = 2^(E - 136) = ldexp(1.0, E - 128 - 8)\n // Equivalent: ldexp(1.0 / 256.0, E - 128)\n // But simpler: const f = (1.0 / 256.0) * Math.pow(2, e - 128);\n // Using ldexp: Math.pow(2, e - 136)\n const f = 2 ** (e - 136);\n out[base] = (r + 0.5) * f;\n out[base + 1] = (g + 0.5) * f;\n out[base + 2] = (b + 0.5) * f;\n }\n }\n\n return ok({ width, height, data: out });\n}\n\ninterface DecodedScanline {\n /** 4 channels, each width bytes */\n readonly 0: Uint8Array;\n readonly 1: Uint8Array;\n readonly 2: Uint8Array;\n readonly 3: Uint8Array;\n readonly totalBytes: number;\n}\n\n/**\n * Decode one scanline of new-RLE data into 4 channel arrays.\n * Returns null on failure (data underrun).\n */\nfunction decodeNewRleScanline(\n bytes: Uint8Array,\n start: number,\n width: number,\n): DecodedScanline | null {\n const channels: Uint8Array[] = [];\n let cursor = start;\n\n for (let ch = 0; ch < 4; ch++) {\n const data = new Uint8Array(width);\n let x = 0;\n while (x < width) {\n if (cursor >= bytes.length) return null;\n // biome-ignore lint/style/noNonNullAssertion: checked above\n const code = bytes[cursor]!;\n cursor++;\n if (code > 128) {\n // RLE run: next byte repeated (code - 128) times\n const count = code - 128;\n if (cursor >= bytes.length || x + count > width) return null;\n // biome-ignore lint/style/noNonNullAssertion: checked above\n const val = bytes[cursor]!;\n cursor++;\n data.fill(val, x, x + count);\n x += count;\n } else {\n // Literal run: next `code` bytes copied verbatim\n if (code === 0) continue;\n if (cursor + code > bytes.length || x + code > width) return null;\n for (let k = 0; k < code; k++) {\n // biome-ignore lint/style/noNonNullAssertion: checked above\n data[x + k] = bytes[cursor + k]!;\n }\n cursor += code;\n x += code;\n }\n }\n channels.push(data);\n }\n\n const ch0 = channels[0];\n const ch1 = channels[1];\n const ch2 = channels[2];\n const ch3 = channels[3];\n if (ch0 === undefined || ch1 === undefined || ch2 === undefined || ch3 === undefined) {\n return null; // channels should always have 4 entries\n }\n return {\n 0: ch0,\n 1: ch1,\n 2: ch2,\n 3: ch3,\n totalBytes: cursor - start,\n };\n}\n\nfunction findByte(bytes: Uint8Array, target: number, start: number): number {\n for (let i = start; i < bytes.length; i++) {\n if (bytes[i] === target) return i;\n }\n return -1;\n}\n\nfunction asciiSubstring(bytes: Uint8Array, start: number, end: number): string {\n let s = '';\n for (let i = start; i < end; i++) {\n // biome-ignore lint/style/noNonNullAssertion: in bounds\n s += String.fromCharCode(bytes[i]!);\n }\n return s;\n}\n\nfunction hdrDecodeError(reason: string): ImageError {\n return imageError({\n code: 'image-hdr-decode-failed',\n reason,\n });\n}\n","// ktx2-encode.ts -- the image-side offline texture encode arm (M3 w18, D-5).\n//\n// This module is the image-semantic layer of the Basis encode path: it maps the\n// sidecar `compressionMode` control-plane value + the source's colorSpace / HDR\n// signal into a delivery encoding (D-12 'auto' derivation), maps that to the\n// encoder parameters, and drives the low-level `basisEncode` binding that lives\n// in `@forgeax/engine-codec/encode` (the WASM + enum plumbing stays in codec;\n// the image semantics stay here -- D-5 \"arm in image, binary in codec/encode\").\n//\n// It is a NODE-ONLY build-time module (consumed by imageImporter, itself a\n// node-only sub-export). It never touches GPU (isolation path b) and is never\n// bundled into the runtime (isolation path a/d: runtime does not import\n// @forgeax/engine-image nor @forgeax/engine-codec/encode).\n//\n// M3 sequencing constraint (plan R-9): the 'auto' derivation is implemented and\n// tested here, but the sidecar DEFAULT stays 'none'. The default flip to 'auto'\n// is M5 (w38); doing it here would make every existing texture encode to Basis\n// ahead of loader support and redden the whole fixture fleet.\n\nimport type { BasisEncodeMode } from '@forgeax/engine-codec/encode';\nimport { basisEncode } from '@forgeax/engine-codec/encode';\n\n/** The sidecar control-plane value (ImageMetadata.compressionMode). */\nexport type CompressionMode = 'auto' | 'etc1s' | 'uastc' | 'none';\n\n/** The resolved delivery encoding after 'auto' derivation. `'none'` = no encode. */\nexport type ResolvedEncodeMode = 'etc1s' | 'uastc' | 'uastc-hdr' | 'none';\n\n/** Source signals that drive 'auto' derivation (D-12) and encoder params. */\nexport interface EncodeSourceInfo {\n /** Color transfer of the source (from the sidecar importSettings). */\n readonly colorSpace: 'srgb' | 'linear';\n /** Whether the source is an HDR image (.hdr -> rgba16float). */\n readonly isHdr: boolean;\n}\n\n/**\n * Resolve the sidecar `compressionMode` into a concrete delivery encoding.\n *\n * D-12 'auto' derivation (zero new required inputs, derived from existing\n * sidecar signals):\n * - HDR source -> 'uastc-hdr' (BC6H target downstream)\n * - colorSpace 'srgb' -> 'etc1s' (albedo / UI color)\n * - colorSpace 'linear' -> 'uastc' (normals / ORM / data)\n *\n * Explicit modes pass through, except an explicit 'uastc' on an HDR source\n * resolves to 'uastc-hdr' (there is no LDR UASTC path for HDR pixels). 'none'\n * and 'etc1s' pass through verbatim.\n */\nexport function resolveEncodeMode(\n mode: CompressionMode,\n source: EncodeSourceInfo,\n): ResolvedEncodeMode {\n switch (mode) {\n case 'none':\n return 'none';\n case 'etc1s':\n return 'etc1s';\n case 'uastc':\n return source.isHdr ? 'uastc-hdr' : 'uastc';\n case 'auto':\n if (source.isHdr) return 'uastc-hdr';\n return source.colorSpace === 'srgb' ? 'etc1s' : 'uastc';\n }\n}\n\n/** Encoder parameters for a resolved delivery encoding. */\nexport interface BasisEncodeParams {\n /** The codec-side delivery encoding. */\n readonly mode: BasisEncodeMode;\n /** Write the sRGB transfer function (LDR color only). */\n readonly srgb: boolean;\n /** ETC1S perceptual (sRGB) metric. */\n readonly perceptual: boolean;\n /** Wrap the UASTC-LDR payload in KTX2 zstd supercompression. */\n readonly uastcSupercompression: boolean;\n /** Encoder-side mip generation. M3 keeps this false (offline mips land in M5). */\n readonly mipGen: boolean;\n}\n\n/**\n * Map the sidecar mode + source into encoder parameters. Returns `null` for the\n * 'none' path -- the caller keeps the uncompressed `.bin` path and never calls\n * the encoder.\n */\nexport function basisEncodeParamsFor(\n mode: CompressionMode,\n source: EncodeSourceInfo,\n): BasisEncodeParams | null {\n const resolved = resolveEncodeMode(mode, source);\n const srgbColor = source.colorSpace === 'srgb';\n switch (resolved) {\n case 'none':\n return null;\n case 'etc1s':\n return {\n mode: 'etc1s',\n srgb: srgbColor,\n perceptual: srgbColor,\n uastcSupercompression: false,\n mipGen: false,\n };\n case 'uastc':\n return {\n mode: 'uastc-ldr',\n srgb: srgbColor,\n perceptual: srgbColor,\n uastcSupercompression: true,\n mipGen: false,\n };\n case 'uastc-hdr':\n return {\n mode: 'uastc-hdr',\n srgb: false,\n perceptual: false,\n uastcSupercompression: false,\n mipGen: false,\n };\n }\n}\n\n/** A successful encode result: KTX2 bytes + the resolved delivery encoding. */\nexport interface EncodedTexture {\n readonly ktx2: Uint8Array;\n readonly mode: ResolvedEncodeMode;\n}\n\n/**\n * Maximum source pixels the wasm32 Basis encoder accepts (4096x4096 = 16.78 Mpx\n * = 1024*1024*16). This mirrors the raised `BASISU_ENCODER_MAX_SOURCE_IMAGE_PIXELS`\n * ceiling patched into the encoder WASM (packages/codec/scripts/build-wasm.mjs).\n * Sources above this are rejected fast with a structured `ktx2-encode-source-too-large`\n * error rather than reaching the encoder and getting a silent 0-byte failure.\n */\nexport const MAX_ENCODE_SOURCE_PIXELS = 4096 * 4096;\n\n/** Failure result carrying a short reason (encoder-side or invalid request). */\nexport interface EncodeFailure {\n readonly code: 'ktx2-encode-failed' | 'codec-init-failed' | 'ktx2-encode-source-too-large';\n readonly mode: ResolvedEncodeMode;\n readonly reason: string;\n}\n\nexport type EncodeTextureResult =\n | { readonly ok: true; readonly value: EncodedTexture }\n | { readonly ok: false; readonly error: EncodeFailure };\n\n/**\n * Encode source pixels into a Basis KTX2 texture per the sidecar mode.\n *\n * `pixels` is tight-packed RGBA: 8-bit RGBA for LDR sources, rgba16float bytes\n * for HDR sources. Returns `{ ok: false }` with `mode: 'none'` if the sidecar\n * mode resolves to 'none' -- the importer treats that as \"no encode, keep the\n * .bin path\" rather than an error (see importer callsite w18).\n */\nexport async function encodeTextureToKtx2(\n pixels: Uint8Array,\n width: number,\n height: number,\n mode: CompressionMode,\n source: EncodeSourceInfo,\n): Promise<EncodeTextureResult> {\n const params = basisEncodeParamsFor(mode, source);\n if (params === null) {\n return {\n ok: false,\n error: {\n code: 'ktx2-encode-failed',\n mode: 'none',\n reason: 'compressionMode resolved to none',\n },\n };\n }\n const resolved = resolveEncodeMode(mode, source);\n // Fail fast above the wasm32 encoder's source-pixel ceiling (4096^2). Above\n // this the encoder returns 0 bytes silently; surface a structured, actionable\n // error instead so the importer reports \"reduce resolution or set\n // compressionMode:'none'\" rather than an opaque encode failure.\n if (width * height > MAX_ENCODE_SOURCE_PIXELS) {\n return {\n ok: false,\n error: {\n code: 'ktx2-encode-source-too-large',\n mode: resolved,\n reason:\n `source ${width}x${height} (${width * height} px) exceeds the ${MAX_ENCODE_SOURCE_PIXELS} px ` +\n '(4096x4096) Basis encode ceiling; reduce the texture resolution to <=4096x4096 ' +\n \"or set compressionMode:'none' in the sidecar to keep it uncompressed\",\n },\n };\n }\n const result = await basisEncode(pixels, {\n mode: params.mode,\n width,\n height,\n srgb: params.srgb,\n perceptual: params.perceptual,\n uastcSupercompression: params.uastcSupercompression,\n mipGen: params.mipGen,\n });\n if (!result.ok) {\n const reason =\n result.error.detail !== undefined && 'reason' in result.error.detail\n ? String((result.error.detail as { reason: unknown }).reason)\n : result.error.code;\n return {\n ok: false,\n error: {\n code:\n result.error.code === 'codec-init-failed' ? 'codec-init-failed' : 'ktx2-encode-failed',\n mode: resolved,\n reason,\n },\n };\n }\n return { ok: true, value: { ktx2: result.value, mode: resolved } };\n}\n","import type { DecodedImage, ImageColorSpace, ImageError } from '@forgeax/engine-types';\nimport * as jpeg from 'jpeg-js';\n// Static imports of upng-js + jpeg-js. tsup external keeps both as runtime\n// require() calls so the browser bundle still tree-shakes them out when\n// only image-decoder-browser.ts (createImageBitmap) is reached at runtime.\n// Synchronous decode is required by the parseImage signature contract (see\n// plan-strategy section 3.3).\nimport * as UPNG from 'upng-js';\nimport { imageError } from './errors.js';\nimport { downscaleRgba } from './resize-image.js';\nimport type { Result } from './result.js';\nimport { err, ok } from './result.js';\n\nexport interface ParseImageOptions {\n /**\n * Maximum allowed dimension (width or height). Defaults to 16384 -- the\n * conservative WebGPU `maxTextureDimension2D` floor across desktop +\n * high-end mobile (research F-3 / spec). Test fixtures pass smaller\n * values to exercise the bounds-check code path with tiny fixtures.\n */\n readonly maxDimension?: number;\n\n /** Optional asset-owned cooked-payload target; source bytes remain unchanged. */\n readonly downscaleMaxDimension?: number;\n\n /**\n * Sidecar `colorSpace` carried over to the DecodedImage POD. Defaults to\n * 'srgb' (typical baseColor / albedo path; plan-strategy section 2.5).\n */\n readonly colorSpace?: ImageColorSpace;\n\n /**\n * Sidecar `mipmap` flag carried over to DecodedImage. Defaults to true\n * (auto-generate via runtime mipmap-generator; plan-strategy section 2.6).\n */\n readonly mipmap?: boolean;\n\n /**\n * Optional source path to embed in error.detail.path (decode-failed /\n * format-unsupported variants). decodeImageFromFile fills this in;\n * in-memory parseImage callers leave it empty.\n */\n readonly path?: string;\n}\n\nconst DEFAULT_MAX_DIMENSION = 16384;\n\nconst SUPPORTED_MIMES: readonly string[] = ['image/png', 'image/jpeg'];\n\ninterface UpngDecoded {\n readonly width: number;\n readonly height: number;\n readonly data: Uint8Array;\n}\n\ninterface JpegDecoded {\n readonly width: number;\n readonly height: number;\n readonly data: Uint8Array;\n}\n\n/**\n * Pure synchronous image decoder. Translates raw byte stream + mime hint\n * into a tight-packed RGBA `DecodedImage` POD. Surfaces all four\n * ImageErrorCode members through the structured `Result<DecodedImage,\n * ImageError>` return (charter P3 explicit failure; AGENTS.md \"Return\n * Result, never throw\").\n *\n * Decoder selection follows the mime hint:\n * - `image/png` -> upng-js `UPNG.decode` + `UPNG.toRGBA8`\n * - `image/jpeg` -> jpeg-js `decode` with `formatAsRGBA: true`\n * - other -> `image-format-unsupported`\n *\n * Decoded bytes are always tight-packed RGBA (`bytes.length === width *\n * height * 4`). `colorSpace` and `mipmap` are carried from the supplied\n * `ParseImageOptions` (decodeImageFromFile passes the sidecar settings).\n */\nexport function parseImage(\n bytes: Uint8Array,\n mime: string,\n opts: ParseImageOptions = {},\n): Result<DecodedImage, ImageError> {\n if (!SUPPORTED_MIMES.includes(mime)) {\n return err(\n imageError({\n code: 'image-format-unsupported',\n actualMime: mime,\n ...(opts.path !== undefined ? { path: opts.path } : {}),\n }),\n );\n }\n\n let width = 0;\n let height = 0;\n let rgba: Uint8Array;\n\n try {\n if (mime === 'image/png') {\n const upngMod: {\n decode: (b: Uint8Array | ArrayBuffer) => UpngDecoded;\n toRGBA8: (i: UpngDecoded) => ArrayBuffer[];\n } = ((UPNG as unknown as { default?: typeof UPNG }).default ?? UPNG) as unknown as {\n decode: (b: Uint8Array | ArrayBuffer) => UpngDecoded;\n toRGBA8: (i: UpngDecoded) => ArrayBuffer[];\n };\n const decoded = upngMod.decode(bytes);\n width = decoded.width;\n height = decoded.height;\n const frames = upngMod.toRGBA8(decoded);\n const first = frames[0];\n if (first === undefined) {\n return err(\n imageError({\n code: 'image-decode-failed',\n reason: 'UPNG.toRGBA8 returned no frames',\n ...(opts.path !== undefined ? { path: opts.path } : {}),\n }),\n );\n }\n rgba = new Uint8Array(first);\n } else {\n // image/jpeg\n const jpegMod: {\n decode: (\n b: Uint8Array | ArrayBuffer,\n o?: { useTArray?: boolean; formatAsRGBA?: boolean },\n ) => JpegDecoded;\n } = ((jpeg as unknown as { default?: typeof jpeg }).default ?? jpeg) as unknown as {\n decode: (\n b: Uint8Array | ArrayBuffer,\n o?: { useTArray?: boolean; formatAsRGBA?: boolean },\n ) => JpegDecoded;\n };\n const decoded = jpegMod.decode(bytes, { useTArray: true, formatAsRGBA: true });\n width = decoded.width;\n height = decoded.height;\n rgba = decoded.data;\n }\n } catch (e) {\n return err(\n imageError({\n code: 'image-decode-failed',\n reason: e instanceof Error ? e.message : String(e),\n ...(opts.path !== undefined ? { path: opts.path } : {}),\n }),\n );\n }\n\n const downscaleLimit = opts.downscaleMaxDimension;\n if (downscaleLimit !== undefined && Number.isInteger(downscaleLimit) && downscaleLimit > 0) {\n const downscaled = downscaleRgba(rgba, width, height, downscaleLimit);\n rgba = downscaled.bytes;\n width = downscaled.width;\n height = downscaled.height;\n }\n\n const limit = opts.maxDimension ?? DEFAULT_MAX_DIMENSION;\n if (width > limit || height > limit) {\n return err(\n imageError({\n code: 'image-dimension-out-of-bounds',\n requested: { width, height },\n limit,\n }),\n );\n }\n\n return ok({\n bytes: rgba,\n width,\n height,\n mime: mime as 'image/png' | 'image/jpeg',\n colorSpace: opts.colorSpace ?? 'srgb',\n mipmap: opts.mipmap ?? true,\n });\n}\n","/** Deterministically downscale tight-packed RGBA pixels with bilinear sampling. */\nexport function downscaleRgba(\n bytes: Uint8Array,\n width: number,\n height: number,\n maxDimension: number,\n): { readonly bytes: Uint8Array; readonly width: number; readonly height: number } {\n if (width <= maxDimension && height <= maxDimension) {\n return { bytes, width, height };\n }\n\n const scale = maxDimension / Math.max(width, height);\n const targetWidth = Math.max(1, Math.round(width * scale));\n const targetHeight = Math.max(1, Math.round(height * scale));\n const output = new Uint8Array(targetWidth * targetHeight * 4);\n const source = (x: number, y: number, channel: number): number =>\n bytes[(y * width + x) * 4 + channel] ?? 0;\n\n for (let y = 0; y < targetHeight; y += 1) {\n const sourceY = ((y + 0.5) * height) / targetHeight - 0.5;\n const y0 = Math.max(0, Math.floor(sourceY));\n const y1 = Math.min(height - 1, y0 + 1);\n const yWeight = Math.max(0, Math.min(1, sourceY - y0));\n for (let x = 0; x < targetWidth; x += 1) {\n const sourceX = ((x + 0.5) * width) / targetWidth - 0.5;\n const x0 = Math.max(0, Math.floor(sourceX));\n const x1 = Math.min(width - 1, x0 + 1);\n const xWeight = Math.max(0, Math.min(1, sourceX - x0));\n const outputOffset = (y * targetWidth + x) * 4;\n for (let channel = 0; channel < 4; channel += 1) {\n const top = source(x0, y0, channel) * (1 - xWeight) + source(x1, y0, channel) * xWeight;\n const bottom = source(x0, y1, channel) * (1 - xWeight) + source(x1, y1, channel) * xWeight;\n output[outputOffset + channel] = Math.round(top * (1 - yWeight) + bottom * yWeight);\n }\n }\n }\n\n return { bytes: output, width: targetWidth, height: targetHeight };\n}\n","import type { TextureMipPolicy, TextureShape } from '@forgeax/engine-types';\nimport {\n err,\n ok,\n type Result,\n type TextureError,\n validateTextureShape,\n} from '@forgeax/engine-types';\n\n/** Versioned source-side declaration for one logical sampled texture. */\nexport interface TextureSourceDescriptor {\n readonly schemaVersion: '1';\n readonly shape: TextureShape;\n readonly format: GPUTextureFormat;\n readonly colorSpace: 'srgb' | 'linear';\n readonly mips: TextureMipPolicy;\n readonly rawSibling: string;\n}\n\nexport interface TextureSourceDescriptorError {\n readonly code: 'texture-source-descriptor-invalid';\n readonly expected: string;\n readonly hint: string;\n readonly detail: { readonly field: string; readonly actual: unknown };\n}\n\nexport type TextureSourceDescriptorResult = Result<\n TextureSourceDescriptor,\n TextureSourceDescriptorError | TextureError\n>;\n\nfunction record(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction positiveInteger(value: unknown): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value > 0;\n}\n\nfunction parseShape(value: unknown): TextureShape | undefined {\n if (!record(value) || !record(value.extent)) return undefined;\n const extent = value.extent;\n if (\n value.viewDimension === '2d' &&\n positiveInteger(extent.width) &&\n positiveInteger(extent.height)\n ) {\n if (extent.layers === undefined && extent.depth === undefined) {\n return { viewDimension: '2d', extent: { width: extent.width, height: extent.height } };\n }\n }\n if (\n value.viewDimension === '2d-array' &&\n positiveInteger(extent.width) &&\n positiveInteger(extent.height) &&\n positiveInteger(extent.layers) &&\n extent.depth === undefined\n ) {\n return {\n viewDimension: '2d-array',\n extent: { width: extent.width, height: extent.height, layers: extent.layers },\n };\n }\n if (\n value.viewDimension === '3d' &&\n positiveInteger(extent.width) &&\n positiveInteger(extent.height) &&\n positiveInteger(extent.depth) &&\n extent.layers === undefined\n ) {\n return {\n viewDimension: '3d',\n extent: { width: extent.width, height: extent.height, depth: extent.depth },\n };\n }\n return undefined;\n}\n\nfunction parseMips(value: unknown): TextureMipPolicy | undefined {\n if (!record(value)) return undefined;\n if (value.kind === 'none' || value.kind === 'generate') return { kind: value.kind };\n if (value.kind === 'packed' && positiveInteger(value.levelCount)) {\n return { kind: 'packed', levelCount: value.levelCount };\n }\n return undefined;\n}\n\nfunction descriptorError(field: string, actual: unknown): TextureSourceDescriptorError {\n return {\n code: 'texture-source-descriptor-invalid',\n expected: 'version 1 descriptor with shape, format, colorSpace, mips, and rawSibling',\n hint: 'repair the texture descriptor and re-import the same texture GUID',\n detail: { field, actual },\n };\n}\n\n/** Parse and validate source facts before any raw sibling bytes are consumed. */\nexport function parseTextureSourceDescriptor(value: unknown): TextureSourceDescriptorResult {\n if (!record(value)) return err(descriptorError('descriptor', value));\n if (value.schemaVersion !== '1')\n return err(descriptorError('schemaVersion', value.schemaVersion));\n const shape = parseShape(value.shape);\n if (shape === undefined) return err(descriptorError('shape', value.shape));\n const mips = parseMips(value.mips);\n if (mips === undefined) return err(descriptorError('mips', value.mips));\n if (typeof value.format !== 'string') return err(descriptorError('format', value.format));\n if (value.colorSpace !== 'srgb' && value.colorSpace !== 'linear') {\n return err(descriptorError('colorSpace', value.colorSpace));\n }\n if (typeof value.rawSibling !== 'string' || value.rawSibling.trim().length === 0) {\n return err(descriptorError('rawSibling', value.rawSibling));\n }\n const shapeResult = validateTextureShape(shape, mips, value.format as GPUTextureFormat);\n if (!shapeResult.ok) return shapeResult;\n return ok({\n schemaVersion: '1',\n shape,\n format: value.format as GPUTextureFormat,\n colorSpace: value.colorSpace,\n mips,\n rawSibling: value.rawSibling,\n });\n}\n","import type {\n ImportContext,\n ImportedAsset,\n TextureAsset,\n TextureError,\n} from '@forgeax/engine-types';\nimport { deriveTextureLayout, err, ImportError, ok, type Result } from '@forgeax/engine-types';\nimport {\n parseTextureSourceDescriptor,\n type TextureSourceDescriptor,\n type TextureSourceDescriptorError,\n} from './source-descriptor.js';\n\nexport interface TextureSourceInput {\n readonly descriptor: unknown;\n readonly guid: string;\n readonly sourceKey: string;\n readSibling(\n uri: string,\n ): Promise<\n | { readonly ok: true; readonly value: Uint8Array }\n | { readonly ok: false; readonly error: unknown }\n >;\n}\n\nexport interface TextureSourceReadError {\n readonly code: 'source-read-failed';\n readonly expected: string;\n readonly hint: string;\n readonly detail: {\n readonly sourceKey: string;\n readonly sibling: string;\n readonly reason: string;\n };\n}\n\nexport type TextureSourceError =\n | TextureSourceDescriptorError\n | TextureSourceReadError\n | TextureError;\n\nexport type TextureSourceResult = Result<ImportedAsset<TextureAsset>, TextureSourceError>;\n\nfunction sourceReadError(input: TextureSourceInput, reason: unknown): TextureSourceReadError {\n return {\n code: 'source-read-failed',\n expected: `readable raw sibling \"${input.descriptor && typeof input.descriptor === 'object' && 'rawSibling' in input.descriptor ? input.descriptor.rawSibling : 'rawSibling'}\"`,\n hint: 'repair the raw sibling path or bytes and re-import the same texture GUID',\n detail: {\n sourceKey: input.sourceKey,\n sibling:\n input.descriptor && typeof input.descriptor === 'object' && 'rawSibling' in input.descriptor\n ? String(input.descriptor.rawSibling)\n : 'rawSibling',\n reason: reason instanceof Error ? reason.message : String(reason),\n },\n };\n}\n\nfunction bodyMediaType(format: GPUTextureFormat): string {\n return format === 'r8unorm' ? 'application/x-forgeax-r8' : `application/x-forgeax-${format}`;\n}\n\n/** Produce one canonical TextureAsset and body artifact from a descriptor sibling. */\nexport async function produceTextureSource(\n input: TextureSourceInput,\n): Promise<TextureSourceResult> {\n const descriptorResult = parseTextureSourceDescriptor(input.descriptor);\n if (!descriptorResult.ok) return descriptorResult;\n const descriptor = descriptorResult.value;\n const sibling = await input.readSibling(descriptor.rawSibling);\n if (!sibling.ok) return err(sourceReadError(input, sibling.error));\n\n const layout = deriveTextureLayout({\n shape: descriptor.shape,\n format: descriptor.format,\n mips: descriptor.mips,\n actualByteLength: sibling.value.byteLength,\n order: 'mip-major,image-major,row-major',\n });\n if (!layout.ok) return layout;\n\n const data = new Uint8Array(sibling.value);\n return ok({\n guid: input.guid,\n kind: 'texture',\n payload: {\n kind: 'texture',\n shape: descriptor.shape,\n format: descriptor.format,\n colorSpace: descriptor.colorSpace,\n mips: descriptor.mips,\n data,\n },\n refs: [],\n artifacts: {\n body: {\n mediaType: bodyMediaType(descriptor.format),\n assetCodec: { name: descriptor.format, version: '1' },\n bytes: data,\n },\n },\n });\n}\n\nfunction sourceValidationError(ctx: ImportContext, error: TextureSourceError): ImportError {\n const detail = 'detail' in error ? error.detail : { field: 'descriptor', actual: error };\n return new ImportError({\n code: 'source-validation-failed',\n expected: error.expected,\n hint: error.hint,\n detail: {\n diagnostics: [\n {\n code: `texture-source-${error.code}`,\n severity: 'error',\n sourcePath: `${ctx.source}#${'field' in detail ? detail.field : 'rawSibling'}`,\n sourceRange: { start: 0, end: 0, line: 1, column: 1 },\n rule: 'texture-source-descriptor',\n expected: error.expected,\n actual: JSON.stringify(detail),\n hint: error.hint,\n },\n ],\n },\n });\n}\n\n/** Import a JSON descriptor whose canonical bytes live in one raw sibling. */\nexport async function importTextureSource(ctx: ImportContext): Promise<\n | {\n readonly ok: true;\n readonly value: {\n readonly assets: readonly ImportedAsset[];\n readonly sourceDependencies: readonly string[];\n };\n }\n | { readonly ok: false; readonly error: ImportError }\n> {\n const source = await ctx.readSource();\n if (!source.ok) {\n const reason = String(source.error);\n return {\n ok: false,\n error: new ImportError({\n code: 'source-read-failed',\n expected: `readable texture descriptor at \"${ctx.source}\"`,\n hint: 'repair the texture descriptor path and retry the import',\n detail: { source: ctx.source, reason },\n }),\n };\n }\n\n let descriptor: unknown;\n try {\n descriptor = JSON.parse(new TextDecoder().decode(source.value));\n } catch (error) {\n return {\n ok: false,\n error: sourceValidationError(ctx, {\n code: 'texture-source-descriptor-invalid',\n expected: 'JSON texture source descriptor',\n hint: 'repair the descriptor JSON and retry the import',\n detail: {\n field: 'descriptor',\n actual: error instanceof Error ? error.message : String(error),\n },\n }),\n };\n }\n const subAsset = ctx.subAssets.length === 1 ? ctx.subAssets[0] : undefined;\n if (subAsset === undefined || subAsset.kind !== 'texture' || subAsset.sourceIndex !== 0) {\n return {\n ok: false,\n error: sourceValidationError(ctx, {\n code: 'texture-source-descriptor-invalid',\n expected: 'one texture subAsset at sourceIndex 0',\n hint: 'repair Meta subAssets and retry the same texture GUID',\n detail: { field: 'subAssets', actual: ctx.subAssets },\n }),\n };\n }\n const produced = await produceTextureSource({\n descriptor,\n guid: subAsset.guid,\n sourceKey: subAsset.sourceKey ?? `${ctx.source}:texture`,\n readSibling: ctx.readSibling,\n });\n if (!produced.ok) return { ok: false, error: sourceValidationError(ctx, produced.error) };\n const parsed = parseTextureSourceDescriptor(descriptor);\n const sibling = parsed.ok ? parsed.value.rawSibling : ctx.source;\n return {\n ok: true,\n value: { assets: [produced.value], sourceDependencies: [ctx.source, sibling] },\n };\n}\n\nexport type { TextureSourceDescriptor };\n","// image-importer.ts - the build-time imageImporter (feat-20260603-asset-import-loader-injection M3 / w23).\n//\n// The `{ key: 'image', import }` Importer the @forgeax/engine-import runner\n// dispatches a `*.meta.json` with `importer: 'image'` to. It absorbs the\n// decode logic that previously lived inline in\n// `@forgeax/engine-vite-plugin-pack`'s generateBundle (research Finding 4,\n// vite-plugin-pack/src/index.ts:354-447): read the source bytes -> parseImage\n// -> tight-packed RGBA `DecodedImage` -> a `TextureAsset` POD whose `data`\n// column carries the imported RGBA bytes under the meta-declared GUID.\n//\n// Why image-importer lives in @forgeax/engine-image (D-9): the image domain\n// logic stays co-located with the package that already owns parseImage (a\n// node-only decoder). Splitting the import into a third package would fracture\n// the SSOT. This module is a NODE-ONLY sub-export\n// (`@forgeax/engine-image/image-importer`, `default: null` under browser\n// conditions) because it statically imports `./parse-image.js` (jpeg-js +\n// upng-js). The browser runtime never reaches it: the texture is decoded at\n// build time and the runtime loader reads the imported `.bin` (M3 strips the\n// runtime decoder edge, AC-15).\n//\n// importSettings folding (colorSpace / mipmap -> TextureAsset.format) mirrors\n// `build-catalog.ts` buildImageMetadata (D-5: `'auto'` -> true / `'none'` ->\n// false, `'srgb'` -> 'rgba8unorm-srgb' / `'linear'` -> 'rgba8unorm') so the\n// importer and the catalog builder derive the same texture metadata. The\n// imported RGBA bytes ride in `TextureAsset.data`; the generateBundle integration (w28)\n// extracts that buffer into a hashed `.bin` and folds width/height/format into\n// the pack-index row.\n//\n// GUID import-stable iron law: every produced `ImportedAsset.guid` comes from\n// `ctx.subAssets[]`, never minted here. A sub-asset of `kind: 'equirect'`\n// (HDR lat-long env map) IS folded by the .hdr arm into an EquirectAsset POD\n// (a single 2D rgba16float image); the cube-to-cube IBL projection is a runtime\n// GPU pass, not a build-time fold (feat-20260630).\n\nimport { type BasisSourceInspection, ktx2ColorSpace, parseKtx2 } from '@forgeax/engine-codec';\nimport type {\n EquirectAsset,\n ImageColorSpace,\n ImportContext,\n ImportedAsset,\n Importer,\n ImportResult,\n TextureAsset,\n} from '@forgeax/engine-types';\nimport { IMPORT_ERROR_HINTS, ImportError } from '@forgeax/engine-types';\nimport type { CompressionMode } from './ktx2-encode.js';\nimport { encodeTextureToKtx2, resolveEncodeMode } from './ktx2-encode.js';\nimport { parseImage } from './parse-image.js';\nimport { importTextureSource } from './texture/importer.js';\n\n/** Map a source path / mime hint to the parseImage mime literal. */\nfunction mimeFromSource(source: string): 'image/png' | 'image/jpeg' | undefined {\n const lower = source.toLowerCase();\n if (lower.endsWith('.png')) return 'image/png';\n if (lower.endsWith('.jpg') || lower.endsWith('.jpeg')) return 'image/jpeg';\n return undefined;\n}\n\ntype RequiredImageOutputKind = 'texture' | 'equirect';\n\nfunction requiredImageOutputKind(source: string): RequiredImageOutputKind | undefined {\n const lower = source.toLowerCase();\n if (lower.endsWith('.hdr')) return 'equirect';\n if (mimeFromSource(source) !== undefined || lower.endsWith('.basis') || lower.endsWith('.ktx2')) {\n return 'texture';\n }\n return undefined;\n}\n\nfunction imageOutputTopologyActual(ctx: ImportContext): string {\n if (ctx.subAssets.length === 0) return 'subAssets[] is empty';\n return ctx.subAssets\n .map(\n (sub, index) => `subAssets[${index}]=${sub.kind}:${sub.guid}:sourceIndex=${sub.sourceIndex}`,\n )\n .join(', ');\n}\n\ntype ImageConversionStage = 'decode' | 'inspect' | 'encode';\n\nfunction imageConversionFailure(\n ctx: ImportContext,\n stage: ImageConversionStage,\n ownerCode: string,\n sourcePath: string,\n expected: string,\n actual: string,\n hint: string,\n): ImportError {\n const diagnosticSourcePath = sourcePath.length === 0 ? ctx.source : sourcePath;\n return new ImportError({\n code: 'source-validation-failed',\n expected,\n actual,\n hint: IMPORT_ERROR_HINTS['source-validation-failed'],\n detail: {\n diagnostics: [\n {\n code: `image-conversion-${stage}-${ownerCode}`,\n severity: 'error',\n sourcePath: diagnosticSourcePath,\n sourceRange: { start: 0, end: 0, line: 1, column: 1 },\n rule: `image-conversion-${stage}`,\n expected,\n actual,\n hint,\n },\n ],\n },\n });\n}\n\nfunction validateImageOutputTopology(\n ctx: ImportContext,\n requiredKind: RequiredImageOutputKind,\n): ImportError | undefined {\n if (\n ctx.subAssets.length === 1 &&\n ctx.subAssets[0]?.kind === requiredKind &&\n ctx.subAssets[0]?.sourceIndex === 0\n ) {\n return undefined;\n }\n\n const expected = `exactly one subAssets[] entry with kind \"${requiredKind}\" and sourceIndex 0`;\n const actual = imageOutputTopologyActual(ctx);\n return new ImportError({\n code: 'source-validation-failed',\n expected,\n actual,\n hint: IMPORT_ERROR_HINTS['source-validation-failed'],\n detail: {\n diagnostics: [\n {\n code: 'image-subasset-topology',\n severity: 'error',\n sourcePath: `${ctx.source}#subAssets`,\n sourceRange: { start: 0, end: 0, line: 1, column: 1 },\n rule: 'image-required-single-output',\n expected,\n actual,\n hint: `declare exactly one ${requiredKind} sub-asset with sourceIndex 0 and remove foreign, duplicate, or misplaced entries`,\n },\n ],\n },\n });\n}\n\n/** D-5 mipmap token mapping (mirrors build-catalog mipmapTokenToBoolean). */\nfunction mipmapTokenToBoolean(token: unknown): boolean {\n return token === 'auto' || token === true;\n}\n\n/** colorSpace -> GPU format literal (mirrors build-catalog colorSpaceToFormat). */\nfunction colorSpaceToFormat(colorSpace: ImageColorSpace): GPUTextureFormat {\n return colorSpace === 'srgb' ? 'rgba8unorm-srgb' : 'rgba8unorm';\n}\n\ntype BasisProfile = 'etc1s' | 'uastc-ldr' | 'uastc-hdr';\n\nasync function inspectKtx2Source(\n ctx: ImportContext,\n bytes: Uint8Array,\n metaColorSpace: ImageColorSpace | undefined,\n): Promise<\n | {\n readonly colorSpace: ImageColorSpace;\n readonly profile: BasisProfile;\n readonly width: number;\n readonly height: number;\n readonly levelCount: number;\n }\n | ImportError\n> {\n const parsed = await parseKtx2(bytes);\n if (!parsed.ok) {\n return imageConversionFailure(\n ctx,\n 'inspect',\n 'ktx2-parse',\n ctx.source,\n 'a valid KTX2 container with a supported Basis profile',\n `codec:${parsed.error.code}`,\n 'repair the KTX2 container and retry the image import',\n );\n }\n const dfdColorSpace = ktx2ColorSpace(parsed.value);\n if (dfdColorSpace === undefined) {\n return imageConversionFailure(\n ctx,\n 'inspect',\n 'ktx2-color-space-missing',\n `${ctx.source}#DFD.transferFunction`,\n 'DFD transfer function to identify sRGB or linear color space',\n 'missing-or-unsupported-transfer-function',\n 'repair the KTX2 DFD color-space declaration before importing',\n );\n }\n if (metaColorSpace !== undefined && metaColorSpace !== dfdColorSpace) {\n return imageConversionFailure(\n ctx,\n 'inspect',\n 'ktx2-color-space-conflict',\n `${ctx.source}#importSettings.colorSpace`,\n 'Meta.colorSpace to match the KTX2 DFD transfer function',\n `meta=${metaColorSpace},dfd=${dfdColorSpace}`,\n 'repair Meta.colorSpace or re-encode the KTX2 source with matching color provenance',\n );\n }\n const { pixelDepth, layerCount, faceCount } = parsed.value.header;\n if (pixelDepth !== 0 || layerCount > 1 || faceCount !== 1) {\n return imageConversionFailure(\n ctx,\n 'inspect',\n 'ktx2-shape-unsupported',\n `${ctx.source}#header`,\n 'a 2D, single-layer, single-face KTX2 texture',\n `pixelDepth=${pixelDepth},layerCount=${layerCount},faceCount=${faceCount}`,\n 're-encode the source as one 2D Basis texture',\n );\n }\n const { initBasisTranscoder } = await import('@forgeax/engine-codec');\n const module = await initBasisTranscoder();\n let file: InstanceType<typeof module.KTX2File>;\n try {\n file = new module.KTX2File(bytes);\n } catch {\n return imageConversionFailure(\n ctx,\n 'inspect',\n 'ktx2-invalid',\n ctx.source,\n 'Basis KTX2File bytes to pass transcoder validation',\n 'basis-file-constructor-failed',\n 'repair or re-encode the KTX2 source before importing',\n );\n }\n try {\n try {\n if (!file.isValid()) {\n return imageConversionFailure(\n ctx,\n 'inspect',\n 'ktx2-invalid',\n ctx.source,\n 'Basis KTX2File bytes to pass transcoder validation',\n 'basis-file-invalid',\n 'repair or re-encode the KTX2 source before importing',\n );\n }\n const profile: BasisProfile | undefined = file.isETC1S()\n ? 'etc1s'\n : file.isHDR() || file.isHDR4x4()\n ? 'uastc-hdr'\n : file.isUASTC_LDR_4x4()\n ? 'uastc-ldr'\n : undefined;\n if (profile === undefined) {\n return imageConversionFailure(\n ctx,\n 'inspect',\n 'ktx2-profile-unsupported',\n `${ctx.source}#Basis.profile`,\n 'ETC1S, UASTC-LDR, or UASTC-HDR Basis profile',\n 'unsupported-basis-profile',\n 're-encode the source with ETC1S, UASTC-LDR, or UASTC-HDR',\n );\n }\n if (profile === 'uastc-hdr' && dfdColorSpace !== 'linear') {\n return imageConversionFailure(\n ctx,\n 'inspect',\n 'ktx2-hdr-color-space-invalid',\n `${ctx.source}#DFD.transferFunction`,\n 'UASTC-HDR source to use linear color space',\n `profile=${profile},dfd=${dfdColorSpace}`,\n 're-encode HDR data with a linear KTX2 DFD transfer function',\n );\n }\n return {\n colorSpace: dfdColorSpace,\n profile,\n width: file.getWidth(),\n height: file.getHeight(),\n levelCount: file.getLevels(),\n };\n } catch {\n return imageConversionFailure(\n ctx,\n 'inspect',\n 'ktx2-invalid',\n ctx.source,\n 'Basis KTX2File bytes to pass transcoder inspection',\n 'basis-inspection-threw',\n 'repair or re-encode the KTX2 source before importing',\n );\n }\n } finally {\n file.close();\n }\n}\n\nasync function importKtx2Source(ctx: ImportContext, bytes: Uint8Array): Promise<ImportResult> {\n const sourceKey = ctx.subAssets[0]?.sourceKey;\n const metaColorSpace =\n sourceKey === undefined\n ? ctx.importSettings.colorSpace\n : ctx.sourceOverrides?.[sourceKey]?.colorSpace;\n const inspection = await inspectKtx2Source(\n ctx,\n bytes,\n metaColorSpace === 'srgb' || metaColorSpace === 'linear' ? metaColorSpace : undefined,\n );\n if (inspection instanceof ImportError) return { ok: false, error: inspection };\n const out: ImportedAsset[] = [];\n for (const sub of ctx.subAssets) {\n if (sub.kind !== 'texture' || sub.sourceIndex !== 0) continue;\n out.push({\n guid: sub.guid,\n kind: 'texture',\n payload: {\n kind: 'texture',\n shape: {\n viewDimension: '2d',\n extent: { width: inspection.width, height: inspection.height },\n },\n format: colorSpaceToFormat(inspection.colorSpace),\n data: bytes,\n colorSpace: inspection.colorSpace,\n mips:\n inspection.levelCount > 1\n ? { kind: 'packed', levelCount: inspection.levelCount }\n : { kind: 'none' },\n },\n refs: [],\n artifacts: {\n body: {\n mediaType: 'image/ktx2',\n assetCodec: {\n name: 'basis',\n container: 'ktx2',\n profile: inspection.profile,\n version: '1',\n },\n bytes,\n },\n },\n });\n }\n return { ok: true, value: { assets: out, sourceDependencies: [] } };\n}\n\nfunction basisMetaColorSpace(ctx: ImportContext): ImageColorSpace | ImportError {\n const sourceKey = ctx.subAssets[0]?.sourceKey;\n const override = sourceKey === undefined ? undefined : ctx.sourceOverrides?.[sourceKey];\n const value = override?.colorSpace ?? ctx.importSettings.colorSpace;\n if (value !== 'srgb' && value !== 'linear') {\n return imageConversionFailure(\n ctx,\n 'inspect',\n 'basis-color-space-invalid',\n `${ctx.source}#Meta.colorSpace`,\n 'Meta.colorSpace to be srgb or linear for raw Basis',\n value === undefined ? 'missing' : `invalid:${String(value)}`,\n 'set Meta.colorSpace to srgb or linear before importing raw Basis bytes',\n );\n }\n return value;\n}\n\nasync function importBasisSource(ctx: ImportContext, bytes: Uint8Array): Promise<ImportResult> {\n const colorSpace = basisMetaColorSpace(ctx);\n if (colorSpace instanceof ImportError) return { ok: false, error: colorSpace };\n const { initBasisTranscoder, inspectBasisSource } = await import('@forgeax/engine-codec');\n const module = await initBasisTranscoder();\n if (module.BasisFile === undefined) {\n throw new Error('basis-source-inspection-unavailable: transcoder lacks BasisFile');\n }\n let file: InstanceType<typeof module.BasisFile>;\n try {\n file = new module.BasisFile(bytes);\n } catch {\n return {\n ok: false,\n error: imageConversionFailure(\n ctx,\n 'inspect',\n 'basis-source-invalid',\n ctx.source,\n 'raw Basis bytes to pass transcoder validation',\n 'basis-file-invalid',\n 'repair or re-encode the raw Basis source before importing',\n ),\n };\n }\n let inspection: BasisSourceInspection | undefined;\n try {\n try {\n const format = file.getBasisTexFormat();\n const profile =\n format === module.basis_tex_format.cETC1S.value\n ? 'etc1s'\n : format === module.basis_tex_format.cUASTC_LDR_4x4.value\n ? 'uastc-ldr'\n : undefined;\n if (profile === undefined) {\n return {\n ok: false,\n error: imageConversionFailure(\n ctx,\n 'inspect',\n 'basis-profile-unsupported',\n `${ctx.source}#Basis.profile`,\n 'ETC1S or UASTC-LDR raw Basis profile',\n 'unsupported-basis-profile',\n 're-encode the source with ETC1S or UASTC-LDR',\n ),\n };\n }\n const result = inspectBasisSource(file, { colorSpace }, profile);\n if (!result.ok) {\n return {\n ok: false,\n error: imageConversionFailure(\n ctx,\n 'inspect',\n 'basis-inspection-failed',\n ctx.source,\n 'raw Basis source metadata to pass codec inspection',\n `codec:${result.error.code}`,\n 'repair the raw Basis source metadata and retry the import',\n ),\n };\n }\n inspection = result.value;\n } catch {\n return {\n ok: false,\n error: imageConversionFailure(\n ctx,\n 'inspect',\n 'basis-source-invalid',\n ctx.source,\n 'raw Basis bytes to pass transcoder inspection',\n 'basis-inspection-threw',\n 'repair or re-encode the raw Basis source before importing',\n ),\n };\n }\n } finally {\n file.close();\n }\n if (inspection === undefined) {\n return {\n ok: false,\n error: imageConversionFailure(\n ctx,\n 'inspect',\n 'basis-inspection-failed',\n ctx.source,\n 'raw Basis source metadata to be available after codec inspection',\n 'missing-inspection-result',\n 'repair the raw Basis source and retry the import',\n ),\n };\n }\n const out: ImportedAsset[] = [];\n for (const sub of ctx.subAssets) {\n if (sub.kind !== 'texture') continue;\n if (sub.sourceIndex !== 0 || inspection.imageCount !== 1) {\n return {\n ok: false,\n error: imageConversionFailure(\n ctx,\n 'inspect',\n 'basis-image-shape-unsupported',\n `${ctx.source}#Basis.images`,\n 'one raw Basis image at sourceIndex 0',\n `imageCount=${inspection.imageCount},sourceIndex=${sub.sourceIndex}`,\n 're-encode the source as one raw Basis image',\n ),\n };\n }\n out.push({\n guid: sub.guid,\n kind: 'texture',\n payload: {\n kind: 'texture',\n shape: {\n viewDimension: '2d',\n extent: { width: inspection.width, height: inspection.height },\n },\n format: colorSpaceToFormat(colorSpace),\n data: bytes,\n colorSpace,\n mips:\n inspection.levelCount > 1\n ? { kind: 'packed', levelCount: inspection.levelCount }\n : { kind: 'none' },\n },\n refs: [],\n artifacts: {\n body: {\n mediaType: 'application/x-forgeax-basis',\n assetCodec: {\n name: 'basis',\n container: 'basis',\n profile: inspection.profile,\n version: '1',\n },\n bytes,\n },\n },\n });\n }\n return { ok: true, value: { assets: out, sourceDependencies: [] } };\n}\n\n/**\n * Read the sidecar compressionMode token (D-12 / M3 w18).\n *\n * M3 SEQUENCING CONSTRAINT (plan R-9): the default is hard-wired to `'none'`.\n * An absent / unrecognised token stays `'none'` so existing textures keep the\n * uncompressed `.bin` path -- flipping the default to `'auto'` is M5 (w38).\n */\nfunction compressionModeToken(token: unknown): CompressionMode {\n if (token === 'auto' || token === 'etc1s' || token === 'uastc' || token === 'none') {\n return token;\n }\n return 'none';\n}\n\n/**\n * Basis encode arm (D-5 / M3 w18; HDR arm feat-20260707): when the sidecar\n * requests a compressed delivery (mode resolves to non-'none'), encode the\n * decoded pixels into a Basis KTX2 and return those bytes; the catalog\n * `compression` discriminant is set by the vite-plugin-pack wiring (w20).\n * Returns `null` for the 'none' path so the caller keeps the uncompressed\n * `.bin` bytes unchanged (rgba8 for LDR, rgba16float for HDR).\n *\n * `pixels` is tight-packed RGBA: 8-bit RGBA for LDR (`isHdr: false`),\n * rgba16float bytes for HDR (`isHdr: true`). The `isHdr` signal drives both the\n * 'auto' derivation (-> 'uastc-hdr') and the encoder's HDR source path.\n */\nasync function maybeEncodeTextureBytes(\n ctx: ImportContext,\n pixels: Uint8Array,\n width: number,\n height: number,\n compressionMode: CompressionMode,\n colorSpace: ImageColorSpace,\n isHdr: boolean,\n): Promise<\n | { readonly ok: true; readonly value: Uint8Array | null }\n | { readonly ok: false; readonly error: ImportError }\n> {\n if (resolveEncodeMode(compressionMode, { colorSpace, isHdr }) === 'none') {\n return { ok: true, value: null };\n }\n const result = await encodeTextureToKtx2(pixels, width, height, compressionMode, {\n colorSpace,\n isHdr,\n });\n if (!result.ok) {\n return {\n ok: false,\n error: imageConversionFailure(\n ctx,\n 'encode',\n result.error.code === 'ktx2-encode-source-too-large'\n ? 'ktx2-source-too-large'\n : 'ktx2-encode-refused',\n `${ctx.source}#compressionMode`,\n 'the requested compression mode to accept the decoded image',\n `codec:${result.error.code},mode:${result.error.mode}`,\n result.error.code === 'ktx2-encode-source-too-large'\n ? 'reduce source dimensions or set compressionMode to none'\n : 'repair the source image or compression settings and retry the import',\n ),\n };\n }\n return { ok: true, value: result.value.ktx2 };\n}\n\nasync function importImage(ctx: ImportContext): Promise<ImportResult> {\n if (ctx.source.toLowerCase().endsWith('.texture.json')) {\n return importTextureSource(ctx);\n }\n const requiredKind = requiredImageOutputKind(ctx.source);\n if (requiredKind !== undefined) {\n const topologyError = validateImageOutputTopology(ctx, requiredKind);\n if (topologyError !== undefined) return { ok: false, error: topologyError };\n }\n\n const read = await ctx.readSource();\n if (!read.ok) {\n return {\n ok: false,\n error: new ImportError({\n code: 'source-read-failed',\n expected: `readable source file at \"${ctx.source}\"`,\n hint: IMPORT_ERROR_HINTS['source-read-failed'],\n detail: {\n source: ctx.source,\n reason: read.error instanceof Error ? read.error.message : String(read.error),\n },\n }),\n };\n }\n const mime = mimeFromSource(ctx.source);\n\n if (ctx.source.toLowerCase().endsWith('.basis')) {\n return importBasisSource(ctx, read.value);\n }\n if (ctx.source.toLowerCase().endsWith('.ktx2')) {\n return importKtx2Source(ctx, read.value);\n }\n\n // --- HDR arm (D-6): .hdr equirect source is decoded via decodeHdr -> f16 ---\n if (mime === undefined && ctx.source.toLowerCase().endsWith('.hdr')) {\n const { decodeHdr } = await import('./hdr-decoder.js');\n const decoded = decodeHdr(read.value);\n if (!decoded.ok) {\n return {\n ok: false,\n error: imageConversionFailure(\n ctx,\n 'decode',\n 'hdr',\n ctx.source,\n 'valid Radiance RGBE bytes to decode into an equirect asset',\n `image:${decoded.error.code}`,\n 'repair the HDR header or pixel payload and retry the import',\n ),\n };\n }\n const dec = decoded.value;\n const { halfFloat } = await import('@forgeax/engine-math');\n const f16Bytes = halfFloat.f32ToF16Bytes(\n new Uint8Array(dec.data.buffer, dec.data.byteOffset, dec.data.byteLength),\n );\n\n // NO block-compression for equirect (feat-20260707 M5 fix). The .hdr arm\n // folds only `kind:'equirect'` sub-assets, and an equirect is ALWAYS an IBL /\n // skybox source: the runtime drives it through equirect-to-cube / irradiance /\n // prefilter / brdf-lut RENDER passes (Skylight.equirect / SkyboxBackground.\n // equirect). A BC6H (block-compressed) texture is sample-only, never a color-\n // renderable render target, so a BC6H equirect breaks cube projection with a\n // \"BC6HRGBUfloat is not color renderable\" WebGPU error. The equirect must stay\n // uncompressed rgba16float; the catalog `compression` discriminant is forced to\n // 'none' in import-texture.ts (compressionFor), so the two agree. A purely-\n // sampled HDR 2D texture (never folded by this arm) may still take the\n // UASTC-HDR path via the standard image arm below.\n const out: ImportedAsset[] = [];\n for (const sub of ctx.subAssets) {\n // The .hdr arm folds equirect sub-assets only: a single 2D rgba16float\n // image (the lat-long env map) with a disk identity. The cube-to-cube IBL\n // projection is a GPU-side pass driven by the runtime record arm, not a\n // build-time fold (feat-20260630 w5; orchestrator adjudication: equirect\n // produces a build .bin, unlike the retired cube-texture).\n if (sub.kind !== 'equirect') continue;\n const payload: EquirectAsset = {\n kind: 'equirect',\n width: dec.width,\n height: dec.height,\n format: 'rgba16float',\n data: f16Bytes,\n colorSpace: 'linear',\n };\n out.push({\n guid: sub.guid,\n kind: 'equirect',\n payload,\n refs: [],\n artifacts: {\n body: {\n mediaType: 'application/x-forgeax-rgba16f',\n assetCodec: { name: 'rgba16float' },\n bytes: f16Bytes,\n },\n },\n });\n }\n return { ok: true, value: { assets: out, sourceDependencies: [] } };\n }\n\n // --- Standard PNG/JPEG path ---\n if (mime === undefined) {\n throw new Error(\n `imageImporter: unsupported source extension for \"${ctx.source}\" (expected .png / .jpg / .jpeg / .hdr / .ktx2 / .basis)`,\n );\n }\n\n const colorSpace: ImageColorSpace = ctx.importSettings.colorSpace === 'srgb' ? 'srgb' : 'linear';\n const mipmap = mipmapTokenToBoolean(ctx.importSettings.mipmap);\n const compressionMode = compressionModeToken(ctx.importSettings.compressionMode);\n const downscaleMaxDimension =\n typeof ctx.importSettings.downscaleMaxDimension === 'number' &&\n Number.isInteger(ctx.importSettings.downscaleMaxDimension) &&\n ctx.importSettings.downscaleMaxDimension > 0\n ? ctx.importSettings.downscaleMaxDimension\n : undefined;\n\n const decoded = parseImage(read.value, mime, {\n colorSpace,\n mipmap,\n ...(downscaleMaxDimension !== undefined ? { downscaleMaxDimension } : {}),\n });\n if (!decoded.ok) {\n return {\n ok: false,\n error: imageConversionFailure(\n ctx,\n 'decode',\n 'ldr',\n ctx.source,\n 'valid PNG or JPEG bytes to decode into RGBA pixels',\n `image:${decoded.error.code}`,\n 'repair the source image bytes and retry the import',\n ),\n };\n }\n const dec = decoded.value;\n\n // Basis encode arm (M3 w18): null keeps the uncompressed rgba8 `.bin` path.\n const encoded = await maybeEncodeTextureBytes(\n ctx,\n dec.bytes,\n dec.width,\n dec.height,\n compressionMode,\n colorSpace,\n false,\n );\n if (!encoded.ok) return encoded;\n const encodedBytes = encoded.value;\n\n const out: ImportedAsset[] = [];\n for (const sub of ctx.subAssets) {\n // Only flat 2D image sub-assets are folded here; cube-texture sub-assets\n // ride the runtime IBL multi-face cook and are intentionally not produced.\n if (sub.kind !== 'texture') continue;\n const payload: TextureAsset = {\n kind: 'texture',\n shape: { viewDimension: '2d', extent: { width: dec.width, height: dec.height } },\n format: colorSpaceToFormat(colorSpace),\n data: encodedBytes ?? dec.bytes,\n colorSpace,\n mips: mipmap ? { kind: 'generate' } : { kind: 'none' },\n };\n out.push({\n guid: sub.guid,\n kind: 'texture',\n payload,\n refs: [],\n artifacts: {\n body: {\n mediaType: encodedBytes === null ? 'application/x-forgeax-rgba8' : 'image/ktx2',\n assetCodec:\n encodedBytes === null\n ? { name: 'rgba8', version: '1' }\n : {\n name: 'basis',\n container: 'ktx2',\n profile: resolveEncodeMode(compressionMode, { colorSpace, isHdr: false }),\n },\n bytes: encodedBytes ?? dec.bytes,\n },\n },\n });\n }\n return { ok: true, value: { assets: out, sourceDependencies: [] } };\n}\n\n/** Bind the image producer to the generic importer runner's decode seam. */\nexport const decodeImageForImport: ImportContext['decodeImage'] = async (\n bytes,\n mimeType,\n importSettings,\n) => {\n const colorSpace =\n importSettings.colorSpace === 'srgb' || importSettings.colorSpace === 'linear'\n ? importSettings.colorSpace\n : 'linear';\n const mipmap = importSettings.mipmap === true;\n const downscaleMaxDimension =\n typeof importSettings.downscaleMaxDimension === 'number' &&\n Number.isInteger(importSettings.downscaleMaxDimension) &&\n importSettings.downscaleMaxDimension > 0\n ? importSettings.downscaleMaxDimension\n : undefined;\n const decoded = parseImage(bytes, mimeType, {\n colorSpace,\n mipmap,\n ...(downscaleMaxDimension === undefined ? {} : { downscaleMaxDimension }),\n });\n if (!decoded.ok) return decoded;\n const tex = decoded.value;\n const requestedCompression =\n importSettings.compressionMode === 'auto' ||\n importSettings.compressionMode === 'etc1s' ||\n importSettings.compressionMode === 'uastc' ||\n importSettings.compressionMode === 'none'\n ? importSettings.compressionMode\n : 'none';\n const resolvedCompression = resolveEncodeMode(requestedCompression, {\n colorSpace,\n isHdr: false,\n });\n let cookedBytes = tex.bytes;\n let mediaType: string = mimeType;\n let assetCodec: { name: string; profile?: string; version?: string } = {\n name: 'rgba8',\n version: '1',\n };\n if (resolvedCompression !== 'none') {\n const encoded = await encodeTextureToKtx2(\n tex.bytes,\n tex.width,\n tex.height,\n requestedCompression,\n { colorSpace, isHdr: false },\n );\n if (!encoded.ok) {\n throw new Error(\n `embedded texture compression failed (${encoded.error.code} / ${encoded.error.mode}): ${encoded.error.reason}`,\n );\n }\n cookedBytes = encoded.value.ktx2;\n mediaType = 'image/ktx2';\n assetCodec = { name: 'basis', profile: encoded.value.mode };\n }\n return {\n ok: true as const,\n value: {\n texture: {\n kind: 'texture' as const,\n data: cookedBytes,\n shape: { viewDimension: '2d', extent: { width: tex.width, height: tex.height } },\n format: colorSpaceToFormat(colorSpace),\n colorSpace,\n mips: mipmap ? { kind: 'generate' as const } : { kind: 'none' as const },\n },\n bytes: cookedBytes,\n mediaType,\n assetCodec,\n },\n };\n};\n\n/**\n * The image {@link Importer}. Register it into an `ImporterRegistry` so the\n * import runner dispatches `meta.importer === 'image'` sidecars here and can\n * offer the same producer's decoder to importers with embedded images.\n *\n * @example\n * ```ts\n * import { ImporterRegistry } from '@forgeax/engine-import';\n * import { imageImporter } from '@forgeax/engine-image/image-importer';\n * const importers = new ImporterRegistry();\n * importers.register(imageImporter);\n * ```\n */\nexport const imageImporter: Importer = {\n key: 'image',\n import: importImage,\n capabilities: { decodeImage: decodeImageForImport },\n};\n"]}
package/dist/index.d.ts CHANGED
@@ -3,6 +3,7 @@ export { decodeHdr } from './hdr-decoder.js';
3
3
  export { decodeImageInBrowser } from './image-decoder-browser.js';
4
4
  export type { JpegModule, UpngModule } from './image-decoder-node.js';
5
5
  export { loadJpeg, loadUpng } from './image-decoder-node.js';
6
+ export { createPixelSurface, type PixelColor, type PixelSurface, type PixelSurfaceNoiseOptions, type PixelSurfaceOptions, type PixelSurfaceRect, } from './pixel-surface.js';
6
7
  export type { EmittedSubAsset, ExistingExternalAssetPackage, ExistingSubAsset, } from './reimport-reuse-meta.js';
7
8
  export { reimportReuseMeta } from './reimport-reuse-meta.js';
8
9
  export type { Result, ResultErr, ResultOk } from './result.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAoBA,OAAO,EAAE,oBAAoB,EAAE,cAAc,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAC/E,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AAClE,YAAY,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AACtE,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,yBAAyB,CAAC;AAC7D,YAAY,EACV,eAAe,EACf,4BAA4B,EAC5B,gBAAgB,GACjB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAC7D,YAAY,EAAE,MAAM,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAC/D,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AACrF,YAAY,EAAE,qBAAqB,EAAE,MAAM,iBAAiB,CAAC;AAC7D,OAAO,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AACvD,YAAY,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACxE,OAAO,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACnE,YAAY,EACV,oBAAoB,EACpB,gBAAgB,EAChB,mBAAmB,GACpB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAoBA,OAAO,EAAE,oBAAoB,EAAE,cAAc,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;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