@ignifx/core 0.12.0 → 0.14.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 (31) hide show
  1. package/dist/{environment-C9AjYJgV.js → environment-Cq2BmA96.js} +2 -2
  2. package/dist/{environment-C9AjYJgV.js.map → environment-Cq2BmA96.js.map} +1 -1
  3. package/dist/hdr-output-DDpIo4Q5.js +300 -0
  4. package/dist/hdr-output-DDpIo4Q5.js.map +1 -0
  5. package/dist/{ignifx-error-Dq2qJMkZ.js → ignifx-error-oYdVnT1S.js} +16 -1
  6. package/dist/ignifx-error-oYdVnT1S.js.map +1 -0
  7. package/dist/index.d.ts +343 -4
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +842 -165
  10. package/dist/index.js.map +1 -1
  11. package/dist/material-CGk5mAah.js +204 -0
  12. package/dist/material-CGk5mAah.js.map +1 -0
  13. package/dist/{material-plugin-BOCB7Stt.js → material-plugin-BUlqLsap.js} +3 -204
  14. package/dist/material-plugin-BUlqLsap.js.map +1 -0
  15. package/dist/{post-effect-compiler-Dw6zW2cG.js → post-effect-compiler-CRek8VxQ.js} +2 -2
  16. package/dist/{post-effect-compiler-Dw6zW2cG.js.map → post-effect-compiler-CRek8VxQ.js.map} +1 -1
  17. package/dist/render-path-Dx0learj.js +135 -0
  18. package/dist/render-path-Dx0learj.js.map +1 -0
  19. package/dist/render-texture-IuR0iFVa.js +174 -0
  20. package/dist/render-texture-IuR0iFVa.js.map +1 -0
  21. package/dist/{shader-material-BxQn9FT4.js → shader-material-BPb_oEZQ.js} +2 -2
  22. package/dist/{shader-material-BxQn9FT4.js.map → shader-material-BPb_oEZQ.js.map} +1 -1
  23. package/dist/{shader-material-DRZmqA_S.js → shader-material-CDQ0Y5kN.js} +3 -3
  24. package/dist/{shader-material-DRZmqA_S.js.map → shader-material-CDQ0Y5kN.js.map} +1 -1
  25. package/dist/{shader-pragma-DrFm5f5m.js → shader-pragma-BKCoZTTA.js} +2 -2
  26. package/dist/{shader-pragma-DrFm5f5m.js.map → shader-pragma-BKCoZTTA.js.map} +1 -1
  27. package/dist/{surface-shader-BgZchRBe.js → surface-shader-CwQ03yHG.js} +5 -4
  28. package/dist/{surface-shader-BgZchRBe.js.map → surface-shader-CwQ03yHG.js.map} +1 -1
  29. package/package.json +1 -1
  30. package/dist/ignifx-error-Dq2qJMkZ.js.map +0 -1
  31. package/dist/material-plugin-BOCB7Stt.js.map +0 -1
@@ -1,4 +1,4 @@
1
- import { n as assertNever } from "./ignifx-error-Dq2qJMkZ.js";
1
+ import { n as assertNever } from "./ignifx-error-oYdVnT1S.js";
2
2
  import { s as degToRad } from "./math-utils-BcDnL-gi.js";
3
3
  import { t as Color } from "./color-DrR6GFTd.js";
4
4
  import { AcesToneMapping, NeutralToneMapping, StandardToneMapping, loadEnvironment, setEnvironmentBlur, setEnvironmentRotation, setFog, setSceneImageProcessing } from "@babylonjs/lite";
@@ -280,4 +280,4 @@ function toneMappingCurve(name) {
280
280
  //#endregion
281
281
  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 };
282
282
 
