@ignifx/core 0.13.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/dist/agx-tone-mapping-Cgt844j6.js +53 -0
  2. package/dist/agx-tone-mapping-Cgt844j6.js.map +1 -0
  3. package/dist/auto-exposure-uzPn0beO.js +246 -0
  4. package/dist/auto-exposure-uzPn0beO.js.map +1 -0
  5. package/dist/bloom-hdr-CLtQj-oY.js +315 -0
  6. package/dist/bloom-hdr-CLtQj-oY.js.map +1 -0
  7. package/dist/contact-shadows-T523EXaP.js +84 -0
  8. package/dist/contact-shadows-T523EXaP.js.map +1 -0
  9. package/dist/{environment-C9AjYJgV.js → environment-DPi0_0SP.js} +19 -5
  10. package/dist/environment-DPi0_0SP.js.map +1 -0
  11. package/dist/gtao-_nr0b6-E.js +630 -0
  12. package/dist/gtao-_nr0b6-E.js.map +1 -0
  13. package/dist/hdr-output-BrUvpAsE.js +525 -0
  14. package/dist/hdr-output-BrUvpAsE.js.map +1 -0
  15. package/dist/{ignifx-error-Dq2qJMkZ.js → ignifx-error-oYdVnT1S.js} +16 -1
  16. package/dist/ignifx-error-oYdVnT1S.js.map +1 -0
  17. package/dist/index.d.ts +753 -18
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +1679 -183
  20. package/dist/index.js.map +1 -1
  21. package/dist/{instanced-mesh-instance-DYwH0vLi.js → instanced-mesh-instance-NnODkvqK.js} +2 -2
  22. package/dist/{instanced-mesh-instance-DYwH0vLi.js.map → instanced-mesh-instance-NnODkvqK.js.map} +1 -1
  23. package/dist/mat4-D6exvAuO.js +949 -0
  24. package/dist/mat4-D6exvAuO.js.map +1 -0
  25. package/dist/material-CGk5mAah.js +204 -0
  26. package/dist/material-CGk5mAah.js.map +1 -0
  27. package/dist/{material-plugin-BOCB7Stt.js → material-plugin-BUlqLsap.js} +3 -204
  28. package/dist/material-plugin-BUlqLsap.js.map +1 -0
  29. package/dist/{post-effect-compiler-Dw6zW2cG.js → post-effect-compiler-CRek8VxQ.js} +2 -2
  30. package/dist/{post-effect-compiler-Dw6zW2cG.js.map → post-effect-compiler-CRek8VxQ.js.map} +1 -1
  31. package/dist/render-path-Be7WgN7r.js +166 -0
  32. package/dist/render-path-Be7WgN7r.js.map +1 -0
  33. package/dist/render-texture-C_TnaSz2.js +200 -0
  34. package/dist/render-texture-C_TnaSz2.js.map +1 -0
  35. package/dist/scene-color-passes-DlNr-qyZ.js +65 -0
  36. package/dist/scene-color-passes-DlNr-qyZ.js.map +1 -0
  37. package/dist/scene-inputs-BxGOsnIZ.js +318 -0
  38. package/dist/scene-inputs-BxGOsnIZ.js.map +1 -0
  39. package/dist/{shader-material-DRZmqA_S.js → shader-material-B6p66wB8.js} +18 -7
  40. package/dist/shader-material-B6p66wB8.js.map +1 -0
  41. package/dist/{shader-material-BxQn9FT4.js → shader-material-C0TAUr4t.js} +102 -4
  42. package/dist/shader-material-C0TAUr4t.js.map +1 -0
  43. package/dist/{shader-pragma-DrFm5f5m.js → shader-pragma-BKCoZTTA.js} +2 -2
  44. package/dist/{shader-pragma-DrFm5f5m.js.map → shader-pragma-BKCoZTTA.js.map} +1 -1
  45. package/dist/ssgi-Dm-maZrc.js +113 -0
  46. package/dist/ssgi-Dm-maZrc.js.map +1 -0
  47. package/dist/{surface-shader-BgZchRBe.js → surface-shader-BaK0kvBB.js} +5 -4
  48. package/dist/{surface-shader-BgZchRBe.js.map → surface-shader-BaK0kvBB.js.map} +1 -1
  49. package/dist/taa-BwBZLy11.js +480 -0
  50. package/dist/taa-BwBZLy11.js.map +1 -0
  51. package/dist/{vec3-T2PasQZv.js → vec3-D-0Y2mzE.js} +4 -948
  52. package/dist/vec3-D-0Y2mzE.js.map +1 -0
  53. package/package.json +1 -1
  54. package/dist/environment-C9AjYJgV.js.map +0 -1
  55. package/dist/ignifx-error-Dq2qJMkZ.js.map +0 -1
  56. package/dist/material-plugin-BOCB7Stt.js.map +0 -1
  57. package/dist/shader-material-BxQn9FT4.js.map +0 -1
  58. package/dist/shader-material-DRZmqA_S.js.map +0 -1
  59. package/dist/vec3-T2PasQZv.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"gtao-_nr0b6-E.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/plan/2026-11-gi-phase-1-execution-plan.md`, steps G8 and G9;\n * `docs/architecture/07-rendering.md` §2.14). Its own chunk: the renderer imports it only when\n * `rendering.ambientOcclusion.enabled` is on, so a project without it loads none of it and its frame\n * 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 (spike S3).** {@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` (G5) 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 `@builtin(position)`\n * (spike S3).\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 (spike S3).\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqFA,MAAa,kBAAkB;CAAE,QAAQ;CAAsB,SAAS;AAAc;;;;;;AAOtF,MAA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S,MAAM,MAAM,MACzC,yBAAyB,OAAO,QAAQ;CAE5C;AACF"}
