@ignifx/core 0.16.0 → 0.18.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 (58) hide show
  1. package/dist/{environment-DPi0_0SP.js → environment-DZ6WUHbm.js} +2 -2
  2. package/dist/{environment-DPi0_0SP.js.map → environment-DZ6WUHbm.js.map} +1 -1
  3. package/dist/{hdr-output-BrUvpAsE.js → hdr-output-Dbv0lhFl.js} +4 -3
  4. package/dist/{hdr-output-BrUvpAsE.js.map → hdr-output-Dbv0lhFl.js.map} +1 -1
  5. package/dist/{ignifx-error-oYdVnT1S.js → ignifx-error-B8ByiSfJ.js} +16 -1
  6. package/dist/ignifx-error-B8ByiSfJ.js.map +1 -0
  7. package/dist/index.d.ts +128 -14654
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +1501 -4037
  10. package/dist/index.js.map +1 -1
  11. package/dist/{instanced-mesh-instance-NnODkvqK.js → instanced-mesh-instance-BMhREEfx.js} +3 -2
  12. package/dist/{instanced-mesh-instance-NnODkvqK.js.map → instanced-mesh-instance-BMhREEfx.js.map} +1 -1
  13. package/dist/light-probe-asset-B60_X-yN.js +331 -0
  14. package/dist/light-probe-asset-B60_X-yN.js.map +1 -0
  15. package/dist/light-probes-DkYN89Qw.js +284 -0
  16. package/dist/light-probes-DkYN89Qw.js.map +1 -0
  17. package/dist/{material-plugin-BUlqLsap.js → material-plugin-CiAmriQ_.js} +2 -2
  18. package/dist/{material-plugin-BUlqLsap.js.map → material-plugin-CiAmriQ_.js.map} +1 -1
  19. package/dist/node-DznSvwap.js +301 -0
  20. package/dist/node-DznSvwap.js.map +1 -0
  21. package/dist/{post-effect-BHl7U56q.js → post-effect-CQnlX1RH.js} +3 -30
  22. package/dist/post-effect-CQnlX1RH.js.map +1 -0
  23. package/dist/{post-effect-compiler-CRek8VxQ.js → post-effect-compiler-C_7HTHZy.js} +3 -3
  24. package/dist/{post-effect-compiler-CRek8VxQ.js.map → post-effect-compiler-C_7HTHZy.js.map} +1 -1
  25. package/dist/prefab-overrides-BLQn5yHS.d.ts +15149 -0
  26. package/dist/prefab-overrides-BLQn5yHS.d.ts.map +1 -0
  27. package/dist/prefab-overrides-DT-wHHAJ.js +2396 -0
  28. package/dist/prefab-overrides-DT-wHHAJ.js.map +1 -0
  29. package/dist/prefab.d.ts +2 -0
  30. package/dist/prefab.js +2 -0
  31. package/dist/reflection-probe-DlVsl3zJ.js +1883 -0
  32. package/dist/reflection-probe-DlVsl3zJ.js.map +1 -0
  33. package/dist/reflection-probes-B8S9WnVX.js +551 -0
  34. package/dist/reflection-probes-B8S9WnVX.js.map +1 -0
  35. package/dist/{render-path-Be7WgN7r.js → render-path-D11i_7X8.js} +3 -2
  36. package/dist/{render-path-Be7WgN7r.js.map → render-path-D11i_7X8.js.map} +1 -1
  37. package/dist/{render-texture-C_TnaSz2.js → render-texture-UqRHRLQy.js} +15 -2
  38. package/dist/{render-texture-C_TnaSz2.js.map → render-texture-UqRHRLQy.js.map} +1 -1
  39. package/dist/rolldown-runtime-D7D4PA-g.js +13 -0
  40. package/dist/{scene-color-passes-DlNr-qyZ.js → scene-color-passes-B93qTOka.js} +35 -12
  41. package/dist/scene-color-passes-B93qTOka.js.map +1 -0
  42. package/dist/{shader-material-B6p66wB8.js → shader-material-C2_UCYdO.js} +6 -17
  43. package/dist/{shader-material-B6p66wB8.js.map → shader-material-C2_UCYdO.js.map} +1 -1
  44. package/dist/{shader-material-C0TAUr4t.js → shader-material-CaAkv5nT.js} +2 -2
  45. package/dist/{shader-material-C0TAUr4t.js.map → shader-material-CaAkv5nT.js.map} +1 -1
  46. package/dist/{shader-pragma-BKCoZTTA.js → shader-pragma-DmZpxGUo.js} +2 -2
  47. package/dist/{shader-pragma-BKCoZTTA.js.map → shader-pragma-DmZpxGUo.js.map} +1 -1
  48. package/dist/{surface-shader-BaK0kvBB.js → surface-shader-BeDRofOV.js} +4 -4
  49. package/dist/{surface-shader-BaK0kvBB.js.map → surface-shader-BeDRofOV.js.map} +1 -1
  50. package/dist/{vec3-D-0Y2mzE.js → vec3-Cc19wl4r.js} +3 -300
  51. package/dist/vec3-Cc19wl4r.js.map +1 -0
  52. package/package.json +8 -4
  53. package/dist/ignifx-error-oYdVnT1S.js.map +0 -1
  54. package/dist/json-CzZZ6K4x.js +0 -24
  55. package/dist/json-CzZZ6K4x.js.map +0 -1
  56. package/dist/post-effect-BHl7U56q.js.map +0 -1
  57. package/dist/scene-color-passes-DlNr-qyZ.js.map +0 -1
  58. package/dist/vec3-D-0Y2mzE.js.map +0 -1
@@ -1,4 +1,5 @@
1
- import { A as setMeshReceiveShadows, D as setMeshId, E as setMeshBounds, M as setMeshSubtreeVisible, O as setMeshMaterial, T as removeMeshFromScene, Y as tagNode, d as cloneMeshUnderNode, j as setMeshRenderOrder, k as setMeshPickable, l as Vec3, u as addMeshToScene, x as detachMeshBounds } from "./vec3-D-0Y2mzE.js";
1
+ import { p as tagNode } from "./node-DznSvwap.js";
2
+ import { A as setMeshReceiveShadows, D as setMeshId, E as setMeshBounds, M as setMeshSubtreeVisible, O as setMeshMaterial, T as removeMeshFromScene, d as cloneMeshUnderNode, j as setMeshRenderOrder, k as setMeshPickable, l as Vec3, u as addMeshToScene, x as detachMeshBounds } from "./vec3-Cc19wl4r.js";
2
3
  import { clearThinInstanceLodPartner, enableThinInstanceDynamicDrawCount, enableThinInstanceGpuCulling, enableThinInstanceWorldBounds, flushThinInstances, setThinInstanceColors, setThinInstanceCount, setThinInstanceCullBoundsPad, setThinInstanceDrawCount, setThinInstanceLodPartner, setThinInstances } from "@babylonjs/lite";
3
4
  //#region src/lite/gpu/thin-instances.ts
