@ignifx/core 0.18.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/dist/{environment-DZ6WUHbm.js → environment-Bf4aphSb.js} +2 -2
  2. package/dist/{environment-DZ6WUHbm.js.map → environment-Bf4aphSb.js.map} +1 -1
  3. package/dist/{gtao-_nr0b6-E.js → gtao-Bpu5-0Ne.js} +2 -2
  4. package/dist/{gtao-_nr0b6-E.js.map → gtao-Bpu5-0Ne.js.map} +1 -1
  5. package/dist/{hdr-output-Dbv0lhFl.js → hdr-output-DBQwMphy.js} +2 -2
  6. package/dist/{hdr-output-Dbv0lhFl.js.map → hdr-output-DBQwMphy.js.map} +1 -1
  7. package/dist/{ignifx-error-B8ByiSfJ.js → ignifx-error-DwIZKxA2.js} +4 -1
  8. package/dist/ignifx-error-DwIZKxA2.js.map +1 -0
  9. package/dist/index.d.ts +218 -696
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +2904 -970
  12. package/dist/index.js.map +1 -1
  13. package/dist/{instanced-mesh-instance-BMhREEfx.js → instanced-mesh-instance-B-fXKSrY.js} +2 -2
  14. package/dist/{instanced-mesh-instance-BMhREEfx.js.map → instanced-mesh-instance-B-fXKSrY.js.map} +1 -1
  15. package/dist/{light-probe-asset-B60_X-yN.js → light-probe-asset-BqfSrJe9.js} +2 -2
  16. package/dist/{light-probe-asset-B60_X-yN.js.map → light-probe-asset-BqfSrJe9.js.map} +1 -1
  17. package/dist/{light-probes-DkYN89Qw.js → light-probes-DDojYajw.js} +4 -4
  18. package/dist/{light-probes-DkYN89Qw.js.map → light-probes-DDojYajw.js.map} +1 -1
  19. package/dist/lightmaps-BUUIIkt9.js +230 -0
  20. package/dist/lightmaps-BUUIIkt9.js.map +1 -0
  21. package/dist/{material-CGk5mAah.js → material-myMbl9mW.js} +37 -2
  22. package/dist/{material-CGk5mAah.js.map → material-myMbl9mW.js.map} +1 -1
  23. package/dist/{material-plugin-CiAmriQ_.js → material-plugin-DapJNj04.js} +2 -2
  24. package/dist/{material-plugin-CiAmriQ_.js.map → material-plugin-DapJNj04.js.map} +1 -1
  25. package/dist/{post-effect-CQnlX1RH.js → post-effect-Cu3Enpz7.js} +2 -2
  26. package/dist/{post-effect-CQnlX1RH.js.map → post-effect-Cu3Enpz7.js.map} +1 -1
  27. package/dist/{post-effect-compiler-C_7HTHZy.js → post-effect-compiler-cCq9lcHt.js} +3 -3
  28. package/dist/{post-effect-compiler-C_7HTHZy.js.map → post-effect-compiler-cCq9lcHt.js.map} +1 -1
  29. package/dist/{prefab-overrides-DT-wHHAJ.js → prefab-overrides-C2GsgOQc.js} +467 -30
  30. package/dist/prefab-overrides-C2GsgOQc.js.map +1 -0
  31. package/dist/{prefab-overrides-BLQn5yHS.d.ts → prefab-overrides-htDc_5Po.d.ts} +1370 -246
  32. package/dist/prefab-overrides-htDc_5Po.d.ts.map +1 -0
  33. package/dist/prefab.d.ts +2 -2
  34. package/dist/prefab.js +2 -2
  35. package/dist/{reflection-probe-DlVsl3zJ.js → reflection-probe-QkD1Fo_d.js} +106 -12
  36. package/dist/{reflection-probe-DlVsl3zJ.js.map → reflection-probe-QkD1Fo_d.js.map} +1 -1
  37. package/dist/reflection-probes-CAzSuqf8.js +921 -0
  38. package/dist/reflection-probes-CAzSuqf8.js.map +1 -0
  39. package/dist/{shader-material-CaAkv5nT.js → shader-material-CJIDFvSb.js} +2 -2
  40. package/dist/{shader-material-CaAkv5nT.js.map → shader-material-CJIDFvSb.js.map} +1 -1
  41. package/dist/{shader-material-C2_UCYdO.js → shader-material-TM4f8eKA.js} +4 -4
  42. package/dist/{shader-material-C2_UCYdO.js.map → shader-material-TM4f8eKA.js.map} +1 -1
  43. package/dist/{shader-pragma-DmZpxGUo.js → shader-pragma-ljmAbVc2.js} +2 -2
  44. package/dist/{shader-pragma-DmZpxGUo.js.map → shader-pragma-ljmAbVc2.js.map} +1 -1
  45. package/dist/{ssgi-Dm-maZrc.js → ssgi-DSnhqotl.js} +2 -2
  46. package/dist/{ssgi-Dm-maZrc.js.map → ssgi-DSnhqotl.js.map} +1 -1
  47. package/dist/{surface-shader-BeDRofOV.js → surface-shader-rpPpeosD.js} +6 -6
  48. package/dist/{surface-shader-BeDRofOV.js.map → surface-shader-rpPpeosD.js.map} +1 -1
  49. package/dist/{vec3-Cc19wl4r.js → vec3-2C3LBZnt.js} +55 -3
  50. package/dist/vec3-2C3LBZnt.js.map +1 -0
  51. package/package.json +1 -1
  52. package/dist/ignifx-error-B8ByiSfJ.js.map +0 -1
  53. package/dist/prefab-overrides-BLQn5yHS.d.ts.map +0 -1
  54. package/dist/prefab-overrides-DT-wHHAJ.js.map +0 -1
  55. package/dist/reflection-probes-B8S9WnVX.js +0 -551
  56. package/dist/reflection-probes-B8S9WnVX.js.map +0 -1
  57. package/dist/vec3-Cc19wl4r.js.map +0 -1
