@ignifx/core 0.14.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 (51) 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-Cq2BmA96.js → environment-DPi0_0SP.js} +18 -4
  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/index.d.ts +452 -20
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +900 -43
  18. package/dist/index.js.map +1 -1
  19. package/dist/{instanced-mesh-instance-DYwH0vLi.js → instanced-mesh-instance-NnODkvqK.js} +2 -2
  20. package/dist/{instanced-mesh-instance-DYwH0vLi.js.map → instanced-mesh-instance-NnODkvqK.js.map} +1 -1
  21. package/dist/mat4-D6exvAuO.js +949 -0
  22. package/dist/mat4-D6exvAuO.js.map +1 -0
  23. package/dist/{render-path-Dx0learj.js → render-path-Be7WgN7r.js} +35 -4
  24. package/dist/render-path-Be7WgN7r.js.map +1 -0
  25. package/dist/{render-texture-IuR0iFVa.js → render-texture-C_TnaSz2.js} +28 -2
  26. package/dist/render-texture-C_TnaSz2.js.map +1 -0
  27. package/dist/scene-color-passes-DlNr-qyZ.js +65 -0
  28. package/dist/scene-color-passes-DlNr-qyZ.js.map +1 -0
  29. package/dist/scene-inputs-BxGOsnIZ.js +318 -0
  30. package/dist/scene-inputs-BxGOsnIZ.js.map +1 -0
  31. package/dist/{shader-material-CDQ0Y5kN.js → shader-material-B6p66wB8.js} +17 -6
  32. package/dist/shader-material-B6p66wB8.js.map +1 -0
  33. package/dist/{shader-material-BPb_oEZQ.js → shader-material-C0TAUr4t.js} +102 -4
  34. package/dist/shader-material-C0TAUr4t.js.map +1 -0
  35. package/dist/ssgi-Dm-maZrc.js +113 -0
  36. package/dist/ssgi-Dm-maZrc.js.map +1 -0
  37. package/dist/{surface-shader-CwQ03yHG.js → surface-shader-BaK0kvBB.js} +2 -2
  38. package/dist/{surface-shader-CwQ03yHG.js.map → surface-shader-BaK0kvBB.js.map} +1 -1
  39. package/dist/taa-BwBZLy11.js +480 -0
  40. package/dist/taa-BwBZLy11.js.map +1 -0
  41. package/dist/{vec3-T2PasQZv.js → vec3-D-0Y2mzE.js} +4 -948
  42. package/dist/vec3-D-0Y2mzE.js.map +1 -0
  43. package/package.json +1 -1
  44. package/dist/environment-Cq2BmA96.js.map +0 -1
  45. package/dist/hdr-output-DDpIo4Q5.js +0 -300
  46. package/dist/hdr-output-DDpIo4Q5.js.map +0 -1
  47. package/dist/render-path-Dx0learj.js.map +0 -1
  48. package/dist/render-texture-IuR0iFVa.js.map +0 -1
  49. package/dist/shader-material-BPb_oEZQ.js.map +0 -1
  50. package/dist/shader-material-CDQ0Y5kN.js.map +0 -1
  51. package/dist/vec3-T2PasQZv.js.map +0 -1
