@ignifx/core 0.13.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/dist/agx-tone-mapping-Cgt844j6.js +53 -0
  2. package/dist/agx-tone-mapping-Cgt844j6.js.map +1 -0
  3. package/dist/auto-exposure-uzPn0beO.js +246 -0
  4. package/dist/auto-exposure-uzPn0beO.js.map +1 -0
  5. package/dist/bloom-hdr-CLtQj-oY.js +315 -0
  6. package/dist/bloom-hdr-CLtQj-oY.js.map +1 -0
  7. package/dist/contact-shadows-T523EXaP.js +84 -0
  8. package/dist/contact-shadows-T523EXaP.js.map +1 -0
  9. package/dist/{environment-C9AjYJgV.js → environment-DPi0_0SP.js} +19 -5
  10. package/dist/environment-DPi0_0SP.js.map +1 -0
  11. package/dist/gtao-_nr0b6-E.js +630 -0
  12. package/dist/gtao-_nr0b6-E.js.map +1 -0
  13. package/dist/hdr-output-BrUvpAsE.js +525 -0
  14. package/dist/hdr-output-BrUvpAsE.js.map +1 -0
  15. package/dist/{ignifx-error-Dq2qJMkZ.js → ignifx-error-oYdVnT1S.js} +16 -1
  16. package/dist/ignifx-error-oYdVnT1S.js.map +1 -0
  17. package/dist/index.d.ts +753 -18
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +1679 -183
  20. package/dist/index.js.map +1 -1
  21. package/dist/{instanced-mesh-instance-DYwH0vLi.js → instanced-mesh-instance-NnODkvqK.js} +2 -2
  22. package/dist/{instanced-mesh-instance-DYwH0vLi.js.map → instanced-mesh-instance-NnODkvqK.js.map} +1 -1
  23. package/dist/mat4-D6exvAuO.js +949 -0
  24. package/dist/mat4-D6exvAuO.js.map +1 -0
  25. package/dist/material-CGk5mAah.js +204 -0
  26. package/dist/material-CGk5mAah.js.map +1 -0
  27. package/dist/{material-plugin-BOCB7Stt.js → material-plugin-BUlqLsap.js} +3 -204
  28. package/dist/material-plugin-BUlqLsap.js.map +1 -0
  29. package/dist/{post-effect-compiler-Dw6zW2cG.js → post-effect-compiler-CRek8VxQ.js} +2 -2
  30. package/dist/{post-effect-compiler-Dw6zW2cG.js.map → post-effect-compiler-CRek8VxQ.js.map} +1 -1
  31. package/dist/render-path-Be7WgN7r.js +166 -0
  32. package/dist/render-path-Be7WgN7r.js.map +1 -0
  33. package/dist/render-texture-C_TnaSz2.js +200 -0
  34. package/dist/render-texture-C_TnaSz2.js.map +1 -0
  35. package/dist/scene-color-passes-DlNr-qyZ.js +65 -0
  36. package/dist/scene-color-passes-DlNr-qyZ.js.map +1 -0
  37. package/dist/scene-inputs-BxGOsnIZ.js +318 -0
  38. package/dist/scene-inputs-BxGOsnIZ.js.map +1 -0
  39. package/dist/{shader-material-DRZmqA_S.js → shader-material-B6p66wB8.js} +18 -7
  40. package/dist/shader-material-B6p66wB8.js.map +1 -0
  41. package/dist/{shader-material-BxQn9FT4.js → shader-material-C0TAUr4t.js} +102 -4
  42. package/dist/shader-material-C0TAUr4t.js.map +1 -0
  43. package/dist/{shader-pragma-DrFm5f5m.js → shader-pragma-BKCoZTTA.js} +2 -2
  44. package/dist/{shader-pragma-DrFm5f5m.js.map → shader-pragma-BKCoZTTA.js.map} +1 -1
  45. package/dist/ssgi-Dm-maZrc.js +113 -0
  46. package/dist/ssgi-Dm-maZrc.js.map +1 -0
  47. package/dist/{surface-shader-BgZchRBe.js → surface-shader-BaK0kvBB.js} +5 -4
  48. package/dist/{surface-shader-BgZchRBe.js.map → surface-shader-BaK0kvBB.js.map} +1 -1
  49. package/dist/taa-BwBZLy11.js +480 -0
  50. package/dist/taa-BwBZLy11.js.map +1 -0
  51. package/dist/{vec3-T2PasQZv.js → vec3-D-0Y2mzE.js} +4 -948
  52. package/dist/vec3-D-0Y2mzE.js.map +1 -0
  53. package/package.json +1 -1
  54. package/dist/environment-C9AjYJgV.js.map +0 -1
  55. package/dist/ignifx-error-Dq2qJMkZ.js.map +0 -1
  56. package/dist/material-plugin-BOCB7Stt.js.map +0 -1
  57. package/dist/shader-material-BxQn9FT4.js.map +0 -1
  58. package/dist/shader-material-DRZmqA_S.js.map +0 -1
  59. package/dist/vec3-T2PasQZv.js.map +0 -1
