@ignifx/core 0.2.1 → 0.3.1

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 (37) hide show
  1. package/dist/async-pipelines-CI5uT5iZ.js +26 -0
  2. package/dist/async-pipelines-CI5uT5iZ.js.map +1 -0
  3. package/dist/color-DrR6GFTd.js +351 -0
  4. package/dist/color-DrR6GFTd.js.map +1 -0
  5. package/dist/effect-task-CMbuO6Kb.js +205 -0
  6. package/dist/effect-task-CMbuO6Kb.js.map +1 -0
  7. package/dist/environment-C_JfuAjj.js +224 -0
  8. package/dist/environment-C_JfuAjj.js.map +1 -0
  9. package/dist/ignifx-error-R1ma_Lzv.js +544 -0
  10. package/dist/ignifx-error-R1ma_Lzv.js.map +1 -0
  11. package/dist/index.d.ts +3756 -1656
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +6404 -5777
  14. package/dist/index.js.map +1 -1
  15. package/dist/instanced-mesh-instance-Cgx1H87p.js +701 -0
  16. package/dist/instanced-mesh-instance-Cgx1H87p.js.map +1 -0
  17. package/dist/material-plugin-CTaWZXEk.js +485 -0
  18. package/dist/material-plugin-CTaWZXEk.js.map +1 -0
  19. package/dist/math-utils-BcDnL-gi.js +277 -0
  20. package/dist/math-utils-BcDnL-gi.js.map +1 -0
  21. package/dist/mesh-CnK_PX46.js +811 -0
  22. package/dist/mesh-CnK_PX46.js.map +1 -0
  23. package/dist/post-effect-C42XJFmo.js +155 -0
  24. package/dist/post-effect-C42XJFmo.js.map +1 -0
  25. package/dist/post-effect-compiler-DTlkT1si.js +311 -0
  26. package/dist/post-effect-compiler-DTlkT1si.js.map +1 -0
  27. package/dist/shader-declaration-5q__jycG.js +165 -0
  28. package/dist/shader-declaration-5q__jycG.js.map +1 -0
  29. package/dist/shader-material-DssOqsvZ.js +1009 -0
  30. package/dist/shader-material-DssOqsvZ.js.map +1 -0
  31. package/dist/shader-material-Xk7Oc9UG.js +207 -0
  32. package/dist/shader-material-Xk7Oc9UG.js.map +1 -0
  33. package/dist/shader-pragma-CNAK4SIb.js +685 -0
  34. package/dist/shader-pragma-CNAK4SIb.js.map +1 -0
  35. package/dist/surface-shader-C2HtysNN.js +1397 -0
  36. package/dist/surface-shader-C2HtysNN.js.map +1 -0
  37. package/package.json +2 -2
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mesh-CnK_PX46.js","names":["updateMeshPositions","updateMeshNormals","updateMeshUvs","updateMeshColors"],"sources":["../src/lite/node.ts","../src/lite/gpu/mesh.ts"],"sourcesContent":["import {\n createTransformNode,\n mat4Decompose,\n setParent,\n setSubtreeVisible,\n type IWorldMatrixProvider,\n type SceneNode,\n} from \"@babylonjs/lite\";\nimport type { MutableQuat, MutableVec3 } from \"../math/types.js\";\n\n/**\n * Scene-graph half of the Babylon Lite adapter: the transform node primitives the kernel's\n * `Transform` component is built from (`docs/architecture/02-scene-graph.md` §5, §5.1). Together\n * with the other files in this directory it is the only place in the package allowed to import\n * `@babylonjs/lite` (`CONSTITUTION.md` §3.4, coding standards §4).\n *\n * Everything here is `@internal`: the kernel decides what becomes public API and what stays behind\n * `Transform`. Nothing in this file is re-exported from `src/index.ts`.\n *\n * ## How Lite computes `worldMatrix` (verified against `@babylonjs/lite@1.27.0`\n * `lib/scene/world-matrix-state.js` and `lib/scene/scene-node.js`)\n *\n * Every node owns a *world-matrix state* holding a cached world matrix, a version counter, a\n * parent link, and a list of the states of the children that were linked through that parent\n * property. The rules that follow from the source are:\n *\n * 1. Writing any TRS value calls the node's dirty hook, which clears the cache, increments the\n * version, and **recursively invalidates every linked descendant** — invalidation is pushed\n * down eagerly, not polled.\n * 2. `ObservableVec3`/`ObservableQuat` per-component setters only fire that hook when the value\n * actually changes; the bulk `set(...)`/`copyFrom(...)` methods fire it unconditionally. So\n * `node.position.x = node.position.x` does not bump the version, while\n * `node.position.set(sameX, sameY, sameZ)` does.\n * 3. `worldMatrix` is a getter. On a cache miss it composes the local matrix from TRS and, when a\n * parent is linked, returns `parentWorld × local` (column-major; translation in elements\n * 12/13/14). A node with no parent returns its local matrix directly.\n * 4. A parent that is a plain {@link IWorldMatrixProvider} rather than a Lite scene node (a camera,\n * for instance) cannot be invalidated eagerly, so the child polls `parent.worldMatrixVersion`\n * on every `worldMatrix` and `worldMatrixVersion` read instead.\n * 5. Nothing in that path touches the scene: a transform node never needs `addToScene` for its\n * matrices to be correct. Only renderable objects do (`docs/architecture/02-scene-graph.md`\n * §5.1).\n */\n\n/**\n * A mutable `{ x, y, z }` accepted as an output parameter. Deliberately the minimal shape: Lite's\n * `Vec3`, the math module's `MutableVec3` (which adds `set`/`copyFrom`), a live `ObservableVec3` over\n * a node's TRS, and a plain object literal all satisfy it, so nothing has to be converted.\n *\n * @internal\n */\nexport interface MutableVec3Like {\n /** The x component. */\n x: number;\n /** The y component. */\n y: number;\n /** The z component. */\n z: number;\n}\n\n/**\n * A mutable `{ x, y, z, w }` accepted as an output parameter. The minimal shape, for the same reason\n * as {@link MutableVec3Like}: Lite's `Quat`, the math module's `MutableQuat`, and a plain object\n * literal all satisfy it.\n *\n * @internal\n */\nexport interface MutableQuatLike {\n /** The x component of the quaternion's vector part. */\n x: number;\n /** The y component of the quaternion's vector part. */\n y: number;\n /** The z component of the quaternion's vector part. */\n z: number;\n /** The scalar part. */\n w: number;\n}\n\n/**\n * A writable 16-element matrix sink in column-major order. `Float32Array` (including the math\n * module's `Mat4.elements`), `Float64Array`, and a plain `number[]` all satisfy it, which is why\n * `length` is a plain `number`: `Float32Array` cannot express the literal `16` that Lite's read-only\n * `Mat4` and the math module's `Mat4Like` declare.\n *\n * @internal\n */\nexport interface MutableMat4Like {\n /** Element count; callers must supply at least 16 slots. */\n readonly length: number;\n /** Column-major element access. */\n [index: number]: number;\n}\n\n/**\n * The ignifx identity written into a Lite node's metadata bag so picking results and physics bodies\n * resolve back to the owning entity (`docs/architecture/00-overview.md` §5,\n * `docs/architecture/02-scene-graph.md` §10).\n *\n * @internal\n */\nexport interface NodeTag {\n /** The dense runtime handle of the entity that owns the node. */\n readonly entity: number;\n /** The component that created the node, when the node is not the entity's own transform. */\n readonly component?: number;\n}\n\n/** The single key ignifx owns inside Lite's open `metadata` record. */\nconst METADATA_KEY = \"ignifx\";\n\n/** Number of elements in a 4x4 matrix. */\nconst MATRIX_LENGTH = 16;\n\n/**\n * Creates a pure transform node at the origin with an identity rotation and unit scale.\n *\n * @remarks\n * The node is deliberately **not** added to any Lite scene: a transform node is only a matrix\n * provider, and `worldMatrix` is valid the moment the node exists (see rule 5 in the module\n * documentation). Renderable Lite objects created by components are parented under it and added\n * with `addToScene` separately.\n *\n * @param name - A human-readable name; Lite never uses it for lookup and it need not be unique.\n * @returns A fresh, unparented transform node.\n *\n * @example\n * ```ts\n * const node = createNode(\"Player\");\n * node.position.set(1, 2, 3);\n * ```\n *\n * @internal\n */\nexport function createNode(name: string): SceneNode {\n return createTransformNode(name);\n}\n\n/**\n * Releases a pure transform node.\n *\n * @remarks\n * Lite requires nothing to release a transform node that was never added to a scene: verified in\n * `lib/scene/transform-node.js` and `lib/scene/scene-node.js`, the node is a plain object holding\n * three observable values, one `Float32Array` for the cached world matrix, and closures — no GPU\n * resource, no ref count, no scene registry. (Reference counting in `lib/resource/ref-count.js`\n * applies to meshes and their GPU buffers only, and `disposeScene` never walks transform nodes.)\n *\n * What *does* need doing is breaking the parent link: a linked parent keeps a reference to this\n * node's world-matrix state so it can invalidate it, so a node dropped while still parented is\n * retained by its parent. This function therefore unlinks the node and drops the ignifx tag. It\n * leaves the node's own `children` alone: the kernel destroys children before parents\n * (`docs/architecture/01-lifecycle-and-time.md` §3 step 9), so each child unlinks itself first.\n *\n * @param node - A node from {@link createNode}.\n *\n * @internal\n */\nexport function disposeNode(node: SceneNode): void {\n linkParent(node, null);\n const metadata = node.metadata;\n if (metadata !== undefined) {\n delete metadata[METADATA_KEY];\n }\n}\n\n/**\n * Links `child` under `parent`, **keeping the child's local values** — its world transform moves\n * with the new parent. This is `setParent(parent, { worldPositionStays: false })` in\n * `docs/architecture/02-scene-graph.md` §5.1.\n *\n * @remarks\n * Lite has no public helper for this case (its own `setParent` preserves the world transform), so\n * the adapter does the linking itself: it assigns `child.parent`, which is the setter that\n * re-registers the child's world-matrix state with the new parent and invalidates the subtree, and\n * maintains the `children` arrays on both the old and the new parent so tree traversal stays\n * consistent. Passing the parent the child already has is a no-op.\n *\n * @param child - The node to move.\n * @param parent - The new parent, or `null` to detach the child to world space.\n *\n * @example\n * ```ts\n * linkParent(child, parent); // child keeps localPosition; its world position changes\n * ```\n *\n * @internal\n */\nexport function linkParent(child: SceneNode, parent: SceneNode | null): void {\n const previous = child.parent;\n if (previous === parent) {\n return;\n }\n const previousChildren = childrenOf(previous);\n if (previousChildren !== null) {\n const index = previousChildren.indexOf(child);\n if (index >= 0) {\n previousChildren.splice(index, 1);\n }\n }\n // The setter, not a field write: it swaps the world-matrix state's parent, re-registers this\n // node in the new parent's invalidation list, and bumps `worldMatrixVersion` down the subtree.\n child.parent = parent;\n if (parent !== null && !parent.children.includes(child)) {\n parent.children.push(child);\n }\n}\n\n/**\n * Reparents `child` under `parent` **keeping its world transform**, by delegating to Lite's own\n * `setParent`. This is `setParent(parent, { worldPositionStays: true })`, the ignifx default\n * (`docs/architecture/02-scene-graph.md` §5.1).\n *\n * @remarks\n * Lite snapshots the child's world matrix, relinks the node (maintaining both `children` arrays),\n * then decomposes `inverse(parentWorld) × childWorld` back into local TRS. Two documented caveats\n * carry straight through to ignifx:\n *\n * - **Singular parent matrices.** When the parent's world matrix has a collapsed axis it cannot be\n * inverted, so no local transform can reproduce the child's world. Lite then keeps the parent\n * link and copies the child's world *position* into its local position, leaving rotation and\n * scale uncompensated. Non-uniform-but-invertible parents are fine; zero scale on any axis is\n * not.\n * - **Canonical, not sign-faithful, decomposition.** The local TRS comes from `mat4Decompose`,\n * which folds a reflection into a negative Y scale. The world matrix is reproduced exactly, but a\n * child that had a negative X scale comes back with a negative Y scale and a different rotation.\n *\n * A third caveat in Lite's TSDoc — that `child.parent` links are only established by `addToScene`,\n * so a node from a freshly loaded asset must have its container added before it is reparented —\n * does not apply to nodes ignifx creates, because {@link linkParent} establishes the link itself.\n *\n * @param child - The node to move.\n * @param parent - The new parent, or `null` to detach the child to world space.\n *\n * @internal\n */\nexport function reparentKeepingWorld(child: SceneNode, parent: SceneNode | null): void {\n setParent(child, parent);\n}\n\n/**\n * Copies a node's world matrix into `out`.\n *\n * @remarks\n * Allocation-free on the ignifx side, which is why the destination is a parameter: Lite's\n * `worldMatrix` getter may recompute up the parent chain, and the object it returns is Lite's own\n * cache — never hold on to it. Lite documents `Mat4` as opaque (\"callers MUST NOT depend on the\n * underlying storage\"); it is a `Float32Array` in 1.27.0 (`lib/math/_matrix-allocator.js`), so\n * copying element by element is the only supported read.\n *\n * @param node - The node to read.\n * @param out - A sink of at least 16 elements, written in column-major order.\n * @returns `out`, for chaining.\n *\n * @internal\n */\nexport function readWorldMatrix(node: SceneNode, out: MutableMat4Like): MutableMat4Like {\n const matrix = node.worldMatrix;\n for (let index = 0; index < MATRIX_LENGTH; index += 1) {\n out[index] = matrix[index] ?? 0;\n }\n return out;\n}\n\n/**\n * Reads a node's world-matrix version — the counter that increases whenever the node's world\n * matrix is invalidated, by its own TRS or by any ancestor's.\n *\n * @remarks\n * Snapshot it to detect movement without comparing matrices; systems that maintain acceleration\n * structures do exactly that (`docs/architecture/02-scene-graph.md` §9). The counter is\n * monotonically increasing but not a change *count*: it moves on invalidation, not on\n * recomputation, and a bulk `position.set(...)` bumps it even when the values are unchanged.\n *\n * @param node - The node to read.\n * @returns The current version.\n *\n * @internal\n */\nexport function worldMatrixVersion(node: SceneNode): number {\n return node.worldMatrixVersion;\n}\n\n/**\n * Decomposes a node's world matrix into translation, rotation, and scale, writing into the three\n * output parameters.\n *\n * @remarks\n * The decomposition is canonical rather than sign-faithful: a mirror is folded into a negative Y\n * scale, so recomposing reproduces the matrix but a matrix built from a negative X or Z scale comes\n * back as a negative Y scale plus a different rotation. A degenerate axis (scale below `1e-8`) is\n * tolerated: the rotation stays finite but is meaningless for that axis.\n *\n * ignifx allocates nothing here, but Lite's `mat4Decompose` allocates its own TRS triple per call\n * (`lib/math/mat4-decompose.js`), so this is not yet a zero-allocation path in the sense of coding\n * standards §7. The math module's in-place decomposition replaces the Lite call when it lands.\n *\n * @param node - The node to read.\n * @param outPosition - Receives the world translation.\n * @param outRotation - Receives the world rotation as a unit quaternion.\n * @param outScale - Receives the per-axis world scale.\n *\n * @internal\n */\nexport function decomposeWorld(\n node: SceneNode,\n outPosition: MutableVec3Like,\n outRotation: MutableQuatLike,\n outScale: MutableVec3Like,\n): void {\n const decomposed = mat4Decompose(node.worldMatrix);\n outPosition.x = decomposed.translation.x;\n outPosition.y = decomposed.translation.y;\n outPosition.z = decomposed.translation.z;\n outRotation.x = decomposed.rotation.x;\n outRotation.y = decomposed.rotation.y;\n outRotation.z = decomposed.rotation.z;\n outRotation.w = decomposed.rotation.w;\n outScale.x = decomposed.scale.x;\n outScale.y = decomposed.scale.y;\n outScale.z = decomposed.scale.z;\n}\n\n/**\n * Shows or hides a node and its whole subtree.\n *\n * @remarks\n * Lite materializes the cascade at write time — it walks `children` and writes `visible` on every\n * descendant — so a node added to the subtree afterwards does not inherit the state and must be\n * set separately. This is how entity deactivation hides render objects\n * (`docs/architecture/01-lifecycle-and-time.md` §6); removing a mesh from its last scene disposes\n * it permanently, so visibility, never removal, is the deactivation path.\n *\n * @param node - The subtree root.\n * @param visible - `true` to show the subtree, `false` to hide it.\n *\n * @internal\n */\nexport function setNodeVisible(node: SceneNode, visible: boolean): void {\n setSubtreeVisible(node, visible);\n}\n\n/**\n * Shows or hides **one** node, without touching its subtree.\n *\n * @remarks\n * Lite's `visible` is per node — the renderer reads each node's own flag, and `setSubtreeVisible`\n * is only a bulk helper that materialises a cascade at write time. ignifx already materialises\n * `activeInHierarchy` over the subtree itself, so it writes one flag per entity: correct for a\n * subtree that mixes active and inactive entities, and linear rather than quadratic.\n *\n * @param node - The node to show or hide.\n * @param visible - `true` to show it, `false` to hide it.\n *\n * @internal\n */\nexport function setNodeSelfVisible(node: SceneNode, visible: boolean): void {\n node.visible = visible;\n}\n\n/**\n * Writes the ignifx identity into a node's Lite metadata bag, under the single `ignifx` key.\n *\n * @remarks\n * `LiteMetadata` is an open record (`{ gltf?: GltfMetadata; [key: string]: unknown }`), so the tag\n * coexists with the `gltf.extras` a glTF load writes. The metadata object is created on demand;\n * nodes ignifx never tags keep `metadata` undefined.\n *\n * @param node - The node to tag.\n * @param tag - The owning entity, and the component that created the node when it is not the\n * entity's own transform.\n *\n * @internal\n */\nexport function tagNode(node: SceneNode, tag: NodeTag): void {\n const metadata = (node.metadata ??= {});\n metadata[METADATA_KEY] = tag;\n}\n\n/**\n * Reads the ignifx identity back from a node.\n *\n * @param node - The node to read; it may be any Lite node, including one ignifx never created.\n * @returns The tag {@link tagNode} wrote, or `null` when the node carries none.\n *\n * @internal\n */\nexport function readNodeTag(node: SceneNode): NodeTag | null {\n const metadata = node.metadata;\n if (metadata === undefined) {\n return null;\n }\n const value = metadata[METADATA_KEY];\n if (typeof value !== \"object\" || value === null || !(\"entity\" in value)) {\n return null;\n }\n const entity = value.entity;\n if (typeof entity !== \"number\") {\n return null;\n }\n const component = \"component\" in value ? value.component : undefined;\n return typeof component === \"number\" ? { entity, component } : { entity };\n}\n\n/**\n * The `children` array of a world-matrix provider, when it has one.\n *\n * @remarks\n * `SceneNode.parent` is typed as the minimal {@link IWorldMatrixProvider}, which declares no\n * `children`, but every parent ignifx links is a scene node. Lite's own `setParent` solves this the\n * same way (`lib/scene/set-parent.js`), and the array check keeps a non-node provider — a camera,\n * say — from being treated as a tree node.\n *\n * @param provider - The candidate parent.\n * @returns The provider's children, or `null` when it is not a tree node.\n */\nfunction childrenOf(provider: IWorldMatrixProvider | null): SceneNode[] | null {\n if (provider === null || !(\"children\" in provider)) {\n return null;\n }\n const children = provider.children;\n // The invariant is that a world-matrix provider with\n // an array-valued `children` is a `SceneNode`, which is what Lite itself assumes here.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return Array.isArray(children) ? (children as SceneNode[]) : null;\n}\n\n/**\n * The Babylon Lite node an ignifx `Transform` wraps, re-exported under an ignifx name so that\n * feature code can name the type without importing `@babylonjs/lite`\n * (`CONSTITUTION.md` §3.4, coding standards §4).\n *\n * @remarks\n * Unstable: it is Lite's type, reachable only through documented `.lite` escape hatches, and it is\n * excluded from the stability guarantees of `CONSTITUTION.md` Article IV.\n *\n * @public\n */\nexport type LiteSceneNode = SceneNode;\n\n/**\n * The node's local position as a live, writable view.\n *\n * @remarks\n * Zero-copy: the returned object *is* Lite's `ObservableVec3` over the node's TRS, so `.x += 1`,\n * `.set(x, y, z)`, and `.copyFrom(v)` write straight through and invalidate the subtree's world\n * matrices (`docs/architecture/02-scene-graph.md` §5). Never hold it past the node's lifetime.\n *\n * @param node - The node to view.\n * @returns The live local position.\n *\n * @internal\n */\nexport function localPosition(node: SceneNode): MutableVec3 {\n return node.position;\n}\n\n/**\n * The node's local rotation as a live, writable view.\n *\n * @param node - The node to view.\n * @returns The live local rotation quaternion.\n *\n * @internal\n */\nexport function localRotation(node: SceneNode): MutableQuat {\n return node.rotationQuaternion;\n}\n\n/**\n * The node's local scale as a live, writable view.\n *\n * @param node - The node to view.\n * @returns The live local scale.\n *\n * @internal\n */\nexport function localScale(node: SceneNode): MutableVec3 {\n return node.scaling;\n}\n\n/**\n * Reads a node's own visibility flag.\n *\n * @remarks\n * Lite leaves `visible` `undefined` on a node that was never hidden, which means *visible*; this\n * normalises that to `true` so callers never have to spell the tri-state out. Only\n * {@link setNodeVisible} writes it, and it materialises the cascade at write time.\n *\n * @param node - The node to read.\n * @returns `true` when the node renders.\n *\n * @internal\n */\nexport function isNodeVisible(node: SceneNode): boolean {\n return node.visible !== false;\n}\n\n/**\n * Renames a node.\n *\n * @remarks\n * Lite never uses the name for lookup, so this is purely for debugging and for the names that show\n * up in Lite-side tooling; ignifx keeps `Entity.name` as the source of truth and mirrors it here.\n *\n * @param node - The node to rename.\n * @param name - The new name.\n *\n * @internal\n */\nexport function setNodeName(node: SceneNode, name: string): void {\n node.name = name;\n}\n\n/**\n * The parent a node is currently linked to, when that parent is itself a scene node.\n *\n * @param node - The node to read.\n * @returns The parent node, or `null` when the node is unparented or its parent is a bare\n * world-matrix provider such as a camera.\n *\n * @internal\n */\nexport function parentNode(node: SceneNode): SceneNode | null {\n const parent = node.parent;\n if (parent === null || !(\"children\" in parent)) {\n return null;\n }\n // A world-matrix provider that carries `children` is\n // a `SceneNode` — the same invariant Lite's own `setParent` relies on.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return parent as SceneNode;\n}\n","import {\n addToScene,\n cloneTransformNode,\n createBox,\n createCapsule,\n createCylinder,\n createGround,\n createMeshFromData,\n createPlane,\n createSphere,\n createTorus,\n removeFromScene,\n setSubtreeVisible,\n updateMeshColors as liteUpdateMeshColors,\n updateMeshNormals as liteUpdateMeshNormals,\n updateMeshPositions as liteUpdateMeshPositions,\n updateMeshUvs as liteUpdateMeshUvs,\n} from \"@babylonjs/lite\";\nimport type {\n BoxOptions,\n CapsuleOptions,\n CylinderOptions,\n EngineContext,\n GroundOptions,\n Material,\n Mesh,\n PlaneOptions,\n SceneContext,\n SceneNode,\n SphereOptions,\n TorusOptions,\n} from \"@babylonjs/lite\";\n\n/**\n * Mesh half of the Babylon Lite adapter (`docs/architecture/07-rendering.md` §2.3). Every function\n * here needs a WebGPU device — `createMeshFromData` uploads four vertex buffers through\n * `engine._device` (`lib/mesh/mesh.js`, `uploadMeshToGPU`) and the null engine has no `_device` —\n * so the whole module lives under `src/lite/gpu/` and is covered by the browser test project.\n *\n * Everything here is `@internal`.\n *\n * ## Ownership, cloning, and disposal (verified against `@babylonjs/lite@1.27.0`)\n *\n * - `cloneTransformNode(mesh)` (`index.d.ts` 1776, `lib/scene/transform-node.js`) shallow-clones a\n * mesh: the clone gets a fresh transform and **the same `_gpu` wrapper object**, with\n * `retain(_gpu)` bumping a reference count. So N clones of one template share exactly one set of\n * GPU buffers — that is spike S2.4's \"instancing shares GPU buffers\", and it is provable by\n * object identity rather than by measuring memory.\n * - Disposal is driven entirely by scene membership. `removeFromScene` calls `unregisterMeshScene`,\n * and only when the mesh has left its **last** scene does it queue `disposeMeshGpu`, which calls\n * `release(_gpu)` and destroys the buffers only when the count drops to one\n * (`lib/scene/scene-remove.js`, `lib/mesh/mesh-dispose.js`, `lib/resource/ref-count.js`). A\n * template that is never added to a scene therefore keeps its buffers alive no matter how many\n * clones come and go — which is what `docs/architecture/07-rendering.md` §2.3 means by \"the\n * template's buffers stay alive while the asset is retained\".\n * - The flip side is that Lite exports **no** mesh disposer. The only public way to release a\n * template's buffers is {@link disposeMeshTemplate}: add it to a scene and take it out again.\n * - `removeFromScene` also recursively removes a mesh's `children` and nulls its `parent`, so\n * removing a `Model`'s root removes the whole instantiated subtree in one call.\n * - Hiding is `setSubtreeVisible` (exported as `setMeshVisible` too, `index.d.ts` 11199): it\n * cascades `visible` down the subtree and bumps a global visibility epoch. Never remove a mesh\n * from the scene to hide it — that disposes it.\n *\n * ## Updating a mesh's vertices (verified against `lib/mesh/mesh-factories.js`)\n *\n * `updateMesh*` writes the GPU buffer and **nothing else**. Three consequences, all of them\n * surprising enough to be worth stating where the calls are:\n *\n * 1. **The retained CPU arrays are not replaced.** `createMeshFromData` keeps `_cpuPositions`,\n * `_cpuNormals`, `_cpuUvs` and `_cpuIndices` — the arrays it was handed — and Lite's CPU ray\n * pick reads them (`lib/picking/ray-pick.js`). Only `updateMeshGeometry`/`resizeMeshGeometry`\n * re-retain, through `retainMeshGeometry`. So an update that hands over a *different* array\n * leaves picking looking at the old geometry, while an update after mutating the retained array\n * in place leaves picking exact. `MeshAsset` keeps its own copy in step for that reason.\n * 2. **Bounds are not recomputed.** `retainMeshGeometry` is what calls `computeAabb` and writes\n * `boundMin`/`boundMax`; the partial updaters do not. `Mesh`'s own declaration says a consumer\n * \"MAY overwrite these with a wider hand-computed box\", so {@link setMeshBounds} exists and\n * `MeshAsset.updatePositions` uses it.\n * 3. **A cloned template cannot be updated at all.** `writeVertexAttributeRange` throws\n * (`ThrowLiteError(360)`) when `mesh._gpu._refCount > 1`, and cloning a mesh retains that very\n * wrapper. A `MeshAsset` a `MeshRenderer` has drawn is therefore frozen; a mesh meant to be\n * edited is a renderable of its own, which is the shape the terrain chunk adapter uses.\n */\n\n/**\n * The Babylon Lite mesh a `MeshAsset` template and a `MeshRenderer` clone are, re-exported under an\n * ignifx name so feature code can name the type without importing `@babylonjs/lite`\n * (`CONSTITUTION.md` §3.4, coding standards §4).\n *\n * @remarks\n * Unstable: it is Lite's own type, reachable only through documented `.lite` escape hatches, and it\n * is excluded from the stability guarantees of `CONSTITUTION.md` Article IV.\n *\n * @public\n */\nexport type LiteMesh = Mesh;\n\n/**\n * Creates a box template.\n *\n * @param engine - The engine that owns the GPU buffers.\n * @param options - A uniform size, or per-axis dimensions.\n * @returns The mesh. It belongs to no scene yet.\n *\n * @example\n * ```ts\n * const template = createBoxMesh(engine, { size: 2 });\n * const instance = cloneMeshUnderNode(template, entityNode);\n * addMeshToScene(scene, instance);\n * ```\n *\n * @internal\n */\nexport function createBoxMesh(engine: EngineContext, options?: number | BoxOptions): Mesh {\n return createBox(engine, options);\n}\n\n/**\n * Creates a sphere template.\n *\n * @param engine - The engine that owns the GPU buffers.\n * @param options - Segment count and diameters.\n * @returns The mesh.\n *\n * @internal\n */\nexport function createSphereMesh(engine: EngineContext, options?: SphereOptions): Mesh {\n return createSphere(engine, options);\n}\n\n/**\n * Creates a plane template in the XY plane.\n *\n * @param engine - The engine that owns the GPU buffers.\n * @param options - Size, or width and height.\n * @returns The mesh.\n *\n * @internal\n */\nexport function createPlaneMesh(engine: EngineContext, options?: PlaneOptions): Mesh {\n return createPlane(engine, options);\n}\n\n/**\n * Creates a subdivided ground template in the XZ plane.\n *\n * @param engine - The engine that owns the GPU buffers.\n * @param options - Width, height, subdivisions, and UV scale.\n * @returns The mesh.\n *\n * @internal\n */\nexport function createGroundMesh(engine: EngineContext, options?: GroundOptions): Mesh {\n return createGround(engine, options);\n}\n\n/**\n * Creates a cylinder template along the Y axis.\n *\n * @param engine - The engine that owns the GPU buffers.\n * @param options - Height, diameters, and tessellation.\n * @returns The mesh.\n *\n * @internal\n */\nexport function createCylinderMesh(engine: EngineContext, options?: CylinderOptions): Mesh {\n return createCylinder(engine, options);\n}\n\n/**\n * Creates a capsule template along the Y axis.\n *\n * @remarks\n * `height` is the **total** height including both caps (`index.d.ts` 1523), which is the same\n * convention `@ignifx/physics`'s capsule collider uses, so a renderer and a collider built from one\n * pair of numbers line up.\n *\n * @param engine - The engine that owns the GPU buffers.\n * @param options - Height, radius, and tessellation.\n * @returns The mesh.\n *\n * @internal\n */\nexport function createCapsuleMesh(engine: EngineContext, options?: CapsuleOptions): Mesh {\n return createCapsule(engine, options);\n}\n\n/**\n * Creates a torus template in the XZ plane.\n *\n * @param engine - The engine that owns the GPU buffers.\n * @param options - Diameter, thickness, and tessellation.\n * @returns The mesh.\n *\n * @internal\n */\nexport function createTorusMesh(engine: EngineContext, options?: TorusOptions): Mesh {\n return createTorus(engine, options);\n}\n\n/**\n * Creates a mesh from raw vertex data.\n *\n * @remarks\n * Lite keeps a reference to the arrays that are handed in — it does not copy them — and uses them\n * for CPU ray picking and bounds (`lib/mesh/mesh-factories.js`). Callers must not mutate them\n * afterwards.\n *\n * @param engine - The engine that owns the GPU buffers.\n * @param name - A debug name.\n * @param positions - Three floats per vertex.\n * @param normals - Three floats per vertex.\n * @param indices - Three indices per triangle.\n * @param uvs - Two floats per vertex, or omitted.\n * @param uvs2 - Two floats per vertex for the second UV set, or omitted.\n * @param tangents - Four floats per vertex, or omitted.\n * @param colors - Four floats per vertex, or omitted.\n * @returns The mesh.\n *\n * @internal\n */\nexport function createMeshFromGeometry(\n engine: EngineContext,\n name: string,\n positions: Float32Array,\n normals: Float32Array,\n indices: Uint32Array,\n uvs?: Float32Array,\n uvs2?: Float32Array,\n tangents?: Float32Array,\n colors?: Float32Array,\n): Mesh {\n return createMeshFromData(engine, name, positions, normals, indices, uvs, uvs2, tangents, colors);\n}\n\n/**\n * Re-uploads part of a mesh's position buffer.\n *\n * @remarks\n * A no-op range is accepted; an out-of-range one, or a mesh whose GPU geometry has co-owners,\n * throws a Lite error (see the module note). It does **not** refresh the CPU picking geometry or\n * the bounds.\n *\n * @param engine - The engine that owns the buffer.\n * @param mesh - The mesh to update.\n * @param positions - Three floats per vertex, read from index 0.\n * @param vertexOffset - The first destination vertex to overwrite.\n * @param vertexCount - How many vertices to write.\n *\n * @internal\n */\nexport function updateMeshPositions(\n engine: EngineContext,\n mesh: Mesh,\n positions: Float32Array,\n vertexOffset: number,\n vertexCount: number,\n): void {\n liteUpdateMeshPositions(engine, mesh, positions, vertexOffset, vertexCount);\n}\n\n/**\n * Re-uploads part of a mesh's normal buffer.\n *\n * @param engine - The engine that owns the buffer.\n * @param mesh - The mesh to update.\n * @param normals - Three floats per vertex.\n * @param vertexOffset - The first destination vertex to overwrite.\n * @param vertexCount - How many vertices to write.\n *\n * @internal\n */\nexport function updateMeshNormals(\n engine: EngineContext,\n mesh: Mesh,\n normals: Float32Array,\n vertexOffset: number,\n vertexCount: number,\n): void {\n liteUpdateMeshNormals(engine, mesh, normals, vertexOffset, vertexCount);\n}\n\n/**\n * Re-uploads part of a mesh's UV buffer.\n *\n * @remarks\n * Lite makes it a no-op when the mesh was created without UVs, rather than an error.\n *\n * @param engine - The engine that owns the buffer.\n * @param mesh - The mesh to update.\n * @param uvs - Two floats per vertex.\n * @param vertexOffset - The first destination vertex to overwrite.\n * @param vertexCount - How many vertices to write.\n *\n * @internal\n */\nexport function updateMeshUvs(\n engine: EngineContext,\n mesh: Mesh,\n uvs: Float32Array,\n vertexOffset: number,\n vertexCount: number,\n): void {\n liteUpdateMeshUvs(engine, mesh, uvs, vertexOffset, vertexCount);\n}\n\n/**\n * Re-uploads part of a mesh's vertex-colour buffer.\n *\n * @remarks\n * The colour attribute is `vec4`, and Lite makes the call a no-op when the mesh was created without\n * colours.\n *\n * @param engine - The engine that owns the buffer.\n * @param mesh - The mesh to update.\n * @param colors - Four floats per vertex.\n * @param vertexOffset - The first destination vertex to overwrite.\n * @param vertexCount - How many vertices to write.\n *\n * @internal\n */\nexport function updateMeshColors(\n engine: EngineContext,\n mesh: Mesh,\n colors: Float32Array,\n vertexOffset: number,\n vertexCount: number,\n): void {\n liteUpdateMeshColors(engine, mesh, colors, vertexOffset, vertexCount);\n}\n\n/**\n * Writes a mesh's object-local bounding box.\n *\n * @remarks\n * `Mesh.boundMin`/`boundMax` are declared consumer-writable, and writing them is the only way to\n * keep the shadow fit, the thin-instance culler and the Havok shape extents honest after a partial\n * vertex update — none of the partial updaters recomputes them. The existing arrays are mutated in\n * place when they are there, so repeated sculpting allocates nothing.\n *\n * @param mesh - The mesh to re-bound.\n * @param minX - The smallest X.\n * @param minY - The smallest Y.\n * @param minZ - The smallest Z.\n * @param maxX - The largest X.\n * @param maxY - The largest Y.\n * @param maxZ - The largest Z.\n *\n * @internal\n */\nexport function setMeshBounds(\n mesh: Mesh,\n minX: number,\n minY: number,\n minZ: number,\n maxX: number,\n maxY: number,\n maxZ: number,\n): void {\n const boundMin = mesh.boundMin;\n if (boundMin === undefined) {\n mesh.boundMin = [minX, minY, minZ];\n } else {\n boundMin[0] = minX;\n boundMin[1] = minY;\n boundMin[2] = minZ;\n }\n const boundMax = mesh.boundMax;\n if (boundMax === undefined) {\n mesh.boundMax = [maxX, maxY, maxZ];\n } else {\n boundMax[0] = maxX;\n boundMax[1] = maxY;\n boundMax[2] = maxZ;\n }\n}\n\n/**\n * Gives a cloned mesh bounding-box arrays of its own.\n *\n * @remarks\n * `cloneMeshNode` shallow-spreads the template (`lib/scene/transform-node.js`), so a clone starts\n * out sharing the template's `boundMin`/`boundMax` arrays and {@link setMeshBounds} — which mutates\n * in place — would write through to the template and to every other clone. Any caller that re-bounds\n * one clone alone has to call this first.\n *\n * @param mesh - The clone.\n *\n * @internal\n */\nexport function detachMeshBounds(mesh: Mesh): void {\n const boundMin = mesh.boundMin;\n if (boundMin !== undefined) {\n mesh.boundMin = [boundMin[0], boundMin[1], boundMin[2]];\n }\n const boundMax = mesh.boundMax;\n if (boundMax !== undefined) {\n mesh.boundMax = [boundMax[0], boundMax[1], boundMax[2]];\n }\n}\n\n/**\n * Recomputes a mesh's object-local bounding box from a position array and writes it.\n *\n * @remarks\n * The partial vertex updaters leave `boundMin`/`boundMax` alone (see the module note), and every\n * consumer that fits a shadow cascade, culls a thin instance, or measures a Havok shape reads them.\n * One linear pass, no allocation. A position array too short to hold one vertex leaves the bounds\n * as they were.\n *\n * @param mesh - The mesh to re-bound.\n * @param positions - Three floats per vertex.\n *\n * @internal\n */\nexport function recomputeMeshBounds(mesh: Mesh, positions: Float32Array): void {\n if (positions.length < 3) {\n return;\n }\n let minX = Number.POSITIVE_INFINITY;\n let minY = Number.POSITIVE_INFINITY;\n let minZ = Number.POSITIVE_INFINITY;\n let maxX = Number.NEGATIVE_INFINITY;\n let maxY = Number.NEGATIVE_INFINITY;\n let maxZ = Number.NEGATIVE_INFINITY;\n for (let index = 0; index + 2 < positions.length; index += 3) {\n const x = positions[index] ?? 0;\n const y = positions[index + 1] ?? 0;\n const z = positions[index + 2] ?? 0;\n minX = x < minX ? x : minX;\n minY = y < minY ? y : minY;\n minZ = z < minZ ? z : minZ;\n maxX = x > maxX ? x : maxX;\n maxY = y > maxY ? y : maxY;\n maxZ = z > maxZ ? z : maxZ;\n }\n setMeshBounds(mesh, minX, minY, minZ, maxX, maxY, maxZ);\n}\n\n/**\n * Clones a template — mesh or transform-node subtree — and parents the clone under an entity node.\n *\n * @remarks\n * The clone shares the template's GPU buffers (see the module note). Cloning a mesh whose buffers\n * were already released throws, which is Lite's way of telling you the template outlived its asset.\n *\n * Only the `parent` link is written; the clone is deliberately **not** pushed into the parent's\n * `children` array, for the same reason cameras and lights are not (`./camera.ts`): ignifx\n * transform nodes are never added to a Lite scene, so nothing in Lite walks their children, and\n * `removeFromScene` nulls a removed mesh's `parent` without touching the array it was listed in —\n * so maintaining it would only create a stale entry to clean up.\n *\n * @param template - The mesh or subtree to clone.\n * @param parent - The entity's transform node, or `null` for world space.\n * @returns The cloned root. Add it to the scene with {@link addMeshToScene}.\n *\n * @internal\n */\nexport function cloneMeshUnderNode(template: SceneNode, parent: SceneNode | null): SceneNode {\n const clone = cloneTransformNode(template);\n clone.parent = parent;\n return clone;\n}\n\n/**\n * Adds a mesh — or a transform-node subtree containing meshes — to a render scene.\n *\n * @remarks\n * `addToScene` recurses into `children` and re-parents each one, so a whole instantiated model goes\n * in with one call. When the scene is already registered, the mesh joins Lite's runtime\n * material-swap queue and appears once its material family's renderable has been rebuilt\n * (`docs/architecture/07-rendering.md` §1.1 and ADR-0014).\n *\n * @param scene - The render scene.\n * @param node - The mesh or subtree root to add.\n *\n * @internal\n */\nexport function addMeshToScene(scene: SceneContext, node: SceneNode): void {\n addToScene(scene, node);\n}\n\n/**\n * Removes a mesh — and everything under it — from a render scene, releasing its GPU buffers when it\n * has left its last scene.\n *\n * @remarks\n * This is destruction, not hiding: use {@link setMeshSubtreeVisible} to hide.\n *\n * @param scene - The render scene.\n * @param node - The mesh or subtree root to remove.\n *\n * @internal\n */\nexport function removeMeshFromScene(scene: SceneContext, node: SceneNode): void {\n removeFromScene(scene, node);\n}\n\n/**\n * Shows or hides a mesh and everything under it.\n *\n * @param node - The subtree root.\n * @param visible - `true` to show it, `false` to hide it.\n *\n * @internal\n */\nexport function setMeshSubtreeVisible(node: SceneNode, visible: boolean): void {\n setSubtreeVisible(node, visible);\n}\n\n/**\n * Assigns a mesh's material.\n *\n * @remarks\n * `Mesh.material` is an accessor once the mesh has joined a scene: writing it queues a material\n * swap on every scene the mesh belongs to (`lib/scene/mesh-scene-registry.js`,\n * `installMaterialSetter`). Assigning the material the mesh already has is a no-op.\n *\n * @param mesh - The mesh to change.\n * @param material - The material to draw it with.\n *\n * @internal\n */\nexport function setMeshMaterial(mesh: Mesh, material: Material): void {\n mesh.material = material;\n}\n\n/**\n * Sets whether a mesh is darkened by shadow maps.\n *\n * @param mesh - The mesh to change.\n * @param receiveShadows - `true` to sample shadow maps on this mesh.\n *\n * @internal\n */\nexport function setMeshReceiveShadows(mesh: Mesh, receiveShadows: boolean): void {\n mesh.receiveShadows = receiveShadows;\n}\n\n/**\n * Sets a mesh's sort key within its phase. Lower values are drawn first.\n *\n * @param mesh - The mesh to change.\n * @param renderOrder - The sort key; it only orders within the opaque or the transparent phase.\n *\n * @internal\n */\nexport function setMeshRenderOrder(mesh: Mesh, renderOrder: number): void {\n mesh.renderOrder = renderOrder;\n}\n\n/**\n * Sets whether picking considers a mesh at all.\n *\n * @remarks\n * `pickable === false` removes the mesh from both the GPU picker's candidate list and the CPU ray\n * test, so it neither occludes nor returns a hit (`index.d.ts` 7214, `lib/picking/ray-pick.js`).\n *\n * @param mesh - The mesh to change.\n * @param pickable - `true` to allow picking.\n *\n * @internal\n */\nexport function setMeshPickable(mesh: Mesh, pickable: boolean): void {\n mesh.pickable = pickable;\n}\n\n/**\n * Gives a mesh the string id Lite's light include/exclude sets match on.\n *\n * @param mesh - The mesh to name.\n * @param id - The id. It should be unique within the scene.\n *\n * @internal\n */\nexport function setMeshId(mesh: Mesh, id: string): void {\n mesh.id = id;\n}\n\n/**\n * Replaces the materials of every mesh in a subtree whose current material carries one of the given\n * names.\n *\n * @remarks\n * `Material.name` is \"populated by loaders from the source asset (e.g. the glTF material name) so\n * callers can look a material up by name\" (`index.d.ts`), which is the identifier\n * `docs/architecture/07-rendering.md` §2.4 means by \"by material name\". Assigning `Mesh.material`\n * queues a material swap on every scene the mesh belongs to; assigning the material a mesh already\n * has is a no-op, so re-running this is cheap.\n *\n * @param node - The subtree root.\n * @param overrides - Source material name to replacement material.\n * @returns How many meshes were re-materialled.\n *\n * @internal\n */\nexport function overrideSubtreeMaterials(node: SceneNode, overrides: ReadonlyMap<string, Material>): number {\n let changed = 0;\n if (\"material\" in node) {\n // A scene node that carries `material` is a mesh —\n // the same structural test Lite's own scene walk uses.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const mesh = node as Mesh;\n const name = mesh.material.name;\n const replacement = name === undefined ? undefined : overrides.get(name);\n if (replacement !== undefined && replacement !== mesh.material) {\n mesh.material = replacement;\n changed += 1;\n }\n }\n const children = node.children;\n for (let index = 0; index < children.length; index += 1) {\n const child = children[index];\n if (child !== undefined) {\n changed += overrideSubtreeMaterials(child, overrides);\n }\n }\n return changed;\n}\n\n/**\n * Releases a template mesh's GPU buffers.\n *\n * @remarks\n * Lite exports no mesh disposer: a mesh's buffers are freed only when it leaves its last scene\n * (`lib/scene/scene-remove.js`). A template that was never added to a scene therefore has to be\n * added and removed to be released, which is exactly what this does. Two consequences the caller\n * must respect:\n *\n * 1. The template must carry no material, or the round trip will build and immediately tear down a\n * renderable for it. Templates created by the factories above start with none.\n * 2. Any clone still alive keeps the shared buffers: the reference count only reaches zero when the\n * last co-owner has gone. Releasing the template while clones are in a scene is safe, but the\n * template can no longer be cloned afterwards.\n *\n * @param scene - Any scene on the template's engine; it is used only as the round trip's vehicle.\n * @param template - The template to release.\n *\n * @internal\n */\nexport function disposeMeshTemplate(scene: SceneContext, template: Mesh): void {\n addToScene(scene, template);\n removeFromScene(scene, template);\n}\n\n/**\n * Collects every mesh in a subtree — the root included — in depth-first order.\n *\n * @remarks\n * A scene node that carries `material` is a mesh: the same structural test\n * {@link overrideSubtreeMaterials} and Lite's own scene walk use (`index.d.ts` 7156 declares\n * `material` on `Mesh` and nowhere on `SceneNode`, 10104).\n *\n * Call it **once**, when the subtree is instantiated. The clone tree `instantiateContainer` built\n * never changes shape afterwards, so walking it again every frame would put a recursion on the\n * render path for an answer that cannot have moved (coding standards §7).\n *\n * @param node - The subtree root.\n * @param out - The list the meshes are appended to; it is not cleared first.\n *\n * @internal\n */\nexport function collectSubtreeMeshes(node: SceneNode, out: Mesh[]): void {\n if (\"material\" in node) {\n // See the note above.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n out.push(node as Mesh);\n }\n const children = node.children;\n for (let index = 0; index < children.length; index += 1) {\n const child = children[index];\n if (child !== undefined) {\n collectSubtreeMeshes(child, out);\n }\n }\n}\n"],"mappings":";;;AA4GA,MAAM,eAAe;;AAGrB,MAAM,gBAAgB;;;;;;;;;;;;;;;;;;;;;AAsBtB,SAAgB,WAAW,MAAyB;CAClD,OAAO,oBAAoB,IAAI;AACjC;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,YAAY,MAAuB;CACjD,WAAW,MAAM,IAAI;CACrB,MAAM,WAAW,KAAK;CACtB,IAAI,aAAa,KAAA,GACf,OAAO,SAAS;AAEpB;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,WAAW,OAAkB,QAAgC;CAC3E,MAAM,WAAW,MAAM;CACvB,IAAI,aAAa,QACf;CAEF,MAAM,mBAAmB,WAAW,QAAQ;CAC5C,IAAI,qBAAqB,MAAM;EAC7B,MAAM,QAAQ,iBAAiB,QAAQ,KAAK;EAC5C,IAAI,SAAS,GACX,iBAAiB,OAAO,OAAO,CAAC;CAEpC;CAGA,MAAM,SAAS;CACf,IAAI,WAAW,QAAQ,CAAC,OAAO,SAAS,SAAS,KAAK,GACpD,OAAO,SAAS,KAAK,KAAK;AAE9B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,SAAgB,qBAAqB,OAAkB,QAAgC;CACrF,UAAU,OAAO,MAAM;AACzB;;;;;;;;;;;;;;;;;AAkBA,SAAgB,gBAAgB,MAAiB,KAAuC;CACtF,MAAM,SAAS,KAAK;CACpB,KAAK,IAAI,QAAQ,GAAG,QAAQ,eAAe,SAAS,GAClD,IAAI,SAAS,OAAO,UAAU;CAEhC,OAAO;AACT;;;;;;;;;;;;;;;;AAiBA,SAAgB,mBAAmB,MAAyB;CAC1D,OAAO,KAAK;AACd;;;;;;;;;;;;;;;AA2EA,SAAgB,mBAAmB,MAAiB,SAAwB;CAC1E,KAAK,UA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;AACjC;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,qBAAqB,MAAiB,KAAmB;CACvE,IAAI,cAAc,MAGhB,IAAI,KAAK,IAAY;CAEvB,MAAM,WAAW,KAAK;CACtB,KAAK,IAAI,QAAQ,GAAG,QAAQ,SAAS,QAAQ,SAAS,GAAG;EACvD,MAAM,QAAQ,SAAS;EACvB,IAAI,UAAU,KAAA,GACZ,qBAAqB,OAAO,GAAG;CAEnC;AACF"}
@@ -0,0 +1,155 @@
1
+ //#region src/serialization/json-view.ts
2
+ /**
3
+ * Narrows a JSON value to an object. `Array.isArray` alone does not remove `JsonArray` from the
4
+ * `JsonValue` union in a way that lets the object half be indexed by an arbitrary string, so the
5
+ * whole discrimination lives here rather than being repeated with an assertion at every call site.
6
+ *
7
+ * @param value - The JSON to narrow.
8
+ * @returns The object, or `null` when the value is an array, `null`, or a primitive.
9
+ *
10
+ * @internal
11
+ */
12
+ function asJsonObject(value) {
13
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
14
+ return value;
15
+ }
16
+ /**
17
+ * Narrows a JSON value to an array.
18
+ *
19
+ * @param value - The JSON to narrow.
20
+ * @returns The array, or `null` when the value is not one.
21
+ *
22
+ * @internal
23
+ */
24
+ function asJsonArray(value) {
25
+ return Array.isArray(value) ? value : null;
26
+ }
27
+ //#endregion
28
+ //#region src/render/post-effect.ts
29
+ /**
30
+ * What a `PostProcessStack` needs to describe a custom `// @ignifx post` effect: its settings record,
31
+ * the uniforms every effect gets for free, and the schema codec its `values` round-trip through
32
+ * (`docs/plan/2026-09-terrain-particles-shaders.md` §3.3).
33
+ *
34
+ * `PostProcessStack` is in every game's static graph, so the WGSL generator and the uniform layout
35
+ * live in `./post-effect-compiler.ts`, which the `.wgsl` loader pulls in only for a `post` file.
36
+ */
37
+ /**
38
+ * The name a `// @ignifx post` file gives its fragment function.
39
+ *
40
+ * @public
41
+ */
42
+ const POST_EFFECT_FUNCTION = "mainFragment";
43
+ /**
44
+ * The uniforms every post effect's `shaderUniforms` block carries before the file's own, in this
45
+ * order.
46
+ *
47
+ * @remarks
48
+ * `screenSize` is in backing-store pixels — `canvas.width`/`canvas.height` — like everything else
49
+ * the engine reports (`docs/architecture/07-rendering.md` §3). The three clocks are the app's, so
50
+ * `time` freezes under `app.pause()` and `unscaledTime` does not.
51
+ *
52
+ * @public
53
+ */
54
+ const POST_EFFECT_BUILTIN_UNIFORMS = Object.freeze([
55
+ {
56
+ name: "screenSize",
57
+ type: "vec2<f32>"
58
+ },
59
+ {
60
+ name: "time",
61
+ type: "f32"
62
+ },
63
+ {
64
+ name: "unscaledTime",
65
+ type: "f32"
66
+ },
67
+ {
68
+ name: "deltaTime",
69
+ type: "f32"
70
+ }
71
+ ]);
72
+ /**
73
+ * Fills in a custom effect's defaults, so a caller names only what it means to set.
74
+ *
75
+ * @param init - The shader and the fields to set.
76
+ * @returns A complete settings record, ready to push onto `PostProcessStack.custom`.
77
+ *
78
+ * @example
79
+ * ```ts
80
+ * stack.custom.push(customEffect({ shader: vignette, order: 5, values: { amount: 0.6 } }));
81
+ * ```
82
+ *
83
+ * @public
84
+ */
85
+ function customEffect(init) {
86
+ return {
87
+ shader: init.shader,
88
+ enabled: init.enabled ?? true,
89
+ order: init.order ?? 10,
90
+ values: { ...init.values },
91
+ textures: { ...init.textures }
92
+ };
93
+ }
94
+ /** The first binding index a declared texture takes. */
95
+ const FIRST_DECLARED_BINDING = 3;
96
+ /**
97
+ * The binding index of one declared texture, and of its sampler.
98
+ *
99
+ * @param index - The texture's index in declaration order.
100
+ * @returns The texture's binding; the sampler is one higher.
101
+ *
102
+ * @internal
103
+ */
104
+ function declaredTextureBinding(index) {
105
+ return FIRST_DECLARED_BINDING + index * 2;
106
+ }
107
+ /**
108
+ * The codec that round-trips a custom effect's `values` record through a scene file.
109
+ *
110
+ * @remarks
111
+ * A schema field cannot describe these: the uniforms are declared by the `.wgsl`, so `map(f32)`
112
+ * would drop every vector and colour uniform and `map(vec4)` would write `amount: 0.6` as four
113
+ * floats. The codec round-trips exactly what a shader file allows — a number or an array of numbers.
114
+ *
115
+ * @returns The codec, for a `custom()` field.
116
+ *
117
+ * @internal
118
+ */
119
+ function postEffectValuesCodec() {
120
+ return {
121
+ createDefault() {
122
+ return {};
123
+ },
124
+ serialize(value) {
125
+ const json = {};
126
+ for (const name of Object.keys(value).toSorted()) {
127
+ const entry = value[name];
128
+ json[name] = typeof entry === "number" ? entry : [...entry ?? []];
129
+ }
130
+ return json;
131
+ },
132
+ deserialize(json) {
133
+ const value = {};
134
+ const object = asJsonObject(json);
135
+ if (object === null) return value;
136
+ for (const name of Object.keys(object)) {
137
+ const entry = object[name];
138
+ if (typeof entry === "number") value[name] = entry;
139
+ else if (Array.isArray(entry)) value[name] = entry.map((component) => typeof component === "number" ? component : 0);
140
+ }
141
+ return value;
142
+ },
143
+ jsonSchema: {
144
+ type: "object",
145
+ additionalProperties: { oneOf: [{ type: "number" }, {
146
+ type: "array",
147
+ items: { type: "number" }
148
+ }] }
149
+ }
150
+ };
151
+ }
152
+ //#endregion
153
+ export { postEffectValuesCodec as a, declaredTextureBinding as i, POST_EFFECT_FUNCTION as n, asJsonArray as o, customEffect as r, asJsonObject as s, POST_EFFECT_BUILTIN_UNIFORMS as t };
154
+
155
+ //# sourceMappingURL=post-effect-C42XJFmo.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"post-effect-C42XJFmo.js","names":[],"sources":["../src/serialization/json-view.ts","../src/render/post-effect.ts"],"sourcesContent":["import type { JsonArray, JsonObject, JsonValue } from \"../schema/json.js\";\n\n/**\n * Narrows a JSON value to an object. `Array.isArray` alone does not remove `JsonArray` from the\n * `JsonValue` union in a way that lets the object half be indexed by an arbitrary string, so the\n * whole discrimination lives here rather than being repeated with an assertion at every call site.\n *\n * @param value - The JSON to narrow.\n * @returns The object, or `null` when the value is an array, `null`, or a primitive.\n *\n * @internal\n */\nexport function asJsonObject(value: JsonValue | undefined): JsonObject | null {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return null;\n }\n // The guard above is exactly `JsonObject` — an\n // object that is neither `null` nor an array — which is what `JsonValue` leaves in the union.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return value as JsonObject;\n}\n\n/**\n * Narrows a JSON value to an array.\n *\n * @param value - The JSON to narrow.\n * @returns The array, or `null` when the value is not one.\n *\n * @internal\n */\nexport function asJsonArray(value: JsonValue | undefined): JsonArray | null {\n return Array.isArray(value) ? value : null;\n}\n","import { asJsonObject } from \"../serialization/json-view.js\";\nimport type { ShaderAsset } from \"./shader-asset.js\";\nimport type { ShaderTextureDeclaration, ShaderUniformType } from \"./shader-declaration.js\";\nimport type { TextureAsset } from \"./texture-asset.js\";\nimport type { AssetHandle } from \"../assets/types.js\";\nimport type { JsonValue } from \"../schema/json.js\";\nimport type { CustomFieldCodec } from \"../schema/types.js\";\n\n/**\n * What a `PostProcessStack` needs to describe a custom `// @ignifx post` effect: its settings record,\n * the uniforms every effect gets for free, and the schema codec its `values` round-trip through\n * (`docs/plan/2026-09-terrain-particles-shaders.md` §3.3).\n *\n * `PostProcessStack` is in every game's static graph, so the WGSL generator and the uniform layout\n * live in `./post-effect-compiler.ts`, which the `.wgsl` loader pulls in only for a `post` file.\n */\n\n/**\n * The name a `// @ignifx post` file gives its fragment function.\n *\n * @public\n */\nexport const POST_EFFECT_FUNCTION = \"mainFragment\";\n\n/**\n * The uniforms every post effect's `shaderUniforms` block carries before the file's own, in this\n * order.\n *\n * @remarks\n * `screenSize` is in backing-store pixels — `canvas.width`/`canvas.height` — like everything else\n * the engine reports (`docs/architecture/07-rendering.md` §3). The three clocks are the app's, so\n * `time` freezes under `app.pause()` and `unscaledTime` does not.\n *\n * @public\n */\nexport const POST_EFFECT_BUILTIN_UNIFORMS: readonly { readonly name: string; readonly type: ShaderUniformType }[] =\n Object.freeze([\n { name: \"screenSize\", type: \"vec2<f32>\" },\n { name: \"time\", type: \"f32\" },\n { name: \"unscaledTime\", type: \"f32\" },\n { name: \"deltaTime\", type: \"f32\" },\n ]);\n\n/**\n * One custom effect on a `PostProcessStack` (`docs/architecture/07-rendering.md` §2.7).\n *\n * @public\n */\nexport interface CustomEffectSettings {\n /** The `// @ignifx post` shader; `null` records nothing. */\n shader: AssetHandle<ShaderAsset> | null;\n /** Whether the effect runs. */\n enabled: boolean;\n /** Position in the chain; lower runs first, alongside bloom's and SMAA's `order`. */\n order: number;\n /** Overrides of the file's declared uniform defaults, by declared name. */\n values: Record<string, number | readonly number[]>;\n /** Textures for the file's declared samplers, by declared name. */\n textures: Record<string, AssetHandle<TextureAsset> | null>;\n}\n\n/**\n * What {@link customEffect} accepts: a shader and whichever fields differ from the defaults.\n *\n * @public\n */\nexport interface CustomEffectInit {\n /** The `// @ignifx post` shader. */\n readonly shader: AssetHandle<ShaderAsset> | null;\n /** Whether the effect runs. Defaults to `true`. */\n readonly enabled?: boolean;\n /** Position in the chain. Defaults to `10`, which is after the built-ins' defaults. */\n readonly order?: number;\n /** Overrides of the file's declared uniform defaults. */\n readonly values?: Readonly<Record<string, number | readonly number[]>>;\n /** Textures for the file's declared samplers. */\n readonly textures?: Readonly<Record<string, AssetHandle<TextureAsset> | null>>;\n}\n\n/**\n * Fills in a custom effect's defaults, so a caller names only what it means to set.\n *\n * @param init - The shader and the fields to set.\n * @returns A complete settings record, ready to push onto `PostProcessStack.custom`.\n *\n * @example\n * ```ts\n * stack.custom.push(customEffect({ shader: vignette, order: 5, values: { amount: 0.6 } }));\n * ```\n *\n * @public\n */\nexport function customEffect(init: CustomEffectInit): CustomEffectSettings {\n return {\n shader: init.shader,\n enabled: init.enabled ?? true,\n order: init.order ?? 10,\n values: { ...init.values },\n textures: { ...init.textures },\n };\n}\n\n/**\n * The binding index of the chain's current colour.\n *\n * @internal\n */\nexport const INPUT_TEXTURE_BINDING = 1;\n\n/**\n * The binding index of the chain's current colour sampler.\n *\n * @internal\n */\nexport const INPUT_SAMPLER_BINDING = 2;\n\n/** The first binding index a declared texture takes. */\nconst FIRST_DECLARED_BINDING = 3;\n\n/**\n * The binding index of one declared texture, and of its sampler.\n *\n * @param index - The texture's index in declaration order.\n * @returns The texture's binding; the sampler is one higher.\n *\n * @internal\n */\nexport function declaredTextureBinding(index: number): number {\n return FIRST_DECLARED_BINDING + index * 2;\n}\n\n/**\n * One member of a compiled effect's uniform struct, with the byte offset the generated WGSL puts it\n * at.\n *\n * @internal\n */\nexport interface PostEffectUniformField {\n /** The WGSL member name. */\n readonly name: string;\n /** The WGSL type. */\n readonly type: ShaderUniformType;\n /** How many floats the value holds. */\n readonly components: number;\n /** Where the member starts in the uniform buffer, in bytes. */\n readonly byteOffset: number;\n}\n\n/**\n * A `// @ignifx post` file compiled into what Babylon Lite's fullscreen effect path needs.\n *\n * @internal\n */\nexport interface CompiledPostEffect {\n /** The shader's address, for diagnostics and for the chain's identity. */\n readonly address: string;\n /** The whole fragment module: the bindings, the generated structs, the file, and the entry point. */\n readonly fragmentWGSL: string;\n /** The uniform members, built-ins first, in struct order. */\n readonly uniforms: readonly PostEffectUniformField[];\n /** The members by name, for a value write. */\n readonly byName: ReadonlyMap<string, PostEffectUniformField>;\n /** How large the uniform buffer has to be. */\n readonly uniformByteLength: number;\n /** The file's declared samplers, in declaration order. */\n readonly textures: readonly ShaderTextureDeclaration[];\n}\n\n/**\n * The codec that round-trips a custom effect's `values` record through a scene file.\n *\n * @remarks\n * A schema field cannot describe these: the uniforms are declared by the `.wgsl`, so `map(f32)`\n * would drop every vector and colour uniform and `map(vec4)` would write `amount: 0.6` as four\n * floats. The codec round-trips exactly what a shader file allows — a number or an array of numbers.\n *\n * @returns The codec, for a `custom()` field.\n *\n * @internal\n */\nexport function postEffectValuesCodec(): CustomFieldCodec<Record<string, number | readonly number[]>> {\n return {\n createDefault(): Record<string, number | readonly number[]> {\n return {};\n },\n serialize(value: Record<string, number | readonly number[]>): JsonValue {\n const json: Record<string, JsonValue> = {};\n // Lexicographic, so two saves of the same state are byte-identical\n // (`docs/architecture/06-serialization-and-scene-format.md` §1).\n for (const name of Object.keys(value).toSorted()) {\n const entry = value[name];\n json[name] = typeof entry === \"number\" ? entry : [...(entry ?? [])];\n }\n return json;\n },\n deserialize(json: JsonValue): Record<string, number | readonly number[]> {\n const value: Record<string, number | readonly number[]> = {};\n const object = asJsonObject(json);\n if (object === null) {\n return value;\n }\n for (const name of Object.keys(object)) {\n const entry = object[name];\n if (typeof entry === \"number\") {\n value[name] = entry;\n } else if (Array.isArray(entry)) {\n value[name] = entry.map((component) => (typeof component === \"number\" ? component : 0));\n }\n }\n return value;\n },\n jsonSchema: {\n type: \"object\",\n additionalProperties: {\n oneOf: [{ type: \"number\" }, { type: \"array\", items: { type: \"number\" } }],\n },\n },\n };\n}\n"],"mappings":";;;;;;;;;;;AAYA,SAAgB,aAAa,OAAiD;CAC5E,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,MAAM,QAAQ,KAAK,GACpE,OAAO;CAKT,OAAO;AACT;;;;;;;;;AAUA,SAAgB,YAAY,OAAgD;CAC1E,OAAO,MAAM,QAAQ,KAAK,IAAI,QAAQ;AACxC;;;;;;;;;;;;;;;;ACVA,MAAa,uBAAuB;;;;;;;;;;;;AAapC,MAAa,+BACX,OAAO,OAAO;CACZ;EAAE,MAAM;EAAc,MAAM;CAAY;CACxC;EAAE,MAAM;EAAQ,MAAM;CAAM;CAC5B;EAAE,MAAM;EAAgB,MAAM;CAAM;CACpC;EAAE,MAAM;EAAa,MAAM;CAAM;AACnC,CAAC;;;;;;;;;;;;;;AAmDH,SAAgB,aAAa,MAA8C;CACzE,OAAO;EACL,QAAQ,KAAK;EACb,SAAS,KAAK,WAAW;EACzB,OAAO,KAAK,SAAS;EACrB,QAAQ,EAAE,GAAG,KAAK,OAAO;EACzB,UAAU,EAAE,GAAG,KAAK,SAAS;CAC/B;AACF;;AAiBA,MAAM,yBAAyB;;;;;;;;;AAU/B,SAAgB,uBAAuB,OAAuB;CAC5D,OAAO,yBAAyB,QAAQ;AAC1C;;;;;;;;;;;;;AAmDA,SAAgB,wBAAsF;CACpG,OAAO;EACL,gBAA4D;GAC1D,OAAO,CAAC;EACV;EACA,UAAU,OAA8D;GACtE,MAAM,OAAkC,CAAC;GAGzC,KAAK,MAAM,QAAQ,OAAO,KAAK,KAAK,CAAC,CAAC,SAAS,GAAG;IAChD,MAAM,QAAQ,MAAM;IACpB,KAAK,QAAQ,OAAO,UAAU,WAAW,QAAQ,CAAC,GAAI,SAAS,CAAC,CAAE;GACpE;GACA,OAAO;EACT;EACA,YAAY,MAA6D;GACvE,MAAM,QAAoD,CAAC;GAC3D,MAAM,SAAS,aAAa,IAAI;GAChC,IAAI,WAAW,MACb,OAAO;GAET,KAAK,MAAM,QAAQ,OAAO,KAAK,MAAM,GAAG;IACtC,MAAM,QAAQ,OAAO;IACrB,IAAI,OAAO,UAAU,UACnB,MAAM,QAAQ;SACT,IAAI,MAAM,QAAQ,KAAK,GAC5B,MAAM,QAAQ,MAAM,KAAK,cAAe,OAAO,cAAc,WAAW,YAAY,CAAE;GAE1F;GACA,OAAO;EACT;EACA,YAAY;GACV,MAAM;GACN,sBAAsB,EACpB,OAAO,CAAC,EAAE,MAAM,SAAS,GAAG;IAAE,MAAM;IAAS,OAAO,EAAE,MAAM,SAAS;GAAE,CAAC,EAC1E;EACF;CACF;AACF"}
@@ -0,0 +1,311 @@
1
+ import { n as assertNever, o as CoreErrorCode, t as IgnifxError } from "./ignifx-error-R1ma_Lzv.js";
2
+ import { i as declaredTextureBinding, n as POST_EFFECT_FUNCTION, t as POST_EFFECT_BUILTIN_UNIFORMS } from "./post-effect-C42XJFmo.js";
3
+ //#region src/render/post-effect-compiler.ts
4
+ /**
5
+ * Turns a `// @ignifx post` file into the fragment module and uniform layout Babylon Lite's
6
+ * fullscreen-effect path needs (`docs/plan/2026-09-terrain-particles-shaders.md` §3.3).
7
+ *
8
+ * `mainFragment` is a plain function, not an entry point: Lite hard-codes the entry-point names
9
+ * `effectFullscreenVertex` and `effectFragment` (`lib/effect/effect-renderer.js` 7, 258-260), so the
10
+ * entry point is generated here and forwards to it. `createEffectWrapper` takes a byte length and a
11
+ * raw writer and computes no offsets, so the struct's member offsets are worked out here from WGSL's
12
+ * own alignment rules and kept in step with the generated struct.
13
+ *
14
+ * Everything in this module is device-free and deterministic, so it is asserted in Node. It is
15
+ * reached through `./post-effect-support.ts` so a game with no custom post effect never loads it.
16
+ */
17
+ /**
18
+ * Compiles a `// @ignifx post` file into a full fragment module and a uniform layout.
19
+ *
20
+ * @remarks
21
+ * Device-free and deterministic, so the whole thing is unit-testable: the result is a WGSL string
22
+ * and a set of byte offsets. It is memoised per shader asset by {@link compiledPostEffect}, because
23
+ * the chain asks for it on every rebuild.
24
+ *
25
+ * @param shader - The loaded shader asset.
26
+ * @returns The compiled effect.
27
+ * @throws IgnifxError with code `IGX-0709` when the file is not a `post` one, or `IGX-0723` when it
28
+ * declares no `mainFragment` function.
29
+ *
30
+ * @example
31
+ * ```ts
32
+ * const compiled = compilePostEffect(vignette.value);
33
+ * compiled.byName.get("amount")?.byteOffset; // 20, right after the four built-ins
34
+ * ```
35
+ *
36
+ * @internal
37
+ */
38
+ function compilePostEffect(shader) {
39
+ if (shader.declaration.kind !== "post") throw new IgnifxError(CoreErrorCode.invalidAssetFile, `${shader.address} declares @ignifx ${shader.declaration.kind}, not @ignifx post.`, {
40
+ context: {
41
+ file: shader.address,
42
+ format: "@ignifx post",
43
+ kind: shader.declaration.kind
44
+ },
45
+ hint: "A PostProcessStack custom effect takes a .post.wgsl file whose pragma is @ignifx post."
46
+ });
47
+ if (!new RegExp(`\\bfn\\s+mainFragment\\s*\\(`, "u").test(shader.source)) throw new IgnifxError(CoreErrorCode.surfaceHookMissing, `${shader.address} declares no ${POST_EFFECT_FUNCTION} function.`, {
48
+ context: {
49
+ asset: shader.address,
50
+ hook: POST_EFFECT_FUNCTION
51
+ },
52
+ hint: `Add fn ${POST_EFFECT_FUNCTION}(in: PostInput) -> vec4<f32>; the @fragment entry point is generated.`
53
+ });
54
+ const declared = shader.declaration.uniforms.filter((uniform) => !isBuiltinUniformName(uniform.name));
55
+ const layout = layOutUniforms([...POST_EFFECT_BUILTIN_UNIFORMS, ...declared.map((uniform) => ({
56
+ name: uniform.name,
57
+ type: uniform.type
58
+ }))]);
59
+ const byName = /* @__PURE__ */ new Map();
60
+ for (const field of layout.fields) byName.set(field.name, field);
61
+ return {
62
+ address: shader.address,
63
+ fragmentWGSL: buildFragmentModule(shader, layout.fields),
64
+ uniforms: layout.fields,
65
+ byName,
66
+ uniformByteLength: layout.byteLength,
67
+ textures: shader.declaration.textures
68
+ };
69
+ }
70
+ /** The compiled form of each shader asset, so a chain rebuild recompiles nothing. */
71
+ let compiled = null;
72
+ /**
73
+ * The compiled form of a post-effect shader, compiled once per asset.
74
+ *
75
+ * @remarks
76
+ * Keyed on the `ShaderAsset` itself, so a hot reload — which replaces the asset object — recompiles
77
+ * for free.
78
+ *
79
+ * @param shader - The loaded shader asset.
80
+ * @returns The compiled effect.
81
+ * @throws IgnifxError as {@link compilePostEffect} documents.
82
+ *
83
+ * @internal
84
+ */
85
+ function compiledPostEffect(shader) {
86
+ const cache = compiled ??= /* @__PURE__ */ new WeakMap();
87
+ const hit = cache.get(shader);
88
+ if (hit !== void 0) return hit;
89
+ const built = compilePostEffect(shader);
90
+ cache.set(shader, built);
91
+ return built;
92
+ }
93
+ /**
94
+ * Writes an effect's current values into the bytes its uniform buffer takes.
95
+ *
96
+ * @remarks
97
+ * The built-in clocks and `screenSize` are written by the caller through the same `out` buffer, so
98
+ * this only fills in the declared members: the declaration's default first, then the settings'
99
+ * override. Unknown names are refused, which is what makes a typo in a `.scene.json` visible.
100
+ *
101
+ * @param effect - The compiled effect.
102
+ * @param shader - The shader, for its declared defaults.
103
+ * @param values - The overrides.
104
+ * @param out - The uniform bytes, at least `effect.uniformByteLength` long.
105
+ * @throws IgnifxError with code `IGX-0712` for an undeclared name, or `IGX-0713` for a wrongly
106
+ * shaped value.
107
+ *
108
+ * @internal
109
+ */
110
+ function writePostEffectValues(effect, shader, values, out) {
111
+ for (const uniform of shader.declaration.uniforms) {
112
+ const field = effect.byName.get(uniform.name);
113
+ if (field === void 0) continue;
114
+ writeField(field, uniform.defaultValue, effect.address, out);
115
+ }
116
+ for (const name in values) {
117
+ if (!Object.hasOwn(values, name)) continue;
118
+ const field = effect.byName.get(name);
119
+ const value = values[name];
120
+ if (value === void 0) continue;
121
+ if (field === void 0 || isBuiltinUniformName(name)) throw new IgnifxError(CoreErrorCode.unknownShaderBinding, `${effect.address} declares no uniform named ${name}.`, {
122
+ context: {
123
+ material: effect.address,
124
+ asset: effect.address,
125
+ name
126
+ },
127
+ hint: `It declares ${[...effect.byName.keys()].join(", ")}.`
128
+ });
129
+ writeField(field, value, effect.address, out);
130
+ }
131
+ }
132
+ /**
133
+ * Computes the byte offsets WGSL gives a struct of these members, in this order.
134
+ *
135
+ * @remarks
136
+ * The rules are the WGSL specification's: a member's offset is its predecessor's end rounded up to
137
+ * the member's alignment, and the struct's size is the last member's end rounded up to the struct's
138
+ * alignment — the largest member alignment, and in the **uniform** address space never less than
139
+ * 16. `vec3<f32>` is the one that catches people out: 16-aligned, 12 wide (plan §3.4).
140
+ *
141
+ * @param members - The members, in declaration order.
142
+ * @returns The layout.
143
+ */
144
+ function layOutUniforms(members) {
145
+ const fields = [];
146
+ let offset = 0;
147
+ let structAlignment = 16;
148
+ for (const member of members) {
149
+ const alignment = typeAlignment(member.type);
150
+ const size = typeSize(member.type);
151
+ structAlignment = Math.max(structAlignment, alignment);
152
+ offset = roundUp(offset, alignment);
153
+ fields.push({
154
+ name: member.name,
155
+ type: member.type,
156
+ components: componentCount(member.type),
157
+ byteOffset: offset
158
+ });
159
+ offset += size;
160
+ }
161
+ return {
162
+ fields,
163
+ byteLength: roundUp(offset, structAlignment)
164
+ };
165
+ }
166
+ /**
167
+ * A WGSL type's alignment in the uniform address space, in bytes.
168
+ *
169
+ * @param type - The type.
170
+ * @returns The alignment.
171
+ */
172
+ function typeAlignment(type) {
173
+ switch (type) {
174
+ case "vec2<f32>": return 8;
175
+ case "vec3<f32>":
176
+ case "vec4<f32>":
177
+ case "mat4x4<f32>": return 16;
178
+ case "f32":
179
+ case "u32":
180
+ case "i32": return 4;
181
+ default: return assertNever(type, "shader uniform type");
182
+ }
183
+ }
184
+ /**
185
+ * A WGSL type's size, in bytes.
186
+ *
187
+ * @param type - The type.
188
+ * @returns The size.
189
+ */
190
+ function typeSize(type) {
191
+ switch (type) {
192
+ case "vec2<f32>": return 8;
193
+ case "vec3<f32>": return 12;
194
+ case "vec4<f32>": return 16;
195
+ case "mat4x4<f32>": return 64;
196
+ case "f32":
197
+ case "u32":
198
+ case "i32": return 4;
199
+ default: return assertNever(type, "shader uniform type");
200
+ }
201
+ }
202
+ /**
203
+ * How many floats one uniform of a declared type occupies.
204
+ *
205
+ * @remarks
206
+ * A private copy of `material-plugin.ts`'s `uniformComponentCount`. `PostProcessStack` is in every
207
+ * game's static graph, and importing it from there would drag `defineMaterialPlugin` and the
208
+ * reserved-name table into a bundle that draws no custom shader at all.
209
+ *
210
+ * @param type - The declared WGSL type.
211
+ * @returns The component count: 1, 2, 3, 4, or 16.
212
+ */
213
+ function componentCount(type) {
214
+ switch (type) {
215
+ case "vec2<f32>": return 2;
216
+ case "vec3<f32>": return 3;
217
+ case "vec4<f32>": return 4;
218
+ case "mat4x4<f32>": return 16;
219
+ case "f32":
220
+ case "u32":
221
+ case "i32": return 1;
222
+ default: return assertNever(type, "shader uniform type");
223
+ }
224
+ }
225
+ /**
226
+ * Rounds a value up to a multiple of an alignment.
227
+ *
228
+ * @param value - The value.
229
+ * @param alignment - The alignment, a power of two.
230
+ * @returns The rounded value.
231
+ */
232
+ function roundUp(value, alignment) {
233
+ return Math.ceil(value / alignment) * alignment;
234
+ }
235
+ /**
236
+ * The whole fragment module: bindings, generated structs, the author's file, and the entry point
237
+ * Lite's pipeline looks for.
238
+ *
239
+ * @param shader - The shader asset.
240
+ * @param fields - The uniform members, in struct order.
241
+ * @returns The WGSL.
242
+ */
243
+ function buildFragmentModule(shader, fields) {
244
+ const lines = [
245
+ `struct PostUniforms{${fields.map((field) => `${field.name}:${field.type},`).join("")}}`,
246
+ "@group(0)@binding(0)var<uniform>shaderUniforms:PostUniforms;",
247
+ `@group(0)@binding(${String(1)})var inputTexture:texture_2d<f32>;`,
248
+ `@group(0)@binding(${String(2)})var inputTextureSampler:sampler;`
249
+ ];
250
+ let index = -1;
251
+ for (const declaration of shader.declaration.textures) {
252
+ index += 1;
253
+ const binding = declaredTextureBinding(index);
254
+ const type = declaration.array ? "texture_2d_array<f32>" : "texture_2d<f32>";
255
+ lines.push(`@group(0)@binding(${String(binding)})var ${declaration.name}:${type};`, `@group(0)@binding(${String(binding + 1)})var ${declaration.name}Sampler:sampler;`);
256
+ }
257
+ lines.push("struct PostInput{uv:vec2<f32>,position:vec2<f32>,}", shader.source, "@fragment fn effectFragment(fragment:EffectVertexOutput)->@location(0)vec4<f32>{", "var ignifxPostInput:PostInput;", "ignifxPostInput.uv=fragment.uv;", "ignifxPostInput.position=fragment.position.xy;", `return ${POST_EFFECT_FUNCTION}(ignifxPostInput);`, "}");
258
+ return lines.join("\n");
259
+ }
260
+ /**
261
+ * Writes one member's value into the uniform bytes.
262
+ *
263
+ * @param field - The member.
264
+ * @param value - The value.
265
+ * @param asset - The shader's address, for diagnostics.
266
+ * @param out - The uniform floats.
267
+ * @throws IgnifxError with code `IGX-0713` when the shape does not match.
268
+ */
269
+ function writeField(field, value, asset, out) {
270
+ const index = field.byteOffset / 4;
271
+ if (typeof value === "number") {
272
+ if (field.components !== 1) throw mismatch(field, asset, "a single number");
273
+ out[index] = value;
274
+ return;
275
+ }
276
+ if (value.length !== field.components) throw mismatch(field, asset, `${String(value.length)} floats`);
277
+ out.set(value instanceof Float32Array ? value : Float32Array.from(value), index);
278
+ }
279
+ /**
280
+ * The `IGX-0713` failure a wrongly shaped value produces.
281
+ *
282
+ * @param field - The member.
283
+ * @param asset - The shader's address.
284
+ * @param actual - What the caller passed.
285
+ * @returns The error to throw.
286
+ */
287
+ function mismatch(field, asset, actual) {
288
+ return new IgnifxError(CoreErrorCode.shaderValueMismatch, `${field.name} on ${asset} expects ${field.type} (${String(field.components)} floats), not ${actual}.`, {
289
+ context: {
290
+ name: field.name,
291
+ material: asset,
292
+ expected: field.type,
293
+ actual
294
+ },
295
+ hint: "A post effect's values are numbers and numeric arrays; a colour takes its three or four components."
296
+ });
297
+ }
298
+ /**
299
+ * Whether a name is one of the four uniforms every post effect gets for free.
300
+ *
301
+ * @param name - The candidate.
302
+ * @returns `true` when the engine writes it.
303
+ */
304
+ function isBuiltinUniformName(name) {
305
+ for (const builtin of POST_EFFECT_BUILTIN_UNIFORMS) if (builtin.name === name) return true;
306
+ return false;
307
+ }
308
+ //#endregion
309
+ export { compilePostEffect, compiledPostEffect, writePostEffectValues };
310
+
311
+ //# sourceMappingURL=post-effect-compiler-DTlkT1si.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"post-effect-compiler-DTlkT1si.js","names":[],"sources":["../src/render/post-effect-compiler.ts"],"sourcesContent":["import { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { assertNever, IgnifxError } from \"../errors/ignifx-error.js\";\nimport {\n declaredTextureBinding,\n INPUT_SAMPLER_BINDING,\n INPUT_TEXTURE_BINDING,\n POST_EFFECT_BUILTIN_UNIFORMS,\n POST_EFFECT_FUNCTION,\n} from \"./post-effect.js\";\nimport type { CompiledPostEffect, PostEffectUniformField } from \"./post-effect.js\";\nimport type { ShaderAsset } from \"./shader-asset.js\";\nimport type { ShaderUniformType } from \"./shader-declaration.js\";\n\n/**\n * Turns a `// @ignifx post` file into the fragment module and uniform layout Babylon Lite's\n * fullscreen-effect path needs (`docs/plan/2026-09-terrain-particles-shaders.md` §3.3).\n *\n * `mainFragment` is a plain function, not an entry point: Lite hard-codes the entry-point names\n * `effectFullscreenVertex` and `effectFragment` (`lib/effect/effect-renderer.js` 7, 258-260), so the\n * entry point is generated here and forwards to it. `createEffectWrapper` takes a byte length and a\n * raw writer and computes no offsets, so the struct's member offsets are worked out here from WGSL's\n * own alignment rules and kept in step with the generated struct.\n *\n * Everything in this module is device-free and deterministic, so it is asserted in Node. It is\n * reached through `./post-effect-support.ts` so a game with no custom post effect never loads it.\n */\n\n/**\n * Compiles a `// @ignifx post` file into a full fragment module and a uniform layout.\n *\n * @remarks\n * Device-free and deterministic, so the whole thing is unit-testable: the result is a WGSL string\n * and a set of byte offsets. It is memoised per shader asset by {@link compiledPostEffect}, because\n * the chain asks for it on every rebuild.\n *\n * @param shader - The loaded shader asset.\n * @returns The compiled effect.\n * @throws IgnifxError with code `IGX-0709` when the file is not a `post` one, or `IGX-0723` when it\n * declares no `mainFragment` function.\n *\n * @example\n * ```ts\n * const compiled = compilePostEffect(vignette.value);\n * compiled.byName.get(\"amount\")?.byteOffset; // 20, right after the four built-ins\n * ```\n *\n * @internal\n */\nexport function compilePostEffect(shader: ShaderAsset): CompiledPostEffect {\n if (shader.declaration.kind !== \"post\") {\n throw new IgnifxError(\n CoreErrorCode.invalidAssetFile,\n `${shader.address} declares @ignifx ${shader.declaration.kind}, not @ignifx post.`,\n {\n context: { file: shader.address, format: \"@ignifx post\", kind: shader.declaration.kind },\n hint: \"A PostProcessStack custom effect takes a .post.wgsl file whose pragma is @ignifx post.\",\n },\n );\n }\n if (!new RegExp(`\\\\bfn\\\\s+${POST_EFFECT_FUNCTION}\\\\s*\\\\(`, \"u\").test(shader.source)) {\n throw new IgnifxError(\n CoreErrorCode.surfaceHookMissing,\n `${shader.address} declares no ${POST_EFFECT_FUNCTION} function.`,\n {\n context: { asset: shader.address, hook: POST_EFFECT_FUNCTION },\n hint: `Add fn ${POST_EFFECT_FUNCTION}(in: PostInput) -> vec4<f32>; the @fragment entry point is generated.`,\n },\n );\n }\n const declared = shader.declaration.uniforms.filter((uniform) => !isBuiltinUniformName(uniform.name));\n const layout = layOutUniforms([\n ...POST_EFFECT_BUILTIN_UNIFORMS,\n ...declared.map((uniform) => ({ name: uniform.name, type: uniform.type })),\n ]);\n const byName = new Map<string, PostEffectUniformField>();\n for (const field of layout.fields) {\n byName.set(field.name, field);\n }\n return {\n address: shader.address,\n fragmentWGSL: buildFragmentModule(shader, layout.fields),\n uniforms: layout.fields,\n byName,\n uniformByteLength: layout.byteLength,\n textures: shader.declaration.textures,\n };\n}\n\n/** The compiled form of each shader asset, so a chain rebuild recompiles nothing. */\nlet compiled: WeakMap<ShaderAsset, CompiledPostEffect> | null = null;\n\n/**\n * The compiled form of a post-effect shader, compiled once per asset.\n *\n * @remarks\n * Keyed on the `ShaderAsset` itself, so a hot reload — which replaces the asset object — recompiles\n * for free.\n *\n * @param shader - The loaded shader asset.\n * @returns The compiled effect.\n * @throws IgnifxError as {@link compilePostEffect} documents.\n *\n * @internal\n */\nexport function compiledPostEffect(shader: ShaderAsset): CompiledPostEffect {\n const cache = (compiled ??= new WeakMap<ShaderAsset, CompiledPostEffect>());\n const hit = cache.get(shader);\n if (hit !== undefined) {\n return hit;\n }\n const built = compilePostEffect(shader);\n cache.set(shader, built);\n return built;\n}\n\n/**\n * Writes an effect's current values into the bytes its uniform buffer takes.\n *\n * @remarks\n * The built-in clocks and `screenSize` are written by the caller through the same `out` buffer, so\n * this only fills in the declared members: the declaration's default first, then the settings'\n * override. Unknown names are refused, which is what makes a typo in a `.scene.json` visible.\n *\n * @param effect - The compiled effect.\n * @param shader - The shader, for its declared defaults.\n * @param values - The overrides.\n * @param out - The uniform bytes, at least `effect.uniformByteLength` long.\n * @throws IgnifxError with code `IGX-0712` for an undeclared name, or `IGX-0713` for a wrongly\n * shaped value.\n *\n * @internal\n */\nexport function writePostEffectValues(\n effect: CompiledPostEffect,\n shader: ShaderAsset,\n values: Readonly<Record<string, number | readonly number[]>>,\n out: Float32Array,\n): void {\n for (const uniform of shader.declaration.uniforms) {\n const field = effect.byName.get(uniform.name);\n if (field === undefined) {\n continue;\n }\n writeField(field, uniform.defaultValue, effect.address, out);\n }\n // `for…in` rather than `Object.keys`: the chain calls this every frame for every recorded effect\n // and a key array per effect per frame is per-frame allocation (coding standards §7).\n for (const name in values) {\n if (!Object.hasOwn(values, name)) {\n continue;\n }\n const field = effect.byName.get(name);\n const value = values[name];\n if (value === undefined) {\n continue;\n }\n if (field === undefined || isBuiltinUniformName(name)) {\n throw new IgnifxError(\n CoreErrorCode.unknownShaderBinding,\n `${effect.address} declares no uniform named ${name}.`,\n {\n context: { material: effect.address, asset: effect.address, name },\n hint: `It declares ${[...effect.byName.keys()].join(\", \")}.`,\n },\n );\n }\n writeField(field, value, effect.address, out);\n }\n}\n\n/** The result of laying out a uniform struct. */\ninterface UniformLayout {\n /** The members, in struct order. */\n readonly fields: readonly PostEffectUniformField[];\n /** The struct's size, in bytes. */\n readonly byteLength: number;\n}\n\n/**\n * Computes the byte offsets WGSL gives a struct of these members, in this order.\n *\n * @remarks\n * The rules are the WGSL specification's: a member's offset is its predecessor's end rounded up to\n * the member's alignment, and the struct's size is the last member's end rounded up to the struct's\n * alignment — the largest member alignment, and in the **uniform** address space never less than\n * 16. `vec3<f32>` is the one that catches people out: 16-aligned, 12 wide (plan §3.4).\n *\n * @param members - The members, in declaration order.\n * @returns The layout.\n */\nfunction layOutUniforms(\n members: readonly { readonly name: string; readonly type: ShaderUniformType }[],\n): UniformLayout {\n const fields: PostEffectUniformField[] = [];\n let offset = 0;\n // WGSL's uniform address space rounds a struct's alignment up to a multiple of 16, so the block's\n // size is always a multiple of 16 whatever its members are.\n let structAlignment = 16;\n for (const member of members) {\n const alignment = typeAlignment(member.type);\n const size = typeSize(member.type);\n structAlignment = Math.max(structAlignment, alignment);\n offset = roundUp(offset, alignment);\n fields.push({\n name: member.name,\n type: member.type,\n components: componentCount(member.type),\n byteOffset: offset,\n });\n offset += size;\n }\n return { fields, byteLength: roundUp(offset, structAlignment) };\n}\n\n/**\n * A WGSL type's alignment in the uniform address space, in bytes.\n *\n * @param type - The type.\n * @returns The alignment.\n */\nfunction typeAlignment(type: ShaderUniformType): number {\n switch (type) {\n case \"vec2<f32>\": {\n return 8;\n }\n case \"vec3<f32>\":\n case \"vec4<f32>\":\n case \"mat4x4<f32>\": {\n return 16;\n }\n case \"f32\":\n case \"u32\":\n case \"i32\": {\n return 4;\n }\n default: {\n return assertNever(type, \"shader uniform type\");\n }\n }\n}\n\n/**\n * A WGSL type's size, in bytes.\n *\n * @param type - The type.\n * @returns The size.\n */\nfunction typeSize(type: ShaderUniformType): number {\n switch (type) {\n case \"vec2<f32>\": {\n return 8;\n }\n case \"vec3<f32>\": {\n return 12;\n }\n case \"vec4<f32>\": {\n return 16;\n }\n case \"mat4x4<f32>\": {\n return 64;\n }\n case \"f32\":\n case \"u32\":\n case \"i32\": {\n return 4;\n }\n default: {\n return assertNever(type, \"shader uniform type\");\n }\n }\n}\n\n/**\n * How many floats one uniform of a declared type occupies.\n *\n * @remarks\n * A private copy of `material-plugin.ts`'s `uniformComponentCount`. `PostProcessStack` is in every\n * game's static graph, and importing it from there would drag `defineMaterialPlugin` and the\n * reserved-name table into a bundle that draws no custom shader at all.\n *\n * @param type - The declared WGSL type.\n * @returns The component count: 1, 2, 3, 4, or 16.\n */\nfunction componentCount(type: ShaderUniformType): number {\n switch (type) {\n case \"vec2<f32>\": {\n return 2;\n }\n case \"vec3<f32>\": {\n return 3;\n }\n case \"vec4<f32>\": {\n return 4;\n }\n case \"mat4x4<f32>\": {\n return 16;\n }\n case \"f32\":\n case \"u32\":\n case \"i32\": {\n return 1;\n }\n default: {\n return assertNever(type, \"shader uniform type\");\n }\n }\n}\n\n/**\n * Rounds a value up to a multiple of an alignment.\n *\n * @param value - The value.\n * @param alignment - The alignment, a power of two.\n * @returns The rounded value.\n */\nfunction roundUp(value: number, alignment: number): number {\n return Math.ceil(value / alignment) * alignment;\n}\n\n/**\n * The whole fragment module: bindings, generated structs, the author's file, and the entry point\n * Lite's pipeline looks for.\n *\n * @param shader - The shader asset.\n * @param fields - The uniform members, in struct order.\n * @returns The WGSL.\n */\nfunction buildFragmentModule(shader: ShaderAsset, fields: readonly PostEffectUniformField[]): string {\n const members = fields.map((field) => `${field.name}:${field.type},`).join(\"\");\n const lines: string[] = [\n `struct PostUniforms{${members}}`,\n \"@group(0)@binding(0)var<uniform>shaderUniforms:PostUniforms;\",\n `@group(0)@binding(${String(INPUT_TEXTURE_BINDING)})var inputTexture:texture_2d<f32>;`,\n `@group(0)@binding(${String(INPUT_SAMPLER_BINDING)})var inputTextureSampler:sampler;`,\n ];\n // `for…of` with an index: the iterator yields the element type rather than `T | undefined`, and\n // this runs once per compiled shader rather than per frame.\n let index = -1;\n for (const declaration of shader.declaration.textures) {\n index += 1;\n const binding = declaredTextureBinding(index);\n const type = declaration.array ? \"texture_2d_array<f32>\" : \"texture_2d<f32>\";\n lines.push(\n `@group(0)@binding(${String(binding)})var ${declaration.name}:${type};`,\n `@group(0)@binding(${String(binding + 1)})var ${declaration.name}Sampler:sampler;`,\n );\n }\n lines.push(\n \"struct PostInput{uv:vec2<f32>,position:vec2<f32>,}\",\n shader.source,\n \"@fragment fn effectFragment(fragment:EffectVertexOutput)->@location(0)vec4<f32>{\",\n \"var ignifxPostInput:PostInput;\",\n \"ignifxPostInput.uv=fragment.uv;\",\n \"ignifxPostInput.position=fragment.position.xy;\",\n `return ${POST_EFFECT_FUNCTION}(ignifxPostInput);`,\n \"}\",\n );\n return lines.join(\"\\n\");\n}\n\n/**\n * Writes one member's value into the uniform bytes.\n *\n * @param field - The member.\n * @param value - The value.\n * @param asset - The shader's address, for diagnostics.\n * @param out - The uniform floats.\n * @throws IgnifxError with code `IGX-0713` when the shape does not match.\n */\nfunction writeField(\n field: PostEffectUniformField,\n value: number | readonly number[],\n asset: string,\n out: Float32Array,\n): void {\n const index = field.byteOffset / 4;\n if (typeof value === \"number\") {\n if (field.components !== 1) {\n throw mismatch(field, asset, \"a single number\");\n }\n out[index] = value;\n return;\n }\n if (value.length !== field.components) {\n throw mismatch(field, asset, `${String(value.length)} floats`);\n }\n out.set(value instanceof Float32Array ? value : Float32Array.from(value), index);\n}\n\n/**\n * The `IGX-0713` failure a wrongly shaped value produces.\n *\n * @param field - The member.\n * @param asset - The shader's address.\n * @param actual - What the caller passed.\n * @returns The error to throw.\n */\nfunction mismatch(field: PostEffectUniformField, asset: string, actual: string): IgnifxError {\n return new IgnifxError(\n CoreErrorCode.shaderValueMismatch,\n `${field.name} on ${asset} expects ${field.type} (${String(field.components)} floats), not ${actual}.`,\n {\n context: { name: field.name, material: asset, expected: field.type, actual },\n hint: \"A post effect's values are numbers and numeric arrays; a colour takes its three or four components.\",\n },\n );\n}\n\n/**\n * Whether a name is one of the four uniforms every post effect gets for free.\n *\n * @param name - The candidate.\n * @returns `true` when the engine writes it.\n */\nfunction isBuiltinUniformName(name: string): boolean {\n for (const builtin of POST_EFFECT_BUILTIN_UNIFORMS) {\n if (builtin.name === name) {\n return true;\n }\n }\n return false;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,SAAgB,kBAAkB,QAAyC;CACzE,IAAI,OAAO,YAAY,SAAS,QAC9B,MAAM,IAAI,YACR,cAAc,kBACd,GAAG,OAAO,QAAQ,oBAAoB,OAAO,YAAY,KAAK,sBAC9D;EACE,SAAS;GAAE,MAAM,OAAO;GAAS,QAAQ;GAAgB,MAAM,OAAO,YAAY;EAAK;EACvF,MAAM;CACR,CACF;CAEF,IAAI,CAAC,IAAI,OAAO,gCAA2C,GAAG,CAAC,CAAC,KAAK,OAAO,MAAM,GAChF,MAAM,IAAI,YACR,cAAc,oBACd,GAAG,OAAO,QAAQ,eAAe,qBAAqB,aACtD;EACE,SAAS;GAAE,OAAO,OAAO;GAAS,MAAM;EAAqB;EAC7D,MAAM,UAAU,qBAAqB;CACvC,CACF;CAEF,MAAM,WAAW,OAAO,YAAY,SAAS,QAAQ,YAAY,CAAC,qBAAqB,QAAQ,IAAI,CAAC;CACpG,MAAM,SAAS,eAAe,CAC5B,GAAG,8BACH,GAAG,SAAS,KAAK,aAAa;EAAE,MAAM,QA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