@ignifx/core 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/async-pipelines-CI5uT5iZ.js +26 -0
  2. package/dist/async-pipelines-CI5uT5iZ.js.map +1 -0
  3. package/dist/color-DrR6GFTd.js +351 -0
  4. package/dist/color-DrR6GFTd.js.map +1 -0
  5. package/dist/effect-task-CMbuO6Kb.js +205 -0
  6. package/dist/effect-task-CMbuO6Kb.js.map +1 -0
  7. package/dist/environment-C_JfuAjj.js +224 -0
  8. package/dist/environment-C_JfuAjj.js.map +1 -0
  9. package/dist/ignifx-error-R1ma_Lzv.js +544 -0
  10. package/dist/ignifx-error-R1ma_Lzv.js.map +1 -0
  11. package/dist/index.d.ts +3756 -1656
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +6404 -5777
  14. package/dist/index.js.map +1 -1
  15. package/dist/instanced-mesh-instance-Cgx1H87p.js +701 -0
  16. package/dist/instanced-mesh-instance-Cgx1H87p.js.map +1 -0
  17. package/dist/material-plugin-CTaWZXEk.js +485 -0
  18. package/dist/material-plugin-CTaWZXEk.js.map +1 -0
  19. package/dist/math-utils-BcDnL-gi.js +277 -0
  20. package/dist/math-utils-BcDnL-gi.js.map +1 -0
  21. package/dist/mesh-CnK_PX46.js +811 -0
  22. package/dist/mesh-CnK_PX46.js.map +1 -0
  23. package/dist/post-effect-C42XJFmo.js +155 -0
  24. package/dist/post-effect-C42XJFmo.js.map +1 -0
  25. package/dist/post-effect-compiler-DTlkT1si.js +311 -0
  26. package/dist/post-effect-compiler-DTlkT1si.js.map +1 -0
  27. package/dist/shader-declaration-5q__jycG.js +165 -0
  28. package/dist/shader-declaration-5q__jycG.js.map +1 -0
  29. package/dist/shader-material-DssOqsvZ.js +1009 -0
  30. package/dist/shader-material-DssOqsvZ.js.map +1 -0
  31. package/dist/shader-material-Xk7Oc9UG.js +207 -0
  32. package/dist/shader-material-Xk7Oc9UG.js.map +1 -0
  33. package/dist/shader-pragma-CNAK4SIb.js +685 -0
  34. package/dist/shader-pragma-CNAK4SIb.js.map +1 -0
  35. package/dist/surface-shader-C2HtysNN.js +1397 -0
  36. package/dist/surface-shader-C2HtysNN.js.map +1 -0
  37. package/package.json +2 -2
