@ignifx/core 0.8.0 → 0.10.0

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 (29) hide show
  1. package/dist/{environment-mr5wp69e.js → environment-BCjfp1jB.js} +2 -2
  2. package/dist/{environment-mr5wp69e.js.map → environment-BCjfp1jB.js.map} +1 -1
  3. package/dist/{ignifx-error-CRh89KUJ.js → ignifx-error-RpK-lWwE.js} +13 -2
  4. package/dist/ignifx-error-RpK-lWwE.js.map +1 -0
  5. package/dist/index.d.ts +1758 -807
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +2695 -467
  8. package/dist/index.js.map +1 -1
  9. package/dist/{instanced-mesh-instance-gguMoIeZ.js → instanced-mesh-instance-DYwH0vLi.js} +2 -2
  10. package/dist/{instanced-mesh-instance-gguMoIeZ.js.map → instanced-mesh-instance-DYwH0vLi.js.map} +1 -1
  11. package/dist/{material-plugin-Cfw_h_Mg.js → material-plugin-CWtV7DkH.js} +3 -3
  12. package/dist/material-plugin-CWtV7DkH.js.map +1 -0
  13. package/dist/overlay-CjVgsfrm.js +239 -0
  14. package/dist/overlay-CjVgsfrm.js.map +1 -0
  15. package/dist/{post-effect-compiler-Rce26Eue.js → post-effect-compiler-pOvXae-i.js} +2 -2
  16. package/dist/{post-effect-compiler-Rce26Eue.js.map → post-effect-compiler-pOvXae-i.js.map} +1 -1
  17. package/dist/{shader-material-U6BKZ8D1.js → shader-material-B6wwFCKB.js} +2 -2
  18. package/dist/{shader-material-U6BKZ8D1.js.map → shader-material-B6wwFCKB.js.map} +1 -1
  19. package/dist/{shader-material-BIG3UDyu.js → shader-material-C4VjLTfV.js} +3 -3
  20. package/dist/{shader-material-BIG3UDyu.js.map → shader-material-C4VjLTfV.js.map} +1 -1
  21. package/dist/{shader-pragma-tw6AKaQD.js → shader-pragma-qO9_6sTd.js} +2 -2
  22. package/dist/{shader-pragma-tw6AKaQD.js.map → shader-pragma-qO9_6sTd.js.map} +1 -1
  23. package/dist/{surface-shader-DAWIDdaa.js → surface-shader-BaR7Kg-F.js} +4 -4
  24. package/dist/{surface-shader-DAWIDdaa.js.map → surface-shader-BaR7Kg-F.js.map} +1 -1
  25. package/dist/{vec3-B31o_KF_.js → vec3-T2PasQZv.js} +2 -2
  26. package/dist/{vec3-B31o_KF_.js.map → vec3-T2PasQZv.js.map} +1 -1
  27. package/package.json +2 -2
  28. package/dist/ignifx-error-CRh89KUJ.js.map +0 -1
  29. package/dist/material-plugin-Cfw_h_Mg.js.map +0 -1
@@ -1,4 +1,4 @@
1
- import { n as assertNever, o as CoreErrorCode, t as IgnifxError } from "./ignifx-error-CRh89KUJ.js";
1
+ import { n as assertNever, o as CoreErrorCode, t as IgnifxError } from "./ignifx-error-RpK-lWwE.js";
2
2
  import { i as declaredTextureBinding, n as POST_EFFECT_FUNCTION, t as POST_EFFECT_BUILTIN_UNIFORMS } from "./post-effect-C42XJFmo.js";
3
3
  //#region src/render/post-effect-compiler.ts