@@ -0,0 +1,630 @@
1
+ import { o as rebuildMaterialPipelines } from "./material-CGk5mAah.js";
2
+ import { SCENE_INPUT_TASK_NAMES, frameGraphTasks } from "./scene-inputs-BxGOsnIZ.js";
3
+ import { addComputeDispatch, addTaskAfter, buildFrameGraphTask, computeStorageTextureBinding, computeTextureBinding, computeUniformBufferBinding, createComputeBindingSet, createComputeDispatch, createComputeShader, createComputeStorageTexture2D, createComputeTask, createComputeTextureResource, createUniformBuffer, disposeComputeBindingSet, disposeComputeShader, disposeComputeStorageTexture2D, disposeUniformBuffer, getEffectiveAspectRatio, getFrameGraph, getPbrUnlit, getProjectionMatrix, getViewMatrix, invertMat4, isPbrMaterial, removeComputeDispatch, updateUniformBuffer } from "@babylonjs/lite";
4
+ //#region src/lite/gpu/gtao.ts
5
+ /**
6
+ * Ground-truth ambient occlusion (`docs/plan/2026-11-gi-phase-1-execution-plan.md`, steps G8 and G9;
7
+ * `docs/architecture/07-rendering.md` §2.14). Its own chunk: the renderer imports it only when
8
+ * `rendering.ambientOcclusion.enabled` is on, so a project without it loads none of it and its frame
9
+ * graph has none of these tasks (`CONSTITUTION.md` §2.5).
10
+ *
11
+ * ```text
12
+ * … depth pyramid → gtao params → gtao (compute: horizons, then depth-aware blur) → scene → …
13
+ * └─ AO texture ─→ every lit PBR material's `occlusion`
14
+ * ```
15
+ *
16
+ * - **GTAO** (Jimenez et al. 2016, after XeGTAO): per pixel, a few screen-space slices through the
17
+ * view vector; along each, the highest horizon on either side within `radius`, then the cosine-
18
+ * weighted visible arc between them against the normal projected into the slice. Depth comes from
19
+ * the scene inputs' depth pyramid (level 1 at half resolution, coarser levels for far taps), normals
20
+ * from the scene inputs' world normals, rotated into view space. Slice angle and step offset are
21
+ * jittered per pixel with interleaved gradient noise.
22
+ * - **Denoise.** A 5×5 blur weighted by view-depth similarity, in the same compute pass.
23
+ * - **Indirect light only (spike S3).** {@link createAmbientOcclusionPlugin} multiplies Lite's PBR
24
+ * `occlusion` variable, which scales the environment's irradiance and specular occlusion and
25
+ * nothing else (`lib/material/pbr/fragments/ibl-fragment.js`), by the AO texture at the
26
+ * fragment's screen position. Every lit PBR variant declares `occlusion` before that slot: the
27
+ * template's `occlusionDefault`, or the reflectance extension's own `AT` code
28
+ * (`lib/material/pbr/fragments/reflectance-fragment.js` line 146). Standard materials, unlit PBR and
29
+ * custom shaders are left alone.
30
+ * - **Camera matrices** are written by a tiny task that runs inside the frame graph, after Lite has
31
+ * updated world matrices for the frame, so the AO never lags a moving camera.
32
+ * - **Resize and device loss.** The scene inputs' `onChange` disables the pass, rebuilds the
33
+ * textures and bindings, swaps them in, and rebuilds the patched materials, whose bind groups hold
34
+ * the AO texture's view. The old textures are disposed a few frames later, once no in-flight bind
35
+ * group can still name them.
36
+ * - **TAA.** `rendering.taa` (G5) filters the final colour, AO included; a dedicated AO history is
37
+ * not wired. It would accumulate {@link AmbientOcclusion.texture} before the plugin reads it.
38
+ */
39
+ /**
40
+ * The frame-graph task names, in the order they run after the scene inputs.
41
+ *
42
+ * @internal
43
+ */
44
+ const GTAO_TASK_NAMES = {
45
+ params: "ignifx:gtao-params",
46
+ compute: "ignifx:gtao"
47
+ };
48
+ /**
49
+ * The name the material plugin carries; part of Lite's pipeline cache key.
50
+ *
51
+ * @internal
52
+ */
53
+ const GTAO_PLUGIN_NAME = "ignifx-gtao";
54
+ /** The uniform block: three matrices, the sizes, the settings. */
55
+ const UNIFORM_FLOATS = 56;
56
+ /** Frames an old texture set outlives its replacement. */
57
+ const RETIRE_FRAMES = 8;
58
+ /** The workgroup edge both shaders use. */
59
+ const WORKGROUP = 8;
60
+ /**
61
+ * The shape of a quality: `"half"` is 2 slices × 4 steps at half resolution, `"full"` 3 × 6 at full.
62
+ *
63
+ * @param quality - The quality.
64
+ * @returns The shape.
65
+ *
66
+ * @internal
67
+ */
68
+ function gtaoShape(quality) {
69
+ return quality === "full" ? {
70
+ scale: 1,
71
+ baseMip: 0,
72
+ slices: 3,
73
+ steps: 6
74
+ } : {
75
+ scale: 2,
76
+ baseMip: 1,
77
+ slices: 2,
78
+ steps: 4
79
+ };
80
+ }
81
+ /**
82
+ * Builds the GTAO compute shader.
83
+ *
84
+ * @param shape - The quality's shape, baked in as constants.
85
+ * @returns The WGSL.
86
+ *
87
+ * @internal
88
+ */
89
+ function gtaoWgsl(shape) {
90
+ return `
91
+ struct GtaoParams {
92
+ proj: mat4x4<f32>,
93
+ invProj: mat4x4<f32>,
94
+ view: mat4x4<f32>,
95
+ size: vec4<f32>,
96
+ settings: vec4<f32>,
97
+ };
98
+ @group(0) @binding(0) var<uniform> params: GtaoParams;
99
+ @group(0) @binding(1) var depthPyramid: texture_2d<f32>;
100
+ @group(0) @binding(2) var normals: texture_2d<f32>;
101
+ @group(0) @binding(3) var aoOut: texture_storage_2d<rgba16float, write>;
102
+
103
+ const SLICES: u32 = ${String(shape.slices)}u;
104
+ const STEPS: u32 = ${String(shape.steps)}u;
105
+ const BASE_MIP: i32 = ${String(shape.baseMip)};
106
+ const SCALE: f32 = ${shape.scale.toFixed(1)};
107
+ const PI: f32 = 3.14159265;
108
+ const HALF_PI: f32 = 1.57079633;
109
+
110
+ fn loadDepth(pixel: vec2<f32>, mip: i32) -> f32 {
111
+ let dims = vec2<i32>(textureDimensions(depthPyramid, mip));
112
+ let coord = clamp(vec2<i32>(floor(pixel / f32(1 << u32(mip)))), vec2<i32>(0), dims - 1);
113
+ return textureLoad(depthPyramid, coord, mip).r;
114
+ }
115
+
116
+ fn viewPosition(pixel: vec2<f32>, depth: f32) -> vec3<f32> {
117
+ let uv = pixel / params.size.xy;
118
+ let p = params.invProj * vec4<f32>(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, depth, 1.0);
119
+ return p.xyz / p.w;
120
+ }
121
+
122
+ fn ign(p: vec2<f32>) -> f32 {
123
+ return fract(52.9829189 * fract(dot(p, vec2<f32>(0.06711056, 0.00583715))));
124
+ }
125
+
126
+ @compute @workgroup_size(${String(WORKGROUP)}, ${String(WORKGROUP)})
127
+ fn main(@builtin(global_invocation_id) id: vec3<u32>) {
128
+ if (f32(id.x) >= params.size.z || f32(id.y) >= params.size.w) {
129
+ return;
130
+ }
131
+ let pixel = (vec2<f32>(id.xy) + 0.5) * SCALE;
132
+ let depth = loadDepth(pixel, BASE_MIP);
133
+ if (depth <= 0.0) {
134
+ textureStore(aoOut, vec2<i32>(id.xy), vec4<f32>(1.0, 0.0, 0.0, 1.0));
135
+ return;
136
+ }
137
+ let P = viewPosition(pixel, depth);
138
+ let V = normalize(viewPosition(pixel, 1.0) - P);
139
+ let full = vec2<i32>(params.size.xy) - 1;
140
+ let stored = textureLoad(normals, clamp(vec2<i32>(pixel), vec2<i32>(0), full), 0).xyz;
141
+ let N = normalize((params.view * vec4<f32>(stored * 2.0 - 1.0, 0.0)).xyz);
142
+
143
+ let radius = params.settings.x;
144
+ let falloffRange = max(params.settings.y * radius, 0.0001);
145
+ let c0 = params.proj * vec4<f32>(P, 1.0);
146
+ let c1 = params.proj * vec4<f32>(P + vec3<f32>(radius, 0.0, 0.0), 1.0);
147
+ let screenRadius = min(abs(c1.x / c1.w - c0.x / c0.w) * 0.5 * params.size.x, 0.3 * max(params.size.x, params.size.y));
148
+ if (screenRadius < SCALE) {
149
+ textureStore(aoOut, vec2<i32>(id.xy), vec4<f32>(1.0, abs(P.z), 0.0, 1.0));
150
+ return;
151
+ }
152
+ let maxMip = i32(textureNumLevels(depthPyramid)) - 1;
153
+ let noiseSlice = ign(vec2<f32>(id.xy));
154
+ let noiseStep = ign(vec2<f32>(id.xy) + vec2<f32>(17.0, 59.0));
155
+
156
+ var visibility = 0.0;
157
+ for (var slice = 0u; slice < SLICES; slice++) {
158
+ let phi = (f32(slice) + noiseSlice) * PI / f32(SLICES);
159
+ let omega = vec2<f32>(cos(phi), -sin(phi));
160
+ let direction = vec3<f32>(omega.x, -omega.y, 0.0);
161
+ let orthoDirection = direction - dot(direction, V) * V;
162
+ let axis = normalize(cross(orthoDirection, V));
163
+ let projected = N - axis * dot(N, axis);
164
+ let projectedLength = length(projected);
165
+ let signN = sign(dot(orthoDirection, projected));
166
+ let cosN = clamp(dot(projected, V) / max(projectedLength, 0.0001), 0.0, 1.0);
167
+ let n = signN * acos(cosN);
168
+ let low0 = cos(n + HALF_PI);
169
+ let low1 = cos(n - HALF_PI);
170
+ var horizon0 = low0;
171
+ var horizon1 = low1;
172
+ for (var step = 0u; step < STEPS; step++) {
173
+ let t = (f32(step) + noiseStep) / f32(STEPS);
174
+ let offsetLength = mix(SCALE, screenRadius, t * t);
175
+ let mip = clamp(i32(floor(log2(offsetLength))) - 3, BASE_MIP, max(maxMip, BASE_MIP));
176
+ let offset = omega * offsetLength;
177
+ let d0 = loadDepth(pixel + offset, mip);
178
+ let d1 = loadDepth(pixel - offset, mip);
179
+ let s0 = viewPosition(pixel + offset, max(d0, 0.000001)) - P;
180
+ let s1 = viewPosition(pixel - offset, max(d1, 0.000001)) - P;
181
+ let l0 = length(s0);
182
+ let l1 = length(s1);
183
+ let w0 = select(0.0, clamp((radius - l0) / falloffRange, 0.0, 1.0), d0 > 0.0);
184
+ let w1 = select(0.0, clamp((radius - l1) / falloffRange, 0.0, 1.0), d1 > 0.0);
185
+ horizon0 = max(horizon0, mix(low0, dot(s0 / max(l0, 0.00001), V), w0));
186
+ horizon1 = max(horizon1, mix(low1, dot(s1 / max(l1, 0.00001), V), w1));
187
+ }
188
+ var h0 = -acos(clamp(horizon1, -1.0, 1.0));
189
+ var h1 = acos(clamp(horizon0, -1.0, 1.0));
190
+ h0 = n + clamp(h0 - n, -HALF_PI, HALF_PI);
191
+ h1 = n + clamp(h1 - n, -HALF_PI, HALF_PI);
192
+ let sinN = sin(n);
193
+ let arc0 = (cosN + 2.0 * h0 * sinN - cos(2.0 * h0 - n)) * 0.25;
194
+ let arc1 = (cosN + 2.0 * h1 * sinN - cos(2.0 * h1 - n)) * 0.25;
195
+ visibility += projectedLength * (arc0 + arc1);
196
+ }
197
+ visibility = clamp(visibility / f32(SLICES), 0.03, 1.0);
198
+ let ao = pow(visibility, params.settings.z);
199
+ textureStore(aoOut, vec2<i32>(id.xy), vec4<f32>(ao, abs(P.z), 0.0, 1.0));
200
+ }
201
+ `;
202
+ }
203
+ /**
204
+ * Builds the denoise shader: a 5×5 Gaussian weighted by view-depth similarity.
205
+ *
206
+ * @returns The WGSL.
207
+ *
208
+ * @internal
209
+ */
210
+ function gtaoDenoiseWgsl() {
211
+ return `
212
+ struct GtaoParams {
213
+ proj: mat4x4<f32>,
214
+ invProj: mat4x4<f32>,
215
+ view: mat4x4<f32>,
216
+ size: vec4<f32>,
217
+ settings: vec4<f32>,
218
+ };
219
+ @group(0) @binding(0) var<uniform> params: GtaoParams;
220
+ @group(0) @binding(1) var rawAo: texture_2d<f32>;
221
+ @group(0) @binding(2) var aoOut: texture_storage_2d<rgba8unorm, write>;
222
+
223
+ @compute @workgroup_size(${String(WORKGROUP)}, ${String(WORKGROUP)})
224
+ fn main(@builtin(global_invocation_id) id: vec3<u32>) {
225
+ if (f32(id.x) >= params.size.z || f32(id.y) >= params.size.w) {
226
+ return;
227
+ }
228
+ let dims = vec2<i32>(textureDimensions(rawAo)) - 1;
229
+ let at = vec2<i32>(id.xy);
230
+ let centre = textureLoad(rawAo, at, 0);
231
+ if (centre.y <= 0.0) {
232
+ textureStore(aoOut, at, vec4<f32>(centre.x, centre.x, centre.x, 1.0));
233
+ return;
234
+ }
235
+ let tolerance = max(centre.y * 0.05, 0.0001);
236
+ var sum = 0.0;
237
+ var weights = 0.0;
238
+ for (var y = -2; y <= 2; y++) {
239
+ for (var x = -2; x <= 2; x++) {
240
+ let tap = textureLoad(rawAo, clamp(at + vec2<i32>(x, y), vec2<i32>(0), dims), 0);
241
+ let spatial = exp(-f32(x * x + y * y) / 4.5);
242
+ let similar = max(0.0, 1.0 - abs(tap.y - centre.y) / tolerance);
243
+ let weight = spatial * similar;
244
+ sum += tap.x * weight;
245
+ weights += weight;
246
+ }
247
+ }
248
+ let ao = sum / max(weights, 0.0001);
249
+ textureStore(aoOut, at, vec4<f32>(ao, ao, ao, 1.0));
250
+ }
251
+ `;
252
+ }
253
+ /**
254
+ * The plugin code that multiplies a PBR fragment's `occlusion` by the AO texture.
255
+ *
256
+ * @remarks
257
+ * At half resolution the AO texel under the fragment is blended bilinearly from four loads rather
258
+ * than through a sampler, so the result does not depend on the storage texture's sampler. The block
259
+ * scope keeps its names out of the shader's. `input.clipPos` is the fragment's `@builtin(position)`
260
+ * (spike S3).
261
+ *
262
+ * @param scale - Full-resolution pixels per AO pixel.
263
+ * @returns The WGSL for `CUSTOM_FRAGMENT_BEFORE_LIGHTS`.
264
+ *
265
+ * @internal
266
+ */
267
+ function gtaoPluginWgsl(scale) {
268
+ if (scale === 1) return "{let igxAoMax=vec2<i32>(textureDimensions(ignifxAo))-1;occlusion*=textureLoad(ignifxAo,clamp(vec2<i32>(input.clipPos.xy),vec2<i32>(0),igxAoMax),0).r;}";
269
+ return `{let igxAoMax=vec2<i32>(textureDimensions(ignifxAo))-1;let igxAoF=input.clipPos.xy/${scale.toFixed(1)}-0.5;let igxAoB=vec2<i32>(floor(igxAoF));let igxAoT=fract(igxAoF);let igxAo00=textureLoad(ignifxAo,clamp(igxAoB,vec2<i32>(0),igxAoMax),0).r;let igxAo10=textureLoad(ignifxAo,clamp(igxAoB+vec2<i32>(1,0),vec2<i32>(0),igxAoMax),0).r;let igxAo01=textureLoad(ignifxAo,clamp(igxAoB+vec2<i32>(0,1),vec2<i32>(0),igxAoMax),0).r;let igxAo11=textureLoad(ignifxAo,clamp(igxAoB+vec2<i32>(1,1),vec2<i32>(0),igxAoMax),0).r;occlusion*=mix(mix(igxAo00,igxAo10,igxAoT.x),mix(igxAo01,igxAo11,igxAoT.x),igxAoT.y);}`;
270
+ }
271
+ /**
272
+ * Builds the material plugin that applies the AO texture to indirect light (spike S3).
273
+ *
274
+ * @param scale - Full-resolution pixels per AO pixel.
275
+ * @param texture - Reads the current AO texture; it changes on resize.
276
+ * @returns The plugin, shared by every lit PBR material.
277
+ *
278
+ * @internal
279
+ */
280
+ function createAmbientOcclusionPlugin(scale, texture) {
281
+ const fragment = { CUSTOM_FRAGMENT_BEFORE_LIGHTS: gtaoPluginWgsl(scale) };
282
+ return {
283
+ name: GTAO_PLUGIN_NAME,
284
+ priority: 600,
285
+ getSamplers: () => [{
286
+ texture: "ignifxAo",
287
+ sampler: "ignifxAoSampler"
288
+ }],
289
+ bindTextures: (out) => {
290
+ out.push({ texture: texture().sampledTexture });
291
+ },
292
+ getCustomCode: (stage) => stage === "fragment" ? fragment : null
293
+ };
294
+ }
295
+ /**
296
+ * Builds the GTAO pass, splices its tasks in after the scene inputs, and returns its handle.
297
+ *
298
+ * @remarks
299
+ * Called once, from the renderer, with a scene-inputs lease the handle now owns. Before the scene is
300
+ * registered (`isFrameGraphBuilt` `false`) `registerScene` records the tasks; afterwards they are
301
+ * recorded here.
302
+ *
303
+ * @param engine - The engine.
304
+ * @param scene - The render scene.
305
+ * @param inputs - A scene-inputs lease; released by {@link AmbientOcclusion.dispose}.
306
+ * @param options - The resolved settings.
307
+ * @param isFrameGraphBuilt - Whether the scene is registered.
308
+ * @returns The handle.
309
+ *
310
+ * @internal
311
+ */
312
+ async function createAmbientOcclusion(engine, scene, inputs, options, isFrameGraphBuilt) {
313
+ const shape = gtaoShape(options.quality);
314
+ let current = await buildGpuSet(engine, inputs, shape);
315
+ const retired = [];
316
+ const data = new Float32Array(UNIFORM_FLOATS);
317
+ let isDisposed = false;
318
+ let generation = 0;
319
+ const compute = createComputeTask(engine, GTAO_TASK_NAMES.compute);
320
+ addComputeDispatch(compute, current.gtao);
321
+ addComputeDispatch(compute, current.denoise);
322
+ const params = createExecuteTask(engine, scene, GTAO_TASK_NAMES.params, () => {
323
+ const enabled = writeParams(scene, current, shape, options, data);
324
+ current.gtao.enabled = enabled;
325
+ current.denoise.enabled = enabled;
326
+ if (enabled) updateUniformBuffer(engine, current.uniforms, data);
327
+ });
328
+ const tasks = [params, compute];
329
+ const pyramid = frameGraphTasks(scene)?.find((task) => task.name === SCENE_INPUT_TASK_NAMES.depthPyramid);
330
+ if (pyramid === void 0) {
331
+ disposeGpuSet(current);
332
+ inputs.release();
333
+ throw new Error("GTAO needs the scene inputs' depth pyramid task in the frame graph.");
334
+ }
335
+ addTaskAfter(scene, params, pyramid);
336
+ addTaskAfter(scene, compute, params);
337
+ if (isFrameGraphBuilt) {
338
+ const graph = getFrameGraph(scene);
339
+ for (const task of tasks) buildFrameGraphTask(graph, task);
340
+ }
341
+ const plugin = createAmbientOcclusionPlugin(shape.scale, () => current.out);
342
+ const stopWatch = inputs.onChange(() => {
343
+ generation += 1;
344
+ const mine = generation;
345
+ compute.executionEnabled = false;
346
+ buildGpuSet(engine, inputs, shape).then((next) => {
347
+ if (isDisposed || mine !== generation) {
348
+ disposeGpuSet(next);
349
+ return;
350
+ }
351
+ removeComputeDispatch(compute, current.gtao);
352
+ removeComputeDispatch(compute, current.denoise);
353
+ addComputeDispatch(compute, next.gtao);
354
+ addComputeDispatch(compute, next.denoise);
355
+ retired.push({
356
+ set: current,
357
+ frames: RETIRE_FRAMES
358
+ });
359
+ current = next;
360
+ compute.executionEnabled = true;
361
+ rebuildPatchedMaterials(scene, plugin);
362
+ }, (error) => {
363
+ options.onError(error);
364
+ });
365
+ });
366
+ return {
367
+ get texture() {
368
+ return current.out;
369
+ },
370
+ update(isSceneRegistered) {
371
+ if (isDisposed) return;
372
+ attachPlugin(scene, plugin, isSceneRegistered);
373
+ for (let index = retired.length - 1; index >= 0; index -= 1) {
374
+ const entry = retired[index];
375
+ if (entry !== void 0 && --entry.frames <= 0) {
376
+ disposeGpuSet(entry.set);
377
+ retired.splice(index, 1);
378
+ }
379
+ }
380
+ },
381
+ dispose() {
382
+ if (isDisposed) return;
383
+ isDisposed = true;
384
+ stopWatch();
385
+ const list = frameGraphTasks(scene);
386
+ for (const task of tasks) {
387
+ task.executionEnabled = false;
388
+ const index = list?.indexOf(task) ?? -1;
389
+ if (list !== null && index >= 0) list.splice(index, 1);
390
+ task.dispose();
391
+ }
392
+ disposeGpuSet(current);
393
+ for (const entry of retired) disposeGpuSet(entry.set);
394
+ retired.length = 0;
395
+ inputs.release();
396
+ }
397
+ };
398
+ }
399
+ /**
400
+ * Writes this frame's uniforms from the scene's camera.
401
+ *
402
+ * @param scene - The scene.
403
+ * @param set - The current GPU set, for its sizes.
404
+ * @param shape - The quality's shape.
405
+ * @param options - The settings.
406
+ * @param out - The uniform floats.
407
+ * @returns `false` when there is no camera or its projection does not invert, so the pass skips.
408
+ */
409
+ function writeParams(scene, set, shape, options, out) {
410
+ const camera = scene.camera;
411
+ if (camera === null) return false;
412
+ const projection = getProjectionMatrix(camera, getEffectiveAspectRatio(camera, set.width, set.height));
413
+ const inverse = invertMat4(projection);
414
+ if (inverse === null) return false;
415
+ copyMat4(projection, out, 0);
416
+ copyMat4(inverse, out, 16);
417
+ copyMat4(getViewMatrix(camera), out, 32);
418
+ out[48] = set.width;
419
+ out[49] = set.height;
420
+ out[50] = set.raw.width;
421
+ out[51] = set.raw.height;
422
+ out[52] = options.radius;
423
+ out[53] = options.falloff;
424
+ out[54] = options.intensity;
425
+ out[55] = shape.slices;
426
+ return true;
427
+ }
428
+ /**
429
+ * Copies a Lite matrix into a float array.
430
+ *
431
+ * @param matrix - The matrix, column-major.
432
+ * @param out - The destination.
433
+ * @param offset - Where the 16 floats start.
434
+ */
435
+ function copyMat4(matrix, out, offset) {
436
+ for (let index = 0; index < 16; index += 1) out[offset + index] = matrix[index] ?? 0;
437
+ }
438
+ /**
439
+ * Creates the textures, shaders and bindings for the current surface size and device.
440
+ *
441
+ * @param engine - The engine.
442
+ * @param inputs - The scene-inputs lease.
443
+ * @param shape - The quality's shape.
444
+ * @returns The set.
445
+ */
446
+ async function buildGpuSet(engine, inputs, shape) {
447
+ const width = inputs.depth.width;
448
+ const height = inputs.depth.height;
449
+ const aoWidth = Math.max(1, Math.ceil(width / shape.scale));
450
+ const aoHeight = Math.max(1, Math.ceil(height / shape.scale));
451
+ const [pyramid, normals] = await Promise.all([createComputeTextureResource(engine, inputs.depthPyramid, { sampleType: "unfilterable-float" }), createComputeTextureResource(engine, inputs.normals, { sampleType: "unfilterable-float" })]);
452
+ const uniforms = createUniformBuffer(engine, 224, { label: "ignifx:gtao-params" });
453
+ const raw = createComputeStorageTexture2D(engine, {
454
+ width: aoWidth,
455
+ height: aoHeight,
456
+ format: "rgba16float",
457
+ label: "ignifx:gtao-raw",
458
+ invertY: false
459
+ });
460
+ const out = createComputeStorageTexture2D(engine, {
461
+ width: aoWidth,
462
+ height: aoHeight,
463
+ format: "rgba8unorm",
464
+ label: "ignifx:gtao",
465
+ invertY: false
466
+ });
467
+ const gtaoShader = createComputeShader(engine, {
468
+ name: "ignifx:gtao",
469
+ computeSource: gtaoWgsl(shape),
470
+ bindings: [
471
+ computeUniformBufferBinding("params", {
472
+ group: 0,
473
+ binding: 0
474
+ }),
475
+ computeTextureBinding("depthPyramid", {
476
+ group: 0,
477
+ binding: 1,
478
+ sampleType: "unfilterable-float"
479
+ }),
480
+ computeTextureBinding("normals", {
481
+ group: 0,
482
+ binding: 2,
483
+ sampleType: "unfilterable-float"
484
+ }),
485
+ computeStorageTextureBinding("aoOut", {
486
+ group: 0,
487
+ binding: 3,
488
+ format: "rgba16float"
489
+ })
490
+ ]
491
+ });
492
+ const denoiseShader = createComputeShader(engine, {
493
+ name: "ignifx:gtao-denoise",
494
+ computeSource: gtaoDenoiseWgsl(),
495
+ bindings: [
496
+ computeUniformBufferBinding("params", {
497
+ group: 0,
498
+ binding: 0
499
+ }),
500
+ computeTextureBinding("rawAo", {
501
+ group: 0,
502
+ binding: 1,
503
+ sampleType: "float"
504
+ }),
505
+ computeStorageTextureBinding("aoOut", {
506
+ group: 0,
507
+ binding: 2,
508
+ format: "rgba8unorm"
509
+ })
510
+ ]
511
+ });
512
+ const size = {
513
+ x: Math.ceil(aoWidth / WORKGROUP),
514
+ y: Math.ceil(aoHeight / WORKGROUP)
515
+ };
516
+ const gtao = createComputeDispatch(gtaoShader, createComputeBindingSet(gtaoShader, {
517
+ params: uniforms,
518
+ depthPyramid: pyramid,
519
+ normals,
520
+ aoOut: raw
521
+ }), {
522
+ size,
523
+ enabled: false
524
+ });
525
+ const denoise = createComputeDispatch(denoiseShader, createComputeBindingSet(denoiseShader, {
526
+ params: uniforms,
527
+ rawAo: raw.computeTexture,
528
+ aoOut: out
529
+ }), {
530
+ size,
531
+ enabled: false
532
+ });
533
+ return {
534
+ uniforms,
535
+ raw,
536
+ out,
537
+ shaders: [gtaoShader, denoiseShader],
538
+ gtao,
539
+ denoise,
540
+ width,
541
+ height
542
+ };
543
+ }
544
+ /**
545
+ * Frees a set's GPU objects.
546
+ *
547
+ * @param set - The set.
548
+ */
549
+ function disposeGpuSet(set) {
550
+ set.gtao.enabled = false;
551
+ set.denoise.enabled = false;
552
+ disposeComputeBindingSet(set.gtao.bindings);
553
+ disposeComputeBindingSet(set.denoise.bindings);
554
+ for (const shader of set.shaders) disposeComputeShader(shader);
555
+ disposeComputeStorageTexture2D(set.raw);
556
+ disposeComputeStorageTexture2D(set.out);
557
+ disposeUniformBuffer(set.uniforms);
558
+ }
559
+ /**
560
+ * Creates a frame-graph task that runs a callback each frame, inside the frame graph.
561
+ *
562
+ * @remarks
563
+ * Lite runs a task's `execute()` fast path instead of its recorded passes
564
+ * (`lib/frame-graph/frame-graph.js`); `record()` and `build()` clear and walk `_passes`, which such
565
+ * a task leaves empty. It runs after Lite's per-frame world-matrix update, unlike `onBeforeRender`.
566
+ *
567
+ * @param engine - The engine.
568
+ * @param scene - The scene.
569
+ * @param name - The task name.
570
+ * @param run - The callback.
571
+ * @returns The task.
572
+ */
573
+ function createExecuteTask(engine, scene, name, run) {
574
+ return {
575
+ name,
576
+ engine,
577
+ scene,
578
+ executionEnabled: true,
579
+ _passes: [],
580
+ record() {},
581
+ execute() {
582
+ run();
583
+ return 0;
584
+ },
585
+ dispose() {}
586
+ };
587
+ }
588
+ /**
589
+ * Gives every lit PBR material in the scene the AO plugin, once.
590
+ *
591
+ * @remarks
592
+ * A walk, for the reasons `./hdr-output.ts`'s `attachLinearOutput` gives: materials come from many
593
+ * places, and a surface shader replaces a material's plugin list.
594
+ *
595
+ * @param scene - The scene.
596
+ * @param plugin - The shared plugin.
597
+ * @param isSceneRegistered - Whether a patched material's pipelines must be rebuilt.
598
+ */
599
+ function attachPlugin(scene, plugin, isSceneRegistered) {
600
+ const meshes = scene.meshes;
601
+ for (let index = 0; index < meshes.length; index += 1) {
602
+ const material = meshes[index]?.material;
603
+ if (material === void 0 || material === null || !isPbrMaterial(material)) continue;
604
+ if (getPbrUnlit(material) !== void 0) continue;
605
+ const current = material.plugins ?? [];
606
+ if (current.includes(plugin)) continue;
607
+ material.plugins = [...current, plugin];
608
+ if (isSceneRegistered) rebuildMaterialPipelines(scene, material);
609
+ }
610
+ }
611
+ /**
612
+ * Rebuilds every material that carries the plugin, so its bind group names the new AO texture.
613
+ *
614
+ * @param scene - The scene.
615
+ * @param plugin - The shared plugin.
616
+ */
617
+ function rebuildPatchedMaterials(scene, plugin) {
618
+ const seen = /* @__PURE__ */ new Set();
619
+ const meshes = scene.meshes;
620
+ for (let index = 0; index < meshes.length; index += 1) {
621
+ const material = meshes[index]?.material;
622
+ if (material === void 0 || material === null || seen.has(material) || !isPbrMaterial(material)) continue;
623
+ seen.add(material);
624
+ if (material.plugins?.includes(plugin) === true) rebuildMaterialPipelines(scene, material);
625
+ }
626
+ }
627
+ //#endregion
628
+ export { GTAO_PLUGIN_NAME, GTAO_TASK_NAMES, createAmbientOcclusion, createAmbientOcclusionPlugin, gtaoDenoiseWgsl, gtaoPluginWgsl, gtaoShape, gtaoWgsl };
629
+
630
+ //# sourceMappingURL=gtao-_nr0b6-E.js.map