@ignifx/core 0.21.0 → 0.22.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -0
- package/dist/{agx-tone-mapping-Cgt844j6.js → agx-tone-mapping-CCdGk_ly.js} +2 -2
- package/dist/agx-tone-mapping-CCdGk_ly.js.map +1 -0
- package/dist/auto-exposure-uzPn0beO.js.map +1 -1
- package/dist/{bloom-hdr-CLtQj-oY.js → bloom-hdr-xPwkIdHG.js} +5 -6
- package/dist/bloom-hdr-xPwkIdHG.js.map +1 -0
- package/dist/contact-shadows-T523EXaP.js.map +1 -1
- package/dist/effect-task-CMbuO6Kb.js.map +1 -1
- package/dist/{environment-Bf4aphSb.js → environment-7fJbN402.js} +2 -2
- package/dist/{environment-Bf4aphSb.js.map → environment-7fJbN402.js.map} +1 -1
- package/dist/{gtao-Bpu5-0Ne.js → gtao-CVAYWBEJ.js} +10 -11
- package/dist/gtao-CVAYWBEJ.js.map +1 -0
- package/dist/{hdr-output-DBQwMphy.js → hdr-output-_2TU-jWy.js} +8 -8
- package/dist/hdr-output-_2TU-jWy.js.map +1 -0
- package/dist/index.d.ts +61 -48
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +148 -129
- package/dist/index.js.map +1 -1
- package/dist/{instanced-mesh-instance-B-fXKSrY.js → instanced-mesh-instance-BLdAJTj8.js} +3 -3
- package/dist/instanced-mesh-instance-BLdAJTj8.js.map +1 -0
- package/dist/{light-probe-asset-BqfSrJe9.js → light-probe-asset-DGNIwKNb.js} +2 -2
- package/dist/light-probe-asset-DGNIwKNb.js.map +1 -0
- package/dist/{light-probes-DDojYajw.js → light-probes-C8jharz9.js} +6 -6
- package/dist/light-probes-C8jharz9.js.map +1 -0
- package/dist/lightmaps-BUUIIkt9.js.map +1 -1
- package/dist/material-myMbl9mW.js.map +1 -1
- package/dist/{material-plugin-DapJNj04.js → material-plugin-BBxIy6eo.js} +4 -4
- package/dist/material-plugin-BBxIy6eo.js.map +1 -0
- package/dist/{overlay-CjVgsfrm.js → overlay-DokHzP6_.js} +2 -3
- package/dist/overlay-DokHzP6_.js.map +1 -0
- package/dist/{post-effect-Cu3Enpz7.js → post-effect-DEZD-r0I.js} +3 -3
- package/dist/post-effect-DEZD-r0I.js.map +1 -0
- package/dist/{post-effect-compiler-cCq9lcHt.js → post-effect-compiler-unDD3hod.js} +4 -4
- package/dist/post-effect-compiler-unDD3hod.js.map +1 -0
- package/dist/{prefab-overrides-C2GsgOQc.js → prefab-overrides-Bb7jVm7A.js} +3 -3
- package/dist/prefab-overrides-Bb7jVm7A.js.map +1 -0
- package/dist/{prefab-overrides-htDc_5Po.d.ts → prefab-overrides-CkwXhp5A.d.ts} +84 -64
- package/dist/{prefab-overrides-htDc_5Po.d.ts.map → prefab-overrides-CkwXhp5A.d.ts.map} +1 -1
- package/dist/prefab.d.ts +1 -1
- package/dist/prefab.js +1 -1
- package/dist/{reflection-probe-QkD1Fo_d.js → reflection-probe-C2jcreI1.js} +5 -5
- package/dist/reflection-probe-C2jcreI1.js.map +1 -0
- package/dist/{reflection-probes-CAzSuqf8.js → reflection-probes-BMVQfbhm.js} +10 -10
- package/dist/reflection-probes-BMVQfbhm.js.map +1 -0
- package/dist/{render-path-D11i_7X8.js → render-path-CWXHrRa2.js} +2 -2
- package/dist/render-path-CWXHrRa2.js.map +1 -0
- package/dist/scene-color-passes-CM_T2KF-.js +177 -0
- package/dist/scene-color-passes-CM_T2KF-.js.map +1 -0
- package/dist/scene-inputs-CbTkrkOw.js +489 -0
- package/dist/scene-inputs-CbTkrkOw.js.map +1 -0
- package/dist/{shader-declaration-5q__jycG.js → shader-declaration-BGprFBLq.js} +4 -4
- package/dist/shader-declaration-BGprFBLq.js.map +1 -0
- package/dist/{shader-material-TM4f8eKA.js → shader-material-C9sYMGWw.js} +8 -9
- package/dist/shader-material-C9sYMGWw.js.map +1 -0
- package/dist/{shader-material-CJIDFvSb.js → shader-material-vmkJ25II.js} +3 -3
- package/dist/shader-material-vmkJ25II.js.map +1 -0
- package/dist/{shader-pragma-ljmAbVc2.js → shader-pragma-D0MjCOIg.js} +3 -3
- package/dist/shader-pragma-D0MjCOIg.js.map +1 -0
- package/dist/ssgi-Dk20U3oR.js +492 -0
- package/dist/ssgi-Dk20U3oR.js.map +1 -0
- package/dist/{surface-shader-rpPpeosD.js → surface-shader-BfADq9Wx.js} +6 -6
- package/dist/surface-shader-BfADq9Wx.js.map +1 -0
- package/dist/{taa-BwBZLy11.js → taa-nxVA78Ur.js} +5 -6
- package/dist/taa-nxVA78Ur.js.map +1 -0
- package/dist/vec3-2C3LBZnt.js.map +1 -1
- package/package.json +1 -1
- package/dist/agx-tone-mapping-Cgt844j6.js.map +0 -1
- package/dist/bloom-hdr-CLtQj-oY.js.map +0 -1
- package/dist/gtao-Bpu5-0Ne.js.map +0 -1
- package/dist/hdr-output-DBQwMphy.js.map +0 -1
- package/dist/instanced-mesh-instance-B-fXKSrY.js.map +0 -1
- package/dist/light-probe-asset-BqfSrJe9.js.map +0 -1
- package/dist/light-probes-DDojYajw.js.map +0 -1
- package/dist/material-plugin-DapJNj04.js.map +0 -1
- package/dist/overlay-CjVgsfrm.js.map +0 -1
- package/dist/post-effect-Cu3Enpz7.js.map +0 -1
- package/dist/post-effect-compiler-cCq9lcHt.js.map +0 -1
- package/dist/prefab-overrides-C2GsgOQc.js.map +0 -1
- package/dist/reflection-probe-QkD1Fo_d.js.map +0 -1
- package/dist/reflection-probes-CAzSuqf8.js.map +0 -1
- package/dist/render-path-D11i_7X8.js.map +0 -1
- package/dist/scene-color-passes-B93qTOka.js +0 -88
- package/dist/scene-color-passes-B93qTOka.js.map +0 -1
- package/dist/scene-inputs-BxGOsnIZ.js +0 -318
- package/dist/scene-inputs-BxGOsnIZ.js.map +0 -1
- package/dist/shader-declaration-5q__jycG.js.map +0 -1
- package/dist/shader-material-CJIDFvSb.js.map +0 -1
- package/dist/shader-material-TM4f8eKA.js.map +0 -1
- package/dist/shader-pragma-ljmAbVc2.js.map +0 -1
- package/dist/ssgi-DSnhqotl.js +0 -113
- package/dist/ssgi-DSnhqotl.js.map +0 -1
- package/dist/surface-shader-rpPpeosD.js.map +0 -1
- package/dist/taa-BwBZLy11.js.map +0 -1
package/README.md
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# @ignifx/core
|
|
2
|
+
|
|
3
|
+
The ignifx core: the app and frame loop, world, entities, transforms, components, scripts, schemas, signals, rendering, assets, the scene and prefab format, storage, and the Babylon Lite adapter boundary. Every other `@ignifx/*` package is an extension registered on a core app.
|
|
4
|
+
|
|
5
|
+
Part of [ignifx](https://ignifx.com), a code-first TypeScript game engine for WebGPU-capable browsers and Electron. The engine is pre-1.0: minor releases may include breaking changes.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
pnpm add @ignifx/core
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
`@babylonjs/lite` is a dependency, pinned to one exact version. The `ignifx` umbrella package re-exports core together with the standard extensions.
|
|
14
|
+
`@ignifx/core/prefab` is a second entry point for tools that edit prefab overrides.
|
|
15
|
+
|
|
16
|
+
## Documentation
|
|
17
|
+
|
|
18
|
+
This package ships no skill of its own. The engine guide is the `ignifx` agent skill in the umbrella package: `skills/ignifx/SKILL.md` (`node_modules/ignifx/skills/ignifx/SKILL.md` once `ignifx` is installed). It covers setup, concepts, API references, file formats, recipes and gotchas.
|
|
19
|
+
|
|
20
|
+
## License
|
|
21
|
+
|
|
22
|
+
Apache-2.0 © Astrum Forge Studios
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
//#region src/lite/gpu/agx-tone-mapping.ts
|
|
2
2
|
/**
|
|
3
3
|
* AgX as a Babylon Lite custom `ToneMapping` (`index.d.ts`, `interface ToneMapping`), for the
|
|
4
|
-
* `"agx"` tone-mapping name (`docs/
|
|
4
|
+
* `"agx"` tone-mapping name (`docs/architecture/07-rendering.md` §2.5).
|
|
5
5
|
*
|
|
6
6
|
* The formulation is Benjamin Wendt's "Minimal AgX implementation" (iolite engine, 2023,
|
|
7
7
|
* https://iolite-engine.com/blog_posts/minimal_agx_implementation), a fit of Troy Sobotka's AgX
|
|
@@ -50,4 +50,4 @@ const AgxToneMapping = {
|
|
|
50
50
|
//#endregion
|
|
51
51
|
export { AGX_CALL_WGSL, AGX_HELPERS_WGSL, AGX_TONE_MAPPING_ID, AgxToneMapping };
|
|
52
52
|
|
|
53
|
-
//# sourceMappingURL=agx-tone-mapping-
|
|
53
|
+
//# sourceMappingURL=agx-tone-mapping-CCdGk_ly.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"agx-tone-mapping-CCdGk_ly.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/architecture/07-rendering.md` §2.5).\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"}
|
|
@@ -1 +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":";;;;;;;AA6EA,MAAa,4BAA4B;CAAE,KAAK;CAAK,MAAM;AAAI;;;;;;AAO/D,MAAa,0BAA0B;CAAE,KAAK;CAAK,KAAK;AAAG;;AAG3D,MAAM,YAAY;;AAGlB,MAAM,OAAO;;AAGb,MAAM,iBAAiB;;AAGvB,MAA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AAM,EAAE,GAAG,EAAE,EAAE,CACnB,CACF;CACF,CAAC;CAED,IAAI,OAAO;CACX,OAAO;EACL,iBAAiB,SAAS;EAC1B,SAAe;GACb,MAAM,MAAM,YAAY,IAAI;GAC5B,OAAO,KAAK,OAAO,IAAI,IAAI,KAAK,IAAI,KAAK,KAAK,MAAM,QAAQ,KAAM,CAAC,GAAG,iBAAiB;GACvF,OAAO;GACP,oBAAoB,QAAQ,UAAU,MAAM;EAC9C;CACF;AACF"}
|
|
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/architecture/07-rendering.md` §2.7). Its own chunk:\n * `../engine.ts` imports it only when `rendering.hdr` and `rendering.autoExposure.enabled` are both\n * 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":";;;;;;;AA6EA,MAAa,4BAA4B;CAAE,KAAK;CAAK,MAAM;AAAI;;;;;;AAO/D,MAAa,0BAA0B;CAAE,KAAK;CAAK,KAAK;AAAG;;AAG3D,MAAM,YAAY;;AAGlB,MAAM,OAAO;;AAGb,MAAM,iBAAiB;;AAGvB,MAAM,OAAO;;AAGb,MAAM,eAAe;;AAGrB,MAAM,oBAAoB;;;;;;AAO1B,SAAS,aAAqB;CAC5B,OAAO;EACL;EACA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AC1B,SAAe;GACb,MAAM,MAAM,YAAY,IAAI;GAC5B,OAAO,KAAK,OAAO,IAAI,IAAI,KAAK,IAAI,KAAK,KAAK,MAAM,QAAQ,KAAM,CAAC,GAAG,iBAAiB;GACvF,OAAO;GACP,oBAAoB,QAAQ,UAAU,MAAM;EAC9C;CACF;AACF"}
|
|
@@ -1,11 +1,10 @@
|
|
|
1
1
|
import { createEffectRenderTask, createEffectWrapper, createSurfaceRenderTargetTexture, disposeEffectWrapper, disposeRenderTargetTexture, onRenderTargetTextureResize, setEffectTexture, setEffectUniforms } from "@babylonjs/lite";
|
|
2
2
|
//#region src/lite/gpu/bloom-hdr.ts
|
|
3
3
|
/**
|
|
4
|
-
* HDR bloom (`docs/
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
* (`CONSTITUTION.md` §2.5).
|
|
4
|
+
* HDR bloom (`docs/architecture/07-rendering.md` §2.7): a downsample/upsample chain on the linear
|
|
5
|
+
* `rgba16float` scene target, recorded before the HDR output pass so the glow is tone mapped with
|
|
6
|
+
* the rest of the frame. Its own chunk: `../../render/hdr-bloom-support.ts` imports it only when a
|
|
7
|
+
* `PostProcessStack` asks for bloom under `rendering.hdr` (`CONSTITUTION.md` §2.5).
|
|
9
8
|
*
|
|
10
9
|
* ```text
|
|
11
10
|
* scene → hdr ─ down₀ → mip₀ ─ down₁ → mip₁ … → mip₅
|
|
@@ -312,4 +311,4 @@ function inertRecord() {}
|
|
|
312
311
|
//#endregion
|
|
313
312
|
export { HDR_BLOOM_FORMAT, HDR_BLOOM_MIP_COUNT, bloomDownsampleWgsl, bloomUpsampleWgsl, installHdrBloom, writeHdrBloomUniforms };
|
|
314
313
|
|
|
315
|
-
//# sourceMappingURL=bloom-hdr-
|
|
314
|
+
//# sourceMappingURL=bloom-hdr-xPwkIdHG.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bloom-hdr-xPwkIdHG.js","names":[],"sources":["../src/lite/gpu/bloom-hdr.ts"],"sourcesContent":["import {\n createEffectRenderTask,\n createEffectWrapper,\n createSurfaceRenderTargetTexture,\n disposeEffectWrapper,\n disposeRenderTargetTexture,\n onRenderTargetTextureResize,\n setEffectTexture,\n setEffectUniforms,\n} from \"@babylonjs/lite\";\nimport type { HdrOutputHandle } from \"./render-path.js\";\nimport type {\n EffectWrapper,\n EngineContext,\n RenderTarget,\n RenderTargetTextureResult,\n SceneContext,\n Task,\n Texture2D,\n} from \"@babylonjs/lite\";\n\n/**\n * HDR bloom (`docs/architecture/07-rendering.md` §2.7): a downsample/upsample chain on the linear\n * `rgba16float` scene target, recorded before the HDR output pass so the glow is tone mapped with\n * the rest of the frame. Its own chunk: `../../render/hdr-bloom-support.ts` imports it only when a\n * `PostProcessStack` asks for bloom under `rendering.hdr` (`CONSTITUTION.md` §2.5).\n *\n * ```text\n * scene → hdr ─ down₀ → mip₀ ─ down₁ → mip₁ … → mip₅\n * mip₄ += up(mip₅) … mip₀ += up(mip₁)\n * hdr = mix(hdr, up(mip₀), intensity) ──→ output pass\n * ```\n *\n * - **Downsample** is the 13-tap filter of Jimenez, \"Next generation post processing in Call of\n * Duty: Advanced Warfare\" (SIGGRAPH 2014): five overlapping 2×2 boxes, the centre one weighted\n * 0.5. The first level weights each box by `1 / (1 + luma)` (Karis average), so one very bright\n * texel cannot flicker into a frame-sized blob, and applies the optional soft-knee threshold.\n * - **Upsample** is a 9-tap tent, blended into the next larger mip as\n * `mip = mix(mip, tent(smaller), radius)`, so `radius` decides how much of the wide, low mips\n * reaches the image while the weights still sum to one.\n * - **Composite** writes into the HDR target itself through the blend unit, so the output pass's\n * input never changes and nothing is rebound: `hdr = mix(hdr, bloom, intensity)` with no\n * threshold (energy-conserving: the image is redistributed, not brightened), `hdr += bloom ·\n * intensity` with one.\n * - Each mip is a surface-scaled target (`{ surface, scale }`), so a resize reallocates it with\n * the frame graph; the resize callbacks rebind the readers' bind groups.\n * - Lite has no task removal, so {@link HdrBloom.dispose} disables the tasks and makes their\n * `record` a no-op: a later frame-graph rebuild still walks them.\n */\n\n/**\n * How many mips the chain builds: half resolution down to 1/64.\n *\n * @internal\n */\nexport const HDR_BLOOM_MIP_COUNT = 6;\n\n/**\n * The format of every mip; the same as the scene target, so values above 1 survive.\n *\n * @internal\n */\nexport const HDR_BLOOM_FORMAT: GPUTextureFormat = \"rgba16float\";\n\n/** Uniform floats per pass: one `vec4`. */\nconst UNIFORM_FLOATS = 4;\n\n/**\n * The tuning a `PostProcessStack`'s `bloom` record feeds the chain.\n *\n * @internal\n */\nexport interface HdrBloomTuning {\n /** How much glow is mixed in, 0–1. */\n readonly intensity: number;\n /** How far the glow spreads, 0–1: the weight of each lower mip when it is upsampled. */\n readonly radius: number;\n /** The linear luminance below which nothing glows; `0` lets every pixel contribute. */\n readonly threshold: number;\n}\n\n/**\n * A recorded HDR bloom chain.\n *\n * @internal\n */\nexport interface HdrBloom {\n /** The mip chain, largest first. */\n readonly mips: readonly Texture2D[];\n /** How many frame-graph tasks it recorded. */\n readonly taskCount: number;\n /**\n * Switches every task of the chain on or off.\n *\n * @param enabled - `false` to skip the chain; the HDR target then reaches the output pass as is.\n */\n setEnabled(enabled: boolean): void;\n /**\n * Uploads the tuning, when it changed.\n *\n * @param tuning - The values.\n */\n apply(tuning: HdrBloomTuning): void;\n /** Disables the tasks, makes them inert to a rebuild, and frees the mips and effects. */\n dispose(): void;\n}\n\n/** The blend that turns a pass's `vec4(rgb, a)` into `dst·(1 − a) + rgb`. */\nconst MIX_BLEND: GPUBlendState = {\n color: { operation: \"add\", srcFactor: \"one\", dstFactor: \"one-minus-src-alpha\" },\n alpha: { operation: \"add\", srcFactor: \"zero\", dstFactor: \"one\" },\n};\n\n/**\n * The uniform block, texture, sampler and helpers every pass declares.\n *\n * @returns The WGSL.\n */\nfunction passHeaderWgsl(): string {\n return [\n \"struct BloomUniforms{params:vec4<f32>};\",\n \"@group(0)@binding(0)var<uniform>bloom:BloomUniforms;\",\n \"@group(0)@binding(1)var source:texture_2d<f32>;\",\n \"@group(0)@binding(2)var sourceSampler:sampler;\",\n // Lite's fullscreen triangle puts uv (0,0) at the bottom left; textures start at the top left.\n \"fn bloomUv(fragment:EffectVertexOutput)->vec2<f32>{return vec2<f32>(fragment.uv.x,1.0-fragment.uv.y);}\",\n \"fn tap(uv:vec2<f32>,offset:vec2<f32>,texel:vec2<f32>)->vec3<f32>{\",\n \"let c=textureSampleLevel(source,sourceSampler,uv+offset*texel,0.0).rgb;\",\n \"return min(max(c,vec3<f32>(0.0)),vec3<f32>(65000.0));\",\n \"}\",\n ].join(\"\\n\");\n}\n\n/**\n * The downsample pass: 13 taps, a Karis average and the soft-knee threshold on the first level.\n *\n * @remarks\n * `params` is `(threshold, knee, isFirstLevel, unused)`.\n *\n * @returns The WGSL, with Lite's `effectFragment` entry point.\n *\n * @internal\n */\nexport function bloomDownsampleWgsl(): string {\n return [\n passHeaderWgsl(),\n \"fn boxWeight(c:vec3<f32>,first:bool)->f32{\",\n \"if(!first){return 1.0;}\",\n \"return 1.0/(1.0+dot(c,vec3<f32>(0.2126,0.7152,0.0722)));\",\n \"}\",\n \"fn knee(c:vec3<f32>,threshold:f32,soft:f32)->vec3<f32>{\",\n \"if(threshold<=0.0){return c;}\",\n \"let b=max(c.r,max(c.g,c.b));\",\n \"var s=clamp(b-threshold+soft,0.0,2.0*soft);\",\n \"s=s*s/(4.0*soft+1e-5);\",\n \"return c*(max(s,b-threshold)/max(b,1e-5));\",\n \"}\",\n \"@fragment fn effectFragment(fragment:EffectVertexOutput)->@location(0)vec4<f32>{\",\n \"let uv=bloomUv(fragment);\",\n \"let texel=1.0/vec2<f32>(textureDimensions(source,0));\",\n \"let first=bloom.params.z>0.5;\",\n \"let a=tap(uv,vec2<f32>(-2.0,-2.0),texel);let b=tap(uv,vec2<f32>(0.0,-2.0),texel);\",\n \"let c=tap(uv,vec2<f32>(2.0,-2.0),texel);let d=tap(uv,vec2<f32>(-2.0,0.0),texel);\",\n \"let e=tap(uv,vec2<f32>(0.0,0.0),texel);let f=tap(uv,vec2<f32>(2.0,0.0),texel);\",\n \"let g=tap(uv,vec2<f32>(-2.0,2.0),texel);let h=tap(uv,vec2<f32>(0.0,2.0),texel);\",\n \"let i=tap(uv,vec2<f32>(2.0,2.0),texel);let j=tap(uv,vec2<f32>(-1.0,-1.0),texel);\",\n \"let k=tap(uv,vec2<f32>(1.0,-1.0),texel);let l=tap(uv,vec2<f32>(-1.0,1.0),texel);\",\n \"let m=tap(uv,vec2<f32>(1.0,1.0),texel);\",\n \"let g0=(j+k+l+m)*0.25;let g1=(a+b+d+e)*0.25;let g2=(b+c+e+f)*0.25;\",\n \"let g3=(d+e+g+h)*0.25;let g4=(e+f+h+i)*0.25;\",\n \"let w0=0.5*boxWeight(g0,first);let w1=0.125*boxWeight(g1,first);let w2=0.125*boxWeight(g2,first);\",\n \"let w3=0.125*boxWeight(g3,first);let w4=0.125*boxWeight(g4,first);\",\n \"var color=(g0*w0+g1*w1+g2*w2+g3*w3+g4*w4)/(w0+w1+w2+w3+w4);\",\n \"if(first){color=knee(color,bloom.params.x,bloom.params.y);}\",\n \"return vec4<f32>(color,1.0);\",\n \"}\",\n ].join(\"\\n\");\n}\n\n/**\n * The upsample and composite pass: a 9-tap tent of the smaller mip, scaled, with the blend weight\n * in alpha.\n *\n * @remarks\n * `params` is `(scale, alpha, unused, unused)`; with {@link MIX_BLEND} the target becomes\n * `target·(1 − alpha) + tent·scale`.\n *\n * @returns The WGSL, with Lite's `effectFragment` entry point.\n *\n * @internal\n */\nexport function bloomUpsampleWgsl(): string {\n return [\n passHeaderWgsl(),\n \"@fragment fn effectFragment(fragment:EffectVertexOutput)->@location(0)vec4<f32>{\",\n \"let uv=bloomUv(fragment);\",\n \"let texel=1.0/vec2<f32>(textureDimensions(source,0));\",\n \"var color=tap(uv,vec2<f32>(0.0,0.0),texel)*4.0;\",\n \"color+=(tap(uv,vec2<f32>(-1.0,0.0),texel)+tap(uv,vec2<f32>(1.0,0.0),texel)\",\n \"+tap(uv,vec2<f32>(0.0,-1.0),texel)+tap(uv,vec2<f32>(0.0,1.0),texel))*2.0;\",\n \"color+=tap(uv,vec2<f32>(-1.0,-1.0),texel)+tap(uv,vec2<f32>(1.0,-1.0),texel)\",\n \"+tap(uv,vec2<f32>(-1.0,1.0),texel)+tap(uv,vec2<f32>(1.0,1.0),texel);\",\n \"return vec4<f32>(color*(bloom.params.x/16.0),bloom.params.y);\",\n \"}\",\n ].join(\"\\n\");\n}\n\n/**\n * Writes every pass's uniforms for a tuning.\n *\n * @remarks\n * Laid out as `HDR_BLOOM_MIP_COUNT` downsample blocks, then `HDR_BLOOM_MIP_COUNT − 1` upsample\n * blocks (smallest first), then the composite: the order the tasks run in. Values are clamped to\n * their documented ranges, so an inspector typo cannot blow the frame up.\n *\n * @param tuning - The values.\n * @param out - `(2 · HDR_BLOOM_MIP_COUNT) · 4` floats, overwritten.\n *\n * @internal\n */\nexport function writeHdrBloomUniforms(tuning: HdrBloomTuning, out: Float32Array): void {\n const threshold = Math.max(0, tuning.threshold);\n const radius = Math.min(1, Math.max(0, tuning.radius));\n const intensity = Math.max(0, tuning.intensity);\n out.fill(0);\n for (let level = 0; level < HDR_BLOOM_MIP_COUNT; level += 1) {\n const base = level * UNIFORM_FLOATS;\n out[base] = threshold;\n out[base + 1] = threshold * 0.5;\n out[base + 2] = level === 0 ? 1 : 0;\n }\n for (let step = 0; step < HDR_BLOOM_MIP_COUNT - 1; step += 1) {\n const base = (HDR_BLOOM_MIP_COUNT + step) * UNIFORM_FLOATS;\n out[base] = radius;\n out[base + 1] = radius;\n }\n const composite = (2 * HDR_BLOOM_MIP_COUNT - 1) * UNIFORM_FLOATS;\n out[composite] = intensity;\n // With a threshold only the highlights are in the chain, so the glow is added; without one the\n // chain holds the whole image and mixing keeps the frame's energy.\n out[composite + 1] = threshold > 0 ? 0 : Math.min(1, intensity);\n}\n\n/** One pass of the chain: its effect, the texture it reads and its task. */\ninterface BloomPass {\n readonly effect: EffectWrapper;\n readonly task: Task;\n readonly source: () => Texture2D;\n}\n\n/**\n * Builds the HDR bloom chain and inserts it before the HDR output pass.\n *\n * @remarks\n * Before the scene is registered the tasks are only inserted, and `registerScene`'s build records\n * them in order; after, each is recorded on the spot (`buildFrameGraphTask`), as\n * `appendPostProcessTask` in `./post-process.ts` does.\n *\n * @param engine - The engine, which is also the primary surface.\n * @param scene - The scene whose frame graph holds the HDR output pass.\n * @param hdr - The HDR half of the scene's presenter.\n * @param isFrameGraphBuilt - Whether the scene has been registered.\n * @returns The chain, enabled, with zero tuning until {@link HdrBloom.apply} runs.\n *\n * @internal\n */\nexport function installHdrBloom(\n engine: EngineContext,\n scene: SceneContext,\n hdr: HdrOutputHandle,\n isFrameGraphBuilt: boolean,\n): HdrBloom {\n const mips: RenderTargetTextureResult[] = [];\n for (let level = 0; level < HDR_BLOOM_MIP_COUNT; level += 1) {\n mips.push(\n createSurfaceRenderTargetTexture(engine, {\n lbl: `ignifx:bloom-mip-${String(level)}`,\n format: HDR_BLOOM_FORMAT,\n samples: 1,\n size: { surface: engine, scale: 0.5 ** (level + 1) },\n }),\n );\n }\n const mipAt = (level: number): RenderTargetTextureResult => {\n const mip = mips[level];\n if (mip === undefined) {\n throw new RangeError(`HDR bloom has no mip ${String(level)}.`);\n }\n return mip;\n };\n const downsample = bloomDownsampleWgsl();\n const upsample = bloomUpsampleWgsl();\n const passes: BloomPass[] = [];\n const addPass = (name: string, fragmentWGSL: string, source: () => Texture2D, target: RenderTarget): void => {\n const blended = fragmentWGSL === upsample;\n const effect = createEffectWrapper(engine, {\n name,\n fragmentWGSL,\n bindings: [\n { name: \"bloom\", binding: 0, kind: \"uniform\", uniformByteLength: UNIFORM_FLOATS * 4 },\n { name: \"source\", binding: 1, kind: \"texture\" },\n { name: \"sourceSampler\", binding: 2, kind: \"sampler\", textureBinding: 1 },\n ],\n ...(blended ? { blend: MIX_BLEND } : {}),\n });\n setEffectTexture(effect, 1, source());\n setEffectUniforms(effect, new Float32Array(UNIFORM_FLOATS));\n const task = createEffectRenderTask({ name, effect, target, clear: !blended }, engine, scene);\n passes.push({ effect, task, source });\n };\n for (let level = 0; level < HDR_BLOOM_MIP_COUNT; level += 1) {\n const source =\n level === 0 ? (): Texture2D => hdr.sceneTargetTexture.texture : (): Texture2D => mipAt(level - 1).texture;\n addPass(`ignifx:bloom-down-${String(level)}`, downsample, source, mipAt(level).rt);\n }\n for (let level = HDR_BLOOM_MIP_COUNT - 2; level >= 0; level -= 1) {\n addPass(`ignifx:bloom-up-${String(level)}`, upsample, () => mipAt(level + 1).texture, mipAt(level).rt);\n }\n addPass(\"ignifx:bloom-composite\", upsample, () => mipAt(0).texture, hdr.sceneTargetTexture.rt);\n\n // After every linear task already in place (TAA among them), right before the output pass.\n for (const pass of passes) {\n hdr.insertLinearTask(pass.task, isFrameGraphBuilt);\n }\n\n // A resize swaps the textures behind the facades; a wrapper's cached bind group keeps the old\n // view until a texture write marks it dirty.\n const rebind = (): void => {\n for (const pass of passes) {\n setEffectTexture(pass.effect, 1, pass.source());\n }\n };\n const unsubscribe = [hdr.sceneTargetTexture, ...mips].map((target) => onRenderTargetTextureResize(target, rebind));\n\n const uniforms = new Float32Array(passes.length * UNIFORM_FLOATS);\n const scratch = new Float32Array(UNIFORM_FLOATS);\n let isDisposed = false;\n let applied: HdrBloomTuning = { intensity: Number.NaN, radius: Number.NaN, threshold: Number.NaN };\n return {\n mips: mips.map((mip) => mip.texture),\n taskCount: passes.length,\n setEnabled(enabled: boolean): void {\n for (const pass of passes) {\n pass.task.executionEnabled = enabled && !isDisposed;\n }\n },\n apply(tuning: HdrBloomTuning): void {\n if (\n isDisposed ||\n (applied.intensity === tuning.intensity &&\n applied.radius === tuning.radius &&\n applied.threshold === tuning.threshold)\n ) {\n return;\n }\n applied = { intensity: tuning.intensity, radius: tuning.radius, threshold: tuning.threshold };\n writeHdrBloomUniforms(tuning, uniforms);\n for (let index = 0; index < passes.length; index += 1) {\n const pass = passes[index];\n if (pass === undefined) {\n continue;\n }\n scratch.set(uniforms.subarray(index * UNIFORM_FLOATS, (index + 1) * UNIFORM_FLOATS));\n setEffectUniforms(pass.effect, scratch);\n }\n },\n dispose(): void {\n if (isDisposed) {\n return;\n }\n isDisposed = true;\n for (const stop of unsubscribe) {\n stop();\n }\n for (const pass of passes) {\n pass.task.executionEnabled = false;\n // Lite cannot remove a task, and a frame-graph rebuild records every task, disabled or not.\n pass.task.record = inertRecord;\n disposeEffectWrapper(pass.effect);\n }\n for (const mip of mips) {\n disposeRenderTargetTexture(mip);\n }\n },\n };\n}\n\n/** What a disposed pass records: nothing. */\nfunction inertRecord(): void {\n // Intentionally empty; see `HdrBloom.dispose`.\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuDA,MAAa,sBAAsB;;;;;;AAOnC,MAAa,mBAAqC;;AAGlD,MAAM,iBAAiB;;AA2CvB,MAAM,YAA2B;CAC/B,OAAO;EAAE,WAAW;EAAO,WAAW;EAAO,WAAW;CAAsB;CAC9E,OAAO;EAAE,WAAW;EAAO,WAAW;EAAQ,WAAW;CAAM;AACjE;;;;;;AAOA,SAAS,iBAAyB;CAChC,OAAO;EACL;EACA;EACA;EACA;EAEA;EACA;EACA;EACA;EACA;CACF,CAAC,CAAC,KAAK,IAAI;AACb;;;;;;;;;;;AAYA,SAAgB,sBAA8B;CAC5C,OAAO;EACL,eAAe;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CAAC,CAAC,KAAK,IAAI;AACb;;;;;;;;;;;;;AAcA,SAAgB,oBAA4B;CAC1C,OAAO;EACL,eAAe;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CAAC,CAAC,KAAK,IAAI;AACb;;;;;;;;;;;;;;AAeA,SAAgB,sBAAsB,QAAwB,KAA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PostProcessTask } from \"@babylonjs/lite\";\nimport type { SceneColorPass } from \"./scene-color-passes.js\";\nimport type {\n Camera,\n DirectionalLight,\n EngineContext,\n RenderTarget,\n SceneContext,\n ScreenSpaceContactShadowsPostProcessTask,\n} from \"@babylonjs/lite\";\n\n/**\n * Screen-space contact shadows
|
|
1
|
+
{"version":3,"file":"contact-shadows-T523EXaP.js","names":[],"sources":["../src/lite/gpu/contact-shadows.ts"],"sourcesContent":["import { createScreenSpaceContactShadowsPostProcessTask } from \"@babylonjs/lite\";\nimport type { SceneColorPass } from \"./scene-color-passes.js\";\nimport type {\n Camera,\n DirectionalLight,\n EngineContext,\n RenderTarget,\n SceneContext,\n ScreenSpaceContactShadowsPostProcessTask,\n} from \"@babylonjs/lite\";\n\n/**\n * Screen-space contact shadows: Lite's `createScreenSpaceContactShadowsPostProcessTask`\n * (`index.d.ts` 3672), fed the shared scene-input depth and run as a scene-colour pass\n * (`./scene-color-passes.ts`). Its own chunk, loaded only while a `PostProcessStack` enables\n * `contactShadows` (`CONSTITUTION.md` §2.5).\n *\n * Lite marches from each pixel towards one light through the depth buffer and multiplies the colour\n * by the occlusion it finds, so the light is the scene's main directional light: the first one that\n * casts shadows, else the first one. With none, the task runs disabled (its composite copies).\n */\n\n/**\n * The tuning a recorded pass follows live.\n *\n * @internal\n */\nexport interface ContactShadowsTuning {\n /** How dark a contact gets, 0 to 4. */\n readonly intensity: number;\n /** How far each ray marches, in world units. */\n readonly length: number;\n /** How thick a surface is assumed to be behind its depth, in world units. */\n readonly thickness: number;\n /** March steps per pixel, 1 to 64. */\n readonly samples: number;\n}\n\n/**\n * A contact-shadows pass: its task once created, and its per-frame update.\n *\n * @internal\n */\nexport interface ContactShadowsPass extends SceneColorPass {\n /**\n * Writes the tuning and the main light's direction onto the task.\n *\n * @param tuning - The stack's `contactShadows` record.\n */\n update(tuning: ContactShadowsTuning): void;\n}\n\n/** The pass's frame-graph task name. */\nconst TASK_NAME = \"ignifx:contact-shadows\";\n\n/**\n * Creates a contact-shadows pass.\n *\n * @param engine - The engine.\n * @param scene - The scene, whose lights are read every frame.\n * @param depth - The scene-input depth target.\n * @param camera - The camera the depth was drawn from.\n * @param tuning - The initial tuning.\n * @returns The pass.\n *\n * @internal\n */\nexport function createContactShadowsPass(\n engine: EngineContext,\n scene: SceneContext,\n depth: RenderTarget,\n camera: Camera,\n tuning: ContactShadowsTuning,\n): ContactShadowsPass {\n // Lite keeps this object and reads it every frame (`lib/post-process/screen-space-contact-shadows.js`).\n const lightDirection = { x: 0, y: -1, z: 0 };\n let task: ScreenSpaceContactShadowsPostProcessTask | null = null;\n return {\n create(source: RenderTarget, target: RenderTarget): ScreenSpaceContactShadowsPostProcessTask {\n task = createScreenSpaceContactShadowsPostProcessTask(\n {\n name: TASK_NAME,\n sourceTexture: source,\n depthTexture: depth,\n targetTexture: target,\n camera,\n lightDirection,\n intensity: tuning.intensity,\n maxDistance: tuning.length,\n thickness: tuning.thickness,\n stepCount: tuning.samples,\n },\n engine,\n scene,\n );\n return task;\n },\n update(next: ContactShadowsTuning): void {\n if (task === null) {\n return;\n }\n task.intensity = next.intensity;\n task.maxDistance = next.length;\n task.thickness = next.thickness;\n task.stepCount = next.samples;\n const light = mainDirectionalLight(scene);\n task.enabled = light !== null;\n if (light !== null) {\n lightDirection.x = light.direction.x;\n lightDirection.y = light.direction.y;\n lightDirection.z = light.direction.z;\n }\n },\n };\n}\n\n/**\n * The scene's main directional light: the first that casts shadows, else the first.\n *\n * @param scene - The scene.\n * @returns The light, or `null` when the scene has none.\n */\nfunction mainDirectionalLight(scene: SceneContext): DirectionalLight | null {\n let first: DirectionalLight | null = null;\n for (const light of scene.lights) {\n if (!isDirectional(light)) {\n continue;\n }\n if (light.shadowGenerator !== undefined) {\n return light;\n }\n first ??= light;\n }\n return first;\n}\n\n/**\n * Whether a scene light is directional.\n *\n * @param light - The light.\n * @param light.lightType - Its type tag.\n * @returns `true` for a directional light.\n */\nfunction isDirectional(light: { readonly lightType: string }): light is DirectionalLight {\n return light.lightType === \"directional\";\n}\n"],"mappings":";;;AAqDA,MAAM,YAAY;;;;;;;;;;;;;AAclB,SAAgB,yBACd,QACA,OACA,OACA,QACA,QACoB;CAEpB,MAAM,iBAAiB;EAAE,GAAG;EAAG,GAAG;EAAI,GAAG;CAAE;CAC3C,IAAI,OAAwD;CAC5D,OAAO;EACL,OAAO,QAAsB,QAAgE;GAC3F,OAAO,+CACL;IACE,MAAM;IACN,eAAe;IACf,cAAc;IACd,eAAe;IACf;IACA;IACA,WAAW,OAAO;IAClB,aAAa,OAAO;IACpB,WAAW,OAAO;IAClB,WAAW,OAAO;GACpB,GACA,QACA,KACF;GACA,OAAO;EACT;EACA,OAAO,MAAkC;GACvC,IAAI,SAAS,MACX;GAEF,KAAK,YAAY,KAAK;GACtB,KAAK,cAAc,KAAK;GACxB,KAAK,YAAY,KAAK;GACtB,KAAK,YAAY,KAAK;GACtB,MAAM,QAAQ,qBAAqB,KAAK;GACxC,KAAK,UAAU,UAAU;GACzB,IAAI,UAAU,MAAM;IAClB,eAAe,IAAI,MAAM,UAAU;IACnC,eAAe,IAAI,MAAM,UAAU;IACnC,eAAe,IAAI,MAAM,UAAU;GACrC;EACF;CACF;AACF;;;;;;;AAQA,SAAS,qBAAqB,OAA8C;CAC1E,IAAI,QAAiC;CACrC,KAAK,MAAM,SAAS,MAAM,QAAQ;EAChC,IAAI,CAAC,cAAc,KAAK,GACtB;EAEF,IAAI,MAAM,oBAAoB,KAAA,GAC5B,OAAO;EAET,UAAU;CACZ;CACA,OAAO;AACT;;;;;;;;AASA,SAAS,cAAc,OAAkE;CACvF,OAAO,MAAM,cAAc;AAC7B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"effect-task-CMbuO6Kb.js","names":[],"sources":["../src/lite/gpu/effect-task.ts"],"sourcesContent":["import {\n createCopyToTextureTask,\n createEffectRenderTask,\n createEffectWrapper,\n createRenderTargetTexture,\n disposeEffectWrapper,\n setEffectTexture,\n setEffectUniforms,\n} from \"@babylonjs/lite\";\nimport type {\n EffectBindingLayout,\n EffectWrapper,\n EngineContext,\n RenderTarget,\n SceneContext,\n Task,\n Texture2D,\n} from \"@babylonjs/lite\";\n\n/**\n * The Babylon Lite half of custom post effects (`docs/plan/2026-09-terrain-particles-shaders.md`\n * §3.3).\n *\n * Everything here is `@internal` and every entry point needs a device.\n *\n * Lite's only public custom-pass path is `createEffectWrapper` + `createEffectRenderTask`\n * (`index.d.ts` 2461, 2452) — the generic `PostProcessTaskConfig` is not exported. The task writes a\n * `RenderTarget` while the wrapper **samples a `Texture2D`**, and a `createRenderTarget` target\n * exposes no `Texture2D`, so a chain that mixes built-ins with custom effects needs links that are\n * both: {@link createEffectChainLink} is `createRenderTargetTexture` (2998), which hands back\n * `{ rt, texture }`.\n *\n * Those links are **eager**, which the chain depends on twice over: an eager target is never\n * reallocated and `disposeRenderTarget` refuses to free one (`lib/engine/render-target.js` 20, 48),\n * so a wrapper's cached bind group cannot end up holding a destroyed view, and an effect that writes\n * the equally eager swapchain can be disposed without destroying it. The price is that a link is\n * fixed size (Lite error 571), so a canvas resize rebuilds the chain.\n *\n * Two more Lite rules: `getEffectPipeline` hard-codes the entry-point names `effectFullscreenVertex`\n * and `effectFragment` and prepends its own vertex module — which declares `EffectVertexOutput` — to\n * the fragment source (`lib/effect/effect-renderer.js` 258-260, 274); and a `sampler` binding with\n * no `textureBinding` falls back to the wrapper's first texture slot (line 342), so\n * {@link createCustomEffect} sets `textureBinding` on every sampler.\n */\n\n/**\n * A Babylon Lite fullscreen effect, re-exported under an ignifx name.\n *\n * @remarks\n * Unstable; excluded from the stability guarantees of `CONSTITUTION.md` Article IV.\n *\n * @internal\n */\nexport type LiteEffect = EffectWrapper;\n\n/**\n * A colour target that is also a sampled texture: what a chain of custom effects ping-pongs through.\n *\n * @internal\n */\nexport interface EffectChainLink {\n /** The render target a task writes. */\n readonly target: RenderTarget;\n /** The sampled texture the next effect reads. */\n readonly texture: Texture2D;\n}\n\n/**\n * What {@link createCustomEffect} needs.\n *\n * @internal\n */\nexport interface CustomEffectOptions {\n /** A debug label for the GPU resources. */\n readonly name: string;\n /** The whole fragment module, including its `effectFragment` entry point. */\n readonly fragmentWGSL: string;\n /** How large the effect's single uniform buffer is, in bytes. */\n readonly uniformByteLength: number;\n /** Whether each declared texture beyond the chain input is a `2d-array` view. */\n readonly declaredTextures: readonly { readonly array: boolean }[];\n}\n\n/**\n * Creates one fullscreen effect: its shader module, bind-group layout, uniform buffer, and texture\n * slots.\n *\n * @remarks\n * The binding layout is fixed and shared with the generated WGSL: `0` the uniform block, `1` and `2`\n * the chain's current colour and its sampler, then a texture/sampler pair per declared texture.\n * Nothing is compiled here — Lite builds the pipeline lazily, on the first `record()`.\n *\n * @param engine - The engine that owns the GPU resources.\n * @param options - The shader, the uniform size, and the declared textures.\n * @returns The effect wrapper. Bind its textures before recording a task for it.\n *\n * @internal\n */\nexport function createCustomEffect(engine: EngineContext, options: CustomEffectOptions): EffectWrapper {\n const bindings: EffectBindingLayout[] = [\n { name: \"shaderUniforms\", binding: 0, kind: \"uniform\", uniformByteLength: options.uniformByteLength },\n { name: \"inputTexture\", binding: 1, kind: \"texture\" },\n { name: \"inputTextureSampler\", binding: 2, kind: \"sampler\", textureBinding: 1 },\n ];\n for (let index = 0; index < options.declaredTextures.length; index += 1) {\n const declared = options.declaredTextures[index];\n const binding = 3 + index * 2;\n const layout: EffectBindingLayout = { name: `texture${String(index)}`, binding, kind: \"texture\" };\n if (declared?.array === true) {\n // The bind-group layout reads `viewDimension` straight off this field\n // (`bindingLayoutEntry`, `lib/effect/effect-renderer.js` 302).\n bindings.push({ ...layout, viewDimension: \"2d-array\" });\n } else {\n bindings.push(layout);\n }\n bindings.push({ name: `sampler${String(index)}`, binding: binding + 1, kind: \"sampler\", textureBinding: binding });\n }\n return createEffectWrapper(engine, { name: options.name, fragmentWGSL: options.fragmentWGSL, bindings });\n}\n\n/**\n * Binds a texture to one of an effect's texture slots.\n *\n * @remarks\n * Also marks the wrapper's bind group dirty, which is the only thing that does, so this is what has\n * to be called after a link is rebuilt or a declared texture is swapped.\n *\n * @param effect - The effect wrapper.\n * @param binding - The binding index.\n * @param texture - The texture.\n *\n * @internal\n */\nexport function bindCustomEffectTexture(effect: EffectWrapper, binding: number, texture: Texture2D): void {\n setEffectTexture(effect, binding, texture);\n}\n\n/**\n * Uploads an effect's uniform bytes.\n *\n * @remarks\n * A plain `queue.writeBuffer`, so it is safe to call every frame and costs nothing on a frame where\n * the bytes did not change — which is why the caller compares first.\n *\n * @param effect - The effect wrapper.\n * @param data - The bytes; no longer than the declared `uniformByteLength`.\n *\n * @internal\n */\nexport function writeCustomEffectUniforms(effect: EffectWrapper, data: Float32Array): void {\n setEffectUniforms(effect, data);\n}\n\n/**\n * Records one fullscreen effect as a frame-graph task writing `target`.\n *\n * @remarks\n * The task clears its target and draws a fullscreen triangle, so the whole target is overwritten and\n * the clear costs nothing. Append it with `appendPostProcessTask` from `./post-process.ts`.\n *\n * @param engine - The engine.\n * @param scene - The scene whose frame graph will hold it.\n * @param name - A debug label.\n * @param effect - The effect wrapper, with every texture already bound.\n * @param target - The colour target it writes; the surface swapchain for the last effect.\n * @returns The task.\n *\n * @internal\n */\nexport function createCustomEffectTask(\n engine: EngineContext,\n scene: SceneContext,\n name: string,\n effect: EffectWrapper,\n target: RenderTarget,\n): Task {\n return createEffectRenderTask({ name, effect, target, clear: true }, engine, scene);\n}\n\n/**\n * Frees an effect wrapper's GPU resources.\n *\n * @param effect - The effect wrapper.\n *\n * @internal\n */\nexport function disposeCustomEffect(effect: EffectWrapper): void {\n disposeEffectWrapper(effect);\n}\n\n/**\n * Creates one ping-pong link of an effect chain: a colour target that is also a sampled texture.\n *\n * @remarks\n * Eager and fixed size, which Lite requires of a sampled render target (error 571) and which the\n * chain needs anyway, because an effect wrapper caches the texture view in its bind group. A resize\n * therefore rebuilds the chain rather than reallocating the link.\n *\n * @param engine - The engine that owns the texture.\n * @param format - The colour format; the surface's, so a built-in pass can write it.\n * @param width - The width in backing-store pixels.\n * @param height - The height in backing-store pixels.\n * @param label - A debug label.\n * @returns The link.\n *\n * @internal\n */\nexport function createEffectChainLink(\n engine: EngineContext,\n format: GPUTextureFormat,\n width: number,\n height: number,\n label: string,\n): EffectChainLink {\n const created = createRenderTargetTexture(engine, {\n lbl: label,\n format,\n samples: 1,\n size: { width: Math.max(1, width), height: Math.max(1, height) },\n });\n return { target: created.rt, texture: created.texture };\n}\n\n/**\n * Frees a chain link's GPU texture.\n *\n * @remarks\n * `disposeRenderTarget` refuses to free an eager target, which is what keeps\n * `EffectRenderTask.dispose` from destroying a shared link, so the texture has to be destroyed here\n * instead.\n *\n * @param link - The link.\n *\n * @internal\n */\nexport function disposeEffectChainLink(link: EffectChainLink): void {\n link.texture.texture.destroy();\n}\n\n/**\n * Records a task that copies one colour target into another.\n *\n * @remarks\n * The chain uses it once, and only when its **first** effect is a custom one: the scene colour the\n * render path drew into is a canvas-sized, non-eager `RenderTarget` with no `Texture2D`, so it\n * cannot be sampled by an effect wrapper. One copy into a link makes it samplable. A chain that\n * starts with bloom or SMAA needs no copy, because those write a link directly.\n *\n * @param engine - The engine.\n * @param scene - The scene whose frame graph will hold it.\n * @param name - A debug label.\n * @param source - The target to read.\n * @param target - The target to write; externally owned, so the task does not rebuild or free it.\n * @returns The task.\n *\n * @internal\n */\nexport function createChainCopyTask(\n engine: EngineContext,\n scene: SceneContext,\n name: string,\n source: RenderTarget,\n target: RenderTarget,\n): Task {\n return createCopyToTextureTask(\n { name, sourceTexture: source, targetTexture: target, ownsTargetTexture: false },\n engine,\n scene,\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAkGA,SAAgB,mBAAmB,QAAuB,SAA6C;CACrG,MAAM,WAAkC;EACtC;GAAE,MAAM;GAAkB,SAAS;GAAG,MAAM;GAAW,mBAAmB,QAAQ;EAAkB;EACpG;GAAE,MAAM;GAAgB,SAAS;GAAG,MAAM;EAAU;EACpD;GAAE,MAAM;GAAu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AAS,QAAQ;CAAQ;AACxD;;;;;;;;;;;;;AAcA,SAAgB,uBAAuB,MAA6B;CAClE,KAAK,QAAQ,QAAQ,QAAQ;AAC/B;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,oBACd,QACA,OACA,MACA,QACA,QACM;CACN,OAAO,wBACL;EAAE;EAAM,eAAe;EAAQ,eAAe;EAAQ,mBAAmB;CAAM,GAC/E,QACA,KACF;AACF"}
|
|
1
|
+
{"version":3,"file":"effect-task-CMbuO6Kb.js","names":[],"sources":["../src/lite/gpu/effect-task.ts"],"sourcesContent":["import {\n createCopyToTextureTask,\n createEffectRenderTask,\n createEffectWrapper,\n createRenderTargetTexture,\n disposeEffectWrapper,\n setEffectTexture,\n setEffectUniforms,\n} from \"@babylonjs/lite\";\nimport type {\n EffectBindingLayout,\n EffectWrapper,\n EngineContext,\n RenderTarget,\n SceneContext,\n Task,\n Texture2D,\n} from \"@babylonjs/lite\";\n\n/**\n * The Babylon Lite half of custom post effects (ADR-0024).\n *\n * Everything here is `@internal` and every entry point needs a device.\n *\n * Lite's only public custom-pass path is `createEffectWrapper` + `createEffectRenderTask`\n * (`index.d.ts` 2461, 2452) — the generic `PostProcessTaskConfig` is not exported. The task writes a\n * `RenderTarget` while the wrapper **samples a `Texture2D`**, and a `createRenderTarget` target\n * exposes no `Texture2D`, so a chain that mixes built-ins with custom effects needs links that are\n * both: {@link createEffectChainLink} is `createRenderTargetTexture` (2998), which hands back\n * `{ rt, texture }`.\n *\n * Those links are **eager**, which the chain depends on twice over: an eager target is never\n * reallocated and `disposeRenderTarget` refuses to free one (`lib/engine/render-target.js` 20, 48),\n * so a wrapper's cached bind group cannot end up holding a destroyed view, and an effect that writes\n * the equally eager swapchain can be disposed without destroying it. The price is that a link is\n * fixed size (Lite error 571), so a canvas resize rebuilds the chain.\n *\n * Two more Lite rules: `getEffectPipeline` hard-codes the entry-point names `effectFullscreenVertex`\n * and `effectFragment` and prepends its own vertex module — which declares `EffectVertexOutput` — to\n * the fragment source (`lib/effect/effect-renderer.js` 258-260, 274); and a `sampler` binding with\n * no `textureBinding` falls back to the wrapper's first texture slot (line 342), so\n * {@link createCustomEffect} sets `textureBinding` on every sampler.\n */\n\n/**\n * A Babylon Lite fullscreen effect, re-exported under an ignifx name.\n *\n * @remarks\n * Unstable; excluded from the stability guarantees of `CONSTITUTION.md` Article IV.\n *\n * @internal\n */\nexport type LiteEffect = EffectWrapper;\n\n/**\n * A colour target that is also a sampled texture: what a chain of custom effects ping-pongs through.\n *\n * @internal\n */\nexport interface EffectChainLink {\n /** The render target a task writes. */\n readonly target: RenderTarget;\n /** The sampled texture the next effect reads. */\n readonly texture: Texture2D;\n}\n\n/**\n * What {@link createCustomEffect} needs.\n *\n * @internal\n */\nexport interface CustomEffectOptions {\n /** A debug label for the GPU resources. */\n readonly name: string;\n /** The whole fragment module, including its `effectFragment` entry point. */\n readonly fragmentWGSL: string;\n /** How large the effect's single uniform buffer is, in bytes. */\n readonly uniformByteLength: number;\n /** Whether each declared texture beyond the chain input is a `2d-array` view. */\n readonly declaredTextures: readonly { readonly array: boolean }[];\n}\n\n/**\n * Creates one fullscreen effect: its shader module, bind-group layout, uniform buffer, and texture\n * slots.\n *\n * @remarks\n * The binding layout is fixed and shared with the generated WGSL: `0` the uniform block, `1` and `2`\n * the chain's current colour and its sampler, then a texture/sampler pair per declared texture.\n * Nothing is compiled here — Lite builds the pipeline lazily, on the first `record()`.\n *\n * @param engine - The engine that owns the GPU resources.\n * @param options - The shader, the uniform size, and the declared textures.\n * @returns The effect wrapper. Bind its textures before recording a task for it.\n *\n * @internal\n */\nexport function createCustomEffect(engine: EngineContext, options: CustomEffectOptions): EffectWrapper {\n const bindings: EffectBindingLayout[] = [\n { name: \"shaderUniforms\", binding: 0, kind: \"uniform\", uniformByteLength: options.uniformByteLength },\n { name: \"inputTexture\", binding: 1, kind: \"texture\" },\n { name: \"inputTextureSampler\", binding: 2, kind: \"sampler\", textureBinding: 1 },\n ];\n for (let index = 0; index < options.declaredTextures.length; index += 1) {\n const declared = options.declaredTextures[index];\n const binding = 3 + index * 2;\n const layout: EffectBindingLayout = { name: `texture${String(index)}`, binding, kind: \"texture\" };\n if (declared?.array === true) {\n // The bind-group layout reads `viewDimension` straight off this field\n // (`bindingLayoutEntry`, `lib/effect/effect-renderer.js` 302).\n bindings.push({ ...layout, viewDimension: \"2d-array\" });\n } else {\n bindings.push(layout);\n }\n bindings.push({ name: `sampler${String(index)}`, binding: binding + 1, kind: \"sampler\", textureBinding: binding });\n }\n return createEffectWrapper(engine, { name: options.name, fragmentWGSL: options.fragmentWGSL, bindings });\n}\n\n/**\n * Binds a texture to one of an effect's texture slots.\n *\n * @remarks\n * Also marks the wrapper's bind group dirty, which is the only thing that does, so this is what has\n * to be called after a link is rebuilt or a declared texture is swapped.\n *\n * @param effect - The effect wrapper.\n * @param binding - The binding index.\n * @param texture - The texture.\n *\n * @internal\n */\nexport function bindCustomEffectTexture(effect: EffectWrapper, binding: number, texture: Texture2D): void {\n setEffectTexture(effect, binding, texture);\n}\n\n/**\n * Uploads an effect's uniform bytes.\n *\n * @remarks\n * A plain `queue.writeBuffer`, so it is safe to call every frame and costs nothing on a frame where\n * the bytes did not change — which is why the caller compares first.\n *\n * @param effect - The effect wrapper.\n * @param data - The bytes; no longer than the declared `uniformByteLength`.\n *\n * @internal\n */\nexport function writeCustomEffectUniforms(effect: EffectWrapper, data: Float32Array): void {\n setEffectUniforms(effect, data);\n}\n\n/**\n * Records one fullscreen effect as a frame-graph task writing `target`.\n *\n * @remarks\n * The task clears its target and draws a fullscreen triangle, so the whole target is overwritten and\n * the clear costs nothing. Append it with `appendPostProcessTask` from `./post-process.ts`.\n *\n * @param engine - The engine.\n * @param scene - The scene whose frame graph will hold it.\n * @param name - A debug label.\n * @param effect - The effect wrapper, with every texture already bound.\n * @param target - The colour target it writes; the surface swapchain for the last effect.\n * @returns The task.\n *\n * @internal\n */\nexport function createCustomEffectTask(\n engine: EngineContext,\n scene: SceneContext,\n name: string,\n effect: EffectWrapper,\n target: RenderTarget,\n): Task {\n return createEffectRenderTask({ name, effect, target, clear: true }, engine, scene);\n}\n\n/**\n * Frees an effect wrapper's GPU resources.\n *\n * @param effect - The effect wrapper.\n *\n * @internal\n */\nexport function disposeCustomEffect(effect: EffectWrapper): void {\n disposeEffectWrapper(effect);\n}\n\n/**\n * Creates one ping-pong link of an effect chain: a colour target that is also a sampled texture.\n *\n * @remarks\n * Eager and fixed size, which Lite requires of a sampled render target (error 571) and which the\n * chain needs anyway, because an effect wrapper caches the texture view in its bind group. A resize\n * therefore rebuilds the chain rather than reallocating the link.\n *\n * @param engine - The engine that owns the texture.\n * @param format - The colour format; the surface's, so a built-in pass can write it.\n * @param width - The width in backing-store pixels.\n * @param height - The height in backing-store pixels.\n * @param label - A debug label.\n * @returns The link.\n *\n * @internal\n */\nexport function createEffectChainLink(\n engine: EngineContext,\n format: GPUTextureFormat,\n width: number,\n height: number,\n label: string,\n): EffectChainLink {\n const created = createRenderTargetTexture(engine, {\n lbl: label,\n format,\n samples: 1,\n size: { width: Math.max(1, width), height: Math.max(1, height) },\n });\n return { target: created.rt, texture: created.texture };\n}\n\n/**\n * Frees a chain link's GPU texture.\n *\n * @remarks\n * `disposeRenderTarget` refuses to free an eager target, which is what keeps\n * `EffectRenderTask.dispose` from destroying a shared link, so the texture has to be destroyed here\n * instead.\n *\n * @param link - The link.\n *\n * @internal\n */\nexport function disposeEffectChainLink(link: EffectChainLink): void {\n link.texture.texture.destroy();\n}\n\n/**\n * Records a task that copies one colour target into another.\n *\n * @remarks\n * The chain uses it once, and only when its **first** effect is a custom one: the scene colour the\n * render path drew into is a canvas-sized, non-eager `RenderTarget` with no `Texture2D`, so it\n * cannot be sampled by an effect wrapper. One copy into a link makes it samplable. A chain that\n * starts with bloom or SMAA needs no copy, because those write a link directly.\n *\n * @param engine - The engine.\n * @param scene - The scene whose frame graph will hold it.\n * @param name - A debug label.\n * @param source - The target to read.\n * @param target - The target to write; externally owned, so the task does not rebuild or free it.\n * @returns The task.\n *\n * @internal\n */\nexport function createChainCopyTask(\n engine: EngineContext,\n scene: SceneContext,\n name: string,\n source: RenderTarget,\n target: RenderTarget,\n): Task {\n return createCopyToTextureTask(\n { name, sourceTexture: source, targetTexture: target, ownsTargetTexture: false },\n engine,\n scene,\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAiGA,SAAgB,mBAAmB,QAAuB,SAA6C;CACrG,MAAM,WAAkC;EACtC;GAAE,MAAM;GAAkB,SAAS;GAAG,MAAM;GAAW,mBAAmB,QAAQ;EAAkB;EACpG;GAAE,MAAM;GAAgB,SAAS;GAAG,MAAM;EAAU;EACpD;GAAE,MAAM;GAAuB,SAAS;GAAG,MAAM;GAAW,gBAAgB;EAAE;CAChF;CACA,KAAK,IAAI,QAAQ,GAAG,QAAQ,QAAQ,iBAAiB,QAAQ,SAAS,GAAG;EACvE,MAAM,WAAW,QAAQ,iBAAiB;EAC1C,MAAM,UAAU,IAAI,QAAQ;EAC5B,MAAM,SAA8B;GAAE,MAAM,UAAU,OAAO,KAAK;GAAK;GAAS,MAAM;EAAU;EAChG,IAAI,UAAU,UAAU,MAGtB,SAAS,KAAK;GAAE,GAAG;GAAQ,eAAe;EAAW,CAAC;OAEtD,SAAS,KAAK,MAAM;EAEtB,SAAS,KAAK;GAAE,MAAM,UAAU,OAAO,KAAK;GAAK,SAAS,UAAU;GAAG,MAAM;GAAW,gBAAgB;EAAQ,CAAC;CACnH;CACA,OAAO,oBAAoB,QAAQ;EAAE,MAAM,QAAQ;EAAM,cAAc,QAAQ;EAAc;CAAS,CAAC;AACzG;;;;;;;;;;;;;;AAeA,SAAgB,wBAAwB,QAAuB,SAAiB,SAA0B;CACxG,iBAAiB,QAAQ,SAAS,OAAO;AAC3C;;;;;;;;;;;;;AAcA,SAAgB,0BAA0B,QAAuB,MAA0B;CACzF,kBAAkB,QAAQ,IAAI;AAChC;;;;;;;;;;;;;;;;;AAkBA,SAAgB,uBACd,QACA,OACA,MACA,QACA,QACM;CACN,OAAO,uBAAuB;EAAE;EAAM;EAAQ;EAAQ,OAAO;CAAK,GAAG,QAAQ,KAAK;AACpF;;;;;;;;AASA,SAAgB,oBAAoB,QAA6B;CAC/D,qBAAqB,MAAM;AAC7B;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,sBACd,QACA,QACA,OACA,QACA,OACiB;CACjB,MAAM,UAAU,0BAA0B,QAAQ;EAChD,KAAK;EACL;EACA,SAAS;EACT,MAAM;GAAE,OAAO,KAAK,IAAI,GAAG,KAAK;GAAG,QAAQ,KAAK,IAAI,GAAG,MAAM;EAAE;CACjE,CAAC;CACD,OAAO;EAAE,QAAQ,QAAQ;EAAI,SAAS,QAAQ;CAAQ;AACxD;;;;;;;;;;;;;AAcA,SAAgB,uBAAuB,MAA6B;CAClE,KAAK,QAAQ,QAAQ,QAAQ;AAC/B;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,oBACd,QACA,OACA,MACA,QACA,QACM;CACN,OAAO,wBACL;EAAE;EAAM,eAAe;EAAQ,eAAe;EAAQ,mBAAmB;CAAM,GAC/E,QACA,KACF;AACF"}
|
|
@@ -228,7 +228,7 @@ function setSceneImageProcessingOptions(scene, exposure, contrast, toneMapping)
|
|
|
228
228
|
contrast,
|
|
229
229
|
toneMappingEnabled: false
|
|
230
230
|
});
|
|
231
|
-
if (toneMapping === "agx") return import("./agx-tone-mapping-
|
|
231
|
+
if (toneMapping === "agx") return import("./agx-tone-mapping-CCdGk_ly.js").then(({ AgxToneMapping }) => setSceneImageProcessing(scene, {
|
|
232
232
|
exposure,
|
|
233
233
|
contrast,
|
|
234
234
|
toneMappingEnabled: true,
|
|
@@ -294,4 +294,4 @@ function toneMappingCurve(name) {
|
|
|
294
294
|
//#endregion
|
|
295
295
|
export { readSceneImageProcessing as a, setSceneEnvironmentRotation as c, readSceneEnvironment as i, setSceneFog as l, installSceneEnvironment as n, setSceneClearColor as o, loadSceneEnvironment as r, setSceneEnvironmentBlur as s, TONE_MAPPING_NAMES as t, setSceneImageProcessingOptions as u };
|
|
296
296
|
|
|
297
|
-
//# sourceMappingURL=environment-
|
|
297
|
+
//# sourceMappingURL=environment-7fJbN402.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"environment-Bf4aphSb.js","names":[],"sources":["../src/lite/gpu/environment.ts"],"sourcesContent":["import {\n AcesToneMapping,\n loadEnvironment,\n loadSkybox,\n NeutralToneMapping,\n setEnvironmentBlur,\n setEnvironmentRotation,\n setFog,\n setSceneImageProcessing,\n StandardToneMapping,\n} from \"@babylonjs/lite\";\nimport { assertNever } from \"../../errors/ignifx-error.js\";\nimport { Color } from \"../../math/color.js\";\nimport { degToRad } from \"../../math/math-utils.js\";\nimport type { EnvironmentTextures, SceneContext, ToneMapping } from \"@babylonjs/lite\";\n\n/**\n * Environment half of the Babylon Lite adapter (`docs/architecture/07-rendering.md` §2.5): image\n * based lighting, the skybox, fog, image processing, and the clear colour.\n *\n * Everything here is `@internal`. Loading uploads cube maps, so the module is GPU-only.\n *\n * ## The BRDF LUT is mandatory (verified against `@babylonjs/lite@1.27.0`)\n *\n * `loadEnvironment(scene, url, options)` (`index.d.ts` 6779) takes a **required** `brdfUrl`: Lite\n * decodes the split-sum BRDF lookup table from a pre-baked RGBD PNG rather than computing it, \"for\n * pixel-perfect parity\" with Babylon.js (`lib/_chunks/env-helpers-*.js`, `loadBrdfImage`, which\n * `fetch`es the URL and decodes it with `createImageBitmap`). ignifx ships that PNG as\n * `tests/fixtures/assets/brdf-lut.png`, decoded from Babylon.js's own\n * `_environmentBRDFBase64Texture` (`packages/dev/core/src/Misc/brdfTextureTools.ts`, Apache-2.0).\n * It is 256×256 RGBA8 and 23 KB.\n *\n * ## Fog\n *\n * `SceneContext.fog` is `FogConfig | null` (`index.d.ts` 5350) with a numeric `mode`; Lite exports\n * no named constants for it, so {@link FOG_MODES} maps ignifx's names onto the numbers.\n *\n * **Fog has to be installed with `setFog`, not by assigning the field.** `scene.fog` is what the PBR\n * group builder reads to decide whether a material's program gets the fog block at all\n * (`lib/material/pbr/pbr-renderable.js` 140-159, `PBR_HAS_FOG`), but the block it compiles reads\n * `scene.vFogInfos.x` out of the scene uniform buffer — and the only writer of those slots is\n * `writeFogUbo`, which nothing registers except `setFog`\n * (`lib/scene/scene-ubo-extras.js`: `setFog` is `scene.fog = config` **plus**\n * `_registerSceneUboContributor(scene, writeFogUbo)`, and `_writePassSceneUBO` runs\n * `scene._sceneUboContributors` and nothing else, `lib/frame-graph/render-task.js` 372-379).\n * Lite says as much in `index.d.ts` 10471: \"importing `setFog` is what pulls the fog UBO writer into\n * the bundle\". Assigning `scene.fog` alone therefore compiles the fog block into every PBR pipeline\n * and leaves `vFogInfos` zeroed, so `vFogInfos.x > 0.0` is never true and the scene renders with no\n * fog at all — the cost with none of the effect.\n *\n * A **fresh** config object goes in on every change, because a render task caches its scene UBO on\n * the identity of `scene.fog` (`s[1] === fog`, `lib/frame-graph/render-task.js` 355-371): mutating\n * the installed object in place leaves the cache key equal and the new density or colour never\n * reaches the GPU. Turning fog off writes mode `0`, which is what the already-compiled fog block\n * reads as \"no fog\"; dropping the field back to `null` would only stop the writer and leave the last\n * fog standing. A scene that never had fog keeps its `null` and pays nothing.\n *\n * ## Image processing\n *\n * `setSceneImageProcessing` is **async** (`index.d.ts` 10917) because tone mapping is baked into\n * the PBR shaders at `registerScene` time; changing it recompiles the affected pipelines\n * (`rebuildScenePbrPipelines`). Setting exposure or contrast alone still goes through the same\n * call. Note that `loadEnvironment` **overwrites** all three (`toneMappingEnabled = true`,\n * `exposure = 0.8`, `contrast = 1.2`) as a side effect of installing an environment, which is why\n * the `Environment` component re-applies its own image processing after every install.\n *\n * ## Swapping the installed environment: `scene._envTextures`\n *\n * Lite 1.27.0 declares **no** public way to replace, clear, or read back a registered scene's\n * environment. `index.d.ts` has no `scene.environmentTexture`, no `unloadEnvironment`, and no\n * setter of any kind; `loadEnvironment` is the only installer and it fetches, decodes, and uploads\n * a fresh cube map every call. What it actually installs is one field —\n * `scene._envTextures = textures` (`lib/_chunks/env-helpers-CRI1i-A3.js` 24, and the same line in\n * `lib/loader-hdr/load-hdr.js` 23, `lib/loader-env/load-dds-env.js` 177 and\n * `lib/loader-gltf/gltf-ext-lights-image-based.js` 65) — and every consumer reads that field:\n *\n * - the PBR group builder, which bakes the cube view and sampler into each material's bind group\n * (`lib/material/pbr/pbr-material.js` 12 → `lib/material/pbr/pbr-renderable.js`);\n * - the scene-uniform packer, for `lodGenerationScale` (`lib/frame-graph/scene-uniforms-pack.js` 21);\n * - the env UBO contributor, for the diffuse spherical harmonics (`lib/scene/scene-ubo-extras.js` 24);\n * - the blur contributor, for `lodGenerationOffset` (`lib/scene/set-environment-blur.js` 8);\n * - the render task's scene-UBO cache key, which is keyed on the **object identity** of the field\n * (`lib/frame-graph/render-task.js` 358), so a new object re-uploads the harmonics by itself.\n *\n * Lite's own device-lost recovery replaces the field exactly this way\n * (`lib/loader-env/environment-recovery.js` 16 and 38), so {@link installSceneEnvironment} writes it\n * too. Bind groups are the one consumer that does *not* re-read it: they hold the `GPUTextureView`,\n * so a swap only reaches the specular reflection once the material groups have been rebuilt, which\n * `rebuildSceneRenderables` does (`lib/scene/scene-rebuild.js`, `rebuildEachGroup`). The\n * `Environment` component therefore reports an install as a topology change and lets the render-sync\n * system fire its one coalesced rebuild. This is the only place in ignifx that touches a Lite field\n * `index.d.ts` does not declare, which is what the adapter boundary exists for\n * (`CONSTITUTION.md` §3.4, ADR-0002); it is pinned by\n * `packages/core/test/lite/render/environment.browser.test.ts`, which fails loudly if the field is\n * renamed.\n */\n\n/**\n * The GPU-resident image-based-lighting textures `loadEnvironment` resolves to, re-exported under an\n * ignifx name (`CONSTITUTION.md` §3.4, coding standards §4).\n *\n * @remarks\n * Unstable; excluded from the stability guarantees of `CONSTITUTION.md` Article IV.\n *\n * @public\n */\nexport type LiteEnvironmentTextures = EnvironmentTextures;\n\n/**\n * ignifx fog mode names mapped to the numbers `FogConfig.mode` uses.\n *\n * @internal\n */\nexport const FOG_MODES = {\n /** No fog. */\n none: 0,\n /** Exponential fog. */\n exp: 1,\n /** Squared-exponential fog. */\n exp2: 2,\n /** Linear fog between `start` and `end`. */\n linear: 3,\n} as const;\n\n/**\n * The union of the fog mode names.\n *\n * @internal\n */\nexport type FogMode = keyof typeof FOG_MODES;\n\n/**\n * The tone-mapping curves `docs/architecture/07-rendering.md` §2.5 exposes. `\"agx\"` is ignifx's\n * own Lite curve (`./agx-tone-mapping.ts`); the others are Lite's built-ins.\n *\n * @public\n */\nexport const TONE_MAPPING_NAMES = [\"none\", \"standard\", \"aces\", \"neutral\", \"agx\"] as const;\n\n/**\n * The `id` of the AgX curve, repeated from `./agx-tone-mapping.ts` so recognising it does not load\n * that chunk.\n */\nconst AGX_TONE_MAPPING_ID = \"ignifx-agx\";\n\n/**\n * The union of the tone-mapping curve names.\n *\n * @internal\n */\nexport type ToneMappingName = (typeof TONE_MAPPING_NAMES)[number];\n\n/**\n * The image processing Lite's PBR shaders apply: exposure, contrast and the tone-mapping curve.\n *\n * @internal\n */\nexport interface ImageProcessingState {\n /** The exposure multiplier. */\n exposure: number;\n /** The contrast multiplier. */\n contrast: number;\n /** The tone-mapping curve, or `\"none\"`. */\n curve: ToneMappingName;\n}\n\n/**\n * How an ignifx `Environment` component configures image based lighting.\n *\n * @internal\n */\nexport interface EnvironmentLoadOptions {\n /** The `.env` file holding the prefiltered specular cube map and its spherical harmonics. */\n readonly url: string;\n /** The RGBD PNG BRDF lookup table. Required by Lite. */\n readonly brdfUrl: string;\n /** A `.dds` or `.env` skybox. Omit for a flat background. */\n readonly skyboxUrl?: string;\n /** The skybox cube's size, in metres. Lite defaults to 20. */\n readonly skyboxSize?: number;\n /** Skip the skybox entirely. */\n readonly skipSkybox?: boolean;\n /** Skip the reflective ground plane Lite would otherwise add. */\n readonly skipGround?: boolean;\n /** A texture for that ground plane. */\n readonly groundTextureUrl?: string;\n}\n\n/**\n * Loads an `.env` environment and installs it on a scene.\n *\n * @param scene - The scene to light.\n * @param options - The environment, BRDF, and skybox URLs.\n * @returns The GPU-resident environment textures, for materials that need them explicitly.\n *\n * @example\n * ```ts\n * await loadSceneEnvironment(scene, {\n * url: \"environments/studio.env\",\n * brdfUrl: \"environments/brdf-lut.png\",\n * });\n * ```\n *\n * @internal\n */\nexport function loadSceneEnvironment(\n scene: SceneContext,\n options: EnvironmentLoadOptions,\n): Promise<EnvironmentTextures> {\n const liteOptions: {\n brdfUrl: string;\n skyboxUrl?: string;\n skyboxSize?: number;\n skipSkybox?: boolean;\n skipGround?: boolean;\n groundTextureUrl?: string;\n } = { brdfUrl: options.brdfUrl };\n if (options.skyboxUrl !== undefined) {\n liteOptions.skyboxUrl = options.skyboxUrl;\n }\n if (options.skyboxSize !== undefined) {\n liteOptions.skyboxSize = options.skyboxSize;\n }\n if (options.skipSkybox !== undefined) {\n liteOptions.skipSkybox = options.skipSkybox;\n }\n if (options.skipGround !== undefined) {\n liteOptions.skipGround = options.skipGround;\n }\n if (options.groundTextureUrl !== undefined) {\n liteOptions.groundTextureUrl = options.groundTextureUrl;\n }\n return loadEnvironment(scene, options.url, liteOptions);\n}\n\n/**\n * The scene fields Babylon Lite 1.27.0 writes for image-based lighting but does not declare in\n * `index.d.ts`. Adapter-internal Lite mirror (coding standards §5.1); see the module header for the\n * `lib/` lines that prove each one.\n */\ninterface SceneEnvironmentSlot {\n /** What `loadEnvironment` installed, or `undefined` on a scene that has never had one. */\n _envTextures?: EnvironmentTextures | undefined;\n}\n\n/**\n * Views a scene through its undeclared environment slot.\n *\n * @param scene - The scene.\n * @returns The same object, typed so the slot is reachable.\n */\nfunction environmentSlotOf(scene: SceneContext): SceneEnvironmentSlot {\n // Boundary assertion (coding standards §5.2): `SceneContext` is a plain object literal Lite\n // creates in `lib/scene/scene-core.js`, and `_envTextures` is one of its own fields — it is\n // absent from `index.d.ts` because it is not part of Lite's declared surface, not because it is\n // a different object. See the module header for every `lib/` line that reads or writes it.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return scene as SceneContext & SceneEnvironmentSlot;\n}\n\n/**\n * Reports which environment textures a scene is currently lit by.\n *\n * @param scene - The scene to inspect.\n * @returns The installed textures, or `null` when no environment has ever been installed.\n *\n * @internal\n */\nexport function readSceneEnvironment(scene: SceneContext): EnvironmentTextures | null {\n // The underscore is Lite's, not ignifx's: coding standards §5.1 reserves `_field` for exactly\n // this, an adapter-internal mirror of a Lite field, and the module header proves the name.\n // oxlint-disable-next-line no-underscore-dangle\n return environmentSlotOf(scene)._envTextures ?? null;\n}\n\n/**\n * Points a scene at an already-loaded set of environment textures, without loading anything.\n *\n * @remarks\n * This is how an `Environment` component swaps environments at runtime: the textures belong to the\n * `EnvironmentAsset` that loaded them and stay alive as long as its handle is retained, so\n * switching between two loaded assets uploads nothing and frees nothing.\n *\n * The specular reflection follows only after the scene's material groups are rebuilt\n * (`rebuildRenderables` in `../shadow.ts`): a PBR bind group holds the cube map's `GPUTextureView`,\n * not the slot. The diffuse harmonics and the LOD scale follow immediately, because the render\n * task's scene-UBO cache is keyed on this object's identity.\n *\n * @param scene - The scene to light.\n * @param textures - The textures to light it with.\n * @returns `true` when the scene was lit by something else and now is not — the caller owes a\n * renderable rebuild; `false` when these textures were already installed and nothing was written.\n *\n * @example\n * ```ts\n * if (installSceneEnvironment(scene, asset.lite.textures)) {\n * await rebuildRenderables(scene);\n * }\n * ```\n *\n * @internal\n */\nexport function installSceneEnvironment(scene: SceneContext, textures: EnvironmentTextures): boolean {\n const slot = environmentSlotOf(scene);\n // As in `readSceneEnvironment`: an adapter-internal Lite mirror (coding standards §5.1).\n // oxlint-disable-next-line no-underscore-dangle\n if (slot._envTextures === textures) {\n return false;\n }\n // oxlint-disable-next-line no-underscore-dangle\n slot._envTextures = textures;\n return true;\n}\n\n/**\n * Loads a six-face cube-map skybox from a base URL.\n *\n * @param scene - The scene to give a background.\n * @param baseUrl - The URL prefix each face name is appended to.\n * @param extension - The face file extension, such as `\".jpg\"`.\n * @param size - The skybox cube's size, in metres.\n * @returns A promise that resolves when the faces are uploaded.\n *\n * @internal\n */\nexport function loadSceneSkybox(scene: SceneContext, baseUrl: string, extension: string, size?: number): Promise<void> {\n return loadSkybox(scene, baseUrl, extension, size);\n}\n\n/**\n * Rotates the environment around the world Y axis.\n *\n * @param scene - The scene to rotate the environment of.\n * @param degrees - The rotation, in degrees.\n *\n * @internal\n */\nexport function setSceneEnvironmentRotation(scene: SceneContext, degrees: number): void {\n setEnvironmentRotation(scene, degToRad(degrees));\n}\n\n/**\n * Blurs the visible skybox. Babylon Lite patches only the skybox shader; no material reads the value.\n *\n * @param scene - The scene to change.\n * @param blur - The blur amount, 0 to 1.\n *\n * @internal\n */\nexport function setSceneEnvironmentBlur(scene: SceneContext, blur: number): void {\n setEnvironmentBlur(scene, blur);\n}\n\n/**\n * Sets the colour the scene is cleared to each frame, so that it presents as the sRGB value given.\n *\n * @remarks\n * Lite stores the clear value into the colour target untouched. Tone mapping, image processing and\n * bloom's threshold never apply to it on the GPU (the renderer applies image processing before this\n * call, `src/render/image-processing-color.ts`), and Lite's own transmission and solid-skybox paths read it\n * as the colour that should come out (`lib/frame-graph/transmission.js` `executeRenderTaskLinear`,\n * `lib/material/pbr/background-solid-skybox.js`). The default surface format is not an sRGB one,\n * so the sRGB value is written unchanged. Only an `*-srgb` surface view (`rendering.srgb: true`)\n * encodes on write; there the value is decoded first, so that the GPU's encoding gives it back.\n * Every target ignifx renders the scene into uses the surface's format (`./render-path.ts`), so\n * the same rule holds on the offscreen path.\n *\n * @param scene - The scene to change.\n * @param r - The sRGB red component, 0 to 1.\n * @param g - The sRGB green component, 0 to 1.\n * @param b - The sRGB blue component, 0 to 1.\n * @param a - The alpha component; only meaningful with a premultiplied canvas alpha mode.\n *\n * @internal\n */\nexport function setSceneClearColor(scene: SceneContext, r: number, g: number, b: number, a: number): void {\n const clear = scene.clearColor;\n const decode = isSrgbEncodingFormat(scene.surface.format);\n clear.r = decode ? Color.srgbToLinear(r) : r;\n clear.g = decode ? Color.srgbToLinear(g) : g;\n clear.b = decode ? Color.srgbToLinear(b) : b;\n clear.a = a;\n}\n\n/**\n * Whether a colour target of this format encodes linear values to sRGB as they are stored.\n *\n * @param format - The target's format. Lite's null engine has none.\n * @returns `true` for an `*-srgb` format.\n *\n * @internal\n */\nexport function isSrgbEncodingFormat(format: string | undefined): boolean {\n return format?.endsWith(\"-srgb\") === true;\n}\n\n/**\n * Configures the scene's fog, or turns it off.\n *\n * @param scene - The scene to change.\n * @param mode - The fog falloff, or `\"none\"` to disable it.\n * @param r - The sRGB red component of the fog colour; Lite's fog block decodes it itself.\n * @param g - The sRGB green component.\n * @param b - The sRGB blue component.\n * @param density - The density, for the exponential modes.\n * @param start - Where linear fog begins, in metres.\n * @param end - Where linear fog reaches full strength, in metres.\n *\n * @internal\n */\nexport function setSceneFog(\n scene: SceneContext,\n mode: FogMode,\n r: number,\n g: number,\n b: number,\n density: number,\n start: number,\n end: number,\n): void {\n if (mode === \"none\" && scene.fog === null) {\n // A scene that never had fog pays nothing: no contributor, no fog block in any PBR pipeline.\n return;\n }\n setFog(scene, { mode: FOG_MODES[mode], density, start, end, color: [r, g, b] });\n}\n\n/**\n * Sets exposure, contrast, and the tone-mapping curve.\n *\n * @remarks\n * Asynchronous by nature: tone mapping is compiled into the PBR shaders, so changing it after\n * `registerScene` recompiles the scene's PBR pipelines. Exposure and contrast alone are uniform\n * values, but Lite routes them through the same call.\n *\n * @param scene - The scene to change.\n * @param exposure - The exposure multiplier.\n * @param contrast - The contrast multiplier.\n * @param toneMapping - The curve, or `\"none\"` to leave the colour untouched.\n * @returns A promise that resolves when any affected pipeline has been rebuilt.\n *\n * @internal\n */\nexport function setSceneImageProcessingOptions(\n scene: SceneContext,\n exposure: number,\n contrast: number,\n toneMapping: ToneMappingName,\n): Promise<void> {\n if (toneMapping === \"none\") {\n return setSceneImageProcessing(scene, { exposure, contrast, toneMappingEnabled: false });\n }\n if (toneMapping === \"agx\") {\n // Its own chunk: a project that never names AgX loads none of its WGSL (CONSTITUTION.md §2.5).\n return import(\"./agx-tone-mapping.js\").then(({ AgxToneMapping }) =>\n setSceneImageProcessing(scene, { exposure, contrast, toneMappingEnabled: true, toneMapping: AgxToneMapping }),\n );\n }\n return setSceneImageProcessing(scene, {\n exposure,\n contrast,\n toneMappingEnabled: true,\n toneMapping: toneMappingCurve(toneMapping),\n });\n}\n\n/**\n * Reads the image processing the scene's PBR shaders currently apply.\n *\n * @remarks\n * Read from Lite rather than from the `Environment` component, because Lite's `loadEnvironment`\n * also writes it (exposure 0.8, contrast 1.2, the standard curve) and the clear colour has to match\n * what the shaders actually do. A custom Lite curve set through `.lite` reads as `\"none\"`.\n *\n * @param scene - The scene.\n * @param out - Receives the exposure, contrast and curve.\n * @returns `out`.\n *\n * @internal\n */\nexport function readSceneImageProcessing(scene: SceneContext, out: ImageProcessingState): ImageProcessingState {\n const processing = scene.imageProcessing;\n out.exposure = processing.exposure;\n out.contrast = processing.contrast;\n out.curve = processing.toneMappingEnabled ? curveName(processing.toneMapping ?? StandardToneMapping) : \"none\";\n return out;\n}\n\n/**\n * Maps a Lite curve object back onto its ignifx name.\n *\n * @param curve - The Lite curve.\n * @returns The name, or `\"none\"` for a curve ignifx does not know.\n */\nfunction curveName(curve: ToneMapping): ToneMappingName {\n switch (curve.id) {\n case StandardToneMapping.id:\n return \"standard\";\n case AcesToneMapping.id:\n return \"aces\";\n case NeutralToneMapping.id:\n return \"neutral\";\n case AGX_TONE_MAPPING_ID:\n return \"agx\";\n default:\n return \"none\";\n }\n}\n\n/**\n * Maps an ignifx tone-mapping name onto the Lite curve object.\n *\n * @param name - The curve name; `\"none\"` and the lazily loaded `\"agx\"` are handled by the caller.\n * @returns The Lite curve.\n */\nfunction toneMappingCurve(name: Exclude<ToneMappingName, \"none\" | \"agx\">): ToneMapping {\n switch (name) {\n case \"standard\":\n return StandardToneMapping;\n case \"aces\":\n return AcesToneMapping;\n case \"neutral\":\n return NeutralToneMapping;\n default:\n return assertNever(name, \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B,OAAO;EACT,KAAK,gBAAgB,IACnB,OAAO;EACT,KAAK,mBAAmB,IACtB,OAAO;EACT,KAAK,qBACH,OAAO;EACT,SACE,OAAO;CACX;AACF;;;;;;;AAQA,SAAS,iBAAiB,MAA6D;CACrF,QAAQ,MAAR;EACE,KAAK,YACH,OAAO;EACT,KAAK,QACH,OAAO;EACT,KAAK,WACH,OAAO;EACT,SACE,OAAO,YAAY,MAAM,cAAc;CAC3C;AACF"}
|
|
1
|
+
{"version":3,"file":"environment-7fJbN402.js","names":[],"sources":["../src/lite/gpu/environment.ts"],"sourcesContent":["import {\n AcesToneMapping,\n loadEnvironment,\n loadSkybox,\n NeutralToneMapping,\n setEnvironmentBlur,\n setEnvironmentRotation,\n setFog,\n setSceneImageProcessing,\n StandardToneMapping,\n} from \"@babylonjs/lite\";\nimport { assertNever } from \"../../errors/ignifx-error.js\";\nimport { Color } from \"../../math/color.js\";\nimport { degToRad } from \"../../math/math-utils.js\";\nimport type { EnvironmentTextures, SceneContext, ToneMapping } from \"@babylonjs/lite\";\n\n/**\n * Environment half of the Babylon Lite adapter (`docs/architecture/07-rendering.md` §2.5): image\n * based lighting, the skybox, fog, image processing, and the clear colour.\n *\n * Everything here is `@internal`. Loading uploads cube maps, so the module is GPU-only.\n *\n * ## The BRDF LUT is mandatory (verified against `@babylonjs/lite@1.27.0`)\n *\n * `loadEnvironment(scene, url, options)` (`index.d.ts` 6779) takes a **required** `brdfUrl`: Lite\n * decodes the split-sum BRDF lookup table from a pre-baked RGBD PNG rather than computing it, \"for\n * pixel-perfect parity\" with Babylon.js (`lib/_chunks/env-helpers-*.js`, `loadBrdfImage`, which\n * `fetch`es the URL and decodes it with `createImageBitmap`). ignifx ships that PNG as\n * `tests/fixtures/assets/brdf-lut.png`, decoded from Babylon.js's own\n * `_environmentBRDFBase64Texture` (`packages/dev/core/src/Misc/brdfTextureTools.ts`, Apache-2.0).\n * It is 256×256 RGBA8 and 23 KB.\n *\n * ## Fog\n *\n * `SceneContext.fog` is `FogConfig | null` (`index.d.ts` 5350) with a numeric `mode`; Lite exports\n * no named constants for it, so {@link FOG_MODES} maps ignifx's names onto the numbers.\n *\n * **Fog has to be installed with `setFog`, not by assigning the field.** `scene.fog` is what the PBR\n * group builder reads to decide whether a material's program gets the fog block at all\n * (`lib/material/pbr/pbr-renderable.js` 140-159, `PBR_HAS_FOG`), but the block it compiles reads\n * `scene.vFogInfos.x` out of the scene uniform buffer — and the only writer of those slots is\n * `writeFogUbo`, which nothing registers except `setFog`\n * (`lib/scene/scene-ubo-extras.js`: `setFog` is `scene.fog = config` **plus**\n * `_registerSceneUboContributor(scene, writeFogUbo)`, and `_writePassSceneUBO` runs\n * `scene._sceneUboContributors` and nothing else, `lib/frame-graph/render-task.js` 372-379).\n * Lite says as much in `index.d.ts` 10471: \"importing `setFog` is what pulls the fog UBO writer into\n * the bundle\". Assigning `scene.fog` alone therefore compiles the fog block into every PBR pipeline\n * and leaves `vFogInfos` zeroed, so `vFogInfos.x > 0.0` is never true and the scene renders with no\n * fog at all — the cost with none of the effect.\n *\n * A **fresh** config object goes in on every change, because a render task caches its scene UBO on\n * the identity of `scene.fog` (`s[1] === fog`, `lib/frame-graph/render-task.js` 355-371): mutating\n * the installed object in place leaves the cache key equal and the new density or colour never\n * reaches the GPU. Turning fog off writes mode `0`, which is what the already-compiled fog block\n * reads as \"no fog\"; dropping the field back to `null` would only stop the writer and leave the last\n * fog standing. A scene that never had fog keeps its `null` and pays nothing.\n *\n * ## Image processing\n *\n * `setSceneImageProcessing` is **async** (`index.d.ts` 10917) because tone mapping is baked into\n * the PBR shaders at `registerScene` time; changing it recompiles the affected pipelines\n * (`rebuildScenePbrPipelines`). Setting exposure or contrast alone still goes through the same\n * call. Note that `loadEnvironment` **overwrites** all three (`toneMappingEnabled = true`,\n * `exposure = 0.8`, `contrast = 1.2`) as a side effect of installing an environment, which is why\n * the `Environment` component re-applies its own image processing after every install.\n *\n * ## Swapping the installed environment: `scene._envTextures`\n *\n * Lite 1.27.0 declares **no** public way to replace, clear, or read back a registered scene's\n * environment. `index.d.ts` has no `scene.environmentTexture`, no `unloadEnvironment`, and no\n * setter of any kind; `loadEnvironment` is the only installer and it fetches, decodes, and uploads\n * a fresh cube map every call. What it actually installs is one field —\n * `scene._envTextures = textures` (`lib/_chunks/env-helpers-CRI1i-A3.js` 24, and the same line in\n * `lib/loader-hdr/load-hdr.js` 23, `lib/loader-env/load-dds-env.js` 177 and\n * `lib/loader-gltf/gltf-ext-lights-image-based.js` 65) — and every consumer reads that field:\n *\n * - the PBR group builder, which bakes the cube view and sampler into each material's bind group\n * (`lib/material/pbr/pbr-material.js` 12 → `lib/material/pbr/pbr-renderable.js`);\n * - the scene-uniform packer, for `lodGenerationScale` (`lib/frame-graph/scene-uniforms-pack.js` 21);\n * - the env UBO contributor, for the diffuse spherical harmonics (`lib/scene/scene-ubo-extras.js` 24);\n * - the blur contributor, for `lodGenerationOffset` (`lib/scene/set-environment-blur.js` 8);\n * - the render task's scene-UBO cache key, which is keyed on the **object identity** of the field\n * (`lib/frame-graph/render-task.js` 358), so a new object re-uploads the harmonics by itself.\n *\n * Lite's own device-lost recovery replaces the field exactly this way\n * (`lib/loader-env/environment-recovery.js` 16 and 38), so {@link installSceneEnvironment} writes it\n * too. Bind groups are the one consumer that does *not* re-read it: they hold the `GPUTextureView`,\n * so a swap only reaches the specular reflection once the material groups have been rebuilt, which\n * `rebuildSceneRenderables` does (`lib/scene/scene-rebuild.js`, `rebuildEachGroup`). The\n * `Environment` component therefore reports an install as a topology change and lets the render-sync\n * system fire its one coalesced rebuild. This is the only place in ignifx that touches a Lite field\n * `index.d.ts` does not declare, which is what the adapter boundary exists for\n * (`CONSTITUTION.md` §3.4, ADR-0002); it is pinned by\n * `packages/core/test/lite/render/environment.browser.test.ts`, which fails loudly if the field is\n * renamed.\n */\n\n/**\n * The GPU-resident image-based-lighting textures `loadEnvironment` resolves to, re-exported under an\n * ignifx name (`CONSTITUTION.md` §3.4, coding standards §4).\n *\n * @remarks\n * Unstable; excluded from the stability guarantees of `CONSTITUTION.md` Article IV.\n *\n * @public\n */\nexport type LiteEnvironmentTextures = EnvironmentTextures;\n\n/**\n * ignifx fog mode names mapped to the numbers `FogConfig.mode` uses.\n *\n * @internal\n */\nexport const FOG_MODES = {\n /** No fog. */\n none: 0,\n /** Exponential fog. */\n exp: 1,\n /** Squared-exponential fog. */\n exp2: 2,\n /** Linear fog between `start` and `end`. */\n linear: 3,\n} as const;\n\n/**\n * The union of the fog mode names.\n *\n * @internal\n */\nexport type FogMode = keyof typeof FOG_MODES;\n\n/**\n * The tone-mapping curves `docs/architecture/07-rendering.md` §2.5 exposes. `\"agx\"` is ignifx's\n * own Lite curve (`./agx-tone-mapping.ts`); the others are Lite's built-ins.\n *\n * @public\n */\nexport const TONE_MAPPING_NAMES = [\"none\", \"standard\", \"aces\", \"neutral\", \"agx\"] as const;\n\n/**\n * The `id` of the AgX curve, repeated from `./agx-tone-mapping.ts` so recognising it does not load\n * that chunk.\n */\nconst AGX_TONE_MAPPING_ID = \"ignifx-agx\";\n\n/**\n * The union of the tone-mapping curve names.\n *\n * @internal\n */\nexport type ToneMappingName = (typeof TONE_MAPPING_NAMES)[number];\n\n/**\n * The image processing Lite's PBR shaders apply: exposure, contrast and the tone-mapping curve.\n *\n * @internal\n */\nexport interface ImageProcessingState {\n /** The exposure multiplier. */\n exposure: number;\n /** The contrast multiplier. */\n contrast: number;\n /** The tone-mapping curve, or `\"none\"`. */\n curve: ToneMappingName;\n}\n\n/**\n * How an ignifx `Environment` component configures image based lighting.\n *\n * @internal\n */\nexport interface EnvironmentLoadOptions {\n /** The `.env` file holding the prefiltered specular cube map and its spherical harmonics. */\n readonly url: string;\n /** The RGBD PNG BRDF lookup table. Required by Lite. */\n readonly brdfUrl: string;\n /** A `.dds` or `.env` skybox. Omit for a flat background. */\n readonly skyboxUrl?: string;\n /** The skybox cube's size, in metres. Lite defaults to 20. */\n readonly skyboxSize?: number;\n /** Skip the skybox entirely. */\n readonly skipSkybox?: boolean;\n /** Skip the reflective ground plane Lite would otherwise add. */\n readonly skipGround?: boolean;\n /** A texture for that ground plane. */\n readonly groundTextureUrl?: string;\n}\n\n/**\n * Loads an `.env` environment and installs it on a scene.\n *\n * @param scene - The scene to light.\n * @param options - The environment, BRDF, and skybox URLs.\n * @returns The GPU-resident environment textures, for materials that need them explicitly.\n *\n * @example\n * ```ts\n * await loadSceneEnvironment(scene, {\n * url: \"environments/studio.env\",\n * brdfUrl: \"environments/brdf-lut.png\",\n * });\n * ```\n *\n * @internal\n */\nexport function loadSceneEnvironment(\n scene: SceneContext,\n options: EnvironmentLoadOptions,\n): Promise<EnvironmentTextures> {\n const liteOptions: {\n brdfUrl: string;\n skyboxUrl?: string;\n skyboxSize?: number;\n skipSkybox?: boolean;\n skipGround?: boolean;\n groundTextureUrl?: string;\n } = { brdfUrl: options.brdfUrl };\n if (options.skyboxUrl !== undefined) {\n liteOptions.skyboxUrl = options.skyboxUrl;\n }\n if (options.skyboxSize !== undefined) {\n liteOptions.skyboxSize = options.skyboxSize;\n }\n if (options.skipSkybox !== undefined) {\n liteOptions.skipSkybox = options.skipSkybox;\n }\n if (options.skipGround !== undefined) {\n liteOptions.skipGround = options.skipGround;\n }\n if (options.groundTextureUrl !== undefined) {\n liteOptions.groundTextureUrl = options.groundTextureUrl;\n }\n return loadEnvironment(scene, options.url, liteOptions);\n}\n\n/**\n * The scene fields Babylon Lite 1.27.0 writes for image-based lighting but does not declare in\n * `index.d.ts`. Adapter-internal Lite mirror (coding standards §5.1); see the module header for the\n * `lib/` lines that prove each one.\n */\ninterface SceneEnvironmentSlot {\n /** What `loadEnvironment` installed, or `undefined` on a scene that has never had one. */\n _envTextures?: EnvironmentTextures | undefined;\n}\n\n/**\n * Views a scene through its undeclared environment slot.\n *\n * @param scene - The scene.\n * @returns The same object, typed so the slot is reachable.\n */\nfunction environmentSlotOf(scene: SceneContext): SceneEnvironmentSlot {\n // Boundary assertion (coding standards §5.2): `SceneContext` is a plain object literal Lite\n // creates in `lib/scene/scene-core.js`, and `_envTextures` is one of its own fields — it is\n // absent from `index.d.ts` because it is not part of Lite's declared surface, not because it is\n // a different object. See the module header for every `lib/` line that reads or writes it.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return scene as SceneContext & SceneEnvironmentSlot;\n}\n\n/**\n * Reports which environment textures a scene is currently lit by.\n *\n * @param scene - The scene to inspect.\n * @returns The installed textures, or `null` when no environment has ever been installed.\n *\n * @internal\n */\nexport function readSceneEnvironment(scene: SceneContext): EnvironmentTextures | null {\n // The underscore is Lite's, not ignifx's: coding standards §5.1 reserves `_field` for exactly\n // this, an adapter-internal mirror of a Lite field, and the module header proves the name.\n // oxlint-disable-next-line no-underscore-dangle\n return environmentSlotOf(scene)._envTextures ?? null;\n}\n\n/**\n * Points a scene at an already-loaded set of environment textures, without loading anything.\n *\n * @remarks\n * This is how an `Environment` component swaps environments at runtime: the textures belong to the\n * `EnvironmentAsset` that loaded them and stay alive as long as its handle is retained, so\n * switching between two loaded assets uploads nothing and frees nothing.\n *\n * The specular reflection follows only after the scene's material groups are rebuilt\n * (`rebuildRenderables` in `../shadow.ts`): a PBR bind group holds the cube map's `GPUTextureView`,\n * not the slot. The diffuse harmonics and the LOD scale follow immediately, because the render\n * task's scene-UBO cache is keyed on this object's identity.\n *\n * @param scene - The scene to light.\n * @param textures - The textures to light it with.\n * @returns `true` when the scene was lit by something else and now is not — the caller owes a\n * renderable rebuild; `false` when these textures were already installed and nothing was written.\n *\n * @example\n * ```ts\n * if (installSceneEnvironment(scene, asset.lite.textures)) {\n * await rebuildRenderables(scene);\n * }\n * ```\n *\n * @internal\n */\nexport function installSceneEnvironment(scene: SceneContext, textures: EnvironmentTextures): boolean {\n const slot = environmentSlotOf(scene);\n // As in `readSceneEnvironment`: an adapter-internal Lite mirror (coding standards §5.1).\n // oxlint-disable-next-line no-underscore-dangle\n if (slot._envTextures === textures) {\n return false;\n }\n // oxlint-disable-next-line no-underscore-dangle\n slot._envTextures = textures;\n return true;\n}\n\n/**\n * Loads a six-face cube-map skybox from a base URL.\n *\n * @param scene - The scene to give a background.\n * @param baseUrl - The URL prefix each face name is appended to.\n * @param extension - The face file extension, such as `\".jpg\"`.\n * @param size - The skybox cube's size, in metres.\n * @returns A promise that resolves when the faces are uploaded.\n *\n * @internal\n */\nexport function loadSceneSkybox(scene: SceneContext, baseUrl: string, extension: string, size?: number): Promise<void> {\n return loadSkybox(scene, baseUrl, extension, size);\n}\n\n/**\n * Rotates the environment around the world Y axis.\n *\n * @param scene - The scene to rotate the environment of.\n * @param degrees - The rotation, in degrees.\n *\n * @internal\n */\nexport function setSceneEnvironmentRotation(scene: SceneContext, degrees: number): void {\n setEnvironmentRotation(scene, degToRad(degrees));\n}\n\n/**\n * Blurs the visible skybox. Babylon Lite patches only the skybox shader; no material reads the value.\n *\n * @param scene - The scene to change.\n * @param blur - The blur amount, 0 to 1.\n *\n * @internal\n */\nexport function setSceneEnvironmentBlur(scene: SceneContext, blur: number): void {\n setEnvironmentBlur(scene, blur);\n}\n\n/**\n * Sets the colour the scene is cleared to each frame, so that it presents as the sRGB value given.\n *\n * @remarks\n * Lite stores the clear value into the colour target untouched. Tone mapping, image processing and\n * bloom's threshold never apply to it on the GPU (the renderer applies image processing before this\n * call, `src/render/image-processing-color.ts`), and Lite's own transmission and solid-skybox paths read it\n * as the colour that should come out (`lib/frame-graph/transmission.js` `executeRenderTaskLinear`,\n * `lib/material/pbr/background-solid-skybox.js`). The default surface format is not an sRGB one,\n * so the sRGB value is written unchanged. Only an `*-srgb` surface view (`rendering.srgb: true`)\n * encodes on write; there the value is decoded first, so that the GPU's encoding gives it back.\n * Every target ignifx renders the scene into uses the surface's format (`./render-path.ts`), so\n * the same rule holds on the offscreen path.\n *\n * @param scene - The scene to change.\n * @param r - The sRGB red component, 0 to 1.\n * @param g - The sRGB green component, 0 to 1.\n * @param b - The sRGB blue component, 0 to 1.\n * @param a - The alpha component; only meaningful with a premultiplied canvas alpha mode.\n *\n * @internal\n */\nexport function setSceneClearColor(scene: SceneContext, r: number, g: number, b: number, a: number): void {\n const clear = scene.clearColor;\n const decode = isSrgbEncodingFormat(scene.surface.format);\n clear.r = decode ? Color.srgbToLinear(r) : r;\n clear.g = decode ? Color.srgbToLinear(g) : g;\n clear.b = decode ? Color.srgbToLinear(b) : b;\n clear.a = a;\n}\n\n/**\n * Whether a colour target of this format encodes linear values to sRGB as they are stored.\n *\n * @param format - The target's format. Lite's null engine has none.\n * @returns `true` for an `*-srgb` format.\n *\n * @internal\n */\nexport function isSrgbEncodingFormat(format: string | undefined): boolean {\n return format?.endsWith(\"-srgb\") === true;\n}\n\n/**\n * Configures the scene's fog, or turns it off.\n *\n * @param scene - The scene to change.\n * @param mode - The fog falloff, or `\"none\"` to disable it.\n * @param r - The sRGB red component of the fog colour; Lite's fog block decodes it itself.\n * @param g - The sRGB green component.\n * @param b - The sRGB blue component.\n * @param density - The density, for the exponential modes.\n * @param start - Where linear fog begins, in metres.\n * @param end - Where linear fog reaches full strength, in metres.\n *\n * @internal\n */\nexport function setSceneFog(\n scene: SceneContext,\n mode: FogMode,\n r: number,\n g: number,\n b: number,\n density: number,\n start: number,\n end: number,\n): void {\n if (mode === \"none\" && scene.fog === null) {\n // A scene that never had fog pays nothing: no contributor, no fog block in any PBR pipeline.\n return;\n }\n setFog(scene, { mode: FOG_MODES[mode], density, start, end, color: [r, g, b] });\n}\n\n/**\n * Sets exposure, contrast, and the tone-mapping curve.\n *\n * @remarks\n * Asynchronous by nature: tone mapping is compiled into the PBR shaders, so changing it after\n * `registerScene` recompiles the scene's PBR pipelines. Exposure and contrast alone are uniform\n * values, but Lite routes them through the same call.\n *\n * @param scene - The scene to change.\n * @param exposure - The exposure multiplier.\n * @param contrast - The contrast multiplier.\n * @param toneMapping - The curve, or `\"none\"` to leave the colour untouched.\n * @returns A promise that resolves when any affected pipeline has been rebuilt.\n *\n * @internal\n */\nexport function setSceneImageProcessingOptions(\n scene: SceneContext,\n exposure: number,\n contrast: number,\n toneMapping: ToneMappingName,\n): Promise<void> {\n if (toneMapping === \"none\") {\n return setSceneImageProcessing(scene, { exposure, contrast, toneMappingEnabled: false });\n }\n if (toneMapping === \"agx\") {\n // Its own chunk: a project that never names AgX loads none of its WGSL (CONSTITUTION.md §2.5).\n return import(\"./agx-tone-mapping.js\").then(({ AgxToneMapping }) =>\n setSceneImageProcessing(scene, { exposure, contrast, toneMappingEnabled: true, toneMapping: AgxToneMapping }),\n );\n }\n return setSceneImageProcessing(scene, {\n exposure,\n contrast,\n toneMappingEnabled: true,\n toneMapping: toneMappingCurve(toneMapping),\n });\n}\n\n/**\n * Reads the image processing the scene's PBR shaders currently apply.\n *\n * @remarks\n * Read from Lite rather than from the `Environment` component, because Lite's `loadEnvironment`\n * also writes it (exposure 0.8, contrast 1.2, the standard curve) and the clear colour has to match\n * what the shaders actually do. A custom Lite curve set through `.lite` reads as `\"none\"`.\n *\n * @param scene - The scene.\n * @param out - Receives the exposure, contrast and curve.\n * @returns `out`.\n *\n * @internal\n */\nexport function readSceneImageProcessing(scene: SceneContext, out: ImageProcessingState): ImageProcessingState {\n const processing = scene.imageProcessing;\n out.exposure = processing.exposure;\n out.contrast = processing.contrast;\n out.curve = processing.toneMappingEnabled ? curveName(processing.toneMapping ?? StandardToneMapping) : \"none\";\n return out;\n}\n\n/**\n * Maps a Lite curve object back onto its ignifx name.\n *\n * @param curve - The Lite curve.\n * @returns The name, or `\"none\"` for a curve ignifx does not know.\n */\nfunction curveName(curve: ToneMapping): ToneMappingName {\n switch (curve.id) {\n case StandardToneMapping.id:\n return \"standard\";\n case AcesToneMapping.id:\n return \"aces\";\n case NeutralToneMapping.id:\n return \"neutral\";\n case AGX_TONE_MAPPING_ID:\n return \"agx\";\n default:\n return \"none\";\n }\n}\n\n/**\n * Maps an ignifx tone-mapping name onto the Lite curve object.\n *\n * @param name - The curve name; `\"none\"` and the lazily loaded `\"agx\"` are handled by the caller.\n * @returns The Lite curve.\n */\nfunction toneMappingCurve(name: Exclude<ToneMappingName, \"none\" | \"agx\">): ToneMapping {\n switch (name) {\n case \"standard\":\n return StandardToneMapping;\n case \"aces\":\n return AcesToneMapping;\n case \"neutral\":\n return NeutralToneMapping;\n default:\n return assertNever(name, \"tone mapping\");\n }\n}\n"],"mappings":";;;;;;;;;;AAiHA,MAAa,YAAY;;CAEvB,MAAM;;CAEN,KAAK;;CAEL,MAAM;;CAEN,QAAQ;AACV;;;;;;;AAeA,MAAa,qBAAqB;CAAC;CAAQ;CAAY;CAAQ;CAAW;AAAK;;;;;AAM/E,MAAM,sBAAsB;;;;;;;;;;;;;;;;;;AA8D5B,SAAgB,qBACd,OACA,SAC8B;CAC9B,MAAM,cAOF,EAAE,SAAS,QAAQ,QAAQ;CAC/B,IAAI,QAAQ,cAAc,KAAA,GACxB,YAAY,YAAY,QAAQ;CAElC,IAAI,QAAQ,eAAe,KAAA,GACzB,YAAY,aAAa,QAAQ;CAEnC,IAAI,QAAQ,eAAe,KAAA,GACzB,YAAY,aAAa,QAAQ;CAEnC,IAAI,QAAQ,eAAe,KAAA,GACzB,YAAY,aAAa,QAAQ;CAEnC,IAAI,QAAQ,qBAAqB,KAAA,GAC/B,YAAY,mBAAmB,QAAQ;CAEzC,OAAO,gBAAgB,OAAO,QAAQ,KAAK,WAAW;AACxD;;;;;;;AAkBA,SAAS,kBAAkB,OAA2C;CAMpE,OAAO;AACT;;;;;;;;;AAUA,SAAgB,qBAAqB,OAAiD;CAIpF,OAAO,kBAAkB,KAAK,CAAC,CAAC,gBAAgB;AAClD;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,SAAgB,wBAAwB,OAAqB,UAAwC;CACnG,MAAM,OAAO,kBAAkB,KAAK;CAGpC,IAAI,KAAK,iBAAiB,UACxB,OAAO;CAGT,KAAK,eAAe;CACpB,OAAO;AACT;;;;;;;;;AAyBA,SAAgB,4BAA4B,OAAqB,SAAuB;CACtF,uBAAuB,OAAO,SAAS,OAAO,CAAC;AACjD;;;;;;;;;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AQ,WAAW,qBAAqB,UAAU,WAAW,eAAe,mBAAmB,IAAI;CACvG,OAAO;AACT;;;;;;;AAQA,SAAS,UAAU,OAAqC;CACtD,QAAQ,MAAM,IAAd;EACE,KAAK,oBAAoB,IACvB,OAAO;EACT,KAAK,gBAAgB,IACnB,OAAO;EACT,KAAK,mBAAmB,IACtB,OAAO;EACT,KAAK,qBACH,OAAO;EACT,SACE,OAAO;CACX;AACF;;;;;;;AAQA,SAAS,iBAAiB,MAA6D;CACrF,QAAQ,MAAR;EACE,KAAK,YACH,OAAO;EACT,KAAK,QACH,OAAO;EACT,KAAK,WACH,OAAO;EACT,SACE,OAAO,YAAY,MAAM,cAAc;CAC3C;AACF"}
|
|
@@ -1,12 +1,11 @@
|
|
|
1
1
|
import { o as rebuildMaterialPipelines } from "./material-myMbl9mW.js";
|
|
2
|
-
import { SCENE_INPUT_TASK_NAMES, frameGraphTasks } from "./scene-inputs-
|
|
2
|
+
import { SCENE_INPUT_TASK_NAMES, frameGraphTasks } from "./scene-inputs-CbTkrkOw.js";
|
|
3
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
4
|
//#region src/lite/gpu/gtao.ts
|
|
5
5
|
/**
|
|
6
|
-
* Ground-truth ambient occlusion (`docs/
|
|
7
|
-
* `
|
|
8
|
-
*
|
|
9
|
-
* graph has none of these tasks (`CONSTITUTION.md` §2.5).
|
|
6
|
+
* Ground-truth ambient occlusion (`docs/architecture/07-rendering.md` §2.14). Its own chunk: the
|
|
7
|
+
* renderer imports it only when `rendering.ambientOcclusion.enabled` is on, so a project without it
|
|
8
|
+
* loads none of it and its frame graph has none of these tasks (`CONSTITUTION.md` §2.5).
|
|
10
9
|
*
|
|
11
10
|
* ```text
|
|
12
11
|
* … depth pyramid → gtao params → gtao (compute: horizons, then depth-aware blur) → scene → …
|
|
@@ -20,7 +19,7 @@ import { addComputeDispatch, addTaskAfter, buildFrameGraphTask, computeStorageTe
|
|
|
20
19
|
* from the scene inputs' world normals, rotated into view space. Slice angle and step offset are
|
|
21
20
|
* jittered per pixel with interleaved gradient noise.
|
|
22
21
|
* - **Denoise.** A 5×5 blur weighted by view-depth similarity, in the same compute pass.
|
|
23
|
-
* - **Indirect light only
|
|
22
|
+
* - **Indirect light only.** {@link createAmbientOcclusionPlugin} multiplies Lite's PBR
|
|
24
23
|
* `occlusion` variable, which scales the environment's irradiance and specular occlusion and
|
|
25
24
|
* nothing else (`lib/material/pbr/fragments/ibl-fragment.js`), by the AO texture at the
|
|
26
25
|
* fragment's screen position. Every lit PBR variant declares `occlusion` before that slot: the
|
|
@@ -33,7 +32,7 @@ import { addComputeDispatch, addTaskAfter, buildFrameGraphTask, computeStorageTe
|
|
|
33
32
|
* textures and bindings, swaps them in, and rebuilds the patched materials, whose bind groups hold
|
|
34
33
|
* the AO texture's view. The old textures are disposed a few frames later, once no in-flight bind
|
|
35
34
|
* group can still name them.
|
|
36
|
-
* - **TAA.** `rendering.taa`
|
|
35
|
+
* - **TAA.** `rendering.taa` filters the final colour, AO included; a dedicated AO history is
|
|
37
36
|
* not wired. It would accumulate {@link AmbientOcclusion.texture} before the plugin reads it.
|
|
38
37
|
*/
|
|
39
38
|
/**
|
|
@@ -256,8 +255,8 @@ fn main(@builtin(global_invocation_id) id: vec3<u32>) {
|
|
|
256
255
|
* @remarks
|
|
257
256
|
* At half resolution the AO texel under the fragment is blended bilinearly from four loads rather
|
|
258
257
|
* 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
|
|
260
|
-
* (
|
|
258
|
+
* scope keeps its names out of the shader's. `input.clipPos` is the fragment's
|
|
259
|
+
* `@builtin(position)`.
|
|
261
260
|
*
|
|
262
261
|
* @param scale - Full-resolution pixels per AO pixel.
|
|
263
262
|
* @returns The WGSL for `CUSTOM_FRAGMENT_BEFORE_LIGHTS`.
|
|
@@ -269,7 +268,7 @@ function gtaoPluginWgsl(scale) {
|
|
|
269
268
|
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
269
|
}
|
|
271
270
|
/**
|
|
272
|
-
* Builds the material plugin that applies the AO texture to indirect light
|
|
271
|
+
* Builds the material plugin that applies the AO texture to indirect light.
|
|
273
272
|
*
|
|
274
273
|
* @param scale - Full-resolution pixels per AO pixel.
|
|
275
274
|
* @param texture - Reads the current AO texture; it changes on resize.
|
|
@@ -627,4 +626,4 @@ function rebuildPatchedMaterials(scene, plugin) {
|
|
|
627
626
|
//#endregion
|
|
628
627
|
export { GTAO_PLUGIN_NAME, GTAO_TASK_NAMES, createAmbientOcclusion, createAmbientOcclusionPlugin, gtaoDenoiseWgsl, gtaoPluginWgsl, gtaoShape, gtaoWgsl };
|
|
629
628
|
|
|
630
|
-
//# sourceMappingURL=gtao-
|
|
629
|
+
//# sourceMappingURL=gtao-CVAYWBEJ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"gtao-CVAYWBEJ.js","names":[],"sources":["../src/lite/gpu/gtao.ts"],"sourcesContent":["import {\n addComputeDispatch,\n addTaskAfter,\n buildFrameGraphTask,\n computeTextureBinding,\n computeStorageTextureBinding,\n computeUniformBufferBinding,\n createComputeBindingSet,\n createComputeDispatch,\n createComputeShader,\n createComputeStorageTexture2D,\n createComputeTask,\n createComputeTextureResource,\n createUniformBuffer,\n disposeComputeBindingSet,\n disposeComputeShader,\n disposeComputeStorageTexture2D,\n disposeUniformBuffer,\n getEffectiveAspectRatio,\n getFrameGraph,\n getPbrUnlit,\n getProjectionMatrix,\n getViewMatrix,\n invertMat4,\n isPbrMaterial,\n removeComputeDispatch,\n updateUniformBuffer,\n} from \"@babylonjs/lite\";\nimport { rebuildMaterialPipelines } from \"../material.js\";\nimport { frameGraphTasks, SCENE_INPUT_TASK_NAMES } from \"./scene-inputs.js\";\nimport type { SceneInputs } from \"./scene-inputs.js\";\nimport type {\n ComputeDispatch,\n ComputeShader,\n ComputeStorageTexture2D,\n ComputeTask,\n EngineContext,\n Mat4,\n Material,\n MaterialPlugin,\n SceneContext,\n Task,\n UniformBuffer,\n} from \"@babylonjs/lite\";\n\n/**\n * Ground-truth ambient occlusion (`docs/architecture/07-rendering.md` §2.14). Its own chunk: the\n * renderer imports it only when `rendering.ambientOcclusion.enabled` is on, so a project without it\n * loads none of it and its frame graph has none of these tasks (`CONSTITUTION.md` §2.5).\n *\n * ```text\n * … depth pyramid → gtao params → gtao (compute: horizons, then depth-aware blur) → scene → …\n * └─ AO texture ─→ every lit PBR material's `occlusion`\n * ```\n *\n * - **GTAO** (Jimenez et al. 2016, after XeGTAO): per pixel, a few screen-space slices through the\n * view vector; along each, the highest horizon on either side within `radius`, then the cosine-\n * weighted visible arc between them against the normal projected into the slice. Depth comes from\n * the scene inputs' depth pyramid (level 1 at half resolution, coarser levels for far taps), normals\n * from the scene inputs' world normals, rotated into view space. Slice angle and step offset are\n * jittered per pixel with interleaved gradient noise.\n * - **Denoise.** A 5×5 blur weighted by view-depth similarity, in the same compute pass.\n * - **Indirect light only.** {@link createAmbientOcclusionPlugin} multiplies Lite's PBR\n * `occlusion` variable, which scales the environment's irradiance and specular occlusion and\n * nothing else (`lib/material/pbr/fragments/ibl-fragment.js`), by the AO texture at the\n * fragment's screen position. Every lit PBR variant declares `occlusion` before that slot: the\n * template's `occlusionDefault`, or the reflectance extension's own `AT` code\n * (`lib/material/pbr/fragments/reflectance-fragment.js` line 146). Standard materials, unlit PBR and\n * custom shaders are left alone.\n * - **Camera matrices** are written by a tiny task that runs inside the frame graph, after Lite has\n * updated world matrices for the frame, so the AO never lags a moving camera.\n * - **Resize and device loss.** The scene inputs' `onChange` disables the pass, rebuilds the\n * textures and bindings, swaps them in, and rebuilds the patched materials, whose bind groups hold\n * the AO texture's view. The old textures are disposed a few frames later, once no in-flight bind\n * group can still name them.\n * - **TAA.** `rendering.taa` filters the final colour, AO included; a dedicated AO history is\n * not wired. It would accumulate {@link AmbientOcclusion.texture} before the plugin reads it.\n */\n\n/**\n * The frame-graph task names, in the order they run after the scene inputs.\n *\n * @internal\n */\nexport const GTAO_TASK_NAMES = { params: \"ignifx:gtao-params\", compute: \"ignifx:gtao\" } as const;\n\n/**\n * The name the material plugin carries; part of Lite's pipeline cache key.\n *\n * @internal\n */\nexport const GTAO_PLUGIN_NAME = \"ignifx-gtao\";\n\n/** The uniform block: three matrices, the sizes, the settings. */\nconst UNIFORM_FLOATS = 16 * 3 + 4 + 4;\n\n/** Frames an old texture set outlives its replacement. */\nconst RETIRE_FRAMES = 8;\n\n/** The workgroup edge both shaders use. */\nconst WORKGROUP = 8;\n\n/**\n * What the GTAO pass is asked for.\n *\n * @internal\n */\nexport interface AmbientOcclusionOptions {\n /** `\"half\"` or `\"full\"` resolution. */\n readonly quality: \"half\" | \"full\";\n /** World-space radius. */\n readonly radius: number;\n /** Exponent on the visibility. */\n readonly intensity: number;\n /** Fraction of the radius over which occluders fade. */\n readonly falloff: number;\n /** Where an asynchronous rebuild's failure goes. */\n readonly onError: (error: unknown) => void;\n}\n\n/**\n * The slice and step counts and the resolution divisor of a quality.\n *\n * @internal\n */\nexport interface GtaoShape {\n /** Full-resolution pixels per AO pixel along each axis: 2 or 1. */\n readonly scale: number;\n /** The depth-pyramid level the centre depth is read from. */\n readonly baseMip: number;\n /** Screen-space slices per pixel. */\n readonly slices: number;\n /** Steps along each side of a slice. */\n readonly steps: number;\n}\n\n/**\n * The shape of a quality: `\"half\"` is 2 slices × 4 steps at half resolution, `\"full\"` 3 × 6 at full.\n *\n * @param quality - The quality.\n * @returns The shape.\n *\n * @internal\n */\nexport function gtaoShape(quality: \"half\" | \"full\"): GtaoShape {\n return quality === \"full\"\n ? { scale: 1, baseMip: 0, slices: 3, steps: 6 }\n : { scale: 2, baseMip: 1, slices: 2, steps: 4 };\n}\n\n/**\n * A running GTAO pass.\n *\n * @internal\n */\nexport interface AmbientOcclusion {\n /** The denoised AO texture, `rgba8unorm`, AO in every colour channel; replaced on resize. */\n readonly texture: ComputeStorageTexture2D;\n /**\n * Attaches the plugin to lit PBR materials that lack it and retires old textures. Once a frame.\n *\n * @param isSceneRegistered - Whether a patched material's pipelines must be rebuilt.\n */\n update(isSceneRegistered: boolean): void;\n /** Removes the tasks, frees every GPU object and releases the scene-inputs lease. Idempotent. */\n dispose(): void;\n}\n\n/** One device's worth of GPU objects, rebuilt on resize and device recovery. */\ninterface GpuSet {\n readonly uniforms: UniformBuffer;\n readonly raw: ComputeStorageTexture2D;\n readonly out: ComputeStorageTexture2D;\n readonly shaders: readonly ComputeShader[];\n readonly gtao: ComputeDispatch;\n readonly denoise: ComputeDispatch;\n /** Full-resolution width and height the set was built for. */\n readonly width: number;\n readonly height: number;\n}\n\n/**\n * Builds the GTAO compute shader.\n *\n * @param shape - The quality's shape, baked in as constants.\n * @returns The WGSL.\n *\n * @internal\n */\nexport function gtaoWgsl(shape: GtaoShape): string {\n return `\nstruct GtaoParams {\n proj: mat4x4<f32>,\n invProj: mat4x4<f32>,\n view: mat4x4<f32>,\n size: vec4<f32>,\n settings: vec4<f32>,\n};\n@group(0) @binding(0) var<uniform> params: GtaoParams;\n@group(0) @binding(1) var depthPyramid: texture_2d<f32>;\n@group(0) @binding(2) var normals: texture_2d<f32>;\n@group(0) @binding(3) var aoOut: texture_storage_2d<rgba16float, write>;\n\nconst SLICES: u32 = ${String(shape.slices)}u;\nconst STEPS: u32 = ${String(shape.steps)}u;\nconst BASE_MIP: i32 = ${String(shape.baseMip)};\nconst SCALE: f32 = ${shape.scale.toFixed(1)};\nconst PI: f32 = 3.14159265;\nconst HALF_PI: f32 = 1.57079633;\n\nfn loadDepth(pixel: vec2<f32>, mip: i32) -> f32 {\n let dims = vec2<i32>(textureDimensions(depthPyramid, mip));\n let coord = clamp(vec2<i32>(floor(pixel / f32(1 << u32(mip)))), vec2<i32>(0), dims - 1);\n return textureLoad(depthPyramid, coord, mip).r;\n}\n\nfn viewPosition(pixel: vec2<f32>, depth: f32) -> vec3<f32> {\n let uv = pixel / params.size.xy;\n let p = params.invProj * vec4<f32>(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, depth, 1.0);\n return p.xyz / p.w;\n}\n\nfn ign(p: vec2<f32>) -> f32 {\n return fract(52.9829189 * fract(dot(p, vec2<f32>(0.06711056, 0.00583715))));\n}\n\n@compute @workgroup_size(${String(WORKGROUP)}, ${String(WORKGROUP)})\nfn main(@builtin(global_invocation_id) id: vec3<u32>) {\n if (f32(id.x) >= params.size.z || f32(id.y) >= params.size.w) {\n return;\n }\n let pixel = (vec2<f32>(id.xy) + 0.5) * SCALE;\n let depth = loadDepth(pixel, BASE_MIP);\n if (depth <= 0.0) {\n textureStore(aoOut, vec2<i32>(id.xy), vec4<f32>(1.0, 0.0, 0.0, 1.0));\n return;\n }\n let P = viewPosition(pixel, depth);\n let V = normalize(viewPosition(pixel, 1.0) - P);\n let full = vec2<i32>(params.size.xy) - 1;\n let stored = textureLoad(normals, clamp(vec2<i32>(pixel), vec2<i32>(0), full), 0).xyz;\n let N = normalize((params.view * vec4<f32>(stored * 2.0 - 1.0, 0.0)).xyz);\n\n let radius = params.settings.x;\n let falloffRange = max(params.settings.y * radius, 0.0001);\n let c0 = params.proj * vec4<f32>(P, 1.0);\n let c1 = params.proj * vec4<f32>(P + vec3<f32>(radius, 0.0, 0.0), 1.0);\n 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));\n if (screenRadius < SCALE) {\n textureStore(aoOut, vec2<i32>(id.xy), vec4<f32>(1.0, abs(P.z), 0.0, 1.0));\n return;\n }\n let maxMip = i32(textureNumLevels(depthPyramid)) - 1;\n let noiseSlice = ign(vec2<f32>(id.xy));\n let noiseStep = ign(vec2<f32>(id.xy) + vec2<f32>(17.0, 59.0));\n\n var visibility = 0.0;\n for (var slice = 0u; slice < SLICES; slice++) {\n let phi = (f32(slice) + noiseSlice) * PI / f32(SLICES);\n let omega = vec2<f32>(cos(phi), -sin(phi));\n let direction = vec3<f32>(omega.x, -omega.y, 0.0);\n let orthoDirection = direction - dot(direction, V) * V;\n let axis = normalize(cross(orthoDirection, V));\n let projected = N - axis * dot(N, axis);\n let projectedLength = length(projected);\n let signN = sign(dot(orthoDirection, projected));\n let cosN = clamp(dot(projected, V) / max(projectedLength, 0.0001), 0.0, 1.0);\n let n = signN * acos(cosN);\n let low0 = cos(n + HALF_PI);\n let low1 = cos(n - HALF_PI);\n var horizon0 = low0;\n var horizon1 = low1;\n for (var step = 0u; step < STEPS; step++) {\n let t = (f32(step) + noiseStep) / f32(STEPS);\n let offsetLength = mix(SCALE, screenRadius, t * t);\n let mip = clamp(i32(floor(log2(offsetLength))) - 3, BASE_MIP, max(maxMip, BASE_MIP));\n let offset = omega * offsetLength;\n let d0 = loadDepth(pixel + offset, mip);\n let d1 = loadDepth(pixel - offset, mip);\n let s0 = viewPosition(pixel + offset, max(d0, 0.000001)) - P;\n let s1 = viewPosition(pixel - offset, max(d1, 0.000001)) - P;\n let l0 = length(s0);\n let l1 = length(s1);\n let w0 = select(0.0, clamp((radius - l0) / falloffRange, 0.0, 1.0), d0 > 0.0);\n let w1 = select(0.0, clamp((radius - l1) / falloffRange, 0.0, 1.0), d1 > 0.0);\n horizon0 = max(horizon0, mix(low0, dot(s0 / max(l0, 0.00001), V), w0));\n horizon1 = max(horizon1, mix(low1, dot(s1 / max(l1, 0.00001), V), w1));\n }\n var h0 = -acos(clamp(horizon1, -1.0, 1.0));\n var h1 = acos(clamp(horizon0, -1.0, 1.0));\n h0 = n + clamp(h0 - n, -HALF_PI, HALF_PI);\n h1 = n + clamp(h1 - n, -HALF_PI, HALF_PI);\n let sinN = sin(n);\n let arc0 = (cosN + 2.0 * h0 * sinN - cos(2.0 * h0 - n)) * 0.25;\n let arc1 = (cosN + 2.0 * h1 * sinN - cos(2.0 * h1 - n)) * 0.25;\n visibility += projectedLength * (arc0 + arc1);\n }\n visibility = clamp(visibility / f32(SLICES), 0.03, 1.0);\n let ao = pow(visibility, params.settings.z);\n textureStore(aoOut, vec2<i32>(id.xy), vec4<f32>(ao, abs(P.z), 0.0, 1.0));\n}\n`;\n}\n\n/**\n * Builds the denoise shader: a 5×5 Gaussian weighted by view-depth similarity.\n *\n * @returns The WGSL.\n *\n * @internal\n */\nexport function gtaoDenoiseWgsl(): string {\n return `\nstruct GtaoParams {\n proj: mat4x4<f32>,\n invProj: mat4x4<f32>,\n view: mat4x4<f32>,\n size: vec4<f32>,\n settings: vec4<f32>,\n};\n@group(0) @binding(0) var<uniform> params: GtaoParams;\n@group(0) @binding(1) var rawAo: texture_2d<f32>;\n@group(0) @binding(2) var aoOut: texture_storage_2d<rgba8unorm, write>;\n\n@compute @workgroup_size(${String(WORKGROUP)}, ${String(WORKGROUP)})\nfn main(@builtin(global_invocation_id) id: vec3<u32>) {\n if (f32(id.x) >= params.size.z || f32(id.y) >= params.size.w) {\n return;\n }\n let dims = vec2<i32>(textureDimensions(rawAo)) - 1;\n let at = vec2<i32>(id.xy);\n let centre = textureLoad(rawAo, at, 0);\n if (centre.y <= 0.0) {\n textureStore(aoOut, at, vec4<f32>(centre.x, centre.x, centre.x, 1.0));\n return;\n }\n let tolerance = max(centre.y * 0.05, 0.0001);\n var sum = 0.0;\n var weights = 0.0;\n for (var y = -2; y <= 2; y++) {\n for (var x = -2; x <= 2; x++) {\n let tap = textureLoad(rawAo, clamp(at + vec2<i32>(x, y), vec2<i32>(0), dims), 0);\n let spatial = exp(-f32(x * x + y * y) / 4.5);\n let similar = max(0.0, 1.0 - abs(tap.y - centre.y) / tolerance);\n let weight = spatial * similar;\n sum += tap.x * weight;\n weights += weight;\n }\n }\n let ao = sum / max(weights, 0.0001);\n textureStore(aoOut, at, vec4<f32>(ao, ao, ao, 1.0));\n}\n`;\n}\n\n/**\n * The plugin code that multiplies a PBR fragment's `occlusion` by the AO texture.\n *\n * @remarks\n * At half resolution the AO texel under the fragment is blended bilinearly from four loads rather\n * than through a sampler, so the result does not depend on the storage texture's sampler. The block\n * scope keeps its names out of the shader's. `input.clipPos` is the fragment's\n * `@builtin(position)`.\n *\n * @param scale - Full-resolution pixels per AO pixel.\n * @returns The WGSL for `CUSTOM_FRAGMENT_BEFORE_LIGHTS`.\n *\n * @internal\n */\nexport function gtaoPluginWgsl(scale: number): string {\n if (scale === 1) {\n return (\n \"{let igxAoMax=vec2<i32>(textureDimensions(ignifxAo))-1;\" +\n \"occlusion*=textureLoad(ignifxAo,clamp(vec2<i32>(input.clipPos.xy),vec2<i32>(0),igxAoMax),0).r;}\"\n );\n }\n return (\n \"{let igxAoMax=vec2<i32>(textureDimensions(ignifxAo))-1;\" +\n `let igxAoF=input.clipPos.xy/${scale.toFixed(1)}-0.5;` +\n \"let igxAoB=vec2<i32>(floor(igxAoF));let igxAoT=fract(igxAoF);\" +\n \"let igxAo00=textureLoad(ignifxAo,clamp(igxAoB,vec2<i32>(0),igxAoMax),0).r;\" +\n \"let igxAo10=textureLoad(ignifxAo,clamp(igxAoB+vec2<i32>(1,0),vec2<i32>(0),igxAoMax),0).r;\" +\n \"let igxAo01=textureLoad(ignifxAo,clamp(igxAoB+vec2<i32>(0,1),vec2<i32>(0),igxAoMax),0).r;\" +\n \"let igxAo11=textureLoad(ignifxAo,clamp(igxAoB+vec2<i32>(1,1),vec2<i32>(0),igxAoMax),0).r;\" +\n \"occlusion*=mix(mix(igxAo00,igxAo10,igxAoT.x),mix(igxAo01,igxAo11,igxAoT.x),igxAoT.y);}\"\n );\n}\n\n/**\n * Builds the material plugin that applies the AO texture to indirect light.\n *\n * @param scale - Full-resolution pixels per AO pixel.\n * @param texture - Reads the current AO texture; it changes on resize.\n * @returns The plugin, shared by every lit PBR material.\n *\n * @internal\n */\nexport function createAmbientOcclusionPlugin(scale: number, texture: () => ComputeStorageTexture2D): MaterialPlugin {\n const fragment = { CUSTOM_FRAGMENT_BEFORE_LIGHTS: gtaoPluginWgsl(scale) };\n return {\n name: GTAO_PLUGIN_NAME,\n priority: 600,\n getSamplers: () => [{ texture: \"ignifxAo\", sampler: \"ignifxAoSampler\" }],\n // No `getActiveTextures`: the texture is the pass's own, and a material holding a pool reference\n // would stop it from being disposed on resize.\n bindTextures: (out) => {\n out.push({ texture: texture().sampledTexture });\n },\n getCustomCode: (stage) => (stage === \"fragment\" ? fragment : null),\n };\n}\n\n/**\n * Builds the GTAO pass, splices its tasks in after the scene inputs, and returns its handle.\n *\n * @remarks\n * Called once, from the renderer, with a scene-inputs lease the handle now owns. Before the scene is\n * registered (`isFrameGraphBuilt` `false`) `registerScene` records the tasks; afterwards they are\n * recorded here.\n *\n * @param engine - The engine.\n * @param scene - The render scene.\n * @param inputs - A scene-inputs lease; released by {@link AmbientOcclusion.dispose}.\n * @param options - The resolved settings.\n * @param isFrameGraphBuilt - Whether the scene is registered.\n * @returns The handle.\n *\n * @internal\n */\nexport async function createAmbientOcclusion(\n engine: EngineContext,\n scene: SceneContext,\n inputs: SceneInputs,\n options: AmbientOcclusionOptions,\n isFrameGraphBuilt: boolean,\n): Promise<AmbientOcclusion> {\n const shape = gtaoShape(options.quality);\n let current = await buildGpuSet(engine, inputs, shape);\n const retired: { set: GpuSet; frames: number }[] = [];\n const data = new Float32Array(UNIFORM_FLOATS);\n let isDisposed = false;\n let generation = 0;\n\n const compute: ComputeTask = createComputeTask(engine, GTAO_TASK_NAMES.compute);\n addComputeDispatch(compute, current.gtao);\n addComputeDispatch(compute, current.denoise);\n const params = createExecuteTask(engine, scene, GTAO_TASK_NAMES.params, () => {\n const enabled = writeParams(scene, current, shape, options, data);\n current.gtao.enabled = enabled;\n current.denoise.enabled = enabled;\n if (enabled) {\n updateUniformBuffer(engine, current.uniforms, data);\n }\n });\n const tasks: readonly Task[] = [params, compute];\n const pyramid = frameGraphTasks(scene)?.find((task) => task.name === SCENE_INPUT_TASK_NAMES.depthPyramid);\n if (pyramid === undefined) {\n disposeGpuSet(current);\n inputs.release();\n throw new Error(\"GTAO needs the scene inputs' depth pyramid task in the frame graph.\");\n }\n addTaskAfter(scene, params, pyramid);\n addTaskAfter(scene, compute, params);\n if (isFrameGraphBuilt) {\n const graph = getFrameGraph(scene);\n for (const task of tasks) {\n buildFrameGraphTask(graph, task);\n }\n }\n\n const plugin = createAmbientOcclusionPlugin(shape.scale, () => current.out);\n const stopWatch = inputs.onChange(() => {\n generation += 1;\n const mine = generation;\n // The pyramid and the input textures were replaced; the bindings name freed ones.\n compute.executionEnabled = false;\n buildGpuSet(engine, inputs, shape).then(\n (next) => {\n if (isDisposed || mine !== generation) {\n disposeGpuSet(next);\n return;\n }\n removeComputeDispatch(compute, current.gtao);\n removeComputeDispatch(compute, current.denoise);\n addComputeDispatch(compute, next.gtao);\n addComputeDispatch(compute, next.denoise);\n retired.push({ set: current, frames: RETIRE_FRAMES });\n current = next;\n compute.executionEnabled = true;\n rebuildPatchedMaterials(scene, plugin);\n },\n (error: unknown) => {\n options.onError(error);\n },\n );\n });\n\n return {\n get texture(): ComputeStorageTexture2D {\n return current.out;\n },\n update(isSceneRegistered: boolean): void {\n if (isDisposed) {\n return;\n }\n attachPlugin(scene, plugin, isSceneRegistered);\n for (let index = retired.length - 1; index >= 0; index -= 1) {\n const entry = retired[index];\n if (entry !== undefined && --entry.frames <= 0) {\n disposeGpuSet(entry.set);\n retired.splice(index, 1);\n }\n }\n },\n dispose(): void {\n if (isDisposed) {\n return;\n }\n isDisposed = true;\n stopWatch();\n const list = frameGraphTasks(scene);\n for (const task of tasks) {\n // Disable first: a disposed task that still executes is a use-after-free.\n task.executionEnabled = false;\n const index = list?.indexOf(task) ?? -1;\n if (list !== null && index >= 0) {\n list.splice(index, 1);\n }\n task.dispose();\n }\n disposeGpuSet(current);\n for (const entry of retired) {\n disposeGpuSet(entry.set);\n }\n retired.length = 0;\n inputs.release();\n },\n };\n}\n\n/**\n * Writes this frame's uniforms from the scene's camera.\n *\n * @param scene - The scene.\n * @param set - The current GPU set, for its sizes.\n * @param shape - The quality's shape.\n * @param options - The settings.\n * @param out - The uniform floats.\n * @returns `false` when there is no camera or its projection does not invert, so the pass skips.\n */\nfunction writeParams(\n scene: SceneContext,\n set: GpuSet,\n shape: GtaoShape,\n options: AmbientOcclusionOptions,\n out: Float32Array,\n): boolean {\n const camera = scene.camera;\n if (camera === null) {\n return false;\n }\n const projection = getProjectionMatrix(camera, getEffectiveAspectRatio(camera, set.width, set.height));\n const inverse = invertMat4(projection);\n if (inverse === null) {\n return false;\n }\n copyMat4(projection, out, 0);\n copyMat4(inverse, out, 16);\n copyMat4(getViewMatrix(camera), out, 32);\n out[48] = set.width;\n out[49] = set.height;\n out[50] = set.raw.width;\n out[51] = set.raw.height;\n out[52] = options.radius;\n out[53] = options.falloff;\n out[54] = options.intensity;\n out[55] = shape.slices;\n return true;\n}\n\n/**\n * Copies a Lite matrix into a float array.\n *\n * @param matrix - The matrix, column-major.\n * @param out - The destination.\n * @param offset - Where the 16 floats start.\n */\nfunction copyMat4(matrix: Mat4, out: Float32Array, offset: number): void {\n for (let index = 0; index < 16; index += 1) {\n out[offset + index] = matrix[index] ?? 0;\n }\n}\n\n/**\n * Creates the textures, shaders and bindings for the current surface size and device.\n *\n * @param engine - The engine.\n * @param inputs - The scene-inputs lease.\n * @param shape - The quality's shape.\n * @returns The set.\n */\nasync function buildGpuSet(engine: EngineContext, inputs: SceneInputs, shape: GtaoShape): Promise<GpuSet> {\n const width = inputs.depth.width;\n const height = inputs.depth.height;\n const aoWidth = Math.max(1, Math.ceil(width / shape.scale));\n const aoHeight = Math.max(1, Math.ceil(height / shape.scale));\n const [pyramid, normals] = await Promise.all([\n createComputeTextureResource(engine, inputs.depthPyramid, { sampleType: \"unfilterable-float\" }),\n createComputeTextureResource(engine, inputs.normals, { sampleType: \"unfilterable-float\" }),\n ]);\n const uniforms = createUniformBuffer(engine, UNIFORM_FLOATS * 4, { label: \"ignifx:gtao-params\" });\n const raw = createComputeStorageTexture2D(engine, {\n width: aoWidth,\n height: aoHeight,\n format: \"rgba16float\",\n label: \"ignifx:gtao-raw\",\n invertY: false,\n });\n const out = createComputeStorageTexture2D(engine, {\n width: aoWidth,\n height: aoHeight,\n format: \"rgba8unorm\",\n label: \"ignifx:gtao\",\n invertY: false,\n });\n const gtaoShader = createComputeShader(engine, {\n name: \"ignifx:gtao\",\n computeSource: gtaoWgsl(shape),\n bindings: [\n computeUniformBufferBinding(\"params\", { group: 0, binding: 0 }),\n computeTextureBinding(\"depthPyramid\", { group: 0, binding: 1, sampleType: \"unfilterable-float\" }),\n computeTextureBinding(\"normals\", { group: 0, binding: 2, sampleType: \"unfilterable-float\" }),\n computeStorageTextureBinding(\"aoOut\", { group: 0, binding: 3, format: \"rgba16float\" }),\n ],\n });\n const denoiseShader = createComputeShader(engine, {\n name: \"ignifx:gtao-denoise\",\n computeSource: gtaoDenoiseWgsl(),\n bindings: [\n computeUniformBufferBinding(\"params\", { group: 0, binding: 0 }),\n computeTextureBinding(\"rawAo\", { group: 0, binding: 1, sampleType: \"float\" }),\n computeStorageTextureBinding(\"aoOut\", { group: 0, binding: 2, format: \"rgba8unorm\" }),\n ],\n });\n const size = { x: Math.ceil(aoWidth / WORKGROUP), y: Math.ceil(aoHeight / WORKGROUP) };\n const gtao = createComputeDispatch(\n gtaoShader,\n createComputeBindingSet(gtaoShader, { params: uniforms, depthPyramid: pyramid, normals, aoOut: raw }),\n { size, enabled: false },\n );\n const denoise = createComputeDispatch(\n denoiseShader,\n createComputeBindingSet(denoiseShader, { params: uniforms, rawAo: raw.computeTexture, aoOut: out }),\n { size, enabled: false },\n );\n return { uniforms, raw, out, shaders: [gtaoShader, denoiseShader], gtao, denoise, width, height };\n}\n\n/**\n * Frees a set's GPU objects.\n *\n * @param set - The set.\n */\nfunction disposeGpuSet(set: GpuSet): void {\n set.gtao.enabled = false;\n set.denoise.enabled = false;\n disposeComputeBindingSet(set.gtao.bindings);\n disposeComputeBindingSet(set.denoise.bindings);\n for (const shader of set.shaders) {\n disposeComputeShader(shader);\n }\n disposeComputeStorageTexture2D(set.raw);\n disposeComputeStorageTexture2D(set.out);\n disposeUniformBuffer(set.uniforms);\n}\n\n/**\n * Creates a frame-graph task that runs a callback each frame, inside the frame graph.\n *\n * @remarks\n * Lite runs a task's `execute()` fast path instead of its recorded passes\n * (`lib/frame-graph/frame-graph.js`); `record()` and `build()` clear and walk `_passes`, which such\n * a task leaves empty. It runs after Lite's per-frame world-matrix update, unlike `onBeforeRender`.\n *\n * @param engine - The engine.\n * @param scene - The scene.\n * @param name - The task name.\n * @param run - The callback.\n * @returns The task.\n */\nfunction createExecuteTask(engine: EngineContext, scene: SceneContext, name: string, run: () => void): Task {\n const task = {\n name,\n engine,\n scene,\n executionEnabled: true,\n // oxlint-disable-next-line no-underscore-dangle\n _passes: [] as unknown[],\n record(): void {\n // Nothing to record: the work happens in `execute`.\n },\n execute(): number {\n run();\n return 0;\n },\n dispose(): void {\n // Owns nothing.\n },\n };\n return task;\n}\n\n/**\n * Gives every lit PBR material in the scene the AO plugin, once.\n *\n * @remarks\n * A walk, for the reasons `./hdr-output.ts`'s `attachLinearOutput` gives: materials come from many\n * places, and a surface shader replaces a material's plugin list.\n *\n * @param scene - The scene.\n * @param plugin - The shared plugin.\n * @param isSceneRegistered - Whether a patched material's pipelines must be rebuilt.\n */\nfunction attachPlugin(scene: SceneContext, plugin: MaterialPlugin, isSceneRegistered: boolean): void {\n const meshes = scene.meshes;\n for (let index = 0; index < meshes.length; index += 1) {\n const material = meshes[index]?.material;\n // Declared non-null, but Lite's mesh factories create meshes with `material: null`.\n // oxlint-disable-next-line typescript/no-unnecessary-condition\n if (material === undefined || material === null || !isPbrMaterial(material)) {\n continue;\n }\n if (getPbrUnlit(material) !== undefined) {\n continue;\n }\n const current = material.plugins ?? [];\n if (current.includes(plugin)) {\n continue;\n }\n material.plugins = [...current, plugin];\n if (isSceneRegistered) {\n rebuildMaterialPipelines(scene, material);\n }\n }\n}\n\n/**\n * Rebuilds every material that carries the plugin, so its bind group names the new AO texture.\n *\n * @param scene - The scene.\n * @param plugin - The shared plugin.\n */\nfunction rebuildPatchedMaterials(scene: SceneContext, plugin: MaterialPlugin): void {\n const seen = new Set<Material>();\n const meshes = scene.meshes;\n for (let index = 0; index < meshes.length; index += 1) {\n const material = meshes[index]?.material;\n // oxlint-disable-next-line typescript/no-unnecessary-condition\n if (material === undefined || material === null || seen.has(material) || !isPbrMaterial(material)) {\n continue;\n }\n seen.add(material);\n if (material.plugins?.includes(plugin) === true) {\n rebuildMaterialPipelines(scene, material);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoFA,MAAa,kBAAkB;CAAE,QAAQ;CAAsB,SAAS;AAAc;;;;;;AAOtF,MAAa,mBAAmB;;AAGhC,MAAM,iBAAiB;;AAGvB,MAAM,gBAAgB;;AAGtB,MAAM,YAAY;;;;;;;;;AA4ClB,SAAgB,UAAU,SA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