@@ -0,0 +1,53 @@
1
+ //#region src/lite/gpu/agx-tone-mapping.ts
2
+ /**
3
+ * AgX as a Babylon Lite custom `ToneMapping` (`index.d.ts`, `interface ToneMapping`), for the
4
+ * `"agx"` tone-mapping name (`docs/plan/2026-11-gi-phase-1-execution-plan.md`, step G13).
5
+ *
6
+ * The formulation is Benjamin Wendt's "Minimal AgX implementation" (iolite engine, 2023,
7
+ * https://iolite-engine.com/blog_posts/minimal_agx_implementation), a fit of Troy Sobotka's AgX
8
+ * (https://github.com/sobotka/AgX) as Blender 4.0 ships it under "AgX Base": the inset matrix, a
9
+ * log2 encode between -12.47393 and +4.026069 EV, a sixth-order polynomial for the default contrast
10
+ * sigmoid, then the outset matrix. Only the base look is used; Wendt's "golden" and "punchy" looks
11
+ * are not exposed. The sigmoid's output is display-encoded, so the call raises it to the power 2.2:
12
+ * Lite's PBR template, and the HDR output pass after it, encode with `pow(1/2.2)` next.
13
+ *
14
+ * Its own chunk: `./environment.ts` imports it only when a scene asks for `"agx"`, and
15
+ * `./hdr-output.ts`, itself a chunk, imports it for the HDR path. `image-processing-color.ts`
16
+ * carries the same numbers on the CPU for the clear colour.
17
+ */
18
+ /**
19
+ * The curve's `id`, Lite's cache key and change check. Prefixed so a future Lite AgX is not taken
20
+ * for this one. `./environment.ts` repeats the literal rather than importing it, which would put
21
+ * this chunk on the entry path; a unit test keeps the two equal.
22
+ *
23
+ * @internal
24
+ */
25
+ const AGX_TONE_MAPPING_ID = "ignifx-agx";
26
+ /**
27
+ * The module-scope WGSL: the matrices and the two functions. Names carry an `ignifx` prefix so
28
+ * they cannot collide with Lite's own helpers in the PBR template.
29
+ *
30
+ * @internal
31
+ */
32
+ const AGX_HELPERS_WGSL = "const ignifxAgxInset=mat3x3<f32>(vec3<f32>(0.842479062253094,0.0423282422610123,0.0423756549057051),vec3<f32>(0.0784335999999992,0.878468636469772,0.0784336),vec3<f32>(0.0792237451477643,0.0791661274605434,0.879142973793104));const ignifxAgxOutset=mat3x3<f32>(vec3<f32>(1.19687900512017,-0.0528968517574562,-0.0529716355144438),vec3<f32>(-0.0980208811401368,1.15190312990417,-0.0980434501171241),vec3<f32>(-0.0990297440797205,-0.0989611768448433,1.15107367264116));const ignifxAgxMinEv:f32=-12.47393;const ignifxAgxMaxEv:f32=4.026069;fn ignifxAgxContrast(x:vec3<f32>)->vec3<f32>{let x2=x*x;let x4=x2*x2;return 15.5*x4*x2-40.14*x4*x+31.96*x4-6.868*x2*x+0.4298*x2+0.1191*x-0.00232;}fn ignifxAgx(c:vec3<f32>)->vec3<f32>{var v=max(ignifxAgxInset*c,vec3<f32>(1e-10));v=clamp(log2(v),vec3<f32>(ignifxAgxMinEv),vec3<f32>(ignifxAgxMaxEv));v=(v-ignifxAgxMinEv)/(ignifxAgxMaxEv-ignifxAgxMinEv);v=ignifxAgxOutset*ignifxAgxContrast(v);return pow(max(v,vec3<f32>(0.0)),vec3<f32>(2.2));}";
33
+ /**
34
+ * The per-fragment WGSL: the exposure first, as Lite's contract for `callWGSL` requires, then the
35
+ * curve on the working `color`.
36
+ *
37
+ * @internal
38
+ */
39
+ const AGX_CALL_WGSL = "color*=scene.vImageInfos.x;color=ignifxAgx(color);";
40
+ /**
41
+ * The AgX curve object Lite bakes into PBR shaders.
42
+ *
43
+ * @internal
44
+ */
45
+ const AgxToneMapping = {
46
+ id: AGX_TONE_MAPPING_ID,
47
+ helpersWGSL: AGX_HELPERS_WGSL,
48
+ callWGSL: AGX_CALL_WGSL
49
+ };
50
+ //#endregion
51
+ export { AGX_CALL_WGSL, AGX_HELPERS_WGSL, AGX_TONE_MAPPING_ID, AgxToneMapping };
52
+
53
+ //# sourceMappingURL=agx-tone-mapping-Cgt844j6.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agx-tone-mapping-Cgt844j6.js","names":[],"sources":["../src/lite/gpu/agx-tone-mapping.ts"],"sourcesContent":["import type { ToneMapping } from \"@babylonjs/lite\";\n\n/**\n * AgX as a Babylon Lite custom `ToneMapping` (`index.d.ts`, `interface ToneMapping`), for the\n * `\"agx\"` tone-mapping name (`docs/plan/2026-11-gi-phase-1-execution-plan.md`, step G13).\n *\n * The formulation is Benjamin Wendt's \"Minimal AgX implementation\" (iolite engine, 2023,\n * https://iolite-engine.com/blog_posts/minimal_agx_implementation), a fit of Troy Sobotka's AgX\n * (https://github.com/sobotka/AgX) as Blender 4.0 ships it under \"AgX Base\": the inset matrix, a\n * log2 encode between -12.47393 and +4.026069 EV, a sixth-order polynomial for the default contrast\n * sigmoid, then the outset matrix. Only the base look is used; Wendt's \"golden\" and \"punchy\" looks\n * are not exposed. The sigmoid's output is display-encoded, so the call raises it to the power 2.2:\n * Lite's PBR template, and the HDR output pass after it, encode with `pow(1/2.2)` next.\n *\n * Its own chunk: `./environment.ts` imports it only when a scene asks for `\"agx\"`, and\n * `./hdr-output.ts`, itself a chunk, imports it for the HDR path. `image-processing-color.ts`\n * carries the same numbers on the CPU for the clear colour.\n */\n\n/**\n * The curve's `id`, Lite's cache key and change check. Prefixed so a future Lite AgX is not taken\n * for this one. `./environment.ts` repeats the literal rather than importing it, which would put\n * this chunk on the entry path; a unit test keeps the two equal.\n *\n * @internal\n */\nexport const AGX_TONE_MAPPING_ID = \"ignifx-agx\";\n\n/**\n * The module-scope WGSL: the matrices and the two functions. Names carry an `ignifx` prefix so\n * they cannot collide with Lite's own helpers in the PBR template.\n *\n * @internal\n */\nexport const AGX_HELPERS_WGSL: string =\n \"const ignifxAgxInset=mat3x3<f32>(\" +\n \"vec3<f32>(0.842479062253094,0.0423282422610123,0.0423756549057051),\" +\n \"vec3<f32>(0.0784335999999992,0.878468636469772,0.0784336),\" +\n \"vec3<f32>(0.0792237451477643,0.0791661274605434,0.879142973793104));\" +\n \"const ignifxAgxOutset=mat3x3<f32>(\" +\n \"vec3<f32>(1.19687900512017,-0.0528968517574562,-0.0529716355144438),\" +\n \"vec3<f32>(-0.0980208811401368,1.15190312990417,-0.0980434501171241),\" +\n \"vec3<f32>(-0.0990297440797205,-0.0989611768448433,1.15107367264116));\" +\n \"const ignifxAgxMinEv:f32=-12.47393;\" +\n \"const ignifxAgxMaxEv:f32=4.026069;\" +\n \"fn ignifxAgxContrast(x:vec3<f32>)->vec3<f32>{let x2=x*x;let x4=x2*x2;\" +\n \"return 15.5*x4*x2-40.14*x4*x+31.96*x4-6.868*x2*x+0.4298*x2+0.1191*x-0.00232;}\" +\n \"fn ignifxAgx(c:vec3<f32>)->vec3<f32>{\" +\n \"var v=max(ignifxAgxInset*c,vec3<f32>(1e-10));\" +\n \"v=clamp(log2(v),vec3<f32>(ignifxAgxMinEv),vec3<f32>(ignifxAgxMaxEv));\" +\n \"v=(v-ignifxAgxMinEv)/(ignifxAgxMaxEv-ignifxAgxMinEv);\" +\n \"v=ignifxAgxOutset*ignifxAgxContrast(v);\" +\n \"return pow(max(v,vec3<f32>(0.0)),vec3<f32>(2.2));}\";\n\n/**\n * The per-fragment WGSL: the exposure first, as Lite's contract for `callWGSL` requires, then the\n * curve on the working `color`.\n *\n * @internal\n */\nexport const AGX_CALL_WGSL: string = \"color*=scene.vImageInfos.x;color=ignifxAgx(color);\";\n\n/**\n * The AgX curve object Lite bakes into PBR shaders.\n *\n * @internal\n */\nexport const AgxToneMapping: ToneMapping = {\n id: AGX_TONE_MAPPING_ID,\n helpersWGSL: AGX_HELPERS_WGSL,\n callWGSL: AGX_CALL_WGSL,\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA0BA,MAAa,sBAAsB;;;;;;;AAQnC,MAAa,mBACX;;;;;;;AAyBF,MAAa,gBAAwB;;;;;;AAOrC,MAAa,iBAA8B;CACzC,IAAI;CACJ,aAAa;CACb,UAAU;AACZ"}
@@ -0,0 +1,246 @@
1
+ import { addComputeDispatch, addTask, computeStorageBufferBinding, computeStorageTextureBinding, computeTextureBinding, computeUniformBufferBinding, createComputeBindingSet, createComputeDispatch, createComputeShader, createComputeStorageTexture2D, createComputeTask, createComputeTextureResource, createStorageBuffer, createUniformBuffer, updateUniformBuffer } from "@babylonjs/lite";
2
+ //#region src/lite/gpu/auto-exposure.ts
3
+ /**
4
+ * The fraction of counted texels dropped at each end of the histogram before averaging.
5
+ *
6
+ * @internal
7
+ */
8
+ const AUTO_EXPOSURE_PERCENTILES = {
9
+ low: .1,
10
+ high: .9
11
+ };
12
+ /**
13
+ * The `log2` luminance range the histogram covers; bins 1–255 split it evenly.
14
+ *
15
+ * @internal
16
+ */
17
+ const AUTO_EXPOSURE_LOG_RANGE = {
18
+ min: -12,
19
+ max: 12
20
+ };
21
+ /** The task's name in the frame graph. */
22
+ const TASK_NAME = "ignifx:auto-exposure";
23
+ /** The edge of the sample grid: 64×64 texels, four workgroups of 16×16 a side. */
24
+ const GRID = 64;
25
+ /** The workgroup edge of the histogram pass. */
26
+ const WORKGROUP_EDGE = 16;
27
+ /** The bin count; also the average pass's workgroup size. */
28
+ const BINS = 256;
29
+ /** Floats in the parameter block: dt, minEv, maxEv, speedUp, speedDown, compensation, low, high. */
30
+ const PARAM_FLOATS = 8;
31
+ /** The longest frame the adaptation integrates, in seconds, so a stall does not jump the exposure. */
32
+ const MAX_DELTA_SECONDS = .25;
33
+ /**
34
+ * The WGSL shared by both passes.
35
+ *
36
+ * @returns The parameter struct and the histogram constants.
37
+ */
38
+ function sharedWgsl() {
39
+ return [
40
+ "struct Params{dt:f32,minEv:f32,maxEv:f32,speedUp:f32,speedDown:f32,compensation:f32,low:f32,high:f32};",
41
+ `const BINS:u32=${String(BINS)}u;`,
42
+ `const LOG_MIN:f32=${AUTO_EXPOSURE_LOG_RANGE.min.toFixed(1)};`,
43
+ `const LOG_MAX:f32=${AUTO_EXPOSURE_LOG_RANGE.max.toFixed(1)};`
44
+ ].join("\n");
45
+ }
46
+ /**
47
+ * Builds the histogram pass: one texel per invocation, binned in workgroup memory and then added to
48
+ * the global bins.
49
+ *
50
+ * @returns The WGSL, entry point `main`.
51
+ *
52
+ * @internal
53
+ */
54
+ function autoExposureHistogramWgsl() {
55
+ return [
56
+ sharedWgsl(),
57
+ `const GRID:f32=${GRID.toFixed(1)};`,
58
+ "@group(0)@binding(0)var hdrColor:texture_2d<f32>;",
59
+ "@group(0)@binding(1)var<storage,read_write>histogram:array<atomic<u32>,256>;",
60
+ "var<workgroup>localBins:array<atomic<u32>,256>;",
61
+ "fn binOf(luminance:f32)->u32{",
62
+ "if(luminance<exp2(LOG_MIN)){return 0u;}",
63
+ "let t=clamp((log2(luminance)-LOG_MIN)/(LOG_MAX-LOG_MIN),0.0,1.0);",
64
+ "return min(1u+u32(t*f32(BINS-2u)+0.5),BINS-1u);",
65
+ "}",
66
+ `@compute @workgroup_size(${String(WORKGROUP_EDGE)},${String(WORKGROUP_EDGE)})`,
67
+ "fn main(@builtin(global_invocation_id)id:vec3<u32>,@builtin(local_invocation_index)localIndex:u32){",
68
+ "atomicStore(&localBins[localIndex],0u);",
69
+ "workgroupBarrier();",
70
+ "let size=textureDimensions(hdrColor);",
71
+ "let pixel=vec2<u32>((vec2<f32>(id.xy)+0.5)/GRID*vec2<f32>(size));",
72
+ "let texel=textureLoad(hdrColor,min(pixel,size-vec2<u32>(1u)),0).rgb;",
73
+ "let luminance=dot(max(texel,vec3<f32>(0.0)),vec3<f32>(0.2126,0.7152,0.0722));",
74
+ "atomicAdd(&localBins[binOf(luminance)],1u);",
75
+ "workgroupBarrier();",
76
+ "let count=atomicLoad(&localBins[localIndex]);",
77
+ "if(count>0u){atomicAdd(&histogram[localIndex],count);}",
78
+ "}"
79
+ ].join("\n");
80
+ }
81
+ /**
82
+ * Builds the average-and-adapt pass: 256 invocations load and clear the bins, then the first one
83
+ * walks them once.
84
+ *
85
+ * @returns The WGSL, entry point `main`.
86
+ *
87
+ * @internal
88
+ */
89
+ function autoExposureAverageWgsl() {
90
+ return [
91
+ sharedWgsl(),
92
+ "@group(0)@binding(0)var<uniform>params:Params;",
93
+ "@group(0)@binding(1)var<storage,read_write>histogram:array<atomic<u32>,256>;",
94
+ "@group(0)@binding(2)var<storage,read_write>state:array<f32,4>;",
95
+ "@group(0)@binding(3)var exposure:texture_storage_2d<r32float,write>;",
96
+ "var<workgroup>bins:array<u32,256>;",
97
+ `@compute @workgroup_size(${String(BINS)})`,
98
+ "fn main(@builtin(local_invocation_index)localIndex:u32){",
99
+ "bins[localIndex]=atomicExchange(&histogram[localIndex],0u);",
100
+ "workgroupBarrier();",
101
+ "if(localIndex!=0u){return;}",
102
+ "var total=0.0;",
103
+ "for(var i=1u;i<BINS;i++){total+=f32(bins[i]);}",
104
+ "var current=state[0];",
105
+ "var goal=current;",
106
+ "if(total>0.0){",
107
+ "let lowCut=total*params.low;",
108
+ "let highCut=total*params.high;",
109
+ "var seen=0.0;var sum=0.0;var weight=0.0;",
110
+ "for(var i=1u;i<BINS;i++){",
111
+ "let count=f32(bins[i]);",
112
+ "let kept=clamp(seen+count,lowCut,highCut)-clamp(seen,lowCut,highCut);",
113
+ "seen+=count;",
114
+ "let binLog=LOG_MIN+(f32(i)-1.0)/f32(BINS-2u)*(LOG_MAX-LOG_MIN);",
115
+ "sum+=kept*binLog;weight+=kept;",
116
+ "}",
117
+ "if(weight>0.0){goal=clamp(sum/weight,params.minEv,params.maxEv);}",
118
+ "}",
119
+ "if(state[1]<0.5){",
120
+ "if(total>0.0){current=goal;state[1]=1.0;}",
121
+ "}else{",
122
+ "let speed=select(params.speedDown,params.speedUp,goal>current);",
123
+ "current+=(goal-current)*(1.0-exp(-params.dt*max(speed,0.0)));",
124
+ "}",
125
+ "state[0]=current;",
126
+ "let value=select(0.0,log2(0.18)+params.compensation-current,state[1]>0.5);",
127
+ "textureStore(exposure,vec2<i32>(0,0),vec4<f32>(value,0.0,0.0,1.0));",
128
+ "}"
129
+ ].join("\n");
130
+ }
131
+ /**
132
+ * Builds the auto exposure passes over the HDR scene target and appends them to the frame graph.
133
+ *
134
+ * @remarks
135
+ * Call it after the scene task and before the output tasks, so the frame meters the colour it is
136
+ * about to present. The HDR texture's compute view is validated asynchronously by Lite
137
+ * (`createComputeTextureResource`), so the dispatches join the task once that settles; until then
138
+ * the exposure texture reads 0 and the output pass multiplies by 1. A resize swaps the texture
139
+ * behind the facade, which Lite's compute bindings notice by themselves
140
+ * (`lib/compute/compute-texture-resource.js`, `_validateComputeTextureResource`).
141
+ *
142
+ * @param engine - The engine.
143
+ * @param scene - The scene whose frame graph gets the task.
144
+ * @param hdrTexture - The linear scene colour, `rgba16float`.
145
+ * @param options - The knobs.
146
+ * @returns The exposure texture and the per-frame update.
147
+ *
148
+ * @internal
149
+ */
150
+ function installAutoExposure(engine, scene, hdrTexture, options) {
151
+ const task = createComputeTask(engine, TASK_NAME);
152
+ addTask(scene, task);
153
+ const histogram = createStorageBuffer(engine, BINS * 4, {
154
+ label: "ignifx:auto-exposure-histogram",
155
+ writable: true
156
+ });
157
+ const state = createStorageBuffer(engine, 16, {
158
+ label: "ignifx:auto-exposure-state",
159
+ writable: true
160
+ });
161
+ const exposure = createComputeStorageTexture2D(engine, {
162
+ width: 1,
163
+ height: 1,
164
+ format: "r32float",
165
+ label: "ignifx:auto-exposure"
166
+ });
167
+ const params = new Float32Array(PARAM_FLOATS);
168
+ params[1] = options.minEv;
169
+ params[2] = options.maxEv;
170
+ params[3] = options.speedUp;
171
+ params[4] = options.speedDown;
172
+ params[5] = options.compensation;
173
+ params[6] = AUTO_EXPOSURE_PERCENTILES.low;
174
+ params[7] = AUTO_EXPOSURE_PERCENTILES.high;
175
+ const uniforms = createUniformBuffer(engine, params, { label: "ignifx:auto-exposure-params" });
176
+ const histogramShader = createComputeShader(engine, {
177
+ name: "ignifx:auto-exposure-histogram",
178
+ computeSource: autoExposureHistogramWgsl(),
179
+ entryPoint: "main",
180
+ bindings: [computeTextureBinding("hdrColor", {
181
+ group: 0,
182
+ binding: 0,
183
+ sampleType: "unfilterable-float"
184
+ }), computeStorageBufferBinding("histogram", {
185
+ group: 0,
186
+ binding: 1,
187
+ access: "read-write"
188
+ })]
189
+ });
190
+ const averageShader = createComputeShader(engine, {
191
+ name: "ignifx:auto-exposure-average",
192
+ computeSource: autoExposureAverageWgsl(),
193
+ entryPoint: "main",
194
+ bindings: [
195
+ computeUniformBufferBinding("params", {
196
+ group: 0,
197
+ binding: 0
198
+ }),
199
+ computeStorageBufferBinding("histogram", {
200
+ group: 0,
201
+ binding: 1,
202
+ access: "read-write"
203
+ }),
204
+ computeStorageBufferBinding("state", {
205
+ group: 0,
206
+ binding: 2,
207
+ access: "read-write"
208
+ }),
209
+ computeStorageTextureBinding("exposure", {
210
+ group: 0,
211
+ binding: 3,
212
+ format: "r32float"
213
+ })
214
+ ]
215
+ });
216
+ createComputeTextureResource(engine, hdrTexture, { sampleType: "unfilterable-float" }).then((hdrColor) => {
217
+ const groups = GRID / WORKGROUP_EDGE;
218
+ addComputeDispatch(task, createComputeDispatch(histogramShader, createComputeBindingSet(histogramShader, {
219
+ hdrColor,
220
+ histogram
221
+ }), { size: {
222
+ x: groups,
223
+ y: groups
224
+ } }));
225
+ addComputeDispatch(task, createComputeDispatch(averageShader, createComputeBindingSet(averageShader, {
226
+ params: uniforms,
227
+ histogram,
228
+ state,
229
+ exposure
230
+ }), { size: { x: 1 } }));
231
+ });
232
+ let last = -1;
233
+ return {
234
+ exposureTexture: exposure.sampledTexture,
235
+ update() {
236
+ const now = performance.now();
237
+ params[0] = last < 0 ? 0 : Math.min(Math.max((now - last) / 1e3, 0), MAX_DELTA_SECONDS);
238
+ last = now;
239
+ updateUniformBuffer(engine, uniforms, params);
240
+ }
241
+ };
242
+ }
243
+ //#endregion
244
+ export { AUTO_EXPOSURE_LOG_RANGE, AUTO_EXPOSURE_PERCENTILES, autoExposureAverageWgsl, autoExposureHistogramWgsl, installAutoExposure };
245
+
246
+ //# sourceMappingURL=auto-exposure-uzPn0beO.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auto-exposure-uzPn0beO.js","names":[],"sources":["../src/lite/gpu/auto-exposure.ts"],"sourcesContent":["import {\n addComputeDispatch,\n addTask,\n computeStorageBufferBinding,\n computeStorageTextureBinding,\n computeTextureBinding,\n computeUniformBufferBinding,\n createComputeBindingSet,\n createComputeDispatch,\n createComputeShader,\n createComputeStorageTexture2D,\n createComputeTask,\n createComputeTextureResource,\n createStorageBuffer,\n createUniformBuffer,\n updateUniformBuffer,\n} from \"@babylonjs/lite\";\nimport type { EngineContext, SceneContext, Texture2D } from \"@babylonjs/lite\";\n\n/**\n * Auto exposure for the HDR render path (`docs/plan/2026-11-gi-phase-1-execution-plan.md`, step G14).\n * Its own chunk: `../engine.ts` imports it only when `rendering.hdr` and\n * `rendering.autoExposure.enabled` are both on (`CONSTITUTION.md` §2.5).\n *\n * ```text\n * scene ─→ hdr ─→ [histogram] ─→ [average + adapt] ─→ exposure (1×1 r32float) ─→ output pass\n * ```\n *\n * - **Histogram.** A 64×64 grid of texels, spread over the whole target whatever its size, is\n * binned by `log2` luminance into 256 bins; bin 0 takes everything darker than the range, such as\n * a black clear, and is left out of the average.\n * - **Average.** One workgroup reads the bins (and zeroes them for the next frame), drops the\n * darkest and brightest {@link AUTO_EXPOSURE_PERCENTILES} of the counted texels, and averages the\n * rest in `log2` space: the scene's metered EV.\n * - **Adaptation.** The metered EV is clamped to `[minEv, maxEv]` and the current EV eases towards\n * it, `speedUp` when the scene got brighter and `speedDown` when it got darker; the first frame\n * snaps. The pass writes `log2` of the multiplier that maps the current EV to middle grey (0.18),\n * plus `compensation`, so an unwritten texture (0) means \"×1\".\n * - **The output pass** multiplies the linear colour by `exp2` of that texel before the\n * `Environment`'s exposure and curve (`./hdr-output.ts`).\n */\n\n/**\n * The auto exposure knobs, in EV (stops, `log2` units) and per-second rates.\n *\n * @internal\n */\nexport interface AutoExposureOptions {\n /** The darkest metered EV the exposure follows: darker scenes are not brightened further. */\n readonly minEv: number;\n /** The brightest metered EV the exposure follows: brighter scenes are not darkened further. */\n readonly maxEv: number;\n /** Adaptation rate, per second, when the scene gets brighter. */\n readonly speedUp: number;\n /** Adaptation rate, per second, when the scene gets darker. */\n readonly speedDown: number;\n /** Stops added to the computed exposure; positive is brighter. */\n readonly compensation: number;\n}\n\n/**\n * What {@link installAutoExposure} hands the output pass.\n *\n * @internal\n */\nexport interface AutoExposurePass {\n /** A 1×1 `r32float` texture holding `log2` of the exposure multiplier; 0 until the first run. */\n readonly exposureTexture: Texture2D;\n /** The per-frame work: uploads the frame's delta time with the knobs. */\n update(): void;\n}\n\n/**\n * The fraction of counted texels dropped at each end of the histogram before averaging.\n *\n * @internal\n */\nexport const AUTO_EXPOSURE_PERCENTILES = { low: 0.1, high: 0.9 } as const;\n\n/**\n * The `log2` luminance range the histogram covers; bins 1–255 split it evenly.\n *\n * @internal\n */\nexport const AUTO_EXPOSURE_LOG_RANGE = { min: -12, max: 12 } as const;\n\n/** The task's name in the frame graph. */\nconst TASK_NAME = \"ignifx:auto-exposure\";\n\n/** The edge of the sample grid: 64×64 texels, four workgroups of 16×16 a side. */\nconst GRID = 64;\n\n/** The workgroup edge of the histogram pass. */\nconst WORKGROUP_EDGE = 16;\n\n/** The bin count; also the average pass's workgroup size. */\nconst BINS = 256;\n\n/** Floats in the parameter block: dt, minEv, maxEv, speedUp, speedDown, compensation, low, high. */\nconst PARAM_FLOATS = 8;\n\n/** The longest frame the adaptation integrates, in seconds, so a stall does not jump the exposure. */\nconst MAX_DELTA_SECONDS = 0.25;\n\n/**\n * The WGSL shared by both passes.\n *\n * @returns The parameter struct and the histogram constants.\n */\nfunction sharedWgsl(): string {\n return [\n \"struct Params{dt:f32,minEv:f32,maxEv:f32,speedUp:f32,speedDown:f32,compensation:f32,low:f32,high:f32};\",\n `const BINS:u32=${String(BINS)}u;`,\n `const LOG_MIN:f32=${AUTO_EXPOSURE_LOG_RANGE.min.toFixed(1)};`,\n `const LOG_MAX:f32=${AUTO_EXPOSURE_LOG_RANGE.max.toFixed(1)};`,\n ].join(\"\\n\");\n}\n\n/**\n * Builds the histogram pass: one texel per invocation, binned in workgroup memory and then added to\n * the global bins.\n *\n * @returns The WGSL, entry point `main`.\n *\n * @internal\n */\nexport function autoExposureHistogramWgsl(): string {\n return [\n sharedWgsl(),\n `const GRID:f32=${GRID.toFixed(1)};`,\n \"@group(0)@binding(0)var hdrColor:texture_2d<f32>;\",\n \"@group(0)@binding(1)var<storage,read_write>histogram:array<atomic<u32>,256>;\",\n \"var<workgroup>localBins:array<atomic<u32>,256>;\",\n \"fn binOf(luminance:f32)->u32{\",\n \"if(luminance<exp2(LOG_MIN)){return 0u;}\",\n \"let t=clamp((log2(luminance)-LOG_MIN)/(LOG_MAX-LOG_MIN),0.0,1.0);\",\n \"return min(1u+u32(t*f32(BINS-2u)+0.5),BINS-1u);\",\n \"}\",\n `@compute @workgroup_size(${String(WORKGROUP_EDGE)},${String(WORKGROUP_EDGE)})`,\n \"fn main(@builtin(global_invocation_id)id:vec3<u32>,@builtin(local_invocation_index)localIndex:u32){\",\n \"atomicStore(&localBins[localIndex],0u);\",\n \"workgroupBarrier();\",\n \"let size=textureDimensions(hdrColor);\",\n \"let pixel=vec2<u32>((vec2<f32>(id.xy)+0.5)/GRID*vec2<f32>(size));\",\n \"let texel=textureLoad(hdrColor,min(pixel,size-vec2<u32>(1u)),0).rgb;\",\n \"let luminance=dot(max(texel,vec3<f32>(0.0)),vec3<f32>(0.2126,0.7152,0.0722));\",\n \"atomicAdd(&localBins[binOf(luminance)],1u);\",\n \"workgroupBarrier();\",\n \"let count=atomicLoad(&localBins[localIndex]);\",\n \"if(count>0u){atomicAdd(&histogram[localIndex],count);}\",\n \"}\",\n ].join(\"\\n\");\n}\n\n/**\n * Builds the average-and-adapt pass: 256 invocations load and clear the bins, then the first one\n * walks them once.\n *\n * @returns The WGSL, entry point `main`.\n *\n * @internal\n */\nexport function autoExposureAverageWgsl(): string {\n return [\n sharedWgsl(),\n \"@group(0)@binding(0)var<uniform>params:Params;\",\n \"@group(0)@binding(1)var<storage,read_write>histogram:array<atomic<u32>,256>;\",\n \"@group(0)@binding(2)var<storage,read_write>state:array<f32,4>;\",\n \"@group(0)@binding(3)var exposure:texture_storage_2d<r32float,write>;\",\n \"var<workgroup>bins:array<u32,256>;\",\n `@compute @workgroup_size(${String(BINS)})`,\n \"fn main(@builtin(local_invocation_index)localIndex:u32){\",\n \"bins[localIndex]=atomicExchange(&histogram[localIndex],0u);\",\n \"workgroupBarrier();\",\n \"if(localIndex!=0u){return;}\",\n \"var total=0.0;\",\n \"for(var i=1u;i<BINS;i++){total+=f32(bins[i]);}\",\n \"var current=state[0];\",\n \"var goal=current;\",\n \"if(total>0.0){\",\n \"let lowCut=total*params.low;\",\n \"let highCut=total*params.high;\",\n \"var seen=0.0;var sum=0.0;var weight=0.0;\",\n \"for(var i=1u;i<BINS;i++){\",\n \"let count=f32(bins[i]);\",\n \"let kept=clamp(seen+count,lowCut,highCut)-clamp(seen,lowCut,highCut);\",\n \"seen+=count;\",\n \"let binLog=LOG_MIN+(f32(i)-1.0)/f32(BINS-2u)*(LOG_MAX-LOG_MIN);\",\n \"sum+=kept*binLog;weight+=kept;\",\n \"}\",\n \"if(weight>0.0){goal=clamp(sum/weight,params.minEv,params.maxEv);}\",\n \"}\",\n \"if(state[1]<0.5){\",\n \"if(total>0.0){current=goal;state[1]=1.0;}\",\n \"}else{\",\n \"let speed=select(params.speedDown,params.speedUp,goal>current);\",\n \"current+=(goal-current)*(1.0-exp(-params.dt*max(speed,0.0)));\",\n \"}\",\n \"state[0]=current;\",\n \"let value=select(0.0,log2(0.18)+params.compensation-current,state[1]>0.5);\",\n \"textureStore(exposure,vec2<i32>(0,0),vec4<f32>(value,0.0,0.0,1.0));\",\n \"}\",\n ].join(\"\\n\");\n}\n\n/**\n * Builds the auto exposure passes over the HDR scene target and appends them to the frame graph.\n *\n * @remarks\n * Call it after the scene task and before the output tasks, so the frame meters the colour it is\n * about to present. The HDR texture's compute view is validated asynchronously by Lite\n * (`createComputeTextureResource`), so the dispatches join the task once that settles; until then\n * the exposure texture reads 0 and the output pass multiplies by 1. A resize swaps the texture\n * behind the facade, which Lite's compute bindings notice by themselves\n * (`lib/compute/compute-texture-resource.js`, `_validateComputeTextureResource`).\n *\n * @param engine - The engine.\n * @param scene - The scene whose frame graph gets the task.\n * @param hdrTexture - The linear scene colour, `rgba16float`.\n * @param options - The knobs.\n * @returns The exposure texture and the per-frame update.\n *\n * @internal\n */\nexport function installAutoExposure(\n engine: EngineContext,\n scene: SceneContext,\n hdrTexture: Texture2D,\n options: AutoExposureOptions,\n): AutoExposurePass {\n const task = createComputeTask(engine, TASK_NAME);\n addTask(scene, task);\n const histogram = createStorageBuffer(engine, BINS * 4, { label: \"ignifx:auto-exposure-histogram\", writable: true });\n const state = createStorageBuffer(engine, 16, { label: \"ignifx:auto-exposure-state\", writable: true });\n const exposure = createComputeStorageTexture2D(engine, {\n width: 1,\n height: 1,\n format: \"r32float\",\n label: \"ignifx:auto-exposure\",\n });\n const params = new Float32Array(PARAM_FLOATS);\n params[1] = options.minEv;\n params[2] = options.maxEv;\n params[3] = options.speedUp;\n params[4] = options.speedDown;\n params[5] = options.compensation;\n params[6] = AUTO_EXPOSURE_PERCENTILES.low;\n params[7] = AUTO_EXPOSURE_PERCENTILES.high;\n const uniforms = createUniformBuffer(engine, params, { label: \"ignifx:auto-exposure-params\" });\n\n const histogramShader = createComputeShader(engine, {\n name: \"ignifx:auto-exposure-histogram\",\n computeSource: autoExposureHistogramWgsl(),\n entryPoint: \"main\",\n bindings: [\n computeTextureBinding(\"hdrColor\", { group: 0, binding: 0, sampleType: \"unfilterable-float\" }),\n computeStorageBufferBinding(\"histogram\", { group: 0, binding: 1, access: \"read-write\" }),\n ],\n });\n const averageShader = createComputeShader(engine, {\n name: \"ignifx:auto-exposure-average\",\n computeSource: autoExposureAverageWgsl(),\n entryPoint: \"main\",\n bindings: [\n computeUniformBufferBinding(\"params\", { group: 0, binding: 0 }),\n computeStorageBufferBinding(\"histogram\", { group: 0, binding: 1, access: \"read-write\" }),\n computeStorageBufferBinding(\"state\", { group: 0, binding: 2, access: \"read-write\" }),\n computeStorageTextureBinding(\"exposure\", { group: 0, binding: 3, format: \"r32float\" }),\n ],\n });\n\n void createComputeTextureResource(engine, hdrTexture, { sampleType: \"unfilterable-float\" }).then((hdrColor) => {\n const groups = GRID / WORKGROUP_EDGE;\n addComputeDispatch(\n task,\n createComputeDispatch(histogramShader, createComputeBindingSet(histogramShader, { hdrColor, histogram }), {\n size: { x: groups, y: groups },\n }),\n );\n addComputeDispatch(\n task,\n createComputeDispatch(\n averageShader,\n createComputeBindingSet(averageShader, { params: uniforms, histogram, state, exposure }),\n { size: { x: 1 } },\n ),\n );\n });\n\n let last = -1;\n return {\n exposureTexture: exposure.sampledTexture,\n update(): void {\n const now = performance.now();\n params[0] = last < 0 ? 0 : Math.min(Math.max((now - last) / 1000, 0), MAX_DELTA_SECONDS);\n last = now;\n updateUniformBuffer(engine, uniforms, params);\n },\n };\n}\n"],"mappings":"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"}
@@ -0,0 +1,315 @@
1
+ import { createEffectRenderTask, createEffectWrapper, createSurfaceRenderTargetTexture, disposeEffectWrapper, disposeRenderTargetTexture, onRenderTargetTextureResize, setEffectTexture, setEffectUniforms } from "@babylonjs/lite";
2
+ //#region src/lite/gpu/bloom-hdr.ts
3
+ /**
4
+ * HDR bloom (`docs/plan/2026-11-gi-phase-1-execution-plan.md`, step G12): a downsample/upsample
5
+ * chain on the linear `rgba16float` scene target, recorded before the HDR output pass so the glow
6
+ * is tone mapped with the rest of the frame. Its own chunk: `../../render/hdr-bloom-support.ts`
7
+ * imports it only when a `PostProcessStack` asks for bloom under `rendering.hdr`
8
+ * (`CONSTITUTION.md` §2.5).
9
+ *
10
+ * ```text
11
+ * scene → hdr ─ down₀ → mip₀ ─ down₁ → mip₁ … → mip₅
12
+ * mip₄ += up(mip₅) … mip₀ += up(mip₁)
13
+ * hdr = mix(hdr, up(mip₀), intensity) ──→ output pass
14
+ * ```
15
+ *
16
+ * - **Downsample** is the 13-tap filter of Jimenez, "Next generation post processing in Call of
17
+ * Duty: Advanced Warfare" (SIGGRAPH 2014): five overlapping 2×2 boxes, the centre one weighted
18
+ * 0.5. The first level weights each box by `1 / (1 + luma)` (Karis average), so one very bright
19
+ * texel cannot flicker into a frame-sized blob, and applies the optional soft-knee threshold.
20
+ * - **Upsample** is a 9-tap tent, blended into the next larger mip as
21
+ * `mip = mix(mip, tent(smaller), radius)`, so `radius` decides how much of the wide, low mips
22
+ * reaches the image while the weights still sum to one.
23
+ * - **Composite** writes into the HDR target itself through the blend unit, so the output pass's
24
+ * input never changes and nothing is rebound: `hdr = mix(hdr, bloom, intensity)` with no
25
+ * threshold (energy-conserving: the image is redistributed, not brightened), `hdr += bloom ·
26
+ * intensity` with one.
27
+ * - Each mip is a surface-scaled target (`{ surface, scale }`), so a resize reallocates it with
28
+ * the frame graph; the resize callbacks rebind the readers' bind groups.
29
+ * - Lite has no task removal, so {@link HdrBloom.dispose} disables the tasks and makes their
30
+ * `record` a no-op: a later frame-graph rebuild still walks them.
31
+ */
32
+ /**
33
+ * How many mips the chain builds: half resolution down to 1/64.
34
+ *
35
+ * @internal
36
+ */
37
+ const HDR_BLOOM_MIP_COUNT = 6;
38
+ /**
39
+ * The format of every mip; the same as the scene target, so values above 1 survive.
40
+ *
41
+ * @internal
42
+ */
43
+ const HDR_BLOOM_FORMAT = "rgba16float";
44
+ /** Uniform floats per pass: one `vec4`. */
45
+ const UNIFORM_FLOATS = 4;
46
+ /** The blend that turns a pass's `vec4(rgb, a)` into `dst·(1 − a) + rgb`. */
47
+ const MIX_BLEND = {
48
+ color: {
49
+ operation: "add",
50
+ srcFactor: "one",
51
+ dstFactor: "one-minus-src-alpha"
52
+ },
53
+ alpha: {
54
+ operation: "add",
55
+ srcFactor: "zero",
56
+ dstFactor: "one"
57
+ }
58
+ };
59
+ /**
60
+ * The uniform block, texture, sampler and helpers every pass declares.
61
+ *
62
+ * @returns The WGSL.
63
+ */
64
+ function passHeaderWgsl() {
65
+ return [
66
+ "struct BloomUniforms{params:vec4<f32>};",
67
+ "@group(0)@binding(0)var<uniform>bloom:BloomUniforms;",
68
+ "@group(0)@binding(1)var source:texture_2d<f32>;",
69
+ "@group(0)@binding(2)var sourceSampler:sampler;",
70
+ "fn bloomUv(fragment:EffectVertexOutput)->vec2<f32>{return vec2<f32>(fragment.uv.x,1.0-fragment.uv.y);}",
71
+ "fn tap(uv:vec2<f32>,offset:vec2<f32>,texel:vec2<f32>)->vec3<f32>{",
72
+ "let c=textureSampleLevel(source,sourceSampler,uv+offset*texel,0.0).rgb;",
73
+ "return min(max(c,vec3<f32>(0.0)),vec3<f32>(65000.0));",
74
+ "}"
75
+ ].join("\n");
76
+ }
77
+ /**
78
+ * The downsample pass: 13 taps, a Karis average and the soft-knee threshold on the first level.
79
+ *
80
+ * @remarks
81
+ * `params` is `(threshold, knee, isFirstLevel, unused)`.
82
+ *
83
+ * @returns The WGSL, with Lite's `effectFragment` entry point.
84
+ *
85
+ * @internal
86
+ */
87
+ function bloomDownsampleWgsl() {
88
+ return [
89
+ passHeaderWgsl(),
90
+ "fn boxWeight(c:vec3<f32>,first:bool)->f32{",
91
+ "if(!first){return 1.0;}",
92
+ "return 1.0/(1.0+dot(c,vec3<f32>(0.2126,0.7152,0.0722)));",
93
+ "}",
94
+ "fn knee(c:vec3<f32>,threshold:f32,soft:f32)->vec3<f32>{",
95
+ "if(threshold<=0.0){return c;}",
96
+ "let b=max(c.r,max(c.g,c.b));",
97
+ "var s=clamp(b-threshold+soft,0.0,2.0*soft);",
98
+ "s=s*s/(4.0*soft+1e-5);",
99
+ "return c*(max(s,b-threshold)/max(b,1e-5));",
100
+ "}",
101
+ "@fragment fn effectFragment(fragment:EffectVertexOutput)->@location(0)vec4<f32>{",
102
+ "let uv=bloomUv(fragment);",
103
+ "let texel=1.0/vec2<f32>(textureDimensions(source,0));",
104
+ "let first=bloom.params.z>0.5;",
105
+ "let a=tap(uv,vec2<f32>(-2.0,-2.0),texel);let b=tap(uv,vec2<f32>(0.0,-2.0),texel);",
106
+ "let c=tap(uv,vec2<f32>(2.0,-2.0),texel);let d=tap(uv,vec2<f32>(-2.0,0.0),texel);",
107
+ "let e=tap(uv,vec2<f32>(0.0,0.0),texel);let f=tap(uv,vec2<f32>(2.0,0.0),texel);",
108
+ "let g=tap(uv,vec2<f32>(-2.0,2.0),texel);let h=tap(uv,vec2<f32>(0.0,2.0),texel);",
109
+ "let i=tap(uv,vec2<f32>(2.0,2.0),texel);let j=tap(uv,vec2<f32>(-1.0,-1.0),texel);",
110
+ "let k=tap(uv,vec2<f32>(1.0,-1.0),texel);let l=tap(uv,vec2<f32>(-1.0,1.0),texel);",
111
+ "let m=tap(uv,vec2<f32>(1.0,1.0),texel);",
112
+ "let g0=(j+k+l+m)*0.25;let g1=(a+b+d+e)*0.25;let g2=(b+c+e+f)*0.25;",
113
+ "let g3=(d+e+g+h)*0.25;let g4=(e+f+h+i)*0.25;",
114
+ "let w0=0.5*boxWeight(g0,first);let w1=0.125*boxWeight(g1,first);let w2=0.125*boxWeight(g2,first);",
115
+ "let w3=0.125*boxWeight(g3,first);let w4=0.125*boxWeight(g4,first);",
116
+ "var color=(g0*w0+g1*w1+g2*w2+g3*w3+g4*w4)/(w0+w1+w2+w3+w4);",
117
+ "if(first){color=knee(color,bloom.params.x,bloom.params.y);}",
118
+ "return vec4<f32>(color,1.0);",
119
+ "}"
120
+ ].join("\n");
121
+ }
122
+ /**
123
+ * The upsample and composite pass: a 9-tap tent of the smaller mip, scaled, with the blend weight
124
+ * in alpha.
125
+ *
126
+ * @remarks
127
+ * `params` is `(scale, alpha, unused, unused)`; with {@link MIX_BLEND} the target becomes
128
+ * `target·(1 − alpha) + tent·scale`.
129
+ *
130
+ * @returns The WGSL, with Lite's `effectFragment` entry point.
131
+ *
132
+ * @internal
133
+ */
134
+ function bloomUpsampleWgsl() {
135
+ return [
136
+ passHeaderWgsl(),
137
+ "@fragment fn effectFragment(fragment:EffectVertexOutput)->@location(0)vec4<f32>{",
138
+ "let uv=bloomUv(fragment);",
139
+ "let texel=1.0/vec2<f32>(textureDimensions(source,0));",
140
+ "var color=tap(uv,vec2<f32>(0.0,0.0),texel)*4.0;",
141
+ "color+=(tap(uv,vec2<f32>(-1.0,0.0),texel)+tap(uv,vec2<f32>(1.0,0.0),texel)",
142
+ "+tap(uv,vec2<f32>(0.0,-1.0),texel)+tap(uv,vec2<f32>(0.0,1.0),texel))*2.0;",
143
+ "color+=tap(uv,vec2<f32>(-1.0,-1.0),texel)+tap(uv,vec2<f32>(1.0,-1.0),texel)",
144
+ "+tap(uv,vec2<f32>(-1.0,1.0),texel)+tap(uv,vec2<f32>(1.0,1.0),texel);",
145
+ "return vec4<f32>(color*(bloom.params.x/16.0),bloom.params.y);",
146
+ "}"
147
+ ].join("\n");
148
+ }
149
+ /**
150
+ * Writes every pass's uniforms for a tuning.
151
+ *
152
+ * @remarks
153
+ * Laid out as `HDR_BLOOM_MIP_COUNT` downsample blocks, then `HDR_BLOOM_MIP_COUNT − 1` upsample
154
+ * blocks (smallest first), then the composite: the order the tasks run in. Values are clamped to
155
+ * their documented ranges, so an inspector typo cannot blow the frame up.
156
+ *
157
+ * @param tuning - The values.
158
+ * @param out - `(2 · HDR_BLOOM_MIP_COUNT) · 4` floats, overwritten.
159
+ *
160
+ * @internal
161
+ */
162
+ function writeHdrBloomUniforms(tuning, out) {
163
+ const threshold = Math.max(0, tuning.threshold);
164
+ const radius = Math.min(1, Math.max(0, tuning.radius));
165
+ const intensity = Math.max(0, tuning.intensity);
166
+ out.fill(0);
167
+ for (let level = 0; level < 6; level += 1) {
168
+ const base = level * UNIFORM_FLOATS;
169
+ out[base] = threshold;
170
+ out[base + 1] = threshold * .5;
171
+ out[base + 2] = level === 0 ? 1 : 0;
172
+ }
173
+ for (let step = 0; step < 5; step += 1) {
174
+ const base = (6 + step) * UNIFORM_FLOATS;
175
+ out[base] = radius;
176
+ out[base + 1] = radius;
177
+ }
178
+ const composite = 44;
179
+ out[composite] = intensity;
180
+ out[45] = threshold > 0 ? 0 : Math.min(1, intensity);
181
+ }
182
+ /**
183
+ * Builds the HDR bloom chain and inserts it before the HDR output pass.
184
+ *
185
+ * @remarks
186
+ * Before the scene is registered the tasks are only inserted, and `registerScene`'s build records
187
+ * them in order; after, each is recorded on the spot (`buildFrameGraphTask`), as
188
+ * `appendPostProcessTask` in `./post-process.ts` does.
189
+ *
190
+ * @param engine - The engine, which is also the primary surface.
191
+ * @param scene - The scene whose frame graph holds the HDR output pass.
192
+ * @param hdr - The HDR half of the scene's presenter.
193
+ * @param isFrameGraphBuilt - Whether the scene has been registered.
194
+ * @returns The chain, enabled, with zero tuning until {@link HdrBloom.apply} runs.
195
+ *
196
+ * @internal
197
+ */
198
+ function installHdrBloom(engine, scene, hdr, isFrameGraphBuilt) {
199
+ const mips = [];
200
+ for (let level = 0; level < 6; level += 1) mips.push(createSurfaceRenderTargetTexture(engine, {
201
+ lbl: `ignifx:bloom-mip-${String(level)}`,
202
+ format: HDR_BLOOM_FORMAT,
203
+ samples: 1,
204
+ size: {
205
+ surface: engine,
206
+ scale: .5 ** (level + 1)
207
+ }
208
+ }));
209
+ const mipAt = (level) => {
210
+ const mip = mips[level];
211
+ if (mip === void 0) throw new RangeError(`HDR bloom has no mip ${String(level)}.`);
212
+ return mip;
213
+ };
214
+ const downsample = bloomDownsampleWgsl();
215
+ const upsample = bloomUpsampleWgsl();
216
+ const passes = [];
217
+ const addPass = (name, fragmentWGSL, source, target) => {
218
+ const blended = fragmentWGSL === upsample;
219
+ const effect = createEffectWrapper(engine, {
220
+ name,
221
+ fragmentWGSL,
222
+ bindings: [
223
+ {
224
+ name: "bloom",
225
+ binding: 0,
226
+ kind: "uniform",
227
+ uniformByteLength: 16
228
+ },
229
+ {
230
+ name: "source",
231
+ binding: 1,
232
+ kind: "texture"
233
+ },
234
+ {
235
+ name: "sourceSampler",
236
+ binding: 2,
237
+ kind: "sampler",
238
+ textureBinding: 1
239
+ }
240
+ ],
241
+ ...blended ? { blend: MIX_BLEND } : {}
242
+ });
243
+ setEffectTexture(effect, 1, source());
244
+ setEffectUniforms(effect, new Float32Array(UNIFORM_FLOATS));
245
+ const task = createEffectRenderTask({
246
+ name,
247
+ effect,
248
+ target,
249
+ clear: !blended
250
+ }, engine, scene);
251
+ passes.push({
252
+ effect,
253
+ task,
254
+ source
255
+ });
256
+ };
257
+ for (let level = 0; level < 6; level += 1) {
258
+ const source = level === 0 ? () => hdr.sceneTargetTexture.texture : () => mipAt(level - 1).texture;
259
+ addPass(`ignifx:bloom-down-${String(level)}`, downsample, source, mipAt(level).rt);
260
+ }
261
+ for (let level = 4; level >= 0; level -= 1) addPass(`ignifx:bloom-up-${String(level)}`, upsample, () => mipAt(level + 1).texture, mipAt(level).rt);
262
+ addPass("ignifx:bloom-composite", upsample, () => mipAt(0).texture, hdr.sceneTargetTexture.rt);
263
+ for (const pass of passes) hdr.insertLinearTask(pass.task, isFrameGraphBuilt);
264
+ const rebind = () => {
265
+ for (const pass of passes) setEffectTexture(pass.effect, 1, pass.source());
266
+ };
267
+ const unsubscribe = [hdr.sceneTargetTexture, ...mips].map((target) => onRenderTargetTextureResize(target, rebind));
268
+ const uniforms = new Float32Array(passes.length * UNIFORM_FLOATS);
269
+ const scratch = new Float32Array(UNIFORM_FLOATS);
270
+ let isDisposed = false;
271
+ let applied = {
272
+ intensity: NaN,
273
+ radius: NaN,
274
+ threshold: NaN
275
+ };
276
+ return {
277
+ mips: mips.map((mip) => mip.texture),
278
+ taskCount: passes.length,
279
+ setEnabled(enabled) {
280
+ for (const pass of passes) pass.task.executionEnabled = enabled && !isDisposed;
281
+ },
282
+ apply(tuning) {
283
+ if (isDisposed || applied.intensity === tuning.intensity && applied.radius === tuning.radius && applied.threshold === tuning.threshold) return;
284
+ applied = {
285
+ intensity: tuning.intensity,
286
+ radius: tuning.radius,
287
+ threshold: tuning.threshold
288
+ };
289
+ writeHdrBloomUniforms(tuning, uniforms);
290
+ for (let index = 0; index < passes.length; index += 1) {
291
+ const pass = passes[index];
292
+ if (pass === void 0) continue;
293
+ scratch.set(uniforms.subarray(index * UNIFORM_FLOATS, (index + 1) * UNIFORM_FLOATS));
294
+ setEffectUniforms(pass.effect, scratch);
295
+ }
296
+ },
297
+ dispose() {
298
+ if (isDisposed) return;
299
+ isDisposed = true;
300
+ for (const stop of unsubscribe) stop();
301
+ for (const pass of passes) {
302
+ pass.task.executionEnabled = false;
303
+ pass.task.record = inertRecord;
304
+ disposeEffectWrapper(pass.effect);
305
+ }
306
+ for (const mip of mips) disposeRenderTargetTexture(mip);
307
+ }
308
+ };
309
+ }
310
+ /** What a disposed pass records: nothing. */
311
+ function inertRecord() {}
312
+ //#endregion
313
+ export { HDR_BLOOM_FORMAT, HDR_BLOOM_MIP_COUNT, bloomDownsampleWgsl, bloomUpsampleWgsl, installHdrBloom, writeHdrBloomUniforms };
314
+
315
+ //# sourceMappingURL=bloom-hdr-CLtQj-oY.js.map