@@ -0,0 +1,525 @@
1
+ import { o as rebuildMaterialPipelines } from "./material-CGk5mAah.js";
2
+ import { i as markHdrScene, t as DEPTH_STENCIL_FORMAT } from "./render-path-Be7WgN7r.js";
3
+ import { AGX_CALL_WGSL, AGX_HELPERS_WGSL } from "./agx-tone-mapping-Cgt844j6.js";
4
+ import { AcesToneMapping, NeutralToneMapping, StandardToneMapping, addTask, addTaskBefore, buildFrameGraphTask, createEffectRenderTask, createEffectWrapper, createRenderTarget, createRenderTask, createSurfaceRenderTargetTexture, enableMaterialPlugins, getFrameGraph, getPbrUnlit, isPbrMaterial, isStandardMaterial, onRenderTargetTextureResize, reconcileMaterialPlugins, setEffectTexture, setEffectUniforms, setEnvironmentRotation, setFog } from "@babylonjs/lite";
5
+ //#region src/lite/gpu/hdr-output.ts
6
+ /**
7
+ * The HDR render path (`docs/plan/2026-11-gi-phase-1-execution-plan.md`, step G2): the frame graph
8
+ * a scene gets when the project declares `rendering.hdr`. Its own chunk: `../engine.ts` imports it
9
+ * only when the setting is on, so a project without HDR loads none of it (`CONSTITUTION.md` §2.5).
10
+ *
11
+ * ```text
12
+ * [shadow] → scene ──→ hdr (rgba16float) ─ [custom effects, linear] ─→ output ──→ swapchain
13
+ * └──→ sceneColor ─ (built-in effects)
14
+ * ```
15
+ *
16
+ * - **Linear colour.** Lite's PBR shader ends every fragment with fog, exposure, the curve, a
17
+ * `pow(1/2.2)` encode, a clamp and contrast (`lib/material/pbr/pbr-template.js` line 171), so an
18
+ * `rgba16float` target alone still holds values ≤ 1. {@link createLinearOutputPlugin} saves the
19
+ * colour before that block and restores it before the fragment is written (spike S1).
20
+ * - **The output pass** applies the scene's `imageProcessing` — exposure, contrast and the curve
21
+ * the `Environment` set, or `loadEnvironment` set — then the same encode, clamp and contrast,
22
+ * so a PBR-only scene presents the same bytes as without HDR, within half-float rounding.
23
+ * - **Two output tasks.** A task cannot change its target once recorded, so there is one that
24
+ * writes the swapchain and one that writes `sceneColor`, an ordinary colour target a
25
+ * `PostProcessStack` chain reads. {@link ScenePresenter.setPresentEnabled} switches between them,
26
+ * so the frame runs exactly one.
27
+ *
28
+ * - **Every other colour writer (step G3).** The restore re-applies the PBR fog, so a fogged scene
29
+ * keeps its fog. A Standard material (and a surface shader on one) gets
30
+ * {@link createStandardLinearPlugin}, which decodes its display colour; a surface shader on a PBR
31
+ * host is caught by the PBR plugin, because its composite runs before the save. Lite's environment
32
+ * skyboxes (`.env`, `.dds`) are patched to return the cube map's linear colour
33
+ * ({@link linearSkyboxFragment}). Custom `.wgsl` materials (particles, foliage) are wrapped by
34
+ * `./shader-material.ts`, which asks {@link markHdrScene}'s record. Sprites need nothing: a
35
+ * `SpriteRenderer` draws its own pass onto the swapchain after the scene, so it never passes
36
+ * through the output pass. Under HDR, Standard and custom-shader colour now gets the scene's
37
+ * exposure, curve and contrast like everything else; with Lite's defaults (exposure 1, contrast 1,
38
+ * no curve) that is the identity and the image matches the plain path.
39
+ * - **Fog colour.** The scene's fog colour is stored decoded here, so the Standard fog block blends
40
+ * in linear space and the PBR restore can use it as is.
41
+ * - **Custom effects first.** A `PostProcessStack`'s custom effects ordered before any built-in one
42
+ * are inserted before the output pass ({@link HdrOutputHandle.insertLinearTask}) and the output
43
+ * pass reads the last one's result ({@link HdrOutputHandle.setOutputSource}). Bloom, SMAA and
44
+ * Lite's image-processing task stay after it: they expect display colour and 8-bit targets.
45
+ *
46
+ * Not covered: Lite's six-face `loadSkybox` cube and its solid-colour and ground backgrounds, which
47
+ * have fixed shaders with no patch point; they still encode twice under HDR.
48
+ */
49
+ /**
50
+ * The colour format of the HDR scene target.
51
+ *
52
+ * @internal
53
+ */
54
+ const HDR_SCENE_FORMAT = "rgba16float";
55
+ /**
56
+ * The name the linear-output plugin carries; part of Lite's pipeline cache key.
57
+ *
58
+ * @internal
59
+ */
60
+ const LINEAR_OUTPUT_PLUGIN_NAME = "ignifx-hdr-linear-output";
61
+ /**
62
+ * The name the Standard material's decode plugin carries.
63
+ *
64
+ * @internal
65
+ */
66
+ const STANDARD_LINEAR_PLUGIN_NAME = "ignifx-hdr-linear-standard";
67
+ /**
68
+ * The name the unlit PBR material's plugin carries.
69
+ *
70
+ * @internal
71
+ */
72
+ const UNLIT_LINEAR_PLUGIN_NAME = "ignifx-hdr-linear-unlit";
73
+ /**
74
+ * Where the skybox patch sits in Lite's skybox patch list: after rotation (0) and blur (1)
75
+ * (`lib/scene/set-environment-rotation.js`, `lib/scene/set-environment-blur.js`).
76
+ */
77
+ const SKYBOX_PATCH_ORDER = 8;
78
+ /**
79
+ * Lite's fog factor (`lib/shader/wgsl-fog.js`) under an ignifx name: the PBR shader declares
80
+ * `calcFogFactor` only when the scene has fog, and the plugin code must compile either way.
81
+ */
82
+ const FOG_FACTOR_WGSL = "fn ignifxFogFactor(d:vec3<f32>)->f32{var k:f32=1.0;let mode=scene.vFogInfos.x;let dist=length(d);if(mode==3.0){k=(scene.vFogInfos.z-dist)/(scene.vFogInfos.z-scene.vFogInfos.y);}else if(mode==1.0){k=1.0/pow(2.71828,dist*scene.vFogInfos.w);}else if(mode==2.0){k=1.0/pow(2.71828,dist*dist*scene.vFogInfos.w*scene.vFogInfos.w);}return clamp(k,0.0,1.0);}";
83
+ /**
84
+ * The PBR fog block (`lib/material/pbr/pbr-fog-wgsl.js`) on the restored colour, except that the
85
+ * fog colour is already linear: the HDR path stores it decoded.
86
+ */
87
+ const FOG_RESTORE_WGSL = "if(scene.vFogInfos.x>0.0){color=mix(scene.vFogColor.rgb,color,pow(ignifxFogFactor((scene.view*vec4<f32>(input.worldPos,1.0)).xyz),2.2));}";
88
+ /**
89
+ * The frame-graph task names, in the order they run after `"scene"`.
90
+ *
91
+ * @internal
92
+ */
93
+ const HDR_OUTPUT_TASK_NAMES = {
94
+ toChain: "ignifx:hdr-output-chain",
95
+ toSwapchain: "ignifx:hdr-output"
96
+ };
97
+ /**
98
+ * The curve numbers the output shader branches on.
99
+ *
100
+ * @internal
101
+ */
102
+ const HDR_CURVE = {
103
+ none: 0,
104
+ standard: 1,
105
+ aces: 2,
106
+ neutral: 3,
107
+ agx: 4
108
+ };
109
+ /** The output pass's uniform block: exposure, contrast, curve, padding. */
110
+ const UNIFORM_FLOATS = 4;
111
+ /**
112
+ * Builds the material plugin that keeps a PBR fragment's colour linear.
113
+ *
114
+ * @remarks
115
+ * `CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION` is injected at two slots (`AI`, `NI`;
116
+ * `lib/material/plugin/plugin-bridge-shared.js` line 13), so the save is an assignment, never a
117
+ * `let`; the second one, after indirect light, wins. Priority 0 puts the restore ahead of any other
118
+ * plugin's `CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR` code, which then works on linear colour.
119
+ *
120
+ * @returns The plugin. Plain data, so one object can be shared by every material.
121
+ *
122
+ * @internal
123
+ */
124
+ function createLinearOutputPlugin() {
125
+ const fragment = {
126
+ CUSTOM_FRAGMENT_DEFINITIONS: `var<private> ignifxLinearColor: vec3<f32>;${FOG_FACTOR_WGSL}`,
127
+ CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION: "ignifxLinearColor = color;",
128
+ CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR: `color = ignifxLinearColor;${FOG_RESTORE_WGSL}`
129
+ };
130
+ return {
131
+ name: LINEAR_OUTPUT_PLUGIN_NAME,
132
+ priority: 0,
133
+ getCustomCode: (stage) => stage === "fragment" ? fragment : null
134
+ };
135
+ }
136
+ /**
137
+ * Builds the plugin that keeps an unlit PBR material's colour linear.
138
+ *
139
+ * @remarks
140
+ * With no environment, Lite's unlit fragment assigns its colour at the `NI` slot
141
+ * (`lib/material/pbr/fragments/unlit-fragment.js`), after the linear-output plugin's save there, so
142
+ * the save would hold the lit colour. This plugin recomputes the unlit colour instead
143
+ * (`baseColor * material.unlitColor`, both in scope before the fragment is written), then applies
144
+ * the fog the restore would.
145
+ *
146
+ * @returns The plugin, shared by every unlit PBR material.
147
+ *
148
+ * @internal
149
+ */
150
+ function createUnlitLinearPlugin() {
151
+ const fragment = {
152
+ CUSTOM_FRAGMENT_DEFINITIONS: FOG_FACTOR_WGSL,
153
+ CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR: `color = baseColor*material.unlitColor;${FOG_RESTORE_WGSL}`
154
+ };
155
+ return {
156
+ name: UNLIT_LINEAR_PLUGIN_NAME,
157
+ priority: 0,
158
+ getCustomCode: (stage) => stage === "fragment" ? fragment : null
159
+ };
160
+ }
161
+ /**
162
+ * Builds the plugin that turns a Standard material's colour linear.
163
+ *
164
+ * @remarks
165
+ * Lite's Standard shader does no image processing and no encode: what it writes is the colour that
166
+ * is displayed. The plugin decodes it with the exact inverse of the output pass's encode
167
+ * (`pow(c, 2.2)`), so the output pass gives it back. It runs at the `BC` slot, before Lite's Standard fog
168
+ * block (the `BA` slot), which then mixes in the decoded fog colour. Priority 1000 puts it after any
169
+ * surface shader's own `CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR` code.
170
+ *
171
+ * @returns The plugin, shared by every Standard material.
172
+ *
173
+ * @internal
174
+ */
175
+ function createStandardLinearPlugin() {
176
+ const fragment = { CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR: "color=vec4<f32>(pow(max(color.rgb,vec3<f32>(0.0)),vec3<f32>(2.2)),color.a);" };
177
+ return {
178
+ name: STANDARD_LINEAR_PLUGIN_NAME,
179
+ priority: 1e3,
180
+ getCustomCode: (stage) => stage === "fragment" ? fragment : null
181
+ };
182
+ }
183
+ /**
184
+ * Makes one of Lite's environment skybox shaders return the cube map's linear colour.
185
+ *
186
+ * @remarks
187
+ * The `.env` (`"hdr"`) and `.dds` skyboxes multiply by `mesh.exposureLinear`, then encode, clamp
188
+ * and apply contrast themselves (`lib/material/pbr/background-hdr-skybox.js`,
189
+ * `lib/_chunks/background-dds-skybox-*.js`), and Lite gives them no material plugin point. The patch
190
+ * returns the colour just before that multiply, so the output pass applies exposure, the curve and
191
+ * the encode once. Code after the inserted `return` is unreachable, which WGSL accepts. A shader the
192
+ * pattern does not match is returned unchanged.
193
+ *
194
+ * @param fragment - The skybox fragment WGSL, after Lite's own rotation and blur patches.
195
+ * @returns The patched WGSL.
196
+ *
197
+ * @internal
198
+ */
199
+ function linearSkyboxFragment(fragment) {
200
+ const match = /\b([A-Za-z_]\w*)\*=mesh\.exposureLinear;/u.exec(fragment);
201
+ if (match === null) return fragment;
202
+ return `${fragment.slice(0, match.index)}return vec4<f32>(${match[1] ?? ""},1.0);${fragment.slice(match.index)}`;
203
+ }
204
+ /**
205
+ * A fog configuration with its colour decoded the way Lite's PBR fog block decodes it.
206
+ *
207
+ * @param fog - The configuration the `Environment` installed, colour in sRGB.
208
+ * @returns A fresh configuration, colour linear.
209
+ *
210
+ * @internal
211
+ */
212
+ function linearFogConfig(fog) {
213
+ return {
214
+ mode: fog.mode,
215
+ density: fog.density,
216
+ start: fog.start,
217
+ end: fog.end,
218
+ color: [
219
+ fog.color[0] ** 2.2,
220
+ fog.color[1] ** 2.2,
221
+ fog.color[2] ** 2.2
222
+ ]
223
+ };
224
+ }
225
+ /**
226
+ * Builds the output pass's fragment shader.
227
+ *
228
+ * @remarks
229
+ * The curves are Lite's own WGSL (`ToneMapping.helpersWGSL`/`callWGSL`) and ignifx's AgX in the
230
+ * same form (`./agx-tone-mapping.ts`, so both paths run one function), which read the exposure
231
+ * from `scene.vImageInfos.x`; naming the uniform block `scene` lets them drop in unchanged. One
232
+ * shader holds all of them and branches on a uniform, so a curve change uploads 16 bytes instead
233
+ * of compiling a pipeline. The encode, clamp and contrast copy the PBR template's tail.
234
+ *
235
+ * @param autoExposure - Whether binding 2 holds the auto exposure texel (`./auto-exposure.ts`),
236
+ * `log2` of a multiplier applied before the curve.
237
+ * @returns The WGSL, with Lite's `effectFragment` entry point.
238
+ *
239
+ * @internal
240
+ */
241
+ function hdrOutputFragmentWgsl(autoExposure = false) {
242
+ return [
243
+ AcesToneMapping.helpersWGSL,
244
+ NeutralToneMapping.helpersWGSL,
245
+ AGX_HELPERS_WGSL,
246
+ "struct HdrOutputUniforms{vImageInfos:vec4<f32>};",
247
+ "@group(0)@binding(0)var<uniform>scene:HdrOutputUniforms;",
248
+ "@group(0)@binding(1)var hdrColor:texture_2d<f32>;",
249
+ autoExposure ? "@group(0)@binding(2)var autoExposure:texture_2d<f32>;" : "",
250
+ "@fragment fn effectFragment(fragment:EffectVertexOutput)->@location(0)vec4<f32>{",
251
+ "let texel=textureLoad(hdrColor,vec2<i32>(fragment.position.xy),0);",
252
+ "var color=max(texel.rgb,vec3<f32>(0.0));",
253
+ autoExposure ? "color*=exp2(textureLoad(autoExposure,vec2<i32>(0,0),0).r);" : "",
254
+ "let curve=i32(scene.vImageInfos.z+0.5);",
255
+ `if(curve==${String(HDR_CURVE.standard)}){${StandardToneMapping.callWGSL}}`,
256
+ `else if(curve==${String(HDR_CURVE.aces)}){${AcesToneMapping.callWGSL}}`,
257
+ `else if(curve==${String(HDR_CURVE.neutral)}){${NeutralToneMapping.callWGSL}}`,
258
+ `else if(curve==${String(HDR_CURVE.agx)}){${AGX_CALL_WGSL}}`,
259
+ "else{color*=scene.vImageInfos.x;}",
260
+ "color=pow(color,vec3<f32>(1.0/2.2));",
261
+ "color=clamp(color,vec3<f32>(0.0),vec3<f32>(1.0));",
262
+ "let highContrast=color*color*(3.0-2.0*color);",
263
+ "if(scene.vImageInfos.y<1.0){color=mix(vec3<f32>(0.5),color,scene.vImageInfos.y);}",
264
+ "else{color=mix(color,highContrast,scene.vImageInfos.y-1.0);}",
265
+ "color=max(color,vec3<f32>(0.0));",
266
+ "return vec4<f32>(color,texel.a);",
267
+ "}"
268
+ ].join("\n");
269
+ }
270
+ /**
271
+ * The curve number for a scene's image processing.
272
+ *
273
+ * @remarks
274
+ * Tone mapping switched on with no curve named is Lite's standard curve (`pbr-renderable.js`). A
275
+ * custom Lite curve the output pass does not know falls back to the standard one.
276
+ *
277
+ * @param processing - The scene's image processing.
278
+ * @returns One of {@link HDR_CURVE}.
279
+ *
280
+ * @internal
281
+ */
282
+ function hdrCurveOf(processing) {
283
+ if (!processing.toneMappingEnabled) return HDR_CURVE.none;
284
+ const id = processing.toneMapping?.id;
285
+ if (id === AcesToneMapping.id) return HDR_CURVE.aces;
286
+ if (id === "ignifx-agx") return HDR_CURVE.agx;
287
+ return id === NeutralToneMapping.id ? HDR_CURVE.neutral : HDR_CURVE.standard;
288
+ }
289
+ /**
290
+ * Writes the output pass's uniforms and says whether they changed.
291
+ *
292
+ * @param processing - The scene's image processing.
293
+ * @param out - The four floats: exposure, contrast, curve, padding.
294
+ * @returns `true` when `out` now differs from what it held.
295
+ *
296
+ * @internal
297
+ */
298
+ function writeHdrOutputUniforms(processing, out) {
299
+ const curve = hdrCurveOf(processing);
300
+ if (out[0] === processing.exposure && out[1] === processing.contrast && out[2] === curve) return false;
301
+ out[0] = processing.exposure;
302
+ out[1] = processing.contrast;
303
+ out[2] = curve;
304
+ return true;
305
+ }
306
+ /**
307
+ * Builds the HDR render path and appends it to the scene's frame graph.
308
+ *
309
+ * @remarks
310
+ * The same contract as `installOffscreenRenderPath` in `./render-path.ts`: call it right after
311
+ * `createSceneContext(engine, { defaultRenderTask: false })` and before `registerScene`. It also
312
+ * installs Lite's material-plugin bridges, which the linear-output plugin needs before the scene is
313
+ * registered. With MSAA on, the scene draws into a multisampled `rgba16float` target that resolves
314
+ * into the sampled one.
315
+ *
316
+ * @param engine - The engine, which is also the primary surface.
317
+ * @param scene - The scene created with no default render task.
318
+ * @param installAutoExposure - Builds the auto exposure passes over the HDR texture, between the
319
+ * scene task and the output tasks (`./auto-exposure.ts`); omitted when auto exposure is off.
320
+ * @returns The presenter, with its {@link ScenePresenter.hdr} handle set.
321
+ *
322
+ * @internal
323
+ */
324
+ function installHdrRenderPath(engine, scene, installAutoExposure) {
325
+ enableMaterialPlugins(scene);
326
+ markHdrScene(scene);
327
+ installLinearSkybox(scene);
328
+ const hdr = createSurfaceRenderTargetTexture(engine, {
329
+ lbl: "ignifx:scene-hdr",
330
+ format: HDR_SCENE_FORMAT,
331
+ samples: 1,
332
+ size: engine
333
+ });
334
+ const isMultisampled = engine.msaaSamples > 1;
335
+ const config = {
336
+ name: "scene",
337
+ rt: hdr.rt
338
+ };
339
+ if (isMultisampled) {
340
+ config.rt = createRenderTarget({
341
+ lbl: "ignifx:scene-hdr-msaa",
342
+ format: HDR_SCENE_FORMAT,
343
+ dFormat: DEPTH_STENCIL_FORMAT,
344
+ samples: engine.msaaSamples,
345
+ size: engine
346
+ });
347
+ config.rst = hdr.rt;
348
+ } else config.depth = createRenderTarget({
349
+ lbl: "ignifx:scene-depth",
350
+ dFormat: DEPTH_STENCIL_FORMAT,
351
+ samples: 1,
352
+ size: engine
353
+ });
354
+ const sceneTask = createRenderTask(config, engine, scene);
355
+ addTask(scene, sceneTask);
356
+ const autoExposure = installAutoExposure?.(hdr.texture) ?? null;
357
+ const effect = createEffectWrapper(engine, {
358
+ name: "ignifx:hdr-output",
359
+ fragmentWGSL: hdrOutputFragmentWgsl(autoExposure !== null),
360
+ bindings: [
361
+ {
362
+ name: "hdrOutput",
363
+ binding: 0,
364
+ kind: "uniform",
365
+ uniformByteLength: 16
366
+ },
367
+ {
368
+ name: "hdrColor",
369
+ binding: 1,
370
+ kind: "texture"
371
+ },
372
+ ...autoExposure === null ? [] : [{
373
+ name: "autoExposure",
374
+ binding: 2,
375
+ kind: "texture",
376
+ textureSampleType: "unfilterable-float"
377
+ }]
378
+ ]
379
+ });
380
+ setEffectTexture(effect, 1, hdr.texture);
381
+ if (autoExposure !== null) setEffectTexture(effect, 2, autoExposure.exposureTexture);
382
+ let outputSource = null;
383
+ onRenderTargetTextureResize(hdr, () => {
384
+ setEffectTexture(effect, 1, outputSource ?? hdr.texture);
385
+ });
386
+ const uniforms = new Float32Array(UNIFORM_FLOATS);
387
+ uniforms[0] = NaN;
388
+ writeHdrOutputUniforms(scene.imageProcessing, uniforms);
389
+ setEffectUniforms(effect, uniforms);
390
+ const sceneColor = createRenderTarget({
391
+ lbl: "ignifx:scene-color",
392
+ format: engine.format,
393
+ samples: 1,
394
+ size: engine
395
+ });
396
+ const toChain = createEffectRenderTask({
397
+ name: HDR_OUTPUT_TASK_NAMES.toChain,
398
+ effect,
399
+ target: sceneColor,
400
+ clear: true
401
+ }, engine, scene);
402
+ const toSwapchain = createEffectRenderTask({
403
+ name: HDR_OUTPUT_TASK_NAMES.toSwapchain,
404
+ effect,
405
+ target: engine.scRT,
406
+ clear: true
407
+ }, engine, scene);
408
+ addTask(scene, toChain);
409
+ addTask(scene, toSwapchain);
410
+ toChain.executionEnabled = false;
411
+ const plugins = {
412
+ pbr: createLinearOutputPlugin(),
413
+ unlit: createUnlitLinearPlugin(),
414
+ standard: createStandardLinearPlugin()
415
+ };
416
+ let linearFog = null;
417
+ const handle = {
418
+ sceneTexture: hdr.texture,
419
+ exposureTexture: autoExposure?.exposureTexture ?? null,
420
+ sceneTarget: hdr.rt,
421
+ sceneTask,
422
+ sceneTargetTexture: hdr,
423
+ update(isSceneRegistered) {
424
+ autoExposure?.update();
425
+ if (writeHdrOutputUniforms(scene.imageProcessing, uniforms)) setEffectUniforms(effect, uniforms);
426
+ const fog = scene.fog;
427
+ if (fog !== null && fog !== linearFog) {
428
+ linearFog = linearFogConfig(fog);
429
+ setFog(scene, linearFog);
430
+ }
431
+ attachLinearOutput(scene, plugins, isSceneRegistered);
432
+ },
433
+ insertLinearTask(task, isFrameGraphBuilt) {
434
+ addTaskBefore(scene, task, toChain);
435
+ if (isFrameGraphBuilt) buildFrameGraphTask(getFrameGraph(scene), task);
436
+ },
437
+ setOutputSource(texture) {
438
+ if (texture === outputSource) return;
439
+ outputSource = texture;
440
+ setEffectTexture(effect, 1, texture ?? hdr.texture);
441
+ }
442
+ };
443
+ let isPresentEnabled = true;
444
+ return {
445
+ sceneColor,
446
+ swapchain: engine.scRT,
447
+ setPresentEnabled(enabled) {
448
+ isPresentEnabled = enabled;
449
+ toSwapchain.executionEnabled = enabled;
450
+ toChain.executionEnabled = !enabled;
451
+ },
452
+ get isPresentEnabled() {
453
+ return isPresentEnabled;
454
+ },
455
+ hdr: handle,
456
+ scenePass: {
457
+ task: sceneTask,
458
+ target: hdr.rt,
459
+ format: HDR_SCENE_FORMAT
460
+ }
461
+ };
462
+ }
463
+ /**
464
+ * Makes Lite's environment skyboxes write linear colour (see {@link linearSkyboxFragment}).
465
+ *
466
+ * @remarks
467
+ * Lite composes a skybox's fragment through `scene._environmentSkyboxShaderComposer`, which runs the
468
+ * loaders in `scene._environmentSkyboxShaderPatchLoaders` in order
469
+ * (`lib/material/pbr/environment-skybox-shader-composer.js`). Neither field is declared in
470
+ * `index.d.ts`, and the composer is created only by Lite's own registration, which also prepends
471
+ * the scene uniforms the `.env` skybox needs. `setEnvironmentRotation(scene, 0)` is that
472
+ * registration with no visible effect (rotation 0 is what the scene has); the `Environment`
473
+ * overwrites it with its own rotation later. The patch is installed before any environment loads,
474
+ * and pinned by `test/render/hdr-coverage.browser.test.ts`.
475
+ *
476
+ * @param scene - The HDR scene.
477
+ */
478
+ function installLinearSkybox(scene) {
479
+ setEnvironmentRotation(scene, 0);
480
+ const slots = scene;
481
+ const loaders = slots._environmentSkyboxShaderPatchLoaders ??= [];
482
+ loaders[SKYBOX_PATCH_ORDER] = () => Promise.resolve({ _apply: linearSkyboxFragment });
483
+ }
484
+ /**
485
+ * Gives every PBR and Standard material in the scene its linear-output plugin, once.
486
+ *
487
+ * @remarks
488
+ * A walk rather than a hook at material creation, because materials come from several places
489
+ * (material assets, glTF models, `.lite` code) and a surface shader replaces a material's whole
490
+ * plugin list; a material that lost the plugin gets it back on the next frame. A PBR skybox
491
+ * (`setPbrSkybox`) is a PBR material and gets the PBR plugin. Lite's mesh factories leave
492
+ * `material` `null` until one is assigned.
493
+ *
494
+ * @param scene - The scene to walk.
495
+ * @param shared - The shared plugins.
496
+ * @param isSceneRegistered - Whether a patched material's pipelines must be rebuilt.
497
+ */
498
+ function attachLinearOutput(scene, shared, isSceneRegistered) {
499
+ const meshes = scene.meshes;
500
+ for (let index = 0; index < meshes.length; index += 1) {
501
+ const material = meshes[index]?.material;
502
+ if (material === void 0 || material === null) continue;
503
+ let plugin;
504
+ if (isPbrMaterial(material)) plugin = getPbrUnlit(material) === void 0 ? shared.pbr : shared.unlit;
505
+ else if (isStandardMaterial(material)) plugin = shared.standard;
506
+ else continue;
507
+ const current = material.plugins ?? [];
508
+ let stale = null;
509
+ if (plugin === shared.pbr) stale = shared.unlit;
510
+ else if (plugin === shared.unlit) stale = shared.pbr;
511
+ const hasStale = stale !== null && current.includes(stale);
512
+ if (current.includes(plugin) && !hasStale) continue;
513
+ const kept = hasStale ? current.filter((other) => other !== stale) : current;
514
+ material.plugins = kept.includes(plugin) ? kept : [...kept, plugin];
515
+ if (plugin === shared.standard) {
516
+ reconcileMaterialPlugins(scene, material);
517
+ continue;
518
+ }
519
+ if (isSceneRegistered) rebuildMaterialPipelines(scene, material);
520
+ }
521
+ }
522
+ //#endregion
523
+ export { installHdrRenderPath };
524
+
525
+ //# sourceMappingURL=hdr-output-BrUvpAsE.js.map