@ignifx/core 0.18.0 → 0.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{environment-DZ6WUHbm.js → environment-Bf4aphSb.js} +2 -2
- package/dist/{environment-DZ6WUHbm.js.map → environment-Bf4aphSb.js.map} +1 -1
- package/dist/{ignifx-error-B8ByiSfJ.js → ignifx-error-DwIZKxA2.js} +4 -1
- package/dist/ignifx-error-DwIZKxA2.js.map +1 -0
- package/dist/index.d.ts +49 -687
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1326 -834
- package/dist/index.js.map +1 -1
- package/dist/{light-probe-asset-B60_X-yN.js → light-probe-asset-BqfSrJe9.js} +2 -2
- package/dist/{light-probe-asset-B60_X-yN.js.map → light-probe-asset-BqfSrJe9.js.map} +1 -1
- package/dist/{light-probes-DkYN89Qw.js → light-probes-DyLapYX9.js} +3 -3
- package/dist/{light-probes-DkYN89Qw.js.map → light-probes-DyLapYX9.js.map} +1 -1
- package/dist/lightmaps-LO6Ygtwe.js +137 -0
- package/dist/lightmaps-LO6Ygtwe.js.map +1 -0
- package/dist/{material-plugin-CiAmriQ_.js → material-plugin-DapJNj04.js} +2 -2
- package/dist/{material-plugin-CiAmriQ_.js.map → material-plugin-DapJNj04.js.map} +1 -1
- package/dist/{post-effect-CQnlX1RH.js → post-effect-CaiqDlhW.js} +2 -2
- package/dist/{post-effect-CQnlX1RH.js.map → post-effect-CaiqDlhW.js.map} +1 -1
- package/dist/{post-effect-compiler-C_7HTHZy.js → post-effect-compiler-jSvOVe0U.js} +3 -3
- package/dist/{post-effect-compiler-C_7HTHZy.js.map → post-effect-compiler-jSvOVe0U.js.map} +1 -1
- package/dist/{prefab-overrides-BLQn5yHS.d.ts → prefab-overrides-CS8_cG66.d.ts} +1334 -251
- package/dist/prefab-overrides-CS8_cG66.d.ts.map +1 -0
- package/dist/{prefab-overrides-DT-wHHAJ.js → prefab-overrides-DRP2DcnC.js} +450 -30
- package/dist/prefab-overrides-DRP2DcnC.js.map +1 -0
- package/dist/prefab.d.ts +2 -2
- package/dist/prefab.js +2 -2
- package/dist/{reflection-probe-DlVsl3zJ.js → reflection-probe-AS8d4uKv.js} +30 -12
- package/dist/{reflection-probe-DlVsl3zJ.js.map → reflection-probe-AS8d4uKv.js.map} +1 -1
- package/dist/{reflection-probes-B8S9WnVX.js → reflection-probes-CUZcOjNW.js} +115 -22
- package/dist/reflection-probes-CUZcOjNW.js.map +1 -0
- package/dist/{shader-material-CaAkv5nT.js → shader-material-CJIDFvSb.js} +2 -2
- package/dist/{shader-material-CaAkv5nT.js.map → shader-material-CJIDFvSb.js.map} +1 -1
- package/dist/{shader-material-C2_UCYdO.js → shader-material-CuwK9tWC.js} +4 -4
- package/dist/{shader-material-C2_UCYdO.js.map → shader-material-CuwK9tWC.js.map} +1 -1
- package/dist/{shader-pragma-DmZpxGUo.js → shader-pragma-ljmAbVc2.js} +2 -2
- package/dist/{shader-pragma-DmZpxGUo.js.map → shader-pragma-ljmAbVc2.js.map} +1 -1
- package/dist/{surface-shader-BeDRofOV.js → surface-shader-DY9_aC9L.js} +4 -4
- package/dist/{surface-shader-BeDRofOV.js.map → surface-shader-DY9_aC9L.js.map} +1 -1
- package/package.json +1 -1
- package/dist/ignifx-error-B8ByiSfJ.js.map +0 -1
- package/dist/prefab-overrides-BLQn5yHS.d.ts.map +0 -1
- package/dist/prefab-overrides-DT-wHHAJ.js.map +0 -1
- package/dist/reflection-probes-B8S9WnVX.js.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { o as CoreErrorCode, t as IgnifxError } from "./ignifx-error-
|
|
1
|
+
import { o as CoreErrorCode, t as IgnifxError } from "./ignifx-error-DwIZKxA2.js";
|
|
2
2
|
//#region src/render/light-probe-asset.ts
|
|
3
3
|
/**
|
|
4
4
|
* Light probes (`docs/plan/2026-11-gi-phase-2-execution-plan.md`, step B2): a regular grid of baked
|
|
@@ -328,4 +328,4 @@ function invalid(address, problem) {
|
|
|
328
328
|
//#endregion
|
|
329
329
|
export { LightProbeAsset as a, readLightProbeFile as c, writeLightProbeFile as d, LIGHT_PROBE_FORMAT_VERSION as i, readLightProbeGrid as l, LIGHT_PROBE_FILE_EXTENSIONS as n, createLightProbeAsset as o, LIGHT_PROBE_FILE_FORMAT as r, packLightProbeTexels as s, LIGHT_PROBE_ASSET_TYPE as t, sampleLightProbes as u };
|
|
330
330
|
|
|
331
|
-
//# sourceMappingURL=light-probe-asset-
|
|
331
|
+
//# sourceMappingURL=light-probe-asset-BqfSrJe9.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"light-probe-asset-B60_X-yN.js","names":[],"sources":["../src/render/light-probe-asset.ts"],"sourcesContent":["import { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { IgnifxError } from \"../errors/ignifx-error.js\";\nimport type { App } from \"../app/types.js\";\nimport type { AssetHandle } from \"../assets/types.js\";\nimport type { Vec3Like } from \"../math/types.js\";\n\n/**\n * Light probes (`docs/plan/2026-11-gi-phase-2-execution-plan.md`, step B2): a regular grid of baked\n * irradiance samples that a `LightProbeVolume` lights PBR materials with, in place of the scene\n * environment's diffuse light. Everything here is plain data and runs in Node.\n *\n * Each probe stores four RGB coefficients of first-order spherical harmonics, already convolved and\n * scaled the way Babylon Lite's environment harmonics are, so the diffuse light a white surface with\n * normal `n` receives is `c0 + c1·n.y + c2·n.z + c3·n.x` (Lite's `environmentIrradiance`, L1 part).\n */\n\n/**\n * The asset type light-probe grids are registered under.\n *\n * @public\n */\nexport const LIGHT_PROBE_ASSET_TYPE = \"lightprobes\";\n\n/**\n * The address extensions that select the light-probe loader.\n *\n * @public\n */\nexport const LIGHT_PROBE_FILE_EXTENSIONS: readonly string[] = Object.freeze([\".probes.json\"]);\n\n/**\n * The `format` header every `.probes.json` carries.\n *\n * @public\n */\nexport const LIGHT_PROBE_FILE_FORMAT = \"ignifx-probes\";\n\n/**\n * The `formatVersion` this engine reads and writes.\n *\n * @public\n */\nexport const LIGHT_PROBE_FORMAT_VERSION = 1;\n\n/** Floats per probe: four RGB coefficients. */\nconst FLOATS_PER_PROBE = 12;\n\n/** The largest grid side along X (the texture is four times as wide) and the largest Y·Z product. */\nconst MAX_X = 1024;\nconst MAX_YZ = 4096;\n\n/** The bounds that keep the generated shader constants valid 32-bit floats. */\nconst MAX_COORDINATE = 1e20;\nconst MIN_CELL = 1e-30;\n\n/**\n * A grid of light probes, as a `.probes.json` stores it.\n *\n * @remarks\n * Probe `(i, j, k)` sits at `origin + (i, j, k) · cellSize`. `coefficients` holds 12 floats per probe,\n * probes ordered X fastest, then Y, then Z (`index = i + countX·(j + countY·k)`); each probe's floats\n * are `c0.rgb, c1.rgb, c2.rgb, c3.rgb` in linear RGB (see the module remarks).\n *\n * @public\n */\nexport interface LightProbeData {\n /** The world position of probe `(0, 0, 0)`. */\n readonly origin: Vec3Like;\n /** The distance between neighbouring probes along each axis, in metres. */\n readonly cellSize: Vec3Like;\n /** How many probes along X, Y and Z; each at least 1. */\n readonly counts: { readonly x: number; readonly y: number; readonly z: number };\n /** 12 floats per probe, `countX · countY · countZ · 12` in all. */\n readonly coefficients: readonly number[];\n}\n\n/**\n * A loaded light-probe grid.\n *\n * @example\n * ```ts\n * const probes = await app.assets.loadAsync<LightProbeAsset>(\"lighting/hall.probes.json\");\n * world.createEntity(\"Probes\").addComponent(LightProbeVolume, { probes });\n * ```\n *\n * @beta\n */\nexport class LightProbeAsset {\n /** The type name the asset service registers light-probe grids under. */\n static assetType: string = LIGHT_PROBE_ASSET_TYPE;\n\n /** The grid. */\n readonly data: LightProbeData;\n\n /**\n * Wraps a checked grid. Use the loader or {@link createLightProbeAsset}.\n *\n * @param data - The grid, already checked by `readLightProbeData`.\n *\n * @internal\n */\n constructor(data: LightProbeData) {\n this.data = data;\n }\n}\n\n/**\n * Publishes a grid built in code, such as the result of a bake, as an asset.\n *\n * @param app - The app.\n * @param data - The grid.\n * @returns A handle a `LightProbeVolume` can take.\n * @throws IgnifxError with code `IGX-0709` when the grid is malformed.\n *\n * @beta\n */\nexport function createLightProbeAsset(app: App, data: LightProbeData): AssetHandle<LightProbeAsset> {\n return app.assets.register(new LightProbeAsset(readLightProbeData(data, \"light probe data\")), {\n type: LIGHT_PROBE_ASSET_TYPE,\n });\n}\n\n/**\n * Turns a grid into the JSON a `.probes.json` file holds.\n *\n * @param data - The grid.\n * @returns The file contents, with the format header.\n *\n * @beta\n */\nexport function writeLightProbeFile(data: LightProbeData): Record<string, unknown> {\n return {\n format: LIGHT_PROBE_FILE_FORMAT,\n formatVersion: LIGHT_PROBE_FORMAT_VERSION,\n origin: { x: data.origin.x, y: data.origin.y, z: data.origin.z },\n cellSize: { x: data.cellSize.x, y: data.cellSize.y, z: data.cellSize.z },\n counts: { x: data.counts.x, y: data.counts.y, z: data.counts.z },\n coefficients: [...data.coefficients],\n };\n}\n\n/**\n * Reads a parsed `.probes.json`.\n *\n * @param parsed - The parsed JSON.\n * @param address - The file's address, for the error.\n * @returns The grid.\n * @throws IgnifxError with code `IGX-0709` when the header, a field or the coefficient count is wrong.\n *\n * @internal\n */\nexport function readLightProbeFile(parsed: unknown, address: string): LightProbeData {\n const file = asRecord(parsed);\n if (\n file === null ||\n file[\"format\"] !== LIGHT_PROBE_FILE_FORMAT ||\n file[\"formatVersion\"] !== LIGHT_PROBE_FORMAT_VERSION\n ) {\n throw invalid(address, `it must start with { \"format\": \"${LIGHT_PROBE_FILE_FORMAT}\", \"formatVersion\": 1 }`);\n }\n return readLightProbeData(file, address);\n}\n\n/**\n * Checks a grid's fields.\n *\n * @param value - The candidate grid.\n * @param address - Where it came from, for the error.\n * @returns A grid with copied, checked fields.\n * @throws IgnifxError with code `IGX-0709` on a malformed field.\n *\n * @internal\n */\nexport function readLightProbeData(value: unknown, address: string): LightProbeData {\n const record = asRecord(value);\n if (record === null) {\n throw invalid(address, \"it is not an object\");\n }\n const grid = readLightProbeGrid(record);\n if (typeof grid === \"string\") {\n throw invalid(address, grid);\n }\n const { origin, cellSize, counts } = grid;\n const coefficients = record[\"coefficients\"];\n const expected = counts.x * counts.y * counts.z * FLOATS_PER_PROBE;\n if (\n !Array.isArray(coefficients) ||\n coefficients.length !== expected ||\n !coefficients.every((n) => Number.isFinite(n))\n ) {\n throw invalid(address, `coefficients must be ${String(expected)} finite numbers (12 per probe)`);\n }\n return { origin, cellSize, counts, coefficients: coefficients.map(Number) };\n}\n\n/**\n * The grid part of a light-probe grid: where it is, how far apart the probes are, and how many.\n *\n * @internal\n */\nexport interface LightProbeGrid {\n readonly origin: { x: number; y: number; z: number };\n readonly cellSize: { x: number; y: number; z: number };\n readonly counts: { x: number; y: number; z: number };\n}\n\n/**\n * Checks the grid fields of a candidate grid, for a file and for a bake alike.\n *\n * @remarks\n * Besides the format's count limits, `origin` stays below 1e20 in size and `cellSize` between\n * 1e-30 and 1e20, so the constants the shader is generated with stay valid 32-bit floats.\n *\n * @param record - An object with `origin`, `cellSize` and `counts`.\n * @returns The checked copies, or what is wrong with them.\n *\n * @internal\n */\nexport function readLightProbeGrid(record: Readonly<Record<string, unknown>>): LightProbeGrid | string {\n const origin = readVec3(record[\"origin\"], (n) => Number.isFinite(n) && Math.abs(n) < MAX_COORDINATE);\n const cellSize = readVec3(record[\"cellSize\"], (n) => Number.isFinite(n) && n > MIN_CELL && n < MAX_COORDINATE);\n const counts = readVec3(record[\"counts\"], (n) => Number.isSafeInteger(n) && n >= 1);\n if (origin === null || cellSize === null || counts === null) {\n return \"origin (finite, below 1e20), cellSize (from 1e-30 to 1e20) and counts (whole, at least 1) must each be { x, y, z }\";\n }\n if (counts.x > MAX_X || counts.y * counts.z > MAX_YZ) {\n return `counts.x must be at most ${String(MAX_X)} and counts.y × counts.z at most ${String(MAX_YZ)}`;\n }\n return { origin, cellSize, counts };\n}\n\n/**\n * The diffuse light a white surface receives at a point, read from the grid on the CPU the same way\n * the shader reads it: trilinear between the eight surrounding probes, clamped at the grid's edges.\n *\n * @param data - The grid.\n * @param x - World X.\n * @param y - World Y.\n * @param z - World Z.\n * @param normal - The surface normal, unit length.\n * @returns Linear RGB.\n *\n * @beta\n */\nexport function sampleLightProbes(\n data: LightProbeData,\n x: number,\n y: number,\n z: number,\n normal: Vec3Like,\n): [number, number, number] {\n const { counts } = data;\n const gx = gridCoordinate(x, data.origin.x, data.cellSize.x, counts.x);\n const gy = gridCoordinate(y, data.origin.y, data.cellSize.y, counts.y);\n const gz = gridCoordinate(z, data.origin.z, data.cellSize.z, counts.z);\n const out: [number, number, number] = [0, 0, 0];\n for (let corner = 0; corner < 8; corner += 1) {\n const ix = corner & 1 ? gx.high : gx.low;\n const iy = corner & 2 ? gy.high : gy.low;\n const iz = corner & 4 ? gz.high : gz.low;\n const weight = (corner & 1 ? gx.t : 1 - gx.t) * (corner & 2 ? gy.t : 1 - gy.t) * (corner & 4 ? gz.t : 1 - gz.t);\n const base = (ix + counts.x * (iy + counts.y * iz)) * FLOATS_PER_PROBE;\n for (let channel = 0; channel < 3; channel += 1) {\n const c = (index: number): number => data.coefficients[base + index * 3 + channel] ?? 0;\n out[channel] = (out[channel] ?? 0) + weight * (c(0) + c(1) * normal.y + c(2) * normal.z + c(3) * normal.x);\n }\n }\n return out;\n}\n\n/**\n * Packs a grid into the half-float RGBA texels the shader reads: probe `(i, j, k)`'s coefficient `c`\n * at texel `(i + countX·c, j + countY·k)`.\n *\n * @param data - The grid.\n * @returns The width, height and texels (four half floats each, alpha 1).\n *\n * @internal\n */\nexport function packLightProbeTexels(data: LightProbeData): { width: number; height: number; texels: Uint16Array } {\n const { x: nx, y: ny, z: nz } = data.counts;\n const width = nx * 4;\n const height = ny * nz;\n const texels = new Uint16Array(width * height * 4);\n const one = toHalfFloat(1);\n for (let k = 0; k < nz; k += 1) {\n for (let j = 0; j < ny; j += 1) {\n for (let i = 0; i < nx; i += 1) {\n const base = (i + nx * (j + ny * k)) * FLOATS_PER_PROBE;\n for (let c = 0; c < 4; c += 1) {\n const texel = (i + nx * c + width * (j + ny * k)) * 4;\n for (let channel = 0; channel < 3; channel += 1) {\n texels[texel + channel] = toHalfFloat(data.coefficients[base + c * 3 + channel] ?? 0);\n }\n texels[texel + 3] = one;\n }\n }\n }\n }\n return { width, height, texels };\n}\n\n/**\n * Converts a number to IEEE 754 half precision, rounding to nearest and saturating to ±65504.\n *\n * @param value - The number.\n * @returns The 16 bits.\n *\n * @internal\n */\nexport function toHalfFloat(value: number): number {\n if (Number.isNaN(value)) {\n return 0x7e00;\n }\n const sign = value < 0 || Object.is(value, -0) ? 0x8000 : 0;\n const magnitude = Math.min(Math.abs(value), 65504);\n if (magnitude < 2 ** -24) {\n return sign;\n }\n if (magnitude < 2 ** -14) {\n return sign | Math.round(magnitude / 2 ** -24);\n }\n const exponent = Math.floor(Math.log2(magnitude));\n const mantissa = Math.round((magnitude / 2 ** exponent - 1) * 1024);\n // A mantissa that rounds up to 1024 carries into the exponent.\n return sign | (((exponent + 15) << 10) + mantissa);\n}\n\n/** A grid axis lookup: the two probe indices around a point and the blend between them. */\ninterface AxisCell {\n readonly low: number;\n readonly high: number;\n readonly t: number;\n}\n\n/**\n * Finds the probes around a coordinate on one axis.\n *\n * @param value - The world coordinate.\n * @param origin - The grid origin on this axis.\n * @param cell - The cell size on this axis.\n * @param count - The probe count on this axis.\n * @returns The cell.\n */\nfunction gridCoordinate(value: number, origin: number, cell: number, count: number): AxisCell {\n const g = Math.min(Math.max((value - origin) / cell, 0), count - 1);\n const low = Math.min(Math.floor(g), Math.max(count - 2, 0));\n const high = Math.min(low + 1, count - 1);\n return { low, high, t: g - low };\n}\n\n/**\n * Reads `{ x, y, z }` whose components all pass a check.\n *\n * @param value - The candidate.\n * @param check - The per-component test.\n * @returns A copy, or `null`.\n */\nfunction readVec3(value: unknown, check: (n: number) => boolean): { x: number; y: number; z: number } | null {\n const record = asRecord(value);\n if (record === null) {\n return null;\n }\n const { x, y, z } = record;\n if (typeof x !== \"number\" || typeof y !== \"number\" || typeof z !== \"number\" || ![x, y, z].every(check)) {\n return null;\n }\n return { x, y, z };\n}\n\n/**\n * Narrows a value to a plain record.\n *\n * @param value - The candidate.\n * @returns The record, or `null` for anything else.\n */\nfunction asRecord(value: unknown): Record<string, unknown> | null {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return null;\n }\n // Boundary narrowing of parsed JSON (coding standards §5.2).\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return value as Record<string, unknown>;\n}\n\n/**\n * The error for a malformed grid.\n *\n * @param address - Where it came from.\n * @param problem - What is wrong.\n * @returns The error.\n */\nfunction invalid(address: string, problem: string): IgnifxError {\n return new IgnifxError(CoreErrorCode.invalidAssetFile, `${address} is not an ${LIGHT_PROBE_FILE_FORMAT} file.`, {\n context: { file: address, format: LIGHT_PROBE_FILE_FORMAT },\n hint: `Fix the file: ${problem}.`,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAqBA,MAAa,yBAAyB;;;;;;AAOtC,MAAa,8BAAiD,OAAO,OAAO,CAAC,cAAc,CAAC;;;;;;AAO5F,MAAa,0BAA0B;;;;;;AAOvC,MAAa,6BAA6B;;AAG1C,MAAM,mBAAmB;;AAGzB,MAAM,QAAQ;AACd,MAAM,SAAS;;AAGf,MAAM,iBAAiB;AACvB,MAAM,WAAW;;;;;;;;;;;;AAkCjB,IAAa,kBAAb,MAA6B;;CAE3B,OAAO,YAAoB;;CAG3B;;;;;;;;CASA,YAAY,MAAsB;EAChC,KAAK,OAAO;CACd;AACF;;;;;;;;;;;AAYA,SAAgB,sBAAsB,KAAU,MAAoD;CAClG,OAAO,IAAI,OAAO,SAAS,IAAI,gBAAgB,mBAAmB,MAAM,kBAAkB,CAAC,GAAG,EAC5F,MAAM,uBACR,CAAC;AACH;;;;;;;;;AAUA,SAAgB,oBAAoB,MAA+C;CACjF,OAAO;EACL,QAAQ;EACR,eAAA;EACA,QAAQ;GAAE,GAAG,KAAK,OAAO;GAAG,GAAG,KAAK,OAAO;GAAG,GAAG,KAAK,OAAO;EAAE;EAC/D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W,KAAK,MAAM,KAAK,KAAK,SAAS,CAAC;CAChD,MAAM,WAAW,KAAK,OAAO,YAAY,KAAK,WAAW,KAAK,IAAI;CAElE,OAAO,QAAU,WAAW,MAAO,MAAM;AAC3C;;;;;;;;;;AAkBA,SAAS,eAAe,OAAe,QAAgB,MAAc,OAAyB;CAC5F,MAAM,IAAI,KAAK,IAAI,KAAK,KAAK,QAAQ,UAAU,MAAM,CAAC,GAAG,QAAQ,CAAC;CAClE,MAAM,MAAM,KAAK,IAAI,KAAK,MAAM,CAAC,GAAG,KAAK,IAAI,QAAQ,GAAG,CAAC,CAAC;CAE1D,OAAO;EAAE;EAAK,MADD,KAAK,IAAI,MAAM,GAAG,QAAQ,CACtB;EAAG,GAAG,IAAI;CAAI;AACjC;;;;;;;;AASA,SAAS,SAAS,OAAgB,OAA2E;CAC3G,MAAM,SAAS,SAAS,KAAK;CAC7B,IAAI,WAAW,MACb,OAAO;CAET,MAAM,EAAE,GAAG,GAAG,MAAM;CACpB,IAAI,OAAO,MAAM,YAAY,OAAO,MAAM,YAAY,OAAO,MAAM,YAAY,CAAC;EAAC;EAAG;EAAG;CAAC,CAAC,CAAC,MAAM,KAAK,GACnG,OAAO;CAET,OAAO;EAAE;EAAG;EAAG;CAAE;AACnB;;;;;;;AAQA,SAAS,SAAS,OAAgD;CAChE,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,MAAM,QAAQ,KAAK,GACpE,OAAO;CAIT,OAAO;AACT;;;;;;;;AASA,SAAS,QAAQ,SAAiB,SAA8B;CAC9D,OAAO,IAAI,YAAY,cAAc,kBAAkB,GAAG,QAAQ,aAAa,wBAAwB,SAAS;EAC9G,SAAS;GAAE,MAAM;GAAS,QAAQ;EAAwB;EAC1D,MAAM,iBAAiB,QAAQ;CACjC,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"light-probe-asset-BqfSrJe9.js","names":[],"sources":["../src/render/light-probe-asset.ts"],"sourcesContent":["import { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { IgnifxError } from \"../errors/ignifx-error.js\";\nimport type { App } from \"../app/types.js\";\nimport type { AssetHandle } from \"../assets/types.js\";\nimport type { Vec3Like } from \"../math/types.js\";\n\n/**\n * Light probes (`docs/plan/2026-11-gi-phase-2-execution-plan.md`, step B2): a regular grid of baked\n * irradiance samples that a `LightProbeVolume` lights PBR materials with, in place of the scene\n * environment's diffuse light. Everything here is plain data and runs in Node.\n *\n * Each probe stores four RGB coefficients of first-order spherical harmonics, already convolved and\n * scaled the way Babylon Lite's environment harmonics are, so the diffuse light a white surface with\n * normal `n` receives is `c0 + c1·n.y + c2·n.z + c3·n.x` (Lite's `environmentIrradiance`, L1 part).\n */\n\n/**\n * The asset type light-probe grids are registered under.\n *\n * @public\n */\nexport const LIGHT_PROBE_ASSET_TYPE = \"lightprobes\";\n\n/**\n * The address extensions that select the light-probe loader.\n *\n * @public\n */\nexport const LIGHT_PROBE_FILE_EXTENSIONS: readonly string[] = Object.freeze([\".probes.json\"]);\n\n/**\n * The `format` header every `.probes.json` carries.\n *\n * @public\n */\nexport const LIGHT_PROBE_FILE_FORMAT = \"ignifx-probes\";\n\n/**\n * The `formatVersion` this engine reads and writes.\n *\n * @public\n */\nexport const LIGHT_PROBE_FORMAT_VERSION = 1;\n\n/** Floats per probe: four RGB coefficients. */\nconst FLOATS_PER_PROBE = 12;\n\n/** The largest grid side along X (the texture is four times as wide) and the largest Y·Z product. */\nconst MAX_X = 1024;\nconst MAX_YZ = 4096;\n\n/** The bounds that keep the generated shader constants valid 32-bit floats. */\nconst MAX_COORDINATE = 1e20;\nconst MIN_CELL = 1e-30;\n\n/**\n * A grid of light probes, as a `.probes.json` stores it.\n *\n * @remarks\n * Probe `(i, j, k)` sits at `origin + (i, j, k) · cellSize`. `coefficients` holds 12 floats per probe,\n * probes ordered X fastest, then Y, then Z (`index = i + countX·(j + countY·k)`); each probe's floats\n * are `c0.rgb, c1.rgb, c2.rgb, c3.rgb` in linear RGB (see the module remarks).\n *\n * @public\n */\nexport interface LightProbeData {\n /** The world position of probe `(0, 0, 0)`. */\n readonly origin: Vec3Like;\n /** The distance between neighbouring probes along each axis, in metres. */\n readonly cellSize: Vec3Like;\n /** How many probes along X, Y and Z; each at least 1. */\n readonly counts: { readonly x: number; readonly y: number; readonly z: number };\n /** 12 floats per probe, `countX · countY · countZ · 12` in all. */\n readonly coefficients: readonly number[];\n}\n\n/**\n * A loaded light-probe grid.\n *\n * @example\n * ```ts\n * const probes = await app.assets.loadAsync<LightProbeAsset>(\"lighting/hall.probes.json\");\n * world.createEntity(\"Probes\").addComponent(LightProbeVolume, { probes });\n * ```\n *\n * @beta\n */\nexport class LightProbeAsset {\n /** The type name the asset service registers light-probe grids under. */\n static assetType: string = LIGHT_PROBE_ASSET_TYPE;\n\n /** The grid. */\n readonly data: LightProbeData;\n\n /**\n * Wraps a checked grid. Use the loader or {@link createLightProbeAsset}.\n *\n * @param data - The grid, already checked by `readLightProbeData`.\n *\n * @internal\n */\n constructor(data: LightProbeData) {\n this.data = data;\n }\n}\n\n/**\n * Publishes a grid built in code, such as the result of a bake, as an asset.\n *\n * @param app - The app.\n * @param data - The grid.\n * @returns A handle a `LightProbeVolume` can take.\n * @throws IgnifxError with code `IGX-0709` when the grid is malformed.\n *\n * @beta\n */\nexport function createLightProbeAsset(app: App, data: LightProbeData): AssetHandle<LightProbeAsset> {\n return app.assets.register(new LightProbeAsset(readLightProbeData(data, \"light probe data\")), {\n type: LIGHT_PROBE_ASSET_TYPE,\n });\n}\n\n/**\n * Turns a grid into the JSON a `.probes.json` file holds.\n *\n * @param data - The grid.\n * @returns The file contents, with the format header.\n *\n * @beta\n */\nexport function writeLightProbeFile(data: LightProbeData): Record<string, unknown> {\n return {\n format: LIGHT_PROBE_FILE_FORMAT,\n formatVersion: LIGHT_PROBE_FORMAT_VERSION,\n origin: { x: data.origin.x, y: data.origin.y, z: data.origin.z },\n cellSize: { x: data.cellSize.x, y: data.cellSize.y, z: data.cellSize.z },\n counts: { x: data.counts.x, y: data.counts.y, z: data.counts.z },\n coefficients: [...data.coefficients],\n };\n}\n\n/**\n * Reads a parsed `.probes.json`.\n *\n * @param parsed - The parsed JSON.\n * @param address - The file's address, for the error.\n * @returns The grid.\n * @throws IgnifxError with code `IGX-0709` when the header, a field or the coefficient count is wrong.\n *\n * @internal\n */\nexport function readLightProbeFile(parsed: unknown, address: string): LightProbeData {\n const file = asRecord(parsed);\n if (\n file === null ||\n file[\"format\"] !== LIGHT_PROBE_FILE_FORMAT ||\n file[\"formatVersion\"] !== LIGHT_PROBE_FORMAT_VERSION\n ) {\n throw invalid(address, `it must start with { \"format\": \"${LIGHT_PROBE_FILE_FORMAT}\", \"formatVersion\": 1 }`);\n }\n return readLightProbeData(file, address);\n}\n\n/**\n * Checks a grid's fields.\n *\n * @param value - The candidate grid.\n * @param address - Where it came from, for the error.\n * @returns A grid with copied, checked fields.\n * @throws IgnifxError with code `IGX-0709` on a malformed field.\n *\n * @internal\n */\nexport function readLightProbeData(value: unknown, address: string): LightProbeData {\n const record = asRecord(value);\n if (record === null) {\n throw invalid(address, \"it is not an object\");\n }\n const grid = readLightProbeGrid(record);\n if (typeof grid === \"string\") {\n throw invalid(address, grid);\n }\n const { origin, cellSize, counts } = grid;\n const coefficients = record[\"coefficients\"];\n const expected = counts.x * counts.y * counts.z * FLOATS_PER_PROBE;\n if (\n !Array.isArray(coefficients) ||\n coefficients.length !== expected ||\n !coefficients.every((n) => Number.isFinite(n))\n ) {\n throw invalid(address, `coefficients must be ${String(expected)} finite numbers (12 per probe)`);\n }\n return { origin, cellSize, counts, coefficients: coefficients.map(Number) };\n}\n\n/**\n * The grid part of a light-probe grid: where it is, how far apart the probes are, and how many.\n *\n * @internal\n */\nexport interface LightProbeGrid {\n readonly origin: { x: number; y: number; z: number };\n readonly cellSize: { x: number; y: number; z: number };\n readonly counts: { x: number; y: number; z: number };\n}\n\n/**\n * Checks the grid fields of a candidate grid, for a file and for a bake alike.\n *\n * @remarks\n * Besides the format's count limits, `origin` stays below 1e20 in size and `cellSize` between\n * 1e-30 and 1e20, so the constants the shader is generated with stay valid 32-bit floats.\n *\n * @param record - An object with `origin`, `cellSize` and `counts`.\n * @returns The checked copies, or what is wrong with them.\n *\n * @internal\n */\nexport function readLightProbeGrid(record: Readonly<Record<string, unknown>>): LightProbeGrid | string {\n const origin = readVec3(record[\"origin\"], (n) => Number.isFinite(n) && Math.abs(n) < MAX_COORDINATE);\n const cellSize = readVec3(record[\"cellSize\"], (n) => Number.isFinite(n) && n > MIN_CELL && n < MAX_COORDINATE);\n const counts = readVec3(record[\"counts\"], (n) => Number.isSafeInteger(n) && n >= 1);\n if (origin === null || cellSize === null || counts === null) {\n return \"origin (finite, below 1e20), cellSize (from 1e-30 to 1e20) and counts (whole, at least 1) must each be { x, y, z }\";\n }\n if (counts.x > MAX_X || counts.y * counts.z > MAX_YZ) {\n return `counts.x must be at most ${String(MAX_X)} and counts.y × counts.z at most ${String(MAX_YZ)}`;\n }\n return { origin, cellSize, counts };\n}\n\n/**\n * The diffuse light a white surface receives at a point, read from the grid on the CPU the same way\n * the shader reads it: trilinear between the eight surrounding probes, clamped at the grid's edges.\n *\n * @param data - The grid.\n * @param x - World X.\n * @param y - World Y.\n * @param z - World Z.\n * @param normal - The surface normal, unit length.\n * @returns Linear RGB.\n *\n * @beta\n */\nexport function sampleLightProbes(\n data: LightProbeData,\n x: number,\n y: number,\n z: number,\n normal: Vec3Like,\n): [number, number, number] {\n const { counts } = data;\n const gx = gridCoordinate(x, data.origin.x, data.cellSize.x, counts.x);\n const gy = gridCoordinate(y, data.origin.y, data.cellSize.y, counts.y);\n const gz = gridCoordinate(z, data.origin.z, data.cellSize.z, counts.z);\n const out: [number, number, number] = [0, 0, 0];\n for (let corner = 0; corner < 8; corner += 1) {\n const ix = corner & 1 ? gx.high : gx.low;\n const iy = corner & 2 ? gy.high : gy.low;\n const iz = corner & 4 ? gz.high : gz.low;\n const weight = (corner & 1 ? gx.t : 1 - gx.t) * (corner & 2 ? gy.t : 1 - gy.t) * (corner & 4 ? gz.t : 1 - gz.t);\n const base = (ix + counts.x * (iy + counts.y * iz)) * FLOATS_PER_PROBE;\n for (let channel = 0; channel < 3; channel += 1) {\n const c = (index: number): number => data.coefficients[base + index * 3 + channel] ?? 0;\n out[channel] = (out[channel] ?? 0) + weight * (c(0) + c(1) * normal.y + c(2) * normal.z + c(3) * normal.x);\n }\n }\n return out;\n}\n\n/**\n * Packs a grid into the half-float RGBA texels the shader reads: probe `(i, j, k)`'s coefficient `c`\n * at texel `(i + countX·c, j + countY·k)`.\n *\n * @param data - The grid.\n * @returns The width, height and texels (four half floats each, alpha 1).\n *\n * @internal\n */\nexport function packLightProbeTexels(data: LightProbeData): { width: number; height: number; texels: Uint16Array } {\n const { x: nx, y: ny, z: nz } = data.counts;\n const width = nx * 4;\n const height = ny * nz;\n const texels = new Uint16Array(width * height * 4);\n const one = toHalfFloat(1);\n for (let k = 0; k < nz; k += 1) {\n for (let j = 0; j < ny; j += 1) {\n for (let i = 0; i < nx; i += 1) {\n const base = (i + nx * (j + ny * k)) * FLOATS_PER_PROBE;\n for (let c = 0; c < 4; c += 1) {\n const texel = (i + nx * c + width * (j + ny * k)) * 4;\n for (let channel = 0; channel < 3; channel += 1) {\n texels[texel + channel] = toHalfFloat(data.coefficients[base + c * 3 + channel] ?? 0);\n }\n texels[texel + 3] = one;\n }\n }\n }\n }\n return { width, height, texels };\n}\n\n/**\n * Converts a number to IEEE 754 half precision, rounding to nearest and saturating to ±65504.\n *\n * @param value - The number.\n * @returns The 16 bits.\n *\n * @internal\n */\nexport function toHalfFloat(value: number): number {\n if (Number.isNaN(value)) {\n return 0x7e00;\n }\n const sign = value < 0 || Object.is(value, -0) ? 0x8000 : 0;\n const magnitude = Math.min(Math.abs(value), 65504);\n if (magnitude < 2 ** -24) {\n return sign;\n }\n if (magnitude < 2 ** -14) {\n return sign | Math.round(magnitude / 2 ** -24);\n }\n const exponent = Math.floor(Math.log2(magnitude));\n const mantissa = Math.round((magnitude / 2 ** exponent - 1) * 1024);\n // A mantissa that rounds up to 1024 carries into the exponent.\n return sign | (((exponent + 15) << 10) + mantissa);\n}\n\n/** A grid axis lookup: the two probe indices around a point and the blend between them. */\ninterface AxisCell {\n readonly low: number;\n readonly high: number;\n readonly t: number;\n}\n\n/**\n * Finds the probes around a coordinate on one axis.\n *\n * @param value - The world coordinate.\n * @param origin - The grid origin on this axis.\n * @param cell - The cell size on this axis.\n * @param count - The probe count on this axis.\n * @returns The cell.\n */\nfunction gridCoordinate(value: number, origin: number, cell: number, count: number): AxisCell {\n const g = Math.min(Math.max((value - origin) / cell, 0), count - 1);\n const low = Math.min(Math.floor(g), Math.max(count - 2, 0));\n const high = Math.min(low + 1, count - 1);\n return { low, high, t: g - low };\n}\n\n/**\n * Reads `{ x, y, z }` whose components all pass a check.\n *\n * @param value - The candidate.\n * @param check - The per-component test.\n * @returns A copy, or `null`.\n */\nfunction readVec3(value: unknown, check: (n: number) => boolean): { x: number; y: number; z: number } | null {\n const record = asRecord(value);\n if (record === null) {\n return null;\n }\n const { x, y, z } = record;\n if (typeof x !== \"number\" || typeof y !== \"number\" || typeof z !== \"number\" || ![x, y, z].every(check)) {\n return null;\n }\n return { x, y, z };\n}\n\n/**\n * Narrows a value to a plain record.\n *\n * @param value - The candidate.\n * @returns The record, or `null` for anything else.\n */\nfunction asRecord(value: unknown): Record<string, unknown> | null {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return null;\n }\n // Boundary narrowing of parsed JSON (coding standards §5.2).\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return value as Record<string, unknown>;\n}\n\n/**\n * The error for a malformed grid.\n *\n * @param address - Where it came from.\n * @param problem - What is wrong.\n * @returns The error.\n */\nfunction invalid(address: string, problem: string): IgnifxError {\n return new IgnifxError(CoreErrorCode.invalidAssetFile, `${address} is not an ${LIGHT_PROBE_FILE_FORMAT} file.`, {\n context: { file: address, format: LIGHT_PROBE_FILE_FORMAT },\n hint: `Fix the file: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AS,OAAgB,OAA2E;CAC3G,MAAM,SAAS,SAAS,KAAK;CAC7B,IAAI,WAAW,MACb,OAAO;CAET,MAAM,EAAE,GAAG,GAAG,MAAM;CACpB,IAAI,OAAO,MAAM,YAAY,OAAO,MAAM,YAAY,OAAO,MAAM,YAAY,CAAC;EAAC;EAAG;EAAG;CAAC,CAAC,CAAC,MAAM,KAAK,GACnG,OAAO;CAET,OAAO;EAAE;EAAG;EAAG;CAAE;AACnB;;;;;;;AAQA,SAAS,SAAS,OAAgD;CAChE,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,MAAM,QAAQ,KAAK,GACpE,OAAO;CAIT,OAAO;AACT;;;;;;;;AASA,SAAS,QAAQ,SAAiB,SAA8B;CAC9D,OAAO,IAAI,YAAY,cAAc,kBAAkB,GAAG,QAAQ,aAAa,wBAAwB,SAAS;EAC9G,SAAS;GAAE,MAAM;GAAS,QAAQ;EAAwB;EAC1D,MAAM,iBAAiB,QAAQ;CACjC,CAAC;AACH"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { i as readSceneEnvironment } from "./environment-
|
|
1
|
+
import { i as readSceneEnvironment } from "./environment-Bf4aphSb.js";
|
|
2
2
|
import { a as markMaterialDirty, o as rebuildMaterialPipelines } from "./material-CGk5mAah.js";
|
|
3
|
-
import { s as packLightProbeTexels } from "./light-probe-asset-
|
|
3
|
+
import { s as packLightProbeTexels } from "./light-probe-asset-BqfSrJe9.js";
|
|
4
4
|
import { n as deviceOf } from "./render-texture-UqRHRLQy.js";
|
|
5
5
|
import { createRenderTexture2D, enableMaterialPlugins, getPbrUnlit, isPbrMaterial, isPbrSkybox } from "@babylonjs/lite";
|
|
6
6
|
//#region src/lite/gpu/light-probes.ts
|
|
@@ -281,4 +281,4 @@ function createLightProbeRuntime(engine, scene) {
|
|
|
281
281
|
//#endregion
|
|
282
282
|
export { createLightProbeRuntime };
|
|
283
283
|
|
|
284
|
-
//# sourceMappingURL=light-probes-
|
|
284
|
+
//# sourceMappingURL=light-probes-DyLapYX9.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"light-probes-DkYN89Qw.js","names":[],"sources":["../src/lite/gpu/light-probes.ts","../src/render/gpu/light-probes.ts"],"sourcesContent":["import { createRenderTexture2D, enableMaterialPlugins, getPbrUnlit, isPbrMaterial, isPbrSkybox } from \"@babylonjs/lite\";\nimport { markMaterialDirty, rebuildMaterialPipelines } from \"../material.js\";\nimport { deviceOf } from \"./render-texture.js\";\nimport type { EngineContext, MaterialPlugin, SceneContext, Texture2D } from \"@babylonjs/lite\";\n\n/**\n * Light probes on the GPU (`docs/plan/2026-11-gi-phase-2-execution-plan.md`, step B2). Its own chunk,\n * loaded only once a world has a `LightProbeVolume` (`CONSTITUTION.md` §2.5). Every Lite claim was\n * read from `@babylonjs/lite@1.34.0`.\n *\n * - **Texture.** The grid's coefficients, packed by `packLightProbeTexels`, in an `rgba16float`\n * texture read with `textureLoad` (plugins bind `texture_2d<f32>` only, `index.d.ts` 10607, so no\n * 3D texture).\n * - **Plugin.** Lite declares `environmentIrradiance` with `let` inside the IBL code\n * (`lib/material/pbr/fragments/ibl-fragment.js`), so a plugin cannot replace it. Instead the plugin\n * adds `(probes − environment) · surfaceAlbedo · occlusion` to `color`, recomputing the\n * environment's harmonics from the scene uniforms the IBL code reads. Its point,\n * `CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION`, is injected twice (`AI` before the IBL code, `NI`\n * after it; `lib/material/plugin/plugin-bridge-shared.js` line 13), so a private counter applies it\n * on the second pass only. Its priority runs it before the HDR linear-output plugin saves `color`.\n * - **Grid constants** are written into the WGSL, so a different grid is a different plugin and a\n * material rebuild: grids change rarely. `intensity` is a uniform on the host material's block,\n * so changing it rebuilds nothing.\n */\n\n/**\n * The name the plugin carries; part of Lite's pipeline cache key.\n *\n * @internal\n */\nexport const LIGHT_PROBE_PLUGIN_NAME = \"ignifx-light-probes\";\n\n/**\n * The grid shape the shader needs.\n *\n * @internal\n */\nexport interface LightProbeGridShape {\n /** Probe `(0, 0, 0)`'s world position. */\n readonly origin: readonly [number, number, number];\n /** The cell size per axis. */\n readonly cellSize: readonly [number, number, number];\n /** Probe counts per axis. */\n readonly counts: readonly [number, number, number];\n}\n\n/**\n * The plugin's live settings: read on every material uniform write, so changing them needs only\n * {@link refreshLightProbeUniforms}, not a pipeline rebuild.\n *\n * @internal\n */\nexport interface LightProbeUniforms {\n /** The multiplier on the probes' light. */\n intensity: number;\n}\n\n/** The uniform field the plugin adds to each host material's block. */\nconst INTENSITY_FIELD = \"ignifxLpIntensity\";\n\n/**\n * A WGSL float literal.\n *\n * @param value - A finite number.\n * @returns The literal.\n */\nfunction f(value: number): string {\n return Number.isInteger(value) ? `${String(value)}.0` : String(value);\n}\n\n/**\n * The plugin's WGSL.\n *\n * @param shape - The grid.\n * @returns The definitions and the composition code.\n *\n * @internal\n */\nexport function lightProbePluginWgsl(shape: LightProbeGridShape): { definitions: string; composition: string } {\n const [nx, ny, nz] = shape.counts;\n const origin = `vec3<f32>(${shape.origin.map(f).join(\",\")})`;\n const inverse = `vec3<f32>(${shape.cellSize.map((size) => f(1 / size)).join(\",\")})`;\n const maxCell = `vec3<f32>(${f(nx - 1)},${f(ny - 1)},${f(nz - 1)})`;\n const definitions =\n \"var<private> igxLpPass:i32;\" +\n \"fn igxLpTexel(c:vec3<i32>,k:i32)->vec3<f32>{\" +\n `return textureLoad(ignifxLp,vec2<i32>(c.x+${String(nx)}*k,c.y+${String(ny)}*c.z),0).rgb;}` +\n \"fn igxLpAt(c:vec3<i32>,n:vec3<f32>)->vec3<f32>{\" +\n \"return igxLpTexel(c,0)+igxLpTexel(c,1)*n.y+igxLpTexel(c,2)*n.z+igxLpTexel(c,3)*n.x;}\" +\n \"fn igxLpSample(p:vec3<f32>,n:vec3<f32>)->vec3<f32>{\" +\n `let m=${maxCell};let g=clamp((p-${origin})*${inverse},vec3<f32>(0.0),m);` +\n \"let lo=min(floor(g),max(m-1.0,vec3<f32>(0.0)));let t=g-lo;let hi=min(lo+1.0,m);\" +\n \"var r=vec3<f32>(0.0);\" +\n \"for(var i=0;i<8;i++){let s=vec3<i32>(i&1,(i>>1u)&1,(i>>2u)&1)==vec3<i32>(1);\" +\n \"let w=select(1.0-t,t,s);r+=igxLpAt(vec3<i32>(select(lo,hi,s)),n)*(w.x*w.y*w.z);}\" +\n // Trilinear blending of ringing harmonics can dip below zero; light never does.\n \"return max(r,vec3<f32>(0.0));}\";\n const composition =\n \"igxLpPass=igxLpPass+1;\" +\n \"if(igxLpPass==2){\" +\n \"let igxC=cos(scene.envRotationY);let igxS=sin(scene.envRotationY);\" +\n \"let igxN=vec3<f32>(N.x*igxC+N.z*igxS,N.y,-N.x*igxS+N.z*igxC);\" +\n \"let igxEnv=(scene.vSphericalL00.rgb+scene.vSphericalL1_1.rgb*igxN.y+scene.vSphericalL10.rgb*igxN.z\" +\n \"+scene.vSphericalL11.rgb*igxN.x+scene.vSphericalL2_2.rgb*(igxN.y*igxN.x)+scene.vSphericalL2_1.rgb*(igxN.y*igxN.z)\" +\n \"+scene.vSphericalL20.rgb*(3.0*igxN.z*igxN.z-1.0)+scene.vSphericalL21.rgb*(igxN.z*igxN.x)\" +\n \"+scene.vSphericalL22.rgb*(igxN.x*igxN.x-igxN.y*igxN.y))*material.environmentIntensity;\" +\n `color+=(igxLpSample(input.worldPos,N)*material.${INTENSITY_FIELD}-igxEnv)*surfaceAlbedo*occlusion;}`;\n return { definitions, composition };\n}\n\n/**\n * Installs Lite's material-plugin bridges, which the plugin needs, unless the project already did.\n *\n * @remarks\n * Idempotent (`lib/material/plugin/enable-material-plugins.js` replaces its one scene hook). The\n * HDR path calls it before `registerScene` (`./hdr-output.ts`); here it runs after, which works for\n * PBR because the bridge assigns a material's plugin identity during the rebuild that attaching\n * the plugin queues. `light-probe.browser.test.ts` covers that case with HDR off.\n *\n * @param scene - The registered scene.\n *\n * @internal\n */\nexport function enableLightProbePlugins(scene: SceneContext): void {\n enableMaterialPlugins(scene);\n}\n\n/**\n * Uploads packed probe texels into a texture.\n *\n * @param engine - The engine.\n * @param width - The texel width.\n * @param height - The texel height.\n * @param texels - Four half floats per texel.\n * @returns The texture, or `null` when the engine has no device.\n *\n * @internal\n */\nexport function createLightProbeTexture(\n engine: EngineContext,\n width: number,\n height: number,\n texels: Uint16Array,\n): Texture2D | null {\n const device = deviceOf(engine);\n if (device === null) {\n return null;\n }\n const texture = createRenderTexture2D(engine, width, height, {\n format: \"rgba16float\",\n minFilter: \"nearest\",\n magFilter: \"nearest\",\n });\n device.queue.writeTexture({ texture: texture.texture }, texels, { bytesPerRow: width * 8 }, { width, height });\n return texture;\n}\n\n/**\n * Builds the plugin for one grid and its texture.\n *\n * @param shape - The grid.\n * @param texture - The packed texture.\n * @param uniforms - The live settings; the plugin reads them on every uniform write.\n * @returns The plugin, shared by every lit PBR material.\n *\n * @internal\n */\nexport function createLightProbePlugin(\n shape: LightProbeGridShape,\n texture: Texture2D,\n uniforms: LightProbeUniforms,\n): MaterialPlugin {\n const wgsl = lightProbePluginWgsl(shape);\n const fragment = {\n CUSTOM_FRAGMENT_DEFINITIONS: wgsl.definitions,\n CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION: wgsl.composition,\n };\n return {\n name: LIGHT_PROBE_PLUGIN_NAME,\n // Before the HDR linear-output plugin (priority 0) saves `color` at the same point.\n priority: -100,\n getSamplers: () => [{ texture: \"ignifxLp\", sampler: \"ignifxLpSampler\" }],\n getUniforms: () => ({ ubo: [{ name: INTENSITY_FIELD, type: \"f32\" }] }),\n writeUbo: (data, offsets) => {\n // Lite hands over byte offsets.\n const byteOffset = offsets.get(INTENSITY_FIELD);\n if (byteOffset !== undefined) {\n data[byteOffset / 4] = uniforms.intensity;\n }\n },\n bindTextures: (out) => {\n out.push({ texture });\n },\n getCustomCode: (stage) => (stage === \"fragment\" ? fragment : null),\n };\n}\n\n/**\n * Re-uploads the plugin's uniforms on every material that carries it, after\n * {@link LightProbeUniforms} changed.\n *\n * @param scene - The scene.\n * @param plugin - The plugin.\n *\n * @internal\n */\nexport function refreshLightProbeUniforms(scene: SceneContext, plugin: MaterialPlugin): void {\n const meshes = scene.meshes;\n for (let index = 0; index < meshes.length; index += 1) {\n const material = meshes[index]?.material;\n // Declared non-null, but Lite's mesh factories create meshes with `material: null`.\n // oxlint-disable-next-line typescript/no-unnecessary-condition\n if (material === undefined || material === null || !isPbrMaterial(material)) {\n continue;\n }\n if (material.plugins?.includes(plugin) === true) {\n markMaterialDirty(material);\n }\n }\n}\n\n/**\n * Gives every lit PBR material `next` in place of `previous`, rebuilding the ones that changed.\n *\n * @param scene - The registered scene.\n * @param previous - The plugin to take off, or `null`.\n * @param next - The plugin to put on, or `null` to only take `previous` off.\n *\n * @internal\n */\nexport function swapLightProbePlugin(\n scene: SceneContext,\n previous: MaterialPlugin | null,\n next: MaterialPlugin | null,\n): void {\n const meshes = scene.meshes;\n for (let index = 0; index < meshes.length; index += 1) {\n const material = meshes[index]?.material;\n // Declared non-null, but Lite's mesh factories create meshes with `material: null`.\n // oxlint-disable-next-line typescript/no-unnecessary-condition\n if (material === undefined || material === null || !isPbrMaterial(material)) {\n continue;\n }\n const current = material.plugins ?? [];\n const lit = getPbrUnlit(material) === undefined && !isPbrSkybox(material);\n const hasPrevious = previous !== null && current.includes(previous);\n const wantsNext = next !== null && lit;\n if (!hasPrevious && (!wantsNext || current.includes(next))) {\n continue;\n }\n const kept = hasPrevious ? current.filter((plugin) => plugin !== previous) : current;\n material.plugins = wantsNext && !kept.includes(next) ? [...kept, next] : kept;\n rebuildMaterialPipelines(scene, material);\n }\n}\n","import { readSceneEnvironment } from \"../../lite/gpu/environment.js\";\nimport {\n createLightProbePlugin,\n createLightProbeTexture,\n enableLightProbePlugins,\n refreshLightProbeUniforms,\n swapLightProbePlugin,\n} from \"../../lite/gpu/light-probes.js\";\nimport { packLightProbeTexels } from \"../light-probe-asset.js\";\nimport type { LightProbeUniforms } from \"../../lite/gpu/light-probes.js\";\nimport type { LiteMaterialPlugin } from \"../../lite/gpu/material-plugin.js\";\nimport type { LiteEngine, LiteScene } from \"../../lite/scene.js\";\nimport type { LightProbeAsset } from \"../light-probe-asset.js\";\nimport type { LightProbeVolume } from \"../light-probe-volume.js\";\n\n/**\n * The render layer's half of light probes (`docs/plan/2026-11-gi-phase-2-execution-plan.md`, step\n * B2): which volume lights the scene, and keeping its plugin on every lit PBR material. Loaded with\n * `../../lite/gpu/light-probes.ts` as one chunk, only once a world has a `LightProbeVolume`.\n */\n\n/** Frames a replaced texture outlives its plugin, so no in-flight bind group still names it. */\nconst RETIRE_FRAMES = 8;\n\n/** What is applied: which grid, at which intensity, through which plugin. */\ninterface Applied {\n readonly asset: LightProbeAsset;\n readonly uniforms: LightProbeUniforms;\n readonly plugin: LiteMaterialPlugin;\n readonly destroy: () => void;\n}\n\n/**\n * The light probes of a renderer.\n *\n * @internal\n */\nexport interface LightProbeRuntime {\n /** Whether a grid is applied. */\n readonly isLighting: boolean;\n /**\n * Picks the volume that lights the scene and keeps its plugin on every lit PBR material.\n *\n * @param volumes - Every `LightProbeVolume` in the world.\n */\n update(volumes: readonly LightProbeVolume[]): void;\n /** Takes the plugin off every material and frees the texture. */\n dispose(): void;\n}\n\n/**\n * Creates the runtime.\n *\n * @param engine - The engine.\n * @param scene - The registered render scene.\n * @returns The runtime.\n *\n * @internal\n */\nexport function createLightProbeRuntime(engine: LiteEngine, scene: LiteScene): LightProbeRuntime {\n enableLightProbePlugins(scene);\n let applied: Applied | null = null;\n const retiring: { destroy: () => void; frames: number }[] = [];\n\n const apply = (asset: LightProbeAsset, intensity: number): Applied | null => {\n const { data } = asset;\n const packed = packLightProbeTexels(data);\n const texture = createLightProbeTexture(engine, packed.width, packed.height, packed.texels);\n if (texture === null) {\n return null;\n }\n const uniforms: LightProbeUniforms = { intensity };\n const plugin = createLightProbePlugin(\n {\n origin: [data.origin.x, data.origin.y, data.origin.z],\n cellSize: [data.cellSize.x, data.cellSize.y, data.cellSize.z],\n counts: [data.counts.x, data.counts.y, data.counts.z],\n },\n texture,\n uniforms,\n );\n return { asset, uniforms, plugin, destroy: () => texture.texture.destroy() };\n };\n\n const replace = (next: Applied | null): void => {\n swapLightProbePlugin(scene, applied?.plugin ?? null, next?.plugin ?? null);\n if (applied !== null) {\n retiring.push({ destroy: applied.destroy, frames: RETIRE_FRAMES });\n }\n applied = next;\n };\n\n return {\n get isLighting(): boolean {\n return applied !== null;\n },\n update(volumes: readonly LightProbeVolume[]): void {\n for (let index = retiring.length - 1; index >= 0; index -= 1) {\n const entry = retiring[index];\n if (entry !== undefined && --entry.frames <= 0) {\n entry.destroy();\n retiring.splice(index, 1);\n }\n }\n let winner: LightProbeVolume | null = null;\n let asset: LightProbeAsset | null = null;\n // The plugin recomputes the environment's harmonics, so it needs one installed.\n if (readSceneEnvironment(scene) !== null) {\n for (const volume of volumes) {\n const loaded = volume.isEnabledInHierarchy ? volume.loadedProbes() : null;\n if (loaded !== null) {\n winner = volume;\n asset = loaded;\n }\n }\n }\n if (winner === null || asset === null) {\n if (applied !== null) {\n replace(null);\n }\n return;\n }\n if (applied === null || applied.asset !== asset) {\n replace(apply(asset, winner.intensity));\n return;\n }\n if (applied.uniforms.intensity !== winner.intensity) {\n applied.uniforms.intensity = winner.intensity;\n refreshLightProbeUniforms(scene, applied.plugin);\n }\n // Meshes created since the last frame get the plugin too; nothing is rebuilt otherwise.\n swapLightProbePlugin(scene, null, applied.plugin);\n },\n dispose(): void {\n replace(null);\n for (const entry of retiring) {\n entry.destroy();\n }\n retiring.length = 0;\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,MAAa,0BAA0B;;AA4BvC,MAAM,kBAAkB;;;;;;;AAQxB,SAAS,EAAE,OAAuB;CAChC,OAAO,OAAO,UAAU,KAAK,IAAI,GAAG,OAAO,KAAK,EAAE,MAAM,OAAO,KAAK;AACtE;;;;;;;;;AAUA,SAAgB,qBAAqB,OAA0E;CAC7G,MA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,UAAU,SAAS;IAC5B,MAAM,SAAS,OAAO,uBAAuB,OAAO,aAAa,IAAI;IACrE,IAAI,WAAW,MAAM;KACnB,SAAS;KACT,QAAQ;IACV;GACF;GAEF,IAAI,WAAW,QAAQ,UAAU,MAAM;IACrC,IAAI,YAAY,MACd,QAAQ,IAAI;IAEd;GACF;GACA,IAAI,YAAY,QAAQ,QAAQ,UAAU,OAAO;IAC/C,QAAQ,MAAM,OAAO,OAAO,SAAS,CAAC;IACtC;GACF;GACA,IAAI,QAAQ,SAAS,cAAc,OAAO,WAAW;IACnD,QAAQ,SAAS,YAAY,OAAO;IACpC,0BAA0B,OAAO,QAAQ,MAAM;GACjD;GAEA,qBAAqB,OAAO,MAAM,QAAQ,MAAM;EAClD;EACA,UAAgB;GACd,QAAQ,IAAI;GACZ,KAAK,MAAM,SAAS,UAClB,MAAM,QAAQ;GAEhB,SAAS,SAAS;EACpB;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"light-probes-DyLapYX9.js","names":[],"sources":["../src/lite/gpu/light-probes.ts","../src/render/gpu/light-probes.ts"],"sourcesContent":["import { createRenderTexture2D, enableMaterialPlugins, getPbrUnlit, isPbrMaterial, isPbrSkybox } from \"@babylonjs/lite\";\nimport { markMaterialDirty, rebuildMaterialPipelines } from \"../material.js\";\nimport { deviceOf } from \"./render-texture.js\";\nimport type { EngineContext, MaterialPlugin, SceneContext, Texture2D } from \"@babylonjs/lite\";\n\n/**\n * Light probes on the GPU (`docs/plan/2026-11-gi-phase-2-execution-plan.md`, step B2). Its own chunk,\n * loaded only once a world has a `LightProbeVolume` (`CONSTITUTION.md` §2.5). Every Lite claim was\n * read from `@babylonjs/lite@1.34.0`.\n *\n * - **Texture.** The grid's coefficients, packed by `packLightProbeTexels`, in an `rgba16float`\n * texture read with `textureLoad` (plugins bind `texture_2d<f32>` only, `index.d.ts` 10607, so no\n * 3D texture).\n * - **Plugin.** Lite declares `environmentIrradiance` with `let` inside the IBL code\n * (`lib/material/pbr/fragments/ibl-fragment.js`), so a plugin cannot replace it. Instead the plugin\n * adds `(probes − environment) · surfaceAlbedo · occlusion` to `color`, recomputing the\n * environment's harmonics from the scene uniforms the IBL code reads. Its point,\n * `CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION`, is injected twice (`AI` before the IBL code, `NI`\n * after it; `lib/material/plugin/plugin-bridge-shared.js` line 13), so a private counter applies it\n * on the second pass only. Its priority runs it before the HDR linear-output plugin saves `color`.\n * - **Grid constants** are written into the WGSL, so a different grid is a different plugin and a\n * material rebuild: grids change rarely. `intensity` is a uniform on the host material's block,\n * so changing it rebuilds nothing.\n */\n\n/**\n * The name the plugin carries; part of Lite's pipeline cache key.\n *\n * @internal\n */\nexport const LIGHT_PROBE_PLUGIN_NAME = \"ignifx-light-probes\";\n\n/**\n * The grid shape the shader needs.\n *\n * @internal\n */\nexport interface LightProbeGridShape {\n /** Probe `(0, 0, 0)`'s world position. */\n readonly origin: readonly [number, number, number];\n /** The cell size per axis. */\n readonly cellSize: readonly [number, number, number];\n /** Probe counts per axis. */\n readonly counts: readonly [number, number, number];\n}\n\n/**\n * The plugin's live settings: read on every material uniform write, so changing them needs only\n * {@link refreshLightProbeUniforms}, not a pipeline rebuild.\n *\n * @internal\n */\nexport interface LightProbeUniforms {\n /** The multiplier on the probes' light. */\n intensity: number;\n}\n\n/** The uniform field the plugin adds to each host material's block. */\nconst INTENSITY_FIELD = \"ignifxLpIntensity\";\n\n/**\n * A WGSL float literal.\n *\n * @param value - A finite number.\n * @returns The literal.\n */\nfunction f(value: number): string {\n return Number.isInteger(value) ? `${String(value)}.0` : String(value);\n}\n\n/**\n * The plugin's WGSL.\n *\n * @param shape - The grid.\n * @returns The definitions and the composition code.\n *\n * @internal\n */\nexport function lightProbePluginWgsl(shape: LightProbeGridShape): { definitions: string; composition: string } {\n const [nx, ny, nz] = shape.counts;\n const origin = `vec3<f32>(${shape.origin.map(f).join(\",\")})`;\n const inverse = `vec3<f32>(${shape.cellSize.map((size) => f(1 / size)).join(\",\")})`;\n const maxCell = `vec3<f32>(${f(nx - 1)},${f(ny - 1)},${f(nz - 1)})`;\n const definitions =\n \"var<private> igxLpPass:i32;\" +\n \"fn igxLpTexel(c:vec3<i32>,k:i32)->vec3<f32>{\" +\n `return textureLoad(ignifxLp,vec2<i32>(c.x+${String(nx)}*k,c.y+${String(ny)}*c.z),0).rgb;}` +\n \"fn igxLpAt(c:vec3<i32>,n:vec3<f32>)->vec3<f32>{\" +\n \"return igxLpTexel(c,0)+igxLpTexel(c,1)*n.y+igxLpTexel(c,2)*n.z+igxLpTexel(c,3)*n.x;}\" +\n \"fn igxLpSample(p:vec3<f32>,n:vec3<f32>)->vec3<f32>{\" +\n `let m=${maxCell};let g=clamp((p-${origin})*${inverse},vec3<f32>(0.0),m);` +\n \"let lo=min(floor(g),max(m-1.0,vec3<f32>(0.0)));let t=g-lo;let hi=min(lo+1.0,m);\" +\n \"var r=vec3<f32>(0.0);\" +\n \"for(var i=0;i<8;i++){let s=vec3<i32>(i&1,(i>>1u)&1,(i>>2u)&1)==vec3<i32>(1);\" +\n \"let w=select(1.0-t,t,s);r+=igxLpAt(vec3<i32>(select(lo,hi,s)),n)*(w.x*w.y*w.z);}\" +\n // Trilinear blending of ringing harmonics can dip below zero; light never does.\n \"return max(r,vec3<f32>(0.0));}\";\n const composition =\n \"igxLpPass=igxLpPass+1;\" +\n \"if(igxLpPass==2){\" +\n \"let igxC=cos(scene.envRotationY);let igxS=sin(scene.envRotationY);\" +\n \"let igxN=vec3<f32>(N.x*igxC+N.z*igxS,N.y,-N.x*igxS+N.z*igxC);\" +\n \"let igxEnv=(scene.vSphericalL00.rgb+scene.vSphericalL1_1.rgb*igxN.y+scene.vSphericalL10.rgb*igxN.z\" +\n \"+scene.vSphericalL11.rgb*igxN.x+scene.vSphericalL2_2.rgb*(igxN.y*igxN.x)+scene.vSphericalL2_1.rgb*(igxN.y*igxN.z)\" +\n \"+scene.vSphericalL20.rgb*(3.0*igxN.z*igxN.z-1.0)+scene.vSphericalL21.rgb*(igxN.z*igxN.x)\" +\n \"+scene.vSphericalL22.rgb*(igxN.x*igxN.x-igxN.y*igxN.y))*material.environmentIntensity;\" +\n `color+=(igxLpSample(input.worldPos,N)*material.${INTENSITY_FIELD}-igxEnv)*surfaceAlbedo*occlusion;}`;\n return { definitions, composition };\n}\n\n/**\n * Installs Lite's material-plugin bridges, which the plugin needs, unless the project already did.\n *\n * @remarks\n * Idempotent (`lib/material/plugin/enable-material-plugins.js` replaces its one scene hook). The\n * HDR path calls it before `registerScene` (`./hdr-output.ts`); here it runs after, which works for\n * PBR because the bridge assigns a material's plugin identity during the rebuild that attaching\n * the plugin queues. `light-probe.browser.test.ts` covers that case with HDR off.\n *\n * @param scene - The registered scene.\n *\n * @internal\n */\nexport function enableLightProbePlugins(scene: SceneContext): void {\n enableMaterialPlugins(scene);\n}\n\n/**\n * Uploads packed probe texels into a texture.\n *\n * @param engine - The engine.\n * @param width - The texel width.\n * @param height - The texel height.\n * @param texels - Four half floats per texel.\n * @returns The texture, or `null` when the engine has no device.\n *\n * @internal\n */\nexport function createLightProbeTexture(\n engine: EngineContext,\n width: number,\n height: number,\n texels: Uint16Array,\n): Texture2D | null {\n const device = deviceOf(engine);\n if (device === null) {\n return null;\n }\n const texture = createRenderTexture2D(engine, width, height, {\n format: \"rgba16float\",\n minFilter: \"nearest\",\n magFilter: \"nearest\",\n });\n device.queue.writeTexture({ texture: texture.texture }, texels, { bytesPerRow: width * 8 }, { width, height });\n return texture;\n}\n\n/**\n * Builds the plugin for one grid and its texture.\n *\n * @param shape - The grid.\n * @param texture - The packed texture.\n * @param uniforms - The live settings; the plugin reads them on every uniform write.\n * @returns The plugin, shared by every lit PBR material.\n *\n * @internal\n */\nexport function createLightProbePlugin(\n shape: LightProbeGridShape,\n texture: Texture2D,\n uniforms: LightProbeUniforms,\n): MaterialPlugin {\n const wgsl = lightProbePluginWgsl(shape);\n const fragment = {\n CUSTOM_FRAGMENT_DEFINITIONS: wgsl.definitions,\n CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION: wgsl.composition,\n };\n return {\n name: LIGHT_PROBE_PLUGIN_NAME,\n // Before the HDR linear-output plugin (priority 0) saves `color` at the same point.\n priority: -100,\n getSamplers: () => [{ texture: \"ignifxLp\", sampler: \"ignifxLpSampler\" }],\n getUniforms: () => ({ ubo: [{ name: INTENSITY_FIELD, type: \"f32\" }] }),\n writeUbo: (data, offsets) => {\n // Lite hands over byte offsets.\n const byteOffset = offsets.get(INTENSITY_FIELD);\n if (byteOffset !== undefined) {\n data[byteOffset / 4] = uniforms.intensity;\n }\n },\n bindTextures: (out) => {\n out.push({ texture });\n },\n getCustomCode: (stage) => (stage === \"fragment\" ? fragment : null),\n };\n}\n\n/**\n * Re-uploads the plugin's uniforms on every material that carries it, after\n * {@link LightProbeUniforms} changed.\n *\n * @param scene - The scene.\n * @param plugin - The plugin.\n *\n * @internal\n */\nexport function refreshLightProbeUniforms(scene: SceneContext, plugin: MaterialPlugin): void {\n const meshes = scene.meshes;\n for (let index = 0; index < meshes.length; index += 1) {\n const material = meshes[index]?.material;\n // Declared non-null, but Lite's mesh factories create meshes with `material: null`.\n // oxlint-disable-next-line typescript/no-unnecessary-condition\n if (material === undefined || material === null || !isPbrMaterial(material)) {\n continue;\n }\n if (material.plugins?.includes(plugin) === true) {\n markMaterialDirty(material);\n }\n }\n}\n\n/**\n * Gives every lit PBR material `next` in place of `previous`, rebuilding the ones that changed.\n *\n * @param scene - The registered scene.\n * @param previous - The plugin to take off, or `null`.\n * @param next - The plugin to put on, or `null` to only take `previous` off.\n *\n * @internal\n */\nexport function swapLightProbePlugin(\n scene: SceneContext,\n previous: MaterialPlugin | null,\n next: MaterialPlugin | null,\n): void {\n const meshes = scene.meshes;\n for (let index = 0; index < meshes.length; index += 1) {\n const material = meshes[index]?.material;\n // Declared non-null, but Lite's mesh factories create meshes with `material: null`.\n // oxlint-disable-next-line typescript/no-unnecessary-condition\n if (material === undefined || material === null || !isPbrMaterial(material)) {\n continue;\n }\n const current = material.plugins ?? [];\n const lit = getPbrUnlit(material) === undefined && !isPbrSkybox(material);\n const hasPrevious = previous !== null && current.includes(previous);\n const wantsNext = next !== null && lit;\n if (!hasPrevious && (!wantsNext || current.includes(next))) {\n continue;\n }\n const kept = hasPrevious ? current.filter((plugin) => plugin !== previous) : current;\n material.plugins = wantsNext && !kept.includes(next) ? [...kept, next] : kept;\n rebuildMaterialPipelines(scene, material);\n }\n}\n","import { readSceneEnvironment } from \"../../lite/gpu/environment.js\";\nimport {\n createLightProbePlugin,\n createLightProbeTexture,\n enableLightProbePlugins,\n refreshLightProbeUniforms,\n swapLightProbePlugin,\n} from \"../../lite/gpu/light-probes.js\";\nimport { packLightProbeTexels } from \"../light-probe-asset.js\";\nimport type { LightProbeUniforms } from \"../../lite/gpu/light-probes.js\";\nimport type { LiteMaterialPlugin } from \"../../lite/gpu/material-plugin.js\";\nimport type { LiteEngine, LiteScene } from \"../../lite/scene.js\";\nimport type { LightProbeAsset } from \"../light-probe-asset.js\";\nimport type { LightProbeVolume } from \"../light-probe-volume.js\";\n\n/**\n * The render layer's half of light probes (`docs/plan/2026-11-gi-phase-2-execution-plan.md`, step\n * B2): which volume lights the scene, and keeping its plugin on every lit PBR material. Loaded with\n * `../../lite/gpu/light-probes.ts` as one chunk, only once a world has a `LightProbeVolume`.\n */\n\n/** Frames a replaced texture outlives its plugin, so no in-flight bind group still names it. */\nconst RETIRE_FRAMES = 8;\n\n/** What is applied: which grid, at which intensity, through which plugin. */\ninterface Applied {\n readonly asset: LightProbeAsset;\n readonly uniforms: LightProbeUniforms;\n readonly plugin: LiteMaterialPlugin;\n readonly destroy: () => void;\n}\n\n/**\n * The light probes of a renderer.\n *\n * @internal\n */\nexport interface LightProbeRuntime {\n /** Whether a grid is applied. */\n readonly isLighting: boolean;\n /**\n * Picks the volume that lights the scene and keeps its plugin on every lit PBR material.\n *\n * @param volumes - Every `LightProbeVolume` in the world.\n */\n update(volumes: readonly LightProbeVolume[]): void;\n /** Takes the plugin off every material and frees the texture. */\n dispose(): void;\n}\n\n/**\n * Creates the runtime.\n *\n * @param engine - The engine.\n * @param scene - The registered render scene.\n * @returns The runtime.\n *\n * @internal\n */\nexport function createLightProbeRuntime(engine: LiteEngine, scene: LiteScene): LightProbeRuntime {\n enableLightProbePlugins(scene);\n let applied: Applied | null = null;\n const retiring: { destroy: () => void; frames: number }[] = [];\n\n const apply = (asset: LightProbeAsset, intensity: number): Applied | null => {\n const { data } = asset;\n const packed = packLightProbeTexels(data);\n const texture = createLightProbeTexture(engine, packed.width, packed.height, packed.texels);\n if (texture === null) {\n return null;\n }\n const uniforms: LightProbeUniforms = { intensity };\n const plugin = createLightProbePlugin(\n {\n origin: [data.origin.x, data.origin.y, data.origin.z],\n cellSize: [data.cellSize.x, data.cellSize.y, data.cellSize.z],\n counts: [data.counts.x, data.counts.y, data.counts.z],\n },\n texture,\n uniforms,\n );\n return { asset, uniforms, plugin, destroy: () => texture.texture.destroy() };\n };\n\n const replace = (next: Applied | null): void => {\n swapLightProbePlugin(scene, applied?.plugin ?? null, next?.plugin ?? null);\n if (applied !== null) {\n retiring.push({ destroy: applied.destroy, frames: RETIRE_FRAMES });\n }\n applied = next;\n };\n\n return {\n get isLighting(): boolean {\n return applied !== null;\n },\n update(volumes: readonly LightProbeVolume[]): void {\n for (let index = retiring.length - 1; index >= 0; index -= 1) {\n const entry = retiring[index];\n if (entry !== undefined && --entry.frames <= 0) {\n entry.destroy();\n retiring.splice(index, 1);\n }\n }\n let winner: LightProbeVolume | null = null;\n let asset: LightProbeAsset | null = null;\n // The plugin recomputes the environment's harmonics, so it needs one installed.\n if (readSceneEnvironment(scene) !== null) {\n for (const volume of volumes) {\n const loaded = volume.isEnabledInHierarchy ? volume.loadedProbes() : null;\n if (loaded !== null) {\n winner = volume;\n asset = loaded;\n }\n }\n }\n if (winner === null || asset === null) {\n if (applied !== null) {\n replace(null);\n }\n return;\n }\n if (applied === null || applied.asset !== asset) {\n replace(apply(asset, winner.intensity));\n return;\n }\n if (applied.uniforms.intensity !== winner.intensity) {\n applied.uniforms.intensity = winner.intensity;\n refreshLightProbeUniforms(scene, applied.plugin);\n }\n // Meshes created since the last frame get the plugin too; nothing is rebuilt otherwise.\n swapLightProbePlugin(scene, null, applied.plugin);\n },\n dispose(): void {\n replace(null);\n for (const entry of retiring) {\n entry.destroy();\n }\n retiring.length = 0;\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,MAAa,0BAA0B;;AA4BvC,MAAM,kBAAkB;;;;;;;AAQxB,SAAS,EAAE,OAAuB;CAChC,OAAO,OAAO,UAAU,KAAK,IAAI,GAAG,OAAO,KAAK,EAAE,MAAM,OAAO,KAAK;AACtE;;;;;;;;;AAUA,SAAgB,qBAAqB,OAA0E;CAC7G,MAAM,CAAC,IAAI,IAAI,MAAM,MAAM;CAC3B,MAAM,SAAS,aAAa,MAAM,OAAO,IAAI,CAAC,CAAC,CAAC,KAAK,GAAG,EAAE;CAC1D,MAAM,UAAU,aAAa,MAAM,SAAS,KAAK,SAAS,EAAE,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,GAAG,EAAE;CACjF,MAAM,UAAU,aAAa,EAAE,KAAK,CAAC,EAAE,GAAG,EAAE,KAAK,CAAC,EAAE,GAAG,EAAE,KAAK,CAAC,EAAE;CAyBjE,OAAO;EAAE,aAAA,oHArBsC,OAAO,EAAE,EAAE,SAAS,OAAO,EAAE,EAAE,4MAInE,QAAQ,kBAAkB,OAAO,IAAI,QAAQ;EAiBlC,aAAA,ylBAD8B,gBAAgB;CAClC;AACpC;;;;;;;;;;;;;;AAeA,SAAgB,wBAAwB,OAA2B;CACjE,sBAAsB,KAAK;AAC7B;;;;;;;;;;;;AAaA,SAAgB,wBACd,QACA,OACA,QACA,QACkB;CAClB,MAAM,SAAS,SAAS,MAAM;CAC9B,IAAI,WAAW,MACb,OAAO;CAET,MAAM,UAAU,sBAAsB,QAAQ,O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rLightmap } from "@babylonjs/lite";
|
|
3
|
+
//#region src/lite/gpu/lightmap.ts
|
|
4
|
+
/**
|
|
5
|
+
* Installs Lite's PBR lightmap extension. Idempotent.
|
|
6
|
+
*
|
|
7
|
+
* @returns A promise that settles once the extension is registered.
|
|
8
|
+
*
|
|
9
|
+
* @internal
|
|
10
|
+
*/
|
|
11
|
+
function enableLightmaps() {
|
|
12
|
+
return enablePbrLightmap();
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Gives a PBR material a lightmap.
|
|
16
|
+
*
|
|
17
|
+
* @param material - A material no other mesh shares, not yet built with other lightmap options.
|
|
18
|
+
* @param texture - The lightmap.
|
|
19
|
+
* @param options - How it is drawn.
|
|
20
|
+
* @returns `false` when the material is not PBR, so nothing was set.
|
|
21
|
+
*
|
|
22
|
+
* @internal
|
|
23
|
+
*/
|
|
24
|
+
function applyLightmap(material, texture, options) {
|
|
25
|
+
if (!isPbrMaterial(material)) return false;
|
|
26
|
+
setPbrLightmap(material, texture, {
|
|
27
|
+
level: options.level,
|
|
28
|
+
coordIndex: options.uv2 ? 1 : 0,
|
|
29
|
+
useAsShadowmap: options.shadowmap,
|
|
30
|
+
gamma: options.gamma
|
|
31
|
+
});
|
|
32
|
+
return true;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Changes a lightmapped material's intensity; only its uniform block is rewritten.
|
|
36
|
+
*
|
|
37
|
+
* @param material - A material {@link applyLightmap} set up.
|
|
38
|
+
* @param level - The new multiplier.
|
|
39
|
+
*
|
|
40
|
+
* @internal
|
|
41
|
+
*/
|
|
42
|
+
function setLightmapLevel(material, level) {
|
|
43
|
+
if (isPbrMaterial(material) && material.lightmapLevel !== level) {
|
|
44
|
+
material.lightmapLevel = level;
|
|
45
|
+
markMaterialDirty(material);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
//#endregion
|
|
49
|
+
//#region src/render/gpu/lightmaps.ts
|
|
50
|
+
/**
|
|
51
|
+
* Installs Lite's lightmap extension and creates the runtime.
|
|
52
|
+
*
|
|
53
|
+
* @param app - The app whose asset service publishes the clones.
|
|
54
|
+
* @param scene - The registered render scene.
|
|
55
|
+
* @returns The runtime, once the extension is registered.
|
|
56
|
+
*
|
|
57
|
+
* @internal
|
|
58
|
+
*/
|
|
59
|
+
async function createLightmapRuntime(app, scene) {
|
|
60
|
+
await enableLightmaps();
|
|
61
|
+
const entries = /* @__PURE__ */ new Map();
|
|
62
|
+
/** Clones handed out this frame, and those whose meshes have drawn them plain for a frame. */
|
|
63
|
+
let fresh = [];
|
|
64
|
+
let due = [];
|
|
65
|
+
const release = (owner) => {
|
|
66
|
+
const entry = entries.get(owner);
|
|
67
|
+
if (entry !== void 0) {
|
|
68
|
+
entries.delete(owner);
|
|
69
|
+
entry.isReleased = true;
|
|
70
|
+
entry.clone.release();
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
return {
|
|
74
|
+
get count() {
|
|
75
|
+
return entries.size;
|
|
76
|
+
},
|
|
77
|
+
materialFor(owner, base, lightmap, settings) {
|
|
78
|
+
const handle = lightmap.texture;
|
|
79
|
+
const texture = handle.state === "loaded" ? handle.value.lite.texture : null;
|
|
80
|
+
if (texture === null) {
|
|
81
|
+
release(owner);
|
|
82
|
+
return base.lite.material;
|
|
83
|
+
}
|
|
84
|
+
const key = `${settings.mode}|${String(settings.gamma)}|${String(settings.uv2)}`;
|
|
85
|
+
const options = {
|
|
86
|
+
level: settings.level,
|
|
87
|
+
shadowmap: settings.mode === "shadowmap",
|
|
88
|
+
gamma: settings.gamma,
|
|
89
|
+
uv2: settings.uv2
|
|
90
|
+
};
|
|
91
|
+
const current = entries.get(owner);
|
|
92
|
+
if (current !== void 0 && current.base === base && current.lightmap === lightmap && current.texture === texture && current.key === key) {
|
|
93
|
+
const material = current.clone.value.lite.material;
|
|
94
|
+
current.options = options;
|
|
95
|
+
if (current.isApplied) setLightmapLevel(material, settings.level);
|
|
96
|
+
return material;
|
|
97
|
+
}
|
|
98
|
+
release(owner);
|
|
99
|
+
const clone = base.clone(app);
|
|
100
|
+
const entry = {
|
|
101
|
+
base,
|
|
102
|
+
lightmap,
|
|
103
|
+
texture,
|
|
104
|
+
key,
|
|
105
|
+
clone,
|
|
106
|
+
options,
|
|
107
|
+
isApplied: false,
|
|
108
|
+
isReleased: false
|
|
109
|
+
};
|
|
110
|
+
entries.set(owner, entry);
|
|
111
|
+
fresh.push(entry);
|
|
112
|
+
return clone.value.lite.material;
|
|
113
|
+
},
|
|
114
|
+
release,
|
|
115
|
+
flush() {
|
|
116
|
+
for (const entry of due) {
|
|
117
|
+
if (entry.isReleased) continue;
|
|
118
|
+
const material = entry.clone.value.lite.material;
|
|
119
|
+
if (applyLightmap(material, entry.texture, entry.options)) {
|
|
120
|
+
entry.isApplied = true;
|
|
121
|
+
rebuildMaterialPipelines(scene, material);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
due = fresh;
|
|
125
|
+
fresh = [];
|
|
126
|
+
},
|
|
127
|
+
dispose() {
|
|
128
|
+
fresh = [];
|
|
129
|
+
due = [];
|
|
130
|
+
for (const owner of entries.keys()) release(owner);
|
|
131
|
+
}
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
//#endregion
|
|
135
|
+
export { createLightmapRuntime };
|
|
136
|
+
|
|
137
|
+
//# sourceMappingURL=lightmaps-LO6Ygtwe.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"lightmaps-LO6Ygtwe.js","names":[],"sources":["../src/lite/gpu/lightmap.ts","../src/render/gpu/lightmaps.ts"],"sourcesContent":["import { enablePbrLightmap, isPbrMaterial, setPbrLightmap } from \"@babylonjs/lite\";\nimport { markMaterialDirty } from \"../material.js\";\nimport type { Material, Texture2D } from \"@babylonjs/lite\";\n\n/**\n * Lightmaps on the GPU (`docs/plan/2026-11-gi-phase-2-execution-plan.md`, step B3). Loaded with\n * `../../render/gpu/lightmaps.ts` as one chunk, only once a static `MeshRenderer` names a loaded\n * lightmap (`CONSTITUTION.md` §2.5). Every Lite claim was read from `@babylonjs/lite@1.34.0`.\n *\n * - **Late enable.** `enablePbrLightmap` (`index.d.ts` 5342) asks to be awaited before\n * `registerScene`, but all it does is register the fragment extension in a process-wide map whose\n * sorted cache it resets (`lib/material/pbr/pbr-flags.js`, `_registerPbrExt`). A material that has\n * no `lightmapTexture` reports no lightmap feature bits (`lightmap-fragment.js`, `detect`), so\n * pipelines built before the call keep their keys, and a material built after it sees the\n * extension. The chunk therefore enables it on load; `rendering.features.lightmaps` only does it\n * earlier.\n * - **Per-material.** `setPbrLightmap` (12635) writes the texture, level, UV set, blend mode and\n * decode onto one material and claims TEXCOORD_1 for it, so a renderer gets its own material\n * before the call. Only `level` is a uniform (`writeLightmapUBO`); the rest are feature bits, so a\n * change of them needs a new material.\n * - **No UV transform.** The fragment samples `input.uv2` raw (line 24), so atlas scale and offset\n * are not applied (GI plan §5, spike P2).\n */\n\n/**\n * The options one material's lightmap is drawn with.\n *\n * @internal\n */\nexport interface LiteLightmapOptions {\n /** Intensity multiplier on the sample. */\n readonly level: number;\n /** `true` multiplies the shaded colour (Lite's `useAsShadowmap`); `false` adds to it. */\n readonly shadowmap: boolean;\n /** Decode the sample from sRGB to linear (`pow(x, 2.2)`). */\n readonly gamma: boolean;\n /** Sample with the second UV set (`TEXCOORD_1`) rather than the first. */\n readonly uv2: boolean;\n}\n\n/**\n * Installs Lite's PBR lightmap extension. Idempotent.\n *\n * @returns A promise that settles once the extension is registered.\n *\n * @internal\n */\nexport function enableLightmaps(): Promise<void> {\n return enablePbrLightmap();\n}\n\n/**\n * Gives a PBR material a lightmap.\n *\n * @param material - A material no other mesh shares, not yet built with other lightmap options.\n * @param texture - The lightmap.\n * @param options - How it is drawn.\n * @returns `false` when the material is not PBR, so nothing was set.\n *\n * @internal\n */\nexport function applyLightmap(material: Material, texture: Texture2D, options: LiteLightmapOptions): boolean {\n if (!isPbrMaterial(material)) {\n return false;\n }\n setPbrLightmap(material, texture, {\n level: options.level,\n coordIndex: options.uv2 ? 1 : 0,\n useAsShadowmap: options.shadowmap,\n gamma: options.gamma,\n });\n return true;\n}\n\n/**\n * Changes a lightmapped material's intensity; only its uniform block is rewritten.\n *\n * @param material - A material {@link applyLightmap} set up.\n * @param level - The new multiplier.\n *\n * @internal\n */\nexport function setLightmapLevel(material: Material, level: number): void {\n if (isPbrMaterial(material) && material.lightmapLevel !== level) {\n material.lightmapLevel = level;\n markMaterialDirty(material);\n }\n}\n","import { applyLightmap, enableLightmaps, setLightmapLevel } from \"../../lite/gpu/lightmap.js\";\nimport { rebuildMaterialPipelines } from \"../../lite/material.js\";\nimport type { App } from \"../../app/types.js\";\nimport type { AssetHandle } from \"../../assets/types.js\";\nimport type { LiteLightmapOptions } from \"../../lite/gpu/lightmap.js\";\nimport type { LiteTexture2D } from \"../../lite/gpu/texture.js\";\nimport type { LiteMaterial } from \"../../lite/material.js\";\nimport type { LiteScene } from \"../../lite/scene.js\";\nimport type { LightmapAsset } from \"../lightmap-asset.js\";\nimport type { MaterialAsset } from \"../material-asset.js\";\nimport type { MeshRendererLightmap } from \"../mesh-renderer.js\";\n\n/**\n * The render layer's half of lightmaps (`docs/plan/2026-11-gi-phase-2-execution-plan.md`, step B3):\n * one material clone per lightmapped renderer. Loaded with `../../lite/gpu/lightmap.ts` as one\n * chunk, only once a static `MeshRenderer` names a loaded lightmap.\n *\n * `MaterialAsset`s are shared, and a lightmap is per renderer, so each renderer draws with\n * `MaterialAsset.clone` of its material carrying the lightmap. The clone is rebuilt when the\n * material, the lightmap, its texture or a compiled option (`mode`, `gamma`, `uv2`) changes; a\n * `level` change only rewrites the clone's uniform block. Edits made to the shared material after\n * the clone was built do not reach it.\n *\n * ## Two frames, because of how Lite plumbs `uv2`\n *\n * Lite decides whether its PBR group carries the `uv2` attribute and varying when it builds the\n * group, from the meshes' materials at that time (`lib/material/pbr/pbr-renderable.js`, `hasAnyUv2`).\n * A `mesh.material` swap reuses the group's single-mesh rebuild (`lib/scene/scene-material-swap.js`),\n * whose composer has no `uv2` then, and a lightmap that samples `input.uv2` fails to compile; the\n * pipeline keeps failing after a later group rebuild, because the broken composition was cached\n * under the same feature key (measured in `lightmap.browser.test.ts`). So the renderer first draws\n * with a plain clone, which compiles like its base material, and on the next\n * {@link LightmapRuntime.flush} the clone gets its lightmap and `rebuildMaterial`, which for a built\n * PBR scene rebuilds the whole PBR group (`lib/scene/scene-runtime-mesh-build.js`, `B`) and so\n * composes the lightmap with `uv2`. That costs one PBR group rebuild per frame that new lightmapped\n * renderers arrive in, and one frame without the lightmap.\n */\n\n/** One renderer's clone and what it was built from. */\ninterface Entry {\n readonly base: MaterialAsset;\n readonly lightmap: LightmapAsset;\n readonly texture: LiteTexture2D;\n readonly key: string;\n readonly clone: AssetHandle<MaterialAsset>;\n /** The options the next flush applies; `level` follows the record every frame. */\n options: LiteLightmapOptions;\n /** Whether the lightmap is set on the clone yet. */\n isApplied: boolean;\n /** Whether the clone was given up, so a pending flush skips it. */\n isReleased: boolean;\n}\n\n/**\n * The lightmaps of a renderer.\n *\n * @internal\n */\nexport interface LightmapRuntime {\n /** How many renderers draw with a lightmapped clone. */\n readonly count: number;\n /**\n * The material a renderer draws with: its lightmapped clone, built or refreshed as needed.\n *\n * @param owner - The renderer, as a map key.\n * @param base - The material it declares.\n * @param lightmap - The loaded lightmap.\n * @param settings - Its `lightmap` record.\n * @returns The clone's Lite material, or `base`'s while the texture is not on the GPU.\n */\n materialFor(\n owner: object,\n base: MaterialAsset,\n lightmap: LightmapAsset,\n settings: MeshRendererLightmap,\n ): LiteMaterial;\n /**\n * Drops a renderer's clone, if it has one.\n *\n * @param owner - The renderer.\n */\n release(owner: object): void;\n /** Gives the clones handed out a frame ago their lightmap; the renderer calls it after every `MeshRenderer` synced. */\n flush(): void;\n /** Drops every clone. */\n dispose(): void;\n}\n\n/**\n * Installs Lite's lightmap extension and creates the runtime.\n *\n * @param app - The app whose asset service publishes the clones.\n * @param scene - The registered render scene.\n * @returns The runtime, once the extension is registered.\n *\n * @internal\n */\nexport async function createLightmapRuntime(app: App, scene: LiteScene): Promise<LightmapRuntime> {\n await enableLightmaps();\n const entries = new Map<object, Entry>();\n /** Clones handed out this frame, and those whose meshes have drawn them plain for a frame. */\n let fresh: Entry[] = [];\n let due: Entry[] = [];\n\n const release = (owner: object): void => {\n const entry = entries.get(owner);\n if (entry !== undefined) {\n entries.delete(owner);\n entry.isReleased = true;\n entry.clone.release();\n }\n };\n\n return {\n get count(): number {\n return entries.size;\n },\n materialFor(owner, base, lightmap, settings): LiteMaterial {\n const handle = lightmap.texture;\n const texture = handle.state === \"loaded\" ? handle.value.lite.texture : null;\n if (texture === null) {\n release(owner);\n return base.lite.material;\n }\n const key = `${settings.mode}|${String(settings.gamma)}|${String(settings.uv2)}`;\n const options: LiteLightmapOptions = {\n level: settings.level,\n shadowmap: settings.mode === \"shadowmap\",\n gamma: settings.gamma,\n uv2: settings.uv2,\n };\n const current = entries.get(owner);\n if (\n current !== undefined &&\n current.base === base &&\n current.lightmap === lightmap &&\n current.texture === texture &&\n current.key === key\n ) {\n const material = current.clone.value.lite.material;\n current.options = options;\n if (current.isApplied) {\n setLightmapLevel(material, settings.level);\n }\n return material;\n }\n release(owner);\n const clone = base.clone(app);\n const entry: Entry = { base, lightmap, texture, key, clone, options, isApplied: false, isReleased: false };\n entries.set(owner, entry);\n fresh.push(entry);\n return clone.value.lite.material;\n },\n release,\n flush(): void {\n for (const entry of due) {\n if (entry.isReleased) {\n continue;\n }\n const material = entry.clone.value.lite.material;\n if (applyLightmap(material, entry.texture, entry.options)) {\n entry.isApplied = true;\n rebuildMaterialPipelines(scene, material);\n }\n }\n due = fresh;\n fresh = [];\n },\n dispose(): void {\n fresh = [];\n due = [];\n for (const owner of entries.keys()) {\n release(owner);\n }\n },\n };\n}\n"],"mappings":";;;;;;;;;;AA+CA,SAAgB,kBAAiC;CAC/C,OAAO,kBAAkB;AAC3B;;;;;;;;;;;AAYA,SAAgB,cAAc,UAA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QAAQ,YAAY,WACpB,QAAQ,QAAQ,KAChB;IACA,MAAM,WAAW,QAAQ,MAAM,MAAM,KAAK;IAC1C,QAAQ,UAAU;IAClB,IAAI,QAAQ,WACV,iBAAiB,UAAU,SAAS,KAAK;IAE3C,OAAO;GACT;GACA,QAAQ,KAAK;GACb,MAAM,QAAQ,KAAK,MAAM,GAAG;GAC5B,MAAM,QAAe;IAAE;IAAM;IAAU;IAAS;IAAK;IAAO;IAAS,WAAW;IAAO,YAAY;GAAM;GACzG,QAAQ,IAAI,OAAO,KAAK;GACxB,MAAM,KAAK,KAAK;GAChB,OAAO,MAAM,MAAM,KAAK;EAC1B;EACA;EACA,QAAc;GACZ,KAAK,MAAM,SAAS,KAAK;IACvB,IAAI,MAAM,YACR;IAEF,MAAM,WAAW,MAAM,MAAM,MAAM,KAAK;IACxC,IAAI,cAAc,UAAU,MAAM,SAAS,MAAM,OAAO,GAAG;KACzD,MAAM,YAAY;KAClB,yBAAyB,OAAO,QAAQ;IAC1C;GACF;GACA,MAAM;GACN,QAAQ,CAAC;EACX;EACA,UAAgB;GACd,QAAQ,CAAC;GACT,MAAM,CAAC;GACP,KAAK,MAAM,SAAS,QAAQ,KAAK,GAC/B,QAAQ,KAAK;EAEjB;CACF;AACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as assertNever, o as CoreErrorCode, t as IgnifxError } from "./ignifx-error-
|
|
1
|
+
import { n as assertNever, o as CoreErrorCode, t as IgnifxError } from "./ignifx-error-DwIZKxA2.js";
|
|
2
2
|
import { u as SHADER_UNIFORM_TYPES } from "./shader-declaration-5q__jycG.js";
|
|
3
3
|
//#region src/render/material-plugin.ts
|
|
4
4
|
/**
|
|
@@ -281,4 +281,4 @@ function assertUniformType(plugin, binding, type) {
|
|
|
281
281
|
//#endregion
|
|
282
282
|
export { defineMaterialPlugin as a, MATERIAL_PLUGIN_SAMPLER_BUDGET as i, MATERIAL_PLUGIN_DEFAULT_PRIORITY as n, isLiteMaterialPluginPoint as o, MATERIAL_PLUGIN_RESERVED_NAMES as r, uniformComponentCount as s, LITE_MATERIAL_PLUGIN_POINTS as t };
|
|
283
283
|
|
|
284
|
-
//# sourceMappingURL=material-plugin-
|
|
284
|
+
//# sourceMappingURL=material-plugin-DapJNj04.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"material-plugin-CiAmriQ_.js","names":[],"sources":["../src/render/material-plugin.ts"],"sourcesContent":["import { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { assertNever, IgnifxError } from \"../errors/ignifx-error.js\";\nimport { SHADER_UNIFORM_TYPES } from \"./shader-declaration.js\";\nimport type { ShaderTextureDeclaration, ShaderUniformDeclaration, ShaderUniformType } from \"./shader-declaration.js\";\n\n/**\n * The raw Babylon Lite material-plugin points, as a `@beta` escape hatch\n * (`docs/plan/2026-09-terrain-particles-shaders.md` §3.2, ADR-0024).\n *\n * `@beta` because the meaning of each point is whatever the surrounding Lite template declares at\n * that line; ignifx's stable contract is the three hooks of `./surface-shader.ts`. Four rules read\n * out of `@babylonjs/lite@1.27.0`'s `lib/` on 2026-09-08:\n *\n * - Plugin uniforms and samplers are **fragment-stage only** on both families\n * (`lib/material/plugin/plugin-bridge-shared.js` 99), and there is no vertex helper-function\n * channel, so vertex code may read only attributes, `mesh.world` and the scene block, and must be\n * statements rather than functions.\n * - `CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION` is injected **twice** — Lite maps it to the two\n * adjacent PBR slots `AI` and `NI` — so its code must be idempotent or guard itself with a flag\n * set at an earlier point, and must declare nothing at statement level.\n * - Only PBR carries `CUSTOM_FRAGMENT_UPDATE_DIFFUSE` after `CUSTOM_FRAGMENT_UPDATE_ALPHA`;\n * Standard's template orders them the other way and has no `AI`/`NI`/`MF` slots.\n * - `roughness` and `metallic` are `let` in the PBR template and cannot be written.\n */\n\n/**\n * The Babylon Lite injection points a {@link MaterialPluginDefinition} may fill in.\n *\n * @remarks\n * The names are Lite's own (`MaterialPluginPoint`, `index.d.ts` 7084) and are taught verbatim,\n * because a plugin's code is written against the template around the point.\n *\n * @beta\n */\nexport const LITE_MATERIAL_PLUGIN_POINTS = [\n \"CUSTOM_FRAGMENT_DEFINITIONS\",\n \"CUSTOM_FRAGMENT_MAIN_BEGIN\",\n \"CUSTOM_FRAGMENT_UPDATE_ALPHA\",\n \"CUSTOM_FRAGMENT_UPDATE_DIFFUSE\",\n \"CUSTOM_FRAGMENT_BEFORE_LIGHTS\",\n \"CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION\",\n \"CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\",\n \"CUSTOM_VERTEX_MAIN_BEGIN\",\n \"CUSTOM_VERTEX_UPDATE_WORLDPOS\",\n \"CUSTOM_VERTEX_MAIN_END\",\n] as const;\n\n/**\n * One of Babylon Lite's ten material-plugin injection points.\n *\n * @beta\n */\nexport type LiteMaterialPluginPoint = (typeof LITE_MATERIAL_PLUGIN_POINTS)[number];\n\n/**\n * The default priority Babylon Lite gives a plugin with none (`index.d.ts` 7057).\n *\n * @beta\n */\nexport const MATERIAL_PLUGIN_DEFAULT_PRIORITY = 500;\n\n/**\n * How many `texture`/`sampler` pairs one material's plugins may declare together.\n *\n * @remarks\n * Measured on a device on 2026-09-08 (spike S0.2): a fully textured PBR material — base colour,\n * normal, ORM, emissive — with image-based lighting and one PCF shadow light already binds seven\n * textures and seven samplers of the sixteen per stage that every WebGPU implementation guarantees,\n * SwiftShader included, and Lite requests no higher `requiredLimits`. Nine is what is left, and it\n * drops to eight with a second shadow light and seven with a lightmap, so a material that means to\n * be portable should stay well under the cap.\n *\n * @beta\n */\nexport const MATERIAL_PLUGIN_SAMPLER_BUDGET = 9;\n\n/**\n * The WGSL names the PBR and Standard templates already own, which a plugin may not reuse for a\n * uniform field or a sampler.\n *\n * @remarks\n * A plugin's fields land in the host's own uniform block and its samplers in the host's own bind\n * group, so a collision is a duplicate WGSL declaration and the whole material stops compiling with\n * a message that names neither the plugin nor the field. Refusing at attach time is the difference\n * between a sentence and a shader dump. Read from `pbr-template.js` `_baseMaterialUboFields` and\n * `_baseBindings`, and `standard-template.js` `materialStruct` and `_baseBindings`.\n *\n * @beta\n */\nexport const MATERIAL_PLUGIN_RESERVED_NAMES: readonly string[] = Object.freeze([\n // Blocks and entry points the templates declare.\n \"material\",\n \"mesh\",\n \"scene\",\n \"lights\",\n \"pluginUbo\",\n \"shadowParams\",\n \"main\",\n // PBR material uniform fields.\n \"environmentIntensity\",\n \"directIntensity\",\n \"reflectance\",\n \"materialAlpha\",\n \"baseColorFactor\",\n \"metallicFactor\",\n \"roughnessFactor\",\n \"normalScale\",\n \"lightFalloffMode\",\n \"anisotropyParams\",\n // PBR samplers.\n \"baseColorTexture\",\n \"baseColorSampler\",\n \"normalTexture\",\n \"normalSampler_\",\n \"ormTexture\",\n \"ormSampler\",\n \"emissiveTexture\",\n \"emissiveSampler\",\n \"specGlossTexture\",\n \"specGlossSampler\",\n // Standard samplers (`standard-template.js` uses two-letter names).\n \"dT\",\n \"dS\",\n \"mat\",\n \"up\",\n]);\n\n/**\n * What a raw material plugin declares: a name, the values and textures it wants beside the host\n * material's own, and the WGSL it injects.\n *\n * @beta\n */\nexport interface MaterialPluginDefinition {\n /** The plugin's identity. It is part of Lite's pipeline cache key, so it must be stable. */\n readonly name: string;\n /** Lower runs first; Lite's own default is {@link MATERIAL_PLUGIN_DEFAULT_PRIORITY}. */\n readonly priority: number;\n /** The uniform fields appended to the host material's uniform block. Fragment stage only. */\n readonly uniforms: readonly ShaderUniformDeclaration[];\n /** The `texture`/`sampler` pairs added to the host material's bind group. Fragment stage only. */\n readonly textures: readonly ShaderTextureDeclaration[];\n /** The WGSL to inject, by point. Vertex points take statements; there are no vertex helpers. */\n readonly code: Readonly<Partial<Record<LiteMaterialPluginPoint, string>>>;\n}\n\n/**\n * The properties {@link defineMaterialPlugin} accepts; everything but `name` and `code` has a\n * default.\n *\n * @beta\n */\nexport interface MaterialPluginDefinitionInit {\n /** The plugin's identity. */\n readonly name: string;\n /** Lower runs first. Defaults to {@link MATERIAL_PLUGIN_DEFAULT_PRIORITY}. */\n readonly priority?: number;\n /** The uniform fields. Defaults to none. */\n readonly uniforms?: readonly ShaderUniformDeclaration[];\n /** The samplers. Defaults to none. */\n readonly textures?: readonly ShaderTextureDeclaration[];\n /** The WGSL to inject, by point. */\n readonly code: Readonly<Partial<Record<LiteMaterialPluginPoint, string>>>;\n}\n\n/** Matches a WGSL identifier. */\nconst IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/** Matches a legal plugin name: an identifier, optionally with `.`, `:`, or `-` inside it. */\nconst PLUGIN_NAME = /^[A-Za-z_][A-Za-z0-9_]*(?:[.:-][A-Za-z0-9_]+)*$/;\n\n/**\n * Validates a raw material-plugin declaration and fills in its defaults.\n *\n * @remarks\n * Nothing here reaches a device: the result is plain data that `attachSurfaceShaders` and\n * `attachMaterialPlugin` turn into a Lite plugin. The checks are the ones whose failure would\n * otherwise surface as a WGSL compile error with no mention of the plugin — an empty `code`, a\n * duplicate or reserved binding name, a name that is not a WGSL identifier, an unknown injection\n * point, or more samplers than {@link MATERIAL_PLUGIN_SAMPLER_BUDGET}.\n *\n * The **surface-shader compiler produces one of these**, so a bug in this validation is a bug in\n * every surface shader too, which is why it lives here rather than inside the compiler.\n *\n * @param definition - The declaration.\n * @returns The same declaration with `priority`, `uniforms`, and `textures` filled in.\n * @throws IgnifxError with code `IGX-0723` when `code` fills in no point, `IGX-0712` when a name is\n * not a legal, unique, unreserved WGSL identifier or a point name is unknown, or `IGX-0726` when the\n * plugin alone exceeds the sampler budget.\n *\n * @example\n * ```ts\n * const tint = defineMaterialPlugin({\n * name: \"tint\",\n * code: { CUSTOM_FRAGMENT_UPDATE_ALPHA: \"baseColor = baseColor * vec3<f32>(1.0, 0.5, 0.5);\" },\n * });\n * ```\n *\n * @beta\n */\nexport function defineMaterialPlugin(definition: MaterialPluginDefinitionInit): MaterialPluginDefinition {\n const name = definition.name;\n if (!PLUGIN_NAME.test(name)) {\n throw new IgnifxError(\n CoreErrorCode.unknownShaderBinding,\n `${JSON.stringify(name)} is not a legal material-plugin name.`,\n {\n context: { plugin: name, name },\n hint: \"Start with a letter or underscore; letters, digits, underscores, and inner . : - follow.\",\n },\n );\n }\n const points = Object.keys(definition.code);\n let filled = 0;\n for (const point of points) {\n if (!isLiteMaterialPluginPoint(point)) {\n throw new IgnifxError(CoreErrorCode.unknownShaderBinding, `${name} declares no Lite point named ${point}.`, {\n context: { plugin: name, name: point, point },\n hint: `The ten points are ${LITE_MATERIAL_PLUGIN_POINTS.join(\", \")}.`,\n });\n }\n if ((definition.code[point] ?? \"\").trim().length > 0) {\n filled += 1;\n }\n }\n if (filled === 0) {\n throw new IgnifxError(CoreErrorCode.surfaceHookMissing, `${name} injects no WGSL at any Lite point.`, {\n context: { plugin: name, name },\n hint: \"Fill in at least one of the ten points, or do not attach the plugin.\",\n });\n }\n const uniforms = definition.uniforms ?? [];\n const textures = definition.textures ?? [];\n const seen = new Set<string>();\n for (const uniform of uniforms) {\n assertBindingName(name, uniform.name, seen);\n assertUniformType(name, uniform.name, uniform.type);\n }\n for (const texture of textures) {\n assertBindingName(name, texture.name, seen);\n assertBindingName(name, `${texture.name}Sampler`, seen);\n }\n if (textures.length > MATERIAL_PLUGIN_SAMPLER_BUDGET) {\n throw new IgnifxError(\n CoreErrorCode.surfaceSamplerBudgetExceeded,\n `${name} declares ${String(textures.length)} samplers; a material's plugins may declare ${String(MATERIAL_PLUGIN_SAMPLER_BUDGET)} together.`,\n {\n context: { plugin: name, samplers: textures.length, budget: MATERIAL_PLUGIN_SAMPLER_BUDGET },\n hint: \"Pack the maps into fewer textures — an RGBA control map rather than four masks.\",\n },\n );\n }\n return {\n name,\n priority: definition.priority ?? MATERIAL_PLUGIN_DEFAULT_PRIORITY,\n uniforms,\n textures,\n code: definition.code,\n };\n}\n\n/**\n * Whether a string is one of Lite's ten injection points.\n *\n * @param value - The candidate.\n * @returns `true` when Lite accepts it.\n *\n * @beta\n */\nexport function isLiteMaterialPluginPoint(value: string): value is LiteMaterialPluginPoint {\n for (const point of LITE_MATERIAL_PLUGIN_POINTS) {\n if (point === value) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * How many floats one uniform of a declared type occupies on the CPU side.\n *\n * @param type - The declared WGSL type.\n * @returns The component count: 1, 2, 3, 4, or 16.\n *\n * @internal\n */\nexport function uniformComponentCount(type: ShaderUniformType): number {\n switch (type) {\n case \"vec2<f32>\": {\n return 2;\n }\n case \"vec3<f32>\": {\n return 3;\n }\n case \"vec4<f32>\": {\n return 4;\n }\n case \"mat4x4<f32>\": {\n return 16;\n }\n case \"f32\":\n case \"u32\":\n case \"i32\": {\n return 1;\n }\n default: {\n return assertNever(type, \"shader uniform type\");\n }\n }\n}\n\n/**\n * Refuses a binding name that is not a unique, unreserved WGSL identifier.\n *\n * @param plugin - The plugin's name, for the message.\n * @param binding - The candidate name.\n * @param seen - The names already taken by this plugin; the accepted name is added.\n * @throws IgnifxError with code `IGX-0712`.\n */\nfunction assertBindingName(plugin: string, binding: string, seen: Set<string>): void {\n if (!IDENTIFIER.test(binding)) {\n throw new IgnifxError(\n CoreErrorCode.unknownShaderBinding,\n `${plugin} declares ${JSON.stringify(binding)}, which is not a WGSL identifier.`,\n { context: { plugin, name: binding }, hint: \"Use letters, digits, and underscores, starting with a letter.\" },\n );\n }\n if (MATERIAL_PLUGIN_RESERVED_NAMES.includes(binding)) {\n throw new IgnifxError(\n CoreErrorCode.unknownShaderBinding,\n `${plugin} declares ${binding}, which Babylon Lite's own PBR or Standard shader already owns.`,\n { context: { plugin, name: binding }, hint: \"Rename it; a plugin shares the host material's WGSL namespace.\" },\n );\n }\n if (seen.has(binding)) {\n throw new IgnifxError(CoreErrorCode.unknownShaderBinding, `${plugin} declares ${binding} twice.`, {\n context: { plugin, name: binding },\n hint: \"Every uniform and texture of one plugin needs its own name.\",\n });\n }\n seen.add(binding);\n}\n\n/**\n * Refuses a uniform type Lite's plugin bridge cannot carry.\n *\n * @param plugin - The plugin's name, for the message.\n * @param binding - The uniform's name.\n * @param type - The declared type.\n * @throws IgnifxError with code `IGX-0712`.\n */\nfunction assertUniformType(plugin: string, binding: string, type: ShaderUniformType): void {\n if (!SHADER_UNIFORM_TYPES.includes(type)) {\n throw new IgnifxError(CoreErrorCode.unknownShaderBinding, `${plugin}.${binding} declares the type ${type}.`, {\n context: { plugin, name: binding, type },\n hint: `The plugin uniform types are ${SHADER_UNIFORM_TYPES.join(\", \")}.`,\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,MAAa,8BAA8B;CACzC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;AAcA,MAAa,mCAAmC;;;;;;;;;;;;;;AAehD,MAAa,iCAAiC;;;;;;;;;;;;;;AAe9C,MAAa,iCAAoD,OAAO,OAAO;CAE7E;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;CACA;CACA;AACF,CAAC;;AAyCD,MAAM,aAAa;;AAGnB,MAAM,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BpB,SAAgB,qBAAqB,YAAoE;CACvG,MAAM,OAAO,WAAW;CACxB,IAAI,CAAC,YAAY,KAAK,IAAI,GACxB,MAAM,IAAI,YACR,cAAc,sBACd,GAAG,KAAK,UAAU,IAAI,EAAE,wCACxB;EACE,SAAS;GAAE,QAAQ;GAAM;EAAK;EAC9B,MAAM;CACR,CACF;CAEF,MAAM,SAAS,OAAO,KAAK,WAAW,IAAI;CAC1C,IAAI,SAAS;CACb,KAAK,MAAM,SAAS,QAAQ;EAC1B,IAAI,CAAC,0BAA0B,KAAK,GAClC,MAAM,IAAI,YAAY,cAAc,sBAAsB,GAAG,KAAK,gCAAgC,MAA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KAAK,eACH,OAAO;EAET,KAAK;EACL,KAAK;EACL,KAAK,OACH,OAAO;EAET,SACE,OAAO,YAAY,MAAM,qBAAqB;CAElD;AACF;;;;;;;;;AAUA,SAAS,kBAAkB,QAAgB,SAAiB,MAAyB;CACnF,IAAI,CAAC,WAAW,KAAK,OAAO,GAC1B,MAAM,IAAI,YACR,cAAc,sBACd,GAAG,OAAO,YAAY,KAAK,UAAU,OAAO,EAAE,oCAC9C;EAAE,SAAS;GAAE;GAAQ,MAAM;EAAQ;EAAG,MAAM;CAAgE,CAC9G;CAEF,IAAI,+BAA+B,SAAS,OAAO,GACjD,MAAM,IAAI,YACR,cAAc,sBACd,GAAG,OAAO,YAAY,QAAQ,kEAC9B;EAAE,SAAS;GAAE;GAAQ,MAAM;EAAQ;EAAG,MAAM;CAAiE,CAC/G;CAEF,IAAI,KAAK,IAAI,OAAO,GAClB,MAAM,IAAI,YAAY,cAAc,sBAAsB,GAAG,OAAO,YAAY,QAAQ,UAAU;EAChG,SAAS;GAAE;GAAQ,MAAM;EAAQ;EACjC,MAAM;CACR,CAAC;CAEH,KAAK,IAAI,OAAO;AAClB;;;;;;;;;AAUA,SAAS,kBAAkB,QAAgB,SAAiB,MAA+B;CACzF,IAAI,CAAC,qBAAqB,SAAS,IAAI,GACrC,MAAM,IAAI,YAAY,cAAc,sBAAsB,GAAG,OAAO,GAAG,QAAQ,qBAAqB,KAAK,IAAI;EAC3G,SAAS;GAAE;GAAQ,MAAM;GAAS;EAAK;EACvC,MAAM,gCAAgC,qBAAqB,KAAK,IAAI,EAAE;CACxE,CAAC;AAEL"}
|
|
1
|
+
{"version":3,"file":"material-plugin-DapJNj04.js","names":[],"sources":["../src/render/material-plugin.ts"],"sourcesContent":["import { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { assertNever, IgnifxError } from \"../errors/ignifx-error.js\";\nimport { SHADER_UNIFORM_TYPES } from \"./shader-declaration.js\";\nimport type { ShaderTextureDeclaration, ShaderUniformDeclaration, ShaderUniformType } from \"./shader-declaration.js\";\n\n/**\n * The raw Babylon Lite material-plugin points, as a `@beta` escape hatch\n * (`docs/plan/2026-09-terrain-particles-shaders.md` §3.2, ADR-0024).\n *\n * `@beta` because the meaning of each point is whatever the surrounding Lite template declares at\n * that line; ignifx's stable contract is the three hooks of `./surface-shader.ts`. Four rules read\n * out of `@babylonjs/lite@1.27.0`'s `lib/` on 2026-09-08:\n *\n * - Plugin uniforms and samplers are **fragment-stage only** on both families\n * (`lib/material/plugin/plugin-bridge-shared.js` 99), and there is no vertex helper-function\n * channel, so vertex code may read only attributes, `mesh.world` and the scene block, and must be\n * statements rather than functions.\n * - `CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION` is injected **twice** — Lite maps it to the two\n * adjacent PBR slots `AI` and `NI` — so its code must be idempotent or guard itself with a flag\n * set at an earlier point, and must declare nothing at statement level.\n * - Only PBR carries `CUSTOM_FRAGMENT_UPDATE_DIFFUSE` after `CUSTOM_FRAGMENT_UPDATE_ALPHA`;\n * Standard's template orders them the other way and has no `AI`/`NI`/`MF` slots.\n * - `roughness` and `metallic` are `let` in the PBR template and cannot be written.\n */\n\n/**\n * The Babylon Lite injection points a {@link MaterialPluginDefinition} may fill in.\n *\n * @remarks\n * The names are Lite's own (`MaterialPluginPoint`, `index.d.ts` 7084) and are taught verbatim,\n * because a plugin's code is written against the template around the point.\n *\n * @beta\n */\nexport const LITE_MATERIAL_PLUGIN_POINTS = [\n \"CUSTOM_FRAGMENT_DEFINITIONS\",\n \"CUSTOM_FRAGMENT_MAIN_BEGIN\",\n \"CUSTOM_FRAGMENT_UPDATE_ALPHA\",\n \"CUSTOM_FRAGMENT_UPDATE_DIFFUSE\",\n \"CUSTOM_FRAGMENT_BEFORE_LIGHTS\",\n \"CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION\",\n \"CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\",\n \"CUSTOM_VERTEX_MAIN_BEGIN\",\n \"CUSTOM_VERTEX_UPDATE_WORLDPOS\",\n \"CUSTOM_VERTEX_MAIN_END\",\n] as const;\n\n/**\n * One of Babylon Lite's ten material-plugin injection points.\n *\n * @beta\n */\nexport type LiteMaterialPluginPoint = (typeof LITE_MATERIAL_PLUGIN_POINTS)[number];\n\n/**\n * The default priority Babylon Lite gives a plugin with none (`index.d.ts` 7057).\n *\n * @beta\n */\nexport const MATERIAL_PLUGIN_DEFAULT_PRIORITY = 500;\n\n/**\n * How many `texture`/`sampler` pairs one material's plugins may declare together.\n *\n * @remarks\n * Measured on a device on 2026-09-08 (spike S0.2): a fully textured PBR material — base colour,\n * normal, ORM, emissive — with image-based lighting and one PCF shadow light already binds seven\n * textures and seven samplers of the sixteen per stage that every WebGPU implementation guarantees,\n * SwiftShader included, and Lite requests no higher `requiredLimits`. Nine is what is left, and it\n * drops to eight with a second shadow light and seven with a lightmap, so a material that means to\n * be portable should stay well under the cap.\n *\n * @beta\n */\nexport const MATERIAL_PLUGIN_SAMPLER_BUDGET = 9;\n\n/**\n * The WGSL names the PBR and Standard templates already own, which a plugin may not reuse for a\n * uniform field or a sampler.\n *\n * @remarks\n * A plugin's fields land in the host's own uniform block and its samplers in the host's own bind\n * group, so a collision is a duplicate WGSL declaration and the whole material stops compiling with\n * a message that names neither the plugin nor the field. Refusing at attach time is the difference\n * between a sentence and a shader dump. Read from `pbr-template.js` `_baseMaterialUboFields` and\n * `_baseBindings`, and `standard-template.js` `materialStruct` and `_baseBindings`.\n *\n * @beta\n */\nexport const MATERIAL_PLUGIN_RESERVED_NAMES: readonly string[] = Object.freeze([\n // Blocks and entry points the templates declare.\n \"material\",\n \"mesh\",\n \"scene\",\n \"lights\",\n \"pluginUbo\",\n \"shadowParams\",\n \"main\",\n // PBR material uniform fields.\n \"environmentIntensity\",\n \"directIntensity\",\n \"reflectance\",\n \"materialAlpha\",\n \"baseColorFactor\",\n \"metallicFactor\",\n \"roughnessFactor\",\n \"normalScale\",\n \"lightFalloffMode\",\n \"anisotropyParams\",\n // PBR samplers.\n \"baseColorTexture\",\n \"baseColorSampler\",\n \"normalTexture\",\n \"normalSampler_\",\n \"ormTexture\",\n \"ormSampler\",\n \"emissiveTexture\",\n \"emissiveSampler\",\n \"specGlossTexture\",\n \"specGlossSampler\",\n // Standard samplers (`standard-template.js` uses two-letter names).\n \"dT\",\n \"dS\",\n \"mat\",\n \"up\",\n]);\n\n/**\n * What a raw material plugin declares: a name, the values and textures it wants beside the host\n * material's own, and the WGSL it injects.\n *\n * @beta\n */\nexport interface MaterialPluginDefinition {\n /** The plugin's identity. It is part of Lite's pipeline cache key, so it must be stable. */\n readonly name: string;\n /** Lower runs first; Lite's own default is {@link MATERIAL_PLUGIN_DEFAULT_PRIORITY}. */\n readonly priority: number;\n /** The uniform fields appended to the host material's uniform block. Fragment stage only. */\n readonly uniforms: readonly ShaderUniformDeclaration[];\n /** The `texture`/`sampler` pairs added to the host material's bind group. Fragment stage only. */\n readonly textures: readonly ShaderTextureDeclaration[];\n /** The WGSL to inject, by point. Vertex points take statements; there are no vertex helpers. */\n readonly code: Readonly<Partial<Record<LiteMaterialPluginPoint, string>>>;\n}\n\n/**\n * The properties {@link defineMaterialPlugin} accepts; everything but `name` and `code` has a\n * default.\n *\n * @beta\n */\nexport interface MaterialPluginDefinitionInit {\n /** The plugin's identity. */\n readonly name: string;\n /** Lower runs first. Defaults to {@link MATERIAL_PLUGIN_DEFAULT_PRIORITY}. */\n readonly priority?: number;\n /** The uniform fields. Defaults to none. */\n readonly uniforms?: readonly ShaderUniformDeclaration[];\n /** The samplers. Defaults to none. */\n readonly textures?: readonly ShaderTextureDeclaration[];\n /** The WGSL to inject, by point. */\n readonly code: Readonly<Partial<Record<LiteMaterialPluginPoint, string>>>;\n}\n\n/** Matches a WGSL identifier. */\nconst IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/** Matches a legal plugin name: an identifier, optionally with `.`, `:`, or `-` inside it. */\nconst PLUGIN_NAME = /^[A-Za-z_][A-Za-z0-9_]*(?:[.:-][A-Za-z0-9_]+)*$/;\n\n/**\n * Validates a raw material-plugin declaration and fills in its defaults.\n *\n * @remarks\n * Nothing here reaches a device: the result is plain data that `attachSurfaceShaders` and\n * `attachMaterialPlugin` turn into a Lite plugin. The checks are the ones whose failure would\n * otherwise surface as a WGSL compile error with no mention of the plugin — an empty `code`, a\n * duplicate or reserved binding name, a name that is not a WGSL identifier, an unknown injection\n * point, or more samplers than {@link MATERIAL_PLUGIN_SAMPLER_BUDGET}.\n *\n * The **surface-shader compiler produces one of these**, so a bug in this validation is a bug in\n * every surface shader too, which is why it lives here rather than inside the compiler.\n *\n * @param definition - The declaration.\n * @returns The same declaration with `priority`, `uniforms`, and `textures` filled in.\n * @throws IgnifxError with code `IGX-0723` when `code` fills in no point, `IGX-0712` when a name is\n * not a legal, unique, unreserved WGSL identifier or a point name is unknown, or `IGX-0726` when the\n * plugin alone exceeds the sampler budget.\n *\n * @example\n * ```ts\n * const tint = defineMaterialPlugin({\n * name: \"tint\",\n * code: { CUSTOM_FRAGMENT_UPDATE_ALPHA: \"baseColor = baseColor * vec3<f32>(1.0, 0.5, 0.5);\" },\n * });\n * ```\n *\n * @beta\n */\nexport function defineMaterialPlugin(definition: MaterialPluginDefinitionInit): MaterialPluginDefinition {\n const name = definition.name;\n if (!PLUGIN_NAME.test(name)) {\n throw new IgnifxError(\n CoreErrorCode.unknownShaderBinding,\n `${JSON.stringify(name)} is not a legal material-plugin name.`,\n {\n context: { plugin: name, name },\n hint: \"Start with a letter or underscore; letters, digits, underscores, and inner . : - follow.\",\n },\n );\n }\n const points = Object.keys(definition.code);\n let filled = 0;\n for (const point of points) {\n if (!isLiteMaterialPluginPoint(point)) {\n throw new IgnifxError(CoreErrorCode.unknownShaderBinding, `${name} declares no Lite point named ${point}.`, {\n context: { plugin: name, name: point, point },\n hint: `The ten points are ${LITE_MATERIAL_PLUGIN_POINTS.join(\", \")}.`,\n });\n }\n if ((definition.code[point] ?? \"\").trim().length > 0) {\n filled += 1;\n }\n }\n if (filled === 0) {\n throw new IgnifxError(CoreErrorCode.surfaceHookMissing, `${name} injects no WGSL at any Lite point.`, {\n context: { plugin: name, name },\n hint: \"Fill in at least one of the ten points, or do not attach the plugin.\",\n });\n }\n const uniforms = definition.uniforms ?? [];\n const textures = definition.textures ?? [];\n const seen = new Set<string>();\n for (const uniform of uniforms) {\n assertBindingName(name, uniform.name, seen);\n assertUniformType(name, uniform.name, uniform.type);\n }\n for (const texture of textures) {\n assertBindingName(name, texture.name, seen);\n assertBindingName(name, `${texture.name}Sampler`, seen);\n }\n if (textures.length > MATERIAL_PLUGIN_SAMPLER_BUDGET) {\n throw new IgnifxError(\n CoreErrorCode.surfaceSamplerBudgetExceeded,\n `${name} declares ${String(textures.length)} samplers; a material's plugins may declare ${String(MATERIAL_PLUGIN_SAMPLER_BUDGET)} together.`,\n {\n context: { plugin: name, samplers: textures.length, budget: MATERIAL_PLUGIN_SAMPLER_BUDGET },\n hint: \"Pack the maps into fewer textures — an RGBA control map rather than four masks.\",\n },\n );\n }\n return {\n name,\n priority: definition.priority ?? MATERIAL_PLUGIN_DEFAULT_PRIORITY,\n uniforms,\n textures,\n code: definition.code,\n };\n}\n\n/**\n * Whether a string is one of Lite's ten injection points.\n *\n * @param value - The candidate.\n * @returns `true` when Lite accepts it.\n *\n * @beta\n */\nexport function isLiteMaterialPluginPoint(value: string): value is LiteMaterialPluginPoint {\n for (const point of LITE_MATERIAL_PLUGIN_POINTS) {\n if (point === value) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * How many floats one uniform of a declared type occupies on the CPU side.\n *\n * @param type - The declared WGSL type.\n * @returns The component count: 1, 2, 3, 4, or 16.\n *\n * @internal\n */\nexport function uniformComponentCount(type: ShaderUniformType): number {\n switch (type) {\n case \"vec2<f32>\": {\n return 2;\n }\n case \"vec3<f32>\": {\n return 3;\n }\n case \"vec4<f32>\": {\n return 4;\n }\n case \"mat4x4<f32>\": {\n return 16;\n }\n case \"f32\":\n case \"u32\":\n case \"i32\": {\n return 1;\n }\n default: {\n return assertNever(type, \"shader uniform type\");\n }\n }\n}\n\n/**\n * Refuses a binding name that is not a unique, unreserved WGSL identifier.\n *\n * @param plugin - The plugin's name, for the message.\n * @param binding - The candidate name.\n * @param seen - The names already taken by this plugin; the accepted name is added.\n * @throws IgnifxError with code `IGX-0712`.\n */\nfunction assertBindingName(plugin: string, binding: string, seen: Set<string>): void {\n if (!IDENTIFIER.test(binding)) {\n throw new IgnifxError(\n CoreErrorCode.unknownShaderBinding,\n `${plugin} declares ${JSON.stringify(binding)}, which is not a WGSL identifier.`,\n { context: { plugin, name: binding }, hint: \"Use letters, digits, and underscores, starting with a letter.\" },\n );\n }\n if (MATERIAL_PLUGIN_RESERVED_NAMES.includes(binding)) {\n throw new IgnifxError(\n CoreErrorCode.unknownShaderBinding,\n `${plugin} declares ${binding}, which Babylon Lite's own PBR or Standard shader already owns.`,\n { context: { plugin, name: binding }, hint: \"Rename it; a plugin shares the host material's WGSL namespace.\" },\n );\n }\n if (seen.has(binding)) {\n throw new IgnifxError(CoreErrorCode.unknownShaderBinding, `${plugin} declares ${binding} twice.`, {\n context: { plugin, name: binding },\n hint: \"Every uniform and texture of one plugin needs its own name.\",\n });\n }\n seen.add(binding);\n}\n\n/**\n * Refuses a uniform type Lite's plugin bridge cannot carry.\n *\n * @param plugin - The plugin's name, for the message.\n * @param binding - The uniform's name.\n * @param type - The declared type.\n * @throws IgnifxError with code `IGX-0712`.\n */\nfunction assertUniformType(plugin: string, binding: string, type: ShaderUniformType): void {\n if (!SHADER_UNIFORM_TYPES.includes(type)) {\n throw new IgnifxError(CoreErrorCode.unknownShaderBinding, `${plugin}.${binding} declares the type ${type}.`, {\n context: { plugin, name: binding, type },\n hint: `The plugin uniform types are ${SHADER_UNIFORM_TYPES.join(\", \")}.`,\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,MAAa,8BAA8B;CACzC;CACA;CACA;CACA;CACA;CACA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C9B;EAAE,SAAS;GAAE;GAAQ,MAAM;EAAQ;EAAG,MAAM;CAAiE,CAC/G;CAEF,IAAI,KAAK,IAAI,OAAO,GAClB,MAAM,IAAI,YAAY,cAAc,sBAAsB,GAAG,OAAO,YAAY,QAAQ,UAAU;EAChG,SAAS;GAAE;GAAQ,MAAM;EAAQ;EACjC,MAAM;CACR,CAAC;CAEH,KAAK,IAAI,OAAO;AAClB;;;;;;;;;AAUA,SAAS,kBAAkB,QAAgB,SAAiB,MAA+B;CACzF,IAAI,CAAC,qBAAqB,SAAS,IAAI,GACrC,MAAM,IAAI,YAAY,cAAc,sBAAsB,GAAG,OAAO,GAAG,QAAQ,qBAAqB,KAAK,IAAI;EAC3G,SAAS;GAAE;GAAQ,MAAM;GAAS;EAAK;EACvC,MAAM,gCAAgC,qBAAqB,KAAK,IAAI,EAAE;CACxE,CAAC;AAEL"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { F as asJsonObject, I as setOwnJsonProperty } from "./prefab-overrides-DRP2DcnC.js";
|
|
2
2
|
//#region src/render/post-effect.ts
|
|
3
3
|
/**
|
|
4
4
|
* What a `PostProcessStack` needs to describe a custom `// @ignifx post` effect: its settings record,
|
|
@@ -126,4 +126,4 @@ function postEffectValuesCodec() {
|
|
|
126
126
|
//#endregion
|
|
127
127
|
export { postEffectValuesCodec as a, declaredTextureBinding as i, POST_EFFECT_FUNCTION as n, customEffect as r, POST_EFFECT_BUILTIN_UNIFORMS as t };
|
|
128
128
|
|
|
129
|
-
//# sourceMappingURL=post-effect-
|
|
129
|
+
//# sourceMappingURL=post-effect-CaiqDlhW.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"post-effect-
|
|
1
|
+
{"version":3,"file":"post-effect-CaiqDlhW.js","names":[],"sources":["../src/render/post-effect.ts"],"sourcesContent":["import { setOwnJsonProperty } from \"../schema/json.js\";\nimport { asJsonObject } from \"../serialization/json-view.js\";\nimport type { ShaderAsset } from \"./shader-asset.js\";\nimport type { ShaderTextureDeclaration, ShaderUniformType } from \"./shader-declaration.js\";\nimport type { TextureAsset } from \"./texture-asset.js\";\nimport type { AssetHandle } from \"../assets/types.js\";\nimport type { JsonValue } from \"../schema/json.js\";\nimport type { CustomFieldCodec } from \"../schema/types.js\";\n\n/**\n * What a `PostProcessStack` needs to describe a custom `// @ignifx post` effect: its settings record,\n * the uniforms every effect gets for free, and the schema codec its `values` round-trip through\n * (`docs/plan/2026-09-terrain-particles-shaders.md` §3.3).\n *\n * `PostProcessStack` is in every game's static graph, so the WGSL generator and the uniform layout\n * live in `./post-effect-compiler.ts`, which the `.wgsl` loader pulls in only for a `post` file.\n */\n\n/**\n * The name a `// @ignifx post` file gives its fragment function.\n *\n * @public\n */\nexport const POST_EFFECT_FUNCTION = \"mainFragment\";\n\n/**\n * The uniforms every post effect's `shaderUniforms` block carries before the file's own, in this\n * order.\n *\n * @remarks\n * `screenSize` is in backing-store pixels — `canvas.width`/`canvas.height` — like everything else\n * the engine reports (`docs/architecture/07-rendering.md` §3). The three clocks are the app's, so\n * `time` freezes under `app.pause()` and `unscaledTime` does not.\n *\n * @public\n */\nexport const POST_EFFECT_BUILTIN_UNIFORMS: readonly { readonly name: string; readonly type: ShaderUniformType }[] =\n Object.freeze([\n { name: \"screenSize\", type: \"vec2<f32>\" },\n { name: \"time\", type: \"f32\" },\n { name: \"unscaledTime\", type: \"f32\" },\n { name: \"deltaTime\", type: \"f32\" },\n ]);\n\n/**\n * One custom effect on a `PostProcessStack` (`docs/architecture/07-rendering.md` §2.7).\n *\n * @public\n */\nexport interface CustomEffectSettings {\n /** The `// @ignifx post` shader; `null` records nothing. */\n shader: AssetHandle<ShaderAsset> | null;\n /** Whether the effect runs. */\n enabled: boolean;\n /** Position in the chain; lower runs first, alongside bloom's and SMAA's `order`. */\n order: number;\n /** Overrides of the file's declared uniform defaults, by declared name. */\n values: Record<string, number | readonly number[]>;\n /** Textures for the file's declared samplers, by declared name. */\n textures: Record<string, AssetHandle<TextureAsset> | null>;\n}\n\n/**\n * What {@link customEffect} accepts: a shader and whichever fields differ from the defaults.\n *\n * @public\n */\nexport interface CustomEffectInit {\n /** The `// @ignifx post` shader. */\n readonly shader: AssetHandle<ShaderAsset> | null;\n /** Whether the effect runs. Defaults to `true`. */\n readonly enabled?: boolean;\n /** Position in the chain. Defaults to `10`, which is after the built-ins' defaults. */\n readonly order?: number;\n /** Overrides of the file's declared uniform defaults. */\n readonly values?: Readonly<Record<string, number | readonly number[]>>;\n /** Textures for the file's declared samplers. */\n readonly textures?: Readonly<Record<string, AssetHandle<TextureAsset> | null>>;\n}\n\n/**\n * Fills in a custom effect's defaults, so a caller names only what it means to set.\n *\n * @param init - The shader and the fields to set.\n * @returns A complete settings record, ready to push onto `PostProcessStack.custom`.\n *\n * @example\n * ```ts\n * stack.custom.push(customEffect({ shader: vignette, order: 5, values: { amount: 0.6 } }));\n * ```\n *\n * @public\n */\nexport function customEffect(init: CustomEffectInit): CustomEffectSettings {\n return {\n shader: init.shader,\n enabled: init.enabled ?? true,\n order: init.order ?? 10,\n values: { ...init.values },\n textures: { ...init.textures },\n };\n}\n\n/**\n * The binding index of the chain's current colour.\n *\n * @internal\n */\nexport const INPUT_TEXTURE_BINDING = 1;\n\n/**\n * The binding index of the chain's current colour sampler.\n *\n * @internal\n */\nexport const INPUT_SAMPLER_BINDING = 2;\n\n/** The first binding index a declared texture takes. */\nconst FIRST_DECLARED_BINDING = 3;\n\n/**\n * The binding index of one declared texture, and of its sampler.\n *\n * @param index - The texture's index in declaration order.\n * @returns The texture's binding; the sampler is one higher.\n *\n * @internal\n */\nexport function declaredTextureBinding(index: number): number {\n return FIRST_DECLARED_BINDING + index * 2;\n}\n\n/**\n * One member of a compiled effect's uniform struct, with the byte offset the generated WGSL puts it\n * at.\n *\n * @internal\n */\nexport interface PostEffectUniformField {\n /** The WGSL member name. */\n readonly name: string;\n /** The WGSL type. */\n readonly type: ShaderUniformType;\n /** How many floats the value holds. */\n readonly components: number;\n /** Where the member starts in the uniform buffer, in bytes. */\n readonly byteOffset: number;\n}\n\n/**\n * A `// @ignifx post` file compiled into what Babylon Lite's fullscreen effect path needs.\n *\n * @internal\n */\nexport interface CompiledPostEffect {\n /** The shader's address, for diagnostics and for the chain's identity. */\n readonly address: string;\n /** The whole fragment module: the bindings, the generated structs, the file, and the entry point. */\n readonly fragmentWGSL: string;\n /** The uniform members, built-ins first, in struct order. */\n readonly uniforms: readonly PostEffectUniformField[];\n /** The members by name, for a value write. */\n readonly byName: ReadonlyMap<string, PostEffectUniformField>;\n /** How large the uniform buffer has to be. */\n readonly uniformByteLength: number;\n /** The file's declared samplers, in declaration order. */\n readonly textures: readonly ShaderTextureDeclaration[];\n}\n\n/**\n * The codec that round-trips a custom effect's `values` record through a scene file.\n *\n * @remarks\n * A schema field cannot describe these: the uniforms are declared by the `.wgsl`, so `map(f32)`\n * would drop every vector and colour uniform and `map(vec4)` would write `amount: 0.6` as four\n * floats. The codec round-trips exactly what a shader file allows — a number or an array of numbers.\n *\n * @returns The codec, for a `custom()` field.\n *\n * @internal\n */\nexport function postEffectValuesCodec(): CustomFieldCodec<Record<string, number | readonly number[]>> {\n return {\n createDefault(): Record<string, number | readonly number[]> {\n return {};\n },\n serialize(value: Record<string, number | readonly number[]>): JsonValue {\n const json: Record<string, JsonValue> = {};\n // Lexicographic, so two saves of the same state are byte-identical\n // (`docs/architecture/06-serialization-and-scene-format.md` §1).\n for (const name of Object.keys(value).toSorted()) {\n const entry = value[name];\n setOwnJsonProperty(json, name, typeof entry === \"number\" ? entry : [...(entry ?? [])]);\n }\n return json;\n },\n deserialize(json: JsonValue): Record<string, number | readonly number[]> {\n const value: Record<string, number | readonly number[]> = {};\n const object = asJsonObject(json);\n if (object === null) {\n return value;\n }\n for (const name of Object.keys(object)) {\n const entry = object[name];\n // Defined, not assigned: a `__proto__` key from a file stays a name instead of a prototype.\n if (typeof entry === \"number\") {\n setOwnJsonProperty(value, name, entry);\n } else if (Array.isArray(entry)) {\n setOwnJsonProperty(\n value,\n name,\n entry.map((component) => (typeof component === \"number\" ? component : 0)),\n );\n }\n }\n return value;\n },\n jsonSchema: {\n type: \"object\",\n additionalProperties: {\n oneOf: [{ type: \"number\" }, { type: \"array\", items: { type: \"number\" } }],\n },\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;AAuBA,MAAa,uBAAuB;;;;;;;;;;;;AAapC,MAAa,+BACX,OAAO,OAAO;CACZ;EAAE,MAAM;EAAc,MAAM;CAAY;CACxC;EAAE,MAAM;EAAQ,MAAM;CAAM;CAC5B;EAAE,MAAM;EAAgB,MAAM;CAAM;CACpC;EAAE,MAAM;EAAa,MAAM;CAAM;AACnC,CAAC;;;;;;;;;;;;;;AAmDH,SAAgB,aAAa,MAA8C;CACzE,OAAO;EACL,QAAQ,KAAK;EACb,SAAS,KAAK,WAAW;EACzB,OAAO,KAAK,SAAS;EACrB,QAAQ,EAAE,GAAG,KAAK,OAAO;EACzB,UAAU,EAAE,GAAG,KAAK,SAAS;CAC/B;AACF;;AAiBA,MAAM,yBAAyB;;;;;;;;;AAU/B,SAAgB,uBAAuB,OAAuB;CAC5D,OAAO,yBAAyB,QAAQ;AAC1C;;;;;;;;;;;;;AAmDA,SAAgB,wBAAsF;CACpG,OAAO;EACL,gBAA4D;GAC1D,OAAO,CAAC;EACV;EACA,UAAU,OAA8D;GACtE,MAAM,OAAkC,CAAC;GAGzC,KAAK,MAAM,QAAQ,OAAO,KAAK,KAAK,CAAC,CAAC,SAAS,GAAG;IAChD,MAAM,QAAQ,MAAM;IACpB,mBAAmB,MAAM,MAAM,OAAO,UAAU,WAAW,QAAQ,CAAC,GAAI,SAAS,CAAC,CAAE,CAAC;GACvF;GACA,OAAO;EACT;EACA,YAAY,MAA6D;GACvE,MAAM,QAAoD,CAAC;GAC3D,MAAM,SAAS,aAAa,IAAI;GAChC,IAAI,WAAW,MACb,OAAO;GAET,KAAK,MAAM,QAAQ,OAAO,KAAK,MAAM,GAAG;IACtC,MAAM,QAAQ,OAAO;IAErB,IAAI,OAAO,UAAU,UACnB,mBAAmB,OAAO,MAAM,KAAK;SAChC,IAAI,MAAM,QAAQ,KAAK,GAC5B,mBACE,OACA,MACA,MAAM,KAAK,cAAe,OAAO,cAAc,WAAW,YAAY,CAAE,CAC1E;GAEJ;GACA,OAAO;EACT;EACA,YAAY;GACV,MAAM;GACN,sBAAsB,EACpB,OAAO,CAAC,EAAE,MAAM,SAAS,GAAG;IAAE,MAAM;IAAS,OAAO,EAAE,MAAM,SAAS;GAAE,CAAC,EAC1E;EACF;CACF;AACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { n as assertNever, o as CoreErrorCode, t as IgnifxError } from "./ignifx-error-
|
|
2
|
-
import { i as declaredTextureBinding, n as POST_EFFECT_FUNCTION, t as POST_EFFECT_BUILTIN_UNIFORMS } from "./post-effect-
|
|
1
|
+
import { n as assertNever, o as CoreErrorCode, t as IgnifxError } from "./ignifx-error-DwIZKxA2.js";
|
|
2
|
+
import { i as declaredTextureBinding, n as POST_EFFECT_FUNCTION, t as POST_EFFECT_BUILTIN_UNIFORMS } from "./post-effect-CaiqDlhW.js";
|
|
3
3
|
//#region src/render/post-effect-compiler.ts
|
|
4
4
|
/**
|
|
5
5
|
* Turns a `// @ignifx post` file into the fragment module and uniform layout Babylon Lite's
|
|
@@ -308,4 +308,4 @@ function isBuiltinUniformName(name) {
|
|
|
308
308
|
//#endregion
|
|
309
309
|
export { compilePostEffect, compiledPostEffect, writePostEffectValues };
|
|
310
310
|
|
|
311
|
-
//# sourceMappingURL=post-effect-compiler-
|
|
311
|
+
//# sourceMappingURL=post-effect-compiler-jSvOVe0U.js.map
|