4
5
  /**
@@ -762,4 +763,4 @@ function asMesh(node) {
762
763
  //#endregion
763
764
  export { InstancedMeshInstance, createInstancedMesh, releaseInstancedMesh };
764
765
 
765
- //# sourceMappingURL=instanced-mesh-instance-NnODkvqK.js.map
766
+ //# sourceMappingURL=instanced-mesh-instance-BMhREEfx.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"instanced-mesh-instance-NnODkvqK.js","names":["setThinInstances","setThinInstanceCount","flushThinInstances","setThinInstanceColors","enableThinInstanceGpuCulling","setThinInstanceCullBoundsPad","enableThinInstanceWorldBounds","enableThinInstanceDynamicDrawCount","setThinInstanceLodPartner","clearThinInstanceLodPartner"],"sources":["../src/lite/gpu/thin-instances.ts","../src/render/gpu/instanced-mesh-instance.ts"],"sourcesContent":["import {\n clearThinInstanceLodPartner as liteClearThinInstanceLodPartner,\n enableThinInstanceDynamicDrawCount as liteEnableThinInstanceDynamicDrawCount,\n enableThinInstanceGpuCulling as liteEnableThinInstanceGpuCulling,\n enableThinInstanceWorldBounds as liteEnableThinInstanceWorldBounds,\n flushThinInstances as liteFlushThinInstances,\n setThinInstanceColors as liteSetThinInstanceColors,\n setThinInstanceCount as liteSetThinInstanceCount,\n setThinInstanceCullBoundsPad as liteSetThinInstanceCullBoundsPad,\n setThinInstanceDrawCount as liteSetThinInstanceDrawCount,\n setThinInstanceLodPartner as liteSetThinInstanceLodPartner,\n setThinInstances as liteSetThinInstances,\n} from \"@babylonjs/lite\";\nimport type { Mesh } from \"@babylonjs/lite\";\n\n/**\n * Thin-instance half of the Babylon Lite adapter (`docs/architecture/07-rendering.md` §2.3,\n * `docs/plan/2026-09-terrain-particles-shaders.md` §3.5). Everything here is `@internal` and needs a\n * WebGPU device, so the browser project is what covers it.\n *\n * Lite fixes the order these must be called in, and both the culling opt-in and the LOD pairing only\n * take effect through the renderable `registerScene` compiles:\n *\n * 1. {@link setThinInstances} — its `count` argument becomes `_capacity`, and the GPU buffer is\n * sized `_capacity * 64` bytes for the life of the mesh, so pass the **capacity** here once and\n * lower the active count with {@link setThinInstanceCount} straight afterwards.\n * 2. {@link enableThinInstanceWorldBounds} — gives the scene AABB the cloud rather than the\n * prototype. It does not fix a shadow frustum: `computeDirectionalLightMatrix` reads\n * `boundMin`/`boundMax` directly (`lib/shadow/shadow-base.js` 54).\n * 3. {@link enableThinInstanceGpuCulling} — compute-based, opaque only.\n * 4. {@link enableThinInstanceDynamicDrawCount} — indirect draw arguments, so a later count change\n * keeps the cached bundle valid.\n * 5. {@link setThinInstanceLodPartner} — needs both meshes instanced already and stamps both\n * `_clone`, so neither can be cloned afterwards.\n * 6. `addMeshToScene`, and only then `registerScene`.\n *\n * Moving instances costs three different amounts (`lib/mesh/thin-instance.js`):\n * {@link flushThinInstances} re-uploads the whole active range and is the only sub-range-free path\n * Lite exposes; {@link setThinInstanceCount} re-uploads as well; {@link setThinInstanceDrawCount}\n * uploads nothing but throws until the pool has completed one GPU synchronisation, which is private\n * state — {@link trySetThinInstanceDrawCount} asks by trying.\n */\n\n/**\n * Points a mesh at a matrix slab and fixes its capacity.\n *\n * @remarks\n * The `capacity` argument is written straight to Lite's `_capacity`, which sizes the GPU buffer\n * (`_capacity * 64` bytes) once and for good. Only the first `count` matrices are ever read from\n * `matrices`, and Lite clamps its dirty range to the active count\n * (`lib/mesh/thin-instance-gpu.js`), so a slab shorter than `capacity * 16` floats is safe as long\n * as the active count is lowered with {@link setThinInstanceCount} before the next frame.\n *\n * Lite keeps the array by reference and never copies it: the caller owns it, and mutating it is the\n * intended way to move instances, followed by {@link flushThinInstances}.\n *\n * @param mesh - The mesh to instance.\n * @param matrices - 16 floats per instance, column-major, caller-owned.\n * @param capacity - The largest instance count this mesh will ever draw.\n *\n * @internal\n */\nexport function setThinInstances(mesh: Mesh, matrices: Float32Array, capacity: number): void {\n liteSetThinInstances(mesh, matrices, capacity);\n}\n\n/**\n * Sets how many instances draw, re-uploading the active range.\n *\n * @remarks\n * Prefer {@link trySetThinInstanceDrawCount} for a per-frame change: this one marks `[0, count)`\n * dirty as well, so it costs a `count * 64`-byte upload.\n *\n * @param mesh - The instanced mesh.\n * @param count - The active count, at most the capacity.\n *\n * @internal\n */\nexport function setThinInstanceCount(mesh: Mesh, count: number): void {\n liteSetThinInstanceCount(mesh, count);\n}\n\n/**\n * Sets how many instances draw without re-uploading anything, when Lite accepts it.\n *\n * @remarks\n * Lite requires the pool to have completed one full-capacity GPU synchronisation first and throws\n * otherwise (`lib/mesh/thin-instance.js`, `ThrowLiteError(369)`); the state it checks — the matrix\n * buffer's existence and its version — is private, so the only way to ask is to call. The throw\n * happens before anything is mutated, so a refusal leaves the mesh untouched and the caller can\n * fall back to {@link setThinInstanceCount}.\n *\n * @param mesh - The instanced mesh.\n * @param count - The active count, at most the capacity.\n * @returns `true` when the count was changed, `false` when Lite is not ready for a bare count\n * change yet.\n *\n * @internal\n */\nexport function trySetThinInstanceDrawCount(mesh: Mesh, count: number): boolean {\n try {\n liteSetThinInstanceDrawCount(mesh, count);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Marks the whole active matrix range dirty, after the caller mutated the slab in place.\n *\n * @param mesh - The instanced mesh.\n *\n * @internal\n */\nexport function flushThinInstances(mesh: Mesh): void {\n liteFlushThinInstances(mesh);\n}\n\n/**\n * Installs, replaces, or removes the per-instance RGBA colours.\n *\n * @remarks\n * Lite exports no way to *remove* colours: `setThinInstanceColors` only assigns, and the colour\n * version counters that drive the upload are private. `ThinInstanceData.colors` is declared\n * optional and mutable (`index.d.ts` 12985), so clearing is a direct field write —\n * which is enough, because `syncThinInstanceGpuData` skips the colour upload entirely while\n * `colors` is null, and the renderable rebuild the caller triggers is what drops\n * `useThinInstanceColors` from the compiled pipeline.\n *\n * @param mesh - The instanced mesh.\n * @param colors - Four floats per instance (linear RGBA), or `null` to stop reading colours.\n *\n * @internal\n */\nexport function setThinInstanceColors(mesh: Mesh, colors: Float32Array | null): void {\n if (colors !== null) {\n liteSetThinInstanceColors(mesh, colors);\n return;\n }\n const data = mesh.thinInstances;\n if (data !== null && data !== undefined) {\n data.colors = null;\n }\n}\n\n/**\n * Turns compute-based GPU frustum culling on or off for an instanced mesh.\n *\n * @remarks\n * Opaque meshes only, and it must run after {@link setThinInstances} and before the scene is\n * registered.\n *\n * @param mesh - The instanced mesh.\n * @param enabled - Whether the culling compute pass runs.\n *\n * @internal\n */\nexport function enableThinInstanceGpuCulling(mesh: Mesh, enabled: boolean): void {\n liteEnableThinInstanceGpuCulling(mesh, enabled);\n}\n\n/**\n * Grows every instance's GPU-culling sphere by a world-space distance.\n *\n * @remarks\n * The culler builds each sphere from the prototype's vertices (`lib/mesh/thin-instance-gpu-culling.js`\n * 426), so a vertex stage that moves an instance outside it gets the instance culled while it is\n * still on screen. Lite reads the pad on every culled pass (`index.d.ts` 11232), so it can change\n * live. Needs {@link setThinInstances} first.\n *\n * @param mesh - The instanced mesh that owns the culling pass.\n * @param pad - The extra radius in world units; `0` is the exact sphere.\n *\n * @internal\n */\nexport function setThinInstanceCullBoundsPad(mesh: Mesh, pad: number): void {\n liteSetThinInstanceCullBoundsPad(mesh, pad);\n}\n\n/**\n * Makes a mesh's world bounds the union of its instances' boxes rather than the prototype's own.\n *\n * @remarks\n * The hook it installs is `O(count)` per bounds computation, and it clamps to\n * `matrices.length / 16`, so a short slab cannot walk off the end. It is read by\n * `expandWorldAabbForMesh` — the scene camera's extent and PBR's scene-size probe — and **not** by\n * the directional shadow fit; see the module note.\n *\n * @param mesh - The instanced mesh.\n *\n * @internal\n */\nexport function enableThinInstanceWorldBounds(mesh: Mesh): void {\n liteEnableThinInstanceWorldBounds(mesh);\n}\n\n/**\n * Opts a fixed-capacity pool into indirect draw arguments, so a later count change keeps the\n * cached render bundle valid.\n *\n * @param mesh - The instanced mesh.\n *\n * @internal\n */\nexport function enableThinInstanceDynamicDrawCount(mesh: Mesh): void {\n liteEnableThinInstanceDynamicDrawCount(mesh);\n}\n\n/**\n * Where a LOD pairing switches, and how softly.\n *\n * @internal\n */\nexport interface ThinInstanceLodOptions {\n /** The camera distance, in world units, at which an in-frustum instance switches to the partner. */\n readonly distance: number;\n /** The width of the per-instance threshold dither window centred on `distance`; `0` is a hard cut. */\n readonly band: number;\n}\n\n/**\n * Pairs a GPU-culled instanced mesh with a lower-detail partner.\n *\n * @remarks\n * Both meshes must already carry thin instances, and the partner may reference the very same matrix\n * slab. While paired the partner draws **only** the far bucket, and the pairing switches its own\n * GPU culling on. Lite refuses the pairing when either mesh has more than one thin-instance owner,\n * when the partner is already paired, or when the partner carries colours the full mesh does not\n * (`ThrowLiteError(375)`, `(377)`, `(379)`). Calling it again with the same pair re-sets `distance`\n * and `band` live.\n *\n * @param fullMesh - The near mesh, which owns the culling pass.\n * @param lodMesh - The far mesh.\n * @param options - Where the switch happens, and how softly.\n *\n * @internal\n */\nexport function setThinInstanceLodPartner(fullMesh: Mesh, lodMesh: Mesh, options: ThinInstanceLodOptions): void {\n liteSetThinInstanceLodPartner(fullMesh, lodMesh, { distance: options.distance, band: options.band });\n}\n\n/**\n * Dissolves a LOD pairing, returning both meshes to independent rendering.\n *\n * @remarks\n * A no-op when the mesh is not paired, so it is safe on the teardown path.\n *\n * @param fullMesh - The near mesh of the pair.\n *\n * @internal\n */\nexport function clearThinInstanceLodPartner(fullMesh: Mesh): void {\n liteClearThinInstanceLodPartner(fullMesh);\n}\n\n/**\n * How many instances a mesh is currently drawing, as Lite sees it.\n *\n * @remarks\n * The browser tests assert against Lite's own state rather than against the component's copy of it,\n * which is the only way to prove the two agree.\n *\n * @param mesh - The mesh to read.\n * @returns The active count, or `0` when the mesh carries no thin instances.\n *\n * @internal\n */\nexport function thinInstanceCount(mesh: Mesh): number {\n return mesh.thinInstances?.count ?? 0;\n}\n","import {\n addMeshToScene,\n cloneMeshUnderNode,\n detachMeshBounds,\n removeMeshFromScene,\n setMeshBounds,\n setMeshId,\n setMeshMaterial,\n setMeshPickable,\n setMeshReceiveShadows,\n setMeshRenderOrder,\n setMeshSubtreeVisible,\n} from \"../../lite/gpu/mesh.js\";\nimport {\n clearThinInstanceLodPartner,\n enableThinInstanceDynamicDrawCount,\n enableThinInstanceGpuCulling,\n enableThinInstanceWorldBounds,\n flushThinInstances,\n setThinInstanceColors,\n setThinInstanceCount,\n setThinInstanceCullBoundsPad,\n setThinInstanceLodPartner,\n setThinInstances,\n trySetThinInstanceDrawCount,\n} from \"../../lite/gpu/thin-instances.js\";\nimport { tagNode } from \"../../lite/node.js\";\nimport { Vec3 } from \"../../math/vec3.js\";\nimport type { LiteMesh } from \"../../lite/gpu/mesh.js\";\nimport type { LiteMaterial } from \"../../lite/material.js\";\nimport type { LiteSceneNode, NodeTag } from \"../../lite/node.js\";\nimport type { LiteScene } from \"../../lite/scene.js\";\nimport type { Transform } from \"../../transform/transform.js\";\n\n/**\n * One `InstancedMeshRenderer`'s near mesh and its optional LOD partner, and everything that writes\n * to them (`docs/plan/2026-09-terrain-particles-shaders.md` §3.5).\n *\n * Every line needs a WebGPU device, which is why it sits in `src/render/gpu/` — excluded from the\n * Node coverage floor and measured by the browser project — and why the component reaches it through\n * a dynamic `import()` (`../instanced-mesh-support.ts`).\n *\n * `capacity`, `gpuCulling` and the partner's identity are constructor arguments rather than `apply*`\n * methods because Lite fixes all three at `registerScene`; `distance` and `band` may be re-set live\n * by calling the pairing again. Both meshes share one matrix slab, which the pairing requires: it\n * compacts the near mesh's culling output into two buckets drawn from the same matrices.\n *\n * Bounds are the one thing an instanced caster needs that a plain mesh does not.\n * `computeDirectionalLightMatrix` composes `mesh.worldMatrix × mesh.boundMin/boundMax` directly\n * (`lib/shadow/shadow-base.js` 54) and never consults the `_expandWorldBounds` hook\n * `enableThinInstanceWorldBounds` installs, so a cloud left at its prototype's box casts nothing\n * (measured on SwiftShader, 2026-09-08). {@link InstancedMeshInstance.applyBounds} publishes the\n * union of the live placements instead; culling accuracy is unaffected because each instance's cull\n * sphere comes from the real vertices (`lib/mesh/thin-instance-gpu-culling.js` 426).\n */\n\n/** What the component remembers between uploads. Mutated in place, so a frame allocates nothing. */\nexport interface InstancedUploadState {\n /** The whole slab has to be re-pointed and re-uploaded. */\n isSlabDirty: boolean;\n /** The caller mutated the slab in place, so the active range has to be re-uploaded. */\n isRangeDirty: boolean;\n /** The count the meshes were last told about. */\n appliedCount: number;\n /** The capacity the meshes were built with. */\n appliedCapacity: number;\n /** Whether the union bounds have been published at least once. */\n hasAppliedBounds: boolean;\n /** Whether the last upload carried a colour slab. */\n hadColors: boolean;\n}\n\n/** The LOD switch the component declares, as much of it as the adapter reads. */\nexport interface InstancedLodFields {\n /** The camera distance at which an instance switches to the partner. */\n readonly distance: number;\n /** The width of the per-instance dither window. */\n readonly band: number;\n}\n\n/** The LOD partner an instance is built with. */\nexport interface InstancedLodConfig {\n /** The coarse template to clone. */\n readonly template: LiteMesh;\n /** The camera distance, in world units, at which an instance switches to the partner. */\n readonly distance: number;\n /** The width of the per-instance dither window centred on `distance`. */\n readonly band: number;\n}\n\n/** The settings Lite fixes when the meshes are built. */\nexport interface InstancedMeshSettings {\n /** The largest instance count the meshes will ever draw. */\n readonly capacity: number;\n /** Whether the compute culling pass runs. */\n readonly gpuCulling: boolean;\n /** The LOD partner, or `null`. */\n readonly lod: InstancedLodConfig | null;\n}\n\n/**\n * A live instanced mesh, and its LOD partner, in a scene.\n *\n * @internal\n */\nexport class InstancedMeshInstance {\n /** The cloned near mesh, parented under the entity's node. */\n readonly clone: LiteSceneNode;\n\n readonly #lod: LiteSceneNode | null;\n\n #material: LiteMaterial;\n\n #receiveShadows: boolean | null = null;\n\n #renderOrder = Number.NaN;\n\n #pickable: boolean | null = null;\n\n #visible = false;\n\n #lodDistance: number;\n\n #lodBand: number;\n\n readonly #nearBox: Float64Array;\n\n readonly #lodBox: Float64Array | null;\n\n readonly #union = new Float64Array(6);\n\n /** The world-space displacement the culling pad and the bounds were last widened by. */\n #displacement = 0;\n\n /** The same displacement in object units, per axis, as the published bounds carry it. */\n readonly #margin = new Vec3();\n\n /** Scratch for the entity's world scale. */\n readonly #scale = new Vec3();\n\n /**\n * Clones the templates, gives them thin instances, applies the baked settings in Lite's required\n * order, and adds them to the scene.\n *\n * @param scene - The render scene.\n * @param template - The near mesh's template.\n * @param parent - The entity's transform node.\n * @param tag - The owning entity and component, for picking.\n * @param meshId - The string id Lite's light include/exclude sets match on.\n * @param material - The material both meshes draw with. Assigned **before** the meshes join the\n * scene, for the reason `MeshInstance`'s constructor records: `addToScene` buckets a mesh by its\n * material's build group.\n * @param settings - Capacity, GPU culling, and the LOD pairing.\n * @param matrices - The matrix slab, caller-owned and never copied.\n * @param count - How many instances draw.\n * @param colors - Four floats per instance, or `null`.\n */\n constructor(\n scene: LiteScene,\n template: LiteMesh,\n parent: LiteSceneNode,\n tag: NodeTag,\n meshId: string,\n material: LiteMaterial,\n settings: InstancedMeshSettings,\n matrices: Float32Array,\n count: number,\n colors: Float32Array | null,\n ) {\n const clone = cloneMeshUnderNode(template, parent);\n tagNode(clone, tag);\n const mesh = asMesh(clone);\n setMeshId(mesh, meshId);\n setMeshMaterial(mesh, material);\n // A clone shares the template's bound arrays, and `applyBounds` mutates them in place.\n detachMeshBounds(mesh);\n this.#nearBox = readBox(mesh);\n installThinInstances(mesh, settings.capacity, matrices, count, colors);\n enableThinInstanceGpuCulling(mesh, settings.gpuCulling);\n enableThinInstanceDynamicDrawCount(mesh);\n\n const lodConfig = settings.lod;\n let lodClone: LiteSceneNode | null = null;\n let lodBox: Float64Array | null = null;\n if (lodConfig !== null) {\n lodClone = cloneMeshUnderNode(lodConfig.template, parent);\n tagNode(lodClone, tag);\n const lodMesh = asMesh(lodClone);\n setMeshId(lodMesh, `${meshId}#lod`);\n setMeshMaterial(lodMesh, material);\n detachMeshBounds(lodMesh);\n lodBox = readBox(lodMesh);\n installThinInstances(lodMesh, settings.capacity, matrices, count, colors);\n setThinInstanceLodPartner(mesh, lodMesh, { distance: lodConfig.distance, band: lodConfig.band });\n }\n this.#lodBox = lodBox;\n\n this.#material = material;\n this.#lodDistance = lodConfig?.distance ?? 0;\n this.#lodBand = lodConfig?.band ?? 0;\n // Hidden until the first `applyVisible`, so a renderer on an inactive entity never flashes.\n setMeshSubtreeVisible(clone, false);\n addMeshToScene(scene, clone);\n if (lodClone !== null) {\n setMeshSubtreeVisible(lodClone, false);\n addMeshToScene(scene, lodClone);\n }\n this.clone = clone;\n this.#lod = lodClone;\n }\n\n /**\n * Whether the meshes are currently drawn.\n *\n * @returns `true` when Lite's `visible` is set on them.\n */\n get isVisible(): boolean {\n return this.#visible;\n }\n\n /**\n * The near mesh.\n *\n * @returns The clone, typed as a mesh.\n */\n get mesh(): LiteMesh {\n return asMesh(this.clone);\n }\n\n /**\n * The LOD partner.\n *\n * @returns The partner clone, or `null` when the renderer declares no LOD.\n */\n get lodMesh(): LiteMesh | null {\n const lod = this.#lod;\n return lod === null ? null : asMesh(lod);\n }\n\n /**\n * Assigns the material to both meshes, when it changed.\n *\n * @param material - The Lite material to draw with.\n */\n applyMaterial(material: LiteMaterial): void {\n if (material === this.#material) {\n return;\n }\n this.#material = material;\n setMeshMaterial(this.mesh, material);\n const lod = this.lodMesh;\n if (lod !== null) {\n setMeshMaterial(lod, material);\n }\n }\n\n /**\n * Writes the per-mesh flags that changed, to both meshes.\n *\n * @param receiveShadows - Whether shadow maps darken the meshes.\n * @param renderOrder - The sort key within the phase.\n * @param pickable - Whether picking considers the meshes at all.\n */\n applyFlags(receiveShadows: boolean, renderOrder: number, pickable: boolean): void {\n if (this.#receiveShadows !== receiveShadows) {\n this.#receiveShadows = receiveShadows;\n this.#eachMesh(setMeshReceiveShadows, receiveShadows);\n }\n if (this.#renderOrder !== renderOrder) {\n this.#renderOrder = renderOrder;\n this.#eachMesh(setMeshRenderOrder, renderOrder);\n }\n if (this.#pickable !== pickable) {\n this.#pickable = pickable;\n this.#eachMesh(setMeshPickable, pickable);\n }\n }\n\n /**\n * Re-sets the LOD switch distance and dither band, when either changed.\n *\n * @param distance - The camera distance at which an instance switches to the partner.\n * @param band - The width of the per-instance dither window centred on `distance`.\n */\n applyLod(distance: number, band: number): void {\n const lod = this.lodMesh;\n if (lod === null || (distance === this.#lodDistance && band === this.#lodBand)) {\n return;\n }\n this.#lodDistance = distance;\n this.#lodBand = band;\n setThinInstanceLodPartner(this.mesh, lod, { distance, band });\n }\n\n /**\n * Shows or hides both meshes, when the state changed.\n *\n * @param visible - `entity.activeInHierarchy && component.enabled`.\n */\n applyVisible(visible: boolean): void {\n if (visible === this.#visible) {\n return;\n }\n this.#visible = visible;\n setMeshSubtreeVisible(this.clone, visible);\n const lod = this.#lod;\n if (lod !== null) {\n setMeshSubtreeVisible(lod, visible);\n }\n }\n\n /**\n * Re-points both meshes at a matrix slab and re-uploads the active range.\n *\n * @param capacity - The capacity the meshes were built with; re-stating it keeps `_capacity`\n * unchanged, which is what stops Lite from re-creating the GPU buffer.\n * @param matrices - The slab, caller-owned.\n * @param count - How many instances draw.\n * @param colors - Four floats per instance, or `null`.\n */\n applySlab(capacity: number, matrices: Float32Array, count: number, colors: Float32Array | null): void {\n installThinInstances(this.mesh, capacity, matrices, count, colors);\n const lod = this.lodMesh;\n if (lod !== null) {\n installThinInstances(lod, capacity, matrices, count, colors);\n }\n }\n\n /**\n * Changes how many instances draw, by the cheapest route Lite accepts.\n *\n * @param count - The active count, at most the capacity.\n */\n applyCount(count: number): void {\n applyMeshCount(this.mesh, count);\n const lod = this.lodMesh;\n if (lod !== null) {\n applyMeshCount(lod, count);\n }\n }\n\n /**\n * Marks the whole active range dirty, after the caller mutated the slab in place.\n *\n * @param colors - The colour slab, when the renderer has one, so its own dirty range moves too.\n */\n flush(colors: Float32Array | null): void {\n flushThinInstances(this.mesh);\n const lod = this.lodMesh;\n if (lod !== null) {\n flushThinInstances(lod);\n }\n if (colors !== null) {\n setThinInstanceColors(this.mesh, colors);\n if (lod !== null) {\n setThinInstanceColors(lod, colors);\n }\n }\n }\n\n /**\n * Publishes the union of the live instance placements as both meshes' object-local bounds, so a\n * directional light's shadow frustum is fitted to the cloud rather than to the prototype.\n *\n * @remarks\n * `O(count)`, allocation-free, and worth paying only for a caster — see the module note. A count\n * of zero restores the prototype's own box, so an empty cloud does not report an infinite one.\n *\n * @param matrices - The live matrix slab.\n * @param count - How many instances are drawn.\n */\n applyBounds(matrices: Float32Array, count: number): void {\n const near = this.#nearBox;\n const lodBox = this.#lodBox;\n const lod = this.lodMesh;\n const margin = this.#margin;\n if (count <= 0) {\n writeBox(this.mesh, near, margin);\n if (lod !== null && lodBox !== null) {\n writeBox(lod, lodBox, margin);\n }\n return;\n }\n const union = this.#union;\n unionOfPlacements(matrices, count, near, union);\n writeBox(this.mesh, union, margin);\n if (lod !== null && lodBox !== null) {\n unionOfPlacements(matrices, count, lodBox, union);\n writeBox(lod, union, margin);\n }\n }\n\n /**\n * Widens both meshes for a vertex stage that moves vertices up to `displacement` metres: the GPU\n * culler pads every instance's sphere, and the bounds published for a shadow frustum grow too.\n *\n * @remarks\n * The culling pad is world-space already. The bounds are object-local, so each axis is divided by\n * the entity's world scale along it. A change clears `state.hasAppliedBounds`, so the next\n * {@link InstancedMeshInstance.sync} re-publishes them.\n *\n * @param state - The component's upload state.\n * @param displacement - The material's displacement, in world metres.\n * @param transform - The entity's transform, whose world scale the meshes inherit.\n */\n applyDisplacement(state: InstancedUploadState, displacement: number, transform: Transform): void {\n if (displacement !== this.#displacement) {\n this.#displacement = displacement;\n // Only the near mesh runs the culling pass; the partner draws from its output.\n setThinInstanceCullBoundsPad(this.mesh, displacement);\n }\n const scale = this.#scale;\n if (displacement > 0) {\n transform.lossyScaleToRef(scale);\n }\n const x = objectMargin(displacement, scale.x);\n const y = objectMargin(displacement, scale.y);\n const z = objectMargin(displacement, scale.z);\n const margin = this.#margin;\n if (x !== margin.x || y !== margin.y || z !== margin.z) {\n margin.set(x, y, z);\n state.hasAppliedBounds = false;\n }\n }\n\n /**\n * Writes everything the component changed since the last frame onto both meshes.\n *\n * @param state - The component's upload state, mutated in place.\n * @param material - The material both meshes draw with.\n * @param receiveShadows - Whether shadow maps darken them.\n * @param renderOrder - The sort key within the phase.\n * @param pickable - Whether picking considers them.\n * @param lod - The LOD record, whose `distance` and `band` Lite re-applies live; `null` for none.\n * @param matrices - The caller-owned matrix slab.\n * @param count - How many instances draw.\n * @param colors - Four floats per instance, or `null`.\n * @param castShadows - Whether the union bounds have to be published for a shadow frustum.\n * @param visible - `entity.activeInHierarchy && component.enabled`.\n * @returns `true` when the compiled pipeline has to change, which only a colour slab arriving or\n * leaving does.\n */\n sync(\n state: InstancedUploadState,\n material: LiteMaterial,\n receiveShadows: boolean,\n renderOrder: number,\n pickable: boolean,\n lod: InstancedLodFields | null,\n matrices: Float32Array,\n count: number,\n colors: Float32Array | null,\n castShadows: boolean,\n visible: boolean,\n ): boolean {\n this.applyMaterial(material);\n this.applyFlags(receiveShadows, renderOrder, pickable);\n if (lod !== null) {\n this.applyLod(lod.distance, lod.band);\n }\n let renderablesChanged = false;\n let placementsMoved = false;\n if (state.isSlabDirty) {\n state.isSlabDirty = false;\n state.isRangeDirty = false;\n this.applySlab(state.appliedCapacity, matrices, count, colors);\n state.appliedCount = count;\n placementsMoved = true;\n const hasColors = colors !== null;\n renderablesChanged = hasColors !== state.hadColors;\n state.hadColors = hasColors;\n } else {\n if (state.isRangeDirty) {\n state.isRangeDirty = false;\n this.flush(colors);\n placementsMoved = true;\n }\n if (count !== state.appliedCount) {\n state.appliedCount = count;\n this.applyCount(count);\n placementsMoved = true;\n }\n }\n // Only a caster pays the `O(count)` bounds pass, and only in a frame whose placements moved.\n if (castShadows && (placementsMoved || !state.hasAppliedBounds)) {\n state.hasAppliedBounds = true;\n this.applyBounds(matrices, count);\n }\n this.applyVisible(visible);\n return renderablesChanged;\n }\n\n /**\n * Appends both meshes to a shadow caster list, when the renderer casts and they are drawn.\n *\n * @param castShadows - Whether the renderer casts.\n * @param out - The caster list being built.\n */\n collectCasters(castShadows: boolean, out: LiteMesh[]): void {\n if (!castShadows || !this.#visible) {\n return;\n }\n out.push(this.mesh);\n const lod = this.lodMesh;\n if (lod !== null) {\n out.push(lod);\n }\n }\n\n /**\n * Dissolves the LOD pairing and removes both meshes from the scene, releasing their share of the\n * templates' buffers.\n *\n * @param scene - The render scene.\n */\n destroy(scene: LiteScene): void {\n const lod = this.#lod;\n if (lod !== null) {\n clearThinInstanceLodPartner(this.mesh);\n removeMeshFromScene(scene, lod);\n }\n removeMeshFromScene(scene, this.clone);\n }\n\n /**\n * Runs a per-mesh Lite setter over the near mesh and the partner.\n *\n * @typeParam T - The setter's value type.\n * @param write - The adapter function to call.\n * @param value - What to write.\n */\n #eachMesh<T>(write: (mesh: LiteMesh, value: T) => void, value: T): void {\n write(this.mesh, value);\n const lod = this.lodMesh;\n if (lod !== null) {\n write(lod, value);\n }\n }\n}\n\n/**\n * Builds the live meshes, filling in the LOD pairing when both templates exist.\n *\n * @param scene - The render scene.\n * @param template - The near mesh's template.\n * @param lodTemplate - The coarse template, or `null`.\n * @param lod - The LOD record the component declares, or `null`.\n * @param parent - The entity's transform node.\n * @param tag - The owning entity and component, for picking.\n * @param meshId - The string id Lite's light include/exclude sets match on.\n * @param material - The material both meshes draw with.\n * @param capacity - The largest instance count the meshes will ever draw.\n * @param gpuCulling - Whether the compute culling pass runs.\n * @param matrices - The matrix slab.\n * @param count - How many instances draw.\n * @param colors - Four floats per instance, or `null`.\n * @returns The instance.\n *\n * @internal\n */\nexport function createInstancedMesh(\n scene: LiteScene,\n template: LiteMesh,\n lodTemplate: LiteMesh | null,\n lod: InstancedLodFields | null,\n parent: LiteSceneNode,\n tag: NodeTag,\n meshId: string,\n material: LiteMaterial,\n capacity: number,\n gpuCulling: boolean,\n matrices: Float32Array,\n count: number,\n colors: Float32Array | null,\n): InstancedMeshInstance {\n const pairing: InstancedLodConfig | null =\n lodTemplate === null || lod === null ? null : { template: lodTemplate, distance: lod.distance, band: lod.band };\n return new InstancedMeshInstance(\n scene,\n template,\n parent,\n tag,\n meshId,\n material,\n { capacity, gpuCulling, lod: pairing },\n matrices,\n count,\n colors,\n );\n}\n\n/**\n * Removes the meshes from the scene, when there are any.\n *\n * @param instance - The live meshes, or `null`.\n * @param scene - The render scene.\n * @returns `true` when something left the scene.\n *\n * @internal\n */\nexport function releaseInstancedMesh(instance: InstancedMeshInstance | null, scene: LiteScene): boolean {\n if (instance === null) {\n return false;\n }\n instance.destroy(scene);\n return true;\n}\n\n/**\n * Gives one mesh its thin instances in the order Lite requires, at a fixed capacity.\n *\n * @remarks\n * `setThinInstances` is handed the **capacity** so that `_capacity` — and the GPU buffer it sizes —\n * never moves; the active count is then lowered in the same breath, before any frame can read the\n * range in between (`src/lite/gpu/thin-instances.ts`).\n *\n * @param mesh - The mesh to instance.\n * @param capacity - The capacity to fix.\n * @param matrices - The slab, caller-owned.\n * @param count - How many instances draw.\n * @param colors - Four floats per instance, or `null`.\n */\nfunction installThinInstances(\n mesh: LiteMesh,\n capacity: number,\n matrices: Float32Array,\n count: number,\n colors: Float32Array | null,\n): void {\n setThinInstances(mesh, matrices, capacity);\n setThinInstanceCount(mesh, count);\n setThinInstanceColors(mesh, colors);\n enableThinInstanceWorldBounds(mesh);\n}\n\n/**\n * Changes one mesh's active count without re-uploading when Lite allows it, and with a re-upload\n * when it does not.\n *\n * @param mesh - The instanced mesh.\n * @param count - The active count.\n */\nfunction applyMeshCount(mesh: LiteMesh, count: number): void {\n if (!trySetThinInstanceDrawCount(mesh, count)) {\n setThinInstanceCount(mesh, count);\n }\n}\n\n/**\n * Reads a mesh's object-local box into six numbers.\n *\n * @remarks\n * A mesh built by any Lite factory carries bounds; the fallback half-metre cube is the same default\n * `computeDirectionalLightMatrix` uses for a mesh that does not\n * (`lib/shadow/shadow-base.js` 62).\n *\n * @param mesh - The mesh to read.\n * @returns `minX, minY, minZ, maxX, maxY, maxZ`.\n */\nfunction readBox(mesh: LiteMesh): Float64Array {\n const min = mesh.boundMin ?? [-0.5, -0.5, -0.5];\n const max = mesh.boundMax ?? [0.5, 0.5, 0.5];\n return Float64Array.of(min[0], min[1], min[2], max[0], max[1], max[2]);\n}\n\n/**\n * Writes a six-number box back onto a mesh, grown by a margin on every side.\n *\n * @param mesh - The mesh to re-bound.\n * @param box - `minX, minY, minZ, maxX, maxY, maxZ`.\n * @param margin - How far to grow each axis, in object units.\n */\nfunction writeBox(mesh: LiteMesh, box: Float64Array, margin: Vec3): void {\n setMeshBounds(\n mesh,\n (box[0] ?? 0) - margin.x,\n (box[1] ?? 0) - margin.y,\n (box[2] ?? 0) - margin.z,\n (box[3] ?? 0) + margin.x,\n (box[4] ?? 0) + margin.y,\n (box[5] ?? 0) + margin.z,\n );\n}\n\n/**\n * Converts a world-space margin into the object-space margin along one axis.\n *\n * @param margin - The margin, in world metres.\n * @param scale - The entity's world scale along the axis.\n * @returns The margin in object units; `0` for no margin or a collapsed axis.\n */\nfunction objectMargin(margin: number, scale: number): number {\n return margin > 0 && scale > 1e-9 ? margin / scale : 0;\n}\n\n/**\n * The axis-aligned union of a prototype box placed under every live instance matrix.\n *\n * @remarks\n * The same oriented-box-to-AABB composition Lite's own\n * `expandThinInstanceWorldBounds` uses, minus the world matrix — because `Mesh.boundMin`/`boundMax`\n * are documented to be **object-local**, the frame `worldMatrix` maps out of. Degenerate matrices\n * are skipped, exactly as Lite skips them, so a slot that has not been written yet does not drag\n * the box to the origin.\n *\n * @param matrices - The slab, 16 column-major floats per instance.\n * @param count - How many instances to consider.\n * @param box - The prototype's own box.\n * @param out - Receives `minX, minY, minZ, maxX, maxY, maxZ`.\n */\nfunction unionOfPlacements(matrices: Float32Array, count: number, box: Float64Array, out: Float64Array): void {\n const centreX = ((box[0] ?? 0) + (box[3] ?? 0)) * 0.5;\n const centreY = ((box[1] ?? 0) + (box[4] ?? 0)) * 0.5;\n const centreZ = ((box[2] ?? 0) + (box[5] ?? 0)) * 0.5;\n const extentX = ((box[3] ?? 0) - (box[0] ?? 0)) * 0.5;\n const extentY = ((box[4] ?? 0) - (box[1] ?? 0)) * 0.5;\n const extentZ = ((box[5] ?? 0) - (box[2] ?? 0)) * 0.5;\n out[0] = Number.POSITIVE_INFINITY;\n out[1] = Number.POSITIVE_INFINITY;\n out[2] = Number.POSITIVE_INFINITY;\n out[3] = Number.NEGATIVE_INFINITY;\n out[4] = Number.NEGATIVE_INFINITY;\n out[5] = Number.NEGATIVE_INFINITY;\n const usable = Math.min(count, Math.floor(matrices.length / 16));\n let placed = 0;\n for (let index = 0; index < usable; index += 1) {\n const base = index * 16;\n let scale = 0;\n for (let element = 0; element < 12; element += 1) {\n if (element % 4 !== 3) {\n scale += Math.abs(matrices[base + element] ?? 0);\n }\n }\n if (scale < 1e-9) {\n continue;\n }\n placed += 1;\n for (let row = 0; row < 3; row += 1) {\n const m0 = matrices[base + row] ?? 0;\n const m1 = matrices[base + 4 + row] ?? 0;\n const m2 = matrices[base + 8 + row] ?? 0;\n const centre = (matrices[base + 12 + row] ?? 0) + m0 * centreX + m1 * centreY + m2 * centreZ;\n const radius = Math.abs(m0) * extentX + Math.abs(m1) * extentY + Math.abs(m2) * extentZ;\n const low = centre - radius;\n const high = centre + radius;\n if (low < (out[row] ?? 0)) {\n out[row] = low;\n }\n if (high > (out[row + 3] ?? 0)) {\n out[row + 3] = high;\n }\n }\n }\n if (placed === 0) {\n out.set(box);\n }\n}\n\n/**\n * Narrows a cloned subtree root to a mesh.\n *\n * @remarks\n * The same boundary assertion `MeshInstance` makes, for the same reason: `cloneTransformNode` is\n * typed as returning the wider `SceneNode` because it also clones plain transform nodes, and the\n * clone of a mesh is a mesh (coding standards §5.2).\n *\n * @param node - The clone.\n * @returns The same object, typed as a mesh.\n */\nfunction asMesh(node: LiteSceneNode): LiteMesh {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- see the note above.\n return node as LiteMesh;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8DA,SAAgBA,mBAAiB,MAAY,UAAwB,UAAwB;CAC3F,iBAAqB,MAAM,UAAU,QAAQ;AAC/C;;;;;;;;;;;;;AAcA,SAAgBC,uBAAqB,MAAY,OAAqB;CACpE,qBAAyB,MAAM,KAAK;AACtC;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,4BAA4B,MAAY,OAAwB;CAC9E,IAAI;EACF,yBAA6B,MAAM,KAAK;EACxC,OAAO;CACT,QAAQ;EACN,OAAO;CACT;AACF;;;;;;;;AASA,SAAg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,EAAE,IAAI;GAChF,MAAM,MAAM,SAAS;GACrB,MAAM,OAAO,SAAS;GACtB,IAAI,OAAO,IAAI,QAAQ,IACrB,IAAI,OAAO;GAEb,IAAI,QAAQ,IAAI,MAAM,MAAM,IAC1B,IAAI,MAAM,KAAK;EAEnB;CACF;CACA,IAAI,WAAW,GACb,IAAI,IAAI,GAAG;AAEf;;;;;;;;;;;;AAaA,SAAS,OAAO,MAA+B;CAE7C,OAAO;AACT"}
1
+ {"version":3,"file":"instanced-mesh-instance-BMhREEfx.js","names":["setThinInstances","setThinInstanceCount","flushThinInstances","setThinInstanceColors","enableThinInstanceGpuCulling","setThinInstanceCullBoundsPad","enableThinInstanceWorldBounds","enableThinInstanceDynamicDrawCount","setThinInstanceLodPartner","clearThinInstanceLodPartner"],"sources":["../src/lite/gpu/thin-instances.ts","../src/render/gpu/instanced-mesh-instance.ts"],"sourcesContent":["import {\n clearThinInstanceLodPartner as liteClearThinInstanceLodPartner,\n enableThinInstanceDynamicDrawCount as liteEnableThinInstanceDynamicDrawCount,\n enableThinInstanceGpuCulling as liteEnableThinInstanceGpuCulling,\n enableThinInstanceWorldBounds as liteEnableThinInstanceWorldBounds,\n flushThinInstances as liteFlushThinInstances,\n setThinInstanceColors as liteSetThinInstanceColors,\n setThinInstanceCount as liteSetThinInstanceCount,\n setThinInstanceCullBoundsPad as liteSetThinInstanceCullBoundsPad,\n setThinInstanceDrawCount as liteSetThinInstanceDrawCount,\n setThinInstanceLodPartner as liteSetThinInstanceLodPartner,\n setThinInstances as liteSetThinInstances,\n} from \"@babylonjs/lite\";\nimport type { Mesh } from \"@babylonjs/lite\";\n\n/**\n * Thin-instance half of the Babylon Lite adapter (`docs/architecture/07-rendering.md` §2.3,\n * `docs/plan/2026-09-terrain-particles-shaders.md` §3.5). Everything here is `@internal` and needs a\n * WebGPU device, so the browser project is what covers it.\n *\n * Lite fixes the order these must be called in, and both the culling opt-in and the LOD pairing only\n * take effect through the renderable `registerScene` compiles:\n *\n * 1. {@link setThinInstances} — its `count` argument becomes `_capacity`, and the GPU buffer is\n * sized `_capacity * 64` bytes for the life of the mesh, so pass the **capacity** here once and\n * lower the active count with {@link setThinInstanceCount} straight afterwards.\n * 2. {@link enableThinInstanceWorldBounds} — gives the scene AABB the cloud rather than the\n * prototype. It does not fix a shadow frustum: `computeDirectionalLightMatrix` reads\n * `boundMin`/`boundMax` directly (`lib/shadow/shadow-base.js` 54).\n * 3. {@link enableThinInstanceGpuCulling} — compute-based, opaque only.\n * 4. {@link enableThinInstanceDynamicDrawCount} — indirect draw arguments, so a later count change\n * keeps the cached bundle valid.\n * 5. {@link setThinInstanceLodPartner} — needs both meshes instanced already and stamps both\n * `_clone`, so neither can be cloned afterwards.\n * 6. `addMeshToScene`, and only then `registerScene`.\n *\n * Moving instances costs three different amounts (`lib/mesh/thin-instance.js`):\n * {@link flushThinInstances} re-uploads the whole active range and is the only sub-range-free path\n * Lite exposes; {@link setThinInstanceCount} re-uploads as well; {@link setThinInstanceDrawCount}\n * uploads nothing but throws until the pool has completed one GPU synchronisation, which is private\n * state — {@link trySetThinInstanceDrawCount} asks by trying.\n */\n\n/**\n * Points a mesh at a matrix slab and fixes its capacity.\n *\n * @remarks\n * The `capacity` argument is written straight to Lite's `_capacity`, which sizes the GPU buffer\n * (`_capacity * 64` bytes) once and for good. Only the first `count` matrices are ever read from\n * `matrices`, and Lite clamps its dirty range to the active count\n * (`lib/mesh/thin-instance-gpu.js`), so a slab shorter than `capacity * 16` floats is safe as long\n * as the active count is lowered with {@link setThinInstanceCount} before the next frame.\n *\n * Lite keeps the array by reference and never copies it: the caller owns it, and mutating it is the\n * intended way to move instances, followed by {@link flushThinInstances}.\n *\n * @param mesh - The mesh to instance.\n * @param matrices - 16 floats per instance, column-major, caller-owned.\n * @param capacity - The largest instance count this mesh will ever draw.\n *\n * @internal\n */\nexport function setThinInstances(mesh: Mesh, matrices: Float32Array, capacity: number): void {\n liteSetThinInstances(mesh, matrices, capacity);\n}\n\n/**\n * Sets how many instances draw, re-uploading the active range.\n *\n * @remarks\n * Prefer {@link trySetThinInstanceDrawCount} for a per-frame change: this one marks `[0, count)`\n * dirty as well, so it costs a `count * 64`-byte upload.\n *\n * @param mesh - The instanced mesh.\n * @param count - The active count, at most the capacity.\n *\n * @internal\n */\nexport function setThinInstanceCount(mesh: Mesh, count: number): void {\n liteSetThinInstanceCount(mesh, count);\n}\n\n/**\n * Sets how many instances draw without re-uploading anything, when Lite accepts it.\n *\n * @remarks\n * Lite requires the pool to have completed one full-capacity GPU synchronisation first and throws\n * otherwise (`lib/mesh/thin-instance.js`, `ThrowLiteError(369)`); the state it checks — the matrix\n * buffer's existence and its version — is private, so the only way to ask is to call. The throw\n * happens before anything is mutated, so a refusal leaves the mesh untouched and the caller can\n * fall back to {@link setThinInstanceCount}.\n *\n * @param mesh - The instanced mesh.\n * @param count - The active count, at most the capacity.\n * @returns `true` when the count was changed, `false` when Lite is not ready for a bare count\n * change yet.\n *\n * @internal\n */\nexport function trySetThinInstanceDrawCount(mesh: Mesh, count: number): boolean {\n try {\n liteSetThinInstanceDrawCount(mesh, count);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Marks the whole active matrix range dirty, after the caller mutated the slab in place.\n *\n * @param mesh - The instanced mesh.\n *\n * @internal\n */\nexport function flushThinInstances(mesh: Mesh): void {\n liteFlushThinInstances(mesh);\n}\n\n/**\n * Installs, replaces, or removes the per-instance RGBA colours.\n *\n * @remarks\n * Lite exports no way to *remove* colours: `setThinInstanceColors` only assigns, and the colour\n * version counters that drive the upload are private. `ThinInstanceData.colors` is declared\n * optional and mutable (`index.d.ts` 12985), so clearing is a direct field write —\n * which is enough, because `syncThinInstanceGpuData` skips the colour upload entirely while\n * `colors` is null, and the renderable rebuild the caller triggers is what drops\n * `useThinInstanceColors` from the compiled pipeline.\n *\n * @param mesh - The instanced mesh.\n * @param colors - Four floats per instance (linear RGBA), or `null` to stop reading colours.\n *\n * @internal\n */\nexport function setThinInstanceColors(mesh: Mesh, colors: Float32Array | null): void {\n if (colors !== null) {\n liteSetThinInstanceColors(mesh, colors);\n return;\n }\n const data = mesh.thinInstances;\n if (data !== null && data !== undefined) {\n data.colors = null;\n }\n}\n\n/**\n * Turns compute-based GPU frustum culling on or off for an instanced mesh.\n *\n * @remarks\n * Opaque meshes only, and it must run after {@link setThinInstances} and before the scene is\n * registered.\n *\n * @param mesh - The instanced mesh.\n * @param enabled - Whether the culling compute pass runs.\n *\n * @internal\n */\nexport function enableThinInstanceGpuCulling(mesh: Mesh, enabled: boolean): void {\n liteEnableThinInstanceGpuCulling(mesh, enabled);\n}\n\n/**\n * Grows every instance's GPU-culling sphere by a world-space distance.\n *\n * @remarks\n * The culler builds each sphere from the prototype's vertices (`lib/mesh/thin-instance-gpu-culling.js`\n * 426), so a vertex stage that moves an instance outside it gets the instance culled while it is\n * still on screen. Lite reads the pad on every culled pass (`index.d.ts` 11232), so it can change\n * live. Needs {@link setThinInstances} first.\n *\n * @param mesh - The instanced mesh that owns the culling pass.\n * @param pad - The extra radius in world units; `0` is the exact sphere.\n *\n * @internal\n */\nexport function setThinInstanceCullBoundsPad(mesh: Mesh, pad: number): void {\n liteSetThinInstanceCullBoundsPad(mesh, pad);\n}\n\n/**\n * Makes a mesh's world bounds the union of its instances' boxes rather than the prototype's own.\n *\n * @remarks\n * The hook it installs is `O(count)` per bounds computation, and it clamps to\n * `matrices.length / 16`, so a short slab cannot walk off the end. It is read by\n * `expandWorldAabbForMesh` — the scene camera's extent and PBR's scene-size probe — and **not** by\n * the directional shadow fit; see the module note.\n *\n * @param mesh - The instanced mesh.\n *\n * @internal\n */\nexport function enableThinInstanceWorldBounds(mesh: Mesh): void {\n liteEnableThinInstanceWorldBounds(mesh);\n}\n\n/**\n * Opts a fixed-capacity pool into indirect draw arguments, so a later count change keeps the\n * cached render bundle valid.\n *\n * @param mesh - The instanced mesh.\n *\n * @internal\n */\nexport function enableThinInstanceDynamicDrawCount(mesh: Mesh): void {\n liteEnableThinInstanceDynamicDrawCount(mesh);\n}\n\n/**\n * Where a LOD pairing switches, and how softly.\n *\n * @internal\n */\nexport interface ThinInstanceLodOptions {\n /** The camera distance, in world units, at which an in-frustum instance switches to the partner. */\n readonly distance: number;\n /** The width of the per-instance threshold dither window centred on `distance`; `0` is a hard cut. */\n readonly band: number;\n}\n\n/**\n * Pairs a GPU-culled instanced mesh with a lower-detail partner.\n *\n * @remarks\n * Both meshes must already carry thin instances, and the partner may reference the very same matrix\n * slab. While paired the partner draws **only** the far bucket, and the pairing switches its own\n * GPU culling on. Lite refuses the pairing when either mesh has more than one thin-instance owner,\n * when the partner is already paired, or when the partner carries colours the full mesh does not\n * (`ThrowLiteError(375)`, `(377)`, `(379)`). Calling it again with the same pair re-sets `distance`\n * and `band` live.\n *\n * @param fullMesh - The near mesh, which owns the culling pass.\n * @param lodMesh - The far mesh.\n * @param options - Where the switch happens, and how softly.\n *\n * @internal\n */\nexport function setThinInstanceLodPartner(fullMesh: Mesh, lodMesh: Mesh, options: ThinInstanceLodOptions): void {\n liteSetThinInstanceLodPartner(fullMesh, lodMesh, { distance: options.distance, band: options.band });\n}\n\n/**\n * Dissolves a LOD pairing, returning both meshes to independent rendering.\n *\n * @remarks\n * A no-op when the mesh is not paired, so it is safe on the teardown path.\n *\n * @param fullMesh - The near mesh of the pair.\n *\n * @internal\n */\nexport function clearThinInstanceLodPartner(fullMesh: Mesh): void {\n liteClearThinInstanceLodPartner(fullMesh);\n}\n\n/**\n * How many instances a mesh is currently drawing, as Lite sees it.\n *\n * @remarks\n * The browser tests assert against Lite's own state rather than against the component's copy of it,\n * which is the only way to prove the two agree.\n *\n * @param mesh - The mesh to read.\n * @returns The active count, or `0` when the mesh carries no thin instances.\n *\n * @internal\n */\nexport function thinInstanceCount(mesh: Mesh): number {\n return mesh.thinInstances?.count ?? 0;\n}\n","import {\n addMeshToScene,\n cloneMeshUnderNode,\n detachMeshBounds,\n removeMeshFromScene,\n setMeshBounds,\n setMeshId,\n setMeshMaterial,\n setMeshPickable,\n setMeshReceiveShadows,\n setMeshRenderOrder,\n setMeshSubtreeVisible,\n} from \"../../lite/gpu/mesh.js\";\nimport {\n clearThinInstanceLodPartner,\n enableThinInstanceDynamicDrawCount,\n enableThinInstanceGpuCulling,\n enableThinInstanceWorldBounds,\n flushThinInstances,\n setThinInstanceColors,\n setThinInstanceCount,\n setThinInstanceCullBoundsPad,\n setThinInstanceLodPartner,\n setThinInstances,\n trySetThinInstanceDrawCount,\n} from \"../../lite/gpu/thin-instances.js\";\nimport { tagNode } from \"../../lite/node.js\";\nimport { Vec3 } from \"../../math/vec3.js\";\nimport type { LiteMesh } from \"../../lite/gpu/mesh.js\";\nimport type { LiteMaterial } from \"../../lite/material.js\";\nimport type { LiteSceneNode, NodeTag } from \"../../lite/node.js\";\nimport type { LiteScene } from \"../../lite/scene.js\";\nimport type { Transform } from \"../../transform/transform.js\";\n\n/**\n * One `InstancedMeshRenderer`'s near mesh and its optional LOD partner, and everything that writes\n * to them (`docs/plan/2026-09-terrain-particles-shaders.md` §3.5).\n *\n * Every line needs a WebGPU device, which is why it sits in `src/render/gpu/` — excluded from the\n * Node coverage floor and measured by the browser project — and why the component reaches it through\n * a dynamic `import()` (`../instanced-mesh-support.ts`).\n *\n * `capacity`, `gpuCulling` and the partner's identity are constructor arguments rather than `apply*`\n * methods because Lite fixes all three at `registerScene`; `distance` and `band` may be re-set live\n * by calling the pairing again. Both meshes share one matrix slab, which the pairing requires: it\n * compacts the near mesh's culling output into two buckets drawn from the same matrices.\n *\n * Bounds are the one thing an instanced caster needs that a plain mesh does not.\n * `computeDirectionalLightMatrix` composes `mesh.worldMatrix × mesh.boundMin/boundMax` directly\n * (`lib/shadow/shadow-base.js` 54) and never consults the `_expandWorldBounds` hook\n * `enableThinInstanceWorldBounds` installs, so a cloud left at its prototype's box casts nothing\n * (measured on SwiftShader, 2026-09-08). {@link InstancedMeshInstance.applyBounds} publishes the\n * union of the live placements instead; culling accuracy is unaffected because each instance's cull\n * sphere comes from the real vertices (`lib/mesh/thin-instance-gpu-culling.js` 426).\n */\n\n/** What the component remembers between uploads. Mutated in place, so a frame allocates nothing. */\nexport interface InstancedUploadState {\n /** The whole slab has to be re-pointed and re-uploaded. */\n isSlabDirty: boolean;\n /** The caller mutated the slab in place, so the active range has to be re-uploaded. */\n isRangeDirty: boolean;\n /** The count the meshes were last told about. */\n appliedCount: number;\n /** The capacity the meshes were built with. */\n appliedCapacity: number;\n /** Whether the union bounds have been published at least once. */\n hasAppliedBounds: boolean;\n /** Whether the last upload carried a colour slab. */\n hadColors: boolean;\n}\n\n/** The LOD switch the component declares, as much of it as the adapter reads. */\nexport interface InstancedLodFields {\n /** The camera distance at which an instance switches to the partner. */\n readonly distance: number;\n /** The width of the per-instance dither window. */\n readonly band: number;\n}\n\n/** The LOD partner an instance is built with. */\nexport interface InstancedLodConfig {\n /** The coarse template to clone. */\n readonly template: LiteMesh;\n /** The camera distance, in world units, at which an instance switches to the partner. */\n readonly distance: number;\n /** The width of the per-instance dither window centred on `distance`. */\n readonly band: number;\n}\n\n/** The settings Lite fixes when the meshes are built. */\nexport interface InstancedMeshSettings {\n /** The largest instance count the meshes will ever draw. */\n readonly capacity: number;\n /** Whether the compute culling pass runs. */\n readonly gpuCulling: boolean;\n /** The LOD partner, or `null`. */\n readonly lod: InstancedLodConfig | null;\n}\n\n/**\n * A live instanced mesh, and its LOD partner, in a scene.\n *\n * @internal\n */\nexport class InstancedMeshInstance {\n /** The cloned near mesh, parented under the entity's node. */\n readonly clone: LiteSceneNode;\n\n readonly #lod: LiteSceneNode | null;\n\n #material: LiteMaterial;\n\n #receiveShadows: boolean | null = null;\n\n #renderOrder = Number.NaN;\n\n #pickable: boolean | null = null;\n\n #visible = false;\n\n #lodDistance: number;\n\n #lodBand: number;\n\n readonly #nearBox: Float64Array;\n\n readonly #lodBox: Float64Array | null;\n\n readonly #union = new Float64Array(6);\n\n /** The world-space displacement the culling pad and the bounds were last widened by. */\n #displacement = 0;\n\n /** The same displacement in object units, per axis, as the published bounds carry it. */\n readonly #margin = new Vec3();\n\n /** Scratch for the entity's world scale. */\n readonly #scale = new Vec3();\n\n /**\n * Clones the templates, gives them thin instances, applies the baked settings in Lite's required\n * order, and adds them to the scene.\n *\n * @param scene - The render scene.\n * @param template - The near mesh's template.\n * @param parent - The entity's transform node.\n * @param tag - The owning entity and component, for picking.\n * @param meshId - The string id Lite's light include/exclude sets match on.\n * @param material - The material both meshes draw with. Assigned **before** the meshes join the\n * scene, for the reason `MeshInstance`'s constructor records: `addToScene` buckets a mesh by its\n * material's build group.\n * @param settings - Capacity, GPU culling, and the LOD pairing.\n * @param matrices - The matrix slab, caller-owned and never copied.\n * @param count - How many instances draw.\n * @param colors - Four floats per instance, or `null`.\n */\n constructor(\n scene: LiteScene,\n template: LiteMesh,\n parent: LiteSceneNode,\n tag: NodeTag,\n meshId: string,\n material: LiteMaterial,\n settings: InstancedMeshSettings,\n matrices: Float32Array,\n count: number,\n colors: Float32Array | null,\n ) {\n const clone = cloneMeshUnderNode(template, parent);\n tagNode(clone, tag);\n const mesh = asMesh(clone);\n setMeshId(mesh, meshId);\n setMeshMaterial(mesh, material);\n // A clone shares the template's bound arrays, and `applyBounds` mutates them in place.\n detachMeshBounds(mesh);\n this.#nearBox = readBox(mesh);\n installThinInstances(mesh, settings.capacity, matrices, count, colors);\n enableThinInstanceGpuCulling(mesh, settings.gpuCulling);\n enableThinInstanceDynamicDrawCount(mesh);\n\n const lodConfig = settings.lod;\n let lodClone: LiteSceneNode | null = null;\n let lodBox: Float64Array | null = null;\n if (lodConfig !== null) {\n lodClone = cloneMeshUnderNode(lodConfig.template, parent);\n tagNode(lodClone, tag);\n const lodMesh = asMesh(lodClone);\n setMeshId(lodMesh, `${meshId}#lod`);\n setMeshMaterial(lodMesh, material);\n detachMeshBounds(lodMesh);\n lodBox = readBox(lodMesh);\n installThinInstances(lodMesh, settings.capacity, matrices, count, colors);\n setThinInstanceLodPartner(mesh, lodMesh, { distance: lodConfig.distance, band: lodConfig.band });\n }\n this.#lodBox = lodBox;\n\n this.#material = material;\n this.#lodDistance = lodConfig?.distance ?? 0;\n this.#lodBand = lodConfig?.band ?? 0;\n // Hidden until the first `applyVisible`, so a renderer on an inactive entity never flashes.\n setMeshSubtreeVisible(clone, false);\n addMeshToScene(scene, clone);\n if (lodClone !== null) {\n setMeshSubtreeVisible(lodClone, false);\n addMeshToScene(scene, lodClone);\n }\n this.clone = clone;\n this.#lod = lodClone;\n }\n\n /**\n * Whether the meshes are currently drawn.\n *\n * @returns `true` when Lite's `visible` is set on them.\n */\n get isVisible(): boolean {\n return this.#visible;\n }\n\n /**\n * The near mesh.\n *\n * @returns The clone, typed as a mesh.\n */\n get mesh(): LiteMesh {\n return asMesh(this.clone);\n }\n\n /**\n * The LOD partner.\n *\n * @returns The partner clone, or `null` when the renderer declares no LOD.\n */\n get lodMesh(): LiteMesh | null {\n const lod = this.#lod;\n return lod === null ? null : asMesh(lod);\n }\n\n /**\n * Assigns the material to both meshes, when it changed.\n *\n * @param material - The Lite material to draw with.\n */\n applyMaterial(material: LiteMaterial): void {\n if (material === this.#material) {\n return;\n }\n this.#material = material;\n setMeshMaterial(this.mesh, material);\n const lod = this.lodMesh;\n if (lod !== null) {\n setMeshMaterial(lod, material);\n }\n }\n\n /**\n * Writes the per-mesh flags that changed, to both meshes.\n *\n * @param receiveShadows - Whether shadow maps darken the meshes.\n * @param renderOrder - The sort key within the phase.\n * @param pickable - Whether picking considers the meshes at all.\n */\n applyFlags(receiveShadows: boolean, renderOrder: number, pickable: boolean): void {\n if (this.#receiveShadows !== receiveShadows) {\n this.#receiveShadows = receiveShadows;\n this.#eachMesh(setMeshReceiveShadows, receiveShadows);\n }\n if (this.#renderOrder !== renderOrder) {\n this.#renderOrder = renderOrder;\n this.#eachMesh(setMeshRenderOrder, renderOrder);\n }\n if (this.#pickable !== pickable) {\n this.#pickable = pickable;\n this.#eachMesh(setMeshPickable, pickable);\n }\n }\n\n /**\n * Re-sets the LOD switch distance and dither band, when either changed.\n *\n * @param distance - The camera distance at which an instance switches to the partner.\n * @param band - The width of the per-instance dither window centred on `distance`.\n */\n applyLod(distance: number, band: number): void {\n const lod = this.lodMesh;\n if (lod === null || (distance === this.#lodDistance && band === this.#lodBand)) {\n return;\n }\n this.#lodDistance = distance;\n this.#lodBand = band;\n setThinInstanceLodPartner(this.mesh, lod, { distance, band });\n }\n\n /**\n * Shows or hides both meshes, when the state changed.\n *\n * @param visible - `entity.activeInHierarchy && component.enabled`.\n */\n applyVisible(visible: boolean): void {\n if (visible === this.#visible) {\n return;\n }\n this.#visible = visible;\n setMeshSubtreeVisible(this.clone, visible);\n const lod = this.#lod;\n if (lod !== null) {\n setMeshSubtreeVisible(lod, visible);\n }\n }\n\n /**\n * Re-points both meshes at a matrix slab and re-uploads the active range.\n *\n * @param capacity - The capacity the meshes were built with; re-stating it keeps `_capacity`\n * unchanged, which is what stops Lite from re-creating the GPU buffer.\n * @param matrices - The slab, caller-owned.\n * @param count - How many instances draw.\n * @param colors - Four floats per instance, or `null`.\n */\n applySlab(capacity: number, matrices: Float32Array, count: number, colors: Float32Array | null): void {\n installThinInstances(this.mesh, capacity, matrices, count, colors);\n const lod = this.lodMesh;\n if (lod !== null) {\n installThinInstances(lod, capacity, matrices, count, colors);\n }\n }\n\n /**\n * Changes how many instances draw, by the cheapest route Lite accepts.\n *\n * @param count - The active count, at most the capacity.\n */\n applyCount(count: number): void {\n applyMeshCount(this.mesh, count);\n const lod = this.lodMesh;\n if (lod !== null) {\n applyMeshCount(lod, count);\n }\n }\n\n /**\n * Marks the whole active range dirty, after the caller mutated the slab in place.\n *\n * @param colors - The colour slab, when the renderer has one, so its own dirty range moves too.\n */\n flush(colors: Float32Array | null): void {\n flushThinInstances(this.mesh);\n const lod = this.lodMesh;\n if (lod !== null) {\n flushThinInstances(lod);\n }\n if (colors !== null) {\n setThinInstanceColors(this.mesh, colors);\n if (lod !== null) {\n setThinInstanceColors(lod, colors);\n }\n }\n }\n\n /**\n * Publishes the union of the live instance placements as both meshes' object-local bounds, so a\n * directional light's shadow frustum is fitted to the cloud rather than to the prototype.\n *\n * @remarks\n * `O(count)`, allocation-free, and worth paying only for a caster — see the module note. A count\n * of zero restores the prototype's own box, so an empty cloud does not report an infinite one.\n *\n * @param matrices - The live matrix slab.\n * @param count - How many instances are drawn.\n */\n applyBounds(matrices: Float32Array, count: number): void {\n const near = this.#nearBox;\n const lodBox = this.#lodBox;\n const lod = this.lodMesh;\n const margin = this.#margin;\n if (count <= 0) {\n writeBox(this.mesh, near, margin);\n if (lod !== null && lodBox !== null) {\n writeBox(lod, lodBox, margin);\n }\n return;\n }\n const union = this.#union;\n unionOfPlacements(matrices, count, near, union);\n writeBox(this.mesh, union, margin);\n if (lod !== null && lodBox !== null) {\n unionOfPlacements(matrices, count, lodBox, union);\n writeBox(lod, union, margin);\n }\n }\n\n /**\n * Widens both meshes for a vertex stage that moves vertices up to `displacement` metres: the GPU\n * culler pads every instance's sphere, and the bounds published for a shadow frustum grow too.\n *\n * @remarks\n * The culling pad is world-space already. The bounds are object-local, so each axis is divided by\n * the entity's world scale along it. A change clears `state.hasAppliedBounds`, so the next\n * {@link InstancedMeshInstance.sync} re-publishes them.\n *\n * @param state - The component's upload state.\n * @param displacement - The material's displacement, in world metres.\n * @param transform - The entity's transform, whose world scale the meshes inherit.\n */\n applyDisplacement(state: InstancedUploadState, displacement: number, transform: Transform): void {\n if (displacement !== this.#displacement) {\n this.#displacement = displacement;\n // Only the near mesh runs the culling pass; the partner draws from its output.\n setThinInstanceCullBoundsPad(this.mesh, displacement);\n }\n const scale = this.#scale;\n if (displacement > 0) {\n transform.lossyScaleToRef(scale);\n }\n const x = objectMargin(displacement, scale.x);\n const y = objectMargin(displacement, scale.y);\n const z = objectMargin(displacement, scale.z);\n const margin = this.#margin;\n if (x !== margin.x || y !== margin.y || z !== margin.z) {\n margin.set(x, y, z);\n state.hasAppliedBounds = false;\n }\n }\n\n /**\n * Writes everything the component changed since the last frame onto both meshes.\n *\n * @param state - The component's upload state, mutated in place.\n * @param material - The material both meshes draw with.\n * @param receiveShadows - Whether shadow maps darken them.\n * @param renderOrder - The sort key within the phase.\n * @param pickable - Whether picking considers them.\n * @param lod - The LOD record, whose `distance` and `band` Lite re-applies live; `null` for none.\n * @param matrices - The caller-owned matrix slab.\n * @param count - How many instances draw.\n * @param colors - Four floats per instance, or `null`.\n * @param castShadows - Whether the union bounds have to be published for a shadow frustum.\n * @param visible - `entity.activeInHierarchy && component.enabled`.\n * @returns `true` when the compiled pipeline has to change, which only a colour slab arriving or\n * leaving does.\n */\n sync(\n state: InstancedUploadState,\n material: LiteMaterial,\n receiveShadows: boolean,\n renderOrder: number,\n pickable: boolean,\n lod: InstancedLodFields | null,\n matrices: Float32Array,\n count: number,\n colors: Float32Array | null,\n castShadows: boolean,\n visible: boolean,\n ): boolean {\n this.applyMaterial(material);\n this.applyFlags(receiveShadows, renderOrder, pickable);\n if (lod !== null) {\n this.applyLod(lod.distance, lod.band);\n }\n let renderablesChanged = false;\n let placementsMoved = false;\n if (state.isSlabDirty) {\n state.isSlabDirty = false;\n state.isRangeDirty = false;\n this.applySlab(state.appliedCapacity, matrices, count, colors);\n state.appliedCount = count;\n placementsMoved = true;\n const hasColors = colors !== null;\n renderablesChanged = hasColors !== state.hadColors;\n state.hadColors = hasColors;\n } else {\n if (state.isRangeDirty) {\n state.isRangeDirty = false;\n this.flush(colors);\n placementsMoved = true;\n }\n if (count !== state.appliedCount) {\n state.appliedCount = count;\n this.applyCount(count);\n placementsMoved = true;\n }\n }\n // Only a caster pays the `O(count)` bounds pass, and only in a frame whose placements moved.\n if (castShadows && (placementsMoved || !state.hasAppliedBounds)) {\n state.hasAppliedBounds = true;\n this.applyBounds(matrices, count);\n }\n this.applyVisible(visible);\n return renderablesChanged;\n }\n\n /**\n * Appends both meshes to a shadow caster list, when the renderer casts and they are drawn.\n *\n * @param castShadows - Whether the renderer casts.\n * @param out - The caster list being built.\n */\n collectCasters(castShadows: boolean, out: LiteMesh[]): void {\n if (!castShadows || !this.#visible) {\n return;\n }\n out.push(this.mesh);\n const lod = this.lodMesh;\n if (lod !== null) {\n out.push(lod);\n }\n }\n\n /**\n * Dissolves the LOD pairing and removes both meshes from the scene, releasing their share of the\n * templates' buffers.\n *\n * @param scene - The render scene.\n */\n destroy(scene: LiteScene): void {\n const lod = this.#lod;\n if (lod !== null) {\n clearThinInstanceLodPartner(this.mesh);\n removeMeshFromScene(scene, lod);\n }\n removeMeshFromScene(scene, this.clone);\n }\n\n /**\n * Runs a per-mesh Lite setter over the near mesh and the partner.\n *\n * @typeParam T - The setter's value type.\n * @param write - The adapter function to call.\n * @param value - What to write.\n */\n #eachMesh<T>(write: (mesh: LiteMesh, value: T) => void, value: T): void {\n write(this.mesh, value);\n const lod = this.lodMesh;\n if (lod !== null) {\n write(lod, value);\n }\n }\n}\n\n/**\n * Builds the live meshes, filling in the LOD pairing when both templates exist.\n *\n * @param scene - The render scene.\n * @param template - The near mesh's template.\n * @param lodTemplate - The coarse template, or `null`.\n * @param lod - The LOD record the component declares, or `null`.\n * @param parent - The entity's transform node.\n * @param tag - The owning entity and component, for picking.\n * @param meshId - The string id Lite's light include/exclude sets match on.\n * @param material - The material both meshes draw with.\n * @param capacity - The largest instance count the meshes will ever draw.\n * @param gpuCulling - Whether the compute culling pass runs.\n * @param matrices - The matrix slab.\n * @param count - How many instances draw.\n * @param colors - Four floats per instance, or `null`.\n * @returns The instance.\n *\n * @internal\n */\nexport function createInstancedMesh(\n scene: LiteScene,\n template: LiteMesh,\n lodTemplate: LiteMesh | null,\n lod: InstancedLodFields | null,\n parent: LiteSceneNode,\n tag: NodeTag,\n meshId: string,\n material: LiteMaterial,\n capacity: number,\n gpuCulling: boolean,\n matrices: Float32Array,\n count: number,\n colors: Float32Array | null,\n): InstancedMeshInstance {\n const pairing: InstancedLodConfig | null =\n lodTemplate === null || lod === null ? null : { template: lodTemplate, distance: lod.distance, band: lod.band };\n return new InstancedMeshInstance(\n scene,\n template,\n parent,\n tag,\n meshId,\n material,\n { capacity, gpuCulling, lod: pairing },\n matrices,\n count,\n colors,\n );\n}\n\n/**\n * Removes the meshes from the scene, when there are any.\n *\n * @param instance - The live meshes, or `null`.\n * @param scene - The render scene.\n * @returns `true` when something left the scene.\n *\n * @internal\n */\nexport function releaseInstancedMesh(instance: InstancedMeshInstance | null, scene: LiteScene): boolean {\n if (instance === null) {\n return false;\n }\n instance.destroy(scene);\n return true;\n}\n\n/**\n * Gives one mesh its thin instances in the order Lite requires, at a fixed capacity.\n *\n * @remarks\n * `setThinInstances` is handed the **capacity** so that `_capacity` — and the GPU buffer it sizes —\n * never moves; the active count is then lowered in the same breath, before any frame can read the\n * range in between (`src/lite/gpu/thin-instances.ts`).\n *\n * @param mesh - The mesh to instance.\n * @param capacity - The capacity to fix.\n * @param matrices - The slab, caller-owned.\n * @param count - How many instances draw.\n * @param colors - Four floats per instance, or `null`.\n */\nfunction installThinInstances(\n mesh: LiteMesh,\n capacity: number,\n matrices: Float32Array,\n count: number,\n colors: Float32Array | null,\n): void {\n setThinInstances(mesh, matrices, capacity);\n setThinInstanceCount(mesh, count);\n setThinInstanceColors(mesh, colors);\n enableThinInstanceWorldBounds(mesh);\n}\n\n/**\n * Changes one mesh's active count without re-uploading when Lite allows it, and with a re-upload\n * when it does not.\n *\n * @param mesh - The instanced mesh.\n * @param count - The active count.\n */\nfunction applyMeshCount(mesh: LiteMesh, count: number): void {\n if (!trySetThinInstanceDrawCount(mesh, count)) {\n setThinInstanceCount(mesh, count);\n }\n}\n\n/**\n * Reads a mesh's object-local box into six numbers.\n *\n * @remarks\n * A mesh built by any Lite factory carries bounds; the fallback half-metre cube is the same default\n * `computeDirectionalLightMatrix` uses for a mesh that does not\n * (`lib/shadow/shadow-base.js` 62).\n *\n * @param mesh - The mesh to read.\n * @returns `minX, minY, minZ, maxX, maxY, maxZ`.\n */\nfunction readBox(mesh: LiteMesh): Float64Array {\n const min = mesh.boundMin ?? [-0.5, -0.5, -0.5];\n const max = mesh.boundMax ?? [0.5, 0.5, 0.5];\n return Float64Array.of(min[0], min[1], min[2], max[0], max[1], max[2]);\n}\n\n/**\n * Writes a six-number box back onto a mesh, grown by a margin on every side.\n *\n * @param mesh - The mesh to re-bound.\n * @param box - `minX, minY, minZ, maxX, maxY, maxZ`.\n * @param margin - How far to grow each axis, in object units.\n */\nfunction writeBox(mesh: LiteMesh, box: Float64Array, margin: Vec3): void {\n setMeshBounds(\n mesh,\n (box[0] ?? 0) - margin.x,\n (box[1] ?? 0) - margin.y,\n (box[2] ?? 0) - margin.z,\n (box[3] ?? 0) + margin.x,\n (box[4] ?? 0) + margin.y,\n (box[5] ?? 0) + margin.z,\n );\n}\n\n/**\n * Converts a world-space margin into the object-space margin along one axis.\n *\n * @param margin - The margin, in world metres.\n * @param scale - The entity's world scale along the axis.\n * @returns The margin in object units; `0` for no margin or a collapsed axis.\n */\nfunction objectMargin(margin: number, scale: number): number {\n return margin > 0 && scale > 1e-9 ? margin / scale : 0;\n}\n\n/**\n * The axis-aligned union of a prototype box placed under every live instance matrix.\n *\n * @remarks\n * The same oriented-box-to-AABB composition Lite's own\n * `expandThinInstanceWorldBounds` uses, minus the world matrix — because `Mesh.boundMin`/`boundMax`\n * are documented to be **object-local**, the frame `worldMatrix` maps out of. Degenerate matrices\n * are skipped, exactly as Lite skips them, so a slot that has not been written yet does not drag\n * the box to the origin.\n *\n * @param matrices - The slab, 16 column-major floats per instance.\n * @param count - How many instances to consider.\n * @param box - The prototype's own box.\n * @param out - Receives `minX, minY, minZ, maxX, maxY, maxZ`.\n */\nfunction unionOfPlacements(matrices: Float32Array, count: number, box: Float64Array, out: Float64Array): void {\n const centreX = ((box[0] ?? 0) + (box[3] ?? 0)) * 0.5;\n const centreY = ((box[1] ?? 0) + (box[4] ?? 0)) * 0.5;\n const centreZ = ((box[2] ?? 0) + (box[5] ?? 0)) * 0.5;\n const extentX = ((box[3] ?? 0) - (box[0] ?? 0)) * 0.5;\n const extentY = ((box[4] ?? 0) - (box[1] ?? 0)) * 0.5;\n const extentZ = ((box[5] ?? 0) - (box[2] ?? 0)) * 0.5;\n out[0] = Number.POSITIVE_INFINITY;\n out[1] = Number.POSITIVE_INFINITY;\n out[2] = Number.POSITIVE_INFINITY;\n out[3] = Number.NEGATIVE_INFINITY;\n out[4] = Number.NEGATIVE_INFINITY;\n out[5] = Number.NEGATIVE_INFINITY;\n const usable = Math.min(count, Math.floor(matrices.length / 16));\n let placed = 0;\n for (let index = 0; index < usable; index += 1) {\n const base = index * 16;\n let scale = 0;\n for (let element = 0; element < 12; element += 1) {\n if (element % 4 !== 3) {\n scale += Math.abs(matrices[base + element] ?? 0);\n }\n }\n if (scale < 1e-9) {\n continue;\n }\n placed += 1;\n for (let row = 0; row < 3; row += 1) {\n const m0 = matrices[base + row] ?? 0;\n const m1 = matrices[base + 4 + row] ?? 0;\n const m2 = matrices[base + 8 + row] ?? 0;\n const centre = (matrices[base + 12 + row] ?? 0) + m0 * centreX + m1 * centreY + m2 * centreZ;\n const radius = Math.abs(m0) * extentX + Math.abs(m1) * extentY + Math.abs(m2) * extentZ;\n const low = centre - radius;\n const high = centre + radius;\n if (low < (out[row] ?? 0)) {\n out[row] = low;\n }\n if (high > (out[row + 3] ?? 0)) {\n out[row + 3] = high;\n }\n }\n }\n if (placed === 0) {\n out.set(box);\n }\n}\n\n/**\n * Narrows a cloned subtree root to a mesh.\n *\n * @remarks\n * The same boundary assertion `MeshInstance` makes, for the same reason: `cloneTransformNode` is\n * typed as returning the wider `SceneNode` because it also clones plain transform nodes, and the\n * clone of a mesh is a mesh (coding standards §5.2).\n *\n * @param node - The clone.\n * @returns The same object, typed as a mesh.\n */\nfunction asMesh(node: LiteSceneNode): LiteMesh {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- see the note above.\n return node as LiteMesh;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8DA,SAAgBA,mBAAiB,MAAY,UAAwB,UAAw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AAM,KAAK,SAAS,OAAO,QAAQ;GACnC,MAAM,KAAK,SAAS,OAAO,IAAI,QAAQ;GACvC,MAAM,KAAK,SAAS,OAAO,IAAI,QAAQ;GACvC,MAAM,UAAU,SAAS,OAAO,KAAK,QAAQ,KAAK,KAAK,UAAU,KAAK,UAAU,KAAK;GACrF,MAAM,SAAS,KAAK,IAAI,EAAE,IAAI,UAAU,KAAK,IAAI,EAAE,IAAI,UAAU,KAAK,IAAI,EAAE,IAAI;GAChF,MAAM,MAAM,SAAS;GACrB,MAAM,OAAO,SAAS;GACtB,IAAI,OAAO,IAAI,QAAQ,IACrB,IAAI,OAAO;GAEb,IAAI,QAAQ,IAAI,MAAM,MAAM,IAC1B,IAAI,MAAM,KAAK;EAEnB;CACF;CACA,IAAI,WAAW,GACb,IAAI,IAAI,GAAG;AAEf;;;;;;;;;;;;AAaA,SAAS,OAAO,MAA+B;CAE7C,OAAO;AACT"}
@@ -0,0 +1,331 @@
1
+ import { o as CoreErrorCode, t as IgnifxError } from "./ignifx-error-B8ByiSfJ.js";
2
+ //#region src/render/light-probe-asset.ts
3
+ /**
4
+ * Light probes (`docs/plan/2026-11-gi-phase-2-execution-plan.md`, step B2): a regular grid of baked
5
+ * irradiance samples that a `LightProbeVolume` lights PBR materials with, in place of the scene
6
+ * environment's diffuse light. Everything here is plain data and runs in Node.
7
+ *
8
+ * Each probe stores four RGB coefficients of first-order spherical harmonics, already convolved and
9
+ * scaled the way Babylon Lite's environment harmonics are, so the diffuse light a white surface with
10
+ * normal `n` receives is `c0 + c1·n.y + c2·n.z + c3·n.x` (Lite's `environmentIrradiance`, L1 part).
11
+ */
12
+ /**
13
+ * The asset type light-probe grids are registered under.
14
+ *
15
+ * @public
16
+ */
17
+ const LIGHT_PROBE_ASSET_TYPE = "lightprobes";
18
+ /**
19
+ * The address extensions that select the light-probe loader.
20
+ *
21
+ * @public
22
+ */
23
+ const LIGHT_PROBE_FILE_EXTENSIONS = Object.freeze([".probes.json"]);
24
+ /**
25
+ * The `format` header every `.probes.json` carries.
26
+ *
27
+ * @public
28
+ */
29
+ const LIGHT_PROBE_FILE_FORMAT = "ignifx-probes";
30
+ /**
31
+ * The `formatVersion` this engine reads and writes.
32
+ *
33
+ * @public
34
+ */
35
+ const LIGHT_PROBE_FORMAT_VERSION = 1;
36
+ /** Floats per probe: four RGB coefficients. */
37
+ const FLOATS_PER_PROBE = 12;
38
+ /** The largest grid side along X (the texture is four times as wide) and the largest Y·Z product. */
39
+ const MAX_X = 1024;
40
+ const MAX_YZ = 4096;
41
+ /** The bounds that keep the generated shader constants valid 32-bit floats. */
42
+ const MAX_COORDINATE = 0x56bc75e2d63100000;
43
+ const MIN_CELL = 1e-30;
44
+ /**
45
+ * A loaded light-probe grid.
46
+ *
47
+ * @example
48
+ * ```ts
49
+ * const probes = await app.assets.loadAsync<LightProbeAsset>("lighting/hall.probes.json");
50
+ * world.createEntity("Probes").addComponent(LightProbeVolume, { probes });
51
+ * ```
52
+ *
53
+ * @beta
54
+ */
55
+ var LightProbeAsset = class {
56
+ /** The type name the asset service registers light-probe grids under. */
57
+ static assetType = LIGHT_PROBE_ASSET_TYPE;
58
+ /** The grid. */
59
+ data;
60
+ /**
61
+ * Wraps a checked grid. Use the loader or {@link createLightProbeAsset}.
62
+ *
63
+ * @param data - The grid, already checked by `readLightProbeData`.
64
+ *
65
+ * @internal
66
+ */
67
+ constructor(data) {
68
+ this.data = data;
69
+ }
70
+ };
71
+ /**
72
+ * Publishes a grid built in code, such as the result of a bake, as an asset.
73
+ *
74
+ * @param app - The app.
75
+ * @param data - The grid.
76
+ * @returns A handle a `LightProbeVolume` can take.
77
+ * @throws IgnifxError with code `IGX-0709` when the grid is malformed.
78
+ *
79
+ * @beta
80
+ */
81
+ function createLightProbeAsset(app, data) {
82
+ return app.assets.register(new LightProbeAsset(readLightProbeData(data, "light probe data")), { type: LIGHT_PROBE_ASSET_TYPE });
83
+ }
84
+ /**
85
+ * Turns a grid into the JSON a `.probes.json` file holds.
86
+ *
87
+ * @param data - The grid.
88
+ * @returns The file contents, with the format header.
89
+ *
90
+ * @beta
91
+ */
92
+ function writeLightProbeFile(data) {
93
+ return {
94
+ format: LIGHT_PROBE_FILE_FORMAT,
95
+ formatVersion: 1,
96
+ origin: {
97
+ x: data.origin.x,
98
+ y: data.origin.y,
99
+ z: data.origin.z
100
+ },
101
+ cellSize: {
102
+ x: data.cellSize.x,
103
+ y: data.cellSize.y,
104
+ z: data.cellSize.z
105
+ },
106
+ counts: {
107
+ x: data.counts.x,
108
+ y: data.counts.y,
109
+ z: data.counts.z
110
+ },
111
+ coefficients: [...data.coefficients]
112
+ };
113
+ }
114
+ /**
115
+ * Reads a parsed `.probes.json`.
116
+ *
117
+ * @param parsed - The parsed JSON.
118
+ * @param address - The file's address, for the error.
119
+ * @returns The grid.
120
+ * @throws IgnifxError with code `IGX-0709` when the header, a field or the coefficient count is wrong.
121
+ *
122
+ * @internal
123
+ */
124
+ function readLightProbeFile(parsed, address) {
125
+ const file = asRecord(parsed);
126
+ if (file === null || file["format"] !== "ignifx-probes" || file["formatVersion"] !== 1) throw invalid(address, `it must start with { "format": "${LIGHT_PROBE_FILE_FORMAT}", "formatVersion": 1 }`);
127
+ return readLightProbeData(file, address);
128
+ }
129
+ /**
130
+ * Checks a grid's fields.
131
+ *
132
+ * @param value - The candidate grid.
133
+ * @param address - Where it came from, for the error.
134
+ * @returns A grid with copied, checked fields.
135
+ * @throws IgnifxError with code `IGX-0709` on a malformed field.
136
+ *
137
+ * @internal
138
+ */
139
+ function readLightProbeData(value, address) {
140
+ const record = asRecord(value);
141
+ if (record === null) throw invalid(address, "it is not an object");
142
+ const grid = readLightProbeGrid(record);
143
+ if (typeof grid === "string") throw invalid(address, grid);
144
+ const { origin, cellSize, counts } = grid;
145
+ const coefficients = record["coefficients"];
146
+ const expected = counts.x * counts.y * counts.z * FLOATS_PER_PROBE;
147
+ if (!Array.isArray(coefficients) || coefficients.length !== expected || !coefficients.every((n) => Number.isFinite(n))) throw invalid(address, `coefficients must be ${String(expected)} finite numbers (12 per probe)`);
148
+ return {
149
+ origin,
150
+ cellSize,
151
+ counts,
152
+ coefficients: coefficients.map(Number)
153
+ };
154
+ }
155
+ /**
156
+ * Checks the grid fields of a candidate grid, for a file and for a bake alike.
157
+ *
158
+ * @remarks
159
+ * Besides the format's count limits, `origin` stays below 1e20 in size and `cellSize` between
160
+ * 1e-30 and 1e20, so the constants the shader is generated with stay valid 32-bit floats.
161
+ *
162
+ * @param record - An object with `origin`, `cellSize` and `counts`.
163
+ * @returns The checked copies, or what is wrong with them.
164
+ *
165
+ * @internal
166
+ */
167
+ function readLightProbeGrid(record) {
168
+ const origin = readVec3(record["origin"], (n) => Number.isFinite(n) && Math.abs(n) < MAX_COORDINATE);
169
+ const cellSize = readVec3(record["cellSize"], (n) => Number.isFinite(n) && n > MIN_CELL && n < MAX_COORDINATE);
170
+ const counts = readVec3(record["counts"], (n) => Number.isSafeInteger(n) && n >= 1);
171
+ if (origin === null || cellSize === null || counts === null) return "origin (finite, below 1e20), cellSize (from 1e-30 to 1e20) and counts (whole, at least 1) must each be { x, y, z }";
172
+ if (counts.x > MAX_X || counts.y * counts.z > MAX_YZ) return `counts.x must be at most ${String(MAX_X)} and counts.y × counts.z at most ${String(MAX_YZ)}`;
173
+ return {
174
+ origin,
175
+ cellSize,
176
+ counts
177
+ };
178
+ }
179
+ /**
180
+ * The diffuse light a white surface receives at a point, read from the grid on the CPU the same way
181
+ * the shader reads it: trilinear between the eight surrounding probes, clamped at the grid's edges.
182
+ *
183
+ * @param data - The grid.
184
+ * @param x - World X.
185
+ * @param y - World Y.
186
+ * @param z - World Z.
187
+ * @param normal - The surface normal, unit length.
188
+ * @returns Linear RGB.
189
+ *
190
+ * @beta
191
+ */
192
+ function sampleLightProbes(data, x, y, z, normal) {
193
+ const { counts } = data;
194
+ const gx = gridCoordinate(x, data.origin.x, data.cellSize.x, counts.x);
195
+ const gy = gridCoordinate(y, data.origin.y, data.cellSize.y, counts.y);
196
+ const gz = gridCoordinate(z, data.origin.z, data.cellSize.z, counts.z);
197
+ const out = [
198
+ 0,
199
+ 0,
200
+ 0
201
+ ];
202
+ for (let corner = 0; corner < 8; corner += 1) {
203
+ const ix = corner & 1 ? gx.high : gx.low;
204
+ const iy = corner & 2 ? gy.high : gy.low;
205
+ const iz = corner & 4 ? gz.high : gz.low;
206
+ const weight = (corner & 1 ? gx.t : 1 - gx.t) * (corner & 2 ? gy.t : 1 - gy.t) * (corner & 4 ? gz.t : 1 - gz.t);
207
+ const base = (ix + counts.x * (iy + counts.y * iz)) * FLOATS_PER_PROBE;
208
+ for (let channel = 0; channel < 3; channel += 1) {
209
+ const c = (index) => data.coefficients[base + index * 3 + channel] ?? 0;
210
+ out[channel] = (out[channel] ?? 0) + weight * (c(0) + c(1) * normal.y + c(2) * normal.z + c(3) * normal.x);
211
+ }
212
+ }
213
+ return out;
214
+ }
215
+ /**
216
+ * Packs a grid into the half-float RGBA texels the shader reads: probe `(i, j, k)`'s coefficient `c`
217
+ * at texel `(i + countX·c, j + countY·k)`.
218
+ *
219
+ * @param data - The grid.
220
+ * @returns The width, height and texels (four half floats each, alpha 1).
221
+ *
222
+ * @internal
223
+ */
224
+ function packLightProbeTexels(data) {
225
+ const { x: nx, y: ny, z: nz } = data.counts;
226
+ const width = nx * 4;
227
+ const height = ny * nz;
228
+ const texels = new Uint16Array(width * height * 4);
229
+ const one = toHalfFloat(1);
230
+ for (let k = 0; k < nz; k += 1) for (let j = 0; j < ny; j += 1) for (let i = 0; i < nx; i += 1) {
231
+ const base = (i + nx * (j + ny * k)) * FLOATS_PER_PROBE;
232
+ for (let c = 0; c < 4; c += 1) {
233
+ const texel = (i + nx * c + width * (j + ny * k)) * 4;
234
+ for (let channel = 0; channel < 3; channel += 1) texels[texel + channel] = toHalfFloat(data.coefficients[base + c * 3 + channel] ?? 0);
235
+ texels[texel + 3] = one;
236
+ }
237
+ }
238
+ return {
239
+ width,
240
+ height,
241
+ texels
242
+ };
243
+ }
244
+ /**
245
+ * Converts a number to IEEE 754 half precision, rounding to nearest and saturating to ±65504.
246
+ *
247
+ * @param value - The number.
248
+ * @returns The 16 bits.
249
+ *
250
+ * @internal
251
+ */
252
+ function toHalfFloat(value) {
253
+ if (Number.isNaN(value)) return 32256;
254
+ const sign = value < 0 || Object.is(value, -0) ? 32768 : 0;
255
+ const magnitude = Math.min(Math.abs(value), 65504);
256
+ if (magnitude < 2 ** -24) return sign;
257
+ if (magnitude < 2 ** -14) return sign | Math.round(magnitude / 2 ** -24);
258
+ const exponent = Math.floor(Math.log2(magnitude));
259
+ const mantissa = Math.round((magnitude / 2 ** exponent - 1) * 1024);
260
+ return sign | (exponent + 15 << 10) + mantissa;
261
+ }
262
+ /**
263
+ * Finds the probes around a coordinate on one axis.
264
+ *
265
+ * @param value - The world coordinate.
266
+ * @param origin - The grid origin on this axis.
267
+ * @param cell - The cell size on this axis.
268
+ * @param count - The probe count on this axis.
269
+ * @returns The cell.
270
+ */
271
+ function gridCoordinate(value, origin, cell, count) {
272
+ const g = Math.min(Math.max((value - origin) / cell, 0), count - 1);
273
+ const low = Math.min(Math.floor(g), Math.max(count - 2, 0));
274
+ return {
275
+ low,
276
+ high: Math.min(low + 1, count - 1),
277
+ t: g - low
278
+ };
279
+ }
280
+ /**
281
+ * Reads `{ x, y, z }` whose components all pass a check.
282
+ *
283
+ * @param value - The candidate.
284
+ * @param check - The per-component test.
285
+ * @returns A copy, or `null`.
286
+ */
287
+ function readVec3(value, check) {
288
+ const record = asRecord(value);
289
+ if (record === null) return null;
290
+ const { x, y, z } = record;
291
+ if (typeof x !== "number" || typeof y !== "number" || typeof z !== "number" || ![
292
+ x,
293
+ y,
294
+ z
295
+ ].every(check)) return null;
296
+ return {
297
+ x,
298
+ y,
299
+ z
300
+ };
301
+ }
302
+ /**
303
+ * Narrows a value to a plain record.
304
+ *
305
+ * @param value - The candidate.
306
+ * @returns The record, or `null` for anything else.
307
+ */
308
+ function asRecord(value) {
309
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
310
+ return value;
311
+ }
312
+ /**
313
+ * The error for a malformed grid.
314
+ *
315
+ * @param address - Where it came from.
316
+ * @param problem - What is wrong.
317
+ * @returns The error.
318
+ */
319
+ function invalid(address, problem) {
320
+ return new IgnifxError(CoreErrorCode.invalidAssetFile, `${address} is not an ${LIGHT_PROBE_FILE_FORMAT} file.`, {
321
+ context: {
322
+ file: address,
323
+ format: LIGHT_PROBE_FILE_FORMAT
324
+ },
325
+ hint: `Fix the file: ${problem}.`
326
+ });
327
+ }
328
+ //#endregion
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
+
331
+ //# sourceMappingURL=light-probe-asset-B60_X-yN.js.map
@@ -0,0 +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,IA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