@ignifx/core 0.12.0 → 0.14.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.
- package/dist/{environment-C9AjYJgV.js → environment-Cq2BmA96.js} +2 -2
- package/dist/{environment-C9AjYJgV.js.map → environment-Cq2BmA96.js.map} +1 -1
- package/dist/hdr-output-DDpIo4Q5.js +300 -0
- package/dist/hdr-output-DDpIo4Q5.js.map +1 -0
- package/dist/{ignifx-error-Dq2qJMkZ.js → ignifx-error-oYdVnT1S.js} +16 -1
- package/dist/ignifx-error-oYdVnT1S.js.map +1 -0
- package/dist/index.d.ts +343 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +842 -165
- package/dist/index.js.map +1 -1
- package/dist/material-CGk5mAah.js +204 -0
- package/dist/material-CGk5mAah.js.map +1 -0
- package/dist/{material-plugin-BOCB7Stt.js → material-plugin-BUlqLsap.js} +3 -204
- package/dist/material-plugin-BUlqLsap.js.map +1 -0
- package/dist/{post-effect-compiler-Dw6zW2cG.js → post-effect-compiler-CRek8VxQ.js} +2 -2
- package/dist/{post-effect-compiler-Dw6zW2cG.js.map → post-effect-compiler-CRek8VxQ.js.map} +1 -1
- package/dist/render-path-Dx0learj.js +135 -0
- package/dist/render-path-Dx0learj.js.map +1 -0
- package/dist/render-texture-IuR0iFVa.js +174 -0
- package/dist/render-texture-IuR0iFVa.js.map +1 -0
- package/dist/{shader-material-BxQn9FT4.js → shader-material-BPb_oEZQ.js} +2 -2
- package/dist/{shader-material-BxQn9FT4.js.map → shader-material-BPb_oEZQ.js.map} +1 -1
- package/dist/{shader-material-DRZmqA_S.js → shader-material-CDQ0Y5kN.js} +3 -3
- package/dist/{shader-material-DRZmqA_S.js.map → shader-material-CDQ0Y5kN.js.map} +1 -1
- package/dist/{shader-pragma-DrFm5f5m.js → shader-pragma-BKCoZTTA.js} +2 -2
- package/dist/{shader-pragma-DrFm5f5m.js.map → shader-pragma-BKCoZTTA.js.map} +1 -1
- package/dist/{surface-shader-BgZchRBe.js → surface-shader-CwQ03yHG.js} +5 -4
- package/dist/{surface-shader-BgZchRBe.js.map → surface-shader-CwQ03yHG.js.map} +1 -1
- package/package.json +1 -1
- package/dist/ignifx-error-Dq2qJMkZ.js.map +0 -1
- package/dist/material-plugin-BOCB7Stt.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"surface-shader-BgZchRBe.js","names":[],"sources":["../src/lite/gpu/material-plugin.ts","../src/render/gpu/surface-shader-host.ts","../src/render/surface-shader-compiler.ts","../src/render/surface-shader.ts"],"sourcesContent":["import type {\n MaterialPlugin,\n MaterialPluginPoint,\n PbrMaterialProps,\n PluginSamplerDecl,\n PluginTextureBinding,\n PluginUboField,\n StandardMaterialProps,\n Texture2D,\n} from \"@babylonjs/lite\";\n\n/**\n * The Babylon Lite half of surface shaders and raw material plugins\n * (`docs/plan/2026-09-terrain-particles-shaders.md` §3.2). Everything here is `@internal`.\n *\n * A `MaterialPlugin` is plain data with function members, so nothing here needs a device, but the\n * `materialPlugins` rendering feature must have installed the bridges before the scene was\n * registered (`../render-features.ts`). Three facts it is written around:\n *\n * - `getCustomCode`, `getUniforms` and `getSamplers` results are stringified into the pipeline cache\n * key (`lib/material/plugin/plugin-bridge-shared.js` 21-34), so they must be **stable**; this\n * module precomputes everything at attach time.\n * - `writeUbo(data, offsets)` gets **byte** offsets (`lib/material/pbr/pbr-renderable.js` 420,\n * confirmed on a device in spike S0.2) — divide by four for a `Float32Array` index.\n * - PBR fields join the material's own uniform block and need `markMaterialUboDirty`; Standard\n * fields become a self-managed `pluginUbo` that is re-uploaded only when `dynamic` is set, so\n * {@link createLiteMaterialPlugin} sets it for a Standard host alone.\n */\n\n/**\n * A Babylon Lite material plugin, re-exported under an ignifx name so feature code can name the\n * type without importing `@babylonjs/lite` (`CONSTITUTION.md` §3.4).\n *\n * @remarks\n * Unstable; excluded from the stability guarantees of `CONSTITUTION.md` Article IV.\n *\n * @internal\n */\nexport type LiteMaterialPlugin = MaterialPlugin;\n\n/**\n * A Babylon Lite material that can carry plugins: PBR or Standard.\n *\n * @internal\n */\nexport type LitePluginHost = PbrMaterialProps | StandardMaterialProps;\n\n/**\n * One uniform field a plugin appends to its host's uniform block.\n *\n * @internal\n */\nexport interface LitePluginField {\n /** The WGSL field name, already prefixed so it cannot collide with the host's own. */\n readonly name: string;\n /** The WGSL type, used verbatim inside the host's struct. */\n readonly type: string;\n /** How many components the CPU-side value holds: 1, 2, 3, 4, or 16. */\n readonly components: number;\n}\n\n/**\n * One texture/sampler pair a plugin adds to its host's bind group.\n *\n * @internal\n */\nexport interface LitePluginSampler {\n /** The WGSL texture variable name, already prefixed. */\n readonly texture: string;\n /** The WGSL sampler variable name, already prefixed. */\n readonly sampler: string;\n /** Whether the binding is a `texture_2d_array<f32>` rather than a `texture_2d<f32>`. */\n readonly array: boolean;\n}\n\n/**\n * What a plugin injects, split by shader stage the way Lite asks for it.\n *\n * @internal\n */\nexport interface LitePluginCode {\n /** Fragment-stage injection points, by Lite point name. */\n readonly fragment: Partial<Record<MaterialPluginPoint, string>>;\n /** Vertex-stage injection points, by Lite point name. */\n readonly vertex: Partial<Record<MaterialPluginPoint, string>>;\n}\n\n/**\n * The live state a plugin reads at upload time. The render layer owns it and mutates it in place, so\n * a value or texture write costs no rebuild of the plugin object.\n *\n * @internal\n */\nexport interface LitePluginState {\n /** Whether the plugin contributes code at all. Toggling it changes Lite's pipeline cache key. */\n enabled: boolean;\n /** Field name to its current CPU-side floats, in component order. */\n readonly values: ReadonlyMap<string, Float32Array>;\n /** The texture for each declared sampler, in declaration order; `null` entries are skipped. */\n readonly textures: readonly (Texture2D | null)[];\n}\n\n/**\n * Everything that is fixed for the life of one attached plugin.\n *\n * @internal\n */\nexport interface LiteMaterialPluginInput {\n /** The plugin's identity; part of Lite's pipeline cache key. */\n readonly name: string;\n /** Lower runs first. */\n readonly priority: number;\n /** The uniform fields, already prefixed. */\n readonly fields: readonly LitePluginField[];\n /** The samplers, already prefixed. */\n readonly samplers: readonly LitePluginSampler[];\n /** The WGSL to inject. */\n readonly code: LitePluginCode;\n /** Whether the host is a Standard material, which needs `dynamic` to re-upload at all. */\n readonly isStandardHost: boolean;\n}\n\n/** The Lite point names that belong to the vertex stage. */\nconst VERTEX_POINTS: readonly string[] = Object.freeze([\n \"CUSTOM_VERTEX_MAIN_BEGIN\",\n \"CUSTOM_VERTEX_UPDATE_WORLDPOS\",\n \"CUSTOM_VERTEX_MAIN_END\",\n]);\n\n/**\n * Whether a Lite injection point belongs to the vertex stage.\n *\n * @param point - The point name.\n * @returns `true` for the three vertex points.\n *\n * @internal\n */\nexport function isVertexPluginPoint(point: string): boolean {\n return VERTEX_POINTS.includes(point);\n}\n\n/**\n * Builds the Babylon Lite plugin object for one attached surface shader or raw plugin.\n *\n * @remarks\n * The returned object closes over `state`, so the render layer changes a value by writing into\n * `state.values` and then marking the host dirty; the plugin object itself never changes, which is\n * what keeps Lite's pipeline cache key stable.\n *\n * `getCustomCode` returns `null` for a stage with no code and for every stage while the plugin is\n * disabled. Lite already treats a disabled plugin as contributing nothing (`isEnabled`), and the\n * `null` keeps the signature short.\n *\n * @param input - What is fixed about the plugin.\n * @param state - The live values, textures, and enabled flag.\n * @returns The Lite plugin, ready for {@link attachLiteMaterialPlugins}.\n *\n * @internal\n */\nexport function createLiteMaterialPlugin(input: LiteMaterialPluginInput, state: LitePluginState): MaterialPlugin {\n const ubo: PluginUboField[] = input.fields.map((field) => ({ name: field.name, type: field.type }));\n const samplers: PluginSamplerDecl[] = input.samplers.map((sampler) =>\n sampler.array\n ? // The declared type is wider than Lite's TypeScript literal, and the bind-group layout\n // derives `viewDimension` from the string, so the cast is the documented route (spike S0.2).\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n ({\n texture: sampler.texture,\n sampler: sampler.sampler,\n textureType: \"texture_2d_array<f32>\",\n } as unknown as PluginSamplerDecl)\n : { texture: sampler.texture, sampler: sampler.sampler },\n );\n const uniforms = { ubo };\n let integerView: Int32Array | null = null;\n let integerBuffer: ArrayBufferLike | null = null;\n const plugin: MaterialPlugin = {\n name: input.name,\n priority: input.priority,\n get isEnabled(): boolean {\n return state.enabled;\n },\n dynamic: input.isStandardHost,\n getCustomCode(stage: \"vertex\" | \"fragment\"): Partial<Record<MaterialPluginPoint, string>> | null {\n const code = stage === \"vertex\" ? input.code.vertex : input.code.fragment;\n return Object.keys(code).length === 0 ? null : code;\n },\n getUniforms(): { ubo?: PluginUboField[] } {\n return uniforms;\n },\n getSamplers(): PluginSamplerDecl[] {\n return samplers;\n },\n writeUbo(data: Float32Array, offsets: ReadonlyMap<string, number>): void {\n for (const field of input.fields) {\n const byteOffset = offsets.get(field.name);\n const values = state.values.get(field.name);\n if (byteOffset === undefined || values === undefined) {\n continue;\n }\n const index = byteOffset / 4;\n if (field.type === \"u32\" || field.type === \"i32\") {\n if (integerBuffer !== data.buffer) {\n integerBuffer = data.buffer;\n integerView = new Int32Array(data.buffer, data.byteOffset, data.length);\n }\n const view = integerView;\n if (view !== null) {\n view[index] = values[0] ?? 0;\n }\n continue;\n }\n for (let component = 0; component < field.components; component += 1) {\n data[index + component] = values[component] ?? 0;\n }\n }\n },\n bindTextures(out: PluginTextureBinding[]): void {\n for (const texture of state.textures) {\n if (texture !== null) {\n out.push({ texture });\n }\n }\n },\n getActiveTextures(out: Texture2D[]): void {\n for (const texture of state.textures) {\n if (texture !== null) {\n out.push(texture);\n }\n }\n },\n };\n return plugin;\n}\n\n/**\n * Replaces a material's plugin list.\n *\n * @remarks\n * `material.plugins = [plugin]` is the documented attach path (`index.d.ts` 8175, 12253). The list\n * is read when the pipeline is built, so a change to it needs a rebuild of the material's\n * renderables — `rebuildMaterialPipelines` in `src/lite/material.ts` — before it shows up.\n *\n * @param material - The PBR or Standard host.\n * @param plugins - The plugins, in any order; Lite sorts them by `priority`.\n *\n * @internal\n */\nexport function attachLiteMaterialPlugins(material: LitePluginHost, plugins: readonly MaterialPlugin[]): void {\n material.plugins = [...plugins];\n}\n\n/**\n * Clears a material's plugin list.\n *\n * @param material - The PBR or Standard host.\n *\n * @internal\n */\nexport function detachLiteMaterialPlugins(material: LitePluginHost): void {\n material.plugins = [];\n}\n\n/**\n * The plugins currently attached to a material.\n *\n * @param material - The PBR or Standard host.\n * @returns The list, or an empty array when it carries none.\n *\n * @internal\n */\nexport function liteMaterialPlugins(material: LitePluginHost): readonly MaterialPlugin[] {\n return material.plugins ?? [];\n}\n","import {\n attachLiteMaterialPlugins,\n createLiteMaterialPlugin,\n detachLiteMaterialPlugins,\n isVertexPluginPoint,\n} from \"../../lite/gpu/material-plugin.js\";\nimport { markMaterialDirty, rebuildMaterialPipelines } from \"../../lite/material.js\";\nimport { uniformComponentCount } from \"../material-plugin.js\";\nimport { shaderMaterialsOf } from \"../shader-material.js\";\nimport type { App } from \"../../app/types.js\";\nimport type {\n LiteMaterialPlugin,\n LitePluginCode,\n LitePluginHost,\n LitePluginState,\n} from \"../../lite/gpu/material-plugin.js\";\nimport type { LiteTexture2D } from \"../../lite/gpu/texture.js\";\nimport type { MaterialAsset } from \"../material-asset.js\";\nimport type { LiteMaterialPluginPoint } from \"../material-plugin.js\";\nimport type { ShaderTextureDeclaration } from \"../shader-declaration.js\";\nimport type { CompiledSurfaceShader, SurfaceHostCapabilities } from \"../surface-shader-compiler.js\";\nimport type { SurfaceShaderInit } from \"../surface-shader.js\";\n\n/**\n * The device-only half of surface shaders: the Lite plugin a compiled `.surface.wgsl` becomes, and\n * the host-material writes that follow it (`docs/plan/2026-09-terrain-particles-shaders.md` §3.2).\n *\n * Each entry point takes the app or the host as a nullable and returns early when it is `null`, so\n * `../surface-shader.ts` keeps no headless branch of its own.\n */\n\n/**\n * The host material a surface shader attaches to, when there is a device.\n *\n * @remarks\n * `assertHostFamily` refused the shader family, so the Lite material is a PBR or Standard one and\n * both carry `plugins` (`index.d.ts` 8175, 12253).\n *\n * @param material - The material asset.\n * @param isHeadless - Whether the app has a device.\n * @returns The Lite material, or `null`.\n *\n * @internal\n */\nexport function resolveSurfaceHost(material: MaterialAsset, isHeadless: boolean): LitePluginHost | null {\n return isHeadless ? null : material.lite.material;\n}\n\n/**\n * Re-uploads the host material's uniform block after a value write.\n *\n * @remarks\n * Lite ignores `dynamic` for a PBR host and re-reads the plugin slice only after this (spike S0.2);\n * a Standard host re-uploads every frame because the plugin sets `dynamic`.\n *\n * @param host - The host material, or `null`.\n * @param isPbr - Whether the host is a PBR material.\n *\n * @internal\n */\nexport function markSurfaceValueChanged(host: LitePluginHost | null, isPbr: boolean): void {\n if (host === null || !isPbr) {\n return;\n }\n markMaterialDirty(host);\n}\n\n/**\n * Rebuilds the host material's renderables, which a bind-group or feature change needs.\n *\n * @param app - The app, or `null` when the attachment was built without one.\n * @param host - The host material, or `null`.\n * @param isLive - Whether Lite has already been handed the plugin list.\n *\n * @internal\n */\nexport function rebuildSurfaceHost(app: App | null, host: LitePluginHost | null, isLive: boolean): void {\n if (!isLive || app === null || host === null || app.isHeadless) {\n return;\n }\n rebuildMaterialPipelines(app.lite.scene, host);\n}\n\n/**\n * Hands Lite the plugins a material's surface shaders compiled to, when there are any.\n *\n * @param host - The host material, or `null`.\n * @param plugins - The plugins, in attach order.\n *\n * @internal\n */\nexport function attachSurfacePlugins(host: LitePluginHost | null, plugins: readonly LiteMaterialPlugin[]): void {\n if (host === null || plugins.length === 0) {\n return;\n }\n attachLiteMaterialPlugins(host, plugins);\n}\n\n/**\n * Takes a material's surface-shader plugins off its Lite material.\n *\n * @remarks\n * A `\"shader\"` material never hosts one, and its Lite object carries no `plugins` field to clear.\n *\n * @param material - The material asset.\n *\n * @internal\n */\nexport function detachSurfacePlugins(material: MaterialAsset): void {\n if (material.definition.kind === \"shader\") {\n return;\n }\n detachLiteMaterialPlugins(material.lite.material);\n}\n\n/**\n * The 1x1 fallback each declared sampler falls back to, or nulls under a headless app.\n *\n * @param app - The app, or `null`.\n * @param declarations - The file's declared samplers, in declaration order.\n * @returns One entry per declaration.\n *\n * @internal\n */\nexport function resolveSurfaceFallbacks(\n app: App | null,\n declarations: readonly ShaderTextureDeclaration[],\n): (LiteTexture2D | null)[] {\n if (app === null || app.isHeadless) {\n return declarations.map((): null => null);\n }\n const registry = shaderMaterialsOf(app);\n return declarations.map((declaration) => registry.fallbackTexture(declaration));\n}\n\n/**\n * Builds the Lite plugin for one compiled surface shader, when there is a device.\n *\n * @param app - The app, or `null`.\n * @param compiled - The compiled shader.\n * @param init - What the material declared, for the priority.\n * @param capabilities - The host family, which decides how a value reaches the GPU.\n * @param state - The live state the plugin reads.\n * @returns The plugin, or `null` under a headless app.\n *\n * @internal\n */\nexport function buildSurfacePlugin(\n app: App | null,\n compiled: CompiledSurfaceShader,\n init: SurfaceShaderInit,\n capabilities: SurfaceHostCapabilities,\n state: LitePluginState,\n): LiteMaterialPlugin | null {\n if (app === null || app.isHeadless) {\n return null;\n }\n return buildLitePlugin(compiled, init, capabilities, state);\n}\n\n/**\n * Builds the Lite plugin for one compiled surface shader.\n *\n * @param compiled - The compiled shader.\n * @param init - What the material declared, for the priority.\n * @param capabilities - The host family, which decides how a value reaches the GPU.\n * @param state - The live state the plugin reads.\n * @returns The plugin.\n */\nfunction buildLitePlugin(\n compiled: CompiledSurfaceShader,\n init: SurfaceShaderInit,\n capabilities: SurfaceHostCapabilities,\n state: LitePluginState,\n): LiteMaterialPlugin {\n const fragment: Record<string, string> = {};\n const vertex: Record<string, string> = {};\n for (const point of Object.keys(compiled.plugin.code)) {\n // The keys came from the compiler, which only ever writes Lite's own point names.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const wgsl = compiled.plugin.code[point as LiteMaterialPluginPoint];\n if (wgsl === undefined) {\n continue;\n }\n if (isVertexPluginPoint(point)) {\n vertex[point] = wgsl;\n } else {\n fragment[point] = wgsl;\n }\n }\n // The two records are keyed by Lite's own point names, which the compiler produced, so the shape\n // is the `Partial<Record<MaterialPluginPoint, string>>` the adapter declares.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const code = { fragment, vertex } as LitePluginCode;\n return createLiteMaterialPlugin(\n {\n name: compiled.plugin.name,\n priority: init.priority ?? compiled.plugin.priority,\n fields: compiled.plugin.uniforms.map((uniform) => ({\n name: uniform.name,\n type: uniform.type,\n components: uniformComponentCount(uniform.type),\n })),\n samplers: compiled.plugin.textures.map((texture) => ({\n texture: texture.name,\n sampler: `${texture.name}Sampler`,\n array: texture.array,\n })),\n code,\n isStandardHost: capabilities.family === \"standard\",\n },\n state,\n );\n}\n","import { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { IgnifxError } from \"../errors/ignifx-error.js\";\nimport { defineMaterialPlugin } from \"./material-plugin.js\";\nimport { SURFACE_HOOK_NAMES, SURFACE_UNIFORM_BLOCK } from \"./shader-declaration.js\";\nimport type { LiteMaterialPluginPoint, MaterialPluginDefinition } from \"./material-plugin.js\";\nimport type { ShaderDeclaration, SurfaceHookName } from \"./shader-declaration.js\";\n\n/**\n * The surface-shader compiler: three plain WGSL functions in, one Babylon Lite material plugin out\n * (`docs/plan/2026-09-terrain-particles-shaders.md` §3.2).\n *\n * A `.surface.wgsl` declares its uniforms and textures with `// @ignifx` pragmas and provides up to\n * three functions that never mention Lite: `SurfaceInput`, `Surface` and `DisplaceInput` are\n * generated here, and `surfaceUniforms.x` is rewritten to whichever uniform block the host family\n * carries.\n *\n * ```wgsl\n * // @ignifx surface\n * // @ignifx uniform amount: f32 = 0.6 range(0, 1)\n * fn surface(in: SurfaceInput, s: ptr<function, Surface>) {\n * (*s).baseColor = mix((*s).baseColor, vec3<f32>(1.0), surfaceUniforms.amount);\n * }\n * ```\n *\n * Where each hook lands, and what that costs:\n *\n * | Hook | PBR slot | Standard slot |\n * | --- | --- | --- |\n * | `displace` | `CUSTOM_VERTEX_UPDATE_WORLDPOS`, inlined | the same |\n * | `surface` | `CUSTOM_FRAGMENT_UPDATE_ALPHA` + `CUSTOM_FRAGMENT_UPDATE_DIFFUSE` | `CUSTOM_FRAGMENT_UPDATE_ALPHA` alone |\n * | `composite` | `CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION` | **unsupported** |\n *\n * - Every declared name is emitted as `<shader>_<name>` and the author's references are rewritten,\n * because a plugin's fields join the **host material's** uniform block and bind group. A declared\n * texture's name is therefore reserved inside the file.\n * - `displace` cannot read a uniform, a texture or a helper function — Lite's plugin uniforms and\n * samplers are fragment-visible only and it offers no vertex helper channel — so its body is\n * inlined with its `return` rewritten to a `break`, and one that reads any of them, or that loops\n * or switches (which would capture that `break`), is refused here.\n * - A `surface` hook's write to `alpha` reaches blending, not the cutout test: the alpha-test\n * fragment sorts before a plugin in Lite's slot composition, so an `alphaMode: \"mask\"` host has\n * already discarded by the time the hook runs.\n * - `composite` is injected twice (Lite maps the point to the adjacent PBR slots `AI` and `NI`), so\n * the generated code is guarded by a flag declared in the `UPDATE_ALPHA` block.\n * - `emissive` is written as the delta `s.emissive - emissive` added to `color`, because the PBR\n * template declares `emissive` as `let` or `var` depending on the host's textures.\n * - `roughness` and `metallic` are readable and ignored on write (`let` in the template). Vertex\n * colour reads white and `uv2` is absent: Lite gates both behind state a plugin cannot see.\n */\n\n/**\n * The material family a surface shader is compiled against. The generated WGSL differs: the two\n * templates name their variables differently and Standard has fewer injection points.\n *\n * @public\n */\nexport type SurfaceHostFamily = \"pbr\" | \"standard\";\n\n/**\n * What the compiler has to know about the host material beyond its family.\n *\n * @remarks\n * Both flags exist because Standard's template declares a varying or a variable only when something\n * asks for it: `input.vu` exists only when the material carries a texture that samples UV\n * (`standard-flags.js` `NEEDS_UV`), and `normalW` only when lighting is on. Referencing either\n * without it is a WGSL compile error in Lite's own template, so the compiler substitutes a constant\n * instead. A PBR host always has both.\n *\n * @public\n */\nexport interface SurfaceHostCapabilities {\n /** Which family's slots and variable names to generate for. */\n readonly family: SurfaceHostFamily;\n /** Whether the host declares a UV varying. `false` makes `in.uv` read `(0, 0)`. */\n readonly hasUv: boolean;\n /** Whether the host declares a shading normal. `false` makes a `normal` write a no-op. */\n readonly hasNormal: boolean;\n}\n\n/**\n * One hook, as it was found in the file.\n *\n * @internal\n */\nexport interface SurfaceHook {\n /** Which hook it is. */\n readonly name: SurfaceHookName;\n /** The parameter identifiers, in order, as the author wrote them. */\n readonly parameters: readonly string[];\n /** The statements between the braces, verbatim. */\n readonly body: string;\n /** Where the whole `fn …` declaration starts in the source. */\n readonly start: number;\n /** Where it ends, one past the closing brace. */\n readonly end: number;\n}\n\n/**\n * The hooks a file provides, plus everything else it declared.\n *\n * @internal\n */\nexport interface SurfaceShaderHooks {\n /** The vertex offset hook, or `null`. */\n readonly displace: SurfaceHook | null;\n /** The surface hook, or `null`. */\n readonly surface: SurfaceHook | null;\n /** The post-lighting hook, or `null`. */\n readonly composite: SurfaceHook | null;\n /** The file with the three hook declarations cut out: structs, constants, helper functions. */\n readonly rest: string;\n}\n\n/** The members a `displace` hook may read off its parameter. */\nconst DISPLACE_MEMBERS: readonly string[] = Object.freeze([\"position\", \"normal\", \"uv\", \"color\", \"world\"]);\n\n/** Matches the start of a top-level hook declaration. */\nconst HOOK_START = /\\bfn\\s+(displace|surface|composite)\\s*\\(/g;\n\n/** Matches `surfaceUniforms.<identifier>`. */\nconst UNIFORM_REFERENCE = /\\bsurfaceUniforms\\s*\\.\\s*([A-Za-z_][A-Za-z0-9_]*)/g;\n\n/** Matches a `return <expression>;` statement. */\nconst RETURN_STATEMENT = /\\breturn\\b([^;]*);/g;\n\n/** Matches any WGSL control-flow construct a `break` could bind to. */\nconst BREAKING_CONSTRUCT = /\\b(loop|for|while|switch)\\b/;\n\n/** Matches the start of any top-level function declaration, capturing its name. */\nconst FUNCTION_START = /\\bfn\\s+([A-Za-z_][A-Za-z0-9_]*)\\s*\\(/g;\n\n/**\n * Finds the hooks a `.surface.wgsl` file declares.\n *\n * @remarks\n * A hand-written brace scan rather than a WGSL parser: the file has already been validated by the\n * Vite plugin at build time, and all this needs is the extent of three top-level functions. It\n * looks for `fn displace|surface|composite (` anywhere in the file and then matches the parameter\n * parentheses and the body braces, so a hook may be written in any order and with any formatting.\n *\n * @param source - The whole file.\n * @param address - The asset address, for the error message.\n * @returns The hooks found and the rest of the file.\n * @throws IgnifxError with code `IGX-0723` when the file declares none of the three, or `IGX-0719`\n * when a hook's braces or parentheses do not close.\n *\n * @internal\n */\nexport function parseSurfaceHooks(source: string, address: string): SurfaceShaderHooks {\n const found = new Map<SurfaceHookName, SurfaceHook>();\n const cuts: { start: number; end: number }[] = [];\n HOOK_START.lastIndex = 0;\n let match = HOOK_START.exec(source);\n while (match !== null) {\n const name = match[1];\n const openParen = match.index + match[0].length - 1;\n const closeParen = matchDelimiter(source, openParen, \"(\", \")\");\n const openBrace = source.indexOf(\"{\", closeParen);\n if (closeParen < 0 || openBrace < 0) {\n throw new IgnifxError(CoreErrorCode.invalidShaderPragma, `${address}: the ${name} hook does not close.`, {\n context: { asset: address, hook: name ?? \"\" },\n hint: \"Check the parentheses and braces of the hook declaration.\",\n });\n }\n const closeBrace = matchDelimiter(source, openBrace, \"{\", \"}\");\n if (closeBrace < 0) {\n throw new IgnifxError(CoreErrorCode.invalidShaderPragma, `${address}: the ${name} hook's body does not close.`, {\n context: { asset: address, hook: name ?? \"\" },\n hint: \"Add the missing closing brace.\",\n });\n }\n if (isSurfaceHookName(name)) {\n found.set(name, {\n name,\n parameters: parseParameterNames(source.slice(openParen + 1, closeParen)),\n body: source.slice(openBrace + 1, closeBrace),\n start: match.index,\n end: closeBrace + 1,\n });\n cuts.push({ start: match.index, end: closeBrace + 1 });\n }\n HOOK_START.lastIndex = closeBrace + 1;\n match = HOOK_START.exec(source);\n }\n if (found.size === 0) {\n throw new IgnifxError(\n CoreErrorCode.surfaceHookMissing,\n `${address} declares a surface shader with none of the hooks displace, surface, or composite.`,\n {\n context: { asset: address },\n hint: \"Add fn surface(in: SurfaceInput, s: ptr<function, Surface>), fn composite(in, color), or fn displace(in).\",\n },\n );\n }\n return {\n displace: found.get(\"displace\") ?? null,\n surface: found.get(\"surface\") ?? null,\n composite: found.get(\"composite\") ?? null,\n rest: cutRanges(source, cuts),\n };\n}\n\n/**\n * What {@link compileSurfaceShader} needs.\n *\n * @internal\n */\nexport interface SurfaceShaderCompileInput {\n /** The shader's name on the material; it prefixes every generated identifier. */\n readonly name: string;\n /** The asset address, for error messages. */\n readonly address: string;\n /** The whole `.surface.wgsl` file. */\n readonly source: string;\n /** What its pragmas declared. */\n readonly declaration: ShaderDeclaration;\n /** The host material family and what its template exposes. */\n readonly host: SurfaceHostCapabilities;\n}\n\n/**\n * A compiled surface shader: the Lite plugin, and the mapping from the names the author declared to\n * the prefixed fields the host material actually carries.\n *\n * @internal\n */\nexport interface CompiledSurfaceShader {\n /** The Lite plugin definition, whose bindings are named `<shader>_<declared>`. */\n readonly plugin: MaterialPluginDefinition;\n /** The prefix every generated identifier carries, including the trailing underscore. */\n readonly prefix: string;\n /** Which hooks the file provided. */\n readonly hooks: Readonly<Record<SurfaceHookName, boolean>>;\n}\n\n/**\n * Compiles a `.surface.wgsl` file into one Babylon Lite material plugin.\n *\n * @remarks\n * Deterministic and device-free, so it is fully testable in Node: the result is the plain\n * {@link MaterialPluginDefinition} the adapter turns into a Lite object.\n *\n * @param input - The shader, its declaration, and the host family.\n * @returns The plugin definition, with the generated WGSL in `code`, and its name prefix.\n * @throws IgnifxError with code `IGX-0723` when the file declares no hook, or a hook the host family\n * has no slot for, or a `displace` that reads a uniform or a texture; `IGX-0712` when a declared\n * name is not usable as a plugin binding; `IGX-0719` when a hook is malformed.\n *\n * @example\n * ```ts\n * const compiled = compileSurfaceShader({\n * name: \"snow\",\n * address: \"shaders/snow.surface.wgsl\",\n * source,\n * declaration,\n * host: { family: \"pbr\", hasUv: true, hasNormal: true },\n * });\n * compiled.plugin.code.CUSTOM_FRAGMENT_UPDATE_ALPHA; // builds SurfaceInput and calls snow_surface\n * ```\n *\n * @internal\n */\nexport function compileSurfaceShader(input: SurfaceShaderCompileInput): CompiledSurfaceShader {\n const hooks = parseSurfaceHooks(input.source, input.address);\n const prefix = `${sanitizeIdentifier(input.name)}_`;\n const isStandard = input.host.family === \"standard\";\n if (isStandard && hooks.composite !== null) {\n throw new IgnifxError(\n CoreErrorCode.surfaceHookMissing,\n `${input.address} declares the composite hook, which a standard material has no slot for.`,\n {\n context: { asset: input.address, hook: \"composite\", family: input.host.family },\n hint: \"Attach the surface shader to a pbr material, or move the effect into the surface hook.\",\n },\n );\n }\n const rewrite = buildRewriter(prefix, input.declaration, isStandard);\n const code: Partial<Record<LiteMaterialPluginPoint, string>> = {};\n const definitions = buildDefinitions(prefix, hooks, rewrite);\n if (definitions !== \"\") {\n code.CUSTOM_FRAGMENT_DEFINITIONS = definitions;\n }\n if (hooks.surface !== null || hooks.composite !== null) {\n code.CUSTOM_FRAGMENT_UPDATE_ALPHA = buildUpdateAlpha(prefix, hooks, input.host);\n if (hooks.surface !== null && !isStandard) {\n code.CUSTOM_FRAGMENT_UPDATE_DIFFUSE = `if(any(${prefix}normal!=${prefix}in.geometricNormal)){N=normalize(${prefix}normal);}`;\n }\n if (!isStandard) {\n code.CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION = buildComposite(prefix, hooks);\n }\n }\n if (hooks.displace !== null) {\n code.CUSTOM_VERTEX_UPDATE_WORLDPOS = buildDisplace(prefix, hooks.displace, input);\n }\n const plugin = defineMaterialPlugin({\n name: input.name,\n uniforms: input.declaration.uniforms.map((uniform) => ({ ...uniform, name: `${prefix}${uniform.name}` })),\n textures: input.declaration.textures.map((texture) => ({ ...texture, name: `${prefix}${texture.name}` })),\n code,\n });\n return {\n plugin,\n prefix,\n hooks: {\n displace: hooks.displace !== null,\n surface: hooks.surface !== null,\n composite: hooks.composite !== null,\n },\n };\n}\n\n/**\n * The fragment helper block: the generated structs and everything the file declared, hooks included,\n * with the two fragment hooks given generated signatures.\n *\n * @param prefix - The per-shader identifier prefix.\n * @param hooks - The parsed hooks.\n * @param rewrite - The identifier rewriter.\n * @returns The WGSL, or `\"\"` when the file provides no fragment hook.\n */\nfunction buildDefinitions(prefix: string, hooks: SurfaceShaderHooks, rewrite: (code: string) => string): string {\n if (hooks.surface === null && hooks.composite === null) {\n return \"\";\n }\n const parts: string[] = [\n `struct ${prefix}SurfaceInput{uv:vec2<f32>,worldPosition:vec3<f32>,geometricNormal:vec3<f32>,viewDirection:vec3<f32>,color:vec4<f32>,}`,\n `struct ${prefix}Surface{baseColor:vec3<f32>,alpha:f32,emissive:vec3<f32>,normal:vec3<f32>,roughness:f32,metallic:f32,}`,\n rewrite(hooks.rest),\n ];\n const surface = hooks.surface;\n if (surface !== null) {\n const input = surface.parameters[0] ?? \"in\";\n const state = surface.parameters[1] ?? \"s\";\n parts.push(\n `fn ${prefix}surface(${input}:${prefix}SurfaceInput,${state}:ptr<function,${prefix}Surface>){${rewrite(surface.body)}}`,\n );\n }\n const composite = hooks.composite;\n if (composite !== null) {\n const input = composite.parameters[0] ?? \"in\";\n const color = composite.parameters[1] ?? \"color\";\n parts.push(\n `fn ${prefix}composite(${input}:${prefix}SurfaceInput,${color}:vec3<f32>)->vec3<f32>{${rewrite(composite.body)}}`,\n );\n }\n return parts.join(\"\\n\");\n}\n\n/**\n * The `CUSTOM_FRAGMENT_UPDATE_ALPHA` block: build `SurfaceInput`, call the hook, write back what the\n * template lets us write back, and stash the rest for the later slots.\n *\n * @remarks\n * Deliberately **not** wrapped in braces: the variables it declares are read by the\n * `UPDATE_DIFFUSE` and `BEFORE_FINALCOLORCOMPOSITION` blocks, which Lite injects into the same\n * function scope further down. Every name is prefixed, so two surface shaders on one material\n * declare two sets rather than colliding.\n *\n * @param prefix - The per-shader identifier prefix.\n * @param hooks - The parsed hooks.\n * @param host - The host family and its capabilities.\n * @returns The WGSL statements.\n */\nfunction buildUpdateAlpha(prefix: string, hooks: SurfaceShaderHooks, host: SurfaceHostCapabilities): string {\n const isStandard = host.family === \"standard\";\n const worldPosition = isStandard ? \"input.vp\" : \"input.worldPos\";\n const geometricNormal = isStandard ? \"normalize(input.vn)\" : \"normalize(input.worldNormal)\";\n const uv = host.hasUv ? (isStandard ? \"input.vu\" : \"input.uv\") : \"vec2<f32>(0.0)\";\n const emissive = isStandard ? \"emissiveContrib\" : \"emissive\";\n const lines: string[] = [\n `var ${prefix}in:${prefix}SurfaceInput;`,\n `${prefix}in.uv=${uv};`,\n `${prefix}in.worldPosition=${worldPosition};`,\n `${prefix}in.geometricNormal=${geometricNormal};`,\n `${prefix}in.viewDirection=normalize(scene.vEyePosition.xyz-${worldPosition});`,\n `${prefix}in.color=vec4<f32>(1.0);`,\n `var ${prefix}emissiveDelta=vec3<f32>(0.0);`,\n `var ${prefix}composited=false;`,\n ];\n if (hooks.surface !== null) {\n lines.push(\n `var ${prefix}s:${prefix}Surface;`,\n `${prefix}s.baseColor=baseColor;`,\n `${prefix}s.alpha=alpha;`,\n `${prefix}s.emissive=${emissive};`,\n `${prefix}s.normal=${prefix}in.geometricNormal;`,\n // Standard has no roughness or metallic at all; PBR has both, as read-only `let`s.\n isStandard ? `${prefix}s.roughness=1.0;` : `${prefix}s.roughness=roughness;`,\n isStandard ? `${prefix}s.metallic=0.0;` : `${prefix}s.metallic=metallic;`,\n `${prefix}surface(${prefix}in,&${prefix}s);`,\n `baseColor=${prefix}s.baseColor;`,\n `alpha=${prefix}s.alpha;`,\n `var ${prefix}normal=${prefix}s.normal;`,\n );\n if (isStandard) {\n // Standard's `/*AC*/` runs before `/*AT*/`, so the normal is written here, and its emissive\n // term is a `var` we can replace outright.\n lines.push(`${emissive}=${prefix}s.emissive;`);\n if (host.hasNormal) {\n lines.push(`if(any(${prefix}normal!=${prefix}in.geometricNormal)){normalW=normalize(${prefix}normal);}`);\n }\n } else {\n lines.push(`${prefix}emissiveDelta=${prefix}s.emissive-${emissive};`);\n }\n }\n return lines.join(\"\\n\");\n}\n\n/**\n * The `CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION` block: the emissive delta and the `composite`\n * hook, guarded because Lite injects this point twice.\n *\n * @param prefix - The per-shader identifier prefix.\n * @param hooks - The parsed hooks.\n * @returns The WGSL statements.\n */\nfunction buildComposite(prefix: string, hooks: SurfaceShaderHooks): string {\n const inner: string[] = [`${prefix}composited=true;`, `color=color+${prefix}emissiveDelta;`];\n if (hooks.composite !== null) {\n inner.push(`color=${prefix}composite(${prefix}in,color);`);\n }\n return `if(!${prefix}composited){${inner.join(\"\")}}`;\n}\n\n/**\n * The `CUSTOM_VERTEX_UPDATE_WORLDPOS` block: the `displace` body, inlined.\n *\n * @remarks\n * Inlined rather than called, because Lite gives a plugin no way to declare a function in the vertex\n * module (`buildPluginFragment` fills `_helperFunctions`, which the composer routes to the fragment\n * template alone). The body is wrapped in a `loop` whose `return` statements are rewritten to\n * `break`, which is what lets an author write ordinary early-returning WGSL: a value-returning\n * function has to return on every path, so the loop always terminates on its first iteration.\n *\n * @param prefix - The per-shader identifier prefix.\n * @param hook - The parsed `displace` hook.\n * @param input - The compile input, for the declaration and the error messages.\n * @returns The WGSL statements.\n * @throws IgnifxError with code `IGX-0723` when the body reads a uniform, a texture, or a member\n * that the vertex stage cannot supply.\n */\nfunction buildDisplace(prefix: string, hook: SurfaceHook, input: SurfaceShaderCompileInput): string {\n assertVertexSafe(hook, input);\n const parameter = hook.parameters[0] ?? \"in\";\n const uv = input.host.hasUv ? \"uv\" : \"vec2<f32>(0.0)\";\n let body = hook.body;\n body = body.replaceAll(new RegExp(`\\\\b${escapeForRegExp(parameter)}\\\\s*\\\\.\\\\s*position\\\\b`, \"g\"), \"position\");\n body = body.replaceAll(new RegExp(`\\\\b${escapeForRegExp(parameter)}\\\\s*\\\\.\\\\s*normal\\\\b`, \"g\"), \"normal\");\n body = body.replaceAll(new RegExp(`\\\\b${escapeForRegExp(parameter)}\\\\s*\\\\.\\\\s*uv\\\\b`, \"g\"), uv);\n body = body.replaceAll(new RegExp(`\\\\b${escapeForRegExp(parameter)}\\\\s*\\\\.\\\\s*color\\\\b`, \"g\"), \"vec4<f32>(1.0)\");\n body = body.replaceAll(new RegExp(`\\\\b${escapeForRegExp(parameter)}\\\\s*\\\\.\\\\s*world\\\\b`, \"g\"), \"finalWorld\");\n body = body.replaceAll(RETURN_STATEMENT, (_whole: string, expression: string): string => {\n return `{${prefix}offset=${expression.trim()};break;}`;\n });\n return [\n `{var ${prefix}offset=vec3<f32>(0.0);`,\n `loop{${body}}`,\n `finalWorld[3].x+=${prefix}offset.x;`,\n `finalWorld[3].y+=${prefix}offset.y;`,\n `finalWorld[3].z+=${prefix}offset.z;}`,\n ].join(\"\\n\");\n}\n\n/**\n * Refuses a `displace` body the vertex stage cannot compile.\n *\n * @param hook - The parsed hook.\n * @param input - The compile input.\n * @throws IgnifxError with code `IGX-0723`.\n */\nfunction assertVertexSafe(hook: SurfaceHook, input: SurfaceShaderCompileInput): void {\n const address = input.address;\n if (hook.body.includes(SURFACE_UNIFORM_BLOCK)) {\n throw new IgnifxError(\n CoreErrorCode.surfaceHookMissing,\n `${address}: the displace hook reads ${SURFACE_UNIFORM_BLOCK}, which Babylon Lite declares in the fragment stage only.`,\n {\n context: { asset: address, hook: \"displace\" },\n hint: \"Displace by geometry alone on Lite 1.27.0; a time-driven offset needs a full shader material.\",\n },\n );\n }\n for (const texture of input.declaration.textures) {\n if (new RegExp(`\\\\b${escapeForRegExp(texture.name)}\\\\b`).test(hook.body)) {\n throw new IgnifxError(\n CoreErrorCode.surfaceHookMissing,\n `${address}: the displace hook samples ${texture.name}, and Babylon Lite's plugin samplers are fragment-stage only.`,\n {\n context: { asset: address, hook: \"displace\", name: texture.name },\n hint: \"Move the texture read into the surface hook, or use a full shader material.\",\n },\n );\n }\n }\n if (BREAKING_CONSTRUCT.test(hook.body)) {\n throw new IgnifxError(\n CoreErrorCode.surfaceHookMissing,\n `${address}: the displace hook uses a loop or switch, which this build cannot inline into Babylon Lite's vertex entry point.`,\n {\n context: { asset: address, hook: \"displace\" },\n hint: \"Write the displacement as straight-line code, or use a full shader material.\",\n },\n );\n }\n for (const helper of fileFunctions(input.source)) {\n if (new RegExp(`\\\\b${escapeForRegExp(helper)}\\\\s*\\\\(`).test(hook.body)) {\n throw new IgnifxError(\n CoreErrorCode.surfaceHookMissing,\n `${address}: the displace hook calls ${helper}, and Babylon Lite gives a plugin no vertex-stage helper functions.`,\n {\n context: { asset: address, hook: \"displace\", name: helper },\n hint: \"Inline the helper into the displace body, or use a full shader material.\",\n },\n );\n }\n }\n const parameter = hook.parameters[0] ?? \"in\";\n const members = new RegExp(`\\\\b${escapeForRegExp(parameter)}\\\\s*\\\\.\\\\s*([A-Za-z_][A-Za-z0-9_]*)`, \"g\");\n let match = members.exec(hook.body);\n while (match !== null) {\n const member = match[1] ?? \"\";\n if (!DISPLACE_MEMBERS.includes(member)) {\n throw new IgnifxError(\n CoreErrorCode.surfaceHookMissing,\n `${address}: the displace hook reads ${parameter}.${member}, which DisplaceInput does not carry.`,\n {\n context: { asset: address, hook: \"displace\", name: member },\n hint: `DisplaceInput carries ${DISPLACE_MEMBERS.join(\", \")}.`,\n },\n );\n }\n match = members.exec(hook.body);\n }\n}\n\n/**\n * The names of every function a file declares that is not one of the three hooks.\n *\n * @param source - The whole `.surface.wgsl` file.\n * @returns The helper names, in declaration order.\n */\nfunction fileFunctions(source: string): readonly string[] {\n const names: string[] = [];\n FUNCTION_START.lastIndex = 0;\n let match = FUNCTION_START.exec(source);\n while (match !== null) {\n const name = match[1] ?? \"\";\n if (!(SURFACE_HOOK_NAMES as readonly string[]).includes(name)) {\n names.push(name);\n }\n match = FUNCTION_START.exec(source);\n }\n return names;\n}\n\n/**\n * Builds the function that rewrites the author's references to the names the host material actually\n * declares.\n *\n * @param prefix - The per-shader identifier prefix.\n * @param declaration - What the file declared, for its texture names.\n * @param isStandard - Whether the host is a Standard material, which reads its plugin uniforms from\n * `pluginUbo` rather than from the PBR material block (`plugin-bridge-shared.js` 99).\n * @returns The rewriter.\n */\nfunction buildRewriter(prefix: string, declaration: ShaderDeclaration, isStandard: boolean): (code: string) => string {\n const block = isStandard ? \"pluginUbo\" : \"material\";\n const samplers: string[] = [];\n for (const texture of declaration.textures) {\n samplers.push(`${texture.name}Sampler`, texture.name);\n }\n // Longest first, so `noiseSampler` is not rewritten as the prefix of `noise` plus `Sampler`.\n samplers.sort((left, right) => right.length - left.length);\n const pattern = samplers.length === 0 ? null : new RegExp(`\\\\b(${samplers.map(escapeForRegExp).join(\"|\")})\\\\b`, \"g\");\n return (code: string): string => {\n const withUniforms = code.replaceAll(UNIFORM_REFERENCE, (_whole: string, name: string): string => {\n return `${block}.${prefix}${name}`;\n });\n return pattern === null\n ? withUniforms\n : withUniforms.replaceAll(pattern, (_whole: string, name: string): string => `${prefix}${name}`);\n };\n}\n\n/**\n * The index of the delimiter that closes the one at `open`.\n *\n * @param source - The text.\n * @param open - The index of the opening delimiter.\n * @param openChar - The opening delimiter.\n * @param closeChar - The closing delimiter.\n * @returns The closing index, or `-1` when it never closes.\n */\nfunction matchDelimiter(source: string, open: number, openChar: string, closeChar: string): number {\n let depth = 0;\n for (let index = open; index < source.length; index += 1) {\n const char = source[index];\n if (char === openChar) {\n depth += 1;\n } else if (char === closeChar) {\n depth -= 1;\n if (depth === 0) {\n return index;\n }\n }\n }\n return -1;\n}\n\n/**\n * The parameter identifiers of a WGSL parameter list.\n *\n * @param list - The text between the parentheses.\n * @returns The names, in order.\n */\nfunction parseParameterNames(list: string): readonly string[] {\n const names: string[] = [];\n let depth = 0;\n let start = 0;\n for (let index = 0; index <= list.length; index += 1) {\n const char = list[index];\n if (char === \"<\" || char === \"(\") {\n depth += 1;\n } else if (char === \">\" || char === \")\") {\n depth -= 1;\n } else if ((char === \",\" && depth === 0) || index === list.length) {\n const parameter = list.slice(start, index).trim();\n const colon = parameter.indexOf(\":\");\n const name = (colon < 0 ? parameter : parameter.slice(0, colon)).trim();\n if (name !== \"\") {\n names.push(name);\n }\n start = index + 1;\n }\n }\n return names;\n}\n\n/**\n * The text with the given ranges removed.\n *\n * @param source - The text.\n * @param ranges - The ranges to cut, in ascending order.\n * @returns What is left.\n */\nfunction cutRanges(source: string, ranges: readonly { start: number; end: number }[]): string {\n let result = \"\";\n let cursor = 0;\n for (const range of ranges) {\n result += source.slice(cursor, range.start);\n cursor = range.end;\n }\n return result + source.slice(cursor);\n}\n\n/**\n * Whether a captured name is one of the three hooks.\n *\n * @param value - The candidate.\n * @returns `true` when it is.\n */\nfunction isSurfaceHookName(value: string | undefined): value is SurfaceHookName {\n return value === \"displace\" || value === \"surface\" || value === \"composite\";\n}\n\n/**\n * Turns a shader name into a WGSL identifier prefix.\n *\n * @param name - The shader's name on the material.\n * @returns The sanitized name; a leading digit is prefixed with an underscore.\n *\n * @internal\n */\nexport function sanitizeIdentifier(name: string): string {\n const replaced = name.replaceAll(/[^A-Za-z0-9_]/g, \"_\");\n return /^[0-9]/.test(replaced) ? `_${replaced}` : replaced;\n}\n\n/**\n * Escapes a literal for use inside a regular expression.\n *\n * @param value - The literal.\n * @returns The escaped form.\n */\nfunction escapeForRegExp(value: string): string {\n return value.replaceAll(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n","import { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { IgnifxError } from \"../errors/ignifx-error.js\";\nimport { Color } from \"../math/color.js\";\nimport {\n attachSurfacePlugins,\n buildSurfacePlugin,\n detachSurfacePlugins,\n markSurfaceValueChanged,\n rebuildSurfaceHost,\n resolveSurfaceFallbacks,\n resolveSurfaceHost,\n} from \"./gpu/surface-shader-host.js\";\nimport { MATERIAL_PLUGIN_SAMPLER_BUDGET, uniformComponentCount } from \"./material-plugin.js\";\nimport { compileSurfaceShader, sanitizeIdentifier } from \"./surface-shader-compiler.js\";\nimport type { MaterialAsset } from \"./material-asset.js\";\nimport type { ShaderAsset } from \"./shader-asset.js\";\nimport type { ShaderUniformDeclaration } from \"./shader-declaration.js\";\nimport type { SurfaceHostCapabilities } from \"./surface-shader-compiler.js\";\nimport type { TextureAsset } from \"./texture-asset.js\";\nimport type { App } from \"../app/types.js\";\nimport type { AssetHandle } from \"../assets/types.js\";\nimport type { LiteMaterialPlugin, LitePluginHost, LitePluginState } from \"../lite/gpu/material-plugin.js\";\nimport type { LiteTexture2D } from \"../lite/gpu/texture.js\";\nimport type { ColorLike } from \"../math/types.js\";\n\n/**\n * Surface shaders: lit, shadowed, IBL-lit custom looks on a **PBR** material\n * (`docs/plan/2026-09-terrain-particles-shaders.md` §3.2, ADR-0024).\n *\n * Three named hooks into the engine's own PBR shader, compiled into one Babylon Lite material\n * plugin, so a custom look keeps direct lighting, shadows, IBL, fog and tone mapping.\n * `./surface-shader-compiler.ts` documents the generated WGSL.\n *\n * ```ts\n * const snow = await app.assets.loadAsync<ShaderAsset>(\"shaders/snow.surface.wgsl\");\n * const rock = createMaterialAsset(\n * app,\n * pbrMaterialDefinition({\n * name: \"rock\",\n * roughness: 0.9,\n * surfaces: [{ shader: snow.address, name: \"snow\", values: {}, textures: {}, enabled: true, priority: 500 }],\n * }),\n * [],\n * );\n * rock.value.surface(\"snow\").set(\"amount\", 0.8);\n * ```\n *\n * Four constraints:\n *\n * - A **Standard** host is refused: Lite 1.27.0 bakes a Standard material's plugin signature from\n * the meshes already in the scene, which in ignifx is never in time.\n * - `rendering.features.materialPlugins` has to be declared before the scene is registered\n * (`IGX-0716` on a device, one warning headless).\n * - A material's surface shaders share one sampler budget of\n * {@link MATERIAL_PLUGIN_SAMPLER_BUDGET}, measured on a device beside a fully textured PBR\n * material with IBL and a shadow light.\n * - Attaching, detaching, toggling `enabled` and binding a texture each change Lite's pipeline cache\n * key and rebuild the material's renderables; writing a value only re-uploads the uniform block.\n */\n\n/**\n * What a material declares for one attached surface shader.\n *\n * @public\n */\nexport interface SurfaceShaderInit {\n /** The loaded `.surface.wgsl`. */\n readonly shader: AssetHandle<ShaderAsset>;\n /**\n * The name the shader answers to on this material. Defaults to the address's basename with\n * `.surface.wgsl` removed, so `shaders/snow.surface.wgsl` is `snow`.\n */\n readonly name?: string;\n /** Overrides of the file's declared uniform defaults, by declared name. */\n readonly values?: Readonly<Record<string, number | readonly number[] | ColorLike>>;\n /** Textures for the file's declared samplers, by declared name. */\n readonly textures?: Readonly<Record<string, AssetHandle<TextureAsset>>>;\n /** Whether the shader contributes anything. Defaults to `true`. */\n readonly enabled?: boolean;\n /** Lower runs first among the material's surface shaders. Defaults to `500`, Babylon Lite's own. */\n readonly priority?: number;\n}\n\n/**\n * What a `.material.json` writes for one surface shader: the shader's address and its values.\n *\n * @remarks\n * The runtime shape is {@link SurfaceShaderInit}, which carries handles; this is the serialized one,\n * which carries addresses, and is what a PBR or Standard material definition holds.\n *\n * @public\n */\nexport interface SurfaceShaderReference {\n /** The address of the `.surface.wgsl`. */\n readonly shader: string;\n /** The name the shader answers to; empty takes the address's basename. */\n readonly name: string;\n /** Overrides of the file's declared uniform defaults. */\n readonly values: Readonly<Record<string, number | readonly number[]>>;\n /** Texture addresses by declared sampler name. */\n readonly textures: Readonly<Record<string, string>>;\n /** Whether the shader contributes anything. */\n readonly enabled: boolean;\n /** Lower runs first. */\n readonly priority: number;\n}\n\n/** Babylon Lite's own default plugin priority; the surface shaders of one material sort by it. */\nconst DEFAULT_PRIORITY = 500;\n\n/** What a material with no surface shaders reports, shared so the per-frame read allocates nothing. */\nconst NO_BINDINGS: readonly SurfaceShaderBinding[] = Object.freeze([]);\n\n/**\n * What a binding tells its attachment when something changes.\n *\n * @internal\n */\nexport interface SurfaceShaderOwner {\n /** A uniform was written: re-upload the host material's uniform block. */\n onValueChanged(): void;\n /**\n * The pipeline cache key moved — a texture was bound, or `enabled` was toggled — so the host\n * material's renderables have to be rebuilt.\n */\n onShapeChanged(): void;\n}\n\n/**\n * The live state one attached surface shader's Lite plugin reads, with the fields the binding\n * writes.\n *\n * @internal\n */\nexport interface MutablePluginState extends LitePluginState {\n /** Whether the plugin contributes code. */\n enabled: boolean;\n /** The texture bound to each declared sampler, in declaration order. */\n readonly textures: (LiteTexture2D | null)[];\n /** The Lite plugin object, or `null` under a headless app, which builds none. */\n plugin: LiteMaterialPlugin | null;\n}\n\n/**\n * What a {@link SurfaceShaderBinding} is built from.\n *\n * @internal\n */\nexport interface SurfaceShaderBindingInput {\n /** The name the shader answers to. */\n readonly name: string;\n /** The shader asset. */\n readonly shader: ShaderAsset;\n /** The sort priority. */\n readonly priority: number;\n /** The host material's name, for diagnostics. */\n readonly material: string;\n /** The generated identifier prefix, including the trailing underscore. */\n readonly prefix: string;\n /** The declared uniforms, by the name the file wrote. */\n readonly uniforms: ReadonlyMap<string, ShaderUniformDeclaration>;\n /** The CPU-side values, by prefixed field name; the same map the Lite plugin reads. */\n readonly values: ReadonlyMap<string, Float32Array>;\n /** Declared sampler name to its index in the texture lists. */\n readonly textureIndex: ReadonlyMap<string, number>;\n /** The 1x1 texture each declared sampler falls back to, in declaration order. */\n readonly fallbacks: readonly (LiteTexture2D | null)[];\n /** The live state the Lite plugin reads. */\n readonly state: MutablePluginState;\n /** The attachment, which reacts to a change. */\n readonly owner: SurfaceShaderOwner;\n}\n\n/**\n * One surface shader attached to one material: the handle a game holds to change its values.\n *\n * @remarks\n * A material's bindings live as long as its attachment; reach them with `material.surfaces` and\n * `material.surface(name)`.\n *\n * @public\n */\nexport class SurfaceShaderBinding {\n /** The name the shader answers to on this material. */\n readonly name: string;\n\n /** The `.surface.wgsl` this binding was compiled from. */\n readonly shader: ShaderAsset;\n\n /** Lower runs first among the material's surface shaders. */\n readonly priority: number;\n\n readonly #material: string;\n\n readonly #prefix: string;\n\n readonly #uniforms: ReadonlyMap<string, ShaderUniformDeclaration>;\n\n readonly #values: ReadonlyMap<string, Float32Array>;\n\n readonly #textureIndex: ReadonlyMap<string, number>;\n\n readonly #fallbacks: readonly (LiteTexture2D | null)[];\n\n readonly #handles: (AssetHandle<TextureAsset> | null)[];\n\n readonly #state: MutablePluginState;\n\n readonly #owner: SurfaceShaderOwner;\n\n /**\n * Wraps one compiled, attached surface shader. `attachSurfaceShaders` constructs these.\n *\n * @param input - Everything the binding needs; assembled by `attachSurfaceShaders`.\n *\n * @internal\n */\n constructor(input: SurfaceShaderBindingInput) {\n this.name = input.name;\n this.shader = input.shader;\n this.priority = input.priority;\n this.#material = input.material;\n this.#prefix = input.prefix;\n this.#uniforms = input.uniforms;\n this.#values = input.values;\n this.#textureIndex = input.textureIndex;\n this.#fallbacks = input.fallbacks;\n this.#handles = input.fallbacks.map(() => null);\n this.#state = input.state;\n this.#owner = input.owner;\n }\n\n /**\n * Whether the shader contributes anything.\n *\n * @returns `true` while it does.\n */\n get enabled(): boolean {\n return this.#state.enabled;\n }\n\n /**\n * Switches the shader off, which restores the host material's plain look.\n *\n * @remarks\n * A disabled plugin contributes no WGSL but still changes Lite's pipeline cache key, so each\n * toggle costs a pipeline rebuild — a settings-screen operation, not a per-frame one.\n *\n * @param value - `false` to switch it off.\n */\n set enabled(value: boolean) {\n if (this.#state.enabled === value) {\n return;\n }\n this.#state.enabled = value;\n this.#owner.onShapeChanged();\n }\n\n /**\n * Writes one of the shader's declared uniforms.\n *\n * @remarks\n * The value is checked against the `// @ignifx uniform` declaration in the file, so a typo fails\n * at the call site rather than as a black surface. A uniform declared `color(…)` takes a\n * {@link ColorLike} in **sRGB** and is uploaded linear, like every other colour in ignifx. The\n * write re-uploads the host material's uniform block and recompiles nothing.\n *\n * @param name - The declared uniform's name, as the file wrote it.\n * @param value - A number, a numeric array of the declared length, or an sRGB colour.\n * @throws IgnifxError with code `IGX-0712` when the file declares no such uniform, or `IGX-0713`\n * when the value's shape does not match the declared type.\n *\n * @example\n * ```ts\n * snow.set(\"amount\", 0.8);\n * snow.set(\"snowColor\", { r: 0.95, g: 0.97, b: 1, a: 1 });\n * ```\n */\n set(name: string, value: number | readonly number[] | Float32Array | ColorLike): void {\n const declaration = this.#uniforms.get(name);\n const store = this.#values.get(`${this.#prefix}${name}`);\n if (declaration === undefined || store === undefined) {\n throw this.#unknownBinding(name, this.#uniforms.keys());\n }\n writeSurfaceValue(store, declaration, value, this.#material, this.name);\n this.#owner.onValueChanged();\n }\n\n /**\n * Reads a declared uniform's current value, as it stands on the CPU side. A colour reads back\n * **linear**, which is what the shader sees.\n *\n * @param name - The declared uniform's name.\n * @param out - Receives a vector or matrix value; omit it for a fresh array, or read a scalar's\n * number directly.\n * @returns The number for `f32`, `u32`, and `i32`, and the filled array for everything else.\n * @throws IgnifxError with code `IGX-0712` when the file declares no such uniform, or `IGX-0713`\n * when `out` is shorter than the value.\n */\n get(name: string, out?: Float32Array): number | Float32Array {\n const store = this.#values.get(`${this.#prefix}${name}`);\n if (store === undefined) {\n throw this.#unknownBinding(name, this.#uniforms.keys());\n }\n if (out === undefined) {\n return store.length === 1 ? (store[0] ?? 0) : store.slice();\n }\n if (out.length < store.length) {\n throw new IgnifxError(\n CoreErrorCode.shaderValueMismatch,\n `${name} on ${this.#material} expects ${String(store.length)} floats, not ${String(out.length)}.`,\n {\n context: { material: this.#material, name, expected: store.length, actual: out.length },\n hint: \"Pass a Float32Array at least as long as the declared type.\",\n },\n );\n }\n out.set(store);\n return out;\n }\n\n /**\n * Binds a texture to one of the shader's declared samplers.\n *\n * @remarks\n * There is no \"unbound\": a bind group with a missing entry fails WebGPU validation, so `null`\n * restores the declaration's 1x1 fallback — white unless the file said\n * `default black` or `default transparent`. The change rebuilds the material's renderables.\n *\n * @param name - The declared sampler's name.\n * @param texture - The texture, or `null` for the fallback.\n * @throws IgnifxError with code `IGX-0712` when the file declares no such sampler.\n */\n setTexture(name: string, texture: AssetHandle<TextureAsset> | null): void {\n const index = this.#textureIndex.get(name);\n if (index === undefined) {\n throw this.#unknownBinding(name, this.#textureIndex.keys());\n }\n this.#handles[index] = texture;\n const loaded = texture !== null && texture.state === \"loaded\" ? texture.value.lite.texture : null;\n this.#state.textures[index] = loaded ?? this.#fallbacks[index] ?? null;\n this.#owner.onShapeChanged();\n }\n\n /**\n * The texture currently bound to a declared sampler.\n *\n * @param name - The declared sampler's name.\n * @returns The handle, or `null` when the declaration's fallback is bound.\n * @throws IgnifxError with code `IGX-0712` when the file declares no such sampler.\n */\n getTexture(name: string): AssetHandle<TextureAsset> | null {\n const index = this.#textureIndex.get(name);\n if (index === undefined) {\n throw this.#unknownBinding(name, this.#textureIndex.keys());\n }\n return this.#handles[index] ?? null;\n }\n\n /**\n * The Babylon Lite plugin this binding drives. Unstable escape hatch\n * (`docs/architecture/00-overview.md` §3).\n *\n * @returns The plugin, or `null` under a headless app, which builds none.\n */\n get lite(): LiteMaterialPlugin | null {\n return this.#state.plugin;\n }\n\n /**\n * The `IGX-0712` failure an undeclared name produces.\n *\n * @param name - The name the caller passed.\n * @param declared - The names the file did declare.\n * @returns The error to throw.\n */\n #unknownBinding(name: string, declared: Iterable<string>): IgnifxError {\n return new IgnifxError(\n CoreErrorCode.unknownShaderBinding,\n `${this.#material} declares no uniform, texture, or storage buffer named ${name}.`,\n {\n context: { material: this.#material, surface: this.name, name },\n hint: `${this.shader.address} declares ${describeNames(declared)}.`,\n },\n );\n }\n}\n\n/** Everything one material's surface shaders share. */\nclass SurfaceShaderAttachment implements SurfaceShaderOwner {\n readonly bindings: SurfaceShaderBinding[] = [];\n\n readonly #app: App | null;\n\n readonly #host: LitePluginHost | null;\n\n readonly #isPbr: boolean;\n\n #isLive = false;\n\n /**\n * Creates the attachment.\n *\n * @param app - The app, or `null` for a pure unit-test attach.\n * @param host - The Lite PBR or Standard material, or `null` under a headless app.\n * @param isPbr - Whether the host is a PBR material, which needs an explicit UBO dirty mark.\n */\n constructor(app: App | null, host: LitePluginHost | null, isPbr: boolean) {\n this.#app = app;\n this.#host = host;\n this.#isPbr = isPbr;\n }\n\n /** Records that Lite has been handed the plugin list, so later changes rebuild. */\n goLive(): void {\n this.#isLive = true;\n }\n\n /** Re-uploads the host material's uniform block. */\n onValueChanged(): void {\n markSurfaceValueChanged(this.#host, this.#isPbr);\n }\n\n /** Rebuilds the host material's renderables, which is what a bind-group or feature change needs. */\n onShapeChanged(): void {\n rebuildSurfaceHost(this.#app, this.#host, this.#isLive);\n }\n}\n\n/** One attachment per material, created on first use so module scope allocates nothing. */\nlet attachments: WeakMap<MaterialAsset, SurfaceShaderAttachment> | null = null;\n\n/**\n * Compiles a material's surface shaders, attaches them to its Babylon Lite material, and returns the\n * handles a game changes their values through.\n *\n * @remarks\n * Replaces whatever was attached before, so calling it twice is a re-attach rather than an addition,\n * and an empty list detaches. Under a headless app — or with `app` `null`, which is how a unit test\n * attaches — every value and texture is held and validated and no Lite plugin is built.\n *\n * The second parameter is the **app**, not the rendering service: a runtime import of `renderer.ts`\n * from a module that `material-asset.ts` imports would close a dependency cycle, because\n * `renderer.ts` builds the default `MaterialAsset`. Everything the attach path needs —\n * `renderer.features`, `isHeadless`, `lite.scene`, `log` — is on the public app.\n *\n * @param material - The PBR material to decorate.\n * @param app - The app, or `null` to compile and validate without touching Babylon Lite.\n * @param surfaces - The shaders to attach, with their values.\n * @returns One binding per shader, in the order given.\n * @throws IgnifxError with code `IGX-0716` when `rendering.features.materialPlugins` is off on a\n * device, `IGX-0708` on a `\"shader\"` host, `IGX-0709` when a file is not a `surface` one, `IGX-0712`\n * when a declared value or texture name is unknown or two shaders share a name, `IGX-0713` on a\n * wrongly shaped value, `IGX-0726` when the material's shaders exceed the sampler budget, and\n * `IGX-0723` when a file declares no hook, declares one this host cannot run, or names a Standard\n * material as its host.\n *\n * @public\n */\nexport function attachSurfaceShaders(\n material: MaterialAsset,\n app: App | null,\n surfaces: readonly SurfaceShaderInit[],\n): readonly SurfaceShaderBinding[] {\n detachSurfaceShaders(material);\n if (surfaces.length === 0) {\n return [];\n }\n const capabilities = assertHostFamily(material);\n const isHeadless = app === null || app.isHeadless;\n assertFeature(material, app, isHeadless, surfaces.length);\n assertPbrHost(material, capabilities);\n const host = resolveSurfaceHost(material, isHeadless);\n const attachment = new SurfaceShaderAttachment(app, host, capabilities.family === \"pbr\");\n const plugins: LiteMaterialPlugin[] = [];\n const names = new Set<string>();\n let samplers = 0;\n for (const init of surfaces) {\n const shader = assertLoadedSurfaceShader(material, init);\n const name = init.name ?? surfaceShaderName(shader.address);\n assertUniqueName(material, name, names);\n samplers += shader.declaration.textures.length;\n if (samplers > MATERIAL_PLUGIN_SAMPLER_BUDGET) {\n throw new IgnifxError(\n CoreErrorCode.surfaceSamplerBudgetExceeded,\n `${material.name} attaches surface shaders declaring ${String(samplers)} samplers; ${String(MATERIAL_PLUGIN_SAMPLER_BUDGET)} fit beside a textured PBR material.`,\n {\n context: { material: material.name, samplers, budget: MATERIAL_PLUGIN_SAMPLER_BUDGET },\n hint: \"Pack the maps into fewer textures — an RGBA control map rather than four masks.\",\n },\n );\n }\n const binding = buildBinding(material, app, capabilities, init, name, shader, attachment);\n attachment.bindings.push(binding.binding);\n const plugin = binding.state.plugin;\n if (plugin !== null) {\n plugins.push(plugin);\n }\n }\n attachSurfacePlugins(host, plugins);\n attachment.goLive();\n // Lite reads `material.plugins` when it builds the pipeline, so a material that is already\n // drawing needs its renderables rebuilt before the plugin's WGSL reaches the screen. Before\n // `app.start()` nothing has been built and the rebuild is a cheap no-op, so it is unconditional.\n attachment.onShapeChanged();\n (attachments ??= new WeakMap<MaterialAsset, SurfaceShaderAttachment>()).set(material, attachment);\n return attachment.bindings;\n}\n\n/**\n * Removes every surface shader from a material, restoring its plain look.\n *\n * @remarks\n * Idempotent, and safe on a material that never had one. It clears Lite's plugin list, which changes\n * the pipeline cache key, so the material's renderables are rebuilt.\n *\n * @param material - The material.\n *\n * @public\n */\nexport function detachSurfaceShaders(material: MaterialAsset): void {\n const existing = attachments?.get(material);\n if (existing === undefined) {\n return;\n }\n attachments?.delete(material);\n detachSurfacePlugins(material);\n existing.onShapeChanged();\n}\n\n/**\n * The surface shaders currently attached to a material, in the order they were attached.\n *\n * @param material - The material.\n * @returns The bindings, or an empty array.\n *\n * @public\n */\nexport function surfaceShaders(material: MaterialAsset): readonly SurfaceShaderBinding[] {\n return attachments?.get(material)?.bindings ?? NO_BINDINGS;\n}\n\n/**\n * One attached surface shader, by the name it answers to.\n *\n * @param material - The material.\n * @param name - The shader's name — the address's basename unless the material renamed it.\n * @returns The binding.\n * @throws IgnifxError with code `IGX-0712` when the material carries no such surface shader.\n *\n * @example\n * ```ts\n * surfaceShaderBinding(rock.value, \"snow\").set(\"amount\", 0.4);\n * ```\n *\n * @public\n */\nexport function surfaceShaderBinding(material: MaterialAsset, name: string): SurfaceShaderBinding {\n for (const binding of surfaceShaders(material)) {\n if (binding.name === name) {\n return binding;\n }\n }\n throw new IgnifxError(\n CoreErrorCode.unknownShaderBinding,\n `${material.name} carries no surface shader named ${name}.`,\n {\n context: { material: material.name, name },\n hint: \"The name is the .surface.wgsl basename unless the material's surfaces entry renamed it.\",\n },\n );\n}\n\n/**\n * The name a surface shader answers to when its material does not rename it: the address's basename\n * with `.surface.wgsl` removed.\n *\n * @param address - The shader's asset address.\n * @returns The name.\n *\n * @example\n * ```ts\n * surfaceShaderName(\"shaders/terrain/snow.surface.wgsl\"); // \"snow\"\n * ```\n *\n * @public\n */\nexport function surfaceShaderName(address: string): string {\n const slash = address.lastIndexOf(\"/\");\n const basename = slash < 0 ? address : address.slice(slash + 1);\n if (basename.endsWith(\".surface.wgsl\")) {\n return basename.slice(0, -\".surface.wgsl\".length);\n }\n return basename.endsWith(\".wgsl\") ? basename.slice(0, -\".wgsl\".length) : basename;\n}\n\n/** What {@link buildBinding} produces. */\ninterface BuiltBinding {\n /** The public handle. */\n readonly binding: SurfaceShaderBinding;\n /** Its live state, which carries the Lite plugin. */\n readonly state: MutablePluginState;\n}\n\n/**\n * Compiles one surface shader and builds its binding and Lite plugin.\n *\n * @param material - The host material.\n * @param app - The app, or `null`.\n * @param capabilities - The host family and what its template exposes.\n * @param init - What the material declared for this shader.\n * @param name - The name the shader answers to.\n * @param shader - The loaded shader asset.\n * @param owner - The attachment.\n * @returns The binding and its state.\n * @throws IgnifxError as `attachSurfaceShaders` documents.\n */\nfunction buildBinding(\n material: MaterialAsset,\n app: App | null,\n capabilities: SurfaceHostCapabilities,\n init: SurfaceShaderInit,\n name: string,\n shader: ShaderAsset,\n owner: SurfaceShaderAttachment,\n): BuiltBinding {\n const compiled = compileSurfaceShader({\n name,\n address: shader.address,\n source: shader.source,\n declaration: shader.declaration,\n host: capabilities,\n });\n const uniforms = new Map<string, ShaderUniformDeclaration>();\n const values = new Map<string, Float32Array>();\n for (const uniform of shader.declaration.uniforms) {\n uniforms.set(uniform.name, uniform);\n values.set(`${compiled.prefix}${uniform.name}`, defaultValueStore(uniform));\n }\n const textureIndex = new Map<string, number>();\n const declarations = shader.declaration.textures;\n for (let index = 0; index < declarations.length; index += 1) {\n textureIndex.set(declarations[index]?.name ?? \"\", index);\n }\n const fallbacks = resolveSurfaceFallbacks(app, declarations);\n const state: MutablePluginState = {\n enabled: init.enabled ?? true,\n values,\n textures: [...fallbacks],\n plugin: null,\n };\n state.plugin = buildSurfacePlugin(app, compiled, init, capabilities, state);\n const binding = new SurfaceShaderBinding({\n name,\n shader,\n priority: init.priority ?? DEFAULT_PRIORITY,\n material: material.name,\n prefix: compiled.prefix,\n uniforms,\n values,\n textureIndex,\n fallbacks,\n state,\n owner,\n });\n applyInitialValues(binding, init);\n return { binding, state };\n}\n\n/**\n * Writes a material's declared value and texture overrides onto a fresh binding.\n *\n * @param binding - The binding.\n * @param init - What the material declared.\n * @throws IgnifxError with code `IGX-0712` or `IGX-0713`.\n */\nfunction applyInitialValues(binding: SurfaceShaderBinding, init: SurfaceShaderInit): void {\n const values = init.values;\n if (values !== undefined) {\n for (const name of Object.keys(values)) {\n const value = values[name];\n if (value !== undefined) {\n binding.set(name, value);\n }\n }\n }\n const textures = init.textures;\n if (textures !== undefined) {\n for (const name of Object.keys(textures)) {\n binding.setTexture(name, textures[name] ?? null);\n }\n }\n}\n\n/**\n * Refuses a surface shader on a material family that cannot host one, and reports what the host's\n * template exposes.\n *\n * @param material - The material.\n * @returns The capabilities.\n * @throws IgnifxError with code `IGX-0708` on a `\"shader\"` material.\n */\nfunction assertHostFamily(material: MaterialAsset): SurfaceHostCapabilities {\n const definition = material.definition;\n if (definition.kind === \"shader\") {\n throw new IgnifxError(\n CoreErrorCode.unsupportedMaterialKind,\n `${material.name} is a shader material, which owns its whole pipeline and cannot host a surface shader.`,\n {\n context: { material: material.name, kind: definition.kind },\n hint: \"Attach surface shaders to a pbr or standard material, or write the effect into the .wgsl itself.\",\n },\n );\n }\n if (definition.kind === \"pbr\") {\n return { family: \"pbr\", hasUv: true, hasNormal: !definition.unlit };\n }\n return {\n family: \"standard\",\n // Standard declares its UV varying only when a texture asks for it (`standard-flags.js`\n // NEEDS_UV); with none, `in.uv` reads (0, 0) rather than failing to compile.\n hasUv: Object.keys(definition.textures).length > 0,\n hasNormal: !definition.unlit,\n };\n}\n\n/**\n * Refuses a surface shader when the project did not opt into Lite's plugin bridges, and warns when\n * it is only a headless app that would have been affected.\n *\n * @param material - The material, for diagnostics.\n * @param app - The app, or `null`.\n * @param isHeadless - Whether there is no device to patch.\n * @param count - How many shaders are being attached, for the message.\n * @throws IgnifxError with code `IGX-0716` on a device.\n */\nfunction assertFeature(material: MaterialAsset, app: App | null, isHeadless: boolean, count: number): void {\n if (app === null || app.renderer.features.materialPlugins) {\n return;\n }\n if (!isHeadless) {\n throw new IgnifxError(\n CoreErrorCode.surfaceShaderFeatureOff,\n `${material.name} carries a surface shader, but rendering.features.materialPlugins is off.`,\n {\n context: { material: material.name, surfaces: count },\n hint: \"Declare materialPlugins in the rendering.features block of createApp() or ignifx.config.ts.\",\n },\n );\n }\n app.log.warn(\n `${CoreErrorCode.surfaceShaderFeatureOff}: {material} carries a surface shader, but ` +\n \"rendering.features.materialPlugins is off, so it would be inert on a device.\",\n material.name,\n );\n}\n\n/**\n * Refuses a surface shader on a **Standard** host, which Babylon Lite 1.27.0 cannot carry one on.\n *\n * @remarks\n * `registerStdPlugins` bakes a per-signature index into every Standard material it finds by walking\n * `scene.meshes` (`lib/material/plugin/std-plugin-bridge.js` 133-155), and ignifx creates a\n * renderer's Lite mesh in the first frame's `PreRender` — after that walk — so a Standard host would\n * silently draw as if it carried nothing. PBR's bridge encodes the signature into the material's\n * feature bits at build time and has no such rule. The compiler can still generate for a Standard\n * host, so the refusal lifts as soon as Lite exposes a way to bake one late.\n *\n * @param material - The material, for diagnostics.\n * @param capabilities - The host family.\n * @throws IgnifxError with code `IGX-0723`.\n */\nfunction assertPbrHost(material: MaterialAsset, capabilities: SurfaceHostCapabilities): void {\n if (capabilities.family === \"pbr\") {\n return;\n }\n throw new IgnifxError(\n CoreErrorCode.surfaceHookMissing,\n `${material.name} is a standard material, and Babylon Lite bakes a standard material's plugins from the meshes already in the scene, so it cannot carry a surface shader.`,\n {\n context: { material: material.name, kind: \"standard\" },\n hint: \"Use a pbr material as the host; surfaces are a pbr-only feature in this release.\",\n },\n );\n}\n\n/**\n * The shader asset one entry names, checked for being a loaded `surface` file.\n *\n * @param material - The host material, for diagnostics.\n * @param init - The entry.\n * @returns The shader asset.\n * @throws IgnifxError with code `IGX-0501` when it is not loaded, or `IGX-0709` when it is not a\n * `// @ignifx surface` file.\n */\nfunction assertLoadedSurfaceShader(material: MaterialAsset, init: SurfaceShaderInit): ShaderAsset {\n const handle = init.shader;\n if (handle.state !== \"loaded\") {\n throw new IgnifxError(CoreErrorCode.assetNotLoaded, `The surface shader ${handle.address} is not loaded.`, {\n context: { asset: handle.address, material: material.name },\n hint: \"await app.assets.loadAsync(address) before building a material from it.\",\n });\n }\n const shader = handle.value;\n if (shader.declaration.kind !== \"surface\") {\n throw new IgnifxError(\n CoreErrorCode.invalidAssetFile,\n `${shader.address} declares @ignifx ${shader.declaration.kind}, not @ignifx surface.`,\n {\n context: {\n file: shader.address,\n format: \"@ignifx surface\",\n material: material.name,\n kind: shader.declaration.kind,\n },\n hint: \"A material's surfaces list takes .surface.wgsl files whose pragma is @ignifx surface.\",\n },\n );\n }\n return shader;\n}\n\n/**\n * Refuses two surface shaders that would answer to the same name — and therefore generate the same\n * WGSL identifiers — on one material.\n *\n * @param material - The host material.\n * @param name - The name this entry resolved to.\n * @param taken - The names already used; the accepted one is added.\n * @throws IgnifxError with code `IGX-0712`.\n */\nfunction assertUniqueName(material: MaterialAsset, name: string, taken: Set<string>): void {\n const sanitized = sanitizeIdentifier(name);\n if (taken.has(sanitized)) {\n throw new IgnifxError(\n CoreErrorCode.unknownShaderBinding,\n `${material.name} attaches two surface shaders that both answer to ${name}.`,\n {\n context: { material: material.name, name },\n hint: \"Name one of them in its surfaces entry; the name prefixes every generated WGSL identifier.\",\n },\n );\n }\n taken.add(sanitized);\n}\n\n/**\n * A uniform's CPU-side store, filled with its declared default and decoded from sRGB when the\n * declaration says it is a colour.\n *\n * @param declaration - The uniform declaration.\n * @returns The store.\n */\nfunction defaultValueStore(declaration: ShaderUniformDeclaration): Float32Array {\n const store = new Float32Array(uniformComponentCount(declaration.type));\n const value = declaration.defaultValue;\n if (typeof value === \"number\") {\n store[0] = value;\n } else {\n store.set(value.slice(0, store.length));\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 store, checking its shape and decoding a colour.\n *\n * @param store - The store.\n * @param declaration - The uniform declaration.\n * @param value - The caller's value.\n * @param material - The host material's name, for diagnostics.\n * @param surface - The surface shader's name, for diagnostics.\n * @throws IgnifxError with code `IGX-0713` when the shape does not match.\n */\nfunction writeSurfaceValue(\n store: Float32Array,\n declaration: ShaderUniformDeclaration,\n value: number | readonly number[] | Float32Array | ColorLike,\n material: string,\n surface: string,\n): void {\n const count = store.length;\n if (typeof value === \"number\") {\n if (count !== 1) {\n throw valueMismatch(declaration, material, surface, `${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 valueMismatch(declaration, material, surface, `${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 valueMismatch(declaration, material, surface, `${String(count)} floats`, `${String(value.length)} floats`);\n }\n store.set(value instanceof Float32Array ? value : Float32Array.from(value));\n if (declaration.color) {\n decodeColourComponents(store);\n }\n}\n\n/**\n * The `IGX-0713` failure a wrongly shaped value produces.\n *\n * @param declaration - The uniform declaration.\n * @param material - The host material's name.\n * @param surface - The surface shader's name.\n * @param expected - What the uniform takes.\n * @param actual - What the caller passed.\n * @returns The error to throw.\n */\nfunction valueMismatch(\n declaration: ShaderUniformDeclaration,\n material: string,\n surface: string,\n expected: string,\n actual: string,\n): IgnifxError {\n return new IgnifxError(\n CoreErrorCode.shaderValueMismatch,\n `${declaration.name} on ${material} expects ${declaration.type} (${expected}), not ${actual}.`,\n {\n context: { name: declaration.name, material, surface, 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\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 * A readable list of declared names, for an error hint.\n *\n * @param names - The names.\n * @returns The list, or a note that there are none.\n */\nfunction describeNames(names: Iterable<string>): string {\n const list = [...names];\n return list.length === 0 ? \"no bindings of that kind\" : list.join(\", \");\n}\n"],"mappings":";;;;;;;AA2HA,MAAM,gBAAmC,OAAO,OAAO;CACrD;CACA;CACA;AACF,CAAC;;;;;;;;;AAUD,SAAgB,oBAAoB,OAAwB;CAC1D,OAAO,cAAc,SAAS,KAAK;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O;EACvE,MAAM;CACR,CACF;AACF;;;;;;;;;;;AAYA,SAAS,uBAAuB,OAA2B;CACzD,MAAM,MAAM,MAAM,SAAS,GAAG,CAAC;CAC/B,IAAI,IAAI,IAAI,KAAK,cAAc,MAAM,aAAa,SAAS,CAAC,CAAC;AAC/D;;;;;;;AAQA,SAAS,YAAY,OAAyE;CAC5F,OAAO,CAAC,MAAM,QAAQ,KAAK,KAAK,EAAE,iBAAiB;AACrD;;;;;;;AAQA,SAAS,cAAc,OAAiC;CACtD,MAAM,OAAO,CAAC,GAAG,KAAK;CACtB,OAAO,KAAK,WAAW,IAAI,6BAA6B,KAAK,KAAK,IAAI;AACxE"}
|
|
1
|
+
{"version":3,"file":"surface-shader-CwQ03yHG.js","names":[],"sources":["../src/lite/gpu/material-plugin.ts","../src/render/gpu/surface-shader-host.ts","../src/render/surface-shader-compiler.ts","../src/render/surface-shader.ts"],"sourcesContent":["import type {\n MaterialPlugin,\n MaterialPluginPoint,\n PbrMaterialProps,\n PluginSamplerDecl,\n PluginTextureBinding,\n PluginUboField,\n StandardMaterialProps,\n Texture2D,\n} from \"@babylonjs/lite\";\n\n/**\n * The Babylon Lite half of surface shaders and raw material plugins\n * (`docs/plan/2026-09-terrain-particles-shaders.md` §3.2). Everything here is `@internal`.\n *\n * A `MaterialPlugin` is plain data with function members, so nothing here needs a device, but the\n * `materialPlugins` rendering feature must have installed the bridges before the scene was\n * registered (`../render-features.ts`). Three facts it is written around:\n *\n * - `getCustomCode`, `getUniforms` and `getSamplers` results are stringified into the pipeline cache\n * key (`lib/material/plugin/plugin-bridge-shared.js` 21-34), so they must be **stable**; this\n * module precomputes everything at attach time.\n * - `writeUbo(data, offsets)` gets **byte** offsets (`lib/material/pbr/pbr-renderable.js` 420,\n * confirmed on a device in spike S0.2) — divide by four for a `Float32Array` index.\n * - PBR fields join the material's own uniform block and need `markMaterialUboDirty`; Standard\n * fields become a self-managed `pluginUbo` that is re-uploaded only when `dynamic` is set, so\n * {@link createLiteMaterialPlugin} sets it for a Standard host alone.\n */\n\n/**\n * A Babylon Lite material plugin, re-exported under an ignifx name so feature code can name the\n * type without importing `@babylonjs/lite` (`CONSTITUTION.md` §3.4).\n *\n * @remarks\n * Unstable; excluded from the stability guarantees of `CONSTITUTION.md` Article IV.\n *\n * @internal\n */\nexport type LiteMaterialPlugin = MaterialPlugin;\n\n/**\n * A Babylon Lite material that can carry plugins: PBR or Standard.\n *\n * @internal\n */\nexport type LitePluginHost = PbrMaterialProps | StandardMaterialProps;\n\n/**\n * One uniform field a plugin appends to its host's uniform block.\n *\n * @internal\n */\nexport interface LitePluginField {\n /** The WGSL field name, already prefixed so it cannot collide with the host's own. */\n readonly name: string;\n /** The WGSL type, used verbatim inside the host's struct. */\n readonly type: string;\n /** How many components the CPU-side value holds: 1, 2, 3, 4, or 16. */\n readonly components: number;\n}\n\n/**\n * One texture/sampler pair a plugin adds to its host's bind group.\n *\n * @internal\n */\nexport interface LitePluginSampler {\n /** The WGSL texture variable name, already prefixed. */\n readonly texture: string;\n /** The WGSL sampler variable name, already prefixed. */\n readonly sampler: string;\n /** Whether the binding is a `texture_2d_array<f32>` rather than a `texture_2d<f32>`. */\n readonly array: boolean;\n}\n\n/**\n * What a plugin injects, split by shader stage the way Lite asks for it.\n *\n * @internal\n */\nexport interface LitePluginCode {\n /** Fragment-stage injection points, by Lite point name. */\n readonly fragment: Partial<Record<MaterialPluginPoint, string>>;\n /** Vertex-stage injection points, by Lite point name. */\n readonly vertex: Partial<Record<MaterialPluginPoint, string>>;\n}\n\n/**\n * The live state a plugin reads at upload time. The render layer owns it and mutates it in place, so\n * a value or texture write costs no rebuild of the plugin object.\n *\n * @internal\n */\nexport interface LitePluginState {\n /** Whether the plugin contributes code at all. Toggling it changes Lite's pipeline cache key. */\n enabled: boolean;\n /** Field name to its current CPU-side floats, in component order. */\n readonly values: ReadonlyMap<string, Float32Array>;\n /** The texture for each declared sampler, in declaration order; `null` entries are skipped. */\n readonly textures: readonly (Texture2D | null)[];\n}\n\n/**\n * Everything that is fixed for the life of one attached plugin.\n *\n * @internal\n */\nexport interface LiteMaterialPluginInput {\n /** The plugin's identity; part of Lite's pipeline cache key. */\n readonly name: string;\n /** Lower runs first. */\n readonly priority: number;\n /** The uniform fields, already prefixed. */\n readonly fields: readonly LitePluginField[];\n /** The samplers, already prefixed. */\n readonly samplers: readonly LitePluginSampler[];\n /** The WGSL to inject. */\n readonly code: LitePluginCode;\n /** Whether the host is a Standard material, which needs `dynamic` to re-upload at all. */\n readonly isStandardHost: boolean;\n}\n\n/** The Lite point names that belong to the vertex stage. */\nconst VERTEX_POINTS: readonly string[] = Object.freeze([\n \"CUSTOM_VERTEX_MAIN_BEGIN\",\n \"CUSTOM_VERTEX_UPDATE_WORLDPOS\",\n \"CUSTOM_VERTEX_MAIN_END\",\n]);\n\n/**\n * Whether a Lite injection point belongs to the vertex stage.\n *\n * @param point - The point name.\n * @returns `true` for the three vertex points.\n *\n * @internal\n */\nexport function isVertexPluginPoint(point: string): boolean {\n return VERTEX_POINTS.includes(point);\n}\n\n/**\n * Builds the Babylon Lite plugin object for one attached surface shader or raw plugin.\n *\n * @remarks\n * The returned object closes over `state`, so the render layer changes a value by writing into\n * `state.values` and then marking the host dirty; the plugin object itself never changes, which is\n * what keeps Lite's pipeline cache key stable.\n *\n * `getCustomCode` returns `null` for a stage with no code and for every stage while the plugin is\n * disabled. Lite already treats a disabled plugin as contributing nothing (`isEnabled`), and the\n * `null` keeps the signature short.\n *\n * @param input - What is fixed about the plugin.\n * @param state - The live values, textures, and enabled flag.\n * @returns The Lite plugin, ready for {@link attachLiteMaterialPlugins}.\n *\n * @internal\n */\nexport function createLiteMaterialPlugin(input: LiteMaterialPluginInput, state: LitePluginState): MaterialPlugin {\n const ubo: PluginUboField[] = input.fields.map((field) => ({ name: field.name, type: field.type }));\n const samplers: PluginSamplerDecl[] = input.samplers.map((sampler) =>\n sampler.array\n ? // The declared type is wider than Lite's TypeScript literal, and the bind-group layout\n // derives `viewDimension` from the string, so the cast is the documented route (spike S0.2).\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n ({\n texture: sampler.texture,\n sampler: sampler.sampler,\n textureType: \"texture_2d_array<f32>\",\n } as unknown as PluginSamplerDecl)\n : { texture: sampler.texture, sampler: sampler.sampler },\n );\n const uniforms = { ubo };\n let integerView: Int32Array | null = null;\n let integerBuffer: ArrayBufferLike | null = null;\n const plugin: MaterialPlugin = {\n name: input.name,\n priority: input.priority,\n get isEnabled(): boolean {\n return state.enabled;\n },\n dynamic: input.isStandardHost,\n getCustomCode(stage: \"vertex\" | \"fragment\"): Partial<Record<MaterialPluginPoint, string>> | null {\n const code = stage === \"vertex\" ? input.code.vertex : input.code.fragment;\n return Object.keys(code).length === 0 ? null : code;\n },\n getUniforms(): { ubo?: PluginUboField[] } {\n return uniforms;\n },\n getSamplers(): PluginSamplerDecl[] {\n return samplers;\n },\n writeUbo(data: Float32Array, offsets: ReadonlyMap<string, number>): void {\n for (const field of input.fields) {\n const byteOffset = offsets.get(field.name);\n const values = state.values.get(field.name);\n if (byteOffset === undefined || values === undefined) {\n continue;\n }\n const index = byteOffset / 4;\n if (field.type === \"u32\" || field.type === \"i32\") {\n if (integerBuffer !== data.buffer) {\n integerBuffer = data.buffer;\n integerView = new Int32Array(data.buffer, data.byteOffset, data.length);\n }\n const view = integerView;\n if (view !== null) {\n view[index] = values[0] ?? 0;\n }\n continue;\n }\n for (let component = 0; component < field.components; component += 1) {\n data[index + component] = values[component] ?? 0;\n }\n }\n },\n bindTextures(out: PluginTextureBinding[]): void {\n for (const texture of state.textures) {\n if (texture !== null) {\n out.push({ texture });\n }\n }\n },\n getActiveTextures(out: Texture2D[]): void {\n for (const texture of state.textures) {\n if (texture !== null) {\n out.push(texture);\n }\n }\n },\n };\n return plugin;\n}\n\n/**\n * Replaces a material's plugin list.\n *\n * @remarks\n * `material.plugins = [plugin]` is the documented attach path (`index.d.ts` 8175, 12253). The list\n * is read when the pipeline is built, so a change to it needs a rebuild of the material's\n * renderables — `rebuildMaterialPipelines` in `src/lite/material.ts` — before it shows up.\n *\n * @param material - The PBR or Standard host.\n * @param plugins - The plugins, in any order; Lite sorts them by `priority`.\n *\n * @internal\n */\nexport function attachLiteMaterialPlugins(material: LitePluginHost, plugins: readonly MaterialPlugin[]): void {\n material.plugins = [...plugins];\n}\n\n/**\n * Clears a material's plugin list.\n *\n * @param material - The PBR or Standard host.\n *\n * @internal\n */\nexport function detachLiteMaterialPlugins(material: LitePluginHost): void {\n material.plugins = [];\n}\n\n/**\n * The plugins currently attached to a material.\n *\n * @param material - The PBR or Standard host.\n * @returns The list, or an empty array when it carries none.\n *\n * @internal\n */\nexport function liteMaterialPlugins(material: LitePluginHost): readonly MaterialPlugin[] {\n return material.plugins ?? [];\n}\n","import {\n attachLiteMaterialPlugins,\n createLiteMaterialPlugin,\n detachLiteMaterialPlugins,\n isVertexPluginPoint,\n} from \"../../lite/gpu/material-plugin.js\";\nimport { markMaterialDirty, rebuildMaterialPipelines } from \"../../lite/material.js\";\nimport { uniformComponentCount } from \"../material-plugin.js\";\nimport { shaderMaterialsOf } from \"../shader-material.js\";\nimport type { App } from \"../../app/types.js\";\nimport type {\n LiteMaterialPlugin,\n LitePluginCode,\n LitePluginHost,\n LitePluginState,\n} from \"../../lite/gpu/material-plugin.js\";\nimport type { LiteTexture2D } from \"../../lite/gpu/texture.js\";\nimport type { MaterialAsset } from \"../material-asset.js\";\nimport type { LiteMaterialPluginPoint } from \"../material-plugin.js\";\nimport type { ShaderTextureDeclaration } from \"../shader-declaration.js\";\nimport type { CompiledSurfaceShader, SurfaceHostCapabilities } from \"../surface-shader-compiler.js\";\nimport type { SurfaceShaderInit } from \"../surface-shader.js\";\n\n/**\n * The device-only half of surface shaders: the Lite plugin a compiled `.surface.wgsl` becomes, and\n * the host-material writes that follow it (`docs/plan/2026-09-terrain-particles-shaders.md` §3.2).\n *\n * Each entry point takes the app or the host as a nullable and returns early when it is `null`, so\n * `../surface-shader.ts` keeps no headless branch of its own.\n */\n\n/**\n * The host material a surface shader attaches to, when there is a device.\n *\n * @remarks\n * `assertHostFamily` refused the shader family, so the Lite material is a PBR or Standard one and\n * both carry `plugins` (`index.d.ts` 8175, 12253).\n *\n * @param material - The material asset.\n * @param isHeadless - Whether the app has a device.\n * @returns The Lite material, or `null`.\n *\n * @internal\n */\nexport function resolveSurfaceHost(material: MaterialAsset, isHeadless: boolean): LitePluginHost | null {\n return isHeadless ? null : material.lite.material;\n}\n\n/**\n * Re-uploads the host material's uniform block after a value write.\n *\n * @remarks\n * Lite ignores `dynamic` for a PBR host and re-reads the plugin slice only after this (spike S0.2);\n * a Standard host re-uploads every frame because the plugin sets `dynamic`.\n *\n * @param host - The host material, or `null`.\n * @param isPbr - Whether the host is a PBR material.\n *\n * @internal\n */\nexport function markSurfaceValueChanged(host: LitePluginHost | null, isPbr: boolean): void {\n if (host === null || !isPbr) {\n return;\n }\n markMaterialDirty(host);\n}\n\n/**\n * Rebuilds the host material's renderables, which a bind-group or feature change needs.\n *\n * @param app - The app, or `null` when the attachment was built without one.\n * @param host - The host material, or `null`.\n * @param isLive - Whether Lite has already been handed the plugin list.\n *\n * @internal\n */\nexport function rebuildSurfaceHost(app: App | null, host: LitePluginHost | null, isLive: boolean): void {\n if (!isLive || app === null || host === null || app.isHeadless) {\n return;\n }\n rebuildMaterialPipelines(app.lite.scene, host);\n}\n\n/**\n * Hands Lite the plugins a material's surface shaders compiled to, when there are any.\n *\n * @param host - The host material, or `null`.\n * @param plugins - The plugins, in attach order.\n *\n * @internal\n */\nexport function attachSurfacePlugins(host: LitePluginHost | null, plugins: readonly LiteMaterialPlugin[]): void {\n if (host === null || plugins.length === 0) {\n return;\n }\n attachLiteMaterialPlugins(host, plugins);\n}\n\n/**\n * Takes a material's surface-shader plugins off its Lite material.\n *\n * @remarks\n * A `\"shader\"` material never hosts one, and its Lite object carries no `plugins` field to clear.\n *\n * @param material - The material asset.\n *\n * @internal\n */\nexport function detachSurfacePlugins(material: MaterialAsset): void {\n if (material.definition.kind === \"shader\") {\n return;\n }\n detachLiteMaterialPlugins(material.lite.material);\n}\n\n/**\n * The 1x1 fallback each declared sampler falls back to, or nulls under a headless app.\n *\n * @param app - The app, or `null`.\n * @param declarations - The file's declared samplers, in declaration order.\n * @returns One entry per declaration.\n *\n * @internal\n */\nexport function resolveSurfaceFallbacks(\n app: App | null,\n declarations: readonly ShaderTextureDeclaration[],\n): (LiteTexture2D | null)[] {\n if (app === null || app.isHeadless) {\n return declarations.map((): null => null);\n }\n const registry = shaderMaterialsOf(app);\n return declarations.map((declaration) => registry.fallbackTexture(declaration));\n}\n\n/**\n * Builds the Lite plugin for one compiled surface shader, when there is a device.\n *\n * @param app - The app, or `null`.\n * @param compiled - The compiled shader.\n * @param init - What the material declared, for the priority.\n * @param capabilities - The host family, which decides how a value reaches the GPU.\n * @param state - The live state the plugin reads.\n * @returns The plugin, or `null` under a headless app.\n *\n * @internal\n */\nexport function buildSurfacePlugin(\n app: App | null,\n compiled: CompiledSurfaceShader,\n init: SurfaceShaderInit,\n capabilities: SurfaceHostCapabilities,\n state: LitePluginState,\n): LiteMaterialPlugin | null {\n if (app === null || app.isHeadless) {\n return null;\n }\n return buildLitePlugin(compiled, init, capabilities, state);\n}\n\n/**\n * Builds the Lite plugin for one compiled surface shader.\n *\n * @param compiled - The compiled shader.\n * @param init - What the material declared, for the priority.\n * @param capabilities - The host family, which decides how a value reaches the GPU.\n * @param state - The live state the plugin reads.\n * @returns The plugin.\n */\nfunction buildLitePlugin(\n compiled: CompiledSurfaceShader,\n init: SurfaceShaderInit,\n capabilities: SurfaceHostCapabilities,\n state: LitePluginState,\n): LiteMaterialPlugin {\n const fragment: Record<string, string> = {};\n const vertex: Record<string, string> = {};\n for (const point of Object.keys(compiled.plugin.code)) {\n // The keys came from the compiler, which only ever writes Lite's own point names.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const wgsl = compiled.plugin.code[point as LiteMaterialPluginPoint];\n if (wgsl === undefined) {\n continue;\n }\n if (isVertexPluginPoint(point)) {\n vertex[point] = wgsl;\n } else {\n fragment[point] = wgsl;\n }\n }\n // The two records are keyed by Lite's own point names, which the compiler produced, so the shape\n // is the `Partial<Record<MaterialPluginPoint, string>>` the adapter declares.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const code = { fragment, vertex } as LitePluginCode;\n return createLiteMaterialPlugin(\n {\n name: compiled.plugin.name,\n priority: init.priority ?? compiled.plugin.priority,\n fields: compiled.plugin.uniforms.map((uniform) => ({\n name: uniform.name,\n type: uniform.type,\n components: uniformComponentCount(uniform.type),\n })),\n samplers: compiled.plugin.textures.map((texture) => ({\n texture: texture.name,\n sampler: `${texture.name}Sampler`,\n array: texture.array,\n })),\n code,\n isStandardHost: capabilities.family === \"standard\",\n },\n state,\n );\n}\n","import { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { IgnifxError } from \"../errors/ignifx-error.js\";\nimport { defineMaterialPlugin } from \"./material-plugin.js\";\nimport { SURFACE_HOOK_NAMES, SURFACE_UNIFORM_BLOCK } from \"./shader-declaration.js\";\nimport type { LiteMaterialPluginPoint, MaterialPluginDefinition } from \"./material-plugin.js\";\nimport type { ShaderDeclaration, SurfaceHookName } from \"./shader-declaration.js\";\n\n/**\n * The surface-shader compiler: three plain WGSL functions in, one Babylon Lite material plugin out\n * (`docs/plan/2026-09-terrain-particles-shaders.md` §3.2).\n *\n * A `.surface.wgsl` declares its uniforms and textures with `// @ignifx` pragmas and provides up to\n * three functions that never mention Lite: `SurfaceInput`, `Surface` and `DisplaceInput` are\n * generated here, and `surfaceUniforms.x` is rewritten to whichever uniform block the host family\n * carries.\n *\n * ```wgsl\n * // @ignifx surface\n * // @ignifx uniform amount: f32 = 0.6 range(0, 1)\n * fn surface(in: SurfaceInput, s: ptr<function, Surface>) {\n * (*s).baseColor = mix((*s).baseColor, vec3<f32>(1.0), surfaceUniforms.amount);\n * }\n * ```\n *\n * Where each hook lands, and what that costs:\n *\n * | Hook | PBR slot | Standard slot |\n * | --- | --- | --- |\n * | `displace` | `CUSTOM_VERTEX_UPDATE_WORLDPOS`, inlined | the same |\n * | `surface` | `CUSTOM_FRAGMENT_UPDATE_ALPHA` + `CUSTOM_FRAGMENT_UPDATE_DIFFUSE` | `CUSTOM_FRAGMENT_UPDATE_ALPHA` alone |\n * | `composite` | `CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION` | **unsupported** |\n *\n * - Every declared name is emitted as `<shader>_<name>` and the author's references are rewritten,\n * because a plugin's fields join the **host material's** uniform block and bind group. A declared\n * texture's name is therefore reserved inside the file.\n * - `displace` cannot read a uniform, a texture or a helper function — Lite's plugin uniforms and\n * samplers are fragment-visible only and it offers no vertex helper channel — so its body is\n * inlined with its `return` rewritten to a `break`, and one that reads any of them, or that loops\n * or switches (which would capture that `break`), is refused here.\n * - A `surface` hook's write to `alpha` reaches blending, not the cutout test: the alpha-test\n * fragment sorts before a plugin in Lite's slot composition, so an `alphaMode: \"mask\"` host has\n * already discarded by the time the hook runs.\n * - `composite` is injected twice (Lite maps the point to the adjacent PBR slots `AI` and `NI`), so\n * the generated code is guarded by a flag declared in the `UPDATE_ALPHA` block.\n * - `emissive` is written as the delta `s.emissive - emissive` added to `color`, because the PBR\n * template declares `emissive` as `let` or `var` depending on the host's textures.\n * - `roughness` and `metallic` are readable and ignored on write (`let` in the template). Vertex\n * colour reads white and `uv2` is absent: Lite gates both behind state a plugin cannot see.\n */\n\n/**\n * The material family a surface shader is compiled against. The generated WGSL differs: the two\n * templates name their variables differently and Standard has fewer injection points.\n *\n * @public\n */\nexport type SurfaceHostFamily = \"pbr\" | \"standard\";\n\n/**\n * What the compiler has to know about the host material beyond its family.\n *\n * @remarks\n * Both flags exist because Standard's template declares a varying or a variable only when something\n * asks for it: `input.vu` exists only when the material carries a texture that samples UV\n * (`standard-flags.js` `NEEDS_UV`), and `normalW` only when lighting is on. Referencing either\n * without it is a WGSL compile error in Lite's own template, so the compiler substitutes a constant\n * instead. A PBR host always has both.\n *\n * @public\n */\nexport interface SurfaceHostCapabilities {\n /** Which family's slots and variable names to generate for. */\n readonly family: SurfaceHostFamily;\n /** Whether the host declares a UV varying. `false` makes `in.uv` read `(0, 0)`. */\n readonly hasUv: boolean;\n /** Whether the host declares a shading normal. `false` makes a `normal` write a no-op. */\n readonly hasNormal: boolean;\n}\n\n/**\n * One hook, as it was found in the file.\n *\n * @internal\n */\nexport interface SurfaceHook {\n /** Which hook it is. */\n readonly name: SurfaceHookName;\n /** The parameter identifiers, in order, as the author wrote them. */\n readonly parameters: readonly string[];\n /** The statements between the braces, verbatim. */\n readonly body: string;\n /** Where the whole `fn …` declaration starts in the source. */\n readonly start: number;\n /** Where it ends, one past the closing brace. */\n readonly end: number;\n}\n\n/**\n * The hooks a file provides, plus everything else it declared.\n *\n * @internal\n */\nexport interface SurfaceShaderHooks {\n /** The vertex offset hook, or `null`. */\n readonly displace: SurfaceHook | null;\n /** The surface hook, or `null`. */\n readonly surface: SurfaceHook | null;\n /** The post-lighting hook, or `null`. */\n readonly composite: SurfaceHook | null;\n /** The file with the three hook declarations cut out: structs, constants, helper functions. */\n readonly rest: string;\n}\n\n/** The members a `displace` hook may read off its parameter. */\nconst DISPLACE_MEMBERS: readonly string[] = Object.freeze([\"position\", \"normal\", \"uv\", \"color\", \"world\"]);\n\n/** Matches the start of a top-level hook declaration. */\nconst HOOK_START = /\\bfn\\s+(displace|surface|composite)\\s*\\(/g;\n\n/** Matches `surfaceUniforms.<identifier>`. */\nconst UNIFORM_REFERENCE = /\\bsurfaceUniforms\\s*\\.\\s*([A-Za-z_][A-Za-z0-9_]*)/g;\n\n/** Matches a `return <expression>;` statement. */\nconst RETURN_STATEMENT = /\\breturn\\b([^;]*);/g;\n\n/** Matches any WGSL control-flow construct a `break` could bind to. */\nconst BREAKING_CONSTRUCT = /\\b(loop|for|while|switch)\\b/;\n\n/** Matches the start of any top-level function declaration, capturing its name. */\nconst FUNCTION_START = /\\bfn\\s+([A-Za-z_][A-Za-z0-9_]*)\\s*\\(/g;\n\n/**\n * Finds the hooks a `.surface.wgsl` file declares.\n *\n * @remarks\n * A hand-written brace scan rather than a WGSL parser: the file has already been validated by the\n * Vite plugin at build time, and all this needs is the extent of three top-level functions. It\n * looks for `fn displace|surface|composite (` anywhere in the file and then matches the parameter\n * parentheses and the body braces, so a hook may be written in any order and with any formatting.\n *\n * @param source - The whole file.\n * @param address - The asset address, for the error message.\n * @returns The hooks found and the rest of the file.\n * @throws IgnifxError with code `IGX-0723` when the file declares none of the three, or `IGX-0719`\n * when a hook's braces or parentheses do not close.\n *\n * @internal\n */\nexport function parseSurfaceHooks(source: string, address: string): SurfaceShaderHooks {\n const found = new Map<SurfaceHookName, SurfaceHook>();\n const cuts: { start: number; end: number }[] = [];\n HOOK_START.lastIndex = 0;\n let match = HOOK_START.exec(source);\n while (match !== null) {\n const name = match[1];\n const openParen = match.index + match[0].length - 1;\n const closeParen = matchDelimiter(source, openParen, \"(\", \")\");\n const openBrace = source.indexOf(\"{\", closeParen);\n if (closeParen < 0 || openBrace < 0) {\n throw new IgnifxError(CoreErrorCode.invalidShaderPragma, `${address}: the ${name} hook does not close.`, {\n context: { asset: address, hook: name ?? \"\" },\n hint: \"Check the parentheses and braces of the hook declaration.\",\n });\n }\n const closeBrace = matchDelimiter(source, openBrace, \"{\", \"}\");\n if (closeBrace < 0) {\n throw new IgnifxError(CoreErrorCode.invalidShaderPragma, `${address}: the ${name} hook's body does not close.`, {\n context: { asset: address, hook: name ?? \"\" },\n hint: \"Add the missing closing brace.\",\n });\n }\n if (isSurfaceHookName(name)) {\n found.set(name, {\n name,\n parameters: parseParameterNames(source.slice(openParen + 1, closeParen)),\n body: source.slice(openBrace + 1, closeBrace),\n start: match.index,\n end: closeBrace + 1,\n });\n cuts.push({ start: match.index, end: closeBrace + 1 });\n }\n HOOK_START.lastIndex = closeBrace + 1;\n match = HOOK_START.exec(source);\n }\n if (found.size === 0) {\n throw new IgnifxError(\n CoreErrorCode.surfaceHookMissing,\n `${address} declares a surface shader with none of the hooks displace, surface, or composite.`,\n {\n context: { asset: address },\n hint: \"Add fn surface(in: SurfaceInput, s: ptr<function, Surface>), fn composite(in, color), or fn displace(in).\",\n },\n );\n }\n return {\n displace: found.get(\"displace\") ?? null,\n surface: found.get(\"surface\") ?? null,\n composite: found.get(\"composite\") ?? null,\n rest: cutRanges(source, cuts),\n };\n}\n\n/**\n * What {@link compileSurfaceShader} needs.\n *\n * @internal\n */\nexport interface SurfaceShaderCompileInput {\n /** The shader's name on the material; it prefixes every generated identifier. */\n readonly name: string;\n /** The asset address, for error messages. */\n readonly address: string;\n /** The whole `.surface.wgsl` file. */\n readonly source: string;\n /** What its pragmas declared. */\n readonly declaration: ShaderDeclaration;\n /** The host material family and what its template exposes. */\n readonly host: SurfaceHostCapabilities;\n}\n\n/**\n * A compiled surface shader: the Lite plugin, and the mapping from the names the author declared to\n * the prefixed fields the host material actually carries.\n *\n * @internal\n */\nexport interface CompiledSurfaceShader {\n /** The Lite plugin definition, whose bindings are named `<shader>_<declared>`. */\n readonly plugin: MaterialPluginDefinition;\n /** The prefix every generated identifier carries, including the trailing underscore. */\n readonly prefix: string;\n /** Which hooks the file provided. */\n readonly hooks: Readonly<Record<SurfaceHookName, boolean>>;\n}\n\n/**\n * Compiles a `.surface.wgsl` file into one Babylon Lite material plugin.\n *\n * @remarks\n * Deterministic and device-free, so it is fully testable in Node: the result is the plain\n * {@link MaterialPluginDefinition} the adapter turns into a Lite object.\n *\n * @param input - The shader, its declaration, and the host family.\n * @returns The plugin definition, with the generated WGSL in `code`, and its name prefix.\n * @throws IgnifxError with code `IGX-0723` when the file declares no hook, or a hook the host family\n * has no slot for, or a `displace` that reads a uniform or a texture; `IGX-0712` when a declared\n * name is not usable as a plugin binding; `IGX-0719` when a hook is malformed.\n *\n * @example\n * ```ts\n * const compiled = compileSurfaceShader({\n * name: \"snow\",\n * address: \"shaders/snow.surface.wgsl\",\n * source,\n * declaration,\n * host: { family: \"pbr\", hasUv: true, hasNormal: true },\n * });\n * compiled.plugin.code.CUSTOM_FRAGMENT_UPDATE_ALPHA; // builds SurfaceInput and calls snow_surface\n * ```\n *\n * @internal\n */\nexport function compileSurfaceShader(input: SurfaceShaderCompileInput): CompiledSurfaceShader {\n const hooks = parseSurfaceHooks(input.source, input.address);\n const prefix = `${sanitizeIdentifier(input.name)}_`;\n const isStandard = input.host.family === \"standard\";\n if (isStandard && hooks.composite !== null) {\n throw new IgnifxError(\n CoreErrorCode.surfaceHookMissing,\n `${input.address} declares the composite hook, which a standard material has no slot for.`,\n {\n context: { asset: input.address, hook: \"composite\", family: input.host.family },\n hint: \"Attach the surface shader to a pbr material, or move the effect into the surface hook.\",\n },\n );\n }\n const rewrite = buildRewriter(prefix, input.declaration, isStandard);\n const code: Partial<Record<LiteMaterialPluginPoint, string>> = {};\n const definitions = buildDefinitions(prefix, hooks, rewrite);\n if (definitions !== \"\") {\n code.CUSTOM_FRAGMENT_DEFINITIONS = definitions;\n }\n if (hooks.surface !== null || hooks.composite !== null) {\n code.CUSTOM_FRAGMENT_UPDATE_ALPHA = buildUpdateAlpha(prefix, hooks, input.host);\n if (hooks.surface !== null && !isStandard) {\n code.CUSTOM_FRAGMENT_UPDATE_DIFFUSE = `if(any(${prefix}normal!=${prefix}in.geometricNormal)){N=normalize(${prefix}normal);}`;\n }\n if (!isStandard) {\n code.CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION = buildComposite(prefix, hooks);\n }\n }\n if (hooks.displace !== null) {\n code.CUSTOM_VERTEX_UPDATE_WORLDPOS = buildDisplace(prefix, hooks.displace, input);\n }\n const plugin = defineMaterialPlugin({\n name: input.name,\n uniforms: input.declaration.uniforms.map((uniform) => ({ ...uniform, name: `${prefix}${uniform.name}` })),\n textures: input.declaration.textures.map((texture) => ({ ...texture, name: `${prefix}${texture.name}` })),\n code,\n });\n return {\n plugin,\n prefix,\n hooks: {\n displace: hooks.displace !== null,\n surface: hooks.surface !== null,\n composite: hooks.composite !== null,\n },\n };\n}\n\n/**\n * The fragment helper block: the generated structs and everything the file declared, hooks included,\n * with the two fragment hooks given generated signatures.\n *\n * @param prefix - The per-shader identifier prefix.\n * @param hooks - The parsed hooks.\n * @param rewrite - The identifier rewriter.\n * @returns The WGSL, or `\"\"` when the file provides no fragment hook.\n */\nfunction buildDefinitions(prefix: string, hooks: SurfaceShaderHooks, rewrite: (code: string) => string): string {\n if (hooks.surface === null && hooks.composite === null) {\n return \"\";\n }\n const parts: string[] = [\n `struct ${prefix}SurfaceInput{uv:vec2<f32>,worldPosition:vec3<f32>,geometricNormal:vec3<f32>,viewDirection:vec3<f32>,color:vec4<f32>,}`,\n `struct ${prefix}Surface{baseColor:vec3<f32>,alpha:f32,emissive:vec3<f32>,normal:vec3<f32>,roughness:f32,metallic:f32,}`,\n rewrite(hooks.rest),\n ];\n const surface = hooks.surface;\n if (surface !== null) {\n const input = surface.parameters[0] ?? \"in\";\n const state = surface.parameters[1] ?? \"s\";\n parts.push(\n `fn ${prefix}surface(${input}:${prefix}SurfaceInput,${state}:ptr<function,${prefix}Surface>){${rewrite(surface.body)}}`,\n );\n }\n const composite = hooks.composite;\n if (composite !== null) {\n const input = composite.parameters[0] ?? \"in\";\n const color = composite.parameters[1] ?? \"color\";\n parts.push(\n `fn ${prefix}composite(${input}:${prefix}SurfaceInput,${color}:vec3<f32>)->vec3<f32>{${rewrite(composite.body)}}`,\n );\n }\n return parts.join(\"\\n\");\n}\n\n/**\n * The `CUSTOM_FRAGMENT_UPDATE_ALPHA` block: build `SurfaceInput`, call the hook, write back what the\n * template lets us write back, and stash the rest for the later slots.\n *\n * @remarks\n * Deliberately **not** wrapped in braces: the variables it declares are read by the\n * `UPDATE_DIFFUSE` and `BEFORE_FINALCOLORCOMPOSITION` blocks, which Lite injects into the same\n * function scope further down. Every name is prefixed, so two surface shaders on one material\n * declare two sets rather than colliding.\n *\n * @param prefix - The per-shader identifier prefix.\n * @param hooks - The parsed hooks.\n * @param host - The host family and its capabilities.\n * @returns The WGSL statements.\n */\nfunction buildUpdateAlpha(prefix: string, hooks: SurfaceShaderHooks, host: SurfaceHostCapabilities): string {\n const isStandard = host.family === \"standard\";\n const worldPosition = isStandard ? \"input.vp\" : \"input.worldPos\";\n const geometricNormal = isStandard ? \"normalize(input.vn)\" : \"normalize(input.worldNormal)\";\n const uv = host.hasUv ? (isStandard ? \"input.vu\" : \"input.uv\") : \"vec2<f32>(0.0)\";\n const emissive = isStandard ? \"emissiveContrib\" : \"emissive\";\n const lines: string[] = [\n `var ${prefix}in:${prefix}SurfaceInput;`,\n `${prefix}in.uv=${uv};`,\n `${prefix}in.worldPosition=${worldPosition};`,\n `${prefix}in.geometricNormal=${geometricNormal};`,\n `${prefix}in.viewDirection=normalize(scene.vEyePosition.xyz-${worldPosition});`,\n `${prefix}in.color=vec4<f32>(1.0);`,\n `var ${prefix}emissiveDelta=vec3<f32>(0.0);`,\n `var ${prefix}composited=false;`,\n ];\n if (hooks.surface !== null) {\n lines.push(\n `var ${prefix}s:${prefix}Surface;`,\n `${prefix}s.baseColor=baseColor;`,\n `${prefix}s.alpha=alpha;`,\n `${prefix}s.emissive=${emissive};`,\n `${prefix}s.normal=${prefix}in.geometricNormal;`,\n // Standard has no roughness or metallic at all; PBR has both, as read-only `let`s.\n isStandard ? `${prefix}s.roughness=1.0;` : `${prefix}s.roughness=roughness;`,\n isStandard ? `${prefix}s.metallic=0.0;` : `${prefix}s.metallic=metallic;`,\n `${prefix}surface(${prefix}in,&${prefix}s);`,\n `baseColor=${prefix}s.baseColor;`,\n `alpha=${prefix}s.alpha;`,\n `var ${prefix}normal=${prefix}s.normal;`,\n );\n if (isStandard) {\n // Standard's `/*AC*/` runs before `/*AT*/`, so the normal is written here, and its emissive\n // term is a `var` we can replace outright.\n lines.push(`${emissive}=${prefix}s.emissive;`);\n if (host.hasNormal) {\n lines.push(`if(any(${prefix}normal!=${prefix}in.geometricNormal)){normalW=normalize(${prefix}normal);}`);\n }\n } else {\n lines.push(`${prefix}emissiveDelta=${prefix}s.emissive-${emissive};`);\n }\n }\n return lines.join(\"\\n\");\n}\n\n/**\n * The `CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION` block: the emissive delta and the `composite`\n * hook, guarded because Lite injects this point twice.\n *\n * @param prefix - The per-shader identifier prefix.\n * @param hooks - The parsed hooks.\n * @returns The WGSL statements.\n */\nfunction buildComposite(prefix: string, hooks: SurfaceShaderHooks): string {\n const inner: string[] = [`${prefix}composited=true;`, `color=color+${prefix}emissiveDelta;`];\n if (hooks.composite !== null) {\n inner.push(`color=${prefix}composite(${prefix}in,color);`);\n }\n return `if(!${prefix}composited){${inner.join(\"\")}}`;\n}\n\n/**\n * The `CUSTOM_VERTEX_UPDATE_WORLDPOS` block: the `displace` body, inlined.\n *\n * @remarks\n * Inlined rather than called, because Lite gives a plugin no way to declare a function in the vertex\n * module (`buildPluginFragment` fills `_helperFunctions`, which the composer routes to the fragment\n * template alone). The body is wrapped in a `loop` whose `return` statements are rewritten to\n * `break`, which is what lets an author write ordinary early-returning WGSL: a value-returning\n * function has to return on every path, so the loop always terminates on its first iteration.\n *\n * @param prefix - The per-shader identifier prefix.\n * @param hook - The parsed `displace` hook.\n * @param input - The compile input, for the declaration and the error messages.\n * @returns The WGSL statements.\n * @throws IgnifxError with code `IGX-0723` when the body reads a uniform, a texture, or a member\n * that the vertex stage cannot supply.\n */\nfunction buildDisplace(prefix: string, hook: SurfaceHook, input: SurfaceShaderCompileInput): string {\n assertVertexSafe(hook, input);\n const parameter = hook.parameters[0] ?? \"in\";\n const uv = input.host.hasUv ? \"uv\" : \"vec2<f32>(0.0)\";\n let body = hook.body;\n body = body.replaceAll(new RegExp(`\\\\b${escapeForRegExp(parameter)}\\\\s*\\\\.\\\\s*position\\\\b`, \"g\"), \"position\");\n body = body.replaceAll(new RegExp(`\\\\b${escapeForRegExp(parameter)}\\\\s*\\\\.\\\\s*normal\\\\b`, \"g\"), \"normal\");\n body = body.replaceAll(new RegExp(`\\\\b${escapeForRegExp(parameter)}\\\\s*\\\\.\\\\s*uv\\\\b`, \"g\"), uv);\n body = body.replaceAll(new RegExp(`\\\\b${escapeForRegExp(parameter)}\\\\s*\\\\.\\\\s*color\\\\b`, \"g\"), \"vec4<f32>(1.0)\");\n body = body.replaceAll(new RegExp(`\\\\b${escapeForRegExp(parameter)}\\\\s*\\\\.\\\\s*world\\\\b`, \"g\"), \"finalWorld\");\n body = body.replaceAll(RETURN_STATEMENT, (_whole: string, expression: string): string => {\n return `{${prefix}offset=${expression.trim()};break;}`;\n });\n return [\n `{var ${prefix}offset=vec3<f32>(0.0);`,\n `loop{${body}}`,\n `finalWorld[3].x+=${prefix}offset.x;`,\n `finalWorld[3].y+=${prefix}offset.y;`,\n `finalWorld[3].z+=${prefix}offset.z;}`,\n ].join(\"\\n\");\n}\n\n/**\n * Refuses a `displace` body the vertex stage cannot compile.\n *\n * @param hook - The parsed hook.\n * @param input - The compile input.\n * @throws IgnifxError with code `IGX-0723`.\n */\nfunction assertVertexSafe(hook: SurfaceHook, input: SurfaceShaderCompileInput): void {\n const address = input.address;\n if (hook.body.includes(SURFACE_UNIFORM_BLOCK)) {\n throw new IgnifxError(\n CoreErrorCode.surfaceHookMissing,\n `${address}: the displace hook reads ${SURFACE_UNIFORM_BLOCK}, which Babylon Lite declares in the fragment stage only.`,\n {\n context: { asset: address, hook: \"displace\" },\n hint: \"Displace by geometry alone on Lite 1.27.0; a time-driven offset needs a full shader material.\",\n },\n );\n }\n for (const texture of input.declaration.textures) {\n if (new RegExp(`\\\\b${escapeForRegExp(texture.name)}\\\\b`).test(hook.body)) {\n throw new IgnifxError(\n CoreErrorCode.surfaceHookMissing,\n `${address}: the displace hook samples ${texture.name}, and Babylon Lite's plugin samplers are fragment-stage only.`,\n {\n context: { asset: address, hook: \"displace\", name: texture.name },\n hint: \"Move the texture read into the surface hook, or use a full shader material.\",\n },\n );\n }\n }\n if (BREAKING_CONSTRUCT.test(hook.body)) {\n throw new IgnifxError(\n CoreErrorCode.surfaceHookMissing,\n `${address}: the displace hook uses a loop or switch, which this build cannot inline into Babylon Lite's vertex entry point.`,\n {\n context: { asset: address, hook: \"displace\" },\n hint: \"Write the displacement as straight-line code, or use a full shader material.\",\n },\n );\n }\n for (const helper of fileFunctions(input.source)) {\n if (new RegExp(`\\\\b${escapeForRegExp(helper)}\\\\s*\\\\(`).test(hook.body)) {\n throw new IgnifxError(\n CoreErrorCode.surfaceHookMissing,\n `${address}: the displace hook calls ${helper}, and Babylon Lite gives a plugin no vertex-stage helper functions.`,\n {\n context: { asset: address, hook: \"displace\", name: helper },\n hint: \"Inline the helper into the displace body, or use a full shader material.\",\n },\n );\n }\n }\n const parameter = hook.parameters[0] ?? \"in\";\n const members = new RegExp(`\\\\b${escapeForRegExp(parameter)}\\\\s*\\\\.\\\\s*([A-Za-z_][A-Za-z0-9_]*)`, \"g\");\n let match = members.exec(hook.body);\n while (match !== null) {\n const member = match[1] ?? \"\";\n if (!DISPLACE_MEMBERS.includes(member)) {\n throw new IgnifxError(\n CoreErrorCode.surfaceHookMissing,\n `${address}: the displace hook reads ${parameter}.${member}, which DisplaceInput does not carry.`,\n {\n context: { asset: address, hook: \"displace\", name: member },\n hint: `DisplaceInput carries ${DISPLACE_MEMBERS.join(\", \")}.`,\n },\n );\n }\n match = members.exec(hook.body);\n }\n}\n\n/**\n * The names of every function a file declares that is not one of the three hooks.\n *\n * @param source - The whole `.surface.wgsl` file.\n * @returns The helper names, in declaration order.\n */\nfunction fileFunctions(source: string): readonly string[] {\n const names: string[] = [];\n FUNCTION_START.lastIndex = 0;\n let match = FUNCTION_START.exec(source);\n while (match !== null) {\n const name = match[1] ?? \"\";\n if (!(SURFACE_HOOK_NAMES as readonly string[]).includes(name)) {\n names.push(name);\n }\n match = FUNCTION_START.exec(source);\n }\n return names;\n}\n\n/**\n * Builds the function that rewrites the author's references to the names the host material actually\n * declares.\n *\n * @param prefix - The per-shader identifier prefix.\n * @param declaration - What the file declared, for its texture names.\n * @param isStandard - Whether the host is a Standard material, which reads its plugin uniforms from\n * `pluginUbo` rather than from the PBR material block (`plugin-bridge-shared.js` 99).\n * @returns The rewriter.\n */\nfunction buildRewriter(prefix: string, declaration: ShaderDeclaration, isStandard: boolean): (code: string) => string {\n const block = isStandard ? \"pluginUbo\" : \"material\";\n const samplers: string[] = [];\n for (const texture of declaration.textures) {\n samplers.push(`${texture.name}Sampler`, texture.name);\n }\n // Longest first, so `noiseSampler` is not rewritten as the prefix of `noise` plus `Sampler`.\n samplers.sort((left, right) => right.length - left.length);\n const pattern = samplers.length === 0 ? null : new RegExp(`\\\\b(${samplers.map(escapeForRegExp).join(\"|\")})\\\\b`, \"g\");\n return (code: string): string => {\n const withUniforms = code.replaceAll(UNIFORM_REFERENCE, (_whole: string, name: string): string => {\n return `${block}.${prefix}${name}`;\n });\n return pattern === null\n ? withUniforms\n : withUniforms.replaceAll(pattern, (_whole: string, name: string): string => `${prefix}${name}`);\n };\n}\n\n/**\n * The index of the delimiter that closes the one at `open`.\n *\n * @param source - The text.\n * @param open - The index of the opening delimiter.\n * @param openChar - The opening delimiter.\n * @param closeChar - The closing delimiter.\n * @returns The closing index, or `-1` when it never closes.\n */\nfunction matchDelimiter(source: string, open: number, openChar: string, closeChar: string): number {\n let depth = 0;\n for (let index = open; index < source.length; index += 1) {\n const char = source[index];\n if (char === openChar) {\n depth += 1;\n } else if (char === closeChar) {\n depth -= 1;\n if (depth === 0) {\n return index;\n }\n }\n }\n return -1;\n}\n\n/**\n * The parameter identifiers of a WGSL parameter list.\n *\n * @param list - The text between the parentheses.\n * @returns The names, in order.\n */\nfunction parseParameterNames(list: string): readonly string[] {\n const names: string[] = [];\n let depth = 0;\n let start = 0;\n for (let index = 0; index <= list.length; index += 1) {\n const char = list[index];\n if (char === \"<\" || char === \"(\") {\n depth += 1;\n } else if (char === \">\" || char === \")\") {\n depth -= 1;\n } else if ((char === \",\" && depth === 0) || index === list.length) {\n const parameter = list.slice(start, index).trim();\n const colon = parameter.indexOf(\":\");\n const name = (colon < 0 ? parameter : parameter.slice(0, colon)).trim();\n if (name !== \"\") {\n names.push(name);\n }\n start = index + 1;\n }\n }\n return names;\n}\n\n/**\n * The text with the given ranges removed.\n *\n * @param source - The text.\n * @param ranges - The ranges to cut, in ascending order.\n * @returns What is left.\n */\nfunction cutRanges(source: string, ranges: readonly { start: number; end: number }[]): string {\n let result = \"\";\n let cursor = 0;\n for (const range of ranges) {\n result += source.slice(cursor, range.start);\n cursor = range.end;\n }\n return result + source.slice(cursor);\n}\n\n/**\n * Whether a captured name is one of the three hooks.\n *\n * @param value - The candidate.\n * @returns `true` when it is.\n */\nfunction isSurfaceHookName(value: string | undefined): value is SurfaceHookName {\n return value === \"displace\" || value === \"surface\" || value === \"composite\";\n}\n\n/**\n * Turns a shader name into a WGSL identifier prefix.\n *\n * @param name - The shader's name on the material.\n * @returns The sanitized name; a leading digit is prefixed with an underscore.\n *\n * @internal\n */\nexport function sanitizeIdentifier(name: string): string {\n const replaced = name.replaceAll(/[^A-Za-z0-9_]/g, \"_\");\n return /^[0-9]/.test(replaced) ? `_${replaced}` : replaced;\n}\n\n/**\n * Escapes a literal for use inside a regular expression.\n *\n * @param value - The literal.\n * @returns The escaped form.\n */\nfunction escapeForRegExp(value: string): string {\n return value.replaceAll(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n","import { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { IgnifxError } from \"../errors/ignifx-error.js\";\nimport { Color } from \"../math/color.js\";\nimport {\n attachSurfacePlugins,\n buildSurfacePlugin,\n detachSurfacePlugins,\n markSurfaceValueChanged,\n rebuildSurfaceHost,\n resolveSurfaceFallbacks,\n resolveSurfaceHost,\n} from \"./gpu/surface-shader-host.js\";\nimport { MATERIAL_PLUGIN_SAMPLER_BUDGET, uniformComponentCount } from \"./material-plugin.js\";\nimport { compileSurfaceShader, sanitizeIdentifier } from \"./surface-shader-compiler.js\";\nimport type { MaterialAsset } from \"./material-asset.js\";\nimport type { ShaderAsset } from \"./shader-asset.js\";\nimport type { ShaderUniformDeclaration } from \"./shader-declaration.js\";\nimport type { SurfaceHostCapabilities } from \"./surface-shader-compiler.js\";\nimport type { TextureAsset } from \"./texture-asset.js\";\nimport type { App } from \"../app/types.js\";\nimport type { AssetHandle } from \"../assets/types.js\";\nimport type { LiteMaterialPlugin, LitePluginHost, LitePluginState } from \"../lite/gpu/material-plugin.js\";\nimport type { LiteTexture2D } from \"../lite/gpu/texture.js\";\nimport type { ColorLike } from \"../math/types.js\";\n\n/**\n * Surface shaders: lit, shadowed, IBL-lit custom looks on a **PBR** material\n * (`docs/plan/2026-09-terrain-particles-shaders.md` §3.2, ADR-0024).\n *\n * Three named hooks into the engine's own PBR shader, compiled into one Babylon Lite material\n * plugin, so a custom look keeps direct lighting, shadows, IBL, fog and tone mapping.\n * `./surface-shader-compiler.ts` documents the generated WGSL.\n *\n * ```ts\n * const snow = await app.assets.loadAsync<ShaderAsset>(\"shaders/snow.surface.wgsl\");\n * const rock = createMaterialAsset(\n * app,\n * pbrMaterialDefinition({\n * name: \"rock\",\n * roughness: 0.9,\n * surfaces: [{ shader: snow.address, name: \"snow\", values: {}, textures: {}, enabled: true, priority: 500 }],\n * }),\n * [],\n * );\n * rock.value.surface(\"snow\").set(\"amount\", 0.8);\n * ```\n *\n * Four constraints:\n *\n * - A **Standard** host is refused: Lite 1.27.0 bakes a Standard material's plugin signature from\n * the meshes already in the scene, which in ignifx is never in time.\n * - `rendering.features.materialPlugins` has to be declared before the scene is registered\n * (`IGX-0716` on a device, one warning headless).\n * - A material's surface shaders share one sampler budget of\n * {@link MATERIAL_PLUGIN_SAMPLER_BUDGET}, measured on a device beside a fully textured PBR\n * material with IBL and a shadow light.\n * - Attaching, detaching, toggling `enabled` and binding a texture each change Lite's pipeline cache\n * key and rebuild the material's renderables; writing a value only re-uploads the uniform block.\n */\n\n/**\n * What a material declares for one attached surface shader.\n *\n * @public\n */\nexport interface SurfaceShaderInit {\n /** The loaded `.surface.wgsl`. */\n readonly shader: AssetHandle<ShaderAsset>;\n /**\n * The name the shader answers to on this material. Defaults to the address's basename with\n * `.surface.wgsl` removed, so `shaders/snow.surface.wgsl` is `snow`.\n */\n readonly name?: string;\n /** Overrides of the file's declared uniform defaults, by declared name. */\n readonly values?: Readonly<Record<string, number | readonly number[] | ColorLike>>;\n /** Textures for the file's declared samplers, by declared name. */\n readonly textures?: Readonly<Record<string, AssetHandle<TextureAsset>>>;\n /** Whether the shader contributes anything. Defaults to `true`. */\n readonly enabled?: boolean;\n /** Lower runs first among the material's surface shaders. Defaults to `500`, Babylon Lite's own. */\n readonly priority?: number;\n}\n\n/**\n * What a `.material.json` writes for one surface shader: the shader's address and its values.\n *\n * @remarks\n * The runtime shape is {@link SurfaceShaderInit}, which carries handles; this is the serialized one,\n * which carries addresses, and is what a PBR or Standard material definition holds.\n *\n * @public\n */\nexport interface SurfaceShaderReference {\n /** The address of the `.surface.wgsl`. */\n readonly shader: string;\n /** The name the shader answers to; empty takes the address's basename. */\n readonly name: string;\n /** Overrides of the file's declared uniform defaults. */\n readonly values: Readonly<Record<string, number | readonly number[]>>;\n /** Texture addresses by declared sampler name. */\n readonly textures: Readonly<Record<string, string>>;\n /** Whether the shader contributes anything. */\n readonly enabled: boolean;\n /** Lower runs first. */\n readonly priority: number;\n}\n\n/** Babylon Lite's own default plugin priority; the surface shaders of one material sort by it. */\nconst DEFAULT_PRIORITY = 500;\n\n/** What a material with no surface shaders reports, shared so the per-frame read allocates nothing. */\nconst NO_BINDINGS: readonly SurfaceShaderBinding[] = Object.freeze([]);\n\n/**\n * What a binding tells its attachment when something changes.\n *\n * @internal\n */\nexport interface SurfaceShaderOwner {\n /** A uniform was written: re-upload the host material's uniform block. */\n onValueChanged(): void;\n /**\n * The pipeline cache key moved — a texture was bound, or `enabled` was toggled — so the host\n * material's renderables have to be rebuilt.\n */\n onShapeChanged(): void;\n}\n\n/**\n * The live state one attached surface shader's Lite plugin reads, with the fields the binding\n * writes.\n *\n * @internal\n */\nexport interface MutablePluginState extends LitePluginState {\n /** Whether the plugin contributes code. */\n enabled: boolean;\n /** The texture bound to each declared sampler, in declaration order. */\n readonly textures: (LiteTexture2D | null)[];\n /** The Lite plugin object, or `null` under a headless app, which builds none. */\n plugin: LiteMaterialPlugin | null;\n}\n\n/**\n * What a {@link SurfaceShaderBinding} is built from.\n *\n * @internal\n */\nexport interface SurfaceShaderBindingInput {\n /** The name the shader answers to. */\n readonly name: string;\n /** The shader asset. */\n readonly shader: ShaderAsset;\n /** The sort priority. */\n readonly priority: number;\n /** The host material's name, for diagnostics. */\n readonly material: string;\n /** The generated identifier prefix, including the trailing underscore. */\n readonly prefix: string;\n /** The declared uniforms, by the name the file wrote. */\n readonly uniforms: ReadonlyMap<string, ShaderUniformDeclaration>;\n /** The CPU-side values, by prefixed field name; the same map the Lite plugin reads. */\n readonly values: ReadonlyMap<string, Float32Array>;\n /** Declared sampler name to its index in the texture lists. */\n readonly textureIndex: ReadonlyMap<string, number>;\n /** The 1x1 texture each declared sampler falls back to, in declaration order. */\n readonly fallbacks: readonly (LiteTexture2D | null)[];\n /** The live state the Lite plugin reads. */\n readonly state: MutablePluginState;\n /** The attachment, which reacts to a change. */\n readonly owner: SurfaceShaderOwner;\n}\n\n/**\n * One surface shader attached to one material: the handle a game holds to change its values.\n *\n * @remarks\n * A material's bindings live as long as its attachment; reach them with `material.surfaces` and\n * `material.surface(name)`.\n *\n * @public\n */\nexport class SurfaceShaderBinding {\n /** The name the shader answers to on this material. */\n readonly name: string;\n\n /** The `.surface.wgsl` this binding was compiled from. */\n readonly shader: ShaderAsset;\n\n /** Lower runs first among the material's surface shaders. */\n readonly priority: number;\n\n readonly #material: string;\n\n readonly #prefix: string;\n\n readonly #uniforms: ReadonlyMap<string, ShaderUniformDeclaration>;\n\n readonly #values: ReadonlyMap<string, Float32Array>;\n\n readonly #textureIndex: ReadonlyMap<string, number>;\n\n readonly #fallbacks: readonly (LiteTexture2D | null)[];\n\n readonly #handles: (AssetHandle<TextureAsset> | null)[];\n\n readonly #state: MutablePluginState;\n\n readonly #owner: SurfaceShaderOwner;\n\n /**\n * Wraps one compiled, attached surface shader. `attachSurfaceShaders` constructs these.\n *\n * @param input - Everything the binding needs; assembled by `attachSurfaceShaders`.\n *\n * @internal\n */\n constructor(input: SurfaceShaderBindingInput) {\n this.name = input.name;\n this.shader = input.shader;\n this.priority = input.priority;\n this.#material = input.material;\n this.#prefix = input.prefix;\n this.#uniforms = input.uniforms;\n this.#values = input.values;\n this.#textureIndex = input.textureIndex;\n this.#fallbacks = input.fallbacks;\n this.#handles = input.fallbacks.map(() => null);\n this.#state = input.state;\n this.#owner = input.owner;\n }\n\n /**\n * Whether the shader contributes anything.\n *\n * @returns `true` while it does.\n */\n get enabled(): boolean {\n return this.#state.enabled;\n }\n\n /**\n * Switches the shader off, which restores the host material's plain look.\n *\n * @remarks\n * A disabled plugin contributes no WGSL but still changes Lite's pipeline cache key, so each\n * toggle costs a pipeline rebuild — a settings-screen operation, not a per-frame one.\n *\n * @param value - `false` to switch it off.\n */\n set enabled(value: boolean) {\n if (this.#state.enabled === value) {\n return;\n }\n this.#state.enabled = value;\n this.#owner.onShapeChanged();\n }\n\n /**\n * Writes one of the shader's declared uniforms.\n *\n * @remarks\n * The value is checked against the `// @ignifx uniform` declaration in the file, so a typo fails\n * at the call site rather than as a black surface. A uniform declared `color(…)` takes a\n * {@link ColorLike} in **sRGB** and is uploaded linear, like every other colour in ignifx. The\n * write re-uploads the host material's uniform block and recompiles nothing.\n *\n * @param name - The declared uniform's name, as the file wrote it.\n * @param value - A number, a numeric array of the declared length, or an sRGB colour.\n * @throws IgnifxError with code `IGX-0712` when the file declares no such uniform, or `IGX-0713`\n * when the value's shape does not match the declared type.\n *\n * @example\n * ```ts\n * snow.set(\"amount\", 0.8);\n * snow.set(\"snowColor\", { r: 0.95, g: 0.97, b: 1, a: 1 });\n * ```\n */\n set(name: string, value: number | readonly number[] | Float32Array | ColorLike): void {\n const declaration = this.#uniforms.get(name);\n const store = this.#values.get(`${this.#prefix}${name}`);\n if (declaration === undefined || store === undefined) {\n throw this.#unknownBinding(name, this.#uniforms.keys());\n }\n writeSurfaceValue(store, declaration, value, this.#material, this.name);\n this.#owner.onValueChanged();\n }\n\n /**\n * Reads a declared uniform's current value, as it stands on the CPU side. A colour reads back\n * **linear**, which is what the shader sees.\n *\n * @param name - The declared uniform's name.\n * @param out - Receives a vector or matrix value; omit it for a fresh array, or read a scalar's\n * number directly.\n * @returns The number for `f32`, `u32`, and `i32`, and the filled array for everything else.\n * @throws IgnifxError with code `IGX-0712` when the file declares no such uniform, or `IGX-0713`\n * when `out` is shorter than the value.\n */\n get(name: string, out?: Float32Array): number | Float32Array {\n const store = this.#values.get(`${this.#prefix}${name}`);\n if (store === undefined) {\n throw this.#unknownBinding(name, this.#uniforms.keys());\n }\n if (out === undefined) {\n return store.length === 1 ? (store[0] ?? 0) : store.slice();\n }\n if (out.length < store.length) {\n throw new IgnifxError(\n CoreErrorCode.shaderValueMismatch,\n `${name} on ${this.#material} expects ${String(store.length)} floats, not ${String(out.length)}.`,\n {\n context: { material: this.#material, name, expected: store.length, actual: out.length },\n hint: \"Pass a Float32Array at least as long as the declared type.\",\n },\n );\n }\n out.set(store);\n return out;\n }\n\n /**\n * Binds a texture to one of the shader's declared samplers.\n *\n * @remarks\n * There is no \"unbound\": a bind group with a missing entry fails WebGPU validation, so `null`\n * restores the declaration's 1x1 fallback — white unless the file said\n * `default black` or `default transparent`. The change rebuilds the material's renderables.\n *\n * @param name - The declared sampler's name.\n * @param texture - The texture, or `null` for the fallback.\n * @throws IgnifxError with code `IGX-0712` when the file declares no such sampler.\n */\n setTexture(name: string, texture: AssetHandle<TextureAsset> | null): void {\n const index = this.#textureIndex.get(name);\n if (index === undefined) {\n throw this.#unknownBinding(name, this.#textureIndex.keys());\n }\n this.#handles[index] = texture;\n const loaded = texture !== null && texture.state === \"loaded\" ? texture.value.lite.texture : null;\n this.#state.textures[index] = loaded ?? this.#fallbacks[index] ?? null;\n this.#owner.onShapeChanged();\n }\n\n /**\n * The texture currently bound to a declared sampler.\n *\n * @param name - The declared sampler's name.\n * @returns The handle, or `null` when the declaration's fallback is bound.\n * @throws IgnifxError with code `IGX-0712` when the file declares no such sampler.\n */\n getTexture(name: string): AssetHandle<TextureAsset> | null {\n const index = this.#textureIndex.get(name);\n if (index === undefined) {\n throw this.#unknownBinding(name, this.#textureIndex.keys());\n }\n return this.#handles[index] ?? null;\n }\n\n /**\n * The Babylon Lite plugin this binding drives. Unstable escape hatch\n * (`docs/architecture/00-overview.md` §3).\n *\n * @returns The plugin, or `null` under a headless app, which builds none.\n */\n get lite(): LiteMaterialPlugin | null {\n return this.#state.plugin;\n }\n\n /**\n * The `IGX-0712` failure an undeclared name produces.\n *\n * @param name - The name the caller passed.\n * @param declared - The names the file did declare.\n * @returns The error to throw.\n */\n #unknownBinding(name: string, declared: Iterable<string>): IgnifxError {\n return new IgnifxError(\n CoreErrorCode.unknownShaderBinding,\n `${this.#material} declares no uniform, texture, or storage buffer named ${name}.`,\n {\n context: { material: this.#material, surface: this.name, name },\n hint: `${this.shader.address} declares ${describeNames(declared)}.`,\n },\n );\n }\n}\n\n/** Everything one material's surface shaders share. */\nclass SurfaceShaderAttachment implements SurfaceShaderOwner {\n readonly bindings: SurfaceShaderBinding[] = [];\n\n readonly #app: App | null;\n\n readonly #host: LitePluginHost | null;\n\n readonly #isPbr: boolean;\n\n #isLive = false;\n\n /**\n * Creates the attachment.\n *\n * @param app - The app, or `null` for a pure unit-test attach.\n * @param host - The Lite PBR or Standard material, or `null` under a headless app.\n * @param isPbr - Whether the host is a PBR material, which needs an explicit UBO dirty mark.\n */\n constructor(app: App | null, host: LitePluginHost | null, isPbr: boolean) {\n this.#app = app;\n this.#host = host;\n this.#isPbr = isPbr;\n }\n\n /** Records that Lite has been handed the plugin list, so later changes rebuild. */\n goLive(): void {\n this.#isLive = true;\n }\n\n /** Re-uploads the host material's uniform block. */\n onValueChanged(): void {\n markSurfaceValueChanged(this.#host, this.#isPbr);\n }\n\n /** Rebuilds the host material's renderables, which is what a bind-group or feature change needs. */\n onShapeChanged(): void {\n rebuildSurfaceHost(this.#app, this.#host, this.#isLive);\n }\n}\n\n/** One attachment per material, created on first use so module scope allocates nothing. */\nlet attachments: WeakMap<MaterialAsset, SurfaceShaderAttachment> | null = null;\n\n/**\n * Compiles a material's surface shaders, attaches them to its Babylon Lite material, and returns the\n * handles a game changes their values through.\n *\n * @remarks\n * Replaces whatever was attached before, so calling it twice is a re-attach rather than an addition,\n * and an empty list detaches. Under a headless app — or with `app` `null`, which is how a unit test\n * attaches — every value and texture is held and validated and no Lite plugin is built.\n *\n * The second parameter is the **app**, not the rendering service: a runtime import of `renderer.ts`\n * from a module that `material-asset.ts` imports would close a dependency cycle, because\n * `renderer.ts` builds the default `MaterialAsset`. Everything the attach path needs —\n * `renderer.features`, `isHeadless`, `lite.scene`, `log` — is on the public app.\n *\n * @param material - The PBR material to decorate.\n * @param app - The app, or `null` to compile and validate without touching Babylon Lite.\n * @param surfaces - The shaders to attach, with their values.\n * @returns One binding per shader, in the order given.\n * @throws IgnifxError with code `IGX-0716` when `rendering.features.materialPlugins` is off on a\n * device, `IGX-0708` on a `\"shader\"` host, `IGX-0709` when a file is not a `surface` one, `IGX-0712`\n * when a declared value or texture name is unknown or two shaders share a name, `IGX-0713` on a\n * wrongly shaped value, `IGX-0726` when the material's shaders exceed the sampler budget, and\n * `IGX-0723` when a file declares no hook, declares one this host cannot run, or names a Standard\n * material as its host.\n *\n * @public\n */\nexport function attachSurfaceShaders(\n material: MaterialAsset,\n app: App | null,\n surfaces: readonly SurfaceShaderInit[],\n): readonly SurfaceShaderBinding[] {\n detachSurfaceShaders(material);\n if (surfaces.length === 0) {\n return [];\n }\n const capabilities = assertHostFamily(material);\n const isHeadless = app === null || app.isHeadless;\n assertFeature(material, app, isHeadless, surfaces.length);\n assertPbrHost(material, capabilities);\n const host = resolveSurfaceHost(material, isHeadless);\n const attachment = new SurfaceShaderAttachment(app, host, capabilities.family === \"pbr\");\n const plugins: LiteMaterialPlugin[] = [];\n const names = new Set<string>();\n let samplers = 0;\n for (const init of surfaces) {\n const shader = assertLoadedSurfaceShader(material, init);\n const name = init.name ?? surfaceShaderName(shader.address);\n assertUniqueName(material, name, names);\n samplers += shader.declaration.textures.length;\n if (samplers > MATERIAL_PLUGIN_SAMPLER_BUDGET) {\n throw new IgnifxError(\n CoreErrorCode.surfaceSamplerBudgetExceeded,\n `${material.name} attaches surface shaders declaring ${String(samplers)} samplers; ${String(MATERIAL_PLUGIN_SAMPLER_BUDGET)} fit beside a textured PBR material.`,\n {\n context: { material: material.name, samplers, budget: MATERIAL_PLUGIN_SAMPLER_BUDGET },\n hint: \"Pack the maps into fewer textures — an RGBA control map rather than four masks.\",\n },\n );\n }\n const binding = buildBinding(material, app, capabilities, init, name, shader, attachment);\n attachment.bindings.push(binding.binding);\n const plugin = binding.state.plugin;\n if (plugin !== null) {\n plugins.push(plugin);\n }\n }\n attachSurfacePlugins(host, plugins);\n attachment.goLive();\n // Lite reads `material.plugins` when it builds the pipeline, so a material that is already\n // drawing needs its renderables rebuilt before the plugin's WGSL reaches the screen. Before\n // `app.start()` nothing has been built and the rebuild is a cheap no-op, so it is unconditional.\n attachment.onShapeChanged();\n (attachments ??= new WeakMap<MaterialAsset, SurfaceShaderAttachment>()).set(material, attachment);\n return attachment.bindings;\n}\n\n/**\n * Removes every surface shader from a material, restoring its plain look.\n *\n * @remarks\n * Idempotent, and safe on a material that never had one. It clears Lite's plugin list, which changes\n * the pipeline cache key, so the material's renderables are rebuilt.\n *\n * @param material - The material.\n *\n * @public\n */\nexport function detachSurfaceShaders(material: MaterialAsset): void {\n const existing = attachments?.get(material);\n if (existing === undefined) {\n return;\n }\n attachments?.delete(material);\n detachSurfacePlugins(material);\n existing.onShapeChanged();\n}\n\n/**\n * The surface shaders currently attached to a material, in the order they were attached.\n *\n * @param material - The material.\n * @returns The bindings, or an empty array.\n *\n * @public\n */\nexport function surfaceShaders(material: MaterialAsset): readonly SurfaceShaderBinding[] {\n return attachments?.get(material)?.bindings ?? NO_BINDINGS;\n}\n\n/**\n * One attached surface shader, by the name it answers to.\n *\n * @param material - The material.\n * @param name - The shader's name — the address's basename unless the material renamed it.\n * @returns The binding.\n * @throws IgnifxError with code `IGX-0712` when the material carries no such surface shader.\n *\n * @example\n * ```ts\n * surfaceShaderBinding(rock.value, \"snow\").set(\"amount\", 0.4);\n * ```\n *\n * @public\n */\nexport function surfaceShaderBinding(material: MaterialAsset, name: string): SurfaceShaderBinding {\n for (const binding of surfaceShaders(material)) {\n if (binding.name === name) {\n return binding;\n }\n }\n throw new IgnifxError(\n CoreErrorCode.unknownShaderBinding,\n `${material.name} carries no surface shader named ${name}.`,\n {\n context: { material: material.name, name },\n hint: \"The name is the .surface.wgsl basename unless the material's surfaces entry renamed it.\",\n },\n );\n}\n\n/**\n * The name a surface shader answers to when its material does not rename it: the address's basename\n * with `.surface.wgsl` removed.\n *\n * @param address - The shader's asset address.\n * @returns The name.\n *\n * @example\n * ```ts\n * surfaceShaderName(\"shaders/terrain/snow.surface.wgsl\"); // \"snow\"\n * ```\n *\n * @public\n */\nexport function surfaceShaderName(address: string): string {\n const slash = address.lastIndexOf(\"/\");\n const basename = slash < 0 ? address : address.slice(slash + 1);\n if (basename.endsWith(\".surface.wgsl\")) {\n return basename.slice(0, -\".surface.wgsl\".length);\n }\n return basename.endsWith(\".wgsl\") ? basename.slice(0, -\".wgsl\".length) : basename;\n}\n\n/** What {@link buildBinding} produces. */\ninterface BuiltBinding {\n /** The public handle. */\n readonly binding: SurfaceShaderBinding;\n /** Its live state, which carries the Lite plugin. */\n readonly state: MutablePluginState;\n}\n\n/**\n * Compiles one surface shader and builds its binding and Lite plugin.\n *\n * @param material - The host material.\n * @param app - The app, or `null`.\n * @param capabilities - The host family and what its template exposes.\n * @param init - What the material declared for this shader.\n * @param name - The name the shader answers to.\n * @param shader - The loaded shader asset.\n * @param owner - The attachment.\n * @returns The binding and its state.\n * @throws IgnifxError as `attachSurfaceShaders` documents.\n */\nfunction buildBinding(\n material: MaterialAsset,\n app: App | null,\n capabilities: SurfaceHostCapabilities,\n init: SurfaceShaderInit,\n name: string,\n shader: ShaderAsset,\n owner: SurfaceShaderAttachment,\n): BuiltBinding {\n const compiled = compileSurfaceShader({\n name,\n address: shader.address,\n source: shader.source,\n declaration: shader.declaration,\n host: capabilities,\n });\n const uniforms = new Map<string, ShaderUniformDeclaration>();\n const values = new Map<string, Float32Array>();\n for (const uniform of shader.declaration.uniforms) {\n uniforms.set(uniform.name, uniform);\n values.set(`${compiled.prefix}${uniform.name}`, defaultValueStore(uniform));\n }\n const textureIndex = new Map<string, number>();\n const declarations = shader.declaration.textures;\n for (let index = 0; index < declarations.length; index += 1) {\n textureIndex.set(declarations[index]?.name ?? \"\", index);\n }\n const fallbacks = resolveSurfaceFallbacks(app, declarations);\n const state: MutablePluginState = {\n enabled: init.enabled ?? true,\n values,\n textures: [...fallbacks],\n plugin: null,\n };\n state.plugin = buildSurfacePlugin(app, compiled, init, capabilities, state);\n const binding = new SurfaceShaderBinding({\n name,\n shader,\n priority: init.priority ?? DEFAULT_PRIORITY,\n material: material.name,\n prefix: compiled.prefix,\n uniforms,\n values,\n textureIndex,\n fallbacks,\n state,\n owner,\n });\n applyInitialValues(binding, init);\n return { binding, state };\n}\n\n/**\n * Writes a material's declared value and texture overrides onto a fresh binding.\n *\n * @param binding - The binding.\n * @param init - What the material declared.\n * @throws IgnifxError with code `IGX-0712` or `IGX-0713`.\n */\nfunction applyInitialValues(binding: SurfaceShaderBinding, init: SurfaceShaderInit): void {\n const values = init.values;\n if (values !== undefined) {\n for (const name of Object.keys(values)) {\n const value = values[name];\n if (value !== undefined) {\n binding.set(name, value);\n }\n }\n }\n const textures = init.textures;\n if (textures !== undefined) {\n for (const name of Object.keys(textures)) {\n binding.setTexture(name, textures[name] ?? null);\n }\n }\n}\n\n/**\n * Refuses a surface shader on a material family that cannot host one, and reports what the host's\n * template exposes.\n *\n * @param material - The material.\n * @returns The capabilities.\n * @throws IgnifxError with code `IGX-0708` on a `\"shader\"` material.\n */\nfunction assertHostFamily(material: MaterialAsset): SurfaceHostCapabilities {\n const definition = material.definition;\n if (definition.kind === \"shader\") {\n throw new IgnifxError(\n CoreErrorCode.unsupportedMaterialKind,\n `${material.name} is a shader material, which owns its whole pipeline and cannot host a surface shader.`,\n {\n context: { material: material.name, kind: definition.kind },\n hint: \"Attach surface shaders to a pbr or standard material, or write the effect into the .wgsl itself.\",\n },\n );\n }\n if (definition.kind === \"pbr\") {\n return { family: \"pbr\", hasUv: true, hasNormal: !definition.unlit };\n }\n return {\n family: \"standard\",\n // Standard declares its UV varying only when a texture asks for it (`standard-flags.js`\n // NEEDS_UV); with none, `in.uv` reads (0, 0) rather than failing to compile.\n hasUv: Object.keys(definition.textures).length > 0,\n hasNormal: !definition.unlit,\n };\n}\n\n/**\n * Refuses a surface shader when the project did not opt into Lite's plugin bridges, and warns when\n * it is only a headless app that would have been affected.\n *\n * @param material - The material, for diagnostics.\n * @param app - The app, or `null`.\n * @param isHeadless - Whether there is no device to patch.\n * @param count - How many shaders are being attached, for the message.\n * @throws IgnifxError with code `IGX-0716` on a device.\n */\nfunction assertFeature(material: MaterialAsset, app: App | null, isHeadless: boolean, count: number): void {\n if (app === null || app.renderer.features.materialPlugins) {\n return;\n }\n if (!isHeadless) {\n throw new IgnifxError(\n CoreErrorCode.surfaceShaderFeatureOff,\n `${material.name} carries a surface shader, but rendering.features.materialPlugins is off.`,\n {\n context: { material: material.name, surfaces: count },\n hint: \"Declare materialPlugins in the rendering.features block of createApp() or ignifx.config.ts.\",\n },\n );\n }\n app.log.warn(\n `${CoreErrorCode.surfaceShaderFeatureOff}: {material} carries a surface shader, but ` +\n \"rendering.features.materialPlugins is off, so it would be inert on a device.\",\n material.name,\n );\n}\n\n/**\n * Refuses a surface shader on a **Standard** host, which Babylon Lite 1.27.0 cannot carry one on.\n *\n * @remarks\n * `registerStdPlugins` bakes a per-signature index into every Standard material it finds by walking\n * `scene.meshes` (`lib/material/plugin/std-plugin-bridge.js` 133-155), and ignifx creates a\n * renderer's Lite mesh in the first frame's `PreRender` — after that walk — so a Standard host would\n * silently draw as if it carried nothing. PBR's bridge encodes the signature into the material's\n * feature bits at build time and has no such rule. The compiler can still generate for a Standard\n * host, so the refusal lifts as soon as Lite exposes a way to bake one late.\n *\n * @param material - The material, for diagnostics.\n * @param capabilities - The host family.\n * @throws IgnifxError with code `IGX-0723`.\n */\nfunction assertPbrHost(material: MaterialAsset, capabilities: SurfaceHostCapabilities): void {\n if (capabilities.family === \"pbr\") {\n return;\n }\n throw new IgnifxError(\n CoreErrorCode.surfaceHookMissing,\n `${material.name} is a standard material, and Babylon Lite bakes a standard material's plugins from the meshes already in the scene, so it cannot carry a surface shader.`,\n {\n context: { material: material.name, kind: \"standard\" },\n hint: \"Use a pbr material as the host; surfaces are a pbr-only feature in this release.\",\n },\n );\n}\n\n/**\n * The shader asset one entry names, checked for being a loaded `surface` file.\n *\n * @param material - The host material, for diagnostics.\n * @param init - The entry.\n * @returns The shader asset.\n * @throws IgnifxError with code `IGX-0501` when it is not loaded, or `IGX-0709` when it is not a\n * `// @ignifx surface` file.\n */\nfunction assertLoadedSurfaceShader(material: MaterialAsset, init: SurfaceShaderInit): ShaderAsset {\n const handle = init.shader;\n if (handle.state !== \"loaded\") {\n throw new IgnifxError(CoreErrorCode.assetNotLoaded, `The surface shader ${handle.address} is not loaded.`, {\n context: { asset: handle.address, material: material.name },\n hint: \"await app.assets.loadAsync(address) before building a material from it.\",\n });\n }\n const shader = handle.value;\n if (shader.declaration.kind !== \"surface\") {\n throw new IgnifxError(\n CoreErrorCode.invalidAssetFile,\n `${shader.address} declares @ignifx ${shader.declaration.kind}, not @ignifx surface.`,\n {\n context: {\n file: shader.address,\n format: \"@ignifx surface\",\n material: material.name,\n kind: shader.declaration.kind,\n },\n hint: \"A material's surfaces list takes .surface.wgsl files whose pragma is @ignifx surface.\",\n },\n );\n }\n return shader;\n}\n\n/**\n * Refuses two surface shaders that would answer to the same name — and therefore generate the same\n * WGSL identifiers — on one material.\n *\n * @param material - The host material.\n * @param name - The name this entry resolved to.\n * @param taken - The names already used; the accepted one is added.\n * @throws IgnifxError with code `IGX-0712`.\n */\nfunction assertUniqueName(material: MaterialAsset, name: string, taken: Set<string>): void {\n const sanitized = sanitizeIdentifier(name);\n if (taken.has(sanitized)) {\n throw new IgnifxError(\n CoreErrorCode.unknownShaderBinding,\n `${material.name} attaches two surface shaders that both answer to ${name}.`,\n {\n context: { material: material.name, name },\n hint: \"Name one of them in its surfaces entry; the name prefixes every generated WGSL identifier.\",\n },\n );\n }\n taken.add(sanitized);\n}\n\n/**\n * A uniform's CPU-side store, filled with its declared default and decoded from sRGB when the\n * declaration says it is a colour.\n *\n * @param declaration - The uniform declaration.\n * @returns The store.\n */\nfunction defaultValueStore(declaration: ShaderUniformDeclaration): Float32Array {\n const store = new Float32Array(uniformComponentCount(declaration.type));\n const value = declaration.defaultValue;\n if (typeof value === \"number\") {\n store[0] = value;\n } else {\n store.set(value.slice(0, store.length));\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 store, checking its shape and decoding a colour.\n *\n * @param store - The store.\n * @param declaration - The uniform declaration.\n * @param value - The caller's value.\n * @param material - The host material's name, for diagnostics.\n * @param surface - The surface shader's name, for diagnostics.\n * @throws IgnifxError with code `IGX-0713` when the shape does not match.\n */\nfunction writeSurfaceValue(\n store: Float32Array,\n declaration: ShaderUniformDeclaration,\n value: number | readonly number[] | Float32Array | ColorLike,\n material: string,\n surface: string,\n): void {\n const count = store.length;\n if (typeof value === \"number\") {\n if (count !== 1) {\n throw valueMismatch(declaration, material, surface, `${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 valueMismatch(declaration, material, surface, `${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 valueMismatch(declaration, material, surface, `${String(count)} floats`, `${String(value.length)} floats`);\n }\n store.set(value instanceof Float32Array ? value : Float32Array.from(value));\n if (declaration.color) {\n decodeColourComponents(store);\n }\n}\n\n/**\n * The `IGX-0713` failure a wrongly shaped value produces.\n *\n * @param declaration - The uniform declaration.\n * @param material - The host material's name.\n * @param surface - The surface shader's name.\n * @param expected - What the uniform takes.\n * @param actual - What the caller passed.\n * @returns The error to throw.\n */\nfunction valueMismatch(\n declaration: ShaderUniformDeclaration,\n material: string,\n surface: string,\n expected: string,\n actual: string,\n): IgnifxError {\n return new IgnifxError(\n CoreErrorCode.shaderValueMismatch,\n `${declaration.name} on ${material} expects ${declaration.type} (${expected}), not ${actual}.`,\n {\n context: { name: declaration.name, material, surface, 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\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 * A readable list of declared names, for an error hint.\n *\n * @param names - The names.\n * @returns The list, or a note that there are none.\n */\nfunction describeNames(names: Iterable<string>): string {\n const list = [...names];\n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