@@ -0,0 +1,1397 @@
1
+ import { t as shaderMaterialsOf } from "./shader-material-DssOqsvZ.js";
2
+ import { o as CoreErrorCode, t as IgnifxError } from "./ignifx-error-R1ma_Lzv.js";
3
+ import { a as defineMaterialPlugin, f as markMaterialDirty, p as rebuildMaterialPipelines, s as uniformComponentCount } from "./material-plugin-CTaWZXEk.js";
4
+ import { t as Color } from "./color-DrR6GFTd.js";
5
+ import { d as SURFACE_HOOK_NAMES, f as SURFACE_UNIFORM_BLOCK } from "./shader-declaration-5q__jycG.js";
6
+ //#region src/lite/gpu/material-plugin.ts
7
+ /** The Lite point names that belong to the vertex stage. */
8
+ const VERTEX_POINTS = Object.freeze([
9
+ "CUSTOM_VERTEX_MAIN_BEGIN",
10
+ "CUSTOM_VERTEX_UPDATE_WORLDPOS",
11
+ "CUSTOM_VERTEX_MAIN_END"
12
+ ]);
13
+ /**
14
+ * Whether a Lite injection point belongs to the vertex stage.
15
+ *
16
+ * @param point - The point name.
17
+ * @returns `true` for the three vertex points.
18
+ *
19
+ * @internal
20
+ */
21
+ function isVertexPluginPoint(point) {
22
+ return VERTEX_POINTS.includes(point);
23
+ }
24
+ /**
25
+ * Builds the Babylon Lite plugin object for one attached surface shader or raw plugin.
26
+ *
27
+ * @remarks
28
+ * The returned object closes over `state`, so the render layer changes a value by writing into
29
+ * `state.values` and then marking the host dirty; the plugin object itself never changes, which is
30
+ * what keeps Lite's pipeline cache key stable.
31
+ *
32
+ * `getCustomCode` returns `null` for a stage with no code and for every stage while the plugin is
33
+ * disabled. Lite already treats a disabled plugin as contributing nothing (`isEnabled`), and the
34
+ * `null` keeps the signature short.
35
+ *
36
+ * @param input - What is fixed about the plugin.
37
+ * @param state - The live values, textures, and enabled flag.
38
+ * @returns The Lite plugin, ready for {@link attachLiteMaterialPlugins}.
39
+ *
40
+ * @internal
41
+ */
42
+ function createLiteMaterialPlugin(input, state) {
43
+ const ubo = input.fields.map((field) => ({
44
+ name: field.name,
45
+ type: field.type
46
+ }));
47
+ const samplers = input.samplers.map((sampler) => sampler.array ? {
48
+ texture: sampler.texture,
49
+ sampler: sampler.sampler,
50
+ textureType: "texture_2d_array<f32>"
51
+ } : {
52
+ texture: sampler.texture,
53
+ sampler: sampler.sampler
54
+ });
55
+ const uniforms = { ubo };
56
+ let integerView = null;
57
+ let integerBuffer = null;
58
+ return {
59
+ name: input.name,
60
+ priority: input.priority,
61
+ get isEnabled() {
62
+ return state.enabled;
63
+ },
64
+ dynamic: input.isStandardHost,
65
+ getCustomCode(stage) {
66
+ const code = stage === "vertex" ? input.code.vertex : input.code.fragment;
67
+ return Object.keys(code).length === 0 ? null : code;
68
+ },
69
+ getUniforms() {
70
+ return uniforms;
71
+ },
72
+ getSamplers() {
73
+ return samplers;
74
+ },
75
+ writeUbo(data, offsets) {
76
+ for (const field of input.fields) {
77
+ const byteOffset = offsets.get(field.name);
78
+ const values = state.values.get(field.name);
79
+ if (byteOffset === void 0 || values === void 0) continue;
80
+ const index = byteOffset / 4;
81
+ if (field.type === "u32" || field.type === "i32") {
82
+ if (integerBuffer !== data.buffer) {
83
+ integerBuffer = data.buffer;
84
+ integerView = new Int32Array(data.buffer, data.byteOffset, data.length);
85
+ }
86
+ const view = integerView;
87
+ if (view !== null) view[index] = values[0] ?? 0;
88
+ continue;
89
+ }
90
+ for (let component = 0; component < field.components; component += 1) data[index + component] = values[component] ?? 0;
91
+ }
92
+ },
93
+ bindTextures(out) {
94
+ for (const texture of state.textures) if (texture !== null) out.push({ texture });
95
+ },
96
+ getActiveTextures(out) {
97
+ for (const texture of state.textures) if (texture !== null) out.push(texture);
98
+ }
99
+ };
100
+ }
101
+ /**
102
+ * Replaces a material's plugin list.
103
+ *
104
+ * @remarks
105
+ * `material.plugins = [plugin]` is the documented attach path (`index.d.ts` 8175, 12253). The list
106
+ * is read when the pipeline is built, so a change to it needs a rebuild of the material's
107
+ * renderables — `rebuildMaterialPipelines` in `src/lite/material.ts` — before it shows up.
108
+ *
109
+ * @param material - The PBR or Standard host.
110
+ * @param plugins - The plugins, in any order; Lite sorts them by `priority`.
111
+ *
112
+ * @internal
113
+ */
114
+ function attachLiteMaterialPlugins(material, plugins) {
115
+ material.plugins = [...plugins];
116
+ }
117
+ /**
118
+ * Clears a material's plugin list.
119
+ *
120
+ * @param material - The PBR or Standard host.
121
+ *
122
+ * @internal
123
+ */
124
+ function detachLiteMaterialPlugins(material) {
125
+ material.plugins = [];
126
+ }
127
+ //#endregion
128
+ //#region src/render/gpu/surface-shader-host.ts
129
+ /**
130
+ * The device-only half of surface shaders: the Lite plugin a compiled `.surface.wgsl` becomes, and
131
+ * the host-material writes that follow it (`docs/plan/2026-09-terrain-particles-shaders.md` §3.2).
132
+ *
133
+ * Each entry point takes the app or the host as a nullable and returns early when it is `null`, so
134
+ * `../surface-shader.ts` keeps no headless branch of its own.
135
+ */
136
+ /**
137
+ * The host material a surface shader attaches to, when there is a device.
138
+ *
139
+ * @remarks
140
+ * `assertHostFamily` refused the shader family, so the Lite material is a PBR or Standard one and
141
+ * both carry `plugins` (`index.d.ts` 8175, 12253).
142
+ *
143
+ * @param material - The material asset.
144
+ * @param isHeadless - Whether the app has a device.
145
+ * @returns The Lite material, or `null`.
146
+ *
147
+ * @internal
148
+ */
149
+ function resolveSurfaceHost(material, isHeadless) {
150
+ return isHeadless ? null : material.lite.material;
151
+ }
152
+ /**
153
+ * Re-uploads the host material's uniform block after a value write.
154
+ *
155
+ * @remarks
156
+ * Lite ignores `dynamic` for a PBR host and re-reads the plugin slice only after this (spike S0.2);
157
+ * a Standard host re-uploads every frame because the plugin sets `dynamic`.
158
+ *
159
+ * @param host - The host material, or `null`.
160
+ * @param isPbr - Whether the host is a PBR material.
161
+ *
162
+ * @internal
163
+ */
164
+ function markSurfaceValueChanged(host, isPbr) {
165
+ if (host === null || !isPbr) return;
166
+ markMaterialDirty(host);
167
+ }
168
+ /**
169
+ * Rebuilds the host material's renderables, which a bind-group or feature change needs.
170
+ *
171
+ * @param app - The app, or `null` when the attachment was built without one.
172
+ * @param host - The host material, or `null`.
173
+ * @param isLive - Whether Lite has already been handed the plugin list.
174
+ *
175
+ * @internal
176
+ */
177
+ function rebuildSurfaceHost(app, host, isLive) {
178
+ if (!isLive || app === null || host === null || app.isHeadless) return;
179
+ rebuildMaterialPipelines(app.lite.scene, host);
180
+ }
181
+ /**
182
+ * Hands Lite the plugins a material's surface shaders compiled to, when there are any.
183
+ *
184
+ * @param host - The host material, or `null`.
185
+ * @param plugins - The plugins, in attach order.
186
+ *
187
+ * @internal
188
+ */
189
+ function attachSurfacePlugins(host, plugins) {
190
+ if (host === null || plugins.length === 0) return;
191
+ attachLiteMaterialPlugins(host, plugins);
192
+ }
193
+ /**
194
+ * Takes a material's surface-shader plugins off its Lite material.
195
+ *
196
+ * @remarks
197
+ * A `"shader"` material never hosts one, and its Lite object carries no `plugins` field to clear.
198
+ *
199
+ * @param material - The material asset.
200
+ *
201
+ * @internal
202
+ */
203
+ function detachSurfacePlugins(material) {
204
+ if (material.definition.kind === "shader") return;
205
+ detachLiteMaterialPlugins(material.lite.material);
206
+ }
207
+ /**
208
+ * The 1x1 fallback each declared sampler falls back to, or nulls under a headless app.
209
+ *
210
+ * @param app - The app, or `null`.
211
+ * @param declarations - The file's declared samplers, in declaration order.
212
+ * @returns One entry per declaration.
213
+ *
214
+ * @internal
215
+ */
216
+ function resolveSurfaceFallbacks(app, declarations) {
217
+ if (app === null || app.isHeadless) return declarations.map(() => null);
218
+ const registry = shaderMaterialsOf(app);
219
+ return declarations.map((declaration) => registry.fallbackTexture(declaration));
220
+ }
221
+ /**
222
+ * Builds the Lite plugin for one compiled surface shader, when there is a device.
223
+ *
224
+ * @param app - The app, or `null`.
225
+ * @param compiled - The compiled shader.
226
+ * @param init - What the material declared, for the priority.
227
+ * @param capabilities - The host family, which decides how a value reaches the GPU.
228
+ * @param state - The live state the plugin reads.
229
+ * @returns The plugin, or `null` under a headless app.
230
+ *
231
+ * @internal
232
+ */
233
+ function buildSurfacePlugin(app, compiled, init, capabilities, state) {
234
+ if (app === null || app.isHeadless) return null;
235
+ return buildLitePlugin(compiled, init, capabilities, state);
236
+ }
237
+ /**
238
+ * Builds the Lite plugin for one compiled surface shader.
239
+ *
240
+ * @param compiled - The compiled shader.
241
+ * @param init - What the material declared, for the priority.
242
+ * @param capabilities - The host family, which decides how a value reaches the GPU.
243
+ * @param state - The live state the plugin reads.
244
+ * @returns The plugin.
245
+ */
246
+ function buildLitePlugin(compiled, init, capabilities, state) {
247
+ const fragment = {};
248
+ const vertex = {};
249
+ for (const point of Object.keys(compiled.plugin.code)) {
250
+ const wgsl = compiled.plugin.code[point];
251
+ if (wgsl === void 0) continue;
252
+ if (isVertexPluginPoint(point)) vertex[point] = wgsl;
253
+ else fragment[point] = wgsl;
254
+ }
255
+ const code = {
256
+ fragment,
257
+ vertex
258
+ };
259
+ return createLiteMaterialPlugin({
260
+ name: compiled.plugin.name,
261
+ priority: init.priority ?? compiled.plugin.priority,
262
+ fields: compiled.plugin.uniforms.map((uniform) => ({
263
+ name: uniform.name,
264
+ type: uniform.type,
265
+ components: uniformComponentCount(uniform.type)
266
+ })),
267
+ samplers: compiled.plugin.textures.map((texture) => ({
268
+ texture: texture.name,
269
+ sampler: `${texture.name}Sampler`,
270
+ array: texture.array
271
+ })),
272
+ code,
273
+ isStandardHost: capabilities.family === "standard"
274
+ }, state);
275
+ }
276
+ //#endregion
277
+ //#region src/render/surface-shader-compiler.ts
278
+ /** The members a `displace` hook may read off its parameter. */
279
+ const DISPLACE_MEMBERS = Object.freeze([
280
+ "position",
281
+ "normal",
282
+ "uv",
283
+ "color",
284
+ "world"
285
+ ]);
286
+ /** Matches the start of a top-level hook declaration. */
287
+ const HOOK_START = /\bfn\s+(displace|surface|composite)\s*\(/g;
288
+ /** Matches `surfaceUniforms.<identifier>`. */
289
+ const UNIFORM_REFERENCE = /\bsurfaceUniforms\s*\.\s*([A-Za-z_][A-Za-z0-9_]*)/g;
290
+ /** Matches a `return <expression>;` statement. */
291
+ const RETURN_STATEMENT = /\breturn\b([^;]*);/g;
292
+ /** Matches any WGSL control-flow construct a `break` could bind to. */
293
+ const BREAKING_CONSTRUCT = /\b(loop|for|while|switch)\b/;
294
+ /** Matches the start of any top-level function declaration, capturing its name. */
295
+ const FUNCTION_START = /\bfn\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(/g;
296
+ /**
297
+ * Finds the hooks a `.surface.wgsl` file declares.
298
+ *
299
+ * @remarks
300
+ * A hand-written brace scan rather than a WGSL parser: the file has already been validated by the
301
+ * Vite plugin at build time, and all this needs is the extent of three top-level functions. It
302
+ * looks for `fn displace|surface|composite (` anywhere in the file and then matches the parameter
303
+ * parentheses and the body braces, so a hook may be written in any order and with any formatting.
304
+ *
305
+ * @param source - The whole file.
306
+ * @param address - The asset address, for the error message.
307
+ * @returns The hooks found and the rest of the file.
308
+ * @throws IgnifxError with code `IGX-0723` when the file declares none of the three, or `IGX-0719`
309
+ * when a hook's braces or parentheses do not close.
310
+ *
311
+ * @internal
312
+ */
313
+ function parseSurfaceHooks(source, address) {
314
+ const found = /* @__PURE__ */ new Map();
315
+ const cuts = [];
316
+ HOOK_START.lastIndex = 0;
317
+ let match = HOOK_START.exec(source);
318
+ while (match !== null) {
319
+ const name = match[1];
320
+ const openParen = match.index + match[0].length - 1;
321
+ const closeParen = matchDelimiter(source, openParen, "(", ")");
322
+ const openBrace = source.indexOf("{", closeParen);
323
+ if (closeParen < 0 || openBrace < 0) throw new IgnifxError(CoreErrorCode.invalidShaderPragma, `${address}: the ${name} hook does not close.`, {
324
+ context: {
325
+ asset: address,
326
+ hook: name ?? ""
327
+ },
328
+ hint: "Check the parentheses and braces of the hook declaration."
329
+ });
330
+ const closeBrace = matchDelimiter(source, openBrace, "{", "}");
331
+ if (closeBrace < 0) throw new IgnifxError(CoreErrorCode.invalidShaderPragma, `${address}: the ${name} hook's body does not close.`, {
332
+ context: {
333
+ asset: address,
334
+ hook: name ?? ""
335
+ },
336
+ hint: "Add the missing closing brace."
337
+ });
338
+ if (isSurfaceHookName(name)) {
339
+ found.set(name, {
340
+ name,
341
+ parameters: parseParameterNames(source.slice(openParen + 1, closeParen)),
342
+ body: source.slice(openBrace + 1, closeBrace),
343
+ start: match.index,
344
+ end: closeBrace + 1
345
+ });
346
+ cuts.push({
347
+ start: match.index,
348
+ end: closeBrace + 1
349
+ });
350
+ }
351
+ HOOK_START.lastIndex = closeBrace + 1;
352
+ match = HOOK_START.exec(source);
353
+ }
354
+ if (found.size === 0) throw new IgnifxError(CoreErrorCode.surfaceHookMissing, `${address} declares a surface shader with none of the hooks displace, surface, or composite.`, {
355
+ context: { asset: address },
356
+ hint: "Add fn surface(in: SurfaceInput, s: ptr<function, Surface>), fn composite(in, color), or fn displace(in)."
357
+ });
358
+ return {
359
+ displace: found.get("displace") ?? null,
360
+ surface: found.get("surface") ?? null,
361
+ composite: found.get("composite") ?? null,
362
+ rest: cutRanges(source, cuts)
363
+ };
364
+ }
365
+ /**
366
+ * Compiles a `.surface.wgsl` file into one Babylon Lite material plugin.
367
+ *
368
+ * @remarks
369
+ * Deterministic and device-free, so it is fully testable in Node: the result is the plain
370
+ * {@link MaterialPluginDefinition} the adapter turns into a Lite object.
371
+ *
372
+ * @param input - The shader, its declaration, and the host family.
373
+ * @returns The plugin definition, with the generated WGSL in `code`, and its name prefix.
374
+ * @throws IgnifxError with code `IGX-0723` when the file declares no hook, or a hook the host family
375
+ * has no slot for, or a `displace` that reads a uniform or a texture; `IGX-0712` when a declared
376
+ * name is not usable as a plugin binding; `IGX-0719` when a hook is malformed.
377
+ *
378
+ * @example
379
+ * ```ts
380
+ * const compiled = compileSurfaceShader({
381
+ * name: "snow",
382
+ * address: "shaders/snow.surface.wgsl",
383
+ * source,
384
+ * declaration,
385
+ * host: { family: "pbr", hasUv: true, hasNormal: true },
386
+ * });
387
+ * compiled.plugin.code.CUSTOM_FRAGMENT_UPDATE_ALPHA; // builds SurfaceInput and calls snow_surface
388
+ * ```
389
+ *
390
+ * @internal
391
+ */
392
+ function compileSurfaceShader(input) {
393
+ const hooks = parseSurfaceHooks(input.source, input.address);
394
+ const prefix = `${sanitizeIdentifier(input.name)}_`;
395
+ const isStandard = input.host.family === "standard";
396
+ if (isStandard && hooks.composite !== null) throw new IgnifxError(CoreErrorCode.surfaceHookMissing, `${input.address} declares the composite hook, which a standard material has no slot for.`, {
397
+ context: {
398
+ asset: input.address,
399
+ hook: "composite",
400
+ family: input.host.family
401
+ },
402
+ hint: "Attach the surface shader to a pbr material, or move the effect into the surface hook."
403
+ });
404
+ const rewrite = buildRewriter(prefix, input.declaration, isStandard);
405
+ const code = {};
406
+ const definitions = buildDefinitions(prefix, hooks, rewrite);
407
+ if (definitions !== "") code.CUSTOM_FRAGMENT_DEFINITIONS = definitions;
408
+ if (hooks.surface !== null || hooks.composite !== null) {
409
+ code.CUSTOM_FRAGMENT_UPDATE_ALPHA = buildUpdateAlpha(prefix, hooks, input.host);
410
+ if (hooks.surface !== null && !isStandard) code.CUSTOM_FRAGMENT_UPDATE_DIFFUSE = `if(any(${prefix}normal!=${prefix}in.geometricNormal)){N=normalize(${prefix}normal);}`;
411
+ if (!isStandard) code.CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION = buildComposite(prefix, hooks);
412
+ }
413
+ if (hooks.displace !== null) code.CUSTOM_VERTEX_UPDATE_WORLDPOS = buildDisplace(prefix, hooks.displace, input);
414
+ return {
415
+ plugin: defineMaterialPlugin({
416
+ name: input.name,
417
+ uniforms: input.declaration.uniforms.map((uniform) => ({
418
+ ...uniform,
419
+ name: `${prefix}${uniform.name}`
420
+ })),
421
+ textures: input.declaration.textures.map((texture) => ({
422
+ ...texture,
423
+ name: `${prefix}${texture.name}`
424
+ })),
425
+ code
426
+ }),
427
+ prefix,
428
+ hooks: {
429
+ displace: hooks.displace !== null,
430
+ surface: hooks.surface !== null,
431
+ composite: hooks.composite !== null
432
+ }
433
+ };
434
+ }
435
+ /**
436
+ * The fragment helper block: the generated structs and everything the file declared, hooks included,
437
+ * with the two fragment hooks given generated signatures.
438
+ *
439
+ * @param prefix - The per-shader identifier prefix.
440
+ * @param hooks - The parsed hooks.
441
+ * @param rewrite - The identifier rewriter.
442
+ * @returns The WGSL, or `""` when the file provides no fragment hook.
443
+ */
444
+ function buildDefinitions(prefix, hooks, rewrite) {
445
+ if (hooks.surface === null && hooks.composite === null) return "";
446
+ const parts = [
447
+ `struct ${prefix}SurfaceInput{uv:vec2<f32>,worldPosition:vec3<f32>,geometricNormal:vec3<f32>,viewDirection:vec3<f32>,color:vec4<f32>,}`,
448
+ `struct ${prefix}Surface{baseColor:vec3<f32>,alpha:f32,emissive:vec3<f32>,normal:vec3<f32>,roughness:f32,metallic:f32,}`,
449
+ rewrite(hooks.rest)
450
+ ];
451
+ const surface = hooks.surface;
452
+ if (surface !== null) {
453
+ const input = surface.parameters[0] ?? "in";
454
+ const state = surface.parameters[1] ?? "s";
455
+ parts.push(`fn ${prefix}surface(${input}:${prefix}SurfaceInput,${state}:ptr<function,${prefix}Surface>){${rewrite(surface.body)}}`);
456
+ }
457
+ const composite = hooks.composite;
458
+ if (composite !== null) {
459
+ const input = composite.parameters[0] ?? "in";
460
+ const color = composite.parameters[1] ?? "color";
461
+ parts.push(`fn ${prefix}composite(${input}:${prefix}SurfaceInput,${color}:vec3<f32>)->vec3<f32>{${rewrite(composite.body)}}`);
462
+ }
463
+ return parts.join("\n");
464
+ }
465
+ /**
466
+ * The `CUSTOM_FRAGMENT_UPDATE_ALPHA` block: build `SurfaceInput`, call the hook, write back what the
467
+ * template lets us write back, and stash the rest for the later slots.
468
+ *
469
+ * @remarks
470
+ * Deliberately **not** wrapped in braces: the variables it declares are read by the
471
+ * `UPDATE_DIFFUSE` and `BEFORE_FINALCOLORCOMPOSITION` blocks, which Lite injects into the same
472
+ * function scope further down. Every name is prefixed, so two surface shaders on one material
473
+ * declare two sets rather than colliding.
474
+ *
475
+ * @param prefix - The per-shader identifier prefix.
476
+ * @param hooks - The parsed hooks.
477
+ * @param host - The host family and its capabilities.
478
+ * @returns The WGSL statements.
479
+ */
480
+ function buildUpdateAlpha(prefix, hooks, host) {
481
+ const isStandard = host.family === "standard";
482
+ const worldPosition = isStandard ? "input.vp" : "input.worldPos";
483
+ const geometricNormal = isStandard ? "normalize(input.vn)" : "normalize(input.worldNormal)";
484
+ const uv = host.hasUv ? isStandard ? "input.vu" : "input.uv" : "vec2<f32>(0.0)";
485
+ const emissive = isStandard ? "emissiveContrib" : "emissive";
486
+ const lines = [
487
+ `var ${prefix}in:${prefix}SurfaceInput;`,
488
+ `${prefix}in.uv=${uv};`,
489
+ `${prefix}in.worldPosition=${worldPosition};`,
490
+ `${prefix}in.geometricNormal=${geometricNormal};`,
491
+ `${prefix}in.viewDirection=normalize(scene.vEyePosition.xyz-${worldPosition});`,
492
+ `${prefix}in.color=vec4<f32>(1.0);`,
493
+ `var ${prefix}emissiveDelta=vec3<f32>(0.0);`,
494
+ `var ${prefix}composited=false;`
495
+ ];
496
+ if (hooks.surface !== null) {
497
+ lines.push(`var ${prefix}s:${prefix}Surface;`, `${prefix}s.baseColor=baseColor;`, `${prefix}s.alpha=alpha;`, `${prefix}s.emissive=${emissive};`, `${prefix}s.normal=${prefix}in.geometricNormal;`, isStandard ? `${prefix}s.roughness=1.0;` : `${prefix}s.roughness=roughness;`, isStandard ? `${prefix}s.metallic=0.0;` : `${prefix}s.metallic=metallic;`, `${prefix}surface(${prefix}in,&${prefix}s);`, `baseColor=${prefix}s.baseColor;`, `alpha=${prefix}s.alpha;`, `var ${prefix}normal=${prefix}s.normal;`);
498
+ if (isStandard) {
499
+ lines.push(`${emissive}=${prefix}s.emissive;`);
500
+ if (host.hasNormal) lines.push(`if(any(${prefix}normal!=${prefix}in.geometricNormal)){normalW=normalize(${prefix}normal);}`);
501
+ } else lines.push(`${prefix}emissiveDelta=${prefix}s.emissive-${emissive};`);
502
+ }
503
+ return lines.join("\n");
504
+ }
505
+ /**
506
+ * The `CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION` block: the emissive delta and the `composite`
507
+ * hook, guarded because Lite injects this point twice.
508
+ *
509
+ * @param prefix - The per-shader identifier prefix.
510
+ * @param hooks - The parsed hooks.
511
+ * @returns The WGSL statements.
512
+ */
513
+ function buildComposite(prefix, hooks) {
514
+ const inner = [`${prefix}composited=true;`, `color=color+${prefix}emissiveDelta;`];
515
+ if (hooks.composite !== null) inner.push(`color=${prefix}composite(${prefix}in,color);`);
516
+ return `if(!${prefix}composited){${inner.join("")}}`;
517
+ }
518
+ /**
519
+ * The `CUSTOM_VERTEX_UPDATE_WORLDPOS` block: the `displace` body, inlined.
520
+ *
521
+ * @remarks
522
+ * Inlined rather than called, because Lite gives a plugin no way to declare a function in the vertex
523
+ * module (`buildPluginFragment` fills `_helperFunctions`, which the composer routes to the fragment
524
+ * template alone). The body is wrapped in a `loop` whose `return` statements are rewritten to
525
+ * `break`, which is what lets an author write ordinary early-returning WGSL: a value-returning
526
+ * function has to return on every path, so the loop always terminates on its first iteration.
527
+ *
528
+ * @param prefix - The per-shader identifier prefix.
529
+ * @param hook - The parsed `displace` hook.
530
+ * @param input - The compile input, for the declaration and the error messages.
531
+ * @returns The WGSL statements.
532
+ * @throws IgnifxError with code `IGX-0723` when the body reads a uniform, a texture, or a member
533
+ * that the vertex stage cannot supply.
534
+ */
535
+ function buildDisplace(prefix, hook, input) {
536
+ assertVertexSafe(hook, input);
537
+ const parameter = hook.parameters[0] ?? "in";
538
+ const uv = input.host.hasUv ? "uv" : "vec2<f32>(0.0)";
539
+ let body = hook.body;
540
+ body = body.replaceAll(new RegExp(`\\b${escapeForRegExp(parameter)}\\s*\\.\\s*position\\b`, "g"), "position");
541
+ body = body.replaceAll(new RegExp(`\\b${escapeForRegExp(parameter)}\\s*\\.\\s*normal\\b`, "g"), "normal");
542
+ body = body.replaceAll(new RegExp(`\\b${escapeForRegExp(parameter)}\\s*\\.\\s*uv\\b`, "g"), uv);
543
+ body = body.replaceAll(new RegExp(`\\b${escapeForRegExp(parameter)}\\s*\\.\\s*color\\b`, "g"), "vec4<f32>(1.0)");
544
+ body = body.replaceAll(new RegExp(`\\b${escapeForRegExp(parameter)}\\s*\\.\\s*world\\b`, "g"), "finalWorld");
545
+ body = body.replaceAll(RETURN_STATEMENT, (_whole, expression) => {
546
+ return `{${prefix}offset=${expression.trim()};break;}`;
547
+ });
548
+ return [
549
+ `{var ${prefix}offset=vec3<f32>(0.0);`,
550
+ `loop{${body}}`,
551
+ `finalWorld[3].x+=${prefix}offset.x;`,
552
+ `finalWorld[3].y+=${prefix}offset.y;`,
553
+ `finalWorld[3].z+=${prefix}offset.z;}`
554
+ ].join("\n");
555
+ }
556
+ /**
557
+ * Refuses a `displace` body the vertex stage cannot compile.
558
+ *
559
+ * @param hook - The parsed hook.
560
+ * @param input - The compile input.
561
+ * @throws IgnifxError with code `IGX-0723`.
562
+ */
563
+ function assertVertexSafe(hook, input) {
564
+ const address = input.address;
565
+ if (hook.body.includes("surfaceUniforms")) throw new IgnifxError(CoreErrorCode.surfaceHookMissing, `${address}: the displace hook reads ${SURFACE_UNIFORM_BLOCK}, which Babylon Lite declares in the fragment stage only.`, {
566
+ context: {
567
+ asset: address,
568
+ hook: "displace"
569
+ },
570
+ hint: "Displace by geometry alone on Lite 1.27.0; a time-driven offset needs a full shader material."
571
+ });
572
+ for (const texture of input.declaration.textures) if (new RegExp(`\\b${escapeForRegExp(texture.name)}\\b`).test(hook.body)) throw new IgnifxError(CoreErrorCode.surfaceHookMissing, `${address}: the displace hook samples ${texture.name}, and Babylon Lite's plugin samplers are fragment-stage only.`, {
573
+ context: {
574
+ asset: address,
575
+ hook: "displace",
576
+ name: texture.name
577
+ },
578
+ hint: "Move the texture read into the surface hook, or use a full shader material."
579
+ });
580
+ if (BREAKING_CONSTRUCT.test(hook.body)) throw new IgnifxError(CoreErrorCode.surfaceHookMissing, `${address}: the displace hook uses a loop or switch, which this build cannot inline into Babylon Lite's vertex entry point.`, {
581
+ context: {
582
+ asset: address,
583
+ hook: "displace"
584
+ },
585
+ hint: "Write the displacement as straight-line code, or use a full shader material."
586
+ });
587
+ for (const helper of fileFunctions(input.source)) if (new RegExp(`\\b${escapeForRegExp(helper)}\\s*\\(`).test(hook.body)) throw new IgnifxError(CoreErrorCode.surfaceHookMissing, `${address}: the displace hook calls ${helper}, and Babylon Lite gives a plugin no vertex-stage helper functions.`, {
588
+ context: {
589
+ asset: address,
590
+ hook: "displace",
591
+ name: helper
592
+ },
593
+ hint: "Inline the helper into the displace body, or use a full shader material."
594
+ });
595
+ const parameter = hook.parameters[0] ?? "in";
596
+ const members = new RegExp(`\\b${escapeForRegExp(parameter)}\\s*\\.\\s*([A-Za-z_][A-Za-z0-9_]*)`, "g");
597
+ let match = members.exec(hook.body);
598
+ while (match !== null) {
599
+ const member = match[1] ?? "";
600
+ if (!DISPLACE_MEMBERS.includes(member)) throw new IgnifxError(CoreErrorCode.surfaceHookMissing, `${address}: the displace hook reads ${parameter}.${member}, which DisplaceInput does not carry.`, {
601
+ context: {
602
+ asset: address,
603
+ hook: "displace",
604
+ name: member
605
+ },
606
+ hint: `DisplaceInput carries ${DISPLACE_MEMBERS.join(", ")}.`
607
+ });
608
+ match = members.exec(hook.body);
609
+ }
610
+ }
611
+ /**
612
+ * The names of every function a file declares that is not one of the three hooks.
613
+ *
614
+ * @param source - The whole `.surface.wgsl` file.
615
+ * @returns The helper names, in declaration order.
616
+ */
617
+ function fileFunctions(source) {
618
+ const names = [];
619
+ FUNCTION_START.lastIndex = 0;
620
+ let match = FUNCTION_START.exec(source);
621
+ while (match !== null) {
622
+ const name = match[1] ?? "";
623
+ if (!SURFACE_HOOK_NAMES.includes(name)) names.push(name);
624
+ match = FUNCTION_START.exec(source);
625
+ }
626
+ return names;
627
+ }
628
+ /**
629
+ * Builds the function that rewrites the author's references to the names the host material actually
630
+ * declares.
631
+ *
632
+ * @param prefix - The per-shader identifier prefix.
633
+ * @param declaration - What the file declared, for its texture names.
634
+ * @param isStandard - Whether the host is a Standard material, which reads its plugin uniforms from
635
+ * `pluginUbo` rather than from the PBR material block (`plugin-bridge-shared.js` 99).
636
+ * @returns The rewriter.
637
+ */
638
+ function buildRewriter(prefix, declaration, isStandard) {
639
+ const block = isStandard ? "pluginUbo" : "material";
640
+ const samplers = [];
641
+ for (const texture of declaration.textures) samplers.push(`${texture.name}Sampler`, texture.name);
642
+ samplers.sort((left, right) => right.length - left.length);
643
+ const pattern = samplers.length === 0 ? null : new RegExp(`\\b(${samplers.map(escapeForRegExp).join("|")})\\b`, "g");
644
+ return (code) => {
645
+ const withUniforms = code.replaceAll(UNIFORM_REFERENCE, (_whole, name) => {
646
+ return `${block}.${prefix}${name}`;
647
+ });
648
+ return pattern === null ? withUniforms : withUniforms.replaceAll(pattern, (_whole, name) => `${prefix}${name}`);
649
+ };
650
+ }
651
+ /**
652
+ * The index of the delimiter that closes the one at `open`.
653
+ *
654
+ * @param source - The text.
655
+ * @param open - The index of the opening delimiter.
656
+ * @param openChar - The opening delimiter.
657
+ * @param closeChar - The closing delimiter.
658
+ * @returns The closing index, or `-1` when it never closes.
659
+ */
660
+ function matchDelimiter(source, open, openChar, closeChar) {
661
+ let depth = 0;
662
+ for (let index = open; index < source.length; index += 1) {
663
+ const char = source[index];
664
+ if (char === openChar) depth += 1;
665
+ else if (char === closeChar) {
666
+ depth -= 1;
667
+ if (depth === 0) return index;
668
+ }
669
+ }
670
+ return -1;
671
+ }
672
+ /**
673
+ * The parameter identifiers of a WGSL parameter list.
674
+ *
675
+ * @param list - The text between the parentheses.
676
+ * @returns The names, in order.
677
+ */
678
+ function parseParameterNames(list) {
679
+ const names = [];
680
+ let depth = 0;
681
+ let start = 0;
682
+ for (let index = 0; index <= list.length; index += 1) {
683
+ const char = list[index];
684
+ if (char === "<" || char === "(") depth += 1;
685
+ else if (char === ">" || char === ")") depth -= 1;
686
+ else if (char === "," && depth === 0 || index === list.length) {
687
+ const parameter = list.slice(start, index).trim();
688
+ const colon = parameter.indexOf(":");
689
+ const name = (colon < 0 ? parameter : parameter.slice(0, colon)).trim();
690
+ if (name !== "") names.push(name);
691
+ start = index + 1;
692
+ }
693
+ }
694
+ return names;
695
+ }
696
+ /**
697
+ * The text with the given ranges removed.
698
+ *
699
+ * @param source - The text.
700
+ * @param ranges - The ranges to cut, in ascending order.
701
+ * @returns What is left.
702
+ */
703
+ function cutRanges(source, ranges) {
704
+ let result = "";
705
+ let cursor = 0;
706
+ for (const range of ranges) {
707
+ result += source.slice(cursor, range.start);
708
+ cursor = range.end;
709
+ }
710
+ return result + source.slice(cursor);
711
+ }
712
+ /**
713
+ * Whether a captured name is one of the three hooks.
714
+ *
715
+ * @param value - The candidate.
716
+ * @returns `true` when it is.
717
+ */
718
+ function isSurfaceHookName(value) {
719
+ return value === "displace" || value === "surface" || value === "composite";
720
+ }
721
+ /**
722
+ * Turns a shader name into a WGSL identifier prefix.
723
+ *
724
+ * @param name - The shader's name on the material.
725
+ * @returns The sanitized name; a leading digit is prefixed with an underscore.
726
+ *
727
+ * @internal
728
+ */
729
+ function sanitizeIdentifier(name) {
730
+ const replaced = name.replaceAll(/[^A-Za-z0-9_]/g, "_");
731
+ return /^[0-9]/.test(replaced) ? `_${replaced}` : replaced;
732
+ }
733
+ /**
734
+ * Escapes a literal for use inside a regular expression.
735
+ *
736
+ * @param value - The literal.
737
+ * @returns The escaped form.
738
+ */
739
+ function escapeForRegExp(value) {
740
+ return value.replaceAll(/[.*+?^${}()|[\]\\]/g, "\\$&");
741
+ }
742
+ //#endregion
743
+ //#region src/render/surface-shader.ts
744
+ /** Babylon Lite's own default plugin priority; the surface shaders of one material sort by it. */
745
+ const DEFAULT_PRIORITY = 500;
746
+ /**
747
+ * One surface shader attached to one material: the handle a game holds to change its values.
748
+ *
749
+ * @remarks
750
+ * A material's bindings live as long as its attachment; reach them with `material.surfaces` and
751
+ * `material.surface(name)`.
752
+ *
753
+ * @public
754
+ */
755
+ var SurfaceShaderBinding = class {
756
+ /** The name the shader answers to on this material. */
757
+ name;
758
+ /** The `.surface.wgsl` this binding was compiled from. */
759
+ shader;
760
+ /** Lower runs first among the material's surface shaders. */
761
+ priority;
762
+ #material;
763
+ #prefix;
764
+ #uniforms;
765
+ #values;
766
+ #textureIndex;
767
+ #fallbacks;
768
+ #handles;
769
+ #state;
770
+ #owner;
771
+ /**
772
+ * Wraps one compiled, attached surface shader. `attachSurfaceShaders` constructs these.
773
+ *
774
+ * @param input - Everything the binding needs; assembled by `attachSurfaceShaders`.
775
+ *
776
+ * @internal
777
+ */
778
+ constructor(input) {
779
+ this.name = input.name;
780
+ this.shader = input.shader;
781
+ this.priority = input.priority;
782
+ this.#material = input.material;
783
+ this.#prefix = input.prefix;
784
+ this.#uniforms = input.uniforms;
785
+ this.#values = input.values;
786
+ this.#textureIndex = input.textureIndex;
787
+ this.#fallbacks = input.fallbacks;
788
+ this.#handles = input.fallbacks.map(() => null);
789
+ this.#state = input.state;
790
+ this.#owner = input.owner;
791
+ }
792
+ /**
793
+ * Whether the shader contributes anything.
794
+ *
795
+ * @returns `true` while it does.
796
+ */
797
+ get enabled() {
798
+ return this.#state.enabled;
799
+ }
800
+ /**
801
+ * Switches the shader off, which restores the host material's plain look.
802
+ *
803
+ * @remarks
804
+ * A disabled plugin contributes no WGSL but still changes Lite's pipeline cache key, so each
805
+ * toggle costs a pipeline rebuild — a settings-screen operation, not a per-frame one.
806
+ *
807
+ * @param value - `false` to switch it off.
808
+ */
809
+ set enabled(value) {
810
+ if (this.#state.enabled === value) return;
811
+ this.#state.enabled = value;
812
+ this.#owner.onShapeChanged();
813
+ }
814
+ /**
815
+ * Writes one of the shader's declared uniforms.
816
+ *
817
+ * @remarks
818
+ * The value is checked against the `// @ignifx uniform` declaration in the file, so a typo fails
819
+ * at the call site rather than as a black surface. A uniform declared `color(…)` takes a
820
+ * {@link ColorLike} in **sRGB** and is uploaded linear, like every other colour in ignifx. The
821
+ * write re-uploads the host material's uniform block and recompiles nothing.
822
+ *
823
+ * @param name - The declared uniform's name, as the file wrote it.
824
+ * @param value - A number, a numeric array of the declared length, or an sRGB colour.
825
+ * @throws IgnifxError with code `IGX-0712` when the file declares no such uniform, or `IGX-0713`
826
+ * when the value's shape does not match the declared type.
827
+ *
828
+ * @example
829
+ * ```ts
830
+ * snow.set("amount", 0.8);
831
+ * snow.set("snowColor", { r: 0.95, g: 0.97, b: 1, a: 1 });
832
+ * ```
833
+ */
834
+ set(name, value) {
835
+ const declaration = this.#uniforms.get(name);
836
+ const store = this.#values.get(`${this.#prefix}${name}`);
837
+ if (declaration === void 0 || store === void 0) throw this.#unknownBinding(name, this.#uniforms.keys());
838
+ writeSurfaceValue(store, declaration, value, this.#material, this.name);
839
+ this.#owner.onValueChanged();
840
+ }
841
+ /**
842
+ * Reads a declared uniform's current value, as it stands on the CPU side. A colour reads back
843
+ * **linear**, which is what the shader sees.
844
+ *
845
+ * @param name - The declared uniform's name.
846
+ * @param out - Receives a vector or matrix value; omit it for a fresh array, or read a scalar's
847
+ * number directly.
848
+ * @returns The number for `f32`, `u32`, and `i32`, and the filled array for everything else.
849
+ * @throws IgnifxError with code `IGX-0712` when the file declares no such uniform, or `IGX-0713`
850
+ * when `out` is shorter than the value.
851
+ */
852
+ get(name, out) {
853
+ const store = this.#values.get(`${this.#prefix}${name}`);
854
+ if (store === void 0) throw this.#unknownBinding(name, this.#uniforms.keys());
855
+ if (out === void 0) return store.length === 1 ? store[0] ?? 0 : store.slice();
856
+ if (out.length < store.length) throw new IgnifxError(CoreErrorCode.shaderValueMismatch, `${name} on ${this.#material} expects ${String(store.length)} floats, not ${String(out.length)}.`, {
857
+ context: {
858
+ material: this.#material,
859
+ name,
860
+ expected: store.length,
861
+ actual: out.length
862
+ },
863
+ hint: "Pass a Float32Array at least as long as the declared type."
864
+ });
865
+ out.set(store);
866
+ return out;
867
+ }
868
+ /**
869
+ * Binds a texture to one of the shader's declared samplers.
870
+ *
871
+ * @remarks
872
+ * There is no "unbound": a bind group with a missing entry fails WebGPU validation, so `null`
873
+ * restores the declaration's 1x1 fallback — white unless the file said
874
+ * `default black` or `default transparent`. The change rebuilds the material's renderables.
875
+ *
876
+ * @param name - The declared sampler's name.
877
+ * @param texture - The texture, or `null` for the fallback.
878
+ * @throws IgnifxError with code `IGX-0712` when the file declares no such sampler.
879
+ */
880
+ setTexture(name, texture) {
881
+ const index = this.#textureIndex.get(name);
882
+ if (index === void 0) throw this.#unknownBinding(name, this.#textureIndex.keys());
883
+ this.#handles[index] = texture;
884
+ const loaded = texture !== null && texture.state === "loaded" ? texture.value.lite.texture : null;
885
+ this.#state.textures[index] = loaded ?? this.#fallbacks[index] ?? null;
886
+ this.#owner.onShapeChanged();
887
+ }
888
+ /**
889
+ * The texture currently bound to a declared sampler.
890
+ *
891
+ * @param name - The declared sampler's name.
892
+ * @returns The handle, or `null` when the declaration's fallback is bound.
893
+ * @throws IgnifxError with code `IGX-0712` when the file declares no such sampler.
894
+ */
895
+ getTexture(name) {
896
+ const index = this.#textureIndex.get(name);
897
+ if (index === void 0) throw this.#unknownBinding(name, this.#textureIndex.keys());
898
+ return this.#handles[index] ?? null;
899
+ }
900
+ /**
901
+ * The Babylon Lite plugin this binding drives. Unstable escape hatch
902
+ * (`docs/architecture/00-overview.md` §3).
903
+ *
904
+ * @returns The plugin, or `null` under a headless app, which builds none.
905
+ */
906
+ get lite() {
907
+ return this.#state.plugin;
908
+ }
909
+ /**
910
+ * The `IGX-0712` failure an undeclared name produces.
911
+ *
912
+ * @param name - The name the caller passed.
913
+ * @param declared - The names the file did declare.
914
+ * @returns The error to throw.
915
+ */
916
+ #unknownBinding(name, declared) {
917
+ return new IgnifxError(CoreErrorCode.unknownShaderBinding, `${this.#material} declares no uniform, texture, or storage buffer named ${name}.`, {
918
+ context: {
919
+ material: this.#material,
920
+ surface: this.name,
921
+ name
922
+ },
923
+ hint: `${this.shader.address} declares ${describeNames(declared)}.`
924
+ });
925
+ }
926
+ };
927
+ /** Everything one material's surface shaders share. */
928
+ var SurfaceShaderAttachment = class {
929
+ bindings = [];
930
+ #app;
931
+ #host;
932
+ #isPbr;
933
+ #isLive = false;
934
+ /**
935
+ * Creates the attachment.
936
+ *
937
+ * @param app - The app, or `null` for a pure unit-test attach.
938
+ * @param host - The Lite PBR or Standard material, or `null` under a headless app.
939
+ * @param isPbr - Whether the host is a PBR material, which needs an explicit UBO dirty mark.
940
+ */
941
+ constructor(app, host, isPbr) {
942
+ this.#app = app;
943
+ this.#host = host;
944
+ this.#isPbr = isPbr;
945
+ }
946
+ /** Records that Lite has been handed the plugin list, so later changes rebuild. */
947
+ goLive() {
948
+ this.#isLive = true;
949
+ }
950
+ /** Re-uploads the host material's uniform block. */
951
+ onValueChanged() {
952
+ markSurfaceValueChanged(this.#host, this.#isPbr);
953
+ }
954
+ /** Rebuilds the host material's renderables, which is what a bind-group or feature change needs. */
955
+ onShapeChanged() {
956
+ rebuildSurfaceHost(this.#app, this.#host, this.#isLive);
957
+ }
958
+ };
959
+ /** One attachment per material, created on first use so module scope allocates nothing. */
960
+ let attachments = null;
961
+ /**
962
+ * Compiles a material's surface shaders, attaches them to its Babylon Lite material, and returns the
963
+ * handles a game changes their values through.
964
+ *
965
+ * @remarks
966
+ * Replaces whatever was attached before, so calling it twice is a re-attach rather than an addition,
967
+ * and an empty list detaches. Under a headless app — or with `app` `null`, which is how a unit test
968
+ * attaches — every value and texture is held and validated and no Lite plugin is built.
969
+ *
970
+ * The second parameter is the **app**, not the rendering service: a runtime import of `renderer.ts`
971
+ * from a module that `material-asset.ts` imports would close a dependency cycle, because
972
+ * `renderer.ts` builds the default `MaterialAsset`. Everything the attach path needs —
973
+ * `renderer.features`, `isHeadless`, `lite.scene`, `log` — is on the public app.
974
+ *
975
+ * @param material - The PBR material to decorate.
976
+ * @param app - The app, or `null` to compile and validate without touching Babylon Lite.
977
+ * @param surfaces - The shaders to attach, with their values.
978
+ * @returns One binding per shader, in the order given.
979
+ * @throws IgnifxError with code `IGX-0716` when `rendering.features.materialPlugins` is off on a
980
+ * device, `IGX-0708` on a `"shader"` host, `IGX-0709` when a file is not a `surface` one, `IGX-0712`
981
+ * when a declared value or texture name is unknown or two shaders share a name, `IGX-0713` on a
982
+ * wrongly shaped value, `IGX-0726` when the material's shaders exceed the sampler budget, and
983
+ * `IGX-0723` when a file declares no hook, declares one this host cannot run, or names a Standard
984
+ * material as its host.
985
+ *
986
+ * @public
987
+ */
988
+ function attachSurfaceShaders(material, app, surfaces) {
989
+ detachSurfaceShaders(material);
990
+ if (surfaces.length === 0) return [];
991
+ const capabilities = assertHostFamily(material);
992
+ const isHeadless = app === null || app.isHeadless;
993
+ assertFeature(material, app, isHeadless, surfaces.length);
994
+ assertPbrHost(material, capabilities);
995
+ const host = resolveSurfaceHost(material, isHeadless);
996
+ const attachment = new SurfaceShaderAttachment(app, host, capabilities.family === "pbr");
997
+ const plugins = [];
998
+ const names = /* @__PURE__ */ new Set();
999
+ let samplers = 0;
1000
+ for (const init of surfaces) {
1001
+ const shader = assertLoadedSurfaceShader(material, init);
1002
+ const name = init.name ?? surfaceShaderName(shader.address);
1003
+ assertUniqueName(material, name, names);
1004
+ samplers += shader.declaration.textures.length;
1005
+ if (samplers > 9) throw new IgnifxError(CoreErrorCode.surfaceSamplerBudgetExceeded, `${material.name} attaches surface shaders declaring ${String(samplers)} samplers; ${String(9)} fit beside a textured PBR material.`, {
1006
+ context: {
1007
+ material: material.name,
1008
+ samplers,
1009
+ budget: 9
1010
+ },
1011
+ hint: "Pack the maps into fewer textures — an RGBA control map rather than four masks."
1012
+ });
1013
+ const binding = buildBinding(material, app, capabilities, init, name, shader, attachment);
1014
+ attachment.bindings.push(binding.binding);
1015
+ const plugin = binding.state.plugin;
1016
+ if (plugin !== null) plugins.push(plugin);
1017
+ }
1018
+ attachSurfacePlugins(host, plugins);
1019
+ attachment.goLive();
1020
+ attachment.onShapeChanged();
1021
+ (attachments ??= /* @__PURE__ */ new WeakMap()).set(material, attachment);
1022
+ return attachment.bindings;
1023
+ }
1024
+ /**
1025
+ * Removes every surface shader from a material, restoring its plain look.
1026
+ *
1027
+ * @remarks
1028
+ * Idempotent, and safe on a material that never had one. It clears Lite's plugin list, which changes
1029
+ * the pipeline cache key, so the material's renderables are rebuilt.
1030
+ *
1031
+ * @param material - The material.
1032
+ *
1033
+ * @public
1034
+ */
1035
+ function detachSurfaceShaders(material) {
1036
+ const existing = attachments?.get(material);
1037
+ if (existing === void 0) return;
1038
+ attachments?.delete(material);
1039
+ detachSurfacePlugins(material);
1040
+ existing.onShapeChanged();
1041
+ }
1042
+ /**
1043
+ * The surface shaders currently attached to a material, in the order they were attached.
1044
+ *
1045
+ * @param material - The material.
1046
+ * @returns The bindings, or an empty array.
1047
+ *
1048
+ * @public
1049
+ */
1050
+ function surfaceShaders(material) {
1051
+ return attachments?.get(material)?.bindings ?? [];
1052
+ }
1053
+ /**
1054
+ * One attached surface shader, by the name it answers to.
1055
+ *
1056
+ * @param material - The material.
1057
+ * @param name - The shader's name — the address's basename unless the material renamed it.
1058
+ * @returns The binding.
1059
+ * @throws IgnifxError with code `IGX-0712` when the material carries no such surface shader.
1060
+ *
1061
+ * @example
1062
+ * ```ts
1063
+ * surfaceShaderBinding(rock.value, "snow").set("amount", 0.4);
1064
+ * ```
1065
+ *
1066
+ * @public
1067
+ */
1068
+ function surfaceShaderBinding(material, name) {
1069
+ for (const binding of surfaceShaders(material)) if (binding.name === name) return binding;
1070
+ throw new IgnifxError(CoreErrorCode.unknownShaderBinding, `${material.name} carries no surface shader named ${name}.`, {
1071
+ context: {
1072
+ material: material.name,
1073
+ name
1074
+ },
1075
+ hint: "The name is the .surface.wgsl basename unless the material's surfaces entry renamed it."
1076
+ });
1077
+ }
1078
+ /**
1079
+ * The name a surface shader answers to when its material does not rename it: the address's basename
1080
+ * with `.surface.wgsl` removed.
1081
+ *
1082
+ * @param address - The shader's asset address.
1083
+ * @returns The name.
1084
+ *
1085
+ * @example
1086
+ * ```ts
1087
+ * surfaceShaderName("shaders/terrain/snow.surface.wgsl"); // "snow"
1088
+ * ```
1089
+ *
1090
+ * @public
1091
+ */
1092
+ function surfaceShaderName(address) {
1093
+ const slash = address.lastIndexOf("/");
1094
+ const basename = slash < 0 ? address : address.slice(slash + 1);
1095
+ if (basename.endsWith(".surface.wgsl")) return basename.slice(0, -13);
1096
+ return basename.endsWith(".wgsl") ? basename.slice(0, -5) : basename;
1097
+ }
1098
+ /**
1099
+ * Compiles one surface shader and builds its binding and Lite plugin.
1100
+ *
1101
+ * @param material - The host material.
1102
+ * @param app - The app, or `null`.
1103
+ * @param capabilities - The host family and what its template exposes.
1104
+ * @param init - What the material declared for this shader.
1105
+ * @param name - The name the shader answers to.
1106
+ * @param shader - The loaded shader asset.
1107
+ * @param owner - The attachment.
1108
+ * @returns The binding and its state.
1109
+ * @throws IgnifxError as `attachSurfaceShaders` documents.
1110
+ */
1111
+ function buildBinding(material, app, capabilities, init, name, shader, owner) {
1112
+ const compiled = compileSurfaceShader({
1113
+ name,
1114
+ address: shader.address,
1115
+ source: shader.source,
1116
+ declaration: shader.declaration,
1117
+ host: capabilities
1118
+ });
1119
+ const uniforms = /* @__PURE__ */ new Map();
1120
+ const values = /* @__PURE__ */ new Map();
1121
+ for (const uniform of shader.declaration.uniforms) {
1122
+ uniforms.set(uniform.name, uniform);
1123
+ values.set(`${compiled.prefix}${uniform.name}`, defaultValueStore(uniform));
1124
+ }
1125
+ const textureIndex = /* @__PURE__ */ new Map();
1126
+ const declarations = shader.declaration.textures;
1127
+ for (let index = 0; index < declarations.length; index += 1) textureIndex.set(declarations[index]?.name ?? "", index);
1128
+ const fallbacks = resolveSurfaceFallbacks(app, declarations);
1129
+ const state = {
1130
+ enabled: init.enabled ?? true,
1131
+ values,
1132
+ textures: [...fallbacks],
1133
+ plugin: null
1134
+ };
1135
+ state.plugin = buildSurfacePlugin(app, compiled, init, capabilities, state);
1136
+ const binding = new SurfaceShaderBinding({
1137
+ name,
1138
+ shader,
1139
+ priority: init.priority ?? DEFAULT_PRIORITY,
1140
+ material: material.name,
1141
+ prefix: compiled.prefix,
1142
+ uniforms,
1143
+ values,
1144
+ textureIndex,
1145
+ fallbacks,
1146
+ state,
1147
+ owner
1148
+ });
1149
+ applyInitialValues(binding, init);
1150
+ return {
1151
+ binding,
1152
+ state
1153
+ };
1154
+ }
1155
+ /**
1156
+ * Writes a material's declared value and texture overrides onto a fresh binding.
1157
+ *
1158
+ * @param binding - The binding.
1159
+ * @param init - What the material declared.
1160
+ * @throws IgnifxError with code `IGX-0712` or `IGX-0713`.
1161
+ */
1162
+ function applyInitialValues(binding, init) {
1163
+ const values = init.values;
1164
+ if (values !== void 0) for (const name of Object.keys(values)) {
1165
+ const value = values[name];
1166
+ if (value !== void 0) binding.set(name, value);
1167
+ }
1168
+ const textures = init.textures;
1169
+ if (textures !== void 0) for (const name of Object.keys(textures)) binding.setTexture(name, textures[name] ?? null);
1170
+ }
1171
+ /**
1172
+ * Refuses a surface shader on a material family that cannot host one, and reports what the host's
1173
+ * template exposes.
1174
+ *
1175
+ * @param material - The material.
1176
+ * @returns The capabilities.
1177
+ * @throws IgnifxError with code `IGX-0708` on a `"shader"` material.
1178
+ */
1179
+ function assertHostFamily(material) {
1180
+ const definition = material.definition;
1181
+ if (definition.kind === "shader") throw new IgnifxError(CoreErrorCode.unsupportedMaterialKind, `${material.name} is a shader material, which owns its whole pipeline and cannot host a surface shader.`, {
1182
+ context: {
1183
+ material: material.name,
1184
+ kind: definition.kind
1185
+ },
1186
+ hint: "Attach surface shaders to a pbr or standard material, or write the effect into the .wgsl itself."
1187
+ });
1188
+ if (definition.kind === "pbr") return {
1189
+ family: "pbr",
1190
+ hasUv: true,
1191
+ hasNormal: !definition.unlit
1192
+ };
1193
+ return {
1194
+ family: "standard",
1195
+ hasUv: Object.keys(definition.textures).length > 0,
1196
+ hasNormal: !definition.unlit
1197
+ };
1198
+ }
1199
+ /**
1200
+ * Refuses a surface shader when the project did not opt into Lite's plugin bridges, and warns when
1201
+ * it is only a headless app that would have been affected.
1202
+ *
1203
+ * @param material - The material, for diagnostics.
1204
+ * @param app - The app, or `null`.
1205
+ * @param isHeadless - Whether there is no device to patch.
1206
+ * @param count - How many shaders are being attached, for the message.
1207
+ * @throws IgnifxError with code `IGX-0716` on a device.
1208
+ */
1209
+ function assertFeature(material, app, isHeadless, count) {
1210
+ if (app === null || app.renderer.features.materialPlugins) return;
1211
+ if (!isHeadless) throw new IgnifxError(CoreErrorCode.surfaceShaderFeatureOff, `${material.name} carries a surface shader, but rendering.features.materialPlugins is off.`, {
1212
+ context: {
1213
+ material: material.name,
1214
+ surfaces: count
1215
+ },
1216
+ hint: "Declare materialPlugins in the rendering.features block of createApp() or ignifx.config.ts."
1217
+ });
1218
+ app.log.warn(`${CoreErrorCode.surfaceShaderFeatureOff}: {material} carries a surface shader, but rendering.features.materialPlugins is off, so it would be inert on a device.`, material.name);
1219
+ }
1220
+ /**
1221
+ * Refuses a surface shader on a **Standard** host, which Babylon Lite 1.27.0 cannot carry one on.
1222
+ *
1223
+ * @remarks
1224
+ * `registerStdPlugins` bakes a per-signature index into every Standard material it finds by walking
1225
+ * `scene.meshes` (`lib/material/plugin/std-plugin-bridge.js` 133-155), and ignifx creates a
1226
+ * renderer's Lite mesh in the first frame's `PreRender` — after that walk — so a Standard host would
1227
+ * silently draw as if it carried nothing. PBR's bridge encodes the signature into the material's
1228
+ * feature bits at build time and has no such rule. The compiler can still generate for a Standard
1229
+ * host, so the refusal lifts as soon as Lite exposes a way to bake one late.
1230
+ *
1231
+ * @param material - The material, for diagnostics.
1232
+ * @param capabilities - The host family.
1233
+ * @throws IgnifxError with code `IGX-0723`.
1234
+ */
1235
+ function assertPbrHost(material, capabilities) {
1236
+ if (capabilities.family === "pbr") return;
1237
+ throw new IgnifxError(CoreErrorCode.surfaceHookMissing, `${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.`, {
1238
+ context: {
1239
+ material: material.name,
1240
+ kind: "standard"
1241
+ },
1242
+ hint: "Use a pbr material as the host; surfaces are a pbr-only feature in this release."
1243
+ });
1244
+ }
1245
+ /**
1246
+ * The shader asset one entry names, checked for being a loaded `surface` file.
1247
+ *
1248
+ * @param material - The host material, for diagnostics.
1249
+ * @param init - The entry.
1250
+ * @returns The shader asset.
1251
+ * @throws IgnifxError with code `IGX-0501` when it is not loaded, or `IGX-0709` when it is not a
1252
+ * `// @ignifx surface` file.
1253
+ */
1254
+ function assertLoadedSurfaceShader(material, init) {
1255
+ const handle = init.shader;
1256
+ if (handle.state !== "loaded") throw new IgnifxError(CoreErrorCode.assetNotLoaded, `The surface shader ${handle.address} is not loaded.`, {
1257
+ context: {
1258
+ asset: handle.address,
1259
+ material: material.name
1260
+ },
1261
+ hint: "await app.assets.loadAsync(address) before building a material from it."
1262
+ });
1263
+ const shader = handle.value;
1264
+ if (shader.declaration.kind !== "surface") throw new IgnifxError(CoreErrorCode.invalidAssetFile, `${shader.address} declares @ignifx ${shader.declaration.kind}, not @ignifx surface.`, {
1265
+ context: {
1266
+ file: shader.address,
1267
+ format: "@ignifx surface",
1268
+ material: material.name,
1269
+ kind: shader.declaration.kind
1270
+ },
1271
+ hint: "A material's surfaces list takes .surface.wgsl files whose pragma is @ignifx surface."
1272
+ });
1273
+ return shader;
1274
+ }
1275
+ /**
1276
+ * Refuses two surface shaders that would answer to the same name — and therefore generate the same
1277
+ * WGSL identifiers — on one material.
1278
+ *
1279
+ * @param material - The host material.
1280
+ * @param name - The name this entry resolved to.
1281
+ * @param taken - The names already used; the accepted one is added.
1282
+ * @throws IgnifxError with code `IGX-0712`.
1283
+ */
1284
+ function assertUniqueName(material, name, taken) {
1285
+ const sanitized = sanitizeIdentifier(name);
1286
+ if (taken.has(sanitized)) throw new IgnifxError(CoreErrorCode.unknownShaderBinding, `${material.name} attaches two surface shaders that both answer to ${name}.`, {
1287
+ context: {
1288
+ material: material.name,
1289
+ name
1290
+ },
1291
+ hint: "Name one of them in its surfaces entry; the name prefixes every generated WGSL identifier."
1292
+ });
1293
+ taken.add(sanitized);
1294
+ }
1295
+ /**
1296
+ * A uniform's CPU-side store, filled with its declared default and decoded from sRGB when the
1297
+ * declaration says it is a colour.
1298
+ *
1299
+ * @param declaration - The uniform declaration.
1300
+ * @returns The store.
1301
+ */
1302
+ function defaultValueStore(declaration) {
1303
+ const store = new Float32Array(uniformComponentCount(declaration.type));
1304
+ const value = declaration.defaultValue;
1305
+ if (typeof value === "number") store[0] = value;
1306
+ else store.set(value.slice(0, store.length));
1307
+ if (declaration.color) decodeColourComponents(store);
1308
+ return store;
1309
+ }
1310
+ /**
1311
+ * Writes a caller's value into a uniform's store, checking its shape and decoding a colour.
1312
+ *
1313
+ * @param store - The store.
1314
+ * @param declaration - The uniform declaration.
1315
+ * @param value - The caller's value.
1316
+ * @param material - The host material's name, for diagnostics.
1317
+ * @param surface - The surface shader's name, for diagnostics.
1318
+ * @throws IgnifxError with code `IGX-0713` when the shape does not match.
1319
+ */
1320
+ function writeSurfaceValue(store, declaration, value, material, surface) {
1321
+ const count = store.length;
1322
+ if (typeof value === "number") {
1323
+ if (count !== 1) throw valueMismatch(declaration, material, surface, `${String(count)} floats`, "a single number");
1324
+ store[0] = value;
1325
+ return;
1326
+ }
1327
+ if (isColorLike(value)) {
1328
+ if (count !== 3 && count !== 4) throw valueMismatch(declaration, material, surface, `${String(count)} floats`, "a colour");
1329
+ store[0] = Color.srgbToLinear(value.r);
1330
+ store[1] = Color.srgbToLinear(value.g);
1331
+ store[2] = Color.srgbToLinear(value.b);
1332
+ if (count === 4) store[3] = value.a;
1333
+ return;
1334
+ }
1335
+ if (value.length !== count) throw valueMismatch(declaration, material, surface, `${String(count)} floats`, `${String(value.length)} floats`);
1336
+ store.set(value instanceof Float32Array ? value : Float32Array.from(value));
1337
+ if (declaration.color) decodeColourComponents(store);
1338
+ }
1339
+ /**
1340
+ * The `IGX-0713` failure a wrongly shaped value produces.
1341
+ *
1342
+ * @param declaration - The uniform declaration.
1343
+ * @param material - The host material's name.
1344
+ * @param surface - The surface shader's name.
1345
+ * @param expected - What the uniform takes.
1346
+ * @param actual - What the caller passed.
1347
+ * @returns The error to throw.
1348
+ */
1349
+ function valueMismatch(declaration, material, surface, expected, actual) {
1350
+ return new IgnifxError(CoreErrorCode.shaderValueMismatch, `${declaration.name} on ${material} expects ${declaration.type} (${expected}), not ${actual}.`, {
1351
+ context: {
1352
+ name: declaration.name,
1353
+ material,
1354
+ surface,
1355
+ expected,
1356
+ actual
1357
+ },
1358
+ hint: "A colour uniform takes a ColorLike or its element count; every other uniform takes its element count."
1359
+ });
1360
+ }
1361
+ /**
1362
+ * Decodes a store's first three components from sRGB to linear, in place.
1363
+ *
1364
+ * @remarks
1365
+ * A `subarray` view and `map` rather than three indexed reads: a `Float32Array` element is typed
1366
+ * `number | undefined` under `noUncheckedIndexedAccess`, and `map` hands the callback a `number`.
1367
+ * It runs on a value write, never per frame.
1368
+ *
1369
+ * @param store - The store, at least three floats long.
1370
+ */
1371
+ function decodeColourComponents(store) {
1372
+ const rgb = store.subarray(0, 3);
1373
+ rgb.set(rgb.map((component) => Color.srgbToLinear(component)));
1374
+ }
1375
+ /**
1376
+ * Whether a value is an sRGB colour rather than a numeric array.
1377
+ *
1378
+ * @param value - The candidate.
1379
+ * @returns `true` for an object carrying `r`, `g`, `b`, and `a`.
1380
+ */
1381
+ function isColorLike(value) {
1382
+ return !Array.isArray(value) && !(value instanceof Float32Array);
1383
+ }
1384
+ /**
1385
+ * A readable list of declared names, for an error hint.
1386
+ *
1387
+ * @param names - The names.
1388
+ * @returns The list, or a note that there are none.
1389
+ */
1390
+ function describeNames(names) {
1391
+ const list = [...names];
1392
+ return list.length === 0 ? "no bindings of that kind" : list.join(", ");
1393
+ }
1394
+ //#endregion
1395
+ export { SurfaceShaderBinding, attachSurfaceShaders, detachSurfaceShaders, surfaceShaderBinding, surfaceShaderName, surfaceShaders };
1396
+
1397
+ //# sourceMappingURL=surface-shader-C2HtysNN.js.map