@@ -0,0 +1,921 @@
1
+ import { J as toEntityHandle, a as resolveReflectionProbeSize, i as resolveReflectionProbeRefreshMode, o as selectReflectionProbe, r as reflectionProbeBlendLayout, s as EDITOR_ONLY_METADATA_KEY, z as readOwnerTag } from "./reflection-probe-QkD1Fo_d.js";
2
+ import { i as readSceneEnvironment } from "./environment-Bf4aphSb.js";
3
+ import { n as deviceOf, r as removeTask, t as colorTextureOf } from "./render-texture-UqRHRLQy.js";
4
+ import { addTask, buildFrameGraphTask, clearPbrLocalEnvironment, createBankedFreeCamera, createPbrLocalEnvironmentProbeSet, createRenderTarget, createRenderTask, enablePbrLocalCubemap, getFrameGraph, getPbrUnlit, isPbrMaterial, isPbrSkybox, rebuildMaterial, setPbrEnvironment, setPbrLocalEnvironment, setPbrLocalEnvironmentProbeSet } from "@babylonjs/lite";
5
+ //#region src/lite/gpu/reflection-probe.ts
6
+ /**
7
+ * Reflection probes (`docs/plan/2026-11-gi-phase-2-execution-plan.md`, step B1). Its own chunk,
8
+ * loaded only when a world has a `ReflectionProbe` (`CONSTITUTION.md` §2.5). Every Lite claim was
9
+ * read from `@babylonjs/lite@1.34.0`.
10
+ *
11
+ * - **Capture.** Lite has no cube capture, so six render tasks (`createRenderTask`, each with its own
12
+ * `rgba16float` target and a `createBankedFreeCamera` looking down one axis, 90° field of view,
13
+ * square target) are appended to the frame graph, switched on for the frames that capture, like
14
+ * `./render-texture.ts`. Faces follow the cube-map convention in Lite's left-handed space: +X, −X
15
+ * and ±Z faces use +Y as up, +Y uses −Z and −Y uses +Z.
16
+ * - **Cube and mips.** In the next frame's `PreRender`, a small render pipeline of ignifx's own copies
17
+ * each face into a cube texture, decoding gamma when `rendering.hdr` is off (the faces then hold
18
+ * tone-mapped sRGB), and box-downsamples the mip chain. It is submitted before Lite's frame, so queue
19
+ * order makes it read the frame that rendered the faces. Mips are not GGX-prefiltered.
20
+ * - **Environment.** The cube is wrapped in an `EnvironmentTextures` (`index.d.ts` 5598) that shares
21
+ * the scene environment's BRDF table and spherical harmonics, so diffuse light is unchanged.
22
+ * - **Materials.** `setPbrLocalEnvironment` (box parallax) or `setPbrEnvironment` (no box) per lit PBR
23
+ * material, then a material rebuild (`index.d.ts` 12612–12654). `enablePbrLocalCubemap` must have
24
+ * resolved first; it is called when the chunk loads.
25
+ * - **Culling mask.** Render tasks have no mesh filter, so each face task's `execute` hides the meshes
26
+ * the caller rejects and shows them again, as `./render-texture.ts` does for editor-only meshes.
27
+ * - **Blending (B1b).** `createPbrLocalEnvironmentProbeSet` (`index.d.ts` 3411) **copies** every
28
+ * probe's cube into one cube array when it is created (`lib/material/pbr/enable-pbr-local-cubemap.js`,
29
+ * `createProbeTexture`) and blends up to four candidates per voxel per fragment. It has no dispose:
30
+ * its buffers and texture are destroyed only when the scene is (`scene._disposables`), so a set
31
+ * replaced earlier is freed through its `_texture`, `_uniformBuffer` and `_gridBuffer` fields and
32
+ * its closure is taken off `scene._disposables`, all read from the pinned source
33
+ * ({@link releaseLiteProbeSet}). A fragment inside a probe's inner box takes
34
+ * that probe alone; between inner and outer boxes the candidates are weighted; outside every outer
35
+ * box the nearest probe by its normalised distance wins (`local-cubemap-fragment.js`).
36
+ */
37
+ /** The colour format of the faces and the cube. */
38
+ const PROBE_FORMAT = "rgba16float";
39
+ /** The depth/stencil format Lite's own render tasks use. */
40
+ const DEPTH_STENCIL_FORMAT = "depth24plus-stencil8";
41
+ /** Each face's view direction and up vector, in cube-face order +X, −X, +Y, −Y, +Z, −Z. */
42
+ const FACES = [
43
+ [
44
+ 1,
45
+ 0,
46
+ 0,
47
+ 0,
48
+ 1,
49
+ 0
50
+ ],
51
+ [
52
+ -1,
53
+ 0,
54
+ 0,
55
+ 0,
56
+ 1,
57
+ 0
58
+ ],
59
+ [
60
+ 0,
61
+ 1,
62
+ 0,
63
+ 0,
64
+ 0,
65
+ -1
66
+ ],
67
+ [
68
+ 0,
69
+ -1,
70
+ 0,
71
+ 0,
72
+ 0,
73
+ 1
74
+ ],
75
+ [
76
+ 0,
77
+ 0,
78
+ 1,
79
+ 0,
80
+ 1,
81
+ 0
82
+ ],
83
+ [
84
+ 0,
85
+ 0,
86
+ -1,
87
+ 0,
88
+ 1,
89
+ 0
90
+ ]
91
+ ];
92
+ /** A full-screen triangle that copies, decodes, or (through a linear sampler) box-downsamples. */
93
+ const BLIT_WGSL = `
94
+ struct VsOut { @builtin(position) position: vec4<f32>, @location(0) uv: vec2<f32> };
95
+ @vertex fn vs(@builtin(vertex_index) index: u32) -> VsOut {
96
+ let corner = vec2<f32>(f32((index << 1u) & 2u), f32(index & 2u));
97
+ var out: VsOut;
98
+ out.position = vec4<f32>(corner * 2.0 - 1.0, 0.0, 1.0);
99
+ out.uv = vec2<f32>(corner.x, 1.0 - corner.y);
100
+ return out;
101
+ }
102
+ @group(0) @binding(0) var source: texture_2d<f32>;
103
+ @group(0) @binding(1) var sourceSampler: sampler;
104
+ @fragment fn copy(in: VsOut) -> @location(0) vec4<f32> {
105
+ return vec4<f32>(textureSampleLevel(source, sourceSampler, in.uv, 0.0).rgb, 1.0);
106
+ }
107
+ @fragment fn decode(in: VsOut) -> @location(0) vec4<f32> {
108
+ let colour = textureSampleLevel(source, sourceSampler, in.uv, 0.0).rgb;
109
+ return vec4<f32>(pow(max(colour, vec3<f32>(0.0)), vec3<f32>(2.2)), 1.0);
110
+ }
111
+ `;
112
+ /** Each device's pipelines, the map created on first use (coding standards §4). */
113
+ let pipelineCache = null;
114
+ /**
115
+ * Loads Lite's local-cubemap shader path. Resolve it before assigning any probe.
116
+ *
117
+ * @returns A promise that resolves once the path is registered.
118
+ *
119
+ * @internal
120
+ */
121
+ function enableReflectionProbes() {
122
+ return enablePbrLocalCubemap();
123
+ }
124
+ /**
125
+ * Creates a probe's six face passes, switched off, at the end of the scene's frame graph.
126
+ *
127
+ * @param engine - The WebGPU engine.
128
+ * @param scene - The registered render scene.
129
+ * @param size - The face size in pixels, a power of two.
130
+ * @param excludeKey - The `metadata` key that, set to `true` on a mesh, keeps it out of the faces.
131
+ * @param accept - Whether a mesh's owner may be captured; `false` hides it during the faces.
132
+ * @returns The probe.
133
+ *
134
+ * @internal
135
+ */
136
+ function createLiteReflectionProbe(engine, scene, size, excludeKey, accept) {
137
+ const targets = [];
138
+ const tasks = [];
139
+ const cameras = [];
140
+ const hidden = [];
141
+ for (const face of FACES) {
142
+ const target = createRenderTarget({
143
+ lbl: "ignifx:reflection-probe-face",
144
+ format: PROBE_FORMAT,
145
+ dFormat: DEPTH_STENCIL_FORMAT,
146
+ samples: 1,
147
+ size: {
148
+ width: size,
149
+ height: size
150
+ }
151
+ });
152
+ const camera = createBankedFreeCamera({
153
+ x: 0,
154
+ y: 0,
155
+ z: 0
156
+ }, {
157
+ x: face[0],
158
+ y: face[1],
159
+ z: face[2]
160
+ }, {
161
+ x: face[3],
162
+ y: face[4],
163
+ z: face[5]
164
+ });
165
+ camera.fov = Math.PI / 2;
166
+ const task = createRenderTask({
167
+ name: "ignifx:reflection-probe",
168
+ rt: target,
169
+ cam: camera
170
+ }, engine, scene);
171
+ task.executionEnabled = false;
172
+ const execute = task.execute?.bind(task);
173
+ if (execute === void 0) throw new TypeError("Lite's render task has no execute(); reflection-probe.ts needs updating for this Lite.");
174
+ task.execute = () => {
175
+ for (const mesh of scene.meshes) if (mesh.visible !== false && (mesh.metadata?.[excludeKey] === true || !accept(readOwnerTag(mesh)))) {
176
+ mesh.visible = false;
177
+ hidden.push(mesh);
178
+ }
179
+ try {
180
+ return execute();
181
+ } finally {
182
+ for (const mesh of hidden) mesh.visible = true;
183
+ hidden.length = 0;
184
+ }
185
+ };
186
+ addTask(scene, task);
187
+ buildFrameGraphTask(getFrameGraph(scene), task);
188
+ targets.push(target);
189
+ tasks.push(task);
190
+ cameras.push(camera);
191
+ }
192
+ let cube = null;
193
+ let environment = null;
194
+ let isCapturing = false;
195
+ let isDisposed = false;
196
+ return {
197
+ size,
198
+ get environment() {
199
+ return environment;
200
+ },
201
+ capture(x, y, z, near, far) {
202
+ if (isDisposed || readSceneEnvironment(scene) === null) return false;
203
+ for (let index = 0; index < FACES.length; index += 1) {
204
+ const face = FACES[index];
205
+ const camera = cameras[index];
206
+ const task = tasks[index];
207
+ if (face === void 0 || camera === void 0 || task === void 0) continue;
208
+ camera.position.set(x, y, z);
209
+ camera.target.set(x + face[0], y + face[1], z + face[2]);
210
+ camera.nearPlane = near;
211
+ camera.farPlane = far;
212
+ task.executionEnabled = true;
213
+ }
214
+ isCapturing = true;
215
+ return true;
216
+ },
217
+ resolve(decodeGamma) {
218
+ if (isDisposed || !isCapturing) return false;
219
+ isCapturing = false;
220
+ for (const task of tasks) task.executionEnabled = false;
221
+ const device = deviceOf(engine);
222
+ const base = readSceneEnvironment(scene);
223
+ if (device === null || base === null) return false;
224
+ cube ??= device.createTexture({
225
+ label: "ignifx:reflection-probe",
226
+ size: [
227
+ size,
228
+ size,
229
+ FACES.length
230
+ ],
231
+ format: PROBE_FORMAT,
232
+ mipLevelCount: Math.log2(size) + 1,
233
+ usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
234
+ });
235
+ if (!blitFaces(device, cube, targets, decodeGamma)) return false;
236
+ if (environment !== null) return false;
237
+ environment = {
238
+ specularCube: cube,
239
+ specularCubeView: cube.createView({ dimension: "cube" }),
240
+ brdfLut: base.brdfLut,
241
+ brdfLutView: base.brdfLutView,
242
+ cubeSampler: base.cubeSampler,
243
+ brdfSampler: base.brdfSampler,
244
+ irradianceSH: base.irradianceSH,
245
+ sphericalHarmonics: base.sphericalHarmonics,
246
+ lodGenerationScale: base.lodGenerationScale,
247
+ lodGenerationOffset: base.lodGenerationOffset ?? 0
248
+ };
249
+ return true;
250
+ },
251
+ dispose(after) {
252
+ if (isDisposed) return;
253
+ isDisposed = true;
254
+ for (const task of tasks) {
255
+ task.executionEnabled = false;
256
+ removeTask(scene, task);
257
+ task.dispose();
258
+ }
259
+ const retired = cube;
260
+ cube = null;
261
+ environment = null;
262
+ if (retired !== null) destroyWhenIdle(deviceOf(engine), retired, after);
263
+ }
264
+ };
265
+ }
266
+ /**
267
+ * Destroys a texture once nothing in flight can name it: a material rebuild finishes asynchronously
268
+ * (`rebuildMaterial`, `index.d.ts` 11136), and until then Lite may still draw with a bind group that
269
+ * holds the old cube, so destruction waits for `after`, then for the queue.
270
+ *
271
+ * @param device - The device, or `null` when it is gone (the texture is destroyed at once).
272
+ * @param texture - The texture.
273
+ * @param after - What must settle first, if anything.
274
+ */
275
+ function destroyWhenIdle(device, texture, after) {
276
+ const destroy = () => {
277
+ texture.destroy();
278
+ };
279
+ Promise.resolve(after).catch(() => void 0).then(async () => device?.queue.onSubmittedWorkDone()).then(destroy, destroy);
280
+ }
281
+ /**
282
+ * Copies the six face targets into the cube's first mip and box-downsamples the rest.
283
+ *
284
+ * @param device - The device.
285
+ * @param cube - The cube texture, six layers.
286
+ * @param targets - The face targets, in cube-face order.
287
+ * @param decodeGamma - Whether to decode gamma on the copy.
288
+ * @returns `false` when a face target has no texture yet.
289
+ */
290
+ function blitFaces(device, cube, targets, decodeGamma) {
291
+ const pipelines = blitPipelines(device);
292
+ const encoder = device.createCommandEncoder({ label: "ignifx:reflection-probe-mips" });
293
+ for (let face = 0; face < targets.length; face += 1) {
294
+ const target = targets[face];
295
+ const source = target === void 0 ? null : colorTextureOf(target);
296
+ if (source === null) return false;
297
+ draw(device, encoder, decodeGamma ? pipelines.decode : pipelines.copy, pipelines.sampler, source.createView(), cubeFace(cube, face, 0));
298
+ for (let mip = 1; mip < cube.mipLevelCount; mip += 1) draw(device, encoder, pipelines.copy, pipelines.sampler, cubeFace(cube, face, mip - 1), cubeFace(cube, face, mip));
299
+ }
300
+ device.queue.submit([encoder.finish()]);
301
+ return true;
302
+ }
303
+ /**
304
+ * A 2D view of one face and mip of the cube.
305
+ *
306
+ * @param cube - The cube texture.
307
+ * @param face - The layer.
308
+ * @param mip - The mip level.
309
+ * @returns The view.
310
+ */
311
+ function cubeFace(cube, face, mip) {
312
+ return cube.createView({
313
+ dimension: "2d",
314
+ baseArrayLayer: face,
315
+ arrayLayerCount: 1,
316
+ baseMipLevel: mip,
317
+ mipLevelCount: 1
318
+ });
319
+ }
320
+ /**
321
+ * Encodes one full-screen blit.
322
+ *
323
+ * @param device - The device.
324
+ * @param encoder - The encoder.
325
+ * @param pipeline - The pipeline.
326
+ * @param sampler - The linear sampler.
327
+ * @param source - The view to read.
328
+ * @param destination - The view to write.
329
+ */
330
+ function draw(device, encoder, pipeline, sampler, source, destination) {
331
+ const bindGroup = device.createBindGroup({
332
+ layout: pipeline.getBindGroupLayout(0),
333
+ entries: [{
334
+ binding: 0,
335
+ resource: source
336
+ }, {
337
+ binding: 1,
338
+ resource: sampler
339
+ }]
340
+ });
341
+ const pass = encoder.beginRenderPass({ colorAttachments: [{
342
+ view: destination,
343
+ loadOp: "clear",
344
+ storeOp: "store",
345
+ clearValue: {
346
+ r: 0,
347
+ g: 0,
348
+ b: 0,
349
+ a: 1
350
+ }
351
+ }] });
352
+ pass.setPipeline(pipeline);
353
+ pass.setBindGroup(0, bindGroup);
354
+ pass.draw(3);
355
+ pass.end();
356
+ }
357
+ /**
358
+ * The device's blit pipelines.
359
+ *
360
+ * @param device - The device.
361
+ * @returns The pipelines, created on first use.
362
+ */
363
+ function blitPipelines(device) {
364
+ pipelineCache ??= /* @__PURE__ */ new WeakMap();
365
+ const cached = pipelineCache.get(device);
366
+ if (cached !== void 0) return cached;
367
+ const module = device.createShaderModule({
368
+ label: "ignifx:reflection-probe-blit",
369
+ code: BLIT_WGSL
370
+ });
371
+ const pipeline = (entryPoint) => device.createRenderPipeline({
372
+ label: `ignifx:reflection-probe-${entryPoint}`,
373
+ layout: "auto",
374
+ vertex: {
375
+ module,
376
+ entryPoint: "vs"
377
+ },
378
+ fragment: {
379
+ module,
380
+ entryPoint,
381
+ targets: [{ format: PROBE_FORMAT }]
382
+ },
383
+ primitive: { topology: "triangle-list" }
384
+ });
385
+ const created = {
386
+ copy: pipeline("copy"),
387
+ decode: pipeline("decode"),
388
+ sampler: device.createSampler({
389
+ magFilter: "linear",
390
+ minFilter: "linear"
391
+ })
392
+ };
393
+ pipelineCache.set(device, created);
394
+ return created;
395
+ }
396
+ /** The three GPU resources of a Lite probe set, by the field names `enable-pbr-local-cubemap.js` uses. */
397
+ const PROBE_SET_RESOURCE_FIELDS = [
398
+ "_texture",
399
+ "_uniformBuffer",
400
+ "_gridBuffer"
401
+ ];
402
+ /**
403
+ * Frees what a Lite probe set holds: its three GPU resources, and the cleanup closure Lite pushed
404
+ * onto `scene._disposables`, which would otherwise keep the whole set (its 64 KiB uniform data and
405
+ * its grid) alive until the scene is disposed.
406
+ *
407
+ * @remarks
408
+ * Every field is checked before use: a Lite upgrade that renames one degrades to `warn` (a leak
409
+ * that is logged) and never throws. Destroying twice is harmless.
410
+ *
411
+ * @param set - The set, as Lite returned it.
412
+ * @param disposables - The scene's `_disposables` list, or anything else when it is not one.
413
+ * @param cleanup - The closure Lite pushed for this set, or `undefined` when it was not found.
414
+ * @param warn - Receives one message per missing field or list.
415
+ *
416
+ * @internal
417
+ */
418
+ function releaseLiteProbeSet(set, disposables, cleanup, warn) {
419
+ const record = typeof set === "object" && set !== null ? set : {};
420
+ for (const field of PROBE_SET_RESOURCE_FIELDS) {
421
+ const resource = record[field];
422
+ const destroy = typeof resource === "object" && resource !== null ? resource.destroy : void 0;
423
+ if (typeof destroy === "function") Reflect.apply(destroy, resource, []);
424
+ else warn(`a Babylon Lite probe set has no ${field} to destroy, so its GPU memory stays until the scene goes`);
425
+ }
426
+ if (!Array.isArray(disposables) || cleanup === void 0) {
427
+ warn("the Babylon Lite probe set's scene cleanup could not be found, so its CPU data stays until the scene goes");
428
+ return;
429
+ }
430
+ const index = disposables.indexOf(cleanup);
431
+ if (index >= 0) disposables.splice(index, 1);
432
+ }
433
+ /**
434
+ * The scene's `_disposables` list, which Lite's set pushes its cleanup onto.
435
+ *
436
+ * @param scene - The scene.
437
+ * @returns The list, or `undefined` when the scene has none (a Lite change).
438
+ */
439
+ function disposablesOf(scene) {
440
+ const list = scene._disposables;
441
+ return Array.isArray(list) ? list : void 0;
442
+ }
443
+ /**
444
+ * Builds a blended set from captured probes.
445
+ *
446
+ * @param engine - The engine, for the queue a disposal waits on.
447
+ * @param scene - The registered scene.
448
+ * @param volumes - The probes, at least two.
449
+ * @param minimum - The voxel grid's minimum corner.
450
+ * @param maximum - The voxel grid's maximum corner.
451
+ * @param cellSize - The voxel edge.
452
+ * @param warn - Where a disposal that cannot free everything reports it.
453
+ * @returns The set.
454
+ * @throws When Lite refuses it: more than four probes in a voxel, more probes than the uniform block
455
+ * holds, or cubes of different formats.
456
+ *
457
+ * @internal
458
+ */
459
+ function createLiteProbeSet(engine, scene, volumes, minimum, maximum, cellSize, warn) {
460
+ const probes = volumes.map((volume) => ({
461
+ shape: "box",
462
+ environment: volume.environment,
463
+ capturePosition: volume.position,
464
+ projectionPosition: volume.position,
465
+ influencePosition: volume.position,
466
+ projectionSize: volume.outer,
467
+ influenceInnerSize: volume.inner,
468
+ influenceOuterSize: volume.outer
469
+ }));
470
+ const disposables = disposablesOf(scene);
471
+ const before = disposables?.length ?? 0;
472
+ const set = createPbrLocalEnvironmentProbeSet(scene, {
473
+ probes,
474
+ voxelGrid: {
475
+ minimum,
476
+ maximum,
477
+ cellSize
478
+ }
479
+ });
480
+ const cleanup = disposables !== void 0 && disposables.length === before + 1 ? disposables[before] : void 0;
481
+ let isDisposed = false;
482
+ return {
483
+ set,
484
+ dispose(after) {
485
+ if (isDisposed) return;
486
+ isDisposed = true;
487
+ const release = () => {
488
+ releaseLiteProbeSet(set, disposables, cleanup, warn);
489
+ };
490
+ const device = deviceOf(engine);
491
+ Promise.resolve(after).catch(() => void 0).then(async () => device?.queue.onSubmittedWorkDone()).then(release, release);
492
+ }
493
+ };
494
+ }
495
+ /**
496
+ * Calls `visit` for every mesh whose material is a lit, non-skybox PBR material.
497
+ *
498
+ * @param scene - The scene.
499
+ * @param visit - Receives the material and the mesh's world position.
500
+ *
501
+ * @internal
502
+ */
503
+ function forEachReflectiveMesh(scene, visit) {
504
+ const meshes = scene.meshes;
505
+ for (let index = 0; index < meshes.length; index += 1) {
506
+ const mesh = meshes[index];
507
+ const material = mesh?.material;
508
+ if (mesh === void 0 || material === void 0 || material === null || !isPbrMaterial(material)) continue;
509
+ if (getPbrUnlit(material) !== void 0 || isPbrSkybox(material)) continue;
510
+ const world = mesh.worldMatrix;
511
+ visit(material, world[12] ?? 0, world[13] ?? 0, world[14] ?? 0);
512
+ }
513
+ }
514
+ /**
515
+ * Points a PBR material at a probe, or back at the scene environment, and rebuilds it.
516
+ *
517
+ * @param scene - The registered scene, or `null` to leave the rebuild to Lite (its device-loss
518
+ * recovery rebuilds every material).
519
+ * @param material - The material.
520
+ * @param binding - The probe, a blended set, or `null` for the scene environment.
521
+ * @returns The rebuild in flight, if Lite runs it asynchronously; Lite reports its failure itself.
522
+ *
523
+ * @internal
524
+ */
525
+ function assignReflectionProbe(scene, material, binding) {
526
+ if (binding === null) clearPbrLocalEnvironment(material);
527
+ else if ("set" in binding) setPbrLocalEnvironmentProbeSet(material, binding.set);
528
+ else if (binding.box === null) setPbrEnvironment(material, binding.environment);
529
+ else setPbrLocalEnvironment(material, binding.environment, {
530
+ shape: "box",
531
+ capturePosition: binding.position,
532
+ projectionPosition: binding.position,
533
+ projectionSize: binding.box
534
+ });
535
+ if (scene === null) return;
536
+ const pending = rebuildMaterial(scene, material);
537
+ return pending instanceof Promise ? pending : void 0;
538
+ }
539
+ //#endregion
540
+ //#region src/render/gpu/reflection-probes.ts
541
+ /**
542
+ * The render layer's half of reflection probes (`docs/plan/2026-11-gi-phase-2-execution-plan.md`,
543
+ * step B1): which probe captures when, and which probe each PBR material reflects. Loaded with
544
+ * `../../lite/gpu/reflection-probe.ts` as one chunk, only once a world has a `ReflectionProbe`.
545
+ *
546
+ * Blending (B1b): when `reflectionProbeBlendLayout` says the frame's probes blend and every box probe
547
+ * has finished capturing (none `everyFrame`), one Lite probe set built from their cubes goes on every
548
+ * lit PBR material. The set copies the cubes, so it is rebuilt when a probe moves, recaptures,
549
+ * resizes its box or changes `blendDistance`, and the replaced set is freed once the material
550
+ * rebuilds that dropped it settled. While a box probe is still capturing, the last set stays (or,
551
+ * before the first, the nearest-probe choice applies); while one is being moved or edited (its
552
+ * binding or `blendDistance` changed within the last {@link BLEND_STILL_FRAMES} frames) the
553
+ * nearest-probe choice applies. A material whose nearest probe has no box keeps that probe. A set Lite refuses (more than four probes
554
+ * overlapping in a voxel, too many probes) logs once and the nearest-probe choice applies.
555
+ */
556
+ /**
557
+ * How many consecutive frames one capture request renders. Lite compiles material pipelines
558
+ * asynchronously, so a single frame right after start or after a scene change can miss meshes that
559
+ * are still compiling; repeating it for a few frames catches them.
560
+ */
561
+ const CAPTURE_FRAMES = 8;
562
+ /**
563
+ * How many frames a blended probe's position, box and `blendDistance` must stay unchanged before a
564
+ * probe set is built with it (about 250 ms at 60 Hz). A set copies every cube and rebuilds every lit
565
+ * material, so a probe being moved, dragged or scrubbed falls back to the nearest-probe choice until
566
+ * it rests.
567
+ */
568
+ const BLEND_STILL_FRAMES = 15;
569
+ /**
570
+ * Creates the runtime once Lite's local-cubemap shader path is loaded.
571
+ *
572
+ * @param engine - The engine.
573
+ * @param scene - The registered render scene.
574
+ * @param warn - Where a probe's warning goes, with the entity's name already in the message.
575
+ * @returns The runtime.
576
+ *
577
+ * @internal
578
+ */
579
+ async function createReflectionProbeRuntime(engine, scene, warn) {
580
+ await enableReflectionProbes();
581
+ const states = /* @__PURE__ */ new Map();
582
+ const assigned = /* @__PURE__ */ new Map();
583
+ /** The blended set on every lit material, or `null` for the nearest-probe choice. */
584
+ let blend = null;
585
+ /** The key of a set Lite refused, so it is not tried again every frame. */
586
+ let refusedKey = null;
587
+ let hasWarnedRefusal = false;
588
+ const warnedLeaks = /* @__PURE__ */ new Set();
589
+ const warnLeakOnce = (message) => {
590
+ if (!warnedLeaks.has(message)) {
591
+ warnedLeaks.add(message);
592
+ warn(`Reflection probe blending: ${message}.`);
593
+ }
594
+ };
595
+ /** Sets replaced this frame, freed with the retired cubes. */
596
+ const retiringSets = [];
597
+ const seen = /* @__PURE__ */ new Set();
598
+ const candidates = [];
599
+ /** The cubes released this frame, freed once the materials that reflected them are rebuilt. */
600
+ const retiring = [];
601
+ /**
602
+ * Material rebuilds still in flight, whichever frame started them: a rebuild started a frame ago
603
+ * may still draw with a cube retired now, so a retired cube waits for all of them.
604
+ */
605
+ const rebuilds = /* @__PURE__ */ new Set();
606
+ /**
607
+ * Probes whose capture was freed while they stayed (resized, environment gone, device lost); they
608
+ * capture again whatever their mode.
609
+ */
610
+ const recapture = /* @__PURE__ */ new WeakSet();
611
+ let hasWarnedEveryFrame = false;
612
+ /** Between a device loss and Lite's recovery, nothing on the GPU may be touched. */
613
+ let isDeviceLost = false;
614
+ const assign = (material, binding) => {
615
+ const pending = assignReflectionProbe(scene, material, binding);
616
+ if (pending !== void 0) {
617
+ rebuilds.add(pending);
618
+ const forget = () => {
619
+ rebuilds.delete(pending);
620
+ };
621
+ pending.then(forget, forget);
622
+ }
623
+ };
624
+ const release = (probe, state) => {
625
+ if (state.lite.environment !== null || state.framesToCapture > 0) recapture.add(probe);
626
+ retiring.push({
627
+ lite: state.lite,
628
+ environment: state.lite.environment
629
+ });
630
+ states.delete(probe);
631
+ };
632
+ /**
633
+ * Frees the cubes released this frame. A material that reflected one and was not reassigned this
634
+ * frame (its mesh left the scene) goes back to the scene environment first, so it never names a
635
+ * destroyed cube; the cubes then wait for every rebuild still in flight, from any frame.
636
+ */
637
+ const retire = () => {
638
+ if (retiring.length > 0) {
639
+ for (const [material, binding] of assigned) if (binding !== null && !("set" in binding) && retiring.some((entry) => entry.environment === binding.environment)) {
640
+ assigned.set(material, null);
641
+ assign(material, null);
642
+ }
643
+ const settled = Promise.allSettled(rebuilds);
644
+ for (const entry of retiring) entry.lite.dispose(settled);
645
+ retiring.length = 0;
646
+ }
647
+ if (retiringSets.length > 0) {
648
+ for (const [material, binding] of assigned) if (binding !== null && "set" in binding && retiringSets.includes(binding)) {
649
+ assigned.set(material, null);
650
+ assign(material, null);
651
+ }
652
+ const settled = Promise.allSettled(rebuilds);
653
+ for (const set of retiringSets) set.dispose(settled);
654
+ retiringSets.length = 0;
655
+ }
656
+ };
657
+ /** Stops blending; the set goes once the materials that used it were rebuilt. */
658
+ const dropBlend = () => {
659
+ if (blend !== null) {
660
+ retiringSets.push(blend.lite);
661
+ blend = null;
662
+ }
663
+ };
664
+ /**
665
+ * Builds, keeps or drops the blended set for this frame's candidates.
666
+ *
667
+ * @param layout - The blend layout, or `null` when the probes do not blend.
668
+ */
669
+ const updateBlend = (layout) => {
670
+ if (layout === null) {
671
+ dropBlend();
672
+ refusedKey = null;
673
+ return;
674
+ }
675
+ let isCapturing = false;
676
+ let hasEveryFrame = false;
677
+ let isMoving = false;
678
+ for (const volume of layout.volumes) {
679
+ const candidate = candidates[volume.index];
680
+ isCapturing ||= candidate?.isCapturing === true;
681
+ hasEveryFrame ||= candidate?.isEveryFrame === true;
682
+ isMoving ||= candidate?.isMoving === true;
683
+ }
684
+ if (hasEveryFrame || isMoving) {
685
+ dropBlend();
686
+ return;
687
+ }
688
+ if (isCapturing) return;
689
+ const key = [];
690
+ const volumes = layout.volumes.map((volume) => {
691
+ const candidate = candidates[volume.index];
692
+ if (candidate !== void 0) key.push(candidate.binding, candidate.generation, candidate.blendDistance);
693
+ return {
694
+ environment: candidate?.binding.environment ?? null,
695
+ position: volume.position,
696
+ outer: volume.outer,
697
+ inner: volume.inner
698
+ };
699
+ });
700
+ if (sameKey(blend?.key ?? null, key) || sameKey(refusedKey, key)) return;
701
+ const ready = volumes.filter((volume) => volume.environment !== null);
702
+ try {
703
+ const created = createLiteProbeSet(engine, scene, ready, layout.minimum, layout.maximum, layout.cellSize, warnLeakOnce);
704
+ dropBlend();
705
+ blend = {
706
+ lite: created,
707
+ key
708
+ };
709
+ refusedKey = null;
710
+ } catch (error) {
711
+ dropBlend();
712
+ refusedKey = key;
713
+ if (!hasWarnedRefusal) {
714
+ hasWarnedRefusal = true;
715
+ warn(`The reflection probes cannot blend (${error instanceof Error ? error.message : String(error)}), so each material reflects its nearest probe. Lite blends at most four overlapping probes.`);
716
+ }
717
+ }
718
+ };
719
+ /** Hands every material back to the scene environment, without walking the scene. */
720
+ const clearMaterials = () => {
721
+ for (const [material, binding] of assigned) if (binding !== null) assign(material, null);
722
+ assigned.clear();
723
+ };
724
+ const assignMaterials = () => {
725
+ if (candidates.length === 0) {
726
+ clearMaterials();
727
+ return;
728
+ }
729
+ seen.clear();
730
+ const blended = blend?.lite ?? null;
731
+ forEachReflectiveMesh(scene, (material, x, y, z) => {
732
+ if (seen.has(material)) return;
733
+ seen.add(material);
734
+ const chosen = candidates[selectReflectionProbe(x, y, z, candidates)];
735
+ const binding = blended !== null && chosen?.box !== null ? blended : chosen?.binding ?? null;
736
+ const current = assigned.get(material);
737
+ if (current === binding || current === void 0 && binding === null) return;
738
+ assigned.set(material, binding);
739
+ assign(material, binding);
740
+ });
741
+ };
742
+ return {
743
+ update(world, probes, isHdr, tier, hasEnvironment) {
744
+ if (isDeviceLost) return;
745
+ candidates.length = 0;
746
+ if (!hasEnvironment) {
747
+ for (const [probe, state] of states) release(probe, state);
748
+ dropBlend();
749
+ clearMaterials();
750
+ retire();
751
+ return;
752
+ }
753
+ const maxSize = tier?.reflectionProbeMaxSize;
754
+ const allowsEveryFrame = tier?.reflectionProbeEveryFrame ?? true;
755
+ for (const [probe, state] of states) if (!probes.includes(probe) || resolveReflectionProbeSize(probe.size, maxSize) !== state.lite.size) release(probe, state);
756
+ for (const probe of probes) {
757
+ const wantsRefresh = probe.consumeRefreshRequest();
758
+ if (!probe.isEnabledInHierarchy) continue;
759
+ const mode = resolveReflectionProbeRefreshMode(probe.refreshMode, allowsEveryFrame);
760
+ if (mode !== probe.refreshMode && !hasWarnedEveryFrame) {
761
+ hasWarnedEveryFrame = true;
762
+ warn(`${JSON.stringify(probe.entity.name)} asks its ReflectionProbe for refreshMode "everyFrame", which only the "high" rendering.quality tier allows, so it captures as "once" (when ready and on refresh()).`);
763
+ }
764
+ let state = states.get(probe);
765
+ if (state === void 0) {
766
+ if (mode === "onDemand" && !wantsRefresh && !recapture.has(probe)) continue;
767
+ recapture.delete(probe);
768
+ state = {
769
+ lite: createLiteReflectionProbe(engine, scene, resolveReflectionProbeSize(probe.size, maxSize), EDITOR_ONLY_METADATA_KEY, cullingFilter(world, probe)),
770
+ framesToCapture: CAPTURE_FRAMES,
771
+ binding: null,
772
+ generation: 0,
773
+ blendDistance: probe.blendDistance,
774
+ stillFrames: 0
775
+ };
776
+ states.set(probe, state);
777
+ }
778
+ state.lite.resolve(!isHdr);
779
+ const matrix = probe.entity.transform.worldMatrix;
780
+ const x = matrix[12] ?? 0;
781
+ const y = matrix[13] ?? 0;
782
+ const z = matrix[14] ?? 0;
783
+ if (wantsRefresh) state.framesToCapture = CAPTURE_FRAMES;
784
+ if ((state.framesToCapture > 0 || mode === "everyFrame") && state.lite.capture(x, y, z, probe.near, probe.far)) {
785
+ state.framesToCapture = Math.max(0, state.framesToCapture - 1);
786
+ state.generation += 1;
787
+ }
788
+ const environment = state.lite.environment;
789
+ if (environment === null) continue;
790
+ const box = probe.boxProjection;
791
+ const binding = bindingFor(state.binding, environment, x, y, z, box);
792
+ state.stillFrames = binding === state.binding && probe.blendDistance === state.blendDistance ? state.stillFrames + 1 : 0;
793
+ state.binding = binding;
794
+ state.blendDistance = probe.blendDistance;
795
+ candidates.push({
796
+ x,
797
+ y,
798
+ z,
799
+ box,
800
+ binding,
801
+ blendDistance: probe.blendDistance,
802
+ generation: state.generation,
803
+ isCapturing: state.framesToCapture > 0,
804
+ isEveryFrame: mode === "everyFrame",
805
+ isMoving: state.stillFrames < BLEND_STILL_FRAMES
806
+ });
807
+ }
808
+ updateBlend(mayBlend(candidates) ? reflectionProbeBlendLayout(candidates) : null);
809
+ assignMaterials();
810
+ retire();
811
+ },
812
+ handleDeviceLost() {
813
+ isDeviceLost = true;
814
+ blend?.lite.dispose();
815
+ blend = null;
816
+ refusedKey = null;
817
+ for (const set of retiringSets) set.dispose();
818
+ retiringSets.length = 0;
819
+ for (const [material, binding] of assigned) if (binding !== null) assignReflectionProbe(null, material, null);
820
+ assigned.clear();
821
+ for (const [probe, state] of states) {
822
+ if (state.lite.environment !== null || state.framesToCapture > 0) recapture.add(probe);
823
+ state.lite.dispose();
824
+ }
825
+ states.clear();
826
+ for (const entry of retiring) entry.lite.dispose();
827
+ retiring.length = 0;
828
+ rebuilds.clear();
829
+ },
830
+ handleDeviceRecovered() {
831
+ isDeviceLost = false;
832
+ },
833
+ dispose() {
834
+ for (const [probe, state] of states) release(probe, state);
835
+ dropBlend();
836
+ clearMaterials();
837
+ const settled = Promise.allSettled(rebuilds);
838
+ for (const entry of retiring) entry.lite.dispose(settled);
839
+ retiring.length = 0;
840
+ for (const set of retiringSets) set.dispose(settled);
841
+ retiringSets.length = 0;
842
+ rebuilds.clear();
843
+ }
844
+ };
845
+ }
846
+ /**
847
+ * Whether a frame's probes can blend at all, checked without allocating: two box probes, one with a
848
+ * `blendDistance`.
849
+ *
850
+ * @param candidates - The frame's candidates.
851
+ * @returns `true` when {@link reflectionProbeBlendLayout} is worth calling.
852
+ */
853
+ function mayBlend(candidates) {
854
+ let boxes = 0;
855
+ let blends = false;
856
+ for (const candidate of candidates) if (candidate.box !== null) {
857
+ boxes += 1;
858
+ blends ||= candidate.blendDistance > 0;
859
+ }
860
+ return boxes >= 2 && blends;
861
+ }
862
+ /**
863
+ * Whether two set keys are equal, element by element.
864
+ *
865
+ * @param a - A key, or `null`.
866
+ * @param b - Another key.
867
+ * @returns `true` when both have the same elements.
868
+ */
869
+ function sameKey(a, b) {
870
+ return a !== null && a.length === b.length && a.every((value, index) => value === b[index]);
871
+ }
872
+ /**
873
+ * Builds the mesh filter of a probe's capture: with a non-empty `cullingMask`, only meshes whose
874
+ * entity is on one of its layers.
875
+ *
876
+ * @param world - The world, for the handle and layer tables.
877
+ * @param probe - The probe; its mask is read on every call, so edits apply to the next capture.
878
+ * @returns The filter.
879
+ */
880
+ function cullingFilter(world, probe) {
881
+ return (tag) => {
882
+ const mask = probe.cullingMask;
883
+ if (mask.length === 0) return true;
884
+ const entity = tag === null ? null : world.getEntityByHandle(toEntityHandle(tag.entity));
885
+ if (entity === null) return false;
886
+ for (const name of mask) if (world.layers.indexOf(name) === entity.layer) return true;
887
+ return false;
888
+ };
889
+ }
890
+ /**
891
+ * The binding a probe's materials use: the previous one while nothing it holds changed, so a still
892
+ * probe never rebuilds its materials.
893
+ *
894
+ * @param previous - The binding last used, or `null`.
895
+ * @param environment - The probe's environment.
896
+ * @param x - The probe's world X.
897
+ * @param y - The probe's world Y.
898
+ * @param z - The probe's world Z.
899
+ * @param box - The projection box size, or `null`.
900
+ * @returns The binding.
901
+ */
902
+ function bindingFor(previous, environment, x, y, z, box) {
903
+ if (previous !== null && previous.environment === environment && previous.position[0] === x && previous.position[1] === y && previous.position[2] === z && (box === null ? previous.box === null : previous.box !== null && previous.box[0] === box.x && previous.box[1] === box.y && previous.box[2] === box.z)) return previous;
904
+ return {
905
+ environment,
906
+ position: [
907
+ x,
908
+ y,
909
+ z
910
+ ],
911
+ box: box === null ? null : [
912
+ box.x,
913
+ box.y,
914
+ box.z
915
+ ]
916
+ };
917
+ }
918
+ //#endregion
919
+ export { createReflectionProbeRuntime };
920
+
921
+ //# sourceMappingURL=reflection-probes-CAzSuqf8.js.map