4
4
  /**
@@ -308,4 +308,4 @@ function isBuiltinUniformName(name) {
308
308
  //#endregion
309
309
  export { compilePostEffect, compiledPostEffect, writePostEffectValues };
310
310
 
311
- //# sourceMappingURL=post-effect-compiler-Rce26Eue.js.map
311
+ //# sourceMappingURL=post-effect-compiler-pOvXae-i.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"post-effect-compiler-Rce26Eue.js","names":[],"sources":["../src/render/post-effect-compiler.ts"],"sourcesContent":["import { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { assertNever, IgnifxError } from \"../errors/ignifx-error.js\";\nimport {\n declaredTextureBinding,\n INPUT_SAMPLER_BINDING,\n INPUT_TEXTURE_BINDING,\n POST_EFFECT_BUILTIN_UNIFORMS,\n POST_EFFECT_FUNCTION,\n} from \"./post-effect.js\";\nimport type { CompiledPostEffect, PostEffectUniformField } from \"./post-effect.js\";\nimport type { ShaderAsset } from \"./shader-asset.js\";\nimport type { ShaderUniformType } from \"./shader-declaration.js\";\n\n/**\n * Turns a `// @ignifx post` file into the fragment module and uniform layout Babylon Lite's\n * fullscreen-effect path needs (`docs/plan/2026-09-terrain-particles-shaders.md` §3.3).\n *\n * `mainFragment` is a plain function, not an entry point: Lite hard-codes the entry-point names\n * `effectFullscreenVertex` and `effectFragment` (`lib/effect/effect-renderer.js` 7, 258-260), so the\n * entry point is generated here and forwards to it. `createEffectWrapper` takes a byte length and a\n * raw writer and computes no offsets, so the struct's member offsets are worked out here from WGSL's\n * own alignment rules and kept in step with the generated struct.\n *\n * Everything in this module is device-free and deterministic, so it is asserted in Node. It is\n * reached through `./post-effect-support.ts` so a game with no custom post effect never loads it.\n */\n\n/**\n * Compiles a `// @ignifx post` file into a full fragment module and a uniform layout.\n *\n * @remarks\n * Device-free and deterministic, so the whole thing is unit-testable: the result is a WGSL string\n * and a set of byte offsets. It is memoised per shader asset by {@link compiledPostEffect}, because\n * the chain asks for it on every rebuild.\n *\n * @param shader - The loaded shader asset.\n * @returns The compiled effect.\n * @throws IgnifxError with code `IGX-0709` when the file is not a `post` one, or `IGX-0723` when it\n * declares no `mainFragment` function.\n *\n * @example\n * ```ts\n * const compiled = compilePostEffect(vignette.value);\n * compiled.byName.get(\"amount\")?.byteOffset; // 20, right after the four built-ins\n * ```\n *\n * @internal\n */\nexport function compilePostEffect(shader: ShaderAsset): CompiledPostEffect {\n if (shader.declaration.kind !== \"post\") {\n throw new IgnifxError(\n CoreErrorCode.invalidAssetFile,\n `${shader.address} declares @ignifx ${shader.declaration.kind}, not @ignifx post.`,\n {\n context: { file: shader.address, format: \"@ignifx post\", kind: shader.declaration.kind },\n hint: \"A PostProcessStack custom effect takes a .post.wgsl file whose pragma is @ignifx post.\",\n },\n );\n }\n if (!new RegExp(`\\\\bfn\\\\s+${POST_EFFECT_FUNCTION}\\\\s*\\\\(`, \"u\").test(shader.source)) {\n throw new IgnifxError(\n CoreErrorCode.surfaceHookMissing,\n `${shader.address} declares no ${POST_EFFECT_FUNCTION} function.`,\n {\n context: { asset: shader.address, hook: POST_EFFECT_FUNCTION },\n hint: `Add fn ${POST_EFFECT_FUNCTION}(in: PostInput) -> vec4<f32>; the @fragment entry point is generated.`,\n },\n );\n }\n const declared = shader.declaration.uniforms.filter((uniform) => !isBuiltinUniformName(uniform.name));\n const layout = layOutUniforms([\n ...POST_EFFECT_BUILTIN_UNIFORMS,\n ...declared.map((uniform) => ({ name: uniform.name, type: uniform.type })),\n ]);\n const byName = new Map<string, PostEffectUniformField>();\n for (const field of layout.fields) {\n byName.set(field.name, field);\n }\n return {\n address: shader.address,\n fragmentWGSL: buildFragmentModule(shader, layout.fields),\n uniforms: layout.fields,\n byName,\n uniformByteLength: layout.byteLength,\n textures: shader.declaration.textures,\n };\n}\n\n/** The compiled form of each shader asset, so a chain rebuild recompiles nothing. */\nlet compiled: WeakMap<ShaderAsset, CompiledPostEffect> | null = null;\n\n/**\n * The compiled form of a post-effect shader, compiled once per asset.\n *\n * @remarks\n * Keyed on the `ShaderAsset` itself, so a hot reload — which replaces the asset object — recompiles\n * for free.\n *\n * @param shader - The loaded shader asset.\n * @returns The compiled effect.\n * @throws IgnifxError as {@link compilePostEffect} documents.\n *\n * @internal\n */\nexport function compiledPostEffect(shader: ShaderAsset): CompiledPostEffect {\n const cache = (compiled ??= new WeakMap<ShaderAsset, CompiledPostEffect>());\n const hit = cache.get(shader);\n if (hit !== undefined) {\n return hit;\n }\n const built = compilePostEffect(shader);\n cache.set(shader, built);\n return built;\n}\n\n/**\n * Writes an effect's current values into the bytes its uniform buffer takes.\n *\n * @remarks\n * The built-in clocks and `screenSize` are written by the caller through the same `out` buffer, so\n * this only fills in the declared members: the declaration's default first, then the settings'\n * override. Unknown names are refused, which is what makes a typo in a `.scene.json` visible.\n *\n * @param effect - The compiled effect.\n * @param shader - The shader, for its declared defaults.\n * @param values - The overrides.\n * @param out - The uniform bytes, at least `effect.uniformByteLength` long.\n * @throws IgnifxError with code `IGX-0712` for an undeclared name, or `IGX-0713` for a wrongly\n * shaped value.\n *\n * @internal\n */\nexport function writePostEffectValues(\n effect: CompiledPostEffect,\n shader: ShaderAsset,\n values: Readonly<Record<string, number | readonly number[]>>,\n out: Float32Array,\n): void {\n for (const uniform of shader.declaration.uniforms) {\n const field = effect.byName.get(uniform.name);\n if (field === undefined) {\n continue;\n }\n writeField(field, uniform.defaultValue, effect.address, out);\n }\n // `for…in` rather than `Object.keys`: the chain calls this every frame for every recorded effect\n // and a key array per effect per frame is per-frame allocation (coding standards §7).\n for (const name in values) {\n if (!Object.hasOwn(values, name)) {\n continue;\n }\n const field = effect.byName.get(name);\n const value = values[name];\n if (value === undefined) {\n continue;\n }\n if (field === undefined || isBuiltinUniformName(name)) {\n throw new IgnifxError(\n CoreErrorCode.unknownShaderBinding,\n `${effect.address} declares no uniform named ${name}.`,\n {\n context: { material: effect.address, asset: effect.address, name },\n hint: `It declares ${[...effect.byName.keys()].join(\", \")}.`,\n },\n );\n }\n writeField(field, value, effect.address, out);\n }\n}\n\n/** The result of laying out a uniform struct. */\ninterface UniformLayout {\n /** The members, in struct order. */\n readonly fields: readonly PostEffectUniformField[];\n /** The struct's size, in bytes. */\n readonly byteLength: number;\n}\n\n/**\n * Computes the byte offsets WGSL gives a struct of these members, in this order.\n *\n * @remarks\n * The rules are the WGSL specification's: a member's offset is its predecessor's end rounded up to\n * the member's alignment, and the struct's size is the last member's end rounded up to the struct's\n * alignment — the largest member alignment, and in the **uniform** address space never less than\n * 16. `vec3<f32>` is the one that catches people out: 16-aligned, 12 wide (plan §3.4).\n *\n * @param members - The members, in declaration order.\n * @returns The layout.\n */\nfunction layOutUniforms(\n members: readonly { readonly name: string; readonly type: ShaderUniformType }[],\n): UniformLayout {\n const fields: PostEffectUniformField[] = [];\n let offset = 0;\n // WGSL's uniform address space rounds a struct's alignment up to a multiple of 16, so the block's\n // size is always a multiple of 16 whatever its members are.\n let structAlignment = 16;\n for (const member of members) {\n const alignment = typeAlignment(member.type);\n const size = typeSize(member.type);\n structAlignment = Math.max(structAlignment, alignment);\n offset = roundUp(offset, alignment);\n fields.push({\n name: member.name,\n type: member.type,\n components: componentCount(member.type),\n byteOffset: offset,\n });\n offset += size;\n }\n return { fields, byteLength: roundUp(offset, structAlignment) };\n}\n\n/**\n * A WGSL type's alignment in the uniform address space, in bytes.\n *\n * @param type - The type.\n * @returns The alignment.\n */\nfunction typeAlignment(type: ShaderUniformType): number {\n switch (type) {\n case \"vec2<f32>\": {\n return 8;\n }\n case \"vec3<f32>\":\n case \"vec4<f32>\":\n case \"mat4x4<f32>\": {\n return 16;\n }\n case \"f32\":\n case \"u32\":\n case \"i32\": {\n return 4;\n }\n default: {\n return assertNever(type, \"shader uniform type\");\n }\n }\n}\n\n/**\n * A WGSL type's size, in bytes.\n *\n * @param type - The type.\n * @returns The size.\n */\nfunction typeSize(type: ShaderUniformType): number {\n switch (type) {\n case \"vec2<f32>\": {\n return 8;\n }\n case \"vec3<f32>\": {\n return 12;\n }\n case \"vec4<f32>\": {\n return 16;\n }\n case \"mat4x4<f32>\": {\n return 64;\n }\n case \"f32\":\n case \"u32\":\n case \"i32\": {\n return 4;\n }\n default: {\n return assertNever(type, \"shader uniform type\");\n }\n }\n}\n\n/**\n * How many floats one uniform of a declared type occupies.\n *\n * @remarks\n * A private copy of `material-plugin.ts`'s `uniformComponentCount`. `PostProcessStack` is in every\n * game's static graph, and importing it from there would drag `defineMaterialPlugin` and the\n * reserved-name table into a bundle that draws no custom shader at all.\n *\n * @param type - The declared WGSL type.\n * @returns The component count: 1, 2, 3, 4, or 16.\n */\nfunction componentCount(type: ShaderUniformType): number {\n switch (type) {\n case \"vec2<f32>\": {\n return 2;\n }\n case \"vec3<f32>\": {\n return 3;\n }\n case \"vec4<f32>\": {\n return 4;\n }\n case \"mat4x4<f32>\": {\n return 16;\n }\n case \"f32\":\n case \"u32\":\n case \"i32\": {\n return 1;\n }\n default: {\n return assertNever(type, \"shader uniform type\");\n }\n }\n}\n\n/**\n * Rounds a value up to a multiple of an alignment.\n *\n * @param value - The value.\n * @param alignment - The alignment, a power of two.\n * @returns The rounded value.\n */\nfunction roundUp(value: number, alignment: number): number {\n return Math.ceil(value / alignment) * alignment;\n}\n\n/**\n * The whole fragment module: bindings, generated structs, the author's file, and the entry point\n * Lite's pipeline looks for.\n *\n * @param shader - The shader asset.\n * @param fields - The uniform members, in struct order.\n * @returns The WGSL.\n */\nfunction buildFragmentModule(shader: ShaderAsset, fields: readonly PostEffectUniformField[]): string {\n const members = fields.map((field) => `${field.name}:${field.type},`).join(\"\");\n const lines: string[] = [\n `struct PostUniforms{${members}}`,\n \"@group(0)@binding(0)var<uniform>shaderUniforms:PostUniforms;\",\n `@group(0)@binding(${String(INPUT_TEXTURE_BINDING)})var inputTexture:texture_2d<f32>;`,\n `@group(0)@binding(${String(INPUT_SAMPLER_BINDING)})var inputTextureSampler:sampler;`,\n ];\n // `for…of` with an index: the iterator yields the element type rather than `T | undefined`, and\n // this runs once per compiled shader rather than per frame.\n let index = -1;\n for (const declaration of shader.declaration.textures) {\n index += 1;\n const binding = declaredTextureBinding(index);\n const type = declaration.array ? \"texture_2d_array<f32>\" : \"texture_2d<f32>\";\n lines.push(\n `@group(0)@binding(${String(binding)})var ${declaration.name}:${type};`,\n `@group(0)@binding(${String(binding + 1)})var ${declaration.name}Sampler:sampler;`,\n );\n }\n lines.push(\n \"struct PostInput{uv:vec2<f32>,position:vec2<f32>,}\",\n shader.source,\n \"@fragment fn effectFragment(fragment:EffectVertexOutput)->@location(0)vec4<f32>{\",\n \"var ignifxPostInput:PostInput;\",\n // Lite's effect vertex puts uv (0, 0) at the bottom-left, but a texture's origin is the top-left,\n // so an unflipped uv mirrors the frame on every pass (`lib/effect/effect-renderer.js` 7).\n \"ignifxPostInput.uv=vec2<f32>(fragment.uv.x,1.0-fragment.uv.y);\",\n \"ignifxPostInput.position=fragment.position.xy;\",\n `return ${POST_EFFECT_FUNCTION}(ignifxPostInput);`,\n \"}\",\n );\n return lines.join(\"\\n\");\n}\n\n/**\n * Writes one member's value into the uniform bytes.\n *\n * @param field - The member.\n * @param value - The value.\n * @param asset - The shader's address, for diagnostics.\n * @param out - The uniform floats.\n * @throws IgnifxError with code `IGX-0713` when the shape does not match.\n */\nfunction writeField(\n field: PostEffectUniformField,\n value: number | readonly number[],\n asset: string,\n out: Float32Array,\n): void {\n const index = field.byteOffset / 4;\n if (typeof value === \"number\") {\n if (field.components !== 1) {\n throw mismatch(field, asset, \"a single number\");\n }\n out[index] = value;\n return;\n }\n if (value.length !== field.components) {\n throw mismatch(field, asset, `${String(value.length)} floats`);\n }\n out.set(value instanceof Float32Array ? value : Float32Array.from(value), index);\n}\n\n/**\n * The `IGX-0713` failure a wrongly shaped value produces.\n *\n * @param field - The member.\n * @param asset - The shader's address.\n * @param actual - What the caller passed.\n * @returns The error to throw.\n */\nfunction mismatch(field: PostEffectUniformField, asset: string, actual: string): IgnifxError {\n return new IgnifxError(\n CoreErrorCode.shaderValueMismatch,\n `${field.name} on ${asset} expects ${field.type} (${String(field.components)} floats), not ${actual}.`,\n {\n context: { name: field.name, material: asset, expected: field.type, actual },\n hint: \"A post effect's values are numbers and numeric arrays; a colour takes its three or four components.\",\n },\n );\n}\n\n/**\n * Whether a name is one of the four uniforms every post effect gets for free.\n *\n * @param name - The candidate.\n * @returns `true` when the engine writes it.\n */\nfunction isBuiltinUniformName(name: string): boolean {\n for (const builtin of POST_EFFECT_BUILTIN_UNIFORMS) {\n if (builtin.name === name) {\n return true;\n }\n }\n return false;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,SAAgB,kBAAkB,QAAyC;CACzE,IAAI,OAAO,YAAY,SAAS,QAC9B,MAAM,IAAI,YACR,cAAc,kBACd,GAAG,OAAO,QAAQ,oBAAoB,OAAO,YAAY,KAAK,sBAC9D;EACE,SAAS;GAAE,MAAM,OAAO;GAAS,QAAQ;GAAgB,MAAM,OAAO,YAAY;EAAK;EACvF,MAAM;CACR,CACF;CAEF,IAAI,CAAC,IAAI,OAA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B,MAAM,SAAS,OAAO,OAAO,iBAAiB;EAEhD,IAAI,SAAS;EACb;CACF;CACA,IAAI,MAAM,WAAW,MAAM,YACzB,MAAM,SAAS,OAAO,OAAO,GAAG,OAAO,MAAM,MAAM,EAAE,QAAQ;CAE/D,IAAI,IAAI,iBAAiB,eAAe,QAAQ,aAAa,KAAK,KAAK,GAAG,KAAK;AACjF;;;;;;;;;AAUA,SAAS,SAAS,OAA+B,OAAe,QAA6B;CAC3F,OAAO,IAAI,YACT,cAAc,qBACd,GAAG,MAAM,KAAK,MAAM,MAAM,WAAW,MAAM,KAAK,IAAI,OAAO,MAAM,UAAU,EAAE,gBAAgB,OAAO,IACpG;EACE,SAAS;GAAE,MAAM,MAAM;GAAM,UAAU;GAAO,UAAU,MAAM;GAAM;EAAO;EAC3E,MAAM;CACR,CACF;AACF;;;;;;;AAQA,SAAS,qBAAqB,MAAuB;CACnD,KAAK,MAAM,WAAW,8BACpB,IAAI,QAAQ,SAAS,MACnB,OAAO;CAGX,OAAO;AACT"}
1
+ {"version":3,"file":"post-effect-compiler-pOvXae-i.js","names":[],"sources":["../src/render/post-effect-compiler.ts"],"sourcesContent":["import { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { assertNever, IgnifxError } from \"../errors/ignifx-error.js\";\nimport {\n declaredTextureBinding,\n INPUT_SAMPLER_BINDING,\n INPUT_TEXTURE_BINDING,\n POST_EFFECT_BUILTIN_UNIFORMS,\n POST_EFFECT_FUNCTION,\n} from \"./post-effect.js\";\nimport type { CompiledPostEffect, PostEffectUniformField } from \"./post-effect.js\";\nimport type { ShaderAsset } from \"./shader-asset.js\";\nimport type { ShaderUniformType } from \"./shader-declaration.js\";\n\n/**\n * Turns a `// @ignifx post` file into the fragment module and uniform layout Babylon Lite's\n * fullscreen-effect path needs (`docs/plan/2026-09-terrain-particles-shaders.md` §3.3).\n *\n * `mainFragment` is a plain function, not an entry point: Lite hard-codes the entry-point names\n * `effectFullscreenVertex` and `effectFragment` (`lib/effect/effect-renderer.js` 7, 258-260), so the\n * entry point is generated here and forwards to it. `createEffectWrapper` takes a byte length and a\n * raw writer and computes no offsets, so the struct's member offsets are worked out here from WGSL's\n * own alignment rules and kept in step with the generated struct.\n *\n * Everything in this module is device-free and deterministic, so it is asserted in Node. It is\n * reached through `./post-effect-support.ts` so a game with no custom post effect never loads it.\n */\n\n/**\n * Compiles a `// @ignifx post` file into a full fragment module and a uniform layout.\n *\n * @remarks\n * Device-free and deterministic, so the whole thing is unit-testable: the result is a WGSL string\n * and a set of byte offsets. It is memoised per shader asset by {@link compiledPostEffect}, because\n * the chain asks for it on every rebuild.\n *\n * @param shader - The loaded shader asset.\n * @returns The compiled effect.\n * @throws IgnifxError with code `IGX-0709` when the file is not a `post` one, or `IGX-0723` when it\n * declares no `mainFragment` function.\n *\n * @example\n * ```ts\n * const compiled = compilePostEffect(vignette.value);\n * compiled.byName.get(\"amount\")?.byteOffset; // 20, right after the four built-ins\n * ```\n *\n * @internal\n */\nexport function compilePostEffect(shader: ShaderAsset): CompiledPostEffect {\n if (shader.declaration.kind !== \"post\") {\n throw new IgnifxError(\n CoreErrorCode.invalidAssetFile,\n `${shader.address} declares @ignifx ${shader.declaration.kind}, not @ignifx post.`,\n {\n context: { file: shader.address, format: \"@ignifx post\", kind: shader.declaration.kind },\n hint: \"A PostProcessStack custom effect takes a .post.wgsl file whose pragma is @ignifx post.\",\n },\n );\n }\n if (!new RegExp(`\\\\bfn\\\\s+${POST_EFFECT_FUNCTION}\\\\s*\\\\(`, \"u\").test(shader.source)) {\n throw new IgnifxError(\n CoreErrorCode.surfaceHookMissing,\n `${shader.address} declares no ${POST_EFFECT_FUNCTION} function.`,\n {\n context: { asset: shader.address, hook: POST_EFFECT_FUNCTION },\n hint: `Add fn ${POST_EFFECT_FUNCTION}(in: PostInput) -> vec4<f32>; the @fragment entry point is generated.`,\n },\n );\n }\n const declared = shader.declaration.uniforms.filter((uniform) => !isBuiltinUniformName(uniform.name));\n const layout = layOutUniforms([\n ...POST_EFFECT_BUILTIN_UNIFORMS,\n ...declared.map((uniform) => ({ name: uniform.name, type: uniform.type })),\n ]);\n const byName = new Map<string, PostEffectUniformField>();\n for (const field of layout.fields) {\n byName.set(field.name, field);\n }\n return {\n address: shader.address,\n fragmentWGSL: buildFragmentModule(shader, layout.fields),\n uniforms: layout.fields,\n byName,\n uniformByteLength: layout.byteLength,\n textures: shader.declaration.textures,\n };\n}\n\n/** The compiled form of each shader asset, so a chain rebuild recompiles nothing. */\nlet compiled: WeakMap<ShaderAsset, CompiledPostEffect> | null = null;\n\n/**\n * The compiled form of a post-effect shader, compiled once per asset.\n *\n * @remarks\n * Keyed on the `ShaderAsset` itself, so a hot reload — which replaces the asset object — recompiles\n * for free.\n *\n * @param shader - The loaded shader asset.\n * @returns The compiled effect.\n * @throws IgnifxError as {@link compilePostEffect} documents.\n *\n * @internal\n */\nexport function compiledPostEffect(shader: ShaderAsset): CompiledPostEffect {\n const cache = (compiled ??= new WeakMap<ShaderAsset, CompiledPostEffect>());\n const hit = cache.get(shader);\n if (hit !== undefined) {\n return hit;\n }\n const built = compilePostEffect(shader);\n cache.set(shader, built);\n return built;\n}\n\n/**\n * Writes an effect's current values into the bytes its uniform buffer takes.\n *\n * @remarks\n * The built-in clocks and `screenSize` are written by the caller through the same `out` buffer, so\n * this only fills in the declared members: the declaration's default first, then the settings'\n * override. Unknown names are refused, which is what makes a typo in a `.scene.json` visible.\n *\n * @param effect - The compiled effect.\n * @param shader - The shader, for its declared defaults.\n * @param values - The overrides.\n * @param out - The uniform bytes, at least `effect.uniformByteLength` long.\n * @throws IgnifxError with code `IGX-0712` for an undeclared name, or `IGX-0713` for a wrongly\n * shaped value.\n *\n * @internal\n */\nexport function writePostEffectValues(\n effect: CompiledPostEffect,\n shader: ShaderAsset,\n values: Readonly<Record<string, number | readonly number[]>>,\n out: Float32Array,\n): void {\n for (const uniform of shader.declaration.uniforms) {\n const field = effect.byName.get(uniform.name);\n if (field === undefined) {\n continue;\n }\n writeField(field, uniform.defaultValue, effect.address, out);\n }\n // `for…in` rather than `Object.keys`: the chain calls this every frame for every recorded effect\n // and a key array per effect per frame is per-frame allocation (coding standards §7).\n for (const name in values) {\n if (!Object.hasOwn(values, name)) {\n continue;\n }\n const field = effect.byName.get(name);\n const value = values[name];\n if (value === undefined) {\n continue;\n }\n if (field === undefined || isBuiltinUniformName(name)) {\n throw new IgnifxError(\n CoreErrorCode.unknownShaderBinding,\n `${effect.address} declares no uniform named ${name}.`,\n {\n context: { material: effect.address, asset: effect.address, name },\n hint: `It declares ${[...effect.byName.keys()].join(\", \")}.`,\n },\n );\n }\n writeField(field, value, effect.address, out);\n }\n}\n\n/** The result of laying out a uniform struct. */\ninterface UniformLayout {\n /** The members, in struct order. */\n readonly fields: readonly PostEffectUniformField[];\n /** The struct's size, in bytes. */\n readonly byteLength: number;\n}\n\n/**\n * Computes the byte offsets WGSL gives a struct of these members, in this order.\n *\n * @remarks\n * The rules are the WGSL specification's: a member's offset is its predecessor's end rounded up to\n * the member's alignment, and the struct's size is the last member's end rounded up to the struct's\n * alignment — the largest member alignment, and in the **uniform** address space never less than\n * 16. `vec3<f32>` is the one that catches people out: 16-aligned, 12 wide (plan §3.4).\n *\n * @param members - The members, in declaration order.\n * @returns The layout.\n */\nfunction layOutUniforms(\n members: readonly { readonly name: string; readonly type: ShaderUniformType }[],\n): UniformLayout {\n const fields: PostEffectUniformField[] = [];\n let offset = 0;\n // WGSL's uniform address space rounds a struct's alignment up to a multiple of 16, so the block's\n // size is always a multiple of 16 whatever its members are.\n let structAlignment = 16;\n for (const member of members) {\n const alignment = typeAlignment(member.type);\n const size = typeSize(member.type);\n structAlignment = Math.max(structAlignment, alignment);\n offset = roundUp(offset, alignment);\n fields.push({\n name: member.name,\n type: member.type,\n components: componentCount(member.type),\n byteOffset: offset,\n });\n offset += size;\n }\n return { fields, byteLength: roundUp(offset, structAlignment) };\n}\n\n/**\n * A WGSL type's alignment in the uniform address space, in bytes.\n *\n * @param type - The type.\n * @returns The alignment.\n */\nfunction typeAlignment(type: ShaderUniformType): number {\n switch (type) {\n case \"vec2<f32>\": {\n return 8;\n }\n case \"vec3<f32>\":\n case \"vec4<f32>\":\n case \"mat4x4<f32>\": {\n return 16;\n }\n case \"f32\":\n case \"u32\":\n case \"i32\": {\n return 4;\n }\n default: {\n return assertNever(type, \"shader uniform type\");\n }\n }\n}\n\n/**\n * A WGSL type's size, in bytes.\n *\n * @param type - The type.\n * @returns The size.\n */\nfunction typeSize(type: ShaderUniformType): number {\n switch (type) {\n case \"vec2<f32>\": {\n return 8;\n }\n case \"vec3<f32>\": {\n return 12;\n }\n case \"vec4<f32>\": {\n return 16;\n }\n case \"mat4x4<f32>\": {\n return 64;\n }\n case \"f32\":\n case \"u32\":\n case \"i32\": {\n return 4;\n }\n default: {\n return assertNever(type, \"shader uniform type\");\n }\n }\n}\n\n/**\n * How many floats one uniform of a declared type occupies.\n *\n * @remarks\n * A private copy of `material-plugin.ts`'s `uniformComponentCount`. `PostProcessStack` is in every\n * game's static graph, and importing it from there would drag `defineMaterialPlugin` and the\n * reserved-name table into a bundle that draws no custom shader at all.\n *\n * @param type - The declared WGSL type.\n * @returns The component count: 1, 2, 3, 4, or 16.\n */\nfunction componentCount(type: ShaderUniformType): number {\n switch (type) {\n case \"vec2<f32>\": {\n return 2;\n }\n case \"vec3<f32>\": {\n return 3;\n }\n case \"vec4<f32>\": {\n return 4;\n }\n case \"mat4x4<f32>\": {\n return 16;\n }\n case \"f32\":\n case \"u32\":\n case \"i32\": {\n return 1;\n }\n default: {\n return assertNever(type, \"shader uniform type\");\n }\n }\n}\n\n/**\n * Rounds a value up to a multiple of an alignment.\n *\n * @param value - The value.\n * @param alignment - The alignment, a power of two.\n * @returns The rounded value.\n */\nfunction roundUp(value: number, alignment: number): number {\n return Math.ceil(value / alignment) * alignment;\n}\n\n/**\n * The whole fragment module: bindings, generated structs, the author's file, and the entry point\n * Lite's pipeline looks for.\n *\n * @param shader - The shader asset.\n * @param fields - The uniform members, in struct order.\n * @returns The WGSL.\n */\nfunction buildFragmentModule(shader: ShaderAsset, fields: readonly PostEffectUniformField[]): string {\n const members = fields.map((field) => `${field.name}:${field.type},`).join(\"\");\n const lines: string[] = [\n `struct PostUniforms{${members}}`,\n \"@group(0)@binding(0)var<uniform>shaderUniforms:PostUniforms;\",\n `@group(0)@binding(${String(INPUT_TEXTURE_BINDING)})var inputTexture:texture_2d<f32>;`,\n `@group(0)@binding(${String(INPUT_SAMPLER_BINDING)})var inputTextureSampler:sampler;`,\n ];\n // `for…of` with an index: the iterator yields the element type rather than `T | undefined`, and\n // this runs once per compiled shader rather than per frame.\n let index = -1;\n for (const declaration of shader.declaration.textures) {\n index += 1;\n const binding = declaredTextureBinding(index);\n const type = declaration.array ? \"texture_2d_array<f32>\" : \"texture_2d<f32>\";\n lines.push(\n `@group(0)@binding(${String(binding)})var ${declaration.name}:${type};`,\n `@group(0)@binding(${String(binding + 1)})var ${declaration.name}Sampler:sampler;`,\n );\n }\n lines.push(\n \"struct PostInput{uv:vec2<f32>,position:vec2<f32>,}\",\n shader.source,\n \"@fragment fn effectFragment(fragment:EffectVertexOutput)->@location(0)vec4<f32>{\",\n \"var ignifxPostInput:PostInput;\",\n // Lite's effect vertex puts uv (0, 0) at the bottom-left, but a texture's origin is the top-left,\n // so an unflipped uv mirrors the frame on every pass (`lib/effect/effect-renderer.js` 7).\n \"ignifxPostInput.uv=vec2<f32>(fragment.uv.x,1.0-fragment.uv.y);\",\n \"ignifxPostInput.position=fragment.position.xy;\",\n `return ${POST_EFFECT_FUNCTION}(ignifxPostInput);`,\n \"}\",\n );\n return lines.join(\"\\n\");\n}\n\n/**\n * Writes one member's value into the uniform bytes.\n *\n * @param field - The member.\n * @param value - The value.\n * @param asset - The shader's address, for diagnostics.\n * @param out - The uniform floats.\n * @throws IgnifxError with code `IGX-0713` when the shape does not match.\n */\nfunction writeField(\n field: PostEffectUniformField,\n value: number | readonly number[],\n asset: string,\n out: Float32Array,\n): void {\n const index = field.byteOffset / 4;\n if (typeof value === \"number\") {\n if (field.components !== 1) {\n throw mismatch(field, asset, \"a single number\");\n }\n out[index] = value;\n return;\n }\n if (value.length !== field.components) {\n throw mismatch(field, asset, `${String(value.length)} floats`);\n }\n out.set(value instanceof Float32Array ? value : Float32Array.from(value), index);\n}\n\n/**\n * The `IGX-0713` failure a wrongly shaped value produces.\n *\n * @param field - The member.\n * @param asset - The shader's address.\n * @param actual - What the caller passed.\n * @returns The error to throw.\n */\nfunction mismatch(field: PostEffectUniformField, asset: string, actual: string): IgnifxError {\n return new IgnifxError(\n CoreErrorCode.shaderValueMismatch,\n `${field.name} on ${asset} expects ${field.type} (${String(field.components)} floats), not ${actual}.`,\n {\n context: { name: field.name, material: asset, expected: field.type, actual },\n hint: \"A post effect's values are numbers and numeric arrays; a colour takes its three or four components.\",\n },\n );\n}\n\n/**\n * Whether a name is one of the four uniforms every post effect gets for free.\n *\n * @param name - The candidate.\n * @returns `true` when the engine writes it.\n */\nfunction isBuiltinUniformName(name: string): boolean {\n for (const builtin of POST_EFFECT_BUILTIN_UNIFORMS) {\n if (builtin.name === name) {\n return true;\n }\n }\n return false;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,SAAgB,kBAAkB,QAAyC;CACzE,IAAI,OAAO,YAAY,SAAS,QAC9B,MAAM,IAAI,YACR,cAAc,kBACd,GAAG,OAAO,QAAQ,oBAAoB,OAAO,YAAY,KAAK,sBAC9D;EACE,SAAS;GAAE,MAAM,OAAO;GAAS,QAAQ;GAAgB,MAAM,OAAO,YAAY;EAAK;EACvF,MAAM;CACR,CACF;CAEF,IAAI,CAAC,IAAI,OAAO,gCAA2C,GAAG,CAAC,CAAC,KAAK,OAAO,MAAM,GAChF,MAAM,IAAI,YACR,cAAc,oBACd,GAAG,OAAO,QAAQ,eAAe,qBAAqB,aACtD;EACE,SAAS;GAAE,OAAO,OAAO;GAAS,MAAM;EAAqB;EAC7D,MAAM,UAAU,q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Ae,QAAQ,aAAa,KAAK,KAAK,GAAG,KAAK;AACjF;;;;;;;;;AAUA,SAAS,SAAS,OAA+B,OAAe,QAA6B;CAC3F,OAAO,IAAI,YACT,cAAc,qBACd,GAAG,MAAM,KAAK,MAAM,MAAM,WAAW,MAAM,KAAK,IAAI,OAAO,MAAM,UAAU,EAAE,gBAAgB,OAAO,IACpG;EACE,SAAS;GAAE,MAAM,MAAM;GAAM,UAAU;GAAO,UAAU,MAAM;GAAM;EAAO;EAC3E,MAAM;CACR,CACF;AACF;;;;;;;AAQA,SAAS,qBAAqB,MAAuB;CACnD,KAAK,MAAM,WAAW,8BACpB,IAAI,QAAQ,SAAS,MACnB,OAAO;CAGX,OAAO;AACT"}
@@ -1,4 +1,4 @@
1
- import { i as readSceneEnvironment } from "./environment-mr5wp69e.js";
1
+ import { i as readSceneEnvironment } from "./environment-BCjfp1jB.js";
2
2
  import { createShaderMaterial, createTexture2DArrayFromPixels, createTexture2DFromPixels, enableShaderMaterialUniformCaching, setShaderMatrix, setShaderStorageBuffer, setShaderTexture, setShaderUniform } from "@babylonjs/lite";
3
3
  //#region src/lite/gpu/shader-material.ts
4
4
  /** The RGBA bytes of each 1x1 fallback texture. */
@@ -204,4 +204,4 @@ function readSceneAmbient(scene, out) {
204
204
  //#endregion
205
205
  export { createFallbackTexture, createShaderMaterialFromOptions, enableShaderUniformCaching, readSceneAmbient, resolveFallbackTexture, writeShaderMatrix, writeShaderStorageBuffer, writeShaderTexture, writeShaderUniform };
206
206
 
207
- //# sourceMappingURL=shader-material-U6BKZ8D1.js.map
207
+ //# sourceMappingURL=shader-material-B6wwFCKB.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"shader-material-U6BKZ8D1.js","names":[],"sources":["../src/lite/gpu/shader-material.ts"],"sourcesContent":["import {\n createShaderMaterial,\n createTexture2DArrayFromPixels,\n createTexture2DFromPixels,\n enableShaderMaterialUniformCaching,\n setShaderMatrix,\n setShaderStorageBuffer,\n setShaderTexture,\n setShaderUniform,\n} from \"@babylonjs/lite\";\nimport { readSceneEnvironment } from \"./environment.js\";\nimport type {\n EngineContext,\n SceneContext,\n ShaderAttributeName,\n ShaderMaterial,\n ShaderSystemUniformName,\n ShaderUniformType,\n StorageBuffer,\n Texture2D,\n} from \"@babylonjs/lite\";\n\n/**\n * The custom-WGSL half of the Babylon Lite adapter: `createShaderMaterial`, the `setShader*`\n * setters, and the 1x1 fallback textures a declared sampler falls back to\n * (`docs/plan/2026-09-terrain-particles-shaders.md` §3.1, ADR-0024). Everything here is `@internal`.\n *\n * Lite exports one barrel, so a static import of `createShaderMaterial` anywhere in the reachable\n * graph pulls `lib/material/shader/**` into every entry chunk. This module is therefore reached with\n * `await import(...)` from `../../render/shader-support.ts`, and only loading a `.wgsl` triggers the\n * fetch. `./storage-buffer.ts` is a separate file for the same reason: `StorageBufferAsset`\n * allocates synchronously, so it cannot wait for this chunk.\n *\n * Two Lite facts it is written around:\n *\n * - Nothing may be left unbound: `createShaderBindGroup` throws (errors 309 and 310) when a declared\n * sampler has no texture or a declared storage buffer has no buffer, which is what\n * {@link createFallbackTexture} exists for.\n * - There is no front-face culling; `ShaderMaterialOptions` carries only `backFaceCulling`\n * (`lib/material/shader/shader-pipeline.js`), so the pragma parser refuses `cull front`.\n */\n\n/**\n * A Babylon Lite custom WGSL material, re-exported under an ignifx name\n * (`CONSTITUTION.md` §3.4, coding standards §4).\n *\n * @remarks\n * Unstable; excluded from the stability guarantees of `CONSTITUTION.md` Article IV.\n *\n * @public\n */\nexport type LiteShaderMaterial = ShaderMaterial;\n\n/** The RGBA bytes of each 1x1 fallback texture. */\nconst FALLBACK_PIXELS: Readonly<Record<string, readonly [number, number, number, number]>> = Object.freeze({\n white: [255, 255, 255, 255],\n black: [0, 0, 0, 255],\n transparent: [0, 0, 0, 0],\n});\n\n/**\n * One declared uniform in the form Babylon Lite's factory takes: either the name of a system\n * uniform it fills in itself, or a custom declaration with its initial value.\n *\n * @internal\n */\nexport type ShaderUniformEntry =\n | ShaderSystemUniformName\n | {\n /** The WGSL identifier. */\n readonly name: string;\n /** The WGSL type. */\n readonly type: ShaderUniformType;\n /** The initial value, **linear** for a colour. */\n readonly defaultValue: number | readonly number[];\n };\n\n/**\n * One declared sampler in the form Babylon Lite's factory takes.\n *\n * @internal\n */\nexport interface ShaderSamplerEntry {\n /** The WGSL identifier; Lite generates `<name>Sampler` beside it. */\n readonly name: string;\n /** `\"2d-array\"` for a `texture_2d_array<f32>` binding. */\n readonly viewDimension: \"2d\" | \"2d-array\";\n}\n\n/**\n * One declared storage buffer in the form Babylon Lite's factory takes.\n *\n * @internal\n */\nexport interface ShaderStorageEntry {\n /** The WGSL identifier. */\n readonly name: string;\n /** The WGSL variable type, verbatim. */\n readonly type: string;\n}\n\n/**\n * Everything Babylon Lite's `createShaderMaterial` needs, in ignifx's own vocabulary so that the\n * mapping from a `ShaderDeclaration` can be built and asserted without a device or a Lite import\n * (`src/render/shader-material.ts`).\n *\n * @remarks\n * A `null` blend state or depth comparison means \"leave Babylon Lite's own default in place\", so\n * this module never restates a Lite default that could change.\n *\n * @internal\n */\nexport interface ShaderMaterialBuildOptions {\n /** The material's name, used in pipeline and shader-module labels. */\n readonly name: string;\n /** The WGSL source, handed to Lite as both the vertex and the fragment source. */\n readonly source: string;\n /** The vertex attributes the vertex stage reads; `position` is mandatory. */\n readonly attributes: readonly ShaderAttributeName[];\n /** The system and custom uniforms, in binding-declaration order. */\n readonly uniforms: readonly ShaderUniformEntry[];\n /** The samplers. */\n readonly samplers: readonly ShaderSamplerEntry[];\n /** The read-only storage buffers. */\n readonly storageBuffers: readonly ShaderStorageEntry[];\n /** The WGSL `const` declarations, resolved from the file's defaults and the material's overrides. */\n readonly defines: Readonly<Record<string, boolean | number>>;\n /** Whether the thin-instance RGBA stream is bound and injected into `VertexInput`. */\n readonly useThinInstanceColors: boolean;\n /** Whether the surface is alpha-blended. */\n readonly needAlphaBlending: boolean;\n /** Which of Lite's two blend equations to use when no explicit state is given. */\n readonly blendMode: \"alpha\" | \"additive\";\n /** An explicit colour-target blend state, which replaces the derived one; `null` to derive it. */\n readonly blend: GPUBlendState | null;\n /** Whether the surface samples the opaque scene colour behind it. */\n readonly transmissive: boolean;\n /** Whether back faces are culled. */\n readonly backFaceCulling: boolean;\n /** Whether the draw writes depth. */\n readonly depthWrite: boolean;\n /** The depth comparison, or `null` for Lite's own reverse-Z default. */\n readonly depthCompare: GPUCompareFunction | null;\n}\n\n/**\n * Builds a Babylon Lite custom WGSL material.\n *\n * @remarks\n * Validation is eager and compilation is lazy, so this runs under the null engine; the pipeline is\n * compiled the first time a mesh wearing the material is drawn.\n *\n * @param options - The sources and the declared attribute, uniform, sampler, and storage layout.\n * @returns The material.\n * @throws Error from Babylon Lite when the declaration is not one it can build.\n *\n * @internal\n */\nexport function createShaderMaterialFromOptions(options: ShaderMaterialBuildOptions): ShaderMaterial {\n return createShaderMaterial({\n name: options.name,\n vertexSource: options.source,\n fragmentSource: options.source,\n attributes: options.attributes,\n uniforms: options.uniforms,\n samplers: options.samplers,\n storageBuffers: options.storageBuffers,\n defines: options.defines,\n useThinInstanceColors: options.useThinInstanceColors,\n needAlphaBlending: options.needAlphaBlending,\n blendMode: options.blendMode,\n ...(options.blend === null ? {} : { blend: options.blend }),\n transmissive: options.transmissive,\n backFaceCulling: options.backFaceCulling,\n depthWrite: options.depthWrite,\n ...(options.depthCompare === null ? {} : { depthCompare: options.depthCompare }),\n });\n}\n\n/**\n * Writes a declared scalar, vector, or matrix uniform.\n *\n * @remarks\n * Lite compares the incoming numbers with the ones it holds and bumps the material's uniform\n * version only when one changed, so calling this every frame with an unchanged value costs a few\n * comparisons and no upload (`lib/material/shader/shader-material.js`, `setUniformValue`).\n *\n * @param material - The material to write to.\n * @param name - The declared uniform name.\n * @param value - The value; its length must match the declared type.\n * @throws Error from Babylon Lite when the name is not declared or the length is wrong.\n *\n * @internal\n */\nexport function writeShaderUniform(\n material: ShaderMaterial,\n name: string,\n value: number | readonly number[] | Float32Array,\n): void {\n setShaderUniform(material, name, value);\n}\n\n/**\n * Writes a declared `mat4x4<f32>` uniform from sixteen column-major floats.\n *\n * @param material - The material to write to.\n * @param name - The declared uniform name.\n * @param value - The matrix.\n *\n * @internal\n */\nexport function writeShaderMatrix(material: ShaderMaterial, name: string, value: Float32Array): void {\n setShaderMatrix(material, name, value);\n}\n\n/**\n * Binds or clears a declared sampler's texture.\n *\n * @param material - The material to write to.\n * @param name - The declared sampler name.\n * @param texture - The texture, or `null` to unbind. An unbound sampler makes the material\n * unbuildable, so ignifx always binds a fallback instead.\n *\n * @internal\n */\nexport function writeShaderTexture(material: ShaderMaterial, name: string, texture: Texture2D | null): void {\n setShaderTexture(material, name, texture);\n}\n\n/**\n * Binds or clears a declared storage buffer.\n *\n * @param material - The material to write to.\n * @param name - The declared storage buffer name.\n * @param buffer - The buffer, or `null` to unbind.\n *\n * @internal\n */\nexport function writeShaderStorageBuffer(material: ShaderMaterial, name: string, buffer: StorageBuffer | null): void {\n setShaderStorageBuffer(material, name, buffer);\n}\n\n/**\n * The 1x1 texture a declared-but-unbound sampler is filled with, created on first use and shared for\n * the life of the app.\n *\n * @param engine - The engine that owns the texture.\n * @param cache - The app's fallback textures, keyed by kind; a miss is created and stored.\n * @param fallback - `\"white\"`, `\"black\"`, or `\"transparent\"`; `null` means white.\n * @param array - `true` for a one-layer `texture_2d_array<f32>`.\n * @returns The texture.\n *\n * @internal\n */\nexport function resolveFallbackTexture(\n engine: EngineContext,\n cache: Map<string, Texture2D>,\n fallback: string | null,\n array: boolean,\n): Texture2D {\n const kind = fallback ?? \"white\";\n const key = array ? `${kind}:array` : kind;\n const cached = cache.get(key);\n if (cached !== undefined) {\n return cached;\n }\n const created = createFallbackTexture(engine, kind, array);\n cache.set(key, created);\n return created;\n}\n\n/**\n * Creates the 1x1 texture a declared-but-unbound sampler is filled with.\n *\n * @remarks\n * Babylon Lite refuses to build a bind group for a sampler with nothing bound (error 309), so a\n * material whose file declares `// @ignifx texture noise` and whose `.material.json` binds nothing\n * would be undrawable. One 1x1 texture per fallback kind per app is what makes it legal, which is\n * also Godot's `hint_default_white` behaviour.\n *\n * @param engine - The engine that owns the texture.\n * @param fallback - `\"white\"`, `\"black\"`, or `\"transparent\"`.\n * @param array - `true` for a one-layer `texture_2d_array<f32>`, which is what a sampler declared\n * `array` binds.\n * @returns The texture.\n *\n * @internal\n */\nexport function createFallbackTexture(engine: EngineContext, fallback: string, array: boolean): Texture2D {\n const rgba = FALLBACK_PIXELS[fallback] ?? FALLBACK_PIXELS[\"white\"];\n const pixels = Uint8Array.from(rgba ?? [255, 255, 255, 255]);\n return array\n ? createTexture2DArrayFromPixels(engine, pixels, 1, 1, 1, { mipMaps: false })\n : createTexture2DFromPixels(engine, pixels, 1, 1, {});\n}\n\n/**\n * Turns on Babylon Lite's cached uniform serialization plans for shader materials.\n *\n * @remarks\n * Process-global and idempotent: it installs two writer functions that keep a `WeakMap` of layout\n * plans per material and rewrite only the custom uniform slots whose value changed\n * (`lib/material/shader/enable-shader-material-uniform-caching.js`). That is exactly the shape of\n * ignifx's per-frame `time` upload, so the adapter enables it as it loads rather than making every\n * project remember to.\n *\n * @internal\n */\nexport function enableShaderUniformCaching(): void {\n enableShaderMaterialUniformCaching();\n}\n\n/**\n * Reads the installed environment's ambient irradiance — the `L00` band of its diffuse spherical\n * harmonics — into `out`.\n *\n * @remarks\n * `EnvironmentTextures.sphericalHarmonics` is declared: 36 floats in a stride-4 layout beginning\n * `[L00.rgb, 0, …]` (`index.d.ts`), the same block Babylon Lite writes into the scene uniform buffer\n * as `scene.vSphericalL00` and friends (`lib/scene/scene-ubo-extras.js`, `writeEnvUbo`). So the\n * value ignifx uploads as `ambientColor` is exactly what a shader could read for itself as\n * `scene.vSphericalL00.rgb`, which is the documented alternative for a shader that would rather not\n * declare the uniform. Reaching the slot goes through `./environment.ts`, which is the one place\n * ignifx touches the undeclared `scene._envTextures` field\n * (`docs/architecture/07-rendering.md` §2.5, §8).\n *\n * @param scene - The render scene.\n * @param out - Receives the three linear channels; left untouched when nothing is installed.\n * @returns `true` when an environment supplied harmonics.\n *\n * @internal\n */\nexport function readSceneAmbient(scene: SceneContext, out: Float32Array): boolean {\n const harmonics = readSceneEnvironment(scene)?.sphericalHarmonics;\n if (harmonics === undefined || harmonics.length < 3) {\n return false;\n }\n out[0] = harmonics[0] ?? 0;\n out[1] = harmonics[1] ?? 0;\n out[2] = harmonics[2] ?? 0;\n return true;\n}\n\n/**\n * The subset of this module `src/render/shader-material.ts` reaches through its dynamic `import()`,\n * named so the memo has a type that does not have to be written as `typeof import(…)` (which the\n * `consistent-type-imports` rule forbids).\n *\n * @remarks\n * Assigning the imported module namespace to this type is what checks the two against each other,\n * so a signature that drifts is a compile error rather than a runtime surprise.\n *\n * @internal\n */\nexport interface ShaderMaterialAdapter {\n /** {@link createShaderMaterialFromOptions}. */\n readonly createShaderMaterialFromOptions: (options: ShaderMaterialBuildOptions) => ShaderMaterial;\n /** {@link writeShaderUniform}. */\n readonly writeShaderUniform: (\n material: ShaderMaterial,\n name: string,\n value: number | readonly number[] | Float32Array,\n ) => void;\n /** {@link writeShaderMatrix}. */\n readonly writeShaderMatrix: (material: ShaderMaterial, name: string, value: Float32Array) => void;\n /** {@link writeShaderTexture}. */\n readonly writeShaderTexture: (material: ShaderMaterial, name: string, texture: Texture2D | null) => void;\n /** {@link writeShaderStorageBuffer}. */\n readonly writeShaderStorageBuffer: (material: ShaderMaterial, name: string, buffer: StorageBuffer | null) => void;\n /** {@link resolveFallbackTexture}. */\n readonly resolveFallbackTexture: (\n engine: EngineContext,\n cache: Map<string, Texture2D>,\n fallback: string | null,\n array: boolean,\n ) => Texture2D;\n /** {@link enableShaderUniformCaching}. */\n readonly enableShaderUniformCaching: () => void;\n /** {@link readSceneAmbient}. */\n readonly readSceneAmbient: (scene: SceneContext, out: Float32Array) => boolean;\n}\n"],"mappings":";;;;AAsDA,MAAM,kBAAuF,OAAO,OAAO;CACzG,OAAO;EAAC;EAAK;EAAK;EAAK;CAA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AAK,OAAO;CACtB,OAAO;AACT;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,sBAAsB,QAAuB,UAAkB,OAA2B;CACxG,MAAM,OAAO,gBAAgB,aAAa,gBAAgB;CAC1D,MAAM,SAAS,WAAW,KAAK,QAAQ;EAAC;EAAK;EAAK;EAAK;CAAG,CAAC;CAC3D,OAAO,QACH,+BAA+B,QAAQ,QAAQ,GAAG,GAAG,GAAG,EAAE,SAAS,MAAM,CAAC,IAC1E,0BAA0B,QAAQ,QAAQ,GAAG,GAAG,CAAC,CAAC;AACxD;;;;;;;;;;;;;AAcA,SAAgB,6BAAmC;CACjD,mCAAmC;AACrC;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,iBAAiB,OAAqB,KAA4B;CAChF,MAAM,YAAY,qBAAqB,KAAK,CAAC,EAAE;CAC/C,IAAI,cAAc,KAAA,KAAa,UAAU,SAAS,GAChD,OAAO;CAET,IAAI,KAAK,UAAU,MAAM;CACzB,IAAI,KAAK,UAAU,MAAM;CACzB,IAAI,KAAK,UAAU,MAAM;CACzB,OAAO;AACT"}
1
+ {"version":3,"file":"shader-material-B6wwFCKB.js","names":[],"sources":["../src/lite/gpu/shader-material.ts"],"sourcesContent":["import {\n createShaderMaterial,\n createTexture2DArrayFromPixels,\n createTexture2DFromPixels,\n enableShaderMaterialUniformCaching,\n setShaderMatrix,\n setShaderStorageBuffer,\n setShaderTexture,\n setShaderUniform,\n} from \"@babylonjs/lite\";\nimport { readSceneEnvironment } from \"./environment.js\";\nimport type {\n EngineContext,\n SceneContext,\n ShaderAttributeName,\n ShaderMaterial,\n ShaderSystemUniformName,\n ShaderUniformType,\n StorageBuffer,\n Texture2D,\n} from \"@babylonjs/lite\";\n\n/**\n * The custom-WGSL half of the Babylon Lite adapter: `createShaderMaterial`, the `setShader*`\n * setters, and the 1x1 fallback textures a declared sampler falls back to\n * (`docs/plan/2026-09-terrain-particles-shaders.md` §3.1, ADR-0024). Everything here is `@internal`.\n *\n * Lite exports one barrel, so a static import of `createShaderMaterial` anywhere in the reachable\n * graph pulls `lib/material/shader/**` into every entry chunk. This module is therefore reached with\n * `await import(...)` from `../../render/shader-support.ts`, and only loading a `.wgsl` triggers the\n * fetch. `./storage-buffer.ts` is a separate file for the same reason: `StorageBufferAsset`\n * allocates synchronously, so it cannot wait for this chunk.\n *\n * Two Lite facts it is written around:\n *\n * - Nothing may be left unbound: `createShaderBindGroup` throws (errors 309 and 310) when a declared\n * sampler has no texture or a declared storage buffer has no buffer, which is what\n * {@link createFallbackTexture} exists for.\n * - There is no front-face culling; `ShaderMaterialOptions` carries only `backFaceCulling`\n * (`lib/material/shader/shader-pipeline.js`), so the pragma parser refuses `cull front`.\n */\n\n/**\n * A Babylon Lite custom WGSL material, re-exported under an ignifx name\n * (`CONSTITUTION.md` §3.4, coding standards §4).\n *\n * @remarks\n * Unstable; excluded from the stability guarantees of `CONSTITUTION.md` Article IV.\n *\n * @public\n */\nexport type LiteShaderMaterial = ShaderMaterial;\n\n/** The RGBA bytes of each 1x1 fallback texture. */\nconst FALLBACK_PIXELS: Readonly<Record<string, readonly [number, number, number, number]>> = Object.freeze({\n white: [255, 255, 255, 255],\n black: [0, 0, 0, 255],\n transparent: [0, 0, 0, 0],\n});\n\n/**\n * One declared uniform in the form Babylon Lite's factory takes: either the name of a system\n * uniform it fills in itself, or a custom declaration with its initial value.\n *\n * @internal\n */\nexport type ShaderUniformEntry =\n | ShaderSystemUniformName\n | {\n /** The WGSL identifier. */\n readonly name: string;\n /** The WGSL type. */\n readonly type: ShaderUniformType;\n /** The initial value, **linear** for a colour. */\n readonly defaultValue: number | readonly number[];\n };\n\n/**\n * One declared sampler in the form Babylon Lite's factory takes.\n *\n * @internal\n */\nexport interface ShaderSamplerEntry {\n /** The WGSL identifier; Lite generates `<name>Sampler` beside it. */\n readonly name: string;\n /** `\"2d-array\"` for a `texture_2d_array<f32>` binding. */\n readonly viewDimension: \"2d\" | \"2d-array\";\n}\n\n/**\n * One declared storage buffer in the form Babylon Lite's factory takes.\n *\n * @internal\n */\nexport interface ShaderStorageEntry {\n /** The WGSL identifier. */\n readonly name: string;\n /** The WGSL variable type, verbatim. */\n readonly type: string;\n}\n\n/**\n * Everything Babylon Lite's `createShaderMaterial` needs, in ignifx's own vocabulary so that the\n * mapping from a `ShaderDeclaration` can be built and asserted without a device or a Lite import\n * (`src/render/shader-material.ts`).\n *\n * @remarks\n * A `null` blend state or depth comparison means \"leave Babylon Lite's own default in place\", so\n * this module never restates a Lite default that could change.\n *\n * @internal\n */\nexport interface ShaderMaterialBuildOptions {\n /** The material's name, used in pipeline and shader-module labels. */\n readonly name: string;\n /** The WGSL source, handed to Lite as both the vertex and the fragment source. */\n readonly source: string;\n /** The vertex attributes the vertex stage reads; `position` is mandatory. */\n readonly attributes: readonly ShaderAttributeName[];\n /** The system and custom uniforms, in binding-declaration order. */\n readonly uniforms: readonly ShaderUniformEntry[];\n /** The samplers. */\n readonly samplers: readonly ShaderSamplerEntry[];\n /** The read-only storage buffers. */\n readonly storageBuffers: readonly ShaderStorageEntry[];\n /** The WGSL `const` declarations, resolved from the file's defaults and the material's overrides. */\n readonly defines: Readonly<Record<string, boolean | number>>;\n /** Whether the thin-instance RGBA stream is bound and injected into `VertexInput`. */\n readonly useThinInstanceColors: boolean;\n /** Whether the surface is alpha-blended. */\n readonly needAlphaBlending: boolean;\n /** Which of Lite's two blend equations to use when no explicit state is given. */\n readonly blendMode: \"alpha\" | \"additive\";\n /** An explicit colour-target blend state, which replaces the derived one; `null` to derive it. */\n readonly blend: GPUBlendState | null;\n /** Whether the surface samples the opaque scene colour behind it. */\n readonly transmissive: boolean;\n /** Whether back faces are culled. */\n readonly backFaceCulling: boolean;\n /** Whether the draw writes depth. */\n readonly depthWrite: boolean;\n /** The depth comparison, or `null` for Lite's own reverse-Z default. */\n readonly depthCompare: GPUCompareFunction | null;\n}\n\n/**\n * Builds a Babylon Lite custom WGSL material.\n *\n * @remarks\n * Validation is eager and compilation is lazy, so this runs under the null engine; the pipeline is\n * compiled the first time a mesh wearing the material is drawn.\n *\n * @param options - The sources and the declared attribute, uniform, sampler, and storage layout.\n * @returns The material.\n * @throws Error from Babylon Lite when the declaration is not one it can build.\n *\n * @internal\n */\nexport function createShaderMaterialFromOptions(options: ShaderMaterialBuildOptions): ShaderMaterial {\n return createShaderMaterial({\n name: options.name,\n vertexSource: options.source,\n fragmentSource: options.source,\n attributes: options.attributes,\n uniforms: options.uniforms,\n samplers: options.samplers,\n storageBuffers: options.storageBuffers,\n defines: options.defines,\n useThinInstanceColors: options.useThinInstanceColors,\n needAlphaBlending: options.needAlphaBlending,\n blendMode: options.blendMode,\n ...(options.blend === null ? {} : { blend: options.blend }),\n transmissive: options.transmissive,\n backFaceCulling: options.backFaceCulling,\n depthWrite: options.depthWrite,\n ...(options.depthCompare === null ? {} : { depthCompare: options.depthCompare }),\n });\n}\n\n/**\n * Writes a declared scalar, vector, or matrix uniform.\n *\n * @remarks\n * Lite compares the incoming numbers with the ones it holds and bumps the material's uniform\n * version only when one changed, so calling this every frame with an unchanged value costs a few\n * comparisons and no upload (`lib/material/shader/shader-material.js`, `setUniformValue`).\n *\n * @param material - The material to write to.\n * @param name - The declared uniform name.\n * @param value - The value; its length must match the declared type.\n * @throws Error from Babylon Lite when the name is not declared or the length is wrong.\n *\n * @internal\n */\nexport function writeShaderUniform(\n material: ShaderMaterial,\n name: string,\n value: number | readonly number[] | Float32Array,\n): void {\n setShaderUniform(material, name, value);\n}\n\n/**\n * Writes a declared `mat4x4<f32>` uniform from sixteen column-major floats.\n *\n * @param material - The material to write to.\n * @param name - The declared uniform name.\n * @param value - The matrix.\n *\n * @internal\n */\nexport function writeShaderMatrix(material: ShaderMaterial, name: string, value: Float32Array): void {\n setShaderMatrix(material, name, value);\n}\n\n/**\n * Binds or clears a declared sampler's texture.\n *\n * @param material - The material to write to.\n * @param name - The declared sampler name.\n * @param texture - The texture, or `null` to unbind. An unbound sampler makes the material\n * unbuildable, so ignifx always binds a fallback instead.\n *\n * @internal\n */\nexport function writeShaderTexture(material: ShaderMaterial, name: string, texture: Texture2D | null): void {\n setShaderTexture(material, name, texture);\n}\n\n/**\n * Binds or clears a declared storage buffer.\n *\n * @param material - The material to write to.\n * @param name - The declared storage buffer name.\n * @param buffer - The buffer, or `null` to unbind.\n *\n * @internal\n */\nexport function writeShaderStorageBuffer(material: ShaderMaterial, name: string, buffer: StorageBuffer | null): void {\n setShaderStorageBuffer(material, name, buffer);\n}\n\n/**\n * The 1x1 texture a declared-but-unbound sampler is filled with, created on first use and shared for\n * the life of the app.\n *\n * @param engine - The engine that owns the texture.\n * @param cache - The app's fallback textures, keyed by kind; a miss is created and stored.\n * @param fallback - `\"white\"`, `\"black\"`, or `\"transparent\"`; `null` means white.\n * @param array - `true` for a one-layer `texture_2d_array<f32>`.\n * @returns The texture.\n *\n * @internal\n */\nexport function resolveFallbackTexture(\n engine: EngineContext,\n cache: Map<string, Texture2D>,\n fallback: string | null,\n array: boolean,\n): Texture2D {\n const kind = fallback ?? \"white\";\n const key = array ? `${kind}:array` : kind;\n const cached = cache.get(key);\n if (cached !== undefined) {\n return cached;\n }\n const created = createFallbackTexture(engine, kind, array);\n cache.set(key, created);\n return created;\n}\n\n/**\n * Creates the 1x1 texture a declared-but-unbound sampler is filled with.\n *\n * @remarks\n * Babylon Lite refuses to build a bind group for a sampler with nothing bound (error 309), so a\n * material whose file declares `// @ignifx texture noise` and whose `.material.json` binds nothing\n * would be undrawable. One 1x1 texture per fallback kind per app is what makes it legal, which is\n * also Godot's `hint_default_white` behaviour.\n *\n * @param engine - The engine that owns the texture.\n * @param fallback - `\"white\"`, `\"black\"`, or `\"transparent\"`.\n * @param array - `true` for a one-layer `texture_2d_array<f32>`, which is what a sampler declared\n * `array` binds.\n * @returns The texture.\n *\n * @internal\n */\nexport function createFallbackTexture(engine: EngineContext, fallback: string, array: boolean): Texture2D {\n const rgba = FALLBACK_PIXELS[fallback] ?? FALLBACK_PIXELS[\"white\"];\n const pixels = Uint8Array.from(rgba ?? [255, 255, 255, 255]);\n return array\n ? createTexture2DArrayFromPixels(engine, pixels, 1, 1, 1, { mipMaps: false })\n : createTexture2DFromPixels(engine, pixels, 1, 1, {});\n}\n\n/**\n * Turns on Babylon Lite's cached uniform serialization plans for shader materials.\n *\n * @remarks\n * Process-global and idempotent: it installs two writer functions that keep a `WeakMap` of layout\n * plans per material and rewrite only the custom uniform slots whose value changed\n * (`lib/material/shader/enable-shader-material-uniform-caching.js`). That is exactly the shape of\n * ignifx's per-frame `time` upload, so the adapter enables it as it loads rather than making every\n * project remember to.\n *\n * @internal\n */\nexport function enableShaderUniformCaching(): void {\n enableShaderMaterialUniformCaching();\n}\n\n/**\n * Reads the installed environment's ambient irradiance — the `L00` band of its diffuse spherical\n * harmonics — into `out`.\n *\n * @remarks\n * `EnvironmentTextures.sphericalHarmonics` is declared: 36 floats in a stride-4 layout beginning\n * `[L00.rgb, 0, …]` (`index.d.ts`), the same block Babylon Lite writes into the scene uniform buffer\n * as `scene.vSphericalL00` and friends (`lib/scene/scene-ubo-extras.js`, `writeEnvUbo`). So the\n * value ignifx uploads as `ambientColor` is exactly what a shader could read for itself as\n * `scene.vSphericalL00.rgb`, which is the documented alternative for a shader that would rather not\n * declare the uniform. Reaching the slot goes through `./environment.ts`, which is the one place\n * ignifx touches the undeclared `scene._envTextures` field\n * (`docs/architecture/07-rendering.md` §2.5, §8).\n *\n * @param scene - The render scene.\n * @param out - Receives the three linear channels; left untouched when nothing is installed.\n * @returns `true` when an environment supplied harmonics.\n *\n * @internal\n */\nexport function readSceneAmbient(scene: SceneContext, out: Float32Array): boolean {\n const harmonics = readSceneEnvironment(scene)?.sphericalHarmonics;\n if (harmonics === undefined || harmonics.length < 3) {\n return false;\n }\n out[0] = harmonics[0] ?? 0;\n out[1] = harmonics[1] ?? 0;\n out[2] = harmonics[2] ?? 0;\n return true;\n}\n\n/**\n * The subset of this module `src/render/shader-material.ts` reaches through its dynamic `import()`,\n * named so the memo has a type that does not have to be written as `typeof import(…)` (which the\n * `consistent-type-imports` rule forbids).\n *\n * @remarks\n * Assigning the imported module namespace to this type is what checks the two against each other,\n * so a signature that drifts is a compile error rather than a runtime surprise.\n *\n * @internal\n */\nexport interface ShaderMaterialAdapter {\n /** {@link createShaderMaterialFromOptions}. */\n readonly createShaderMaterialFromOptions: (options: ShaderMaterialBuildOptions) => ShaderMaterial;\n /** {@link writeShaderUniform}. */\n readonly writeShaderUniform: (\n material: ShaderMaterial,\n name: string,\n value: number | readonly number[] | Float32Array,\n ) => void;\n /** {@link writeShaderMatrix}. */\n readonly writeShaderMatrix: (material: ShaderMaterial, name: string, value: Float32Array) => void;\n /** {@link writeShaderTexture}. */\n readonly writeShaderTexture: (material: ShaderMaterial, name: string, texture: Texture2D | null) => void;\n /** {@link writeShaderStorageBuffer}. */\n readonly writeShaderStorageBuffer: (material: ShaderMaterial, name: string, buffer: StorageBuffer | null) => void;\n /** {@link resolveFallbackTexture}. */\n readonly resolveFallbackTexture: (\n engine: EngineContext,\n cache: Map<string, Texture2D>,\n fallback: string | null,\n array: boolean,\n ) => Texture2D;\n /** {@link enableShaderUniformCaching}. */\n readonly enableShaderUniformCaching: () => void;\n /** {@link readSceneAmbient}. */\n readonly readSceneAmbient: (scene: SceneContext, out: Float32Array) => boolean;\n}\n"],"mappings":";;;;AAsDA,MAAM,kBAAuF,OAAO,OAAO;CACzG,OAAO;EAAC;EAAK;EAAK;EAAK;CAAG;CAC1B,OAAO;EAAC;EAAG;EAAG;EAAG;CAAG;CACpB,aAAa;EAAC;EAAG;EAAG;EAAG;CAAC;AAC1B,CAAC;;;;;;;;;;;;;;AAoGD,SAAgB,gCAAgC,SAAqD;CACnG,OAAO,qBAAqB;EAC1B,MAAM,QAAQ;EACd,cAAc,QAAQ;EACtB,gBAAgB,QAAQ;EACxB,YAAY,QAAQ;EACpB,UAAU,QAAQ;EAClB,UAAU,QAAQ;EAClB,gBAAgB,QAAQ;EACxB,SAAS,QAAQ;EACjB,uBAAuB,QAAQ;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xD;;;;;;;;;;;;;AAcA,SAAgB,6BAAmC;CACjD,mCAAmC;AACrC;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,iBAAiB,OAAqB,KAA4B;CAChF,MAAM,YAAY,qBAAqB,KAAK,CAAC,EAAE;CAC/C,IAAI,cAAc,KAAA,KAAa,UAAU,SAAS,GAChD,OAAO;CAET,IAAI,KAAK,UAAU,MAAM;CACzB,IAAI,KAAK,UAAU,MAAM;CACzB,IAAI,KAAK,UAAU,MAAM;CACzB,OAAO;AACT"}
@@ -1,4 +1,4 @@
1
- import { o as CoreErrorCode, t as IgnifxError } from "./ignifx-error-CRh89KUJ.js";
1
+ import { o as CoreErrorCode, t as IgnifxError } from "./ignifx-error-RpK-lWwE.js";
2
2
  import { t as Color } from "./color-DrR6GFTd.js";
3
3
  import { n as IGNIFX_UNIFORM_TYPES, r as LITE_SYSTEM_UNIFORM_NAMES, t as IGNIFX_UNIFORM_NAMES } from "./shader-declaration-5q__jycG.js";
4
4
  //#region \0rolldown/runtime.js
@@ -172,7 +172,7 @@ let adapter = null;
172
172
  */
173
173
  async function loadShaderMaterialAdapter() {
174
174
  if (adapter !== null) return;
175
- const loaded = await import("./shader-material-U6BKZ8D1.js");
175
+ const loaded = await import("./shader-material-B6wwFCKB.js");
176
176
  loaded.enableShaderUniformCaching();
177
177
  adapter = loaded;
178
178
  }
@@ -1006,4 +1006,4 @@ function shapeMismatch(declaration, material, expected, actual) {
1006
1006
  //#endregion
1007
1007
  export { shader_material_exports as n, shaderMaterialsOf as t };
1008
1008
 
1009
- //# sourceMappingURL=shader-material-BIG3UDyu.js.map
1009
+ //# sourceMappingURL=shader-material-C4VjLTfV.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"shader-material-BIG3UDyu.js","names":[],"sources":["../src/render/shader-material.ts"],"sourcesContent":["import { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { IgnifxError } from \"../errors/ignifx-error.js\";\nimport { Color } from \"../math/color.js\";\nimport { IGNIFX_UNIFORM_TYPES, IGNIFX_UNIFORM_NAMES, LITE_SYSTEM_UNIFORM_NAMES } from \"./shader-declaration.js\";\nimport type { ShaderAsset } from \"./shader-asset.js\";\nimport type {\n IgnifxUniformName,\n ShaderDeclaration,\n ShaderTextureDeclaration,\n ShaderUniformDeclaration,\n ShaderUniformType,\n} from \"./shader-declaration.js\";\nimport type { ShaderMaterialDefinition } from \"./shader-material-definition.js\";\nimport type { StorageBufferAsset } from \"./storage-buffer-asset.js\";\nimport type { TextureAsset } from \"./texture-asset.js\";\nimport type { App } from \"../app/types.js\";\nimport type { AssetHandle } from \"../assets/types.js\";\nimport type {\n LiteShaderMaterial,\n ShaderMaterialAdapter,\n ShaderMaterialBuildOptions,\n ShaderSamplerEntry,\n ShaderStorageEntry,\n ShaderUniformEntry,\n} from \"../lite/gpu/shader-material.js\";\nimport type { LiteTexture2D } from \"../lite/gpu/texture.js\";\nimport type { ColorLike } from \"../math/types.js\";\nimport type { Disconnect } from \"../signal/signal.js\";\n\n/**\n * The `\"shader\"` material family (`docs/plan/2026-09-terrain-particles-shaders.md` §3.1): a\n * `ShaderAsset` plus the values a material sets on it.\n *\n * Nothing here imports Babylon Lite: {@link toShaderMaterialOptions} is the whole mapping onto the\n * shape `createShaderMaterial` takes, as plain data, and the adapter itself arrives through\n * {@link loadShaderMaterialAdapter} so a project that loads no `.wgsl` never fetches that chunk\n * (`./shader-support.ts`).\n *\n * Two Lite rules shape the design:\n *\n * - A declared sampler must have something bound (error 309), so an unbound declared texture gets\n * the declaration's 1x1 fallback and `setTexture(name, null)` restores it rather than unbinding.\n * - A declared storage buffer must have something bound too (error 310), and `array<T>` has no 1x1\n * equivalent, so such a material is not drawable until `setStorageBuffer` binds one.\n */\n\n/** The uniform names Babylon Lite and ignifx write themselves, which a material may not set. */\nconst ENGINE_UNIFORM_NAMES: readonly string[] = Object.freeze([...LITE_SYSTEM_UNIFORM_NAMES, ...IGNIFX_UNIFORM_NAMES]);\n\n/** How many floats the `PreRender` system's frame buffer holds: direction, colour, ambient. */\nconst FRAME_FLOATS = 9;\n\n/** Where the main light's direction starts inside the frame buffer. */\nconst DIRECTION_OFFSET = 0;\n\n/** Where the main light's colour starts inside the frame buffer. */\nconst LIGHT_COLOR_OFFSET = 3;\n\n/** Where the ambient colour starts inside the frame buffer. */\nconst AMBIENT_OFFSET = 6;\n\n/** How many elements each uniform type holds. */\nconst ELEMENT_COUNTS: Readonly<Record<ShaderUniformType, number>> = Object.freeze({\n f32: 1,\n u32: 1,\n i32: 1,\n \"vec2<f32>\": 2,\n \"vec3<f32>\": 3,\n \"vec4<f32>\": 4,\n \"mat4x4<f32>\": 16,\n});\n\n/**\n * The premultiplied-alpha blend state, which Babylon Lite's two named modes cannot express.\n *\n * @remarks\n * `blendMode: \"alpha\"` compiles `srcFactor: \"src-alpha\"` (`lib/material/shader/shader-pipeline.js`),\n * which multiplies the source colour by its alpha a second time. A premultiplied surface has\n * already done that, so it needs `srcFactor: \"one\"` — the state that lets additive and over-blended\n * particles share one draw.\n */\nconst PREMULTIPLIED_BLEND: GPUBlendState = Object.freeze({\n color: Object.freeze({ srcFactor: \"one\", dstFactor: \"one-minus-src-alpha\", operation: \"add\" }),\n alpha: Object.freeze({ srcFactor: \"one\", dstFactor: \"one-minus-src-alpha\", operation: \"add\" }),\n});\n\n/**\n * Maps a shader file's declaration and a material's `define` overrides onto the shape\n * `createShaderMaterial` takes.\n *\n * @remarks\n * Pure data in, pure data out, so every mapping rule is asserted headlessly:\n *\n * - `blend opaque` leaves blending off; `alpha` and `additive` are Lite's two named modes;\n * `premultiplied` supplies an explicit `GPUBlendState`, because Lite's `\"alpha\"` mode multiplies\n * by alpha a second time.\n * - `depthWrite` is passed explicitly, because the declaration already resolved Lite's\n * \"blended defaults to off unless stated\" rule.\n * - `depthTest off` becomes `depthCompare: \"always\"`; `depthTest on` passes `null`, which leaves\n * Lite's reverse-Z default in place.\n * - `instancing matrices` and `matrices-colors` differ only in `useThinInstanceColors`; which\n * pipeline layout a mesh draws with is Lite's decision at build time, from whether the mesh has a\n * thin-instance colour stream.\n * - A colour uniform's declared default is sRGB and is decoded here, which is the one place the\n * conversion happens for defaults.\n *\n * @param name - The material's name, for GPU debug labels.\n * @param source - The whole `.wgsl` file.\n * @param declaration - What the file's pragmas declared.\n * @param uniforms - The initial value of every custom uniform, keyed by name, already **linear**.\n * @param defines - The resolved `define` values.\n * @returns The options.\n *\n * @internal\n */\nexport function toShaderMaterialOptions(\n name: string,\n source: string,\n declaration: ShaderDeclaration,\n uniforms: ReadonlyMap<string, Float32Array>,\n defines: Readonly<Record<string, boolean | number>>,\n): ShaderMaterialBuildOptions {\n const entries: ShaderUniformEntry[] = [];\n // `for…of` rather than an indexed loop: this runs once per material build, not per frame, and the\n // iterator yields the element type rather than `T | undefined`.\n for (const system of declaration.system) {\n entries.push(system);\n }\n for (const ignifx of declaration.ignifx) {\n const type = IGNIFX_UNIFORM_TYPES[ignifx];\n entries.push({ name: ignifx, type, defaultValue: zeros(ELEMENT_COUNTS[type]) });\n }\n for (const uniform of declaration.uniforms) {\n entries.push({\n name: uniform.name,\n type: uniform.type,\n defaultValue: Array.from(uniforms.get(uniform.name) ?? uniformStore(uniform)),\n });\n }\n const samplers: ShaderSamplerEntry[] = [];\n for (const texture of declaration.textures) {\n samplers.push({ name: texture.name, viewDimension: texture.array ? \"2d-array\" : \"2d\" });\n }\n const storageBuffers: ShaderStorageEntry[] = [];\n for (const storage of declaration.storage) {\n storageBuffers.push({ name: storage.name, type: storage.type });\n }\n const pipeline = declaration.pipeline;\n const blended = pipeline.blend !== \"opaque\";\n return {\n name,\n source,\n attributes: declaration.attributes,\n uniforms: entries,\n samplers,\n storageBuffers,\n defines,\n useThinInstanceColors: pipeline.instancing === \"matrices-colors\",\n needAlphaBlending: blended,\n blendMode: pipeline.blend === \"additive\" ? \"additive\" : \"alpha\",\n blend: pipeline.blend === \"premultiplied\" ? PREMULTIPLIED_BLEND : null,\n transmissive: pipeline.transmissive,\n backFaceCulling: pipeline.cull === \"back\",\n depthWrite: pipeline.depthWrite,\n depthCompare: pipeline.depthTest ? null : \"always\",\n };\n}\n\n/** The dynamically imported Babylon Lite adapter, memoised for the process. */\nlet adapter: ShaderMaterialAdapter | null = null;\n\n/**\n * Loads the custom-WGSL half of the Babylon Lite adapter, once per process.\n *\n * @remarks\n * The shader **loader** awaits this before it hands back a `ShaderAsset`, which is what makes\n * {@link shaderMaterialAdapter} safe to call from the synchronous material builders. Loading it also\n * turns on Lite's cached uniform serialization plans, which is what makes the per-frame `time`\n * upload rewrite only the slots that changed.\n *\n * @returns A promise that resolves once the adapter is in place.\n *\n * @internal\n */\nexport async function loadShaderMaterialAdapter(): Promise<void> {\n if (adapter !== null) {\n return;\n }\n const loaded = await import(\"../lite/gpu/shader-material.js\");\n loaded.enableShaderUniformCaching();\n // The assignment is what checks `ShaderMaterialAdapter` against the module it stands for.\n adapter = loaded;\n}\n\n/**\n * The adapter, if it has been loaded.\n *\n * @returns The module, or `null` before any `.wgsl` has been loaded.\n *\n * @internal\n */\nexport function shaderMaterialAdapter(): ShaderMaterialAdapter | null {\n return adapter;\n}\n\n/**\n * The adapter, or the failure a material built before the `.wgsl` loader ran produces.\n *\n * @param shader - The shader being built, for the message.\n * @returns The adapter.\n * @throws IgnifxError with code `IGX-0715` when the chunk has not been loaded.\n */\nfunction requireShaderMaterialAdapter(shader: ShaderAsset): ShaderMaterialAdapter {\n const module = shaderMaterialAdapter();\n if (module === null) {\n throw new IgnifxError(\n CoreErrorCode.shaderCompileFailed,\n `${shader.address} cannot be built because the shader adapter has not been loaded.`,\n {\n context: { asset: shader.address, message: \"adapter not loaded\" },\n hint: \"Load the .wgsl through app.assets, which is what loads the adapter.\",\n },\n );\n }\n return module;\n}\n\n/**\n * The per-app state the shader material family needs: the 1x1 fallback textures declared samplers\n * fall back to, and the list of live materials whose per-frame ignifx uniforms have to be written.\n *\n * @remarks\n * It hangs off the app through a lazily created `WeakMap` rather than a service, so a shader\n * material works whether or not an extension registered anything, and two apps in one process keep\n * separate state (`CONSTITUTION.md` §3.6).\n *\n * @internal\n */\nexport class ShaderMaterialRegistry {\n readonly #app: App;\n\n /** Live materials that declare at least one ignifx uniform, in no particular order. */\n readonly #animated: ShaderMaterialState[] = [];\n\n readonly #fallbacks = new Map<string, LiteTexture2D>();\n\n /**\n * Creates the registry.\n *\n * @param app - The app it belongs to.\n */\n constructor(app: App) {\n this.#app = app;\n }\n\n /**\n * The materials the `PreRender` uniform system has to write this frame.\n *\n * @returns The list; the registry's own array, iterated without copying.\n */\n get animated(): readonly ShaderMaterialState[] {\n return this.#animated;\n }\n\n /**\n * Starts writing a material's ignifx uniforms every frame.\n *\n * @param state - The material.\n */\n add(state: ShaderMaterialState): void {\n if (!this.#animated.includes(state)) {\n this.#animated.push(state);\n }\n }\n\n /**\n * Stops writing a material's ignifx uniforms.\n *\n * @param state - The material.\n */\n remove(state: ShaderMaterialState): void {\n const index = this.#animated.indexOf(state);\n if (index < 0) {\n return;\n }\n const last = this.#animated.pop();\n if (last !== undefined && index < this.#animated.length) {\n this.#animated[index] = last;\n }\n }\n\n /**\n * The 1x1 texture a declared-but-unbound sampler is filled with, created on first use and shared\n * for the life of the app.\n *\n * @param declaration - The sampler declaration, for its `default` and `array` flags.\n * @returns The texture, or `null` under a headless app or before the adapter has loaded.\n */\n fallbackTexture(declaration: ShaderTextureDeclaration): LiteTexture2D | null {\n const module = shaderMaterialAdapter();\n if (module === null || this.#app.isHeadless) {\n return null;\n }\n return module.resolveFallbackTexture(\n this.#app.lite.engine,\n this.#fallbacks,\n declaration.fallback,\n declaration.array,\n );\n }\n}\n\n/** The per-app registries, created on first use so module scope allocates nothing. */\nlet registries: WeakMap<App, ShaderMaterialRegistry> | null = null;\n\n/**\n * The shader material state of one app.\n *\n * @param app - The app.\n * @returns Its registry, created on first use.\n *\n * @internal\n */\nexport function shaderMaterialsOf(app: App): ShaderMaterialRegistry {\n const map = (registries ??= new WeakMap<App, ShaderMaterialRegistry>());\n const existing = map.get(app);\n if (existing !== undefined) {\n return existing;\n }\n const created = new ShaderMaterialRegistry(app);\n map.set(app, created);\n return created;\n}\n\n/**\n * One live `\"shader\"` material: the Babylon Lite material, the CPU-side copy of every value written\n * to it, and the bindings it has to replay when the shader file or a `define` changes.\n *\n * @remarks\n * `MaterialAsset` owns one of these and forwards `setUniform`, `getUniform`, `setTexture`,\n * `setDefine`, and `setStorageBuffer` to it. It is `@internal` because the public surface is the\n * material's methods, not this object.\n *\n * @internal\n */\nexport class ShaderMaterialState {\n /** The definition the material was built from; a clone replays it. */\n readonly definition: ShaderMaterialDefinition;\n\n readonly #app: App;\n\n readonly #values = new Map<string, Float32Array>();\n\n readonly #textures = new Map<string, AssetHandle<TextureAsset> | null>();\n\n readonly #storage = new Map<string, AssetHandle<StorageBufferAsset> | null>();\n\n readonly #defines = new Map<string, boolean | number>();\n\n /** The last light values written, so an unchanged light costs no upload. */\n readonly #light = new Float32Array(FRAME_FLOATS);\n\n /** The ignifx-provided uniforms the file declares, paired with their stores. */\n readonly #engineSlots: { readonly name: IgnifxUniformName; readonly store: Float32Array }[] = [];\n\n #shader: ShaderAsset;\n\n #material: LiteShaderMaterial;\n\n /**\n * The adapter every write goes through. Captured once, because a state can only be built after\n * {@link buildLiteShaderMaterial} has proved the chunk is in memory.\n */\n readonly #adapter: ShaderMaterialAdapter;\n\n #hasLight = false;\n\n #hasWarnedAboutLight = false;\n\n #onReplaced: Disconnect | null = null;\n\n /**\n * Builds the material. Use {@link buildShaderMaterialState}.\n *\n * @param app - The app that owns the engine, the log, and the registry.\n * @param shader - The shader the material sets values on.\n * @param definition - The declaration.\n * @param material - The already-built Babylon Lite material.\n * @param liteAdapter - The custom-WGSL adapter every write goes through.\n */\n constructor(\n app: App,\n shader: ShaderAsset,\n definition: ShaderMaterialDefinition,\n material: LiteShaderMaterial,\n liteAdapter: ShaderMaterialAdapter,\n ) {\n this.#app = app;\n this.#adapter = liteAdapter;\n this.#shader = shader;\n this.definition = definition;\n this.#material = material;\n // Not zeros: a light really at the origin pointing along +Z would then never be written.\n this.#light.fill(Number.NaN);\n }\n\n /**\n * The shader the material is values for.\n *\n * @returns The shader asset, which a hot reload replaces.\n */\n get shader(): ShaderAsset {\n return this.#shader;\n }\n\n /**\n * The Babylon Lite material, which `setDefine` and a hot reload replace with a new object.\n *\n * @returns The material.\n */\n get material(): LiteShaderMaterial {\n return this.#material;\n }\n\n /**\n * Whether the shader declares any ignifx-provided uniform, and so needs a per-frame write.\n *\n * @returns `true` when the `PreRender` system has work to do for this material.\n */\n get isAnimated(): boolean {\n return this.#shader.declaration.ignifx.length > 0;\n }\n\n /**\n * Whether every declared storage buffer has a buffer bound, which is what Babylon Lite needs\n * before the material can be drawn at all.\n *\n * @returns `true` when the material is drawable.\n */\n get isDrawable(): boolean {\n const declared = this.#shader.declaration.storage;\n for (let index = 0; index < declared.length; index += 1) {\n const name = declared[index]?.name;\n if (name !== undefined && (this.#storage.get(name) ?? null) === null) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Writes a declared uniform.\n *\n * @param name - The uniform's name.\n * @param value - The value: a number, a numeric array, or — for a `color` uniform — an sRGB\n * colour, which is uploaded linear.\n * @throws IgnifxError with code `IGX-0712` when the shader declares no such uniform or the engine\n * writes it, or `IGX-0713` when the value has the wrong shape.\n */\n setUniform(name: string, value: number | readonly number[] | Float32Array | ColorLike): void {\n const declaration = this.#writableUniform(name);\n const store = this.#values.get(name) ?? uniformStore(declaration);\n this.#values.set(name, store);\n writeUniformValue(store, declaration, value, this.definition.name);\n this.#write(name, store);\n }\n\n /**\n * Reads the current CPU-side value of a declared uniform.\n *\n * @param name - The uniform's name.\n * @param out - Receives the value for a vector or matrix uniform; a fresh array is allocated when\n * it is omitted.\n * @returns The number for a scalar uniform, or the filled array.\n * @throws IgnifxError with code `IGX-0712` when the shader declares no such uniform, or\n * `IGX-0713` when `out` is too short.\n */\n getUniform(name: string, out?: Float32Array): number | Float32Array {\n const declaration = this.#uniform(name);\n const store = this.#values.get(name) ?? uniformStore(declaration);\n this.#values.set(name, store);\n if (store.length === 1 && out === undefined) {\n return store[0] ?? 0;\n }\n if (out === undefined) {\n return Float32Array.from(store);\n }\n if (out.length < store.length) {\n throw new IgnifxError(\n CoreErrorCode.shaderValueMismatch,\n `${name} on ${this.definition.name} expects ${String(store.length)} floats, not ${String(out.length)}.`,\n {\n context: { name, material: this.definition.name, expected: store.length, actual: out.length },\n hint: \"Pass an out array at least as long as the uniform's element count.\",\n },\n );\n }\n out.set(store);\n return out;\n }\n\n /**\n * Binds a texture to a declared sampler, or restores the declaration's fallback.\n *\n * @param name - The sampler's name.\n * @param texture - The texture, or `null` for the declared 1x1 fallback.\n * @throws IgnifxError with code `IGX-0712` when the shader declares no such sampler.\n */\n setTexture(name: string, texture: AssetHandle<TextureAsset> | null): void {\n const declaration = this.#texture(name);\n this.#textures.set(name, texture);\n this.#bindTexture(declaration, texture);\n }\n\n /**\n * Binds a storage buffer to a declared binding.\n *\n * @param name - The binding's name.\n * @param buffer - The buffer, or `null` to unbind. A material with an unbound declared storage\n * buffer cannot be drawn.\n * @throws IgnifxError with code `IGX-0712` when the shader declares no such storage buffer.\n */\n setStorageBuffer(name: string, buffer: AssetHandle<StorageBufferAsset> | null): void {\n const declared = this.#shader.declaration.storage;\n let found = false;\n for (let index = 0; index < declared.length; index += 1) {\n if (declared[index]?.name === name) {\n found = true;\n break;\n }\n }\n if (!found) {\n throw this.#unknownBinding(name, \"storage buffer\");\n }\n this.#storage.set(name, buffer);\n this.#bindStorage(name, buffer);\n }\n\n /**\n * Overrides a declared `define` and rebuilds the Babylon Lite material, because a define is a\n * WGSL `const` baked into the compiled pipeline.\n *\n * @remarks\n * The rebuild replaces the Lite material **object**. `MeshRenderer` re-reads\n * `MaterialAsset.lite.material` every `PreRender` and writes it onto its mesh when it changed,\n * and Lite's `mesh.material` setter enqueues a material swap that the next frame drains\n * (`lib/scene/mesh-scene-registry.js`), so the new pipeline is picked up on the following frame\n * with no explicit topology flag.\n *\n * @param name - The define's name.\n * @param value - The new value.\n * @throws IgnifxError with code `IGX-0712` when the shader declares no such define.\n */\n setDefine(name: string, value: boolean | number): void {\n const declared = this.#shader.declaration.defines;\n let fileValue: boolean | number | undefined;\n for (let index = 0; index < declared.length; index += 1) {\n const definition = declared[index];\n if (definition?.name === name) {\n fileValue = definition.value;\n break;\n }\n }\n if (fileValue === undefined) {\n throw this.#unknownBinding(name, \"define\");\n }\n // Compared against the value in force, not against the override map, so re-setting what the\n // file already declares is not a pipeline rebuild.\n if ((this.#defines.get(name) ?? fileValue) === value) {\n return;\n }\n this.#defines.set(name, value);\n this.#rebuild(this.#shader);\n }\n\n /**\n * Writes this frame's ignifx uniforms. The `PreRender` system calls it.\n *\n * @param time - Scaled seconds since `app.start()`.\n * @param unscaledTime - Unscaled seconds since `app.start()`.\n * @param deltaTime - Scaled seconds since the previous frame.\n * @param light - Nine floats: the main light's world direction, its linear colour times its\n * intensity, and the ambient colour.\n * @param hasLight - Whether an enabled directional light supplied the first six.\n */\n writeFrameUniforms(\n time: number,\n unscaledTime: number,\n deltaTime: number,\n light: Float32Array,\n hasLight: boolean,\n ): void {\n let lightChanged = this.#hasLight !== hasLight;\n this.#hasLight = hasLight;\n for (let index = 0; index < this.#light.length; index += 1) {\n if (this.#light[index] !== light[index]) {\n this.#light[index] = light[index] ?? 0;\n lightChanged = true;\n }\n }\n const slots = this.#engineSlots;\n for (let index = 0; index < slots.length; index += 1) {\n const slot = slots[index];\n if (slot === undefined) {\n continue;\n }\n switch (slot.name) {\n case \"time\":\n this.#writeScalar(slot.name, slot.store, time);\n break;\n case \"unscaledTime\":\n this.#writeScalar(slot.name, slot.store, unscaledTime);\n break;\n case \"deltaTime\":\n this.#writeScalar(slot.name, slot.store, deltaTime);\n break;\n case \"mainLightDirection\":\n if (lightChanged) {\n this.#writeTriple(slot.name, slot.store, light, DIRECTION_OFFSET);\n }\n break;\n case \"mainLightColor\":\n if (lightChanged) {\n this.#writeTriple(slot.name, slot.store, light, LIGHT_COLOR_OFFSET);\n }\n break;\n case \"ambientColor\":\n if (lightChanged) {\n this.#writeTriple(slot.name, slot.store, light, AMBIENT_OFFSET);\n }\n break;\n default:\n break;\n }\n }\n if (!hasLight && !this.#hasWarnedAboutLight && this.#needsLight()) {\n this.#hasWarnedAboutLight = true;\n const declared = this.#engineSlots.map((slot) => slot.name).join(\", \");\n this.#app.log.warnOnce(\n `${CoreErrorCode.shaderLightUniformWithoutLight}:${this.definition.name}`,\n `${CoreErrorCode.shaderLightUniformWithoutLight}: ${this.definition.name} declares ${declared}, ` +\n \"but this world has no enabled directional light; zeros are uploaded.\",\n );\n }\n }\n\n /**\n * Replays the definition's values, textures, defines, and storage bindings onto a freshly built\n * Babylon Lite material, and connects the hot-reload hook. Called once, by\n * {@link buildShaderMaterialState}.\n *\n * @param textures - The texture handles the loader resolved, in declaration order.\n */\n initialise(textures: readonly AssetHandle<TextureAsset>[]): void {\n const declaration = this.#shader.declaration;\n for (const name of Object.keys(this.definition.defines)) {\n const value = this.definition.defines[name];\n if (value !== undefined) {\n this.#defines.set(name, value);\n }\n }\n for (const name of Object.keys(this.definition.values)) {\n const value = this.definition.values[name];\n if (value !== undefined) {\n this.setUniform(name, value);\n }\n }\n const addresses = Object.keys(this.definition.textures);\n for (let index = 0; index < declaration.textures.length; index += 1) {\n const declared = declaration.textures[index];\n if (declared === undefined) {\n continue;\n }\n const slot = addresses.indexOf(declared.name);\n const handle = slot < 0 ? undefined : textures[slot];\n this.#textures.set(declared.name, handle ?? null);\n this.#bindTexture(declared, handle ?? null);\n }\n this.#refreshEngineSlots();\n if (this.isAnimated) {\n shaderMaterialsOf(this.#app).add(this);\n }\n const source = this.#app.assets.get<ShaderAsset>(this.definition.shader);\n this.#onReplaced =\n source?.onReplaced.connect((value: ShaderAsset): void => {\n this.#reload(value);\n }) ?? null;\n }\n\n /**\n * Stops the per-frame writes and the hot-reload hook. The `material` asset type's `unload` runs\n * it when the last holder releases the material.\n */\n dispose(): void {\n this.#onReplaced?.();\n this.#onReplaced = null;\n shaderMaterialsOf(this.#app).remove(this);\n }\n\n /**\n * Rebuilds the Lite material for a replaced shader file, keeping the previous one on failure.\n *\n * @param shader - The re-parsed shader asset.\n */\n #reload(shader: ShaderAsset): void {\n try {\n this.#rebuild(shader);\n this.#shader = shader;\n } catch (error: unknown) {\n this.#app.onError.emit({\n error: new IgnifxError(\n CoreErrorCode.shaderCompileFailed,\n `${shader.address} failed to rebuild; the previous material stays in use. ${String(error)}`,\n {\n context: { asset: shader.address, message: String(error) },\n cause: error,\n hint: \"Fix the shader file; the running material is the last one that built.\",\n },\n ),\n source: \"asset\",\n phase: null,\n entity: null,\n component: null,\n });\n }\n }\n\n /**\n * Builds a new Lite material from a declaration and replays every binding that still exists.\n *\n * @param shader - The shader to build from.\n */\n #rebuild(shader: ShaderAsset): void {\n const declaration = shader.declaration;\n const previous = this.#shader;\n // The Lite material is replaced halfway through, so a failure has to put the old one back or the\n // material would be left drawing a new program against the old declaration's bindings.\n const previousMaterial = this.#material;\n const previousValues = new Map(this.#values);\n this.#shader = shader;\n try {\n const values = new Map<string, Float32Array>();\n for (let index = 0; index < declaration.uniforms.length; index += 1) {\n const uniform = declaration.uniforms[index];\n if (uniform === undefined) {\n continue;\n }\n const kept = this.#values.get(uniform.name);\n values.set(\n uniform.name,\n kept !== undefined && kept.length === ELEMENT_COUNTS[uniform.type] ? kept : uniformStore(uniform),\n );\n }\n this.#material = buildLiteShaderMaterial(this.definition.name, shader, values, this.#resolveDefines(shader));\n this.#values.clear();\n for (const [name, store] of values) {\n this.#values.set(name, store);\n }\n this.#rebind(declaration);\n } catch (error: unknown) {\n this.#shader = previous;\n this.#material = previousMaterial;\n this.#values.clear();\n for (const [name, store] of previousValues) {\n this.#values.set(name, store);\n }\n throw error;\n }\n }\n\n /**\n * Re-applies the texture and storage bindings that the new declaration still has, dropping the\n * ones it no longer declares.\n *\n * @param declaration - The new declaration.\n */\n #rebind(declaration: ShaderDeclaration): void {\n const textures = new Map(this.#textures);\n this.#textures.clear();\n for (let index = 0; index < declaration.textures.length; index += 1) {\n const declared = declaration.textures[index];\n if (declared === undefined) {\n continue;\n }\n const handle = textures.get(declared.name) ?? null;\n this.#textures.set(declared.name, handle);\n this.#bindTexture(declared, handle);\n }\n const storage = new Map(this.#storage);\n this.#storage.clear();\n for (let index = 0; index < declaration.storage.length; index += 1) {\n const name = declaration.storage[index]?.name;\n if (name === undefined) {\n continue;\n }\n const handle = storage.get(name) ?? null;\n this.#storage.set(name, handle);\n this.#bindStorage(name, handle);\n }\n this.#refreshEngineSlots();\n const registry = shaderMaterialsOf(this.#app);\n if (this.isAnimated) {\n registry.add(this);\n } else {\n registry.remove(this);\n }\n this.#light.fill(Number.NaN);\n }\n\n /**\n * The declared `define` values with this material's overrides applied.\n *\n * @param shader - The shader whose declaration supplies the defaults.\n * @returns The resolved values.\n */\n #resolveDefines(shader: ShaderAsset): Readonly<Record<string, boolean | number>> {\n const resolved: Record<string, boolean | number> = {};\n const declared = shader.declaration.defines;\n for (let index = 0; index < declared.length; index += 1) {\n const define = declared[index];\n if (define === undefined) {\n continue;\n }\n resolved[define.name] = this.#defines.get(define.name) ?? define.value;\n }\n return resolved;\n }\n\n /**\n * Binds a texture, or the declaration's fallback when there is none.\n *\n * @param declaration - The sampler declaration.\n * @param handle - The texture handle, or `null`.\n */\n #bindTexture(declaration: ShaderTextureDeclaration, handle: AssetHandle<TextureAsset> | null): void {\n const loaded = handle?.state === \"loaded\" ? handle.value.lite.texture : null;\n this.#adapter.writeShaderTexture(\n this.#material,\n declaration.name,\n loaded ?? shaderMaterialsOf(this.#app).fallbackTexture(declaration),\n );\n }\n\n /**\n * Binds a storage buffer.\n *\n * @param name - The binding's name.\n * @param handle - The buffer handle, or `null`.\n */\n #bindStorage(name: string, handle: AssetHandle<StorageBufferAsset> | null): void {\n this.#adapter.writeShaderStorageBuffer(\n this.#material,\n name,\n handle?.state === \"loaded\" ? handle.value.lite.buffer : null,\n );\n }\n\n /**\n * Writes one CPU-side value through to Babylon Lite.\n *\n * @param name - The uniform's name.\n * @param store - The value.\n */\n #write(name: string, store: Float32Array): void {\n this.#adapter.writeShaderUniform(this.#material, name, store);\n }\n\n /**\n * Writes one engine-owned scalar uniform through its CPU-side store.\n *\n * @param name - The uniform's name.\n * @param store - The store, which is also what `getUniform` reads.\n * @param value - The value.\n */\n #writeScalar(name: string, store: Float32Array, value: number): void {\n store[0] = value;\n this.#adapter.writeShaderUniform(this.#material, name, store);\n }\n\n /**\n * Writes three floats of an engine-owned `vec3<f32>` uniform, without allocating.\n *\n * @param name - The uniform's name.\n * @param store - The store, which is also what `getUniform` reads.\n * @param source - The nine-float frame buffer.\n * @param offset - Where the triple starts inside it.\n */\n #writeTriple(name: string, store: Float32Array, source: Float32Array, offset: number): void {\n store.set(source.subarray(offset, offset + 3));\n this.#adapter.writeShaderUniform(this.#material, name, store);\n }\n\n /**\n * Resolves the CPU-side store of every ignifx-provided uniform the file declares, so the\n * per-frame write is an indexed loop with no name lookup (coding standards §7).\n */\n #refreshEngineSlots(): void {\n const slots = this.#engineSlots;\n slots.length = 0;\n const declared = this.#shader.declaration.ignifx;\n for (let index = 0; index < declared.length; index += 1) {\n const name = declared[index];\n if (name === undefined) {\n continue;\n }\n const count = ELEMENT_COUNTS[IGNIFX_UNIFORM_TYPES[name]];\n const store = this.#values.get(name) ?? new Float32Array(count);\n this.#values.set(name, store);\n slots.push({ name, store });\n }\n }\n\n /**\n * Whether the shader declares a uniform that needs a directional light.\n *\n * @returns `true` when `mainLightDirection` or `mainLightColor` is declared.\n */\n #needsLight(): boolean {\n const declared = this.#shader.declaration.ignifx;\n for (let index = 0; index < declared.length; index += 1) {\n const name = declared[index];\n if (name === \"mainLightDirection\" || name === \"mainLightColor\") {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Looks a custom uniform declaration up.\n *\n * @param name - The uniform's name.\n * @returns The declaration.\n * @throws IgnifxError with code `IGX-0712`.\n */\n #uniform(name: string): ShaderUniformDeclaration {\n const custom = this.#customUniform(name);\n if (custom !== null) {\n return custom;\n }\n const engine = this.#engineUniform(name);\n if (engine !== null) {\n return engine;\n }\n throw this.#unknownBinding(name, \"uniform\");\n }\n\n /**\n * Looks a custom uniform declaration up, refusing the ones the engine writes.\n *\n * @param name - The uniform's name.\n * @returns The declaration.\n * @throws IgnifxError with code `IGX-0712`.\n */\n #writableUniform(name: string): ShaderUniformDeclaration {\n const custom = this.#customUniform(name);\n if (custom !== null) {\n return custom;\n }\n if (ENGINE_UNIFORM_NAMES.includes(name)) {\n throw new IgnifxError(\n CoreErrorCode.unknownShaderBinding,\n `${name} on ${this.definition.name} is written by the engine every frame and cannot be set.`,\n {\n context: { material: this.definition.name, name },\n hint: \"System uniforms come from Babylon Lite and the ignifx uniforms from the PreRender system.\",\n },\n );\n }\n throw this.#unknownBinding(name, \"uniform\");\n }\n\n /**\n * The file's own declaration of a uniform, if it declares one by that name.\n *\n * @param name - The uniform's name.\n * @returns The declaration, or `null`.\n */\n #customUniform(name: string): ShaderUniformDeclaration | null {\n const declared = this.#shader.declaration.uniforms;\n for (let index = 0; index < declared.length; index += 1) {\n const uniform = declared[index];\n if (uniform !== undefined && uniform.name === name) {\n return uniform;\n }\n }\n return null;\n }\n\n /**\n * The synthetic declaration of an ignifx-provided uniform the file declared, so `getUniform` can\n * read back what the `PreRender` system wrote.\n *\n * @param name - The uniform's name.\n * @returns The declaration, or `null` when the file declares no such engine uniform.\n */\n #engineUniform(name: string): ShaderUniformDeclaration | null {\n const declared = this.#shader.declaration.ignifx;\n for (let index = 0; index < declared.length; index += 1) {\n const ignifx = declared[index];\n if (ignifx !== undefined && ignifx === name) {\n return {\n name: ignifx,\n type: IGNIFX_UNIFORM_TYPES[ignifx],\n defaultValue: zeros(ELEMENT_COUNTS[IGNIFX_UNIFORM_TYPES[ignifx]]),\n color: false,\n range: null,\n step: null,\n tooltip: null,\n };\n }\n }\n return null;\n }\n\n /**\n * Looks a sampler declaration up.\n *\n * @param name - The sampler's name.\n * @returns The declaration.\n * @throws IgnifxError with code `IGX-0712`.\n */\n #texture(name: string): ShaderTextureDeclaration {\n const declared = this.#shader.declaration.textures;\n for (let index = 0; index < declared.length; index += 1) {\n const texture = declared[index];\n if (texture !== undefined && texture.name === name) {\n return texture;\n }\n }\n throw this.#unknownBinding(name, \"texture\");\n }\n\n /**\n * Builds the `IGX-0712` failure an undeclared binding name produces.\n *\n * @param name - The name that was asked for.\n * @param what - What kind of binding was expected.\n * @returns The error to throw.\n */\n #unknownBinding(name: string, what: string): IgnifxError {\n return new IgnifxError(\n CoreErrorCode.unknownShaderBinding,\n `${this.definition.name} declares no ${what} named ${name}.`,\n {\n context: { material: this.definition.name, name },\n hint: `Declare it in ${this.#shader.address} with an // @ignifx ${what} pragma.`,\n },\n );\n }\n}\n\n/**\n * Builds the live state of a `\"shader\"` material: the Babylon Lite material, then every value,\n * texture, and define the definition names.\n *\n * @param app - The app that owns the engine, the log, and the registry.\n * @param shader - The shader the material sets values on.\n * @param definition - The declaration.\n * @param textures - The texture handles the loader resolved, in the order the definition's\n * `textures` record names them.\n * @returns The state.\n * @throws IgnifxError with code `IGX-0715` when the adapter has not been loaded, `IGX-0712` for an\n * undeclared value or define name, or `IGX-0713` for a value of the wrong shape.\n *\n * @internal\n */\nexport function buildShaderMaterialState(\n app: App,\n shader: ShaderAsset,\n definition: ShaderMaterialDefinition,\n textures: readonly AssetHandle<TextureAsset>[],\n): ShaderMaterialState {\n const defines: Record<string, boolean | number> = {};\n const declared = shader.declaration.defines;\n for (let index = 0; index < declared.length; index += 1) {\n const define = declared[index];\n if (define !== undefined) {\n defines[define.name] = definition.defines[define.name] ?? define.value;\n }\n }\n for (const name of Object.keys(definition.defines)) {\n if (!(name in defines)) {\n throw new IgnifxError(\n CoreErrorCode.unknownShaderBinding,\n `${definition.name} declares no define named ${name}.`,\n {\n context: { material: definition.name, name },\n hint: `Declare it in ${shader.address} with an // @ignifx define pragma.`,\n },\n );\n }\n }\n const material = buildLiteShaderMaterial(definition.name, shader, new Map(), defines);\n const state = new ShaderMaterialState(app, shader, definition, material, requireShaderMaterialAdapter(shader));\n state.initialise(textures);\n return state;\n}\n\n/**\n * Builds the Babylon Lite material a declaration describes, through the dynamically loaded adapter.\n *\n * @param name - The material's name.\n * @param shader - The shader.\n * @param values - Current custom uniform values to seed the declaration's defaults with.\n * @param defines - The resolved `define` values.\n * @returns The Lite material.\n * @throws IgnifxError with code `IGX-0715` when the adapter has not been loaded yet.\n */\nfunction buildLiteShaderMaterial(\n name: string,\n shader: ShaderAsset,\n values: ReadonlyMap<string, Float32Array>,\n defines: Readonly<Record<string, boolean | number>>,\n): LiteShaderMaterial {\n return requireShaderMaterialAdapter(shader).createShaderMaterialFromOptions(\n toShaderMaterialOptions(name, shader.source, shader.declaration, values, defines),\n );\n}\n\n/**\n * A number, or an array of that many zeros, matching what a uniform of that arity starts at.\n *\n * @param count - How many elements the uniform holds.\n * @returns The zero value.\n */\nfunction zeros(count: number): number | readonly number[] {\n if (count === 1) {\n return 0;\n }\n const values: number[] = [];\n for (let index = 0; index < count; index += 1) {\n values.push(0);\n }\n return values;\n}\n\n/**\n * A fresh CPU-side store for one uniform, filled with its declared default — **linear** for a\n * colour, because that is what the GPU reads.\n *\n * @param declaration - The uniform declaration.\n * @returns The store.\n */\nfunction uniformStore(declaration: ShaderUniformDeclaration): Float32Array {\n const count = ELEMENT_COUNTS[declaration.type];\n const store = new Float32Array(count);\n const value = declaration.defaultValue;\n if (typeof value === \"number\") {\n store[0] = value;\n } else {\n store.set(value.slice(0, count));\n }\n if (declaration.color) {\n decodeColourComponents(store);\n }\n return store;\n}\n\n/**\n * Writes a caller's value into a uniform's CPU-side store, checking its shape and decoding a\n * colour.\n *\n * @param store - The store to write into.\n * @param declaration - The uniform declaration.\n * @param value - The caller's value.\n * @param material - The material's name, for diagnostics.\n * @throws IgnifxError with code `IGX-0713` when the value's shape does not match the declared type.\n */\nfunction writeUniformValue(\n store: Float32Array,\n declaration: ShaderUniformDeclaration,\n value: number | readonly number[] | Float32Array | ColorLike,\n material: string,\n): void {\n const count = store.length;\n if (typeof value === \"number\") {\n if (count !== 1) {\n throw shapeMismatch(declaration, material, `${declaration.type} (${String(count)} floats)`, \"a single number\");\n }\n store[0] = value;\n return;\n }\n if (isColorLike(value)) {\n if (count !== 3 && count !== 4) {\n throw shapeMismatch(declaration, material, `${declaration.type} (${String(count)} floats)`, \"a colour\");\n }\n store[0] = Color.srgbToLinear(value.r);\n store[1] = Color.srgbToLinear(value.g);\n store[2] = Color.srgbToLinear(value.b);\n if (count === 4) {\n store[3] = value.a;\n }\n return;\n }\n if (value.length !== count) {\n throw shapeMismatch(\n declaration,\n material,\n `${declaration.type} (${String(count)} floats)`,\n `${String(value.length)} floats`,\n );\n }\n store.set(value instanceof Float32Array ? value : Float32Array.from(value));\n if (declaration.color) {\n decodeColourComponents(store);\n }\n}\n\n/**\n * Decodes a store's first three components from sRGB to linear, in place.\n *\n * @remarks\n * A `subarray` view and `map` rather than three indexed reads: a `Float32Array` element is typed\n * `number | undefined` under `noUncheckedIndexedAccess`, and `map` hands the callback a `number`.\n * It runs on a value write, never per frame.\n *\n * @param store - The store, at least three floats long.\n */\nfunction decodeColourComponents(store: Float32Array): void {\n const rgb = store.subarray(0, 3);\n rgb.set(rgb.map((component) => Color.srgbToLinear(component)));\n}\n\n/**\n * Whether a value is an sRGB colour rather than a numeric array.\n *\n * @param value - The candidate.\n * @returns `true` for an object carrying `r`, `g`, `b`, and `a`.\n */\nfunction isColorLike(value: readonly number[] | Float32Array | ColorLike): value is ColorLike {\n return !Array.isArray(value) && !(value instanceof Float32Array);\n}\n\n/**\n * Builds the `IGX-0713` failure a wrongly shaped value produces.\n *\n * @param declaration - The uniform declaration.\n * @param material - The material's name.\n * @param expected - What the uniform takes.\n * @param actual - What the caller passed.\n * @returns The error to throw.\n */\nfunction shapeMismatch(\n declaration: ShaderUniformDeclaration,\n material: string,\n expected: string,\n actual: string,\n): IgnifxError {\n return new IgnifxError(\n CoreErrorCode.shaderValueMismatch,\n `${declaration.name} on ${material} expects ${expected}, not ${actual}.`,\n {\n context: { name: declaration.name, material, expected, actual },\n hint: \"A colour uniform takes a ColorLike or its element count; every other uniform takes its element count.\",\n },\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CA,MAAM,uBAA0C,OAAO,OAAO,CAAC,GAAG,2BAA2B,GAAG,oBAAoB,CAAC;;AAGrH,MAAM,eAAe;;AAGrB,MAAM,mBAAmB;;AAGzB,MAAM,qBAAqB;;AAG3B,MAAM,iBAAiB;;AAGvB,MAAM,iBAA8D,OAAO,OAAO;CAChF,KAAK;CACL,KAAK;CACL,KAAK;CACL,aAAa;CACb,aAAa;CACb,aAAa;CACb,eAAe;AACjB,CAAC;;;;;;;;;;AAWD,MAAM,sBAAqC,OAAO,OAAO;CACvD,OAAO,OAAO,OAAO;EAAE,WAAW;EAAO,WAAW;EAAuB,WAAW;CAAM,CAAC;CAC7F,OAAO,OAAO,OAAO;EAAE,WAAW;EAAO,WAAW;EAAuB,WAAW;CAAM,CAAC;AAC/F,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BD,SAAgB,wBACd,MACA,QACA,aACA,UACA,SAC4B;CAC5B,MAAM,UAAgC,CAAC;CAGvC,KAAK,MAAM,UAAU,YAAY,QAC/B,QAAQ,KAAK,MAAM;CAErB,KAAK,MAAM,UAAU,YAAY,QAAQ;EACvC,MAAM,OAAO,qBAAqB;EAClC,QAAQ,KAAK;GAAE,MAAM;GAAQ;GAAM,cAAc,MAAM,eAAe,KAAK;EAAE,CAAC;CAChF;CACA,KAAK,MAAM,WAAW,YAAY,UAChC,QAAQ,KAAK;EACX,MAAM,QAAQ;EACd,MAAM,QAAQ;EACd,cAAc,MAAM,KAAK,SAAS,IAAI,QAAQ,IAAI,KAAK,aAAa,OAAO,CAAC;CAC9E,CAAC;CAEH,MAAM,WAAiC,CAAC;CACxC,KAAK,MAAM,WAAW,YAAY,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ACE,SAAS;GAAE,MAAM,YAAY;GAAM;GAAU;GAAU;EAAO;EAC9D,MAAM;CACR,CACF;AACF"}
1
+ {"version":3,"file":"shader-material-C4VjLTfV.js","names":[],"sources":["../src/render/shader-material.ts"],"sourcesContent":["import { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { IgnifxError } from \"../errors/ignifx-error.js\";\nimport { Color } from \"../math/color.js\";\nimport { IGNIFX_UNIFORM_TYPES, IGNIFX_UNIFORM_NAMES, LITE_SYSTEM_UNIFORM_NAMES } from \"./shader-declaration.js\";\nimport type { ShaderAsset } from \"./shader-asset.js\";\nimport type {\n IgnifxUniformName,\n ShaderDeclaration,\n ShaderTextureDeclaration,\n ShaderUniformDeclaration,\n ShaderUniformType,\n} from \"./shader-declaration.js\";\nimport type { ShaderMaterialDefinition } from \"./shader-material-definition.js\";\nimport type { StorageBufferAsset } from \"./storage-buffer-asset.js\";\nimport type { TextureAsset } from \"./texture-asset.js\";\nimport type { App } from \"../app/types.js\";\nimport type { AssetHandle } from \"../assets/types.js\";\nimport type {\n LiteShaderMaterial,\n ShaderMaterialAdapter,\n ShaderMaterialBuildOptions,\n ShaderSamplerEntry,\n ShaderStorageEntry,\n ShaderUniformEntry,\n} from \"../lite/gpu/shader-material.js\";\nimport type { LiteTexture2D } from \"../lite/gpu/texture.js\";\nimport type { ColorLike } from \"../math/types.js\";\nimport type { Disconnect } from \"../signal/signal.js\";\n\n/**\n * The `\"shader\"` material family (`docs/plan/2026-09-terrain-particles-shaders.md` §3.1): a\n * `ShaderAsset` plus the values a material sets on it.\n *\n * Nothing here imports Babylon Lite: {@link toShaderMaterialOptions} is the whole mapping onto the\n * shape `createShaderMaterial` takes, as plain data, and the adapter itself arrives through\n * {@link loadShaderMaterialAdapter} so a project that loads no `.wgsl` never fetches that chunk\n * (`./shader-support.ts`).\n *\n * Two Lite rules shape the design:\n *\n * - A declared sampler must have something bound (error 309), so an unbound declared texture gets\n * the declaration's 1x1 fallback and `setTexture(name, null)` restores it rather than unbinding.\n * - A declared storage buffer must have something bound too (error 310), and `array<T>` has no 1x1\n * equivalent, so such a material is not drawable until `setStorageBuffer` binds one.\n */\n\n/** The uniform names Babylon Lite and ignifx write themselves, which a material may not set. */\nconst ENGINE_UNIFORM_NAMES: readonly string[] = Object.freeze([...LITE_SYSTEM_UNIFORM_NAMES, ...IGNIFX_UNIFORM_NAMES]);\n\n/** How many floats the `PreRender` system's frame buffer holds: direction, colour, ambient. */\nconst FRAME_FLOATS = 9;\n\n/** Where the main light's direction starts inside the frame buffer. */\nconst DIRECTION_OFFSET = 0;\n\n/** Where the main light's colour starts inside the frame buffer. */\nconst LIGHT_COLOR_OFFSET = 3;\n\n/** Where the ambient colour starts inside the frame buffer. */\nconst AMBIENT_OFFSET = 6;\n\n/** How many elements each uniform type holds. */\nconst ELEMENT_COUNTS: Readonly<Record<ShaderUniformType, number>> = Object.freeze({\n f32: 1,\n u32: 1,\n i32: 1,\n \"vec2<f32>\": 2,\n \"vec3<f32>\": 3,\n \"vec4<f32>\": 4,\n \"mat4x4<f32>\": 16,\n});\n\n/**\n * The premultiplied-alpha blend state, which Babylon Lite's two named modes cannot express.\n *\n * @remarks\n * `blendMode: \"alpha\"` compiles `srcFactor: \"src-alpha\"` (`lib/material/shader/shader-pipeline.js`),\n * which multiplies the source colour by its alpha a second time. A premultiplied surface has\n * already done that, so it needs `srcFactor: \"one\"` — the state that lets additive and over-blended\n * particles share one draw.\n */\nconst PREMULTIPLIED_BLEND: GPUBlendState = Object.freeze({\n color: Object.freeze({ srcFactor: \"one\", dstFactor: \"one-minus-src-alpha\", operation: \"add\" }),\n alpha: Object.freeze({ srcFactor: \"one\", dstFactor: \"one-minus-src-alpha\", operation: \"add\" }),\n});\n\n/**\n * Maps a shader file's declaration and a material's `define` overrides onto the shape\n * `createShaderMaterial` takes.\n *\n * @remarks\n * Pure data in, pure data out, so every mapping rule is asserted headlessly:\n *\n * - `blend opaque` leaves blending off; `alpha` and `additive` are Lite's two named modes;\n * `premultiplied` supplies an explicit `GPUBlendState`, because Lite's `\"alpha\"` mode multiplies\n * by alpha a second time.\n * - `depthWrite` is passed explicitly, because the declaration already resolved Lite's\n * \"blended defaults to off unless stated\" rule.\n * - `depthTest off` becomes `depthCompare: \"always\"`; `depthTest on` passes `null`, which leaves\n * Lite's reverse-Z default in place.\n * - `instancing matrices` and `matrices-colors` differ only in `useThinInstanceColors`; which\n * pipeline layout a mesh draws with is Lite's decision at build time, from whether the mesh has a\n * thin-instance colour stream.\n * - A colour uniform's declared default is sRGB and is decoded here, which is the one place the\n * conversion happens for defaults.\n *\n * @param name - The material's name, for GPU debug labels.\n * @param source - The whole `.wgsl` file.\n * @param declaration - What the file's pragmas declared.\n * @param uniforms - The initial value of every custom uniform, keyed by name, already **linear**.\n * @param defines - The resolved `define` values.\n * @returns The options.\n *\n * @internal\n */\nexport function toShaderMaterialOptions(\n name: string,\n source: string,\n declaration: ShaderDeclaration,\n uniforms: ReadonlyMap<string, Float32Array>,\n defines: Readonly<Record<string, boolean | number>>,\n): ShaderMaterialBuildOptions {\n const entries: ShaderUniformEntry[] = [];\n // `for…of` rather than an indexed loop: this runs once per material build, not per frame, and the\n // iterator yields the element type rather than `T | undefined`.\n for (const system of declaration.system) {\n entries.push(system);\n }\n for (const ignifx of declaration.ignifx) {\n const type = IGNIFX_UNIFORM_TYPES[ignifx];\n entries.push({ name: ignifx, type, defaultValue: zeros(ELEMENT_COUNTS[type]) });\n }\n for (const uniform of declaration.uniforms) {\n entries.push({\n name: uniform.name,\n type: uniform.type,\n defaultValue: Array.from(uniforms.get(uniform.name) ?? uniformStore(uniform)),\n });\n }\n const samplers: ShaderSamplerEntry[] = [];\n for (const texture of declaration.textures) {\n samplers.push({ name: texture.name, viewDimension: texture.array ? \"2d-array\" : \"2d\" });\n }\n const storageBuffers: ShaderStorageEntry[] = [];\n for (const storage of declaration.storage) {\n storageBuffers.push({ name: storage.name, type: storage.type });\n }\n const pipeline = declaration.pipeline;\n const blended = pipeline.blend !== \"opaque\";\n return {\n name,\n source,\n attributes: declaration.attributes,\n uniforms: entries,\n samplers,\n storageBuffers,\n defines,\n useThinInstanceColors: pipeline.instancing === \"matrices-colors\",\n needAlphaBlending: blended,\n blendMode: pipeline.blend === \"additive\" ? \"additive\" : \"alpha\",\n blend: pipeline.blend === \"premultiplied\" ? PREMULTIPLIED_BLEND : null,\n transmissive: pipeline.transmissive,\n backFaceCulling: pipeline.cull === \"back\",\n depthWrite: pipeline.depthWrite,\n depthCompare: pipeline.depthTest ? null : \"always\",\n };\n}\n\n/** The dynamically imported Babylon Lite adapter, memoised for the process. */\nlet adapter: ShaderMaterialAdapter | null = null;\n\n/**\n * Loads the custom-WGSL half of the Babylon Lite adapter, once per process.\n *\n * @remarks\n * The shader **loader** awaits this before it hands back a `ShaderAsset`, which is what makes\n * {@link shaderMaterialAdapter} safe to call from the synchronous material builders. Loading it also\n * turns on Lite's cached uniform serialization plans, which is what makes the per-frame `time`\n * upload rewrite only the slots that changed.\n *\n * @returns A promise that resolves once the adapter is in place.\n *\n * @internal\n */\nexport async function loadShaderMaterialAdapter(): Promise<void> {\n if (adapter !== null) {\n return;\n }\n const loaded = await import(\"../lite/gpu/shader-material.js\");\n loaded.enableShaderUniformCaching();\n // The assignment is what checks `ShaderMaterialAdapter` against the module it stands for.\n adapter = loaded;\n}\n\n/**\n * The adapter, if it has been loaded.\n *\n * @returns The module, or `null` before any `.wgsl` has been loaded.\n *\n * @internal\n */\nexport function shaderMaterialAdapter(): ShaderMaterialAdapter | null {\n return adapter;\n}\n\n/**\n * The adapter, or the failure a material built before the `.wgsl` loader ran produces.\n *\n * @param shader - The shader being built, for the message.\n * @returns The adapter.\n * @throws IgnifxError with code `IGX-0715` when the chunk has not been loaded.\n */\nfunction requireShaderMaterialAdapter(shader: ShaderAsset): ShaderMaterialAdapter {\n const module = shaderMaterialAdapter();\n if (module === null) {\n throw new IgnifxError(\n CoreErrorCode.shaderCompileFailed,\n `${shader.address} cannot be built because the shader adapter has not been loaded.`,\n {\n context: { asset: shader.address, message: \"adapter not loaded\" },\n hint: \"Load the .wgsl through app.assets, which is what loads the adapter.\",\n },\n );\n }\n return module;\n}\n\n/**\n * The per-app state the shader material family needs: the 1x1 fallback textures declared samplers\n * fall back to, and the list of live materials whose per-frame ignifx uniforms have to be written.\n *\n * @remarks\n * It hangs off the app through a lazily created `WeakMap` rather than a service, so a shader\n * material works whether or not an extension registered anything, and two apps in one process keep\n * separate state (`CONSTITUTION.md` §3.6).\n *\n * @internal\n */\nexport class ShaderMaterialRegistry {\n readonly #app: App;\n\n /** Live materials that declare at least one ignifx uniform, in no particular order. */\n readonly #animated: ShaderMaterialState[] = [];\n\n readonly #fallbacks = new Map<string, LiteTexture2D>();\n\n /**\n * Creates the registry.\n *\n * @param app - The app it belongs to.\n */\n constructor(app: App) {\n this.#app = app;\n }\n\n /**\n * The materials the `PreRender` uniform system has to write this frame.\n *\n * @returns The list; the registry's own array, iterated without copying.\n */\n get animated(): readonly ShaderMaterialState[] {\n return this.#animated;\n }\n\n /**\n * Starts writing a material's ignifx uniforms every frame.\n *\n * @param state - The material.\n */\n add(state: ShaderMaterialState): void {\n if (!this.#animated.includes(state)) {\n this.#animated.push(state);\n }\n }\n\n /**\n * Stops writing a material's ignifx uniforms.\n *\n * @param state - The material.\n */\n remove(state: ShaderMaterialState): void {\n const index = this.#animated.indexOf(state);\n if (index < 0) {\n return;\n }\n const last = this.#animated.pop();\n if (last !== undefined && index < this.#animated.length) {\n this.#animated[index] = last;\n }\n }\n\n /**\n * The 1x1 texture a declared-but-unbound sampler is filled with, created on first use and shared\n * for the life of the app.\n *\n * @param declaration - The sampler declaration, for its `default` and `array` flags.\n * @returns The texture, or `null` under a headless app or before the adapter has loaded.\n */\n fallbackTexture(declaration: ShaderTextureDeclaration): LiteTexture2D | null {\n const module = shaderMaterialAdapter();\n if (module === null || this.#app.isHeadless) {\n return null;\n }\n return module.resolveFallbackTexture(\n this.#app.lite.engine,\n this.#fallbacks,\n declaration.fallback,\n declaration.array,\n );\n }\n}\n\n/** The per-app registries, created on first use so module scope allocates nothing. */\nlet registries: WeakMap<App, ShaderMaterialRegistry> | null = null;\n\n/**\n * The shader material state of one app.\n *\n * @param app - The app.\n * @returns Its registry, created on first use.\n *\n * @internal\n */\nexport function shaderMaterialsOf(app: App): ShaderMaterialRegistry {\n const map = (registries ??= new WeakMap<App, ShaderMaterialRegistry>());\n const existing = map.get(app);\n if (existing !== undefined) {\n return existing;\n }\n const created = new ShaderMaterialRegistry(app);\n map.set(app, created);\n return created;\n}\n\n/**\n * One live `\"shader\"` material: the Babylon Lite material, the CPU-side copy of every value written\n * to it, and the bindings it has to replay when the shader file or a `define` changes.\n *\n * @remarks\n * `MaterialAsset` owns one of these and forwards `setUniform`, `getUniform`, `setTexture`,\n * `setDefine`, and `setStorageBuffer` to it. It is `@internal` because the public surface is the\n * material's methods, not this object.\n *\n * @internal\n */\nexport class ShaderMaterialState {\n /** The definition the material was built from; a clone replays it. */\n readonly definition: ShaderMaterialDefinition;\n\n readonly #app: App;\n\n readonly #values = new Map<string, Float32Array>();\n\n readonly #textures = new Map<string, AssetHandle<TextureAsset> | null>();\n\n readonly #storage = new Map<string, AssetHandle<StorageBufferAsset> | null>();\n\n readonly #defines = new Map<string, boolean | number>();\n\n /** The last light values written, so an unchanged light costs no upload. */\n readonly #light = new Float32Array(FRAME_FLOATS);\n\n /** The ignifx-provided uniforms the file declares, paired with their stores. */\n readonly #engineSlots: { readonly name: IgnifxUniformName; readonly store: Float32Array }[] = [];\n\n #shader: ShaderAsset;\n\n #material: LiteShaderMaterial;\n\n /**\n * The adapter every write goes through. Captured once, because a state can only be built after\n * {@link buildLiteShaderMaterial} has proved the chunk is in memory.\n */\n readonly #adapter: ShaderMaterialAdapter;\n\n #hasLight = false;\n\n #hasWarnedAboutLight = false;\n\n #onReplaced: Disconnect | null = null;\n\n /**\n * Builds the material. Use {@link buildShaderMaterialState}.\n *\n * @param app - The app that owns the engine, the log, and the registry.\n * @param shader - The shader the material sets values on.\n * @param definition - The declaration.\n * @param material - The already-built Babylon Lite material.\n * @param liteAdapter - The custom-WGSL adapter every write goes through.\n */\n constructor(\n app: App,\n shader: ShaderAsset,\n definition: ShaderMaterialDefinition,\n material: LiteShaderMaterial,\n liteAdapter: ShaderMaterialAdapter,\n ) {\n this.#app = app;\n this.#adapter = liteAdapter;\n this.#shader = shader;\n this.definition = definition;\n this.#material = material;\n // Not zeros: a light really at the origin pointing along +Z would then never be written.\n this.#light.fill(Number.NaN);\n }\n\n /**\n * The shader the material is values for.\n *\n * @returns The shader asset, which a hot reload replaces.\n */\n get shader(): ShaderAsset {\n return this.#shader;\n }\n\n /**\n * The Babylon Lite material, which `setDefine` and a hot reload replace with a new object.\n *\n * @returns The material.\n */\n get material(): LiteShaderMaterial {\n return this.#material;\n }\n\n /**\n * Whether the shader declares any ignifx-provided uniform, and so needs a per-frame write.\n *\n * @returns `true` when the `PreRender` system has work to do for this material.\n */\n get isAnimated(): boolean {\n return this.#shader.declaration.ignifx.length > 0;\n }\n\n /**\n * Whether every declared storage buffer has a buffer bound, which is what Babylon Lite needs\n * before the material can be drawn at all.\n *\n * @returns `true` when the material is drawable.\n */\n get isDrawable(): boolean {\n const declared = this.#shader.declaration.storage;\n for (let index = 0; index < declared.length; index += 1) {\n const name = declared[index]?.name;\n if (name !== undefined && (this.#storage.get(name) ?? null) === null) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Writes a declared uniform.\n *\n * @param name - The uniform's name.\n * @param value - The value: a number, a numeric array, or — for a `color` uniform — an sRGB\n * colour, which is uploaded linear.\n * @throws IgnifxError with code `IGX-0712` when the shader declares no such uniform or the engine\n * writes it, or `IGX-0713` when the value has the wrong shape.\n */\n setUniform(name: string, value: number | readonly number[] | Float32Array | ColorLike): void {\n const declaration = this.#writableUniform(name);\n const store = this.#values.get(name) ?? uniformStore(declaration);\n this.#values.set(name, store);\n writeUniformValue(store, declaration, value, this.definition.name);\n this.#write(name, store);\n }\n\n /**\n * Reads the current CPU-side value of a declared uniform.\n *\n * @param name - The uniform's name.\n * @param out - Receives the value for a vector or matrix uniform; a fresh array is allocated when\n * it is omitted.\n * @returns The number for a scalar uniform, or the filled array.\n * @throws IgnifxError with code `IGX-0712` when the shader declares no such uniform, or\n * `IGX-0713` when `out` is too short.\n */\n getUniform(name: string, out?: Float32Array): number | Float32Array {\n const declaration = this.#uniform(name);\n const store = this.#values.get(name) ?? uniformStore(declaration);\n this.#values.set(name, store);\n if (store.length === 1 && out === undefined) {\n return store[0] ?? 0;\n }\n if (out === undefined) {\n return Float32Array.from(store);\n }\n if (out.length < store.length) {\n throw new IgnifxError(\n CoreErrorCode.shaderValueMismatch,\n `${name} on ${this.definition.name} expects ${String(store.length)} floats, not ${String(out.length)}.`,\n {\n context: { name, material: this.definition.name, expected: store.length, actual: out.length },\n hint: \"Pass an out array at least as long as the uniform's element count.\",\n },\n );\n }\n out.set(store);\n return out;\n }\n\n /**\n * Binds a texture to a declared sampler, or restores the declaration's fallback.\n *\n * @param name - The sampler's name.\n * @param texture - The texture, or `null` for the declared 1x1 fallback.\n * @throws IgnifxError with code `IGX-0712` when the shader declares no such sampler.\n */\n setTexture(name: string, texture: AssetHandle<TextureAsset> | null): void {\n const declaration = this.#texture(name);\n this.#textures.set(name, texture);\n this.#bindTexture(declaration, texture);\n }\n\n /**\n * Binds a storage buffer to a declared binding.\n *\n * @param name - The binding's name.\n * @param buffer - The buffer, or `null` to unbind. A material with an unbound declared storage\n * buffer cannot be drawn.\n * @throws IgnifxError with code `IGX-0712` when the shader declares no such storage buffer.\n */\n setStorageBuffer(name: string, buffer: AssetHandle<StorageBufferAsset> | null): void {\n const declared = this.#shader.declaration.storage;\n let found = false;\n for (let index = 0; index < declared.length; index += 1) {\n if (declared[index]?.name === name) {\n found = true;\n break;\n }\n }\n if (!found) {\n throw this.#unknownBinding(name, \"storage buffer\");\n }\n this.#storage.set(name, buffer);\n this.#bindStorage(name, buffer);\n }\n\n /**\n * Overrides a declared `define` and rebuilds the Babylon Lite material, because a define is a\n * WGSL `const` baked into the compiled pipeline.\n *\n * @remarks\n * The rebuild replaces the Lite material **object**. `MeshRenderer` re-reads\n * `MaterialAsset.lite.material` every `PreRender` and writes it onto its mesh when it changed,\n * and Lite's `mesh.material` setter enqueues a material swap that the next frame drains\n * (`lib/scene/mesh-scene-registry.js`), so the new pipeline is picked up on the following frame\n * with no explicit topology flag.\n *\n * @param name - The define's name.\n * @param value - The new value.\n * @throws IgnifxError with code `IGX-0712` when the shader declares no such define.\n */\n setDefine(name: string, value: boolean | number): void {\n const declared = this.#shader.declaration.defines;\n let fileValue: boolean | number | undefined;\n for (let index = 0; index < declared.length; index += 1) {\n const definition = declared[index];\n if (definition?.name === name) {\n fileValue = definition.value;\n break;\n }\n }\n if (fileValue === undefined) {\n throw this.#unknownBinding(name, \"define\");\n }\n // Compared against the value in force, not against the override map, so re-setting what the\n // file already declares is not a pipeline rebuild.\n if ((this.#defines.get(name) ?? fileValue) === value) {\n return;\n }\n this.#defines.set(name, value);\n this.#rebuild(this.#shader);\n }\n\n /**\n * Writes this frame's ignifx uniforms. The `PreRender` system calls it.\n *\n * @param time - Scaled seconds since `app.start()`.\n * @param unscaledTime - Unscaled seconds since `app.start()`.\n * @param deltaTime - Scaled seconds since the previous frame.\n * @param light - Nine floats: the main light's world direction, its linear colour times its\n * intensity, and the ambient colour.\n * @param hasLight - Whether an enabled directional light supplied the first six.\n */\n writeFrameUniforms(\n time: number,\n unscaledTime: number,\n deltaTime: number,\n light: Float32Array,\n hasLight: boolean,\n ): void {\n let lightChanged = this.#hasLight !== hasLight;\n this.#hasLight = hasLight;\n for (let index = 0; index < this.#light.length; index += 1) {\n if (this.#light[index] !== light[index]) {\n this.#light[index] = light[index] ?? 0;\n lightChanged = true;\n }\n }\n const slots = this.#engineSlots;\n for (let index = 0; index < slots.length; index += 1) {\n const slot = slots[index];\n if (slot === undefined) {\n continue;\n }\n switch (slot.name) {\n case \"time\":\n this.#writeScalar(slot.name, slot.store, time);\n break;\n case \"unscaledTime\":\n this.#writeScalar(slot.name, slot.store, unscaledTime);\n break;\n case \"deltaTime\":\n this.#writeScalar(slot.name, slot.store, deltaTime);\n break;\n case \"mainLightDirection\":\n if (lightChanged) {\n this.#writeTriple(slot.name, slot.store, light, DIRECTION_OFFSET);\n }\n break;\n case \"mainLightColor\":\n if (lightChanged) {\n this.#writeTriple(slot.name, slot.store, light, LIGHT_COLOR_OFFSET);\n }\n break;\n case \"ambientColor\":\n if (lightChanged) {\n this.#writeTriple(slot.name, slot.store, light, AMBIENT_OFFSET);\n }\n break;\n default:\n break;\n }\n }\n if (!hasLight && !this.#hasWarnedAboutLight && this.#needsLight()) {\n this.#hasWarnedAboutLight = true;\n const declared = this.#engineSlots.map((slot) => slot.name).join(\", \");\n this.#app.log.warnOnce(\n `${CoreErrorCode.shaderLightUniformWithoutLight}:${this.definition.name}`,\n `${CoreErrorCode.shaderLightUniformWithoutLight}: ${this.definition.name} declares ${declared}, ` +\n \"but this world has no enabled directional light; zeros are uploaded.\",\n );\n }\n }\n\n /**\n * Replays the definition's values, textures, defines, and storage bindings onto a freshly built\n * Babylon Lite material, and connects the hot-reload hook. Called once, by\n * {@link buildShaderMaterialState}.\n *\n * @param textures - The texture handles the loader resolved, in declaration order.\n */\n initialise(textures: readonly AssetHandle<TextureAsset>[]): void {\n const declaration = this.#shader.declaration;\n for (const name of Object.keys(this.definition.defines)) {\n const value = this.definition.defines[name];\n if (value !== undefined) {\n this.#defines.set(name, value);\n }\n }\n for (const name of Object.keys(this.definition.values)) {\n const value = this.definition.values[name];\n if (value !== undefined) {\n this.setUniform(name, value);\n }\n }\n const addresses = Object.keys(this.definition.textures);\n for (let index = 0; index < declaration.textures.length; index += 1) {\n const declared = declaration.textures[index];\n if (declared === undefined) {\n continue;\n }\n const slot = addresses.indexOf(declared.name);\n const handle = slot < 0 ? undefined : textures[slot];\n this.#textures.set(declared.name, handle ?? null);\n this.#bindTexture(declared, handle ?? null);\n }\n this.#refreshEngineSlots();\n if (this.isAnimated) {\n shaderMaterialsOf(this.#app).add(this);\n }\n const source = this.#app.assets.get<ShaderAsset>(this.definition.shader);\n this.#onReplaced =\n source?.onReplaced.connect((value: ShaderAsset): void => {\n this.#reload(value);\n }) ?? null;\n }\n\n /**\n * Stops the per-frame writes and the hot-reload hook. The `material` asset type's `unload` runs\n * it when the last holder releases the material.\n */\n dispose(): void {\n this.#onReplaced?.();\n this.#onReplaced = null;\n shaderMaterialsOf(this.#app).remove(this);\n }\n\n /**\n * Rebuilds the Lite material for a replaced shader file, keeping the previous one on failure.\n *\n * @param shader - The re-parsed shader asset.\n */\n #reload(shader: ShaderAsset): void {\n try {\n this.#rebuild(shader);\n this.#shader = shader;\n } catch (error: unknown) {\n this.#app.onError.emit({\n error: new IgnifxError(\n CoreErrorCode.shaderCompileFailed,\n `${shader.address} failed to rebuild; the previous material stays in use. ${String(error)}`,\n {\n context: { asset: shader.address, message: String(error) },\n cause: error,\n hint: \"Fix the shader file; the running material is the last one that built.\",\n },\n ),\n source: \"asset\",\n phase: null,\n entity: null,\n component: null,\n });\n }\n }\n\n /**\n * Builds a new Lite material from a declaration and replays every binding that still exists.\n *\n * @param shader - The shader to build from.\n */\n #rebuild(shader: ShaderAsset): void {\n const declaration = shader.declaration;\n const previous = this.#shader;\n // The Lite material is replaced halfway through, so a failure has to put the old one back or the\n // material would be left drawing a new program against the old declaration's bindings.\n const previousMaterial = this.#material;\n const previousValues = new Map(this.#values);\n this.#shader = shader;\n try {\n const values = new Map<string, Float32Array>();\n for (let index = 0; index < declaration.uniforms.length; index += 1) {\n const uniform = declaration.uniforms[index];\n if (uniform === undefined) {\n continue;\n }\n const kept = this.#values.get(uniform.name);\n values.set(\n uniform.name,\n kept !== undefined && kept.length === ELEMENT_COUNTS[uniform.type] ? kept : uniformStore(uniform),\n );\n }\n this.#material = buildLiteShaderMaterial(this.definition.name, shader, values, this.#resolveDefines(shader));\n this.#values.clear();\n for (const [name, store] of values) {\n this.#values.set(name, store);\n }\n this.#rebind(declaration);\n } catch (error: unknown) {\n this.#shader = previous;\n this.#material = previousMaterial;\n this.#values.clear();\n for (const [name, store] of previousValues) {\n this.#values.set(name, store);\n }\n throw error;\n }\n }\n\n /**\n * Re-applies the texture and storage bindings that the new declaration still has, dropping the\n * ones it no longer declares.\n *\n * @param declaration - The new declaration.\n */\n #rebind(declaration: ShaderDeclaration): void {\n const textures = new Map(this.#textures);\n this.#textures.clear();\n for (let index = 0; index < declaration.textures.length; index += 1) {\n const declared = declaration.textures[index];\n if (declared === undefined) {\n continue;\n }\n const handle = textures.get(declared.name) ?? null;\n this.#textures.set(declared.name, handle);\n this.#bindTexture(declared, handle);\n }\n const storage = new Map(this.#storage);\n this.#storage.clear();\n for (let index = 0; index < declaration.storage.length; index += 1) {\n const name = declaration.storage[index]?.name;\n if (name === undefined) {\n continue;\n }\n const handle = storage.get(name) ?? null;\n this.#storage.set(name, handle);\n this.#bindStorage(name, handle);\n }\n this.#refreshEngineSlots();\n const registry = shaderMaterialsOf(this.#app);\n if (this.isAnimated) {\n registry.add(this);\n } else {\n registry.remove(this);\n }\n this.#light.fill(Number.NaN);\n }\n\n /**\n * The declared `define` values with this material's overrides applied.\n *\n * @param shader - The shader whose declaration supplies the defaults.\n * @returns The resolved values.\n */\n #resolveDefines(shader: ShaderAsset): Readonly<Record<string, boolean | number>> {\n const resolved: Record<string, boolean | number> = {};\n const declared = shader.declaration.defines;\n for (let index = 0; index < declared.length; index += 1) {\n const define = declared[index];\n if (define === undefined) {\n continue;\n }\n resolved[define.name] = this.#defines.get(define.name) ?? define.value;\n }\n return resolved;\n }\n\n /**\n * Binds a texture, or the declaration's fallback when there is none.\n *\n * @param declaration - The sampler declaration.\n * @param handle - The texture handle, or `null`.\n */\n #bindTexture(declaration: ShaderTextureDeclaration, handle: AssetHandle<TextureAsset> | null): void {\n const loaded = handle?.state === \"loaded\" ? handle.value.lite.texture : null;\n this.#adapter.writeShaderTexture(\n this.#material,\n declaration.name,\n loaded ?? shaderMaterialsOf(this.#app).fallbackTexture(declaration),\n );\n }\n\n /**\n * Binds a storage buffer.\n *\n * @param name - The binding's name.\n * @param handle - The buffer handle, or `null`.\n */\n #bindStorage(name: string, handle: AssetHandle<StorageBufferAsset> | null): void {\n this.#adapter.writeShaderStorageBuffer(\n this.#material,\n name,\n handle?.state === \"loaded\" ? handle.value.lite.buffer : null,\n );\n }\n\n /**\n * Writes one CPU-side value through to Babylon Lite.\n *\n * @param name - The uniform's name.\n * @param store - The value.\n */\n #write(name: string, store: Float32Array): void {\n this.#adapter.writeShaderUniform(this.#material, name, store);\n }\n\n /**\n * Writes one engine-owned scalar uniform through its CPU-side store.\n *\n * @param name - The uniform's name.\n * @param store - The store, which is also what `getUniform` reads.\n * @param value - The value.\n */\n #writeScalar(name: string, store: Float32Array, value: number): void {\n store[0] = value;\n this.#adapter.writeShaderUniform(this.#material, name, store);\n }\n\n /**\n * Writes three floats of an engine-owned `vec3<f32>` uniform, without allocating.\n *\n * @param name - The uniform's name.\n * @param store - The store, which is also what `getUniform` reads.\n * @param source - The nine-float frame buffer.\n * @param offset - Where the triple starts inside it.\n */\n #writeTriple(name: string, store: Float32Array, source: Float32Array, offset: number): void {\n store.set(source.subarray(offset, offset + 3));\n this.#adapter.writeShaderUniform(this.#material, name, store);\n }\n\n /**\n * Resolves the CPU-side store of every ignifx-provided uniform the file declares, so the\n * per-frame write is an indexed loop with no name lookup (coding standards §7).\n */\n #refreshEngineSlots(): void {\n const slots = this.#engineSlots;\n slots.length = 0;\n const declared = this.#shader.declaration.ignifx;\n for (let index = 0; index < declared.length; index += 1) {\n const name = declared[index];\n if (name === undefined) {\n continue;\n }\n const count = ELEMENT_COUNTS[IGNIFX_UNIFORM_TYPES[name]];\n const store = this.#values.get(name) ?? new Float32Array(count);\n this.#values.set(name, store);\n slots.push({ name, store });\n }\n }\n\n /**\n * Whether the shader declares a uniform that needs a directional light.\n *\n * @returns `true` when `mainLightDirection` or `mainLightColor` is declared.\n */\n #needsLight(): boolean {\n const declared = this.#shader.declaration.ignifx;\n for (let index = 0; index < declared.length; index += 1) {\n const name = declared[index];\n if (name === \"mainLightDirection\" || name === \"mainLightColor\") {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Looks a custom uniform declaration up.\n *\n * @param name - The uniform's name.\n * @returns The declaration.\n * @throws IgnifxError with code `IGX-0712`.\n */\n #uniform(name: string): ShaderUniformDeclaration {\n const custom = this.#customUniform(name);\n if (custom !== null) {\n return custom;\n }\n const engine = this.#engineUniform(name);\n if (engine !== null) {\n return engine;\n }\n throw this.#unknownBinding(name, \"uniform\");\n }\n\n /**\n * Looks a custom uniform declaration up, refusing the ones the engine writes.\n *\n * @param name - The uniform's name.\n * @returns The declaration.\n * @throws IgnifxError with code `IGX-0712`.\n */\n #writableUniform(name: string): ShaderUniformDeclaration {\n const custom = this.#customUniform(name);\n if (custom !== null) {\n return custom;\n }\n if (ENGINE_UNIFORM_NAMES.includes(name)) {\n throw new IgnifxError(\n CoreErrorCode.unknownShaderBinding,\n `${name} on ${this.definition.name} is written by the engine every frame and cannot be set.`,\n {\n context: { material: this.definition.name, name },\n hint: \"System uniforms come from Babylon Lite and the ignifx uniforms from the PreRender system.\",\n },\n );\n }\n throw this.#unknownBinding(name, \"uniform\");\n }\n\n /**\n * The file's own declaration of a uniform, if it declares one by that name.\n *\n * @param name - The uniform's name.\n * @returns The declaration, or `null`.\n */\n #customUniform(name: string): ShaderUniformDeclaration | null {\n const declared = this.#shader.declaration.uniforms;\n for (let index = 0; index < declared.length; index += 1) {\n const uniform = declared[index];\n if (uniform !== undefined && uniform.name === name) {\n return uniform;\n }\n }\n return null;\n }\n\n /**\n * The synthetic declaration of an ignifx-provided uniform the file declared, so `getUniform` can\n * read back what the `PreRender` system wrote.\n *\n * @param name - The uniform's name.\n * @returns The declaration, or `null` when the file declares no such engine uniform.\n */\n #engineUniform(name: string): ShaderUniformDeclaration | null {\n const declared = this.#shader.declaration.ignifx;\n for (let index = 0; index < declared.length; index += 1) {\n const ignifx = declared[index];\n if (ignifx !== undefined && ignifx === name) {\n return {\n name: ignifx,\n type: IGNIFX_UNIFORM_TYPES[ignifx],\n defaultValue: zeros(ELEMENT_COUNTS[IGNIFX_UNIFORM_TYPES[ignifx]]),\n color: false,\n range: null,\n step: null,\n tooltip: null,\n };\n }\n }\n return null;\n }\n\n /**\n * Looks a sampler declaration up.\n *\n * @param name - The sampler's name.\n * @returns The declaration.\n * @throws IgnifxError with code `IGX-0712`.\n */\n #texture(name: string): ShaderTextureDeclaration {\n const declared = this.#shader.declaration.textures;\n for (let index = 0; index < declared.length; index += 1) {\n const texture = declared[index];\n if (texture !== undefined && texture.name === name) {\n return texture;\n }\n }\n throw this.#unknownBinding(name, \"texture\");\n }\n\n /**\n * Builds the `IGX-0712` failure an undeclared binding name produces.\n *\n * @param name - The name that was asked for.\n * @param what - What kind of binding was expected.\n * @returns The error to throw.\n */\n #unknownBinding(name: string, what: string): IgnifxError {\n return new IgnifxError(\n CoreErrorCode.unknownShaderBinding,\n `${this.definition.name} declares no ${what} named ${name}.`,\n {\n context: { material: this.definition.name, name },\n hint: `Declare it in ${this.#shader.address} with an // @ignifx ${what} pragma.`,\n },\n );\n }\n}\n\n/**\n * Builds the live state of a `\"shader\"` material: the Babylon Lite material, then every value,\n * texture, and define the definition names.\n *\n * @param app - The app that owns the engine, the log, and the registry.\n * @param shader - The shader the material sets values on.\n * @param definition - The declaration.\n * @param textures - The texture handles the loader resolved, in the order the definition's\n * `textures` record names them.\n * @returns The state.\n * @throws IgnifxError with code `IGX-0715` when the adapter has not been loaded, `IGX-0712` for an\n * undeclared value or define name, or `IGX-0713` for a value of the wrong shape.\n *\n * @internal\n */\nexport function buildShaderMaterialState(\n app: App,\n shader: ShaderAsset,\n definition: ShaderMaterialDefinition,\n textures: readonly AssetHandle<TextureAsset>[],\n): ShaderMaterialState {\n const defines: Record<string, boolean | number> = {};\n const declared = shader.declaration.defines;\n for (let index = 0; index < declared.length; index += 1) {\n const define = declared[index];\n if (define !== undefined) {\n defines[define.name] = definition.defines[define.name] ?? define.value;\n }\n }\n for (const name of Object.keys(definition.defines)) {\n if (!(name in defines)) {\n throw new IgnifxError(\n CoreErrorCode.unknownShaderBinding,\n `${definition.name} declares no define named ${name}.`,\n {\n context: { material: definition.name, name },\n hint: `Declare it in ${shader.address} with an // @ignifx define pragma.`,\n },\n );\n }\n }\n const material = buildLiteShaderMaterial(definition.name, shader, new Map(), defines);\n const state = new ShaderMaterialState(app, shader, definition, material, requireShaderMaterialAdapter(shader));\n state.initialise(textures);\n return state;\n}\n\n/**\n * Builds the Babylon Lite material a declaration describes, through the dynamically loaded adapter.\n *\n * @param name - The material's name.\n * @param shader - The shader.\n * @param values - Current custom uniform values to seed the declaration's defaults with.\n * @param defines - The resolved `define` values.\n * @returns The Lite material.\n * @throws IgnifxError with code `IGX-0715` when the adapter has not been loaded yet.\n */\nfunction buildLiteShaderMaterial(\n name: string,\n shader: ShaderAsset,\n values: ReadonlyMap<string, Float32Array>,\n defines: Readonly<Record<string, boolean | number>>,\n): LiteShaderMaterial {\n return requireShaderMaterialAdapter(shader).createShaderMaterialFromOptions(\n toShaderMaterialOptions(name, shader.source, shader.declaration, values, defines),\n );\n}\n\n/**\n * A number, or an array of that many zeros, matching what a uniform of that arity starts at.\n *\n * @param count - How many elements the uniform holds.\n * @returns The zero value.\n */\nfunction zeros(count: number): number | readonly number[] {\n if (count === 1) {\n return 0;\n }\n const values: number[] = [];\n for (let index = 0; index < count; index += 1) {\n values.push(0);\n }\n return values;\n}\n\n/**\n * A fresh CPU-side store for one uniform, filled with its declared default — **linear** for a\n * colour, because that is what the GPU reads.\n *\n * @param declaration - The uniform declaration.\n * @returns The store.\n */\nfunction uniformStore(declaration: ShaderUniformDeclaration): Float32Array {\n const count = ELEMENT_COUNTS[declaration.type];\n const store = new Float32Array(count);\n const value = declaration.defaultValue;\n if (typeof value === \"number\") {\n store[0] = value;\n } else {\n store.set(value.slice(0, count));\n }\n if (declaration.color) {\n decodeColourComponents(store);\n }\n return store;\n}\n\n/**\n * Writes a caller's value into a uniform's CPU-side store, checking its shape and decoding a\n * colour.\n *\n * @param store - The store to write into.\n * @param declaration - The uniform declaration.\n * @param value - The caller's value.\n * @param material - The material's name, for diagnostics.\n * @throws IgnifxError with code `IGX-0713` when the value's shape does not match the declared type.\n */\nfunction writeUniformValue(\n store: Float32Array,\n declaration: ShaderUniformDeclaration,\n value: number | readonly number[] | Float32Array | ColorLike,\n material: string,\n): void {\n const count = store.length;\n if (typeof value === \"number\") {\n if (count !== 1) {\n throw shapeMismatch(declaration, material, `${declaration.type} (${String(count)} floats)`, \"a single number\");\n }\n store[0] = value;\n return;\n }\n if (isColorLike(value)) {\n if (count !== 3 && count !== 4) {\n throw shapeMismatch(declaration, material, `${declaration.type} (${String(count)} floats)`, \"a colour\");\n }\n store[0] = Color.srgbToLinear(value.r);\n store[1] = Color.srgbToLinear(value.g);\n store[2] = Color.srgbToLinear(value.b);\n if (count === 4) {\n store[3] = value.a;\n }\n return;\n }\n if (value.length !== count) {\n throw shapeMismatch(\n declaration,\n material,\n `${declaration.type} (${String(count)} floats)`,\n `${String(value.length)} floats`,\n );\n }\n store.set(value instanceof Float32Array ? value : Float32Array.from(value));\n if (declaration.color) {\n decodeColourComponents(store);\n }\n}\n\n/**\n * Decodes a store's first three components from sRGB to linear, in place.\n *\n * @remarks\n * A `subarray` view and `map` rather than three indexed reads: a `Float32Array` element is typed\n * `number | undefined` under `noUncheckedIndexedAccess`, and `map` hands the callback a `number`.\n * It runs on a value write, never per frame.\n *\n * @param store - The store, at least three floats long.\n */\nfunction decodeColourComponents(store: Float32Array): void {\n const rgb = store.subarray(0, 3);\n rgb.set(rgb.map((component) => Color.srgbToLinear(component)));\n}\n\n/**\n * Whether a value is an sRGB colour rather than a numeric array.\n *\n * @param value - The candidate.\n * @returns `true` for an object carrying `r`, `g`, `b`, and `a`.\n */\nfunction isColorLike(value: readonly number[] | Float32Array | ColorLike): value is ColorLike {\n return !Array.isArray(value) && !(value instanceof Float32Array);\n}\n\n/**\n * Builds the `IGX-0713` failure a wrongly shaped value produces.\n *\n * @param declaration - The uniform declaration.\n * @param material - The material's name.\n * @param expected - What the uniform takes.\n * @param actual - What the caller passed.\n * @returns The error to throw.\n */\nfunction shapeMismatch(\n declaration: ShaderUniformDeclaration,\n material: string,\n expected: string,\n actual: string,\n): IgnifxError {\n return new IgnifxError(\n CoreErrorCode.shaderValueMismatch,\n `${declaration.name} on ${material} expects ${expected}, not ${actual}.`,\n {\n context: { name: declaration.name, material, expected, actual },\n hint: \"A colour uniform takes a ColorLike or its element count; every other uniform takes its element count.\",\n },\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CA,MAAM,uBAA0C,OAAO,OAAO,CAAC,GAAG,2BAA2B,GAAG,oBAAoB,CAAC;;AAGrH,MAAM,eAAe;;AAGrB,MAAM,mBAAmB;;AAGzB,MAAM,qBAAqB;;AAG3B,MAAM,iBAAiB;;AAGvB,MAAM,iBAA8D,OAAO,OAAO;CAChF,KAAK;CACL,KAAK;CACL,KAAK;CACL,aAAa;CACb,aAAa;CACb,aAAa;CACb,eAAe;AACjB,CAAC;;;;;;;;;;AAWD,MAAM,sBAAqC,OAAO,OAAO;CACvD,OAAO,OAAO,OAAO;EAAE,WAAW;EAAO,WAAW;EAAuB,WAAW;CAAM,CAAC;CAC7F,OAAO,OAAO,OAAO;EAAE,WAAW;EAAO,WAAW;EAAuB,WAAW;CAAM,CAAC;AAC/F,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BD,SAAgB,wBACd,MACA,QACA,aACA,UACA,SAC4B;CAC5B,MAAM,UAAgC,CAAC;CAGvC,KAAK,MAAM,UAAU,YAAY,QAC/B,QAAQ,KAAK,MAAM;CAErB,KAAK,MAAM,UAAU,YAAY,QAAQ;EACvC,MAAM,OAAO,qBAAqB;EAClC,QAAQ,KAAK;GAAE,MAAM;GAAQ;GAAM,cAAc,M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CAAC,CAAC;AAC/D;;;;;;;AAQA,SAAS,YAAY,OAAyE;CAC5F,OAAO,CAAC,MAAM,QAAQ,KAAK,KAAK,EAAE,iBAAiB;AACrD;;;;;;;;;;AAWA,SAAS,cACP,aACA,UACA,UACA,QACa;CACb,OAAO,IAAI,YACT,cAAc,qBACd,GAAG,YAAY,KAAK,MAAM,SAAS,WAAW,SAAS,QAAQ,OAAO,IACtE;EACE,SAAS;GAAE,MAAM,YAAY;GAAM;GAAU;GAAU;EAAO;EAC9D,MAAM;CACR,CACF;AACF"}
@@ -1,4 +1,4 @@
1
- import { o as CoreErrorCode, t as IgnifxError } from "./ignifx-error-CRh89KUJ.js";
1
+ import { o as CoreErrorCode, t as IgnifxError } from "./ignifx-error-RpK-lWwE.js";
2
2
  import { a as SHADER_BLEND_MODES, i as SHADER_ATTRIBUTE_NAMES, l as SHADER_TEXTURE_FALLBACKS, o as SHADER_CULL_MODES, r as LITE_SYSTEM_UNIFORM_NAMES, s as SHADER_INSTANCING_MODES, t as IGNIFX_UNIFORM_NAMES, u as SHADER_UNIFORM_TYPES } from "./shader-declaration-5q__jycG.js";
3
3
  //#region src/render/shader-pragma.ts
4
4
  /**
@@ -703,4 +703,4 @@ function pragmaError(address, line, message) {
703
703
  //#endregion
704
704
  export { parseShaderDeclaration };
705
705
 
706
- //# sourceMappingURL=shader-pragma-tw6AKaQD.js.map
706
+ //# sourceMappingURL=shader-pragma-qO9_6sTd.js.map