283
- //# sourceMappingURL=environment-C9AjYJgV.js.map
283
+ //# sourceMappingURL=environment-Cq2BmA96.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"environment-C9AjYJgV.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.\n *\n * @public\n */\nexport const TONE_MAPPING_NAMES = [\"none\", \"standard\", \"aces\", \"neutral\"] as const;\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 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 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\"` is handled by the caller.\n * @returns The Lite curve.\n */\nfunction toneMappingCurve(name: Exclude<ToneMappingName, \"none\">): 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;;;;;;AAcA,MAAa,qBAAqB;CAAC;CAAQ;CAAY;CAAQ;AAAS;;;;;;;;;;;;;;;;;;AA8DxE,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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,QAAQ,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,SACE,OAAO;CACX;AACF;;;;;;;AAQA,SAAS,iBAAiB,MAAqD;CAC7E,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-Cq2BmA96.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.\n *\n * @public\n */\nexport const TONE_MAPPING_NAMES = [\"none\", \"standard\", \"aces\", \"neutral\"] as const;\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 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 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\"` is handled by the caller.\n * @returns The Lite curve.\n */\nfunction toneMappingCurve(name: Exclude<ToneMappingName, \"none\">): 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;;;;;;AAcA,MAAa,qBAAqB;CAAC;CA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import { t as DEPTH_STENCIL_FORMAT } from "./render-path-Dx0learj.js";
3
+ import { AcesToneMapping, NeutralToneMapping, StandardToneMapping, addTask, createEffectRenderTask, createEffectWrapper, createRenderTarget, createRenderTask, createSurfaceRenderTargetTexture, enableMaterialPlugins, isPbrMaterial, isPbrSkybox, onRenderTargetTextureResize, setEffectTexture, setEffectUniforms } from "@babylonjs/lite";
4
+ //#region src/lite/gpu/hdr-output.ts
5
+ /**
6
+ * The HDR render path (`docs/plan/2026-11-gi-phase-1-execution-plan.md`, step G2): the frame graph
7
+ * a scene gets when the project declares `rendering.hdr`. Its own chunk: `../engine.ts` imports it
8
+ * only when the setting is on, so a project without HDR loads none of it (`CONSTITUTION.md` §2.5).
9
+ *
10
+ * ```text
11
+ * [shadow] → scene ──→ hdr (rgba16float) ──→ output ──→ swapchain
12
+ * └──→ sceneColor ─ (a PostProcessStack's chain)
13
+ * ```
14
+ *
15
+ * - **Linear colour.** Lite's PBR shader ends every fragment with fog, exposure, the curve, a
16
+ * `pow(1/2.2)` encode, a clamp and contrast (`lib/material/pbr/pbr-template.js` line 171), so an
17
+ * `rgba16float` target alone still holds values ≤ 1. {@link createLinearOutputPlugin} saves the
18
+ * colour before that block and restores it before the fragment is written (spike S1).
19
+ * - **The output pass** applies the scene's `imageProcessing` — exposure, contrast and the curve
20
+ * the `Environment` set, or `loadEnvironment` set — then the same encode, clamp and contrast,
21
+ * so a PBR-only scene presents the same bytes as without HDR, within half-float rounding.
22
+ * - **Two output tasks.** A task cannot change its target once recorded, so there is one that
23
+ * writes the swapchain and one that writes `sceneColor`, an ordinary colour target a
24
+ * `PostProcessStack` chain reads. {@link ScenePresenter.setPresentEnabled} switches between them,
25
+ * so the frame runs exactly one.
26
+ *
27
+ * Not yet covered (step G3): fog is dropped with the restore; Standard materials, surface shaders,
28
+ * sprites, particles and the skybox still write encoded colour, which the output pass encodes again.
29
+ */
30
+ /**
31
+ * The colour format of the HDR scene target.
32
+ *
33
+ * @internal
34
+ */
35
+ const HDR_SCENE_FORMAT = "rgba16float";
36
+ /**
37
+ * The name the linear-output plugin carries; part of Lite's pipeline cache key.
38
+ *
39
+ * @internal
40
+ */
41
+ const LINEAR_OUTPUT_PLUGIN_NAME = "ignifx-hdr-linear-output";
42
+ /**
43
+ * The frame-graph task names, in the order they run after `"scene"`.
44
+ *
45
+ * @internal
46
+ */
47
+ const HDR_OUTPUT_TASK_NAMES = {
48
+ toChain: "ignifx:hdr-output-chain",
49
+ toSwapchain: "ignifx:hdr-output"
50
+ };
51
+ /**
52
+ * The curve numbers the output shader branches on.
53
+ *
54
+ * @internal
55
+ */
56
+ const HDR_CURVE = {
57
+ none: 0,
58
+ standard: 1,
59
+ aces: 2,
60
+ neutral: 3
61
+ };
62
+ /** The output pass's uniform block: exposure, contrast, curve, padding. */
63
+ const UNIFORM_FLOATS = 4;
64
+ /**
65
+ * Builds the material plugin that keeps a PBR fragment's colour linear.
66
+ *
67
+ * @remarks
68
+ * `CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION` is injected at two slots (`AI`, `NI`;
69
+ * `lib/material/plugin/plugin-bridge-shared.js` line 13), so the save is an assignment, never a
70
+ * `let`; the second one, after indirect light, wins. Priority 0 puts the restore ahead of any other
71
+ * plugin's `CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR` code, which then works on linear colour.
72
+ *
73
+ * @returns The plugin. Plain data, so one object can be shared by every material.
74
+ *
75
+ * @internal
76
+ */
77
+ function createLinearOutputPlugin() {
78
+ const fragment = {
79
+ CUSTOM_FRAGMENT_DEFINITIONS: "var<private> ignifxLinearColor: vec3<f32>;",
80
+ CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION: "ignifxLinearColor = color;",
81
+ CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR: "color = ignifxLinearColor;"
82
+ };
83
+ return {
84
+ name: LINEAR_OUTPUT_PLUGIN_NAME,
85
+ priority: 0,
86
+ getCustomCode: (stage) => stage === "fragment" ? fragment : null
87
+ };
88
+ }
89
+ /**
90
+ * Builds the output pass's fragment shader.
91
+ *
92
+ * @remarks
93
+ * The curves are Lite's own WGSL (`ToneMapping.helpersWGSL`/`callWGSL`), which read the exposure
94
+ * from `scene.vImageInfos.x`; naming the uniform block `scene` lets them drop in unchanged. One
95
+ * shader holds all of them and branches on a uniform, so a curve change uploads 16 bytes instead
96
+ * of compiling a pipeline. The encode, clamp and contrast copy the PBR template's tail.
97
+ *
98
+ * @returns The WGSL, with Lite's `effectFragment` entry point.
99
+ *
100
+ * @internal
101
+ */
102
+ function hdrOutputFragmentWgsl() {
103
+ return [
104
+ AcesToneMapping.helpersWGSL,
105
+ NeutralToneMapping.helpersWGSL,
106
+ "struct HdrOutputUniforms{vImageInfos:vec4<f32>};",
107
+ "@group(0)@binding(0)var<uniform>scene:HdrOutputUniforms;",
108
+ "@group(0)@binding(1)var hdrColor:texture_2d<f32>;",
109
+ "@fragment fn effectFragment(fragment:EffectVertexOutput)->@location(0)vec4<f32>{",
110
+ "let texel=textureLoad(hdrColor,vec2<i32>(fragment.position.xy),0);",
111
+ "var color=max(texel.rgb,vec3<f32>(0.0));",
112
+ "let curve=i32(scene.vImageInfos.z+0.5);",
113
+ `if(curve==${String(HDR_CURVE.standard)}){${StandardToneMapping.callWGSL}}`,
114
+ `else if(curve==${String(HDR_CURVE.aces)}){${AcesToneMapping.callWGSL}}`,
115
+ `else if(curve==${String(HDR_CURVE.neutral)}){${NeutralToneMapping.callWGSL}}`,
116
+ "else{color*=scene.vImageInfos.x;}",
117
+ "color=pow(color,vec3<f32>(1.0/2.2));",
118
+ "color=clamp(color,vec3<f32>(0.0),vec3<f32>(1.0));",
119
+ "let highContrast=color*color*(3.0-2.0*color);",
120
+ "if(scene.vImageInfos.y<1.0){color=mix(vec3<f32>(0.5),color,scene.vImageInfos.y);}",
121
+ "else{color=mix(color,highContrast,scene.vImageInfos.y-1.0);}",
122
+ "color=max(color,vec3<f32>(0.0));",
123
+ "return vec4<f32>(color,texel.a);",
124
+ "}"
125
+ ].join("\n");
126
+ }
127
+ /**
128
+ * The curve number for a scene's image processing.
129
+ *
130
+ * @remarks
131
+ * Tone mapping switched on with no curve named is Lite's standard curve (`pbr-renderable.js`). A
132
+ * custom Lite curve the output pass does not know falls back to the standard one.
133
+ *
134
+ * @param processing - The scene's image processing.
135
+ * @returns One of {@link HDR_CURVE}.
136
+ *
137
+ * @internal
138
+ */
139
+ function hdrCurveOf(processing) {
140
+ if (!processing.toneMappingEnabled) return HDR_CURVE.none;
141
+ const id = processing.toneMapping?.id;
142
+ if (id === AcesToneMapping.id) return HDR_CURVE.aces;
143
+ return id === NeutralToneMapping.id ? HDR_CURVE.neutral : HDR_CURVE.standard;
144
+ }
145
+ /**
146
+ * Writes the output pass's uniforms and says whether they changed.
147
+ *
148
+ * @param processing - The scene's image processing.
149
+ * @param out - The four floats: exposure, contrast, curve, padding.
150
+ * @returns `true` when `out` now differs from what it held.
151
+ *
152
+ * @internal
153
+ */
154
+ function writeHdrOutputUniforms(processing, out) {
155
+ const curve = hdrCurveOf(processing);
156
+ if (out[0] === processing.exposure && out[1] === processing.contrast && out[2] === curve) return false;
157
+ out[0] = processing.exposure;
158
+ out[1] = processing.contrast;
159
+ out[2] = curve;
160
+ return true;
161
+ }
162
+ /**
163
+ * Builds the HDR render path and appends it to the scene's frame graph.
164
+ *
165
+ * @remarks
166
+ * The same contract as `installOffscreenRenderPath` in `./render-path.ts`: call it right after
167
+ * `createSceneContext(engine, { defaultRenderTask: false })` and before `registerScene`. It also
168
+ * installs Lite's material-plugin bridges, which the linear-output plugin needs before the scene is
169
+ * registered. With MSAA on, the scene draws into a multisampled `rgba16float` target that resolves
170
+ * into the sampled one.
171
+ *
172
+ * @param engine - The engine, which is also the primary surface.
173
+ * @param scene - The scene created with no default render task.
174
+ * @returns The presenter, with its {@link ScenePresenter.hdr} handle set.
175
+ *
176
+ * @internal
177
+ */
178
+ function installHdrRenderPath(engine, scene) {
179
+ enableMaterialPlugins(scene);
180
+ const hdr = createSurfaceRenderTargetTexture(engine, {
181
+ lbl: "ignifx:scene-hdr",
182
+ format: HDR_SCENE_FORMAT,
183
+ samples: 1,
184
+ size: engine
185
+ });
186
+ const isMultisampled = engine.msaaSamples > 1;
187
+ const config = {
188
+ name: "scene",
189
+ rt: hdr.rt
190
+ };
191
+ if (isMultisampled) {
192
+ config.rt = createRenderTarget({
193
+ lbl: "ignifx:scene-hdr-msaa",
194
+ format: HDR_SCENE_FORMAT,
195
+ dFormat: DEPTH_STENCIL_FORMAT,
196
+ samples: engine.msaaSamples,
197
+ size: engine
198
+ });
199
+ config.rst = hdr.rt;
200
+ } else config.depth = createRenderTarget({
201
+ lbl: "ignifx:scene-depth",
202
+ dFormat: DEPTH_STENCIL_FORMAT,
203
+ samples: 1,
204
+ size: engine
205
+ });
206
+ addTask(scene, createRenderTask(config, engine, scene));
207
+ const effect = createEffectWrapper(engine, {
208
+ name: "ignifx:hdr-output",
209
+ fragmentWGSL: hdrOutputFragmentWgsl(),
210
+ bindings: [{
211
+ name: "hdrOutput",
212
+ binding: 0,
213
+ kind: "uniform",
214
+ uniformByteLength: 16
215
+ }, {
216
+ name: "hdrColor",
217
+ binding: 1,
218
+ kind: "texture"
219
+ }]
220
+ });
221
+ setEffectTexture(effect, 1, hdr.texture);
222
+ onRenderTargetTextureResize(hdr, () => {
223
+ setEffectTexture(effect, 1, hdr.texture);
224
+ });
225
+ const uniforms = new Float32Array(UNIFORM_FLOATS);
226
+ uniforms[0] = NaN;
227
+ writeHdrOutputUniforms(scene.imageProcessing, uniforms);
228
+ setEffectUniforms(effect, uniforms);
229
+ const sceneColor = createRenderTarget({
230
+ lbl: "ignifx:scene-color",
231
+ format: engine.format,
232
+ samples: 1,
233
+ size: engine
234
+ });
235
+ const toChain = createEffectRenderTask({
236
+ name: HDR_OUTPUT_TASK_NAMES.toChain,
237
+ effect,
238
+ target: sceneColor,
239
+ clear: true
240
+ }, engine, scene);
241
+ const toSwapchain = createEffectRenderTask({
242
+ name: HDR_OUTPUT_TASK_NAMES.toSwapchain,
243
+ effect,
244
+ target: engine.scRT,
245
+ clear: true
246
+ }, engine, scene);
247
+ addTask(scene, toChain);
248
+ addTask(scene, toSwapchain);
249
+ toChain.executionEnabled = false;
250
+ const plugin = createLinearOutputPlugin();
251
+ const handle = {
252
+ sceneTexture: hdr.texture,
253
+ update(isSceneRegistered) {
254
+ if (writeHdrOutputUniforms(scene.imageProcessing, uniforms)) setEffectUniforms(effect, uniforms);
255
+ attachLinearOutput(scene, plugin, isSceneRegistered);
256
+ }
257
+ };
258
+ let isPresentEnabled = true;
259
+ return {
260
+ sceneColor,
261
+ swapchain: engine.scRT,
262
+ setPresentEnabled(enabled) {
263
+ isPresentEnabled = enabled;
264
+ toSwapchain.executionEnabled = enabled;
265
+ toChain.executionEnabled = !enabled;
266
+ },
267
+ get isPresentEnabled() {
268
+ return isPresentEnabled;
269
+ },
270
+ hdr: handle
271
+ };
272
+ }
273
+ /**
274
+ * Gives every PBR material in the scene the linear-output plugin, once.
275
+ *
276
+ * @remarks
277
+ * A walk rather than a hook at material creation, because PBR materials come from several places
278
+ * (material assets, glTF models, `.lite` code) and a surface shader replaces a material's whole
279
+ * plugin list; a material that lost the plugin gets it back on the next frame. The skybox is left
280
+ * alone: it is not lit and G3 handles it.
281
+ *
282
+ * @param scene - The scene to walk.
283
+ * @param plugin - The shared plugin.
284
+ * @param isSceneRegistered - Whether a patched material's pipelines must be rebuilt.
285
+ */
286
+ function attachLinearOutput(scene, plugin, isSceneRegistered) {
287
+ const meshes = scene.meshes;
288
+ for (let index = 0; index < meshes.length; index += 1) {
289
+ const material = meshes[index]?.material;
290
+ if (material === void 0 || !isPbrMaterial(material) || isPbrSkybox(material)) continue;
291
+ const plugins = material.plugins ?? [];
292
+ if (plugins.includes(plugin)) continue;
293
+ material.plugins = [...plugins, plugin];
294
+ if (isSceneRegistered) rebuildMaterialPipelines(scene, material);
295
+ }
296
+ }
297
+ //#endregion
298
+ export { installHdrRenderPath };
299
+
300
+ //# sourceMappingURL=hdr-output-DDpIo4Q5.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hdr-output-DDpIo4Q5.js","names":[],"sources":["../src/lite/gpu/hdr-output.ts"],"sourcesContent":["import {\n AcesToneMapping,\n addTask,\n createEffectRenderTask,\n createEffectWrapper,\n createRenderTarget,\n createRenderTask,\n createSurfaceRenderTargetTexture,\n enableMaterialPlugins,\n isPbrMaterial,\n isPbrSkybox,\n NeutralToneMapping,\n onRenderTargetTextureResize,\n setEffectTexture,\n setEffectUniforms,\n StandardToneMapping,\n} from \"@babylonjs/lite\";\nimport { rebuildMaterialPipelines } from \"../material.js\";\nimport { DEPTH_STENCIL_FORMAT } from \"./render-path.js\";\nimport type { HdrOutputHandle, ScenePresenter } from \"./render-path.js\";\nimport type {\n EffectWrapper,\n EngineContext,\n ImageProcessingConfig,\n MaterialPlugin,\n RenderTarget,\n SceneContext,\n Task,\n} from \"@babylonjs/lite\";\n\n/**\n * The HDR render path (`docs/plan/2026-11-gi-phase-1-execution-plan.md`, step G2): the frame graph\n * a scene gets when the project declares `rendering.hdr`. Its own chunk: `../engine.ts` imports it\n * only when the setting is on, so a project without HDR loads none of it (`CONSTITUTION.md` §2.5).\n *\n * ```text\n * [shadow] → scene ──→ hdr (rgba16float) ──→ output ──→ swapchain\n * └──→ sceneColor ─ (a PostProcessStack's chain)\n * ```\n *\n * - **Linear colour.** Lite's PBR shader ends every fragment with fog, exposure, the curve, a\n * `pow(1/2.2)` encode, a clamp and contrast (`lib/material/pbr/pbr-template.js` line 171), so an\n * `rgba16float` target alone still holds values ≤ 1. {@link createLinearOutputPlugin} saves the\n * colour before that block and restores it before the fragment is written (spike S1).\n * - **The output pass** applies the scene's `imageProcessing` — exposure, contrast and the curve\n * the `Environment` set, or `loadEnvironment` set — then the same encode, clamp and contrast,\n * so a PBR-only scene presents the same bytes as without HDR, within half-float rounding.\n * - **Two output tasks.** A task cannot change its target once recorded, so there is one that\n * writes the swapchain and one that writes `sceneColor`, an ordinary colour target a\n * `PostProcessStack` chain reads. {@link ScenePresenter.setPresentEnabled} switches between them,\n * so the frame runs exactly one.\n *\n * Not yet covered (step G3): fog is dropped with the restore; Standard materials, surface shaders,\n * sprites, particles and the skybox still write encoded colour, which the output pass encodes again.\n */\n\n/**\n * The colour format of the HDR scene target.\n *\n * @internal\n */\nexport const HDR_SCENE_FORMAT: GPUTextureFormat = \"rgba16float\";\n\n/**\n * The name the linear-output plugin carries; part of Lite's pipeline cache key.\n *\n * @internal\n */\nexport const LINEAR_OUTPUT_PLUGIN_NAME = \"ignifx-hdr-linear-output\";\n\n/**\n * The frame-graph task names, in the order they run after `\"scene\"`.\n *\n * @internal\n */\nexport const HDR_OUTPUT_TASK_NAMES = { toChain: \"ignifx:hdr-output-chain\", toSwapchain: \"ignifx:hdr-output\" } as const;\n\n/**\n * The curve numbers the output shader branches on.\n *\n * @internal\n */\nexport const HDR_CURVE = { none: 0, standard: 1, aces: 2, neutral: 3 } as const;\n\n/** The output pass's uniform block: exposure, contrast, curve, padding. */\nconst UNIFORM_FLOATS = 4;\n\n/**\n * Builds the material plugin that keeps a PBR fragment's colour linear.\n *\n * @remarks\n * `CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION` is injected at two slots (`AI`, `NI`;\n * `lib/material/plugin/plugin-bridge-shared.js` line 13), so the save is an assignment, never a\n * `let`; the second one, after indirect light, wins. Priority 0 puts the restore ahead of any other\n * plugin's `CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR` code, which then works on linear colour.\n *\n * @returns The plugin. Plain data, so one object can be shared by every material.\n *\n * @internal\n */\nexport function createLinearOutputPlugin(): MaterialPlugin {\n const fragment = {\n CUSTOM_FRAGMENT_DEFINITIONS: \"var<private> ignifxLinearColor: vec3<f32>;\",\n CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION: \"ignifxLinearColor = color;\",\n CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR: \"color = ignifxLinearColor;\",\n };\n return {\n name: LINEAR_OUTPUT_PLUGIN_NAME,\n priority: 0,\n getCustomCode: (stage) => (stage === \"fragment\" ? fragment : null),\n };\n}\n\n/**\n * Builds the output pass's fragment shader.\n *\n * @remarks\n * The curves are Lite's own WGSL (`ToneMapping.helpersWGSL`/`callWGSL`), which read the exposure\n * from `scene.vImageInfos.x`; naming the uniform block `scene` lets them drop in unchanged. One\n * shader holds all of them and branches on a uniform, so a curve change uploads 16 bytes instead\n * of compiling a pipeline. The encode, clamp and contrast copy the PBR template's tail.\n *\n * @returns The WGSL, with Lite's `effectFragment` entry point.\n *\n * @internal\n */\nexport function hdrOutputFragmentWgsl(): string {\n return [\n AcesToneMapping.helpersWGSL,\n NeutralToneMapping.helpersWGSL,\n \"struct HdrOutputUniforms{vImageInfos:vec4<f32>};\",\n \"@group(0)@binding(0)var<uniform>scene:HdrOutputUniforms;\",\n \"@group(0)@binding(1)var hdrColor:texture_2d<f32>;\",\n \"@fragment fn effectFragment(fragment:EffectVertexOutput)->@location(0)vec4<f32>{\",\n \"let texel=textureLoad(hdrColor,vec2<i32>(fragment.position.xy),0);\",\n \"var color=max(texel.rgb,vec3<f32>(0.0));\",\n \"let curve=i32(scene.vImageInfos.z+0.5);\",\n `if(curve==${String(HDR_CURVE.standard)}){${StandardToneMapping.callWGSL}}`,\n `else if(curve==${String(HDR_CURVE.aces)}){${AcesToneMapping.callWGSL}}`,\n `else if(curve==${String(HDR_CURVE.neutral)}){${NeutralToneMapping.callWGSL}}`,\n \"else{color*=scene.vImageInfos.x;}\",\n \"color=pow(color,vec3<f32>(1.0/2.2));\",\n \"color=clamp(color,vec3<f32>(0.0),vec3<f32>(1.0));\",\n \"let highContrast=color*color*(3.0-2.0*color);\",\n \"if(scene.vImageInfos.y<1.0){color=mix(vec3<f32>(0.5),color,scene.vImageInfos.y);}\",\n \"else{color=mix(color,highContrast,scene.vImageInfos.y-1.0);}\",\n \"color=max(color,vec3<f32>(0.0));\",\n \"return vec4<f32>(color,texel.a);\",\n \"}\",\n ].join(\"\\n\");\n}\n\n/**\n * The curve number for a scene's image processing.\n *\n * @remarks\n * Tone mapping switched on with no curve named is Lite's standard curve (`pbr-renderable.js`). A\n * custom Lite curve the output pass does not know falls back to the standard one.\n *\n * @param processing - The scene's image processing.\n * @returns One of {@link HDR_CURVE}.\n *\n * @internal\n */\nexport function hdrCurveOf(processing: Pick<ImageProcessingConfig, \"toneMappingEnabled\" | \"toneMapping\">): number {\n if (!processing.toneMappingEnabled) {\n return HDR_CURVE.none;\n }\n const id = processing.toneMapping?.id;\n if (id === AcesToneMapping.id) {\n return HDR_CURVE.aces;\n }\n return id === NeutralToneMapping.id ? HDR_CURVE.neutral : HDR_CURVE.standard;\n}\n\n/**\n * Writes the output pass's uniforms and says whether they changed.\n *\n * @param processing - The scene's image processing.\n * @param out - The four floats: exposure, contrast, curve, padding.\n * @returns `true` when `out` now differs from what it held.\n *\n * @internal\n */\nexport function writeHdrOutputUniforms(processing: ImageProcessingConfig, out: Float32Array): boolean {\n const curve = hdrCurveOf(processing);\n if (out[0] === processing.exposure && out[1] === processing.contrast && out[2] === curve) {\n return false;\n }\n out[0] = processing.exposure;\n out[1] = processing.contrast;\n out[2] = curve;\n return true;\n}\n\n/**\n * Builds the HDR render path and appends it to the scene's frame graph.\n *\n * @remarks\n * The same contract as `installOffscreenRenderPath` in `./render-path.ts`: call it right after\n * `createSceneContext(engine, { defaultRenderTask: false })` and before `registerScene`. It also\n * installs Lite's material-plugin bridges, which the linear-output plugin needs before the scene is\n * registered. With MSAA on, the scene draws into a multisampled `rgba16float` target that resolves\n * into the sampled one.\n *\n * @param engine - The engine, which is also the primary surface.\n * @param scene - The scene created with no default render task.\n * @returns The presenter, with its {@link ScenePresenter.hdr} handle set.\n *\n * @internal\n */\nexport function installHdrRenderPath(engine: EngineContext, scene: SceneContext): ScenePresenter {\n enableMaterialPlugins(scene);\n const hdr = createSurfaceRenderTargetTexture(engine, {\n lbl: \"ignifx:scene-hdr\",\n format: HDR_SCENE_FORMAT,\n samples: 1,\n size: engine,\n });\n const isMultisampled = engine.msaaSamples > 1;\n const config: { name: string; rt: RenderTarget; rst?: RenderTarget; depth?: RenderTarget } = {\n name: \"scene\",\n rt: hdr.rt,\n };\n if (isMultisampled) {\n config.rt = createRenderTarget({\n lbl: \"ignifx:scene-hdr-msaa\",\n format: HDR_SCENE_FORMAT,\n dFormat: DEPTH_STENCIL_FORMAT,\n samples: engine.msaaSamples,\n size: engine,\n });\n config.rst = hdr.rt;\n } else {\n config.depth = createRenderTarget({\n lbl: \"ignifx:scene-depth\",\n dFormat: DEPTH_STENCIL_FORMAT,\n samples: 1,\n size: engine,\n });\n }\n addTask(scene, createRenderTask(config, engine, scene));\n\n const effect: EffectWrapper = createEffectWrapper(engine, {\n name: \"ignifx:hdr-output\",\n fragmentWGSL: hdrOutputFragmentWgsl(),\n bindings: [\n { name: \"hdrOutput\", binding: 0, kind: \"uniform\", uniformByteLength: UNIFORM_FLOATS * 4 },\n { name: \"hdrColor\", binding: 1, kind: \"texture\" },\n ],\n });\n setEffectTexture(effect, 1, hdr.texture);\n // A resize swaps the texture behind the facade; the wrapper's cached bind group still holds the\n // old view until a texture write marks it dirty.\n onRenderTargetTextureResize(hdr, () => {\n setEffectTexture(effect, 1, hdr.texture);\n });\n const uniforms = new Float32Array(UNIFORM_FLOATS);\n uniforms[0] = Number.NaN;\n writeHdrOutputUniforms(scene.imageProcessing, uniforms);\n setEffectUniforms(effect, uniforms);\n\n const sceneColor = createRenderTarget({ lbl: \"ignifx:scene-color\", format: engine.format, samples: 1, size: engine });\n const toChain: Task = createEffectRenderTask(\n { name: HDR_OUTPUT_TASK_NAMES.toChain, effect, target: sceneColor, clear: true },\n engine,\n scene,\n );\n const toSwapchain: Task = createEffectRenderTask(\n { name: HDR_OUTPUT_TASK_NAMES.toSwapchain, effect, target: engine.scRT, clear: true },\n engine,\n scene,\n );\n addTask(scene, toChain);\n addTask(scene, toSwapchain);\n toChain.executionEnabled = false;\n\n const plugin = createLinearOutputPlugin();\n const handle: HdrOutputHandle = {\n sceneTexture: hdr.texture,\n update(isSceneRegistered: boolean): void {\n if (writeHdrOutputUniforms(scene.imageProcessing, uniforms)) {\n setEffectUniforms(effect, uniforms);\n }\n attachLinearOutput(scene, plugin, isSceneRegistered);\n },\n };\n let isPresentEnabled = true;\n return {\n sceneColor,\n swapchain: engine.scRT,\n setPresentEnabled(enabled: boolean): void {\n isPresentEnabled = enabled;\n toSwapchain.executionEnabled = enabled;\n toChain.executionEnabled = !enabled;\n },\n get isPresentEnabled(): boolean {\n return isPresentEnabled;\n },\n hdr: handle,\n };\n}\n\n/**\n * Gives every PBR material in the scene the linear-output plugin, once.\n *\n * @remarks\n * A walk rather than a hook at material creation, because PBR materials come from several places\n * (material assets, glTF models, `.lite` code) and a surface shader replaces a material's whole\n * plugin list; a material that lost the plugin gets it back on the next frame. The skybox is left\n * alone: it is not lit and G3 handles it.\n *\n * @param scene - The scene to walk.\n * @param plugin - The shared plugin.\n * @param isSceneRegistered - Whether a patched material's pipelines must be rebuilt.\n */\nfunction attachLinearOutput(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 if (material === undefined || !isPbrMaterial(material) || isPbrSkybox(material)) {\n continue;\n }\n const plugins = material.plugins ?? [];\n if (plugins.includes(plugin)) {\n continue;\n }\n material.plugins = [...plugins, plugin];\n if (isSceneRegistered) {\n rebuildMaterialPipelines(scene, material);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6DA,MAAa,mBAAqC;;;;;;AAOlD,MAAa,4BAA4B;;;;;;AAOzC,MAAa,wBAAwB;CAAE,SAAS;CAA2B,aAAa;AAAoB;;;;;;AAO5G,MAAa,YAAY;CAAE,MAAM;CAAG,UAAU;CAAG,MAAM;CAAG,SAAS;AAAE;;AAGrE,MAAM,iBAAiB;;;;;;;;;;;;;;A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,iBAAiB,QAAQ,GACxD,kBAAkB,QAAQ,QAAQ;GAEpC,mBAAmB,OAAO,QAAQ,iBAAiB;EACrD;CACF;CACA,IAAI,mBAAmB;CACvB,OAAO;EACL;EACA,WAAW,OAAO;EAClB,kBAAkB,SAAwB;GACxC,mBAAmB;GACnB,YAAY,mBAAmB;GAC/B,QAAQ,mBAAmB,CAAC;EAC9B;EACA,IAAI,mBAA4B;GAC9B,OAAO;EACT;EACA,KAAK;CACP;AACF;;;;;;;;;;;;;;AAeA,SAAS,mBAAmB,OAAqB,QAAwB,mBAAkC;CACzG,MAAM,SAAS,MAAM;CACrB,KAAK,IAAI,QAAQ,GAAG,QAAQ,OAAO,QAAQ,SAAS,GAAG;EACrD,MAAM,WAAW,OAAO,MAAM,EAAE;EAChC,IAAI,aAAa,KAAA,KAAa,CAAC,cAAc,QAAQ,KAAK,YAAY,QAAQ,GAC5E;EAEF,MAAM,UAAU,SAAS,WAAW,CAAC;EACrC,IAAI,QAAQ,SAAS,MAAM,GACzB;EAEF,SAAS,UAAU,CAAC,GAAG,SAAS,MAAM;EACtC,IAAI,mBACF,yBAAyB,OAAO,QAAQ;CAE5C;AACF"}
@@ -168,6 +168,8 @@ const CoreErrorCode = {
168
168
  physicsCallbackOutsideFixedStep: "IGX-0409",
169
169
  /** A second, different simulation scene was handed to a world that already has one. */
170
170
  simulationSceneAlreadySet: "IGX-0410",
171
+ /** One `Extension` object was handed to a second app while the first still runs it. */
172
+ extensionInstalledTwice: "IGX-0411",
171
173
  /** An asset's value was read before the asset finished loading. */
172
174
  assetNotLoaded: "IGX-0501",
173
175
  /** An asset load was aborted through its `AbortSignal`. */
@@ -260,6 +262,14 @@ const CoreErrorCode = {
260
262
  instancingLodWithoutCulling: "IGX-0727",
261
263
  /** `app.renderer.openOverlay()` was called on a headless app, or before `app.start()` registered the render scene. */
262
264
  overlayNeedsRenderScene: "IGX-0728",
265
+ /** A render texture was rendered into or read on a headless app, or before `app.start()` started the render loop. */
266
+ renderTextureNeedsRenderLoop: "IGX-0729",
267
+ /** `app.renderer.createRenderTexture` was given a side that is not a whole number from 1 to 4096. */
268
+ invalidRenderTextureSize: "IGX-0730",
269
+ /** A render texture was used after `dispose()`, or with another app's renderer. */
270
+ renderTextureUnusable: "IGX-0731",
271
+ /** `app.renderer.renderToTexture` was given a camera that is not attached to an entity. */
272
+ renderTextureCameraDetached: "IGX-0732",
263
273
  /** The host exposes no Web Crypto implementation. */
264
274
  cryptoUnavailable: "IGX-1420",
265
275
  /** A storage namespace name is not a legal namespace segment. */
@@ -334,6 +344,7 @@ const CORE_ERROR_MESSAGES = {
334
344
  "IGX-0408": "The {section} settings section is invalid: {issues}.",
335
345
  "IGX-0409": "Physics callbacks are dispatched inside the fixed loop only; {callback} was not.",
336
346
  "IGX-0410": "A world has one simulation scene, and this world already has a different one.",
347
+ "IGX-0411": "The {extension} extension object is already installed in another app that has not been disposed.",
337
348
  "IGX-0501": "The asset {asset} has no value yet because it is still loading.",
338
349
  "IGX-0502": "Loading {asset} was aborted.",
339
350
  "IGX-0503": "The app that owned the asset {asset} was disposed before loading finished.",
@@ -378,6 +389,10 @@ const CORE_ERROR_MESSAGES = {
378
389
  "IGX-0726": "{samplers} plugin samplers are declared; {budget} fit beside a textured PBR material.",
379
390
  "IGX-0727": "{entity} declares an InstancedMeshRenderer lod with gpuCulling off; the LOD mesh never draws. Turn gpuCulling on.",
380
391
  "IGX-0728": "openOverlay() needs a canvas-backed app whose render scene is registered.",
392
+ "IGX-0729": "{member} needs a canvas-backed app whose render loop is running.",
393
+ "IGX-0730": "A render texture of {width}x{height}: each side must be a whole number from 1 to {max}.",
394
+ "IGX-0731": "{member}: the render texture is disposed or belongs to another app.",
395
+ "IGX-0732": "renderToTexture() needs a camera attached to an entity.",
381
396
  "IGX-1420": "This host does not expose Web Crypto.",
382
397
  "IGX-1421": "{namespace} is not a valid storage namespace.",
383
398
  "IGX-1422": "That storage key is empty, too long, or contains a control character.",
@@ -562,4 +577,4 @@ function assertNever(value, what) {
562
577
  //#endregion
563
578
  export { CORE_ERROR_MESSAGES as a, THIRD_PARTY_ERROR_PREFIX as c, isIgnifxError as i, isValidErrorCode as l, assertNever as n, CoreErrorCode as o, formatErrorMessage as r, ErrorRange as s, IgnifxError as t };
564
579
 
565
- //# sourceMappingURL=ignifx-error-Dq2qJMkZ.js.map
580
+ //# sourceMappingURL=ignifx-error-oYdVnT1S.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ignifx-error-oYdVnT1S.js","names":[],"sources":["../src/errors/error-codes.ts","../src/errors/ignifx-error.ts"],"sourcesContent":["/**\n * The error code registry data: the subsystem ranges from\n * `docs/architecture/15-devtools-and-diagnostics.md` §1, the codes `@ignifx/core` itself owns, and\n * the format rule every code must satisfy.\n *\n * This module is pure data plus one predicate; it imports nothing, which is what lets\n * {@link IgnifxError} depend on it without a cycle (coding standards §4).\n */\n\n/**\n * The two-digit prefix each subsystem owns inside the `IGX-####` space\n * (`docs/architecture/15-devtools-and-diagnostics.md` §1). A code is the prefix followed by a\n * two-digit ordinal, so `rendering` owns `IGX-0700` through `IGX-0799`.\n *\n * @example\n * ```ts\n * const code = `IGX-${ErrorRange.rendering}01` satisfies ErrorCode; // \"IGX-0701\"\n * ```\n *\n * @public\n */\nexport const ErrorRange = {\n /** App lifecycle, phases, time, coroutines, destruction. */\n lifecycle: \"01\",\n /** Components, scripts, and their registration. */\n components: \"02\",\n /** Scenes, scene instances, layers. */\n scenes: \"03\",\n /** The extension host and its contract. */\n extensions: \"04\",\n /** Asset handles, loaders, and caching. */\n assets: \"05\",\n /** Schemas, scene/prefab JSON, references. */\n serialization: \"06\",\n /** The renderer and the Babylon Lite adapter. */\n rendering: \"07\",\n /** Input devices, actions, and bindings. */\n input: \"08\",\n /** 3D physics. */\n physics: \"09\",\n /** Audio buses, sources, and clips. */\n audio: \"10\",\n /** The 2D toolkit. */\n twoD: \"11\",\n /** The 3D toolkit. */\n threeD: \"12\",\n /** The UI overlay. */\n ui: \"13\",\n /** Platform integration (browser, Electron). */\n platform: \"14\",\n /** Devtools, logging, and diagnostics. */\n devtools: \"15\",\n /** Terrain assets, chunks, and queries. */\n terrain: \"16\",\n /** Particle systems, 3D and 2D. */\n particles: \"17\",\n /** The editor host package and its Vite plugin. */\n editorHost: \"18\",\n} as const;\n\n/**\n * The union of the two-digit subsystem prefixes declared by `ErrorRange`.\n *\n * @public\n */\nexport type ErrorRange = (typeof ErrorRange)[keyof typeof ErrorRange];\n\n/**\n * The first digit of the range reserved for extensions published outside the `@ignifx` scope\n * (`IGX-9000` through `IGX-9999`). First-party subsystems never allocate here.\n *\n * @public\n */\nexport const THIRD_PARTY_ERROR_PREFIX = \"9\";\n\n/**\n * The shape of every ignifx diagnostic code: the literal `IGX-` followed by four digits.\n *\n * @remarks\n * The template literal is the widest useful type; it accepts strings such as `\"IGX-1\"` that are not\n * real codes. {@link isValidErrorCode} is the runtime check, `CoreErrorCode` is the narrowed\n * string-literal union for the codes this package owns, and extensions narrow their own the same\n * way.\n *\n * @public\n */\nexport type ErrorCode = `IGX-${number}`;\n\n/**\n * Every diagnostic code `@ignifx/core` can throw, keyed by an intention-revealing name so call\n * sites read as prose and the compiler catches typos (coding standards §5.2 — `as const` objects in\n * place of enums).\n *\n * @example\n * ```ts\n * throw new IgnifxError(CoreErrorCode.mutationAfterDestroy, \"The entity has been destroyed.\", {\n * context: { entity: entity.uid },\n * });\n * ```\n *\n * @remarks\n * Code blocks reserved for other first-party packages, which cannot import this table\n * (`docs/architecture/00-overview.md` §2): `@ignifx/cli` owns `IGX-1401`–`IGX-1419`; `@ignifx/electron`\n * owns `IGX-1460`–`IGX-1499` (core's own platform codes therefore stop at `IGX-1459`); `@ignifx/devtools`\n * owns `IGX-1550`–`IGX-1599` (core's own devtools-range codes stop at `IGX-1549`);\n * `@ignifx/vite-plugin` owns `IGX-0550`–`IGX-0599` and `IGX-0650`–`IGX-0699`. Core allocates its\n * own codes from the bottom of each range and, in the platform range, from `IGX-1420` upward —\n * which is where `app.platform` and `app.storage` live, because storage is a *platform* service:\n * the same three calls resolve to IndexedDB, a directory, or the Electron bridge depending only on\n * the host, so a failure is a platform failure and not a serialization or asset one.\n *\n * @public\n */\nexport const CoreErrorCode = {\n /** An entity, component, or app was used after it had been destroyed or disposed. */\n mutationAfterDestroy: \"IGX-0101\",\n /** `destroyImmediate()` was called from inside a lifecycle callback. */\n destroyImmediateInCallback: \"IGX-0102\",\n /** A signal handler asked for deferred delivery on a signal that has no scheduler. */\n deferredSignalWithoutScheduler: \"IGX-0103\",\n /** A signal handler threw and no handler-error reporter was installed. */\n signalHandlerThrew: \"IGX-0104\",\n /** `app.step()` was called while Babylon Lite's render loop was driving the frames. */\n stepOutsideHeadless: \"IGX-0105\",\n /** An app was used after `app.dispose()` had run. */\n appDisposed: \"IGX-0106\",\n /** A part of the app was reached before `createApp()` had finished building it. */\n appNotReady: \"IGX-0107\",\n /** A `Time` property was set to a value outside its documented domain. */\n invalidTimeValue: \"IGX-0108\",\n /** A `app.tweens.to(...)` option was outside its documented domain. */\n invalidTweenOptions: \"IGX-0109\",\n /** A tweened field is not a number, `Vec2`, `Vec3`, or `Quat`, or is not writable. */\n tweenFieldNotTweenable: \"IGX-0110\",\n /** A coroutine was started in an edit-mode app by a script whose class does not run in edit mode. */\n coroutineInEditMode: \"IGX-0111\",\n /** A component declared through `requires` is missing from the entity. */\n requiredComponentMissing: \"IGX-0201\",\n /** A second instance of a component type that does not allow multiples was added. */\n multipleComponentsNotAllowed: \"IGX-0202\",\n /** Two component types were registered under the same `typeId`. */\n duplicateComponentTypeId: \"IGX-0203\",\n /** A component without a `typeId` was serialized. */\n componentTypeIdMissing: \"IGX-0204\",\n /** `Transform` was removed or disabled; every entity must keep exactly one enabled transform. */\n transformIsNotRemovable: \"IGX-0205\",\n /** A component's engine-assigned state was read before the engine attached it to an entity. */\n componentNotAttached: \"IGX-0206\",\n /** A hot-reloaded class kept the `\"patch\"` policy while its schema shape changed. */\n hotReloadSchemaChanged: \"IGX-0207\",\n /** `app.hotReload.apply()` was called from inside a lifecycle callback. */\n hotReloadInsideCallback: \"IGX-0208\",\n /** A component class's `static requires` chain loops, through the class itself or a class it requires. */\n requiresCycle: \"IGX-0209\",\n /** A scene was instantiated before it had finished loading. */\n sceneNotLoaded: \"IGX-0301\",\n /** Instantiating a scene would place an instance inside itself. */\n sceneInstanceCycle: \"IGX-0302\",\n /** A layer name that the project settings do not declare was used. */\n unknownLayer: \"IGX-0303\",\n /** Two layer slots were given the same name. */\n duplicateLayerName: \"IGX-0304\",\n /** The project settings declare more layer names than the 32 available slots. */\n tooManyLayers: \"IGX-0305\",\n /** Reparenting an entity under its own descendant would make the scene tree cyclic. */\n parentingCycle: \"IGX-0306\",\n /** A scene file names a component `typeId` that no extension has registered. */\n unknownComponentTypeId: \"IGX-0307\",\n /** A file handed to the scene loader does not carry the `ignifx.scene` format header. */\n notASceneFile: \"IGX-0308\",\n /** An operation that only accepts a scene root was given an entity that has a parent. */\n entityIsNotSceneRoot: \"IGX-0309\",\n /** Two extensions defined the same app property. */\n appPropertyAlreadyDefined: \"IGX-0401\",\n /** The `requires` graph of the registered extensions contains a cycle. */\n extensionRequiresCycle: \"IGX-0402\",\n /** An extension declares a `requires` entry that was never registered. */\n extensionMissing: \"IGX-0403\",\n /** An extension's `engine` range does not match the running core version. */\n extensionEngineMismatch: \"IGX-0404\",\n /** `ctx.require()` asked for a service that no earlier extension registered. */\n serviceNotRegistered: \"IGX-0405\",\n /** Two extensions were registered under the same name. */\n duplicateExtensionName: \"IGX-0406\",\n /** `ctx.settings()` asked for a settings section that was never registered. */\n unknownSettingsSection: \"IGX-0407\",\n /** A project settings section did not validate against the schema its extension registered. */\n invalidSettings: \"IGX-0408\",\n /** An extension dispatched a physics callback from outside the fixed loop. */\n physicsCallbackOutsideFixedStep: \"IGX-0409\",\n /** A second, different simulation scene was handed to a world that already has one. */\n simulationSceneAlreadySet: \"IGX-0410\",\n /** One `Extension` object was handed to a second app while the first still runs it. */\n extensionInstalledTwice: \"IGX-0411\",\n /** An asset's value was read before the asset finished loading. */\n assetNotLoaded: \"IGX-0501\",\n /** An asset load was aborted through its `AbortSignal`. */\n assetLoadAborted: \"IGX-0502\",\n /** An asset promise outlived the app that owned it. */\n assetAppDisposed: \"IGX-0503\",\n /** No registered loader claims the address's type or extension. */\n assetNoLoader: \"IGX-0504\",\n /** An asset load failed after its last retry. */\n assetLoadFailed: \"IGX-0505\",\n /** Two loaders were registered for the same asset type. */\n duplicateAssetLoader: \"IGX-0506\",\n /** A `.mesh.json` file names an unknown primitive, or an option the primitive does not take or cannot use. */\n invalidMeshFile: \"IGX-0507\",\n /** A serialized number was `NaN` or infinite. */\n nonFiniteNumber: \"IGX-0601\",\n /** A serialized `$entity`/`$component` reference could not be resolved. */\n unresolvedReference: \"IGX-0602\",\n /** A scene, prefab, or manifest declares a format version this build cannot read. */\n unsupportedFormatVersion: \"IGX-0603\",\n /** A scene instance's override hash does not match the scene file it was recorded against. */\n instanceHashMismatch: \"IGX-0604\",\n /** A value had the wrong JavaScript or JSON type for its schema field kind. */\n schemaTypeMismatch: \"IGX-0605\",\n /** A value had the right type but fell outside its schema field's declared value domain. */\n schemaOutOfRange: \"IGX-0606\",\n /**\n * A property bag named a field the schema does not declare, or a schema declaration named a field\n * it may not use: not identifier-like, a `Component`/`Script` member, or an `Object.prototype`\n * member such as `constructor` or `__proto__`.\n */\n schemaUnknownField: \"IGX-0607\",\n /** A scene file failed structural validation against the generated scene-file JSON Schema. */\n sceneFileInvalid: \"IGX-0608\",\n /** An instance override declares a `path` the override grammar does not accept. */\n invalidOverridePath: \"IGX-0609\",\n /** WebGPU is not available in the current environment. */\n webGpuUnavailable: \"IGX-0701\",\n /** A runtime handle was used after disposal, or was not created by ignifx. */\n invalidRuntime: \"IGX-0702\",\n /** Shadows were requested from a light kind Babylon Lite cannot shadow. */\n shadowsUnsupportedForLight: \"IGX-0703\",\n /** A rendering feature opt-in was requested after the render scene had been registered. */\n renderingFeatureTooLate: \"IGX-0704\",\n /** A second `Environment` was enabled in one world; the most recent one wins. */\n multipleEnvironments: \"IGX-0705\",\n /** A world rendered with no enabled camera, so nothing was drawn. */\n noEnabledCamera: \"IGX-0706\",\n /** A screenshot was requested with no render loop running, so no frame will ever be presented. */\n screenshotNeedsRenderLoop: \"IGX-0707\",\n /** A material file declares a family this build cannot construct. */\n unsupportedMaterialKind: \"IGX-0708\",\n /** An asset file does not carry the format header its loader requires. */\n invalidAssetFile: \"IGX-0709\",\n /** A `PostProcessStack` was attached without the `postProcessing` rendering feature. */\n postProcessingFeatureOff: \"IGX-0710\",\n /** An `Environment.skybox` asks for a background the environment it installed cannot draw. */\n skyboxFixedAtLoad: \"IGX-0711\",\n /** A shader material was asked for a uniform, texture, or storage buffer its shader never declared. */\n unknownShaderBinding: \"IGX-0712\",\n /** A shader uniform was written with a value whose shape does not match its declared type. */\n shaderValueMismatch: \"IGX-0713\",\n /** A shader declares a main-light uniform, but the world has no enabled directional light. */\n shaderLightUniformWithoutLight: \"IGX-0714\",\n /** A shader failed to compile or rebuild; the previous material stays in use. */\n shaderCompileFailed: \"IGX-0715\",\n /** A surface shader was attached without the `materialPlugins` rendering feature. */\n surfaceShaderFeatureOff: \"IGX-0716\",\n /** An `InstancedMeshRenderer` setting Lite fixes at scene registration was changed afterwards. */\n instancingSettingTooLate: \"IGX-0717\",\n /** A shader-material method was called on a PBR or Standard material. */\n notAShaderMaterial: \"IGX-0718\",\n /** A `.wgsl` file carries an `@ignifx` pragma this build cannot read. */\n invalidShaderPragma: \"IGX-0719\",\n /** A storage buffer update reaches past the buffer's capacity. */\n storageBufferOutOfRange: \"IGX-0720\",\n /** More instances were written to an `InstancedMeshRenderer` than its capacity holds. */\n instancedCapacityExceeded: \"IGX-0721\",\n /** Pixel data handed to a texture does not match its declared size. */\n invalidPixelData: \"IGX-0722\",\n /** A surface shader cannot run on its host: no hook, a hook the host lacks, or a Standard host. */\n surfaceHookMissing: \"IGX-0723\",\n /** A shader-material mesh was left out of an ESM shadow caster list, which Lite cannot render for it. */\n shaderMaterialEsmCasterSkipped: \"IGX-0724\",\n /** A `MeshAsset` vertex update named a range the geometry cannot hold. */\n invalidGeometryUpdate: \"IGX-0725\",\n /** The surface shaders attached to one material declare more samplers than fit beside the host material. */\n surfaceSamplerBudgetExceeded: \"IGX-0726\",\n /** An `InstancedMeshRenderer` declares a LOD partner with `gpuCulling` off, so the partner never draws. */\n instancingLodWithoutCulling: \"IGX-0727\",\n /** `app.renderer.openOverlay()` was called on a headless app, or before `app.start()` registered the render scene. */\n overlayNeedsRenderScene: \"IGX-0728\",\n /** A render texture was rendered into or read on a headless app, or before `app.start()` started the render loop. */\n renderTextureNeedsRenderLoop: \"IGX-0729\",\n /** `app.renderer.createRenderTexture` was given a side that is not a whole number from 1 to 4096. */\n invalidRenderTextureSize: \"IGX-0730\",\n /** A render texture was used after `dispose()`, or with another app's renderer. */\n renderTextureUnusable: \"IGX-0731\",\n /** `app.renderer.renderToTexture` was given a camera that is not attached to an entity. */\n renderTextureCameraDetached: \"IGX-0732\",\n /** The host exposes no Web Crypto implementation. */\n cryptoUnavailable: \"IGX-1420\",\n /** A storage namespace name is not a legal namespace segment. */\n storageInvalidNamespace: \"IGX-1421\",\n /** A storage key is empty, too long, or contains a control character. */\n storageInvalidKey: \"IGX-1422\",\n /** A value handed to `app.storage.set` has no JSON form. */\n storageValueNotSerializable: \"IGX-1423\",\n /** The storage backend refused a write because the host is out of quota or disk space. */\n storageQuotaExceeded: \"IGX-1424\",\n /** The storage backend failed for a reason the engine cannot classify. */\n storageBackendFailed: \"IGX-1425\",\n /** A stored value could not be read back; the store was damaged or written by something else. */\n storageValueCorrupt: \"IGX-1426\",\n /** An error code was registered twice. */\n duplicateErrorCode: \"IGX-1501\",\n /** An error code does not match `IGX-####` in a known range. */\n malformedErrorCode: \"IGX-1502\",\n /** A diagnostics counter group was registered twice. */\n duplicateDiagnosticsGroup: \"IGX-1503\",\n /** A diagnostics counter name was not declared when its group was registered. */\n unknownDiagnosticsCounter: \"IGX-1504\",\n /** A `switch` over a union reached a case the type system said was impossible. */\n unreachableCase: \"IGX-1505\",\n /** `app.hotReload.reloadScene()` was given an instance that was not built from a scene asset. */\n sceneNotReloadable: \"IGX-1506\",\n} as const;\n\n/**\n * The union of the codes `@ignifx/core` owns. Use it to narrow `catch` blocks to core failures.\n *\n * @public\n */\nexport type CoreErrorCode = (typeof CoreErrorCode)[keyof typeof CoreErrorCode];\n\n/**\n * The one-line message template for every `CoreErrorCode`. Templates name context keys in\n * braces (`{entity}`); the throwing call site substitutes the values it has and puts the same\n * identifiers in {@link IgnifxError.context} so production builds stay useful without the prose.\n *\n * @public\n */\nexport const CORE_ERROR_MESSAGES: Readonly<Record<CoreErrorCode, string>> = {\n \"IGX-0101\": \"{target} has been destroyed and can no longer be used.\",\n \"IGX-0102\": \"destroyImmediate() cannot run inside the {phase} callback; use destroy() instead.\",\n \"IGX-0103\": \"Deferred signal delivery needs a scheduler; construct the signal with a deferred queue.\",\n \"IGX-0104\": \"A signal handler threw.\",\n \"IGX-0105\": \"step() is only available in headless mode or while the render loop is stopped.\",\n \"IGX-0106\": \"The app has been disposed; {member} is no longer available.\",\n \"IGX-0107\": \"{member} is not available until createApp() resolves.\",\n \"IGX-0108\": \"{property} must be {domain}; got {value}.\",\n \"IGX-0109\": \"The tween option {option} must be {domain}; got {value}.\",\n \"IGX-0110\": \"{field} is not a number, Vec2, Vec3, or Quat on the tween target.\",\n \"IGX-0111\": \"{script} cannot start a coroutine in edit mode because its class does not run in edit mode.\",\n \"IGX-0201\": \"{component} requires {required} on the same entity.\",\n \"IGX-0202\": \"{component} does not allow multiple instances on one entity.\",\n \"IGX-0203\": \"The component type id {typeId} is already registered by {owner}.\",\n \"IGX-0204\": \"{component} cannot be serialized because it has no typeId.\",\n \"IGX-0205\": \"Transform cannot be removed or disabled.\",\n \"IGX-0206\": \"{component} is not attached to an entity yet.\",\n \"IGX-0207\":\n '{component} changed its schema shape under the \"patch\" hot-reload policy; its instances were re-created.',\n \"IGX-0208\": \"app.hotReload.apply() cannot run inside the {phase} callback; apply it between frames.\",\n \"IGX-0209\": \"{component} has a static requires cycle: {cycle}.\",\n \"IGX-0301\": \"The scene {scene} is not loaded yet.\",\n \"IGX-0302\": \"Instantiating {scene} under {entity} would nest the scene inside itself.\",\n \"IGX-0303\": \"{layer} is not a layer declared in the project settings.\",\n \"IGX-0304\": \"The layer name {layer} is declared twice.\",\n \"IGX-0305\": \"The project settings declare {count} layers; at most {limit} fit in the 32 slots.\",\n \"IGX-0306\": \"{entity} cannot be parented to {parent}, which is inside its own subtree.\",\n \"IGX-0307\": \"{typeId} is not a registered component type.\",\n \"IGX-0308\": \"{file} is not an ignifx scene file.\",\n \"IGX-0309\": \"{entity} is not a scene root; only roots can move between scene instances.\",\n \"IGX-0401\": \"The app property {property} is already defined by {owner}.\",\n \"IGX-0402\": \"The extension requires graph contains a cycle: {cycle}.\",\n \"IGX-0403\": \"{extension} requires {required}, which is not registered.\",\n \"IGX-0404\": \"{extension} supports engine {range} but the running core is {version}.\",\n \"IGX-0405\": \"The service {service} required by {extension} is not registered.\",\n \"IGX-0406\": \"The extension name {extension} is registered twice.\",\n \"IGX-0407\": \"{section} is not a registered settings section.\",\n \"IGX-0408\": \"The {section} settings section is invalid: {issues}.\",\n \"IGX-0409\": \"Physics callbacks are dispatched inside the fixed loop only; {callback} was not.\",\n \"IGX-0410\": \"A world has one simulation scene, and this world already has a different one.\",\n \"IGX-0411\": \"The {extension} extension object is already installed in another app that has not been disposed.\",\n \"IGX-0501\": \"The asset {asset} has no value yet because it is still loading.\",\n \"IGX-0502\": \"Loading {asset} was aborted.\",\n \"IGX-0503\": \"The app that owned the asset {asset} was disposed before loading finished.\",\n \"IGX-0504\": \"No loader is registered for {asset}.\",\n \"IGX-0505\": \"Loading {asset} from {url} failed after {attempts} attempts.\",\n \"IGX-0506\": \"A loader for the asset type {type} is already registered.\",\n \"IGX-0507\": \"{file} is not a valid mesh file: {problem}\",\n \"IGX-0601\": \"{field} must be a finite number.\",\n \"IGX-0602\": \"The reference {reference} in {scene} could not be resolved.\",\n \"IGX-0603\": \"{file} declares format version {version}, which this build cannot read.\",\n \"IGX-0604\": \"The overrides recorded for {scene} do not match the scene file.\",\n \"IGX-0605\": \"{field} has the wrong type for a {kind} field.\",\n \"IGX-0606\": \"{field} is outside the declared value domain.\",\n \"IGX-0607\": \"{field} is not a field this schema declares, or not a name a schema field may use.\",\n \"IGX-0608\": \"{file} does not match the scene file schema.\",\n \"IGX-0609\": \"{path} is not a valid instance override path.\",\n \"IGX-0701\": \"WebGPU is not available in this environment.\",\n \"IGX-0702\": \"This handle was already disposed, or was not created by ignifx.\",\n \"IGX-0703\": \"Babylon Lite has no shadow generator for a {lightType} light.\",\n \"IGX-0704\": \"The rendering feature {feature} must be enabled before the scene is registered.\",\n \"IGX-0705\": \"{entity} enabled a second Environment in this world; the most recent one wins.\",\n \"IGX-0706\": \"This world has no enabled camera, so nothing is drawn.\",\n \"IGX-0707\": \"captureScreenshot() needs a running render loop; a headless app never presents a frame.\",\n \"IGX-0708\": \"{asset} declares the material kind {kind}, which this build cannot construct.\",\n \"IGX-0709\": \"{file} is not an {format} file.\",\n \"IGX-0710\": \"{entity} attached a PostProcessStack, but rendering.features.postProcessing is off.\",\n \"IGX-0711\":\n \"{entity} asks for an Environment.skybox that {asset} was not loaded with; declare it in the .environment.json.\",\n \"IGX-0712\": \"{name} is not a uniform, texture, storage buffer, or plugin binding that is declared.\",\n \"IGX-0713\": \"{name} on {material} expects {expected}, not {actual}.\",\n \"IGX-0714\": \"{material} declares {name}, but this world has no enabled directional light; zeros are uploaded.\",\n \"IGX-0715\": \"{asset} failed to compile; the previous material stays in use. {message}\",\n \"IGX-0716\": \"{material} carries a surface shader, but rendering.features.materialPlugins is off.\",\n \"IGX-0717\": \"{entity} changed {field} on an InstancedMeshRenderer after the scene was registered.\",\n \"IGX-0718\": \"{material} is a {kind} material; {method} needs a shader material.\",\n \"IGX-0719\": \"{asset} line {line}: {message}\",\n \"IGX-0720\": \"{buffer}: an update of {bytes} bytes at offset {offset} exceeds the {capacity}-byte buffer.\",\n \"IGX-0721\": \"{entity}: {count} instances exceed the capacity of {capacity}.\",\n \"IGX-0722\": \"{asset}: {bytes} bytes of pixel data do not match {width}x{height} RGBA.\",\n \"IGX-0723\":\n \"A surface shader or post effect declares no hook this host can run: displace, surface, composite, or mainFragment.\",\n \"IGX-0724\":\n \"{entity} uses a shader material under ESM shadows; Babylon Lite 1.27.0 cannot render it into an ESM map, so it casts no shadow. Use pcf shadows or castShadows: false.\",\n \"IGX-0725\": \"{asset}: an update of {count} vertices at offset {offset} does not fit the {total}-vertex mesh.\",\n \"IGX-0726\": \"{samplers} plugin samplers are declared; {budget} fit beside a textured PBR material.\",\n \"IGX-0727\":\n \"{entity} declares an InstancedMeshRenderer lod with gpuCulling off; the LOD mesh never draws. Turn gpuCulling on.\",\n \"IGX-0728\": \"openOverlay() needs a canvas-backed app whose render scene is registered.\",\n \"IGX-0729\": \"{member} needs a canvas-backed app whose render loop is running.\",\n \"IGX-0730\": \"A render texture of {width}x{height}: each side must be a whole number from 1 to {max}.\",\n \"IGX-0731\": \"{member}: the render texture is disposed or belongs to another app.\",\n \"IGX-0732\": \"renderToTexture() needs a camera attached to an entity.\",\n \"IGX-1420\": \"This host does not expose Web Crypto.\",\n \"IGX-1421\": \"{namespace} is not a valid storage namespace.\",\n \"IGX-1422\": \"That storage key is empty, too long, or contains a control character.\",\n \"IGX-1423\": \"The value stored at {key} has no JSON form.\",\n \"IGX-1424\": \"The {backend} storage backend has no quota left for {operation}.\",\n \"IGX-1425\": \"The {backend} storage backend could not {operation}.\",\n \"IGX-1426\": \"The value stored at {key} could not be read back.\",\n \"IGX-1501\": \"The error code {code} is already registered by {owner}.\",\n \"IGX-1502\": \"{code} is not a valid IGX-#### code in a known range.\",\n \"IGX-1503\": \"The diagnostics group {group} is already registered.\",\n \"IGX-1504\": \"{counter} is not a counter of the diagnostics group {group}.\",\n \"IGX-1505\": \"Unreachable case reached for {what}.\",\n \"IGX-1506\": \"The scene instance {scene} was not built from a scene asset, so it cannot be reloaded.\",\n};\n\n/** The fixed length of an `IGX-####` code. */\nconst ERROR_CODE_LENGTH = 8;\n\n/** Where the four digits start inside an `IGX-####` code. */\nconst ERROR_CODE_DIGITS_OFFSET = 4;\n\n/** The characters allowed in the numeric part of a code. */\nconst DIGITS = \"0123456789\";\n\n/**\n * Reports whether a string is a well-formed ignifx error code.\n *\n * @remarks\n * The rule has exactly two parts and the `ignifx/error-code-format` lint rule mirrors it:\n *\n * 1. the string is `IGX-` followed by four ASCII digits, and\n * 2. the first two digits are one of the fifteen `ErrorRange` prefixes, or the first digit is\n * {@link THIRD_PARTY_ERROR_PREFIX} (the third-party block `IGX-9000`–`IGX-9999`).\n *\n * @param code - The candidate code.\n * @returns `true` when the code is well formed and inside an allocated range. The signature is a\n * type predicate, so a validated string narrows to {@link ErrorCode} without a type assertion.\n *\n * @example\n * ```ts\n * isValidErrorCode(\"IGX-0701\"); // true — rendering\n * isValidErrorCode(\"IGX-9042\"); // true — third party\n * isValidErrorCode(\"IGX-1801\"); // false — no subsystem owns 18\n * ```\n *\n * @public\n */\nexport function isValidErrorCode(code: string): code is ErrorCode {\n // The literal below is the prefix the `ignifx/error-code-format` rule looks for. This function is\n // the validator that rule mirrors, not a throw site, so the rule is switched off for one line.\n // eslint-disable-next-line ignifx/error-code-format -- see the comment above\n if (code.length !== ERROR_CODE_LENGTH || !code.startsWith(\"IGX-\")) {\n return false;\n }\n const digits = code.slice(ERROR_CODE_DIGITS_OFFSET);\n for (const digit of digits) {\n if (!DIGITS.includes(digit)) {\n return false;\n }\n }\n const prefix = digits.slice(0, 2);\n if (prefix.startsWith(THIRD_PARTY_ERROR_PREFIX)) {\n return true;\n }\n for (const range of Object.values(ErrorRange)) {\n if (range === prefix) {\n return true;\n }\n }\n return false;\n}\n","import { CoreErrorCode, type ErrorCode } from \"./error-codes.js\";\n\n/**\n * The identifiers that make a failure actionable: entity and component uids, asset keys, layer\n * names, extension names. Values are primitives so the whole record survives being sent to a\n * devtools panel or a log sink without cloning engine objects.\n *\n * @public\n */\nexport type ErrorContext = Readonly<Record<string, string | number | boolean | null>>;\n\n/**\n * How much of an error is spelled out in `Error.message`.\n *\n * @remarks\n * `\"development\"` writes the full sentence, the context values, and the hint. `\"production\"` keeps\n * the code and the *names* of the context keys and drops every value and the prose, so shipped\n * games neither leak content paths nor pay for message strings (`CONSTITUTION.md` §3.9). The\n * structured `code`, `context`, and `hint` properties are populated in both modes.\n *\n * @public\n */\nexport type ErrorFormatMode = \"development\" | \"production\";\n\n/**\n * Options accepted by {@link IgnifxError}. Extends the standard `ErrorOptions`, so `cause` keeps\n * the original failure when an error is wrapped.\n *\n * @public\n */\nexport interface IgnifxErrorOptions extends ErrorOptions {\n /** Identifiers that locate the failure. Defaults to an empty record. */\n readonly context?: ErrorContext;\n /** One sentence telling the developer what to do about it. Defaults to `null`. */\n readonly hint?: string | null;\n /** How verbose `message` should be. Defaults to `\"development\"`. */\n readonly mode?: ErrorFormatMode;\n}\n\n/** Shared empty context so the common case allocates nothing. */\nconst EMPTY_CONTEXT: ErrorContext = {};\n\n/**\n * Builds the `Error.message` of an {@link IgnifxError}.\n *\n * @remarks\n * Development messages read `IGX-0201: Mover requires Rigidbody. [entity=01J…] Hint: add it.`\n * Production messages read `IGX-0201 [entity]` — enough to look the code up in the registry and to\n * know which identifiers the `context` property carries, with no prose in the bundle.\n *\n * @param code - The stable diagnostic code.\n * @param message - The actionable development sentence.\n * @param context - Identifiers that locate the failure.\n * @param hint - A remedy sentence, or `null`.\n * @param mode - Whether to format for development or production.\n * @returns The formatted message.\n *\n * @example\n * ```ts\n * formatErrorMessage(\"IGX-0303\", \"Enemy is not a declared layer.\", { layer: \"Enemy\" }, null, \"production\");\n * // \"IGX-0303 [layer]\"\n * ```\n *\n * @public\n */\nexport function formatErrorMessage(\n code: ErrorCode,\n message: string,\n context: ErrorContext,\n hint: string | null,\n mode: ErrorFormatMode,\n): string {\n const keys = Object.keys(context);\n if (mode === \"production\") {\n return keys.length === 0 ? code : `${code} [${keys.join(\", \")}]`;\n }\n let formatted = `${code}: ${message}`;\n if (keys.length > 0) {\n const parts: string[] = [];\n for (const key of keys) {\n parts.push(`${key}=${String(context[key] ?? null)}`);\n }\n formatted += ` [${parts.join(\", \")}]`;\n }\n if (hint !== null && hint.length > 0) {\n formatted += ` Hint: ${hint}`;\n }\n return formatted;\n}\n\n/**\n * The error every ignifx API throws for misuse (`CONSTITUTION.md` §3.9). It always carries a stable\n * `IGX-####` `code` and the `context` identifiers needed to find the offending object,\n * so a production build can compact the human-readable half without losing meaning.\n *\n * @example\n * ```ts\n * try {\n * world.instantiate(scene);\n * } catch (error) {\n * if (isIgnifxError(error) && error.code === CoreErrorCode.sceneNotLoaded) {\n * await scene.load();\n * }\n * }\n * ```\n *\n * @public\n */\nexport class IgnifxError extends Error {\n /** The stable diagnostic code for this failure. */\n readonly code: ErrorCode;\n\n /** Identifiers that locate the failure (entity uid, component type id, asset key, …). */\n readonly context: ErrorContext;\n\n /** One sentence telling the developer how to fix it, or `null` when there is nothing to add. */\n readonly hint: string | null;\n\n /**\n * Creates an ignifx error.\n *\n * @param code - The stable `IGX-####` code for the failure.\n * @param message - An actionable description of what went wrong, used in development mode.\n * @param options - Context, hint, format mode, and the standard `cause`.\n */\n constructor(code: ErrorCode, message: string, options?: IgnifxErrorOptions) {\n const context = options?.context ?? EMPTY_CONTEXT;\n const hint = options?.hint ?? null;\n super(formatErrorMessage(code, message, context, hint, options?.mode ?? \"development\"), options);\n this.name = \"IgnifxError\";\n this.code = code;\n this.context = context;\n this.hint = hint;\n }\n}\n\n/**\n * Narrows an unknown value — a `catch` binding, a rejected promise, a signal payload — to an\n * {@link IgnifxError}.\n *\n * @param value - The value to test.\n * @returns `true` when the value is an ignifx error produced by this copy of `@ignifx/core`.\n *\n * @example\n * ```ts\n * app.onError.connect((report) => {\n * if (isIgnifxError(report.error)) {\n * console.warn(report.error.code, report.error.context);\n * }\n * });\n * ```\n *\n * @public\n */\nexport function isIgnifxError(value: unknown): value is IgnifxError {\n return value instanceof IgnifxError;\n}\n\n/**\n * The default branch of an exhaustive `switch` (coding standards §5.2). The compiler rejects the\n * call as soon as a new union member is left unhandled, and at runtime it throws rather than\n * falling through silently.\n *\n * @param value - The value the type system proved impossible.\n * @param what - What was being switched over, for the message.\n * @throws IgnifxError with code `IGX-1505`; the function never returns.\n *\n * @example\n * ```ts\n * switch (level) {\n * case \"debug\":\n * return 10;\n * default:\n * return assertNever(level, \"log level\");\n * }\n * ```\n *\n * @public\n */\nexport function assertNever(value: never, what: string): never {\n throw new IgnifxError(CoreErrorCode.unreachableCase, `Unreachable case reached for ${what}.`, {\n context: { what, value: String(value) },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAqBA,MAAa,aAAa;;CAExB,WAAW;;CAEX,YAAY;;CAEZ,QAAQ;;CAER,YAAY;;CAEZ,QAAQ;;CAER,eAAe;;CAEf,WAAW;;CAEX,OAAO;;CAEP,SAAS;;CAET,OAAO;;CAEP,MAAM;;CAEN,QAAQ;;CAER,IAAI;;CAEJ,UAAU;;CAEV,UAAU;;CAEV,SAAS;;CAET,WAAW;;CAEX,YAAY;AACd;;;;;;;AAeA,MAAa,2BAA2B;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCxC,MAAa,gBAAgB;;CAE3B,sBAAsB;;CAEtB,4BAA4B;;CAE5B,gCAAgC;;CAEhC,oBAAoB;;CAEpB,qBAAqB;;CAErB,aAAa;;CAEb,aAAa;;CAEb,kBAAkB;;CAElB,qBAAqB;;CAErB,wBAAwB;;CAExB,qBAAqB;;CAErB,0BAA0B;;CAE1B,8BAA8B;;CAE9B,0BAA0B;;CAE1B,wBAAwB;;CAExB,yBAAyB;;CAEzB,sBAAsB;;CAEtB,wBAAwB;;CAExB,yBAAyB;;CAEzB,eAAe;;CAEf,gBAAgB;;CAEhB,oBAAoB;;CAEpB,cAAc;;C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