@babylonjs/lite-gl 1.23.0 → 1.24.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 (94) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +103 -6
  3. package/blend.d.ts +1 -1
  4. package/blend.js +1 -1
  5. package/blend.js.map +1 -1
  6. package/context.d.ts +52 -4
  7. package/context.js +108 -11
  8. package/context.js.map +1 -1
  9. package/depth-stencil.d.ts +4 -16
  10. package/depth-stencil.js +10 -11
  11. package/depth-stencil.js.map +1 -1
  12. package/dynamic-texture.d.ts +6 -3
  13. package/dynamic-texture.js +16 -4
  14. package/dynamic-texture.js.map +1 -1
  15. package/effect-renderer.d.ts +1 -11
  16. package/effect-renderer.js.map +1 -1
  17. package/effect.d.ts +16 -29
  18. package/effect.js +52 -19
  19. package/effect.js.map +1 -1
  20. package/family.d.ts +474 -0
  21. package/family.js +14 -0
  22. package/family.js.map +1 -0
  23. package/framebuffer-validation.d.ts +20 -0
  24. package/framebuffer-validation.js +37 -0
  25. package/framebuffer-validation.js.map +1 -0
  26. package/html-texture.d.ts +2 -2
  27. package/html-texture.js.map +1 -1
  28. package/index.d.ts +10 -7
  29. package/index.js +5 -4
  30. package/index.js.map +1 -1
  31. package/mesh.d.ts +72 -15
  32. package/mesh.js +221 -64
  33. package/mesh.js.map +1 -1
  34. package/native/command-stream.d.ts +1 -0
  35. package/native/command-stream.js +135 -0
  36. package/native/command-stream.js.map +1 -0
  37. package/native/context.d.ts +26 -0
  38. package/native/context.js +89 -0
  39. package/native/context.js.map +1 -0
  40. package/native/effect.d.ts +44 -0
  41. package/native/effect.js +276 -0
  42. package/native/effect.js.map +1 -0
  43. package/native/family.d.ts +75 -0
  44. package/native/family.js +2 -0
  45. package/native/family.js.map +1 -0
  46. package/native/identity.d.ts +11 -0
  47. package/native/identity.js +2 -0
  48. package/native/identity.js.map +1 -0
  49. package/native/index.d.ts +25 -0
  50. package/native/index.js +7 -0
  51. package/native/index.js.map +1 -0
  52. package/native/mesh.d.ts +53 -0
  53. package/native/mesh.js +137 -0
  54. package/native/mesh.js.map +1 -0
  55. package/native/render-target.d.ts +35 -0
  56. package/native/render-target.js +159 -0
  57. package/native/render-target.js.map +1 -0
  58. package/native/runtime.d.ts +1 -0
  59. package/native/runtime.js +12 -0
  60. package/native/runtime.js.map +1 -0
  61. package/native/state.d.ts +19 -0
  62. package/native/state.js +104 -0
  63. package/native/state.js.map +1 -0
  64. package/native/texture.d.ts +37 -0
  65. package/native/texture.js +86 -0
  66. package/native/texture.js.map +1 -0
  67. package/package.json +11 -3
  68. package/render-target.d.ts +18 -9
  69. package/render-target.js +84 -31
  70. package/render-target.js.map +1 -1
  71. package/scissor.d.ts +3 -3
  72. package/scissor.js +2 -2
  73. package/scissor.js.map +1 -1
  74. package/sprites.d.ts +5 -3
  75. package/sprites.js +24 -23
  76. package/sprites.js.map +1 -1
  77. package/state.d.ts +26 -13
  78. package/state.js +15 -15
  79. package/state.js.map +1 -1
  80. package/text/_gpu/text-instances.js +1 -1
  81. package/text/_gpu/text-instances.js.map +1 -1
  82. package/text/text-renderer.js.map +1 -1
  83. package/texture-3d.d.ts +2 -1
  84. package/texture-3d.js +7 -2
  85. package/texture-3d.js.map +1 -1
  86. package/texture-source.d.ts +4 -2
  87. package/texture-source.js +3 -2
  88. package/texture-source.js.map +1 -1
  89. package/texture.d.ts +18 -8
  90. package/texture.js +61 -35
  91. package/texture.js.map +1 -1
  92. package/web-family.d.ts +88 -0
  93. package/web-family.js +2 -0
  94. package/web-family.js.map +1 -0
package/sprites.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"sprites.js","sourceRoot":"","sources":["../src/sprites.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAwB,MAAM,cAAc,CAAC;AAC3F,OAAO,EAAE,YAAY,EAAE,aAAa,EAAiB,aAAa,EAAE,gB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ourcesContent":["/**\n * Sprite / instanced-quad renderer.\n *\n * Part of the public API via the `@babylonjs/lite-gl` barrel. The package is\n * `sideEffects: false`, so consumers that don't render sprites tree-shake it out.\n *\n * This is the lite-gl equivalent of Babylon's `SpriteRenderer` + `ThinSprite`\n * (`Sprites/spriteRenderer.js`, `Sprites/thinSprite.js`). The vertex layout,\n * per-cell UV math and corner/rotation transform are copied verbatim from the\n * non-instanced path of Babylon's `SpriteRenderer` so a future NeonBrush port\n * renders identically. The shaders are the GLSL ES 3.00 translation of\n * Babylon's `Shaders/sprites.vertex.js` / `sprites.fragment.js`, with the\n * fog / log-depth / pixel-perfect / alpha-test branches removed (lite-gl has\n * no depth attachment by default — see notes on `disableDepthWrite` below).\n */\nimport { offContextRestored, onContextRestored, type GLEngineContext } from \"./context.js\";\nimport { createEffect, disposeEffect, type GLEffect, isEffectReady, setEffectTexture, useEffect } from \"./effect.js\";\nimport { GLBlendMode, setBlendMode } from \"./blend.js\";\nimport { applyGLStates } from \"./apply-states.js\";\nimport { type GLTexture } from \"./texture.js\";\n\n/* ───────────────────────────── shaders (GLSL ES 3.00) ───────────────────── */\n\n/** Vertex shader — GLSL ES 3.00 translation of Babylon's `spritesVertexShader`\n * core path. Attribute locations 0..5 match `createSpriteRenderer`'s\n * `attributeNames` order so the renderer's VAO feeds every program correctly. */\nconst SPRITE_VERTEX_SOURCE = `#version 300 es\nprecision highp float;\nlayout(location = 0) in vec4 position;\nlayout(location = 1) in vec2 options;\nlayout(location = 2) in vec2 offsets;\nlayout(location = 3) in vec2 inverts;\nlayout(location = 4) in vec4 cellInfo;\nlayout(location = 5) in vec4 color;\nuniform mat4 view;\nuniform mat4 projection;\nout vec2 vUV;\nout vec4 vColor;\nvoid main(void) {\n vec3 viewPos = (view * vec4(position.xyz, 1.0)).xyz;\n float angle = position.w;\n vec2 size = vec2(options.x, options.y);\n vec2 offset = offsets.xy;\n vec2 cornerPos = vec2(offset.x - 0.5, offset.y - 0.5) * size;\n vec3 rotatedCorner;\n rotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\n rotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\n rotatedCorner.z = 0.0;\n viewPos += rotatedCorner;\n gl_Position = projection * vec4(viewPos, 1.0);\n vColor = color;\n vec2 uvOffset = vec2(abs(offset.x - inverts.x), abs(1.0 - offset.y - inverts.y));\n vec2 uvPlace = cellInfo.xy;\n vec2 uvSize = cellInfo.zw;\n vUV.x = uvPlace.x + uvSize.x * uvOffset.x;\n vUV.y = uvPlace.y + uvSize.y * uvOffset.y;\n}`;\n\n/** Fragment shader — GLSL ES 3.00 translation of Babylon's `spritesPixelShader`\n * color pass: `texture(diffuseSampler, vUV) * vColor`. The alpha-test/discard\n * branch is dropped because lite-gl never runs the depth pre-pass. */\nconst SPRITE_FRAGMENT_SOURCE = `#version 300 es\nprecision highp float;\nin vec2 vUV;\nin vec4 vColor;\nuniform sampler2D diffuseSampler;\nout vec4 glFragColor;\nvoid main(void) {\n vec4 color = texture(diffuseSampler, vUV);\n color *= vColor;\n glFragColor = color;\n}`;\n\n/* ───────────────────────────── layout constants ─────────────────────────── */\n\n/** Floats per vertex: position.xyz + angle (4), size (2), corner offset (2),\n * inverts (2), cellInfo (4), color (4) = 18. Matches Babylon's non-instanced\n * `_vertexBufferSize`. */\nconst FLOATS_PER_VERTEX = 18;\n/** Four corner vertices per sprite quad (non-instanced, like Babylon). */\nconst VERTS_PER_SPRITE = 4;\n/** Six indices per sprite (two triangles). */\nconst INDICES_PER_SPRITE = 6;\n/** Bytes per float — `Float32Array.BYTES_PER_ELEMENT`. */\nconst BYTES_PER_FLOAT = 4;\n/** Stride between consecutive vertices, in bytes. */\nconst VERTEX_STRIDE_BYTES = FLOATS_PER_VERTEX * BYTES_PER_FLOAT;\n/** UV inset applied to each quad corner, matching Babylon's default\n * `SpriteRenderer` epsilon (0.01) so cell sampling never bleeds neighbours. */\nconst SPRITE_EPSILON = 0.01;\n/** Max sprites: 4 verts/sprite must keep every index within `Uint16` range\n * (`capacity * 4 - 1 <= 65535`). */\nconst MAX_CAPACITY = 16384;\n\n/** Per-corner U offset (pre-epsilon), one entry per quad vertex. Module-scoped\n * literal — pure per bundler convention, allocated once (never per frame). */\nconst CORNER_OFFSET_X = [0, 1, 1, 0];\n/** Per-corner V offset (pre-epsilon), one entry per quad vertex. */\nconst CORNER_OFFSET_Y = [0, 0, 1, 1];\n\n/** Attribute names in location order — index `i` is bound to `location = i` by\n * `createEffect`/`linkProgram`, matching the shader's `layout(location = i)`. */\nconst SPRITE_ATTRIBUTES = [\"position\", \"options\", \"offsets\", \"inverts\", \"cellInfo\", \"color\"] as const;\n\n/* ─────────────────────────────── public types ──────────────────────────── */\n\n/** An RGBA color with each channel in `[0, 1]`, used for per-sprite tint. */\nexport interface GLSpriteColor {\n /** Red, 0..1. */\n r: number;\n /** Green, 0..1. */\n g: number;\n /** Blue, 0..1. */\n b: number;\n /** Alpha, 0..1. */\n a: number;\n}\n\n/** A single sprite — a plain data object mirroring the fields of Babylon's\n * `ThinSprite` that the renderer reads. No animation state: `cellIndex` is set\n * directly by the consumer (lite-gl does not port `ThinSprite.playAnimation`). */\nexport interface GLSprite {\n /** World-space position of the sprite center. */\n position: { x: number; y: number; z: number };\n /** Width in world units. */\n width: number;\n /** Height in world units. */\n height: number;\n /** Rotation angle, in radians. */\n angle: number;\n /** Sprite-sheet cell index (0-based, row-major). Out-of-range / negative\n * values are clamped to 0, matching Babylon's `if (!cellIndex) = 0`. Ignored\n * when a manual UV rect (`uSize`) is set. Optional — defaults to `0`. */\n cellIndex?: number;\n /** Optional tint; defaults to opaque white `{ r: 1, g: 1, b: 1, a: 1 }`. */\n color?: GLSpriteColor;\n /** Flip the cell horizontally. Defaults to `false`. */\n invertU?: boolean;\n /** Flip the cell vertically. Defaults to `false`. */\n invertV?: boolean;\n /** Manual UV rect — normalized left (U) origin in `[0, 1]`, mirroring\n * Babylon's `ThinSprite._xOffset`. Set together with {@link GLSprite.uSize}\n * to address an arbitrary sub-rectangle of the sheet instead of the fixed\n * `cellIndex` grid (used by the lottie atlas, whose cells vary in size). */\n uOffset?: number;\n /** Manual UV rect — normalized top (V) origin in `[0, 1]` (≙ Babylon\n * `ThinSprite._yOffset`). See {@link GLSprite.uSize}. */\n vOffset?: number;\n /** Manual UV rect — cell width in **texels** (≙ Babylon `ThinSprite._xSize`;\n * divided by the texture width when building vertices). Presence of `uSize`\n * switches the sprite into manual-UV mode (the `cellIndex` grid is ignored).\n * `0` samples a single column — the \"solid color\" trick. */\n uSize?: number;\n /** Manual UV rect — cell height in **texels** (≙ Babylon `ThinSprite._ySize`).\n * See {@link GLSprite.uSize}. Defaults to `0` when `uSize` is set but `vSize`\n * is omitted. */\n vSize?: number;\n /** When `false`, the sprite is skipped. Defaults to `true`. */\n isVisible?: boolean;\n}\n\n/** Options for {@link createSpriteRenderer}. */\nexport interface GLSpriteRendererOptions {\n /** Maximum number of sprites drawable in one `renderSprites` call. Must be\n * an integer in `[1, 16384]` (the `Uint16` index-buffer limit). */\n capacity: number;\n /** Cell width in texels within the sprite sheet, for the fixed-grid\n * `cellIndex` path. Optional — defaults to `1`; irrelevant when every\n * sprite supplies a manual UV rect (`uSize`), as the lottie atlas does. */\n cellWidth?: number;\n /** Cell height in texels within the sprite sheet. Optional — defaults to\n * `1`. See {@link GLSpriteRendererOptions.cellWidth}. */\n cellHeight?: number;\n /** Per-corner UV/position inset applied to each quad vertex, in the `[0, 0.5)`\n * range — the `epsilon` constructor argument of Babylon's `SpriteRenderer`.\n * It both insets cell UV sampling (so a cell never bleeds its neighbours) and\n * shrinks the quad by `epsilon * size` per side. Defaults to `0.01` (Babylon's\n * `SpriteRenderer` default). Pass `0` to disable insetting — the lottie atlas\n * does this (it relies on edge-extruded cells + center sampling instead, so a\n * non-zero inset would shrink every sprite by ~`0.01·size` per edge). */\n epsilon?: number;\n /** The sprite-sheet texture. May be swapped later via\n * {@link setSpriteRendererTexture}. */\n texture: GLTexture;\n /** Blend mode for the draw. Defaults to {@link GLBlendMode.ALPHA} (2),\n * matching Babylon's `SpriteRenderer.blendMode` default. */\n blendMode?: GLBlendMode;\n /** When `true` (default), `renderSprites` resets the blend mode to\n * {@link GLBlendMode.DISABLE} after drawing — mirroring Babylon's\n * `SpriteRenderer.autoResetAlpha = true`. Set `false` to leave the\n * renderer's `blendMode` applied after the draw (the lottie player relies\n * on this so its premultiplied alpha mode persists across passes). */\n autoResetAlpha?: boolean;\n /** Accepted for Babylon API parity. lite-gl's default engine has no depth\n * attachment (`depth: false`), so there is no depth pre-pass and this flag\n * has no observable effect; it is stored verbatim for a future depth-aware\n * consumer. Defaults to `false`. */\n disableDepthWrite?: boolean;\n}\n\n/**\n * A sprite renderer owning its own VBO/IBO/VAO and `GLEffect`. Created by\n * {@link createSpriteRenderer}; drive it with {@link renderSprites} and release\n * it with {@link disposeSpriteRenderer}.\n */\nexport interface GLSpriteRenderer {\n /** The sprite-sheet texture sampled by the shader. Swap via\n * {@link setSpriteRendererTexture}. */\n texture: GLTexture;\n /** Cell width in texels (selects the sub-rectangle for `cellIndex`). */\n cellWidth: number;\n /** Cell height in texels. */\n cellHeight: number;\n /** Per-corner UV/position inset (Babylon `SpriteRenderer` `epsilon`). */\n epsilon: number;\n /** Active blend mode applied by `renderSprites` before drawing. */\n blendMode: GLBlendMode;\n /** When `true`, `renderSprites` resets blend to {@link GLBlendMode.DISABLE}\n * after drawing (Babylon `autoResetAlpha`). */\n autoResetAlpha: boolean;\n /** Babylon-parity flag (no effect without a depth attachment). */\n disableDepthWrite: boolean;\n /** Maximum sprites per draw, fixed at creation. */\n readonly capacity: number;\n /** @internal The compiled sprite effect this renderer owns. */\n _effect: GLEffect;\n /** @internal Sprite VAO (attribute pointers + element binding). Null until\n * built and after disposal; rebuilt on `webglcontextrestored`. */\n _vao: WebGLVertexArrayObject | null;\n /** @internal Dynamic vertex buffer, sized for `capacity` at creation. */\n _vbo: WebGLBuffer | null;\n /** @internal Static index buffer (`capacity * 6` `Uint16` indices). */\n _ibo: WebGLBuffer | null;\n /** @internal Preallocated CPU-side vertex scratch — reused every frame\n * (`renderSprites` performs zero allocations). */\n _vertexData: Float32Array;\n /** @internal Preallocated index data, uploaded once. */\n _indices: Uint16Array;\n /** @internal Context-restored handler — rebuilds the GPU buffers. */\n _restore: () => void;\n /** @internal True once disposed; subsequent calls are no-ops. */\n _disposed: boolean;\n}\n\n/* ──────────────────────────────── public API ───────────────────────────── */\n\n/**\n * Create a sprite renderer with its own GPU buffers and compiled effect.\n *\n * Preallocates the CPU vertex scratch and the index buffer at `capacity`, so\n * {@link renderSprites} performs no allocations. The sprite GPU buffers are\n * rebuilt automatically on `webglcontextrestored` (the owned effect is rebuilt\n * by the engine's context-restore protocol).\n *\n * @param engine - The engine to create GL resources on.\n * @param options - See {@link GLSpriteRendererOptions}.\n * @returns The new {@link GLSpriteRenderer}.\n * @throws If `capacity` is not an integer in `[1, 16384]`, or if a provided\n * `cellWidth`/`cellHeight` is not positive.\n */\nexport function createSpriteRenderer(engine: GLEngineContext, options: GLSpriteRendererOptions): GLSpriteRenderer {\n const capacity = options.capacity;\n if (!Number.isInteger(capacity) || capacity < 1 || capacity > MAX_CAPACITY) {\n throw new Error(`lite-gl: sprite renderer capacity must be an integer in [1, ${MAX_CAPACITY}], got ${capacity}`);\n }\n // cellWidth/cellHeight drive only the fixed-grid `cellIndex` path; manual-UV\n // consumers (the lottie atlas) omit them. Default to 1; reject explicit ≤ 0.\n const cellWidth = options.cellWidth ?? 1;\n const cellHeight = options.cellHeight ?? 1;\n if (!(cellWidth > 0) || !(cellHeight > 0)) {\n throw new Error(\"lite-gl: sprite renderer cellWidth/cellHeight must be > 0\");\n }\n\n const effect = createEffect(engine, {\n name: \"sprites\",\n vertexSource: SPRITE_VERTEX_SOURCE,\n fragmentSource: SPRITE_FRAGMENT_SOURCE,\n uniformNames: [\"view\", \"projection\"],\n samplerNames: [\"diffuseSampler\"],\n attributeNames: SPRITE_ATTRIBUTES,\n });\n\n // Build the static index buffer data once: [0,1,2, 0,2,3] per sprite.\n const indices = new Uint16Array(capacity * INDICES_PER_SPRITE);\n for (let i = 0; i < capacity; i++) {\n const v = i * VERTS_PER_SPRITE;\n const o = i * INDICES_PER_SPRITE;\n indices[o] = v;\n indices[o + 1] = v + 1;\n indices[o + 2] = v + 2;\n indices[o + 3] = v;\n indices[o + 4] = v + 2;\n indices[o + 5] = v + 3;\n }\n\n const renderer: GLSpriteRenderer = {\n texture: options.texture,\n cellWidth,\n cellHeight,\n epsilon: options.epsilon ?? SPRITE_EPSILON,\n blendMode: options.blendMode ?? GLBlendMode.ALPHA,\n autoResetAlpha: options.autoResetAlpha ?? true,\n disableDepthWrite: options.disableDepthWrite ?? false,\n capacity,\n _effect: effect,\n _vao: null,\n _vbo: null,\n _ibo: null,\n _vertexData: new Float32Array(capacity * VERTS_PER_SPRITE * FLOATS_PER_VERTEX),\n _indices: indices,\n _restore: () => {},\n _disposed: false,\n };\n\n renderer._restore = (): void => {\n buildSpriteBuffers(engine, renderer);\n };\n onContextRestored(engine, renderer._restore);\n buildSpriteBuffers(engine, renderer);\n return renderer;\n}\n\n/**\n * Build the per-sprite vertex data and draw all visible sprites in one\n * `drawElements` call. Performs no allocations — the vertex scratch is reused\n * and uploaded with `bufferSubData`.\n *\n * No-op when the context is lost/disposed, the renderer is disposed, the\n * texture is not ready, the effect is not ready, or there are no visible\n * sprites. Sets the renderer's blend mode before drawing and resets to\n * {@link GLBlendMode.DISABLE} afterwards (matching Babylon's\n * `autoResetAlpha = true`), so a subsequent `drawEffect` is unaffected.\n *\n * @param renderer - The renderer to draw with.\n * @param sprites - The sprites to draw (only `isVisible !== false` are drawn;\n * excess beyond `capacity` is ignored, matching Babylon).\n * @param deltaTime - Accepted for Babylon API parity; unused (lite-gl `GLSprite`\n * holds no animation state, so `cellIndex` is consumer-driven).\n * @param viewMatrix - Column-major 4x4 view matrix.\n * @param projectionMatrix - Column-major 4x4 projection matrix.\n */\nexport function renderSprites(\n renderer: GLSpriteRenderer,\n sprites: readonly GLSprite[],\n deltaTime: number,\n viewMatrix: Float32Array | number[],\n projectionMatrix: Float32Array | number[]\n): void {\n const engine = renderer._effect._engine;\n if (engine._isLost || engine._disposed || renderer._disposed) {\n return;\n }\n // `deltaTime` is accepted for Babylon `SpriteRenderer.render` parity but\n // unused: `GLSprite` carries no animation state, so `cellIndex` is driven\n // entirely by the consumer. Referenced here to keep the parameter name in\n // the public signature without tripping `noUnusedParameters`.\n void deltaTime;\n const tex = renderer.texture;\n if (!tex.isReady || sprites.length === 0) {\n return;\n }\n const effect = renderer._effect;\n if (!isEffectReady(effect)) {\n return;\n }\n if (renderer._vao === null || renderer._vbo === null) {\n return;\n }\n\n // ── Build vertex data (allocation-free) ──────────────────────────────────\n const vd = renderer._vertexData;\n const eps = renderer.epsilon;\n const texW = tex.width;\n const texH = tex.height;\n const cellW = renderer.cellWidth;\n const cellH = renderer.cellHeight;\n const rowSize = texW / cellW; // cells per sheet row\n const cellWidthN = cellW / texW;\n const cellHeightN = cellH / texH;\n const cap = renderer.capacity;\n const count = sprites.length;\n let visible = 0;\n for (let i = 0; i < count && visible < cap; i++) {\n const sprite = sprites[i];\n if (sprite === undefined || sprite.isVisible === false) {\n continue;\n }\n // UV rect — manual per-sprite rect (Babylon `ThinSprite._xOffset/_xSize`\n // path, selected when `uSize` is set) or the fixed `cellIndex` grid.\n // Both resolve to a normalized `(left, top, widthN, heightN)` rectangle,\n // matching Babylon's `_appendSpriteVertex` vertex layout exactly.\n let cellLeft: number;\n let cellTop: number;\n let cellWN: number;\n let cellHN: number;\n if (sprite.uSize !== undefined) {\n cellLeft = sprite.uOffset ?? 0;\n cellTop = sprite.vOffset ?? 0;\n cellWN = sprite.uSize / texW;\n cellHN = (sprite.vSize ?? 0) / texH;\n } else {\n const cellIndex = (sprite.cellIndex ?? 0) > 0 ? (sprite.cellIndex as number) : 0;\n const row = (cellIndex / rowSize) >> 0;\n cellLeft = ((cellIndex - row * rowSize) * cellW) / texW;\n cellTop = (row * cellH) / texH;\n cellWN = cellWidthN;\n cellHN = cellHeightN;\n }\n\n const px = sprite.position.x;\n const py = sprite.position.y;\n const pz = sprite.position.z;\n const angle = sprite.angle;\n const w = sprite.width;\n const h = sprite.height;\n const invU = sprite.invertU === true ? 1 : 0;\n const invV = sprite.invertV === true ? 1 : 0;\n const color = sprite.color;\n const cr = color !== undefined ? color.r : 1;\n const cg = color !== undefined ? color.g : 1;\n const cb = color !== undefined ? color.b : 1;\n const ca = color !== undefined ? color.a : 1;\n\n let off = visible * VERTS_PER_SPRITE * FLOATS_PER_VERTEX;\n for (let c = 0; c < VERTS_PER_SPRITE; c++) {\n const ox = CORNER_OFFSET_X[c] === 0 ? eps : 1 - eps;\n const oy = CORNER_OFFSET_Y[c] === 0 ? eps : 1 - eps;\n vd[off] = px;\n vd[off + 1] = py;\n vd[off + 2] = pz;\n vd[off + 3] = angle;\n vd[off + 4] = w;\n vd[off + 5] = h;\n vd[off + 6] = ox;\n vd[off + 7] = oy;\n vd[off + 8] = invU;\n vd[off + 9] = invV;\n vd[off + 10] = cellLeft;\n vd[off + 11] = cellTop;\n vd[off + 12] = cellWN;\n vd[off + 13] = cellHN;\n vd[off + 14] = cr;\n vd[off + 15] = cg;\n vd[off + 16] = cb;\n vd[off + 17] = ca;\n off += FLOATS_PER_VERTEX;\n }\n visible++;\n }\n if (visible === 0) {\n return;\n }\n\n // ── Upload + draw ────────────────────────────────────────────────────────\n const gl = engine.gl;\n const s = engine._state;\n const vao = renderer._vao;\n if (s.boundVao !== vao) {\n gl.bindVertexArray(vao);\n s.boundVao = vao;\n // Binding the VAO restores its element-array binding (VAO state).\n s.boundElementBuffer = renderer._ibo;\n }\n const vbo = renderer._vbo;\n if (s.boundArrayBuffer !== vbo) {\n gl.bindBuffer(gl.ARRAY_BUFFER, vbo);\n s.boundArrayBuffer = vbo;\n }\n const floatCount = visible * VERTS_PER_SPRITE * FLOATS_PER_VERTEX;\n gl.bufferSubData(gl.ARRAY_BUFFER, 0, vd, 0, floatCount);\n\n useEffect(effect);\n const viewLoc = effect.uniformLocations[\"view\"];\n if (viewLoc !== null && viewLoc !== undefined) {\n gl.uniformMatrix4fv(viewLoc, false, viewMatrix);\n }\n const projLoc = effect.uniformLocations[\"projection\"];\n if (projLoc !== null && projLoc !== undefined) {\n gl.uniformMatrix4fv(projLoc, false, projectionMatrix);\n }\n setEffectTexture(effect, \"diffuseSampler\", tex);\n\n setBlendMode(engine, renderer.blendMode);\n applyGLStates(engine);\n gl.drawElements(gl.TRIANGLES, visible * INDICES_PER_SPRITE, gl.UNSIGNED_SHORT, 0);\n // Auto-reset (Babylon `autoResetAlpha = true`): leave blend disabled so a\n // subsequent fullscreen `drawEffect` renders with the same state as before.\n // When `autoResetAlpha` is false (lottie), keep `renderer.blendMode` applied\n // so a premultiplied-alpha mode persists across multiple atlas-page passes.\n if (renderer.autoResetAlpha) {\n setBlendMode(engine, GLBlendMode.DISABLE);\n }\n}\n\n/** Swap the sprite-sheet texture (≙ Babylon assigning `SpriteRenderer.texture`\n * after an async load). The cell size is unchanged — adjust `cellWidth` /\n * `cellHeight` on the renderer directly if the new sheet differs. No-op when\n * the renderer is disposed.\n * No GL call is made — the texture is bound at draw time.\n *\n * @param renderer - The renderer to update.\n * @param texture - The new sprite-sheet texture. */\nexport function setSpriteRendererTexture(renderer: GLSpriteRenderer, texture: GLTexture): void {\n if (renderer._disposed) {\n return;\n }\n renderer.texture = texture;\n}\n\n/** Release the renderer's VAO/VBO/IBO and the effect it owns, and unregister\n * its context-restore handler. Idempotent. Does NOT dispose the texture — the\n * consumer that supplied it owns its lifetime.\n *\n * @param renderer - The renderer to dispose. */\nexport function disposeSpriteRenderer(renderer: GLSpriteRenderer): void {\n const engine = renderer._effect._engine;\n if (renderer._disposed) {\n return;\n }\n renderer._disposed = true;\n offContextRestored(engine, renderer._restore);\n disposeEffect(renderer._effect);\n if (!engine._isLost && !engine._disposed) {\n const gl = engine.gl;\n const s = engine._state;\n if (renderer._vao !== null) {\n gl.deleteVertexArray(renderer._vao);\n if (s.boundVao === renderer._vao) {\n s.boundVao = null;\n }\n }\n if (renderer._vbo !== null) {\n gl.deleteBuffer(renderer._vbo);\n if (s.boundArrayBuffer === renderer._vbo) {\n s.boundArrayBuffer = null;\n }\n }\n if (renderer._ibo !== null) {\n gl.deleteBuffer(renderer._ibo);\n if (s.boundElementBuffer === renderer._ibo) {\n s.boundElementBuffer = null;\n }\n }\n }\n renderer._vao = null;\n renderer._vbo = null;\n renderer._ibo = null;\n}\n\n/* ──────────────────────────── internal helpers ──────────────────────────── */\n\n/** (Re)create the VAO + VBO + IBO and configure the six vertex attributes.\n * Called from `createSpriteRenderer` and from the `webglcontextrestored`\n * handler (the prior handles are dead per the WebGL spec — not deleted here).\n * No-op when the context is lost/disposed. */\nfunction buildSpriteBuffers(engine: GLEngineContext, renderer: GLSpriteRenderer): void {\n if (engine._isLost || engine._disposed) {\n return;\n }\n const gl = engine.gl;\n const s = engine._state;\n\n const vao = gl.createVertexArray();\n if (vao === null) {\n throw new Error(\"lite-gl: gl.createVertexArray returned null (sprite VAO)\");\n }\n renderer._vao = vao;\n gl.bindVertexArray(vao);\n s.boundVao = vao;\n\n const vbo = gl.createBuffer();\n if (vbo === null) {\n throw new Error(\"lite-gl: gl.createBuffer returned null (sprite VBO)\");\n }\n renderer._vbo = vbo;\n gl.bindBuffer(gl.ARRAY_BUFFER, vbo);\n s.boundArrayBuffer = vbo;\n // Allocate the dynamic vertex storage at full capacity; filled per frame.\n gl.bufferData(gl.ARRAY_BUFFER, renderer._vertexData.byteLength, gl.DYNAMIC_DRAW);\n\n // Attribute pointers — locations match SPRITE_ATTRIBUTES / shader layout.\n gl.enableVertexAttribArray(0);\n gl.vertexAttribPointer(0, 4, gl.FLOAT, false, VERTEX_STRIDE_BYTES, 0);\n gl.enableVertexAttribArray(1);\n gl.vertexAttribPointer(1, 2, gl.FLOAT, false, VERTEX_STRIDE_BYTES, 4 * BYTES_PER_FLOAT);\n gl.enableVertexAttribArray(2);\n gl.vertexAttribPointer(2, 2, gl.FLOAT, false, VERTEX_STRIDE_BYTES, 6 * BYTES_PER_FLOAT);\n gl.enableVertexAttribArray(3);\n gl.vertexAttribPointer(3, 2, gl.FLOAT, false, VERTEX_STRIDE_BYTES, 8 * BYTES_PER_FLOAT);\n gl.enableVertexAttribArray(4);\n gl.vertexAttribPointer(4, 4, gl.FLOAT, false, VERTEX_STRIDE_BYTES, 10 * BYTES_PER_FLOAT);\n gl.enableVertexAttribArray(5);\n gl.vertexAttribPointer(5, 4, gl.FLOAT, false, VERTEX_STRIDE_BYTES, 14 * BYTES_PER_FLOAT);\n\n const ibo = gl.createBuffer();\n if (ibo === null) {\n throw new Error(\"lite-gl: gl.createBuffer returned null (sprite IBO)\");\n }\n renderer._ibo = ibo;\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, ibo);\n s.boundElementBuffer = ibo;\n gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, renderer._indices, gl.STATIC_DRAW);\n}\n"]}
1
+ {"version":3,"file":"sprites.js","sourceRoot":"","sources":["../src/sprites.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAwB,MAAM,cAAc,CAAC;AAC3F,OAAO,EAAE,YAAY,EAAE,aAAa,EAAiB,aAAa,EAAE,gBAAgB,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACrH,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AACvD,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAGlD,kFAAkF;AAElF;;kFAEkF;AAClF,MAAM,oBAAoB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA8B3B,CAAC;AAEH;;uEAEuE;AACvE,MAAM,sBAAsB,GAAG;;;;;;;;;;EAU7B,CAAC;AAEH,kFAAkF;AAElF;;2BAE2B;AAC3B,MAAM,iBAAiB,GAA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AoB,EAAE,GAAG,CAAC,CAAC;IAC5C,CAAC,CAAC,kBAAkB,GAAG,GAAG,CAAC;IAC3B,wEAAwE;IACxE,4EAA4E;IAC5E,MAAM,OAAO,GAAG,IAAI,WAAW,CAAC,QAAQ,CAAC,QAAQ,GAAG,kBAAkB,CAAC,CAAC;IACxE,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,IAAI,kBAAkB,EAAE,CAAC,IAAI,gBAAgB,EAAE,CAAC;QACxF,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;QAChC,OAAO,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QACvB,OAAO,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QACxC,OAAO,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IAC3B,CAAC;IACD,EAAE,CAAC,UAAU,CAAC,EAAE,CAAC,oBAAoB,EAAE,OAAO,EAAE,EAAE,CAAC,WAAW,CAAC,CAAC;AACpE,CAAC","sourcesContent":["/**\n * Sprite / instanced-quad renderer.\n *\n * Part of the public API via the `@babylonjs/lite-gl` barrel. The package is\n * `sideEffects: false`, so consumers that don't render sprites tree-shake it out.\n *\n * This is the lite-gl equivalent of Babylon's `SpriteRenderer` + `ThinSprite`\n * (`Sprites/spriteRenderer.js`, `Sprites/thinSprite.js`). The vertex layout,\n * per-cell UV math and corner/rotation transform are copied verbatim from the\n * non-instanced path of Babylon's `SpriteRenderer` so a ported `ThinEngine`\n * consumer renders identically. The shaders are the GLSL ES 3.00 translation of\n * Babylon's `Shaders/sprites.vertex.js` / `sprites.fragment.js`, with the\n * fog / log-depth / pixel-perfect / alpha-test branches removed (lite-gl has\n * no depth attachment by default — see notes on `disableDepthWrite` below).\n */\nimport { offContextRestored, onContextRestored, type GLEngineContext } from \"./context.js\";\nimport { createEffect, disposeEffect, type GLEffect, isEffectReady, setEffectTexture, useEffect } from \"./effect.js\";\nimport { GLBlendMode, setBlendMode } from \"./blend.js\";\nimport { applyGLStates } from \"./apply-states.js\";\nimport { type GLTexture } from \"./texture.js\";\n\n/* ───────────────────────────── shaders (GLSL ES 3.00) ───────────────────── */\n\n/** Vertex shader — GLSL ES 3.00 translation of Babylon's `spritesVertexShader`\n * core path. Attribute locations 0..5 match `createSpriteRenderer`'s\n * `attributeNames` order so the renderer's VAO feeds every program correctly. */\nconst SPRITE_VERTEX_SOURCE = `#version 300 es\nprecision highp float;\nlayout(location = 0) in vec4 position;\nlayout(location = 1) in vec2 options;\nlayout(location = 2) in vec2 offsets;\nlayout(location = 3) in vec2 inverts;\nlayout(location = 4) in vec4 cellInfo;\nlayout(location = 5) in vec4 color;\nuniform mat4 view;\nuniform mat4 projection;\nout vec2 vUV;\nout vec4 vColor;\nvoid main(void) {\n vec3 viewPos = (view * vec4(position.xyz, 1.0)).xyz;\n float angle = position.w;\n vec2 size = vec2(options.x, options.y);\n vec2 offset = offsets.xy;\n vec2 cornerPos = vec2(offset.x - 0.5, offset.y - 0.5) * size;\n vec3 rotatedCorner;\n rotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\n rotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\n rotatedCorner.z = 0.0;\n viewPos += rotatedCorner;\n gl_Position = projection * vec4(viewPos, 1.0);\n vColor = color;\n vec2 uvOffset = vec2(abs(offset.x - inverts.x), abs(1.0 - offset.y - inverts.y));\n vec2 uvPlace = cellInfo.xy;\n vec2 uvSize = cellInfo.zw;\n vUV.x = uvPlace.x + uvSize.x * uvOffset.x;\n vUV.y = uvPlace.y + uvSize.y * uvOffset.y;\n}`;\n\n/** Fragment shader — GLSL ES 3.00 translation of Babylon's `spritesPixelShader`\n * color pass: `texture(diffuseSampler, vUV) * vColor`. The alpha-test/discard\n * branch is dropped because lite-gl never runs the depth pre-pass. */\nconst SPRITE_FRAGMENT_SOURCE = `#version 300 es\nprecision highp float;\nin vec2 vUV;\nin vec4 vColor;\nuniform sampler2D diffuseSampler;\nout vec4 glFragColor;\nvoid main(void) {\n vec4 color = texture(diffuseSampler, vUV);\n color *= vColor;\n glFragColor = color;\n}`;\n\n/* ───────────────────────────── layout constants ─────────────────────────── */\n\n/** Floats per vertex: position.xyz + angle (4), size (2), corner offset (2),\n * inverts (2), cellInfo (4), color (4) = 18. Matches Babylon's non-instanced\n * `_vertexBufferSize`. */\nconst FLOATS_PER_VERTEX = 18;\n/** Four corner vertices per sprite quad (non-instanced, like Babylon). */\nconst VERTS_PER_SPRITE = 4;\n/** Six indices per sprite (two triangles). */\nconst INDICES_PER_SPRITE = 6;\n/** Bytes per float — `Float32Array.BYTES_PER_ELEMENT`. */\nconst BYTES_PER_FLOAT = 4;\n/** Stride between consecutive vertices, in bytes. */\nconst VERTEX_STRIDE_BYTES = FLOATS_PER_VERTEX * BYTES_PER_FLOAT;\n/** UV inset applied to each quad corner, matching Babylon's default\n * `SpriteRenderer` epsilon (0.01) so cell sampling never bleeds neighbours. */\nconst SPRITE_EPSILON = 0.01;\n/** Max sprites: 4 verts/sprite must keep every index within `Uint16` range\n * (`capacity * 4 - 1 <= 65535`). */\nconst MAX_CAPACITY = 16384;\n\n/** Per-corner U offset (pre-epsilon), one entry per quad vertex. Module-scoped\n * literal — pure per bundler convention, allocated once (never per frame). */\nconst CORNER_OFFSET_X = [0, 1, 1, 0];\n/** Per-corner V offset (pre-epsilon), one entry per quad vertex. */\nconst CORNER_OFFSET_Y = [0, 0, 1, 1];\n\n/** Attribute names in location order — index `i` is bound to `location = i` by\n * `createEffect`/`linkProgram`, matching the shader's `layout(location = i)`. */\nconst SPRITE_ATTRIBUTES = [\"position\", \"options\", \"offsets\", \"inverts\", \"cellInfo\", \"color\"] as const;\n\n/* ─────────────────────────────── public types ──────────────────────────── */\n\n/** An RGBA color with each channel in `[0, 1]`, used for per-sprite tint. */\nexport interface GLSpriteColor {\n /** Red, 0..1. */\n r: number;\n /** Green, 0..1. */\n g: number;\n /** Blue, 0..1. */\n b: number;\n /** Alpha, 0..1. */\n a: number;\n}\n\n/** A single sprite — a plain data object mirroring the fields of Babylon's\n * `ThinSprite` that the renderer reads. No animation state: `cellIndex` is set\n * directly by the consumer (lite-gl does not port `ThinSprite.playAnimation`). */\nexport interface GLSprite {\n /** World-space position of the sprite center. */\n position: { x: number; y: number; z: number };\n /** Width in world units. */\n width: number;\n /** Height in world units. */\n height: number;\n /** Rotation angle, in radians. */\n angle: number;\n /** Sprite-sheet cell index (0-based, row-major). Out-of-range / negative\n * values are clamped to 0, matching Babylon's `if (!cellIndex) = 0`. Ignored\n * when a manual UV rect (`uSize`) is set. Optional — defaults to `0`. */\n cellIndex?: number;\n /** Optional tint; defaults to opaque white `{ r: 1, g: 1, b: 1, a: 1 }`. */\n color?: GLSpriteColor;\n /** Flip the cell horizontally. Defaults to `false`. */\n invertU?: boolean;\n /** Flip the cell vertically. Defaults to `false`. */\n invertV?: boolean;\n /** Manual UV rect — normalized left (U) origin in `[0, 1]`, mirroring\n * Babylon's `ThinSprite._xOffset`. Set together with {@link GLSprite.uSize}\n * to address an arbitrary sub-rectangle of the sheet instead of the fixed\n * `cellIndex` grid (used by the lottie atlas, whose cells vary in size). */\n uOffset?: number;\n /** Manual UV rect — normalized top (V) origin in `[0, 1]` (≙ Babylon\n * `ThinSprite._yOffset`). See {@link GLSprite.uSize}. */\n vOffset?: number;\n /** Manual UV rect — cell width in **texels** (≙ Babylon `ThinSprite._xSize`;\n * divided by the texture width when building vertices). Presence of `uSize`\n * switches the sprite into manual-UV mode (the `cellIndex` grid is ignored).\n * `0` samples a single column — the \"solid color\" trick. */\n uSize?: number;\n /** Manual UV rect — cell height in **texels** (≙ Babylon `ThinSprite._ySize`).\n * See {@link GLSprite.uSize}. Defaults to `0` when `uSize` is set but `vSize`\n * is omitted. */\n vSize?: number;\n /** When `false`, the sprite is skipped. Defaults to `true`. */\n isVisible?: boolean;\n}\n\n/** Options for {@link createSpriteRenderer}. */\nexport interface GLSpriteRendererOptions {\n /** Maximum number of sprites drawable in one `renderSprites` call. Must be\n * an integer in `[1, 16384]` (the `Uint16` index-buffer limit). */\n capacity: number;\n /** Cell width in texels within the sprite sheet, for the fixed-grid\n * `cellIndex` path. Optional — defaults to `1`; irrelevant when every\n * sprite supplies a manual UV rect (`uSize`), as the lottie atlas does. */\n cellWidth?: number;\n /** Cell height in texels within the sprite sheet. Optional — defaults to\n * `1`. See {@link GLSpriteRendererOptions.cellWidth}. */\n cellHeight?: number;\n /** Per-corner UV/position inset applied to each quad vertex, in the `[0, 0.5)`\n * range — the `epsilon` constructor argument of Babylon's `SpriteRenderer`.\n * It both insets cell UV sampling (so a cell never bleeds its neighbours) and\n * shrinks the quad by `epsilon * size` per side. Defaults to `0.01` (Babylon's\n * `SpriteRenderer` default). Pass `0` to disable insetting — the lottie atlas\n * does this (it relies on edge-extruded cells + center sampling instead, so a\n * non-zero inset would shrink every sprite by ~`0.01·size` per edge). */\n epsilon?: number;\n /** The sprite-sheet texture. May be swapped later via\n * {@link setSpriteRendererTexture}. */\n texture: GLTexture;\n /** Blend mode for the draw. Defaults to {@link GLBlendMode.ALPHA} (2),\n * matching Babylon's `SpriteRenderer.blendMode` default. */\n blendMode?: GLBlendMode;\n /** When `true` (default), `renderSprites` resets the blend mode to\n * {@link GLBlendMode.DISABLE} after drawing — mirroring Babylon's\n * `SpriteRenderer.autoResetAlpha = true`. Set `false` to leave the\n * renderer's `blendMode` applied after the draw (the lottie player relies\n * on this so its premultiplied alpha mode persists across passes). */\n autoResetAlpha?: boolean;\n /** Accepted for Babylon API parity. lite-gl's default engine has no depth\n * attachment (`depth: false`), so there is no depth pre-pass and this flag\n * has no observable effect; it is stored verbatim for a future depth-aware\n * consumer. Defaults to `false`. */\n disableDepthWrite?: boolean;\n}\n\n/**\n * A sprite renderer owning its own VBO/IBO/VAO and `GLEffect`. Created by\n * {@link createSpriteRenderer}; drive it with {@link renderSprites} and release\n * it with {@link disposeSpriteRenderer}.\n */\nexport interface GLSpriteRenderer {\n /** The sprite-sheet texture sampled by the shader. Swap via\n * {@link setSpriteRendererTexture}. */\n texture: GLTexture;\n /** Cell width in texels (selects the sub-rectangle for `cellIndex`). */\n cellWidth: number;\n /** Cell height in texels. */\n cellHeight: number;\n /** Per-corner UV/position inset (Babylon `SpriteRenderer` `epsilon`). */\n epsilon: number;\n /** Active blend mode applied by `renderSprites` before drawing. */\n blendMode: GLBlendMode;\n /** When `true`, `renderSprites` resets blend to {@link GLBlendMode.DISABLE}\n * after drawing (Babylon `autoResetAlpha`). */\n autoResetAlpha: boolean;\n /** Babylon-parity flag (no effect without a depth attachment). */\n disableDepthWrite: boolean;\n /** Maximum sprites per draw, fixed at creation. */\n readonly capacity: number;\n /** @internal The compiled sprite effect this renderer owns. */\n _effect: GLEffect;\n /** @internal Sprite VAO (attribute pointers + element binding). Null until\n * built and after disposal; rebuilt on `webglcontextrestored`. */\n _vao: WebGLVertexArrayObject | null;\n /** @internal Dynamic vertex buffer, sized for `capacity` at creation. */\n _vbo: WebGLBuffer | null;\n /** @internal Static index buffer (`capacity * 6` `Uint16` indices). */\n _ibo: WebGLBuffer | null;\n /** @internal Preallocated CPU-side vertex scratch — reused every frame\n * (`renderSprites` performs zero allocations). */\n _vertexData: Float32Array;\n /** @internal Context-restored handler — rebuilds the GPU buffers. */\n _restore?: () => void;\n /** @internal True once disposed; subsequent calls are no-ops. */\n _disposed: boolean;\n}\n\n/* ──────────────────────────────── public API ───────────────────────────── */\n\n/**\n * Create a sprite renderer with its own GPU buffers and compiled effect.\n *\n * Preallocates the CPU vertex scratch and the index buffer at `capacity`, so\n * {@link renderSprites} performs no allocations. The sprite GPU buffers are\n * rebuilt automatically on `webglcontextrestored` (the owned effect is rebuilt\n * by the engine's context-restore protocol), unless the engine is host-owned\n * (`createHostOwnedGLEngine`). Static index data is regenerated on rebuild, not\n * retained.\n *\n * @param engine - The engine to create GL resources on.\n * @param options - See {@link GLSpriteRendererOptions}.\n * @returns The new {@link GLSpriteRenderer}.\n * @throws If `capacity` is not an integer in `[1, 16384]`, or if a provided\n * `cellWidth`/`cellHeight` is not positive.\n */\nexport function createSpriteRenderer(engine: GLEngineContext, options: GLSpriteRendererOptions): GLSpriteRenderer {\n const capacity = options.capacity;\n if (!Number.isInteger(capacity) || capacity < 1 || capacity > MAX_CAPACITY) {\n throw new Error(`lite-gl: sprite renderer capacity must be an integer in [1, ${MAX_CAPACITY}], got ${capacity}`);\n }\n // cellWidth/cellHeight drive only the fixed-grid `cellIndex` path; manual-UV\n // consumers (the lottie atlas) omit them. Default to 1; reject explicit ≤ 0.\n const cellWidth = options.cellWidth ?? 1;\n const cellHeight = options.cellHeight ?? 1;\n if (!(cellWidth > 0) || !(cellHeight > 0)) {\n throw new Error(\"lite-gl: sprite renderer cellWidth/cellHeight must be > 0\");\n }\n\n const effect = createEffect(engine, {\n name: \"sprites\",\n vertexSource: SPRITE_VERTEX_SOURCE,\n fragmentSource: SPRITE_FRAGMENT_SOURCE,\n uniformNames: [\"view\", \"projection\"],\n samplerNames: [\"diffuseSampler\"],\n attributeNames: SPRITE_ATTRIBUTES,\n });\n\n const renderer: GLSpriteRenderer = {\n texture: options.texture,\n cellWidth,\n cellHeight,\n epsilon: options.epsilon ?? SPRITE_EPSILON,\n blendMode: options.blendMode ?? GLBlendMode.ALPHA,\n autoResetAlpha: options.autoResetAlpha ?? true,\n disableDepthWrite: options.disableDepthWrite ?? false,\n capacity,\n _effect: effect,\n _vao: null,\n _vbo: null,\n _ibo: null,\n _vertexData: new Float32Array(capacity * VERTS_PER_SPRITE * FLOATS_PER_VERTEX),\n _disposed: false,\n };\n\n buildSpriteBuffers(engine, renderer);\n if (!engine._noRestore) {\n renderer._restore = (): void => {\n buildSpriteBuffers(engine, renderer);\n };\n onContextRestored(engine, renderer._restore);\n }\n return renderer;\n}\n\n/**\n * Build the per-sprite vertex data and draw all visible sprites in one\n * `drawElements` call. Performs no allocations — the vertex scratch is reused\n * and uploaded with `bufferSubData`.\n *\n * No-op when the context is lost/disposed, the renderer is disposed, the\n * texture is not ready, the effect is not ready, or there are no visible\n * sprites. Sets the renderer's blend mode before drawing and resets to\n * {@link GLBlendMode.DISABLE} afterwards (matching Babylon's\n * `autoResetAlpha = true`), so a subsequent `drawEffect` is unaffected.\n *\n * @param renderer - The renderer to draw with.\n * @param sprites - The sprites to draw (only `isVisible !== false` are drawn;\n * excess beyond `capacity` is ignored, matching Babylon).\n * @param deltaTime - Accepted for Babylon API parity; unused (lite-gl `GLSprite`\n * holds no animation state, so `cellIndex` is consumer-driven).\n * @param viewMatrix - Column-major 4x4 view matrix.\n * @param projectionMatrix - Column-major 4x4 projection matrix.\n */\nexport function renderSprites(\n renderer: GLSpriteRenderer,\n sprites: readonly GLSprite[],\n deltaTime: number,\n viewMatrix: Float32Array | number[],\n projectionMatrix: Float32Array | number[]\n): void {\n const engine = renderer._effect._engine;\n if (engine._isLost || engine._disposed || renderer._disposed) {\n return;\n }\n // `deltaTime` is accepted for Babylon `SpriteRenderer.render` parity but\n // unused: `GLSprite` carries no animation state, so `cellIndex` is driven\n // entirely by the consumer. Referenced here to keep the parameter name in\n // the public signature without tripping `noUnusedParameters`.\n void deltaTime;\n const tex = renderer.texture;\n if (!tex.isReady || sprites.length === 0) {\n return;\n }\n const effect = renderer._effect;\n if (!isEffectReady(effect)) {\n return;\n }\n if (renderer._vao === null || renderer._vbo === null) {\n return;\n }\n\n // ── Build vertex data (allocation-free) ──────────────────────────────────\n const vd = renderer._vertexData;\n const eps = renderer.epsilon;\n const texW = tex.width;\n const texH = tex.height;\n const cellW = renderer.cellWidth;\n const cellH = renderer.cellHeight;\n const rowSize = texW / cellW; // cells per sheet row\n const cellWidthN = cellW / texW;\n const cellHeightN = cellH / texH;\n const cap = renderer.capacity;\n const count = sprites.length;\n let visible = 0;\n for (let i = 0; i < count && visible < cap; i++) {\n const sprite = sprites[i];\n if (sprite === undefined || sprite.isVisible === false) {\n continue;\n }\n // UV rect — manual per-sprite rect (Babylon `ThinSprite._xOffset/_xSize`\n // path, selected when `uSize` is set) or the fixed `cellIndex` grid.\n // Both resolve to a normalized `(left, top, widthN, heightN)` rectangle,\n // matching Babylon's `_appendSpriteVertex` vertex layout exactly.\n let cellLeft: number;\n let cellTop: number;\n let cellWN: number;\n let cellHN: number;\n if (sprite.uSize !== undefined) {\n cellLeft = sprite.uOffset ?? 0;\n cellTop = sprite.vOffset ?? 0;\n cellWN = sprite.uSize / texW;\n cellHN = (sprite.vSize ?? 0) / texH;\n } else {\n const cellIndex = (sprite.cellIndex ?? 0) > 0 ? (sprite.cellIndex as number) : 0;\n const row = (cellIndex / rowSize) >> 0;\n cellLeft = ((cellIndex - row * rowSize) * cellW) / texW;\n cellTop = (row * cellH) / texH;\n cellWN = cellWidthN;\n cellHN = cellHeightN;\n }\n\n const px = sprite.position.x;\n const py = sprite.position.y;\n const pz = sprite.position.z;\n const angle = sprite.angle;\n const w = sprite.width;\n const h = sprite.height;\n const invU = sprite.invertU === true ? 1 : 0;\n const invV = sprite.invertV === true ? 1 : 0;\n const color = sprite.color;\n const cr = color !== undefined ? color.r : 1;\n const cg = color !== undefined ? color.g : 1;\n const cb = color !== undefined ? color.b : 1;\n const ca = color !== undefined ? color.a : 1;\n\n let off = visible * VERTS_PER_SPRITE * FLOATS_PER_VERTEX;\n for (let c = 0; c < VERTS_PER_SPRITE; c++) {\n const ox = CORNER_OFFSET_X[c] === 0 ? eps : 1 - eps;\n const oy = CORNER_OFFSET_Y[c] === 0 ? eps : 1 - eps;\n vd[off] = px;\n vd[off + 1] = py;\n vd[off + 2] = pz;\n vd[off + 3] = angle;\n vd[off + 4] = w;\n vd[off + 5] = h;\n vd[off + 6] = ox;\n vd[off + 7] = oy;\n vd[off + 8] = invU;\n vd[off + 9] = invV;\n vd[off + 10] = cellLeft;\n vd[off + 11] = cellTop;\n vd[off + 12] = cellWN;\n vd[off + 13] = cellHN;\n vd[off + 14] = cr;\n vd[off + 15] = cg;\n vd[off + 16] = cb;\n vd[off + 17] = ca;\n off += FLOATS_PER_VERTEX;\n }\n visible++;\n }\n if (visible === 0) {\n return;\n }\n\n // ── Upload + draw ────────────────────────────────────────────────────────\n const gl = engine.gl;\n const s = engine._state;\n const vao = renderer._vao;\n if (s.boundVao !== vao) {\n gl.bindVertexArray(vao);\n s.boundVao = vao;\n // Binding the VAO restores its element-array binding (VAO state).\n s.boundElementBuffer = renderer._ibo;\n }\n const vbo = renderer._vbo;\n if (s.boundArrayBuffer !== vbo) {\n gl.bindBuffer(gl.ARRAY_BUFFER, vbo);\n s.boundArrayBuffer = vbo;\n }\n const floatCount = visible * VERTS_PER_SPRITE * FLOATS_PER_VERTEX;\n gl.bufferSubData(gl.ARRAY_BUFFER, 0, vd, 0, floatCount);\n\n useEffect(effect);\n const viewLoc = effect.uniformLocations[\"view\"];\n if (viewLoc !== null && viewLoc !== undefined) {\n gl.uniformMatrix4fv(viewLoc, false, viewMatrix);\n }\n const projLoc = effect.uniformLocations[\"projection\"];\n if (projLoc !== null && projLoc !== undefined) {\n gl.uniformMatrix4fv(projLoc, false, projectionMatrix);\n }\n setEffectTexture(effect, \"diffuseSampler\", tex);\n\n setBlendMode(engine, renderer.blendMode);\n applyGLStates(engine);\n gl.drawElements(gl.TRIANGLES, visible * INDICES_PER_SPRITE, gl.UNSIGNED_SHORT, 0);\n // Auto-reset (Babylon `autoResetAlpha = true`): leave blend disabled so a\n // subsequent fullscreen `drawEffect` renders with the same state as before.\n // When `autoResetAlpha` is false (lottie), keep `renderer.blendMode` applied\n // so a premultiplied-alpha mode persists across multiple atlas-page passes.\n if (renderer.autoResetAlpha) {\n setBlendMode(engine, GLBlendMode.DISABLE);\n }\n}\n\n/** Swap the sprite-sheet texture (≙ Babylon assigning `SpriteRenderer.texture`\n * after an async load). The cell size is unchanged — adjust `cellWidth` /\n * `cellHeight` on the renderer directly if the new sheet differs. No-op when\n * the renderer is disposed.\n * No GL call is made — the texture is bound at draw time.\n *\n * @param renderer - The renderer to update.\n * @param texture - The new sprite-sheet texture. */\nexport function setSpriteRendererTexture(renderer: GLSpriteRenderer, texture: GLTexture): void {\n if (renderer._disposed) {\n return;\n }\n renderer.texture = texture;\n}\n\n/** Release the renderer's VAO/VBO/IBO and the effect it owns, and unregister\n * its context-restore handler. Idempotent. Does NOT dispose the texture — the\n * consumer that supplied it owns its lifetime.\n *\n * @param renderer - The renderer to dispose. */\nexport function disposeSpriteRenderer(renderer: GLSpriteRenderer): void {\n const engine = renderer._effect._engine;\n if (renderer._disposed) {\n return;\n }\n renderer._disposed = true;\n if (renderer._restore) {\n offContextRestored(engine, renderer._restore);\n }\n disposeEffect(renderer._effect);\n if (!engine._isLost && !engine._disposed) {\n const gl = engine.gl;\n const s = engine._state;\n if (renderer._vao !== null) {\n gl.deleteVertexArray(renderer._vao);\n if (s.boundVao === renderer._vao) {\n s.boundVao = null;\n }\n }\n if (renderer._vbo !== null) {\n gl.deleteBuffer(renderer._vbo);\n if (s.boundArrayBuffer === renderer._vbo) {\n s.boundArrayBuffer = null;\n }\n }\n if (renderer._ibo !== null) {\n gl.deleteBuffer(renderer._ibo);\n if (s.boundElementBuffer === renderer._ibo) {\n s.boundElementBuffer = null;\n }\n }\n }\n renderer._vao = null;\n renderer._vbo = null;\n renderer._ibo = null;\n}\n\n/* ──────────────────────────── internal helpers ──────────────────────────── */\n\n/** (Re)create the VAO + VBO + IBO and configure the six vertex attributes.\n * Called from `createSpriteRenderer` and from the `webglcontextrestored`\n * handler (the prior handles are dead per the WebGL spec — not deleted here).\n * No-op when the context is lost/disposed. */\nfunction buildSpriteBuffers(engine: GLEngineContext, renderer: GLSpriteRenderer): void {\n if (engine._isLost || engine._disposed) {\n return;\n }\n const gl = engine.gl;\n const s = engine._state;\n\n const vao = gl.createVertexArray();\n if (vao === null) {\n throw new Error(\"lite-gl: gl.createVertexArray returned null (sprite VAO)\");\n }\n renderer._vao = vao;\n gl.bindVertexArray(vao);\n s.boundVao = vao;\n\n const vbo = gl.createBuffer();\n if (vbo === null) {\n throw new Error(\"lite-gl: gl.createBuffer returned null (sprite VBO)\");\n }\n renderer._vbo = vbo;\n gl.bindBuffer(gl.ARRAY_BUFFER, vbo);\n s.boundArrayBuffer = vbo;\n // Allocate the dynamic vertex storage at full capacity; filled per frame.\n gl.bufferData(gl.ARRAY_BUFFER, renderer._vertexData.byteLength, gl.DYNAMIC_DRAW);\n\n // Attribute pointers — locations match SPRITE_ATTRIBUTES / shader layout.\n gl.enableVertexAttribArray(0);\n gl.vertexAttribPointer(0, 4, gl.FLOAT, false, VERTEX_STRIDE_BYTES, 0);\n gl.enableVertexAttribArray(1);\n gl.vertexAttribPointer(1, 2, gl.FLOAT, false, VERTEX_STRIDE_BYTES, 4 * BYTES_PER_FLOAT);\n gl.enableVertexAttribArray(2);\n gl.vertexAttribPointer(2, 2, gl.FLOAT, false, VERTEX_STRIDE_BYTES, 6 * BYTES_PER_FLOAT);\n gl.enableVertexAttribArray(3);\n gl.vertexAttribPointer(3, 2, gl.FLOAT, false, VERTEX_STRIDE_BYTES, 8 * BYTES_PER_FLOAT);\n gl.enableVertexAttribArray(4);\n gl.vertexAttribPointer(4, 4, gl.FLOAT, false, VERTEX_STRIDE_BYTES, 10 * BYTES_PER_FLOAT);\n gl.enableVertexAttribArray(5);\n gl.vertexAttribPointer(5, 4, gl.FLOAT, false, VERTEX_STRIDE_BYTES, 14 * BYTES_PER_FLOAT);\n\n const ibo = gl.createBuffer();\n if (ibo === null) {\n throw new Error(\"lite-gl: gl.createBuffer returned null (sprite IBO)\");\n }\n renderer._ibo = ibo;\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, ibo);\n s.boundElementBuffer = ibo;\n // Regenerate the static [0,1,2, 0,2,3] pattern instead of retaining it:\n // creation and the rare restore pay one transient array, nothing per frame.\n const indices = new Uint16Array(renderer.capacity * INDICES_PER_SPRITE);\n for (let i = 0, v = 0; i < indices.length; i += INDICES_PER_SPRITE, v += VERTS_PER_SPRITE) {\n indices[i] = indices[i + 3] = v;\n indices[i + 1] = v + 1;\n indices[i + 2] = indices[i + 4] = v + 2;\n indices[i + 5] = v + 3;\n }\n gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW);\n}\n"]}
package/state.d.ts CHANGED
@@ -28,22 +28,29 @@
28
28
  */
29
29
  export interface GLState {
30
30
  currentProgram: WebGLProgram | null;
31
+ /** Active texture unit, or -1 when unknown. */
31
32
  activeTextureUnit: number;
32
- /** Per-unit TEXTURE_2D binding; length === caps.maxTextureUnits. */
33
- boundTextures: (WebGLTexture | null)[];
33
+ /** Per-unit TEXTURE_2D binding; undefined = unknown, null = confirmed unbound.
34
+ * Length === caps.maxTextureUnits. */
35
+ boundTextures: (WebGLTexture | null | undefined)[];
34
36
  boundArrayBuffer: WebGLBuffer | null;
35
37
  boundElementBuffer: WebGLBuffer | null;
36
- boundVao: WebGLVertexArrayObject | null;
38
+ /** Bound VAO; `null` = the default VAO, `undefined` = unknown (fresh or wiped
39
+ * cache, context loss), so the next VAO bind is always issued. */
40
+ boundVao: WebGLVertexArrayObject | null | undefined;
37
41
  viewportX: number;
38
42
  viewportY: number;
39
43
  viewportW: number;
40
44
  viewportH: number;
41
45
  /**
42
- * Currently-bound draw framebuffer, or `null` for the default (canvas)
43
- * framebuffer. Owned by the render-target module's `bindRenderTarget`
44
- * (binding `null` returns to the canvas). Reset to `null` on context-lost.
46
+ * Currently-bound draw framebuffer, `null` for the default (canvas)
47
+ * framebuffer, or `undefined` when unknown (fresh or wiped cache — the
48
+ * context may be shared with a host that left its own framebuffer bound).
49
+ * Owned by the render-target module's `bindRenderTarget` (binding `null`
50
+ * returns to the canvas). Reset to `undefined` by `wipeGLStateCache` and on
51
+ * context loss.
45
52
  */
46
- boundFramebuffer: WebGLFramebuffer | null;
53
+ boundFramebuffer: WebGLFramebuffer | null | undefined;
47
54
  /**
48
55
  * Deferred render-state (blend / depth / cull / stencil / color-mask) packed
49
56
  * into a flat `Float64Array(46)`. Slots `0..20` (indexed by the `RS_*`
@@ -83,6 +90,7 @@ export interface GLState {
83
90
  statesDirty: boolean;
84
91
  /** Scissor-test enable tri-state (`-1` unset, `0` off, `1` on). */
85
92
  scissorEnabled: number;
93
+ /** Cached scissor rectangle; a `scissorW` of `-1` marks it unknown. */
86
94
  scissorX: number;
87
95
  scissorY: number;
88
96
  scissorW: number;
@@ -94,12 +102,14 @@ export interface GLState {
94
102
  /** Cached `gl.pixelStorei(UNPACK_PREMULTIPLY_ALPHA_WEBGL)`, or `-1` unset. */
95
103
  unpackPremultiplyAlpha: number;
96
104
  /**
97
- * Per-location vertex-attribute enable flags for the DEFAULT (null) VAO —
105
+ * Per-location vertex-attribute bindings for the DEFAULT (null) VAO —
98
106
  * the mesh / instancing path (mirrors Babylon's `_vertexAttribArraysEnabled`).
99
- * Index is the attribute location. lite-gl's quad / sprite paths use their
100
- * own VAOs and do not touch this. Cleared on context-lost.
107
+ * A buffer handle means enabled with that pointer; true means enabled with
108
+ * an invalidated pointer; null means confirmed disabled; undefined means
109
+ * disabled — or unknown while `_unknownAttribs` is set. Index is the
110
+ * attribute location. Cleared on context loss or cache wipe.
101
111
  */
102
- enabledAttribs: boolean[];
112
+ enabledAttribs: (WebGLBuffer | true | null)[];
103
113
  /**
104
114
  * Attribute locations currently configured with a non-default vertex divisor
105
115
  * (instanced attributes), mirroring Babylon's `_currentInstanceLocations`.
@@ -112,7 +122,8 @@ export interface GLState {
112
122
  quadIbo: WebGLBuffer | null;
113
123
  quadVao: WebGLVertexArrayObject | null;
114
124
  }
115
- /** Allocate a fresh, fully-null GLState sized for `maxTextureUnits`. */
125
+ /** Allocate a fresh GLState with unknown texture, VAO and framebuffer bindings
126
+ * (the canvas context may already be in use by a host), sized for `maxTextureUnits`. */
116
127
  export declare function createGLState(maxTextureUnits: number): GLState;
117
128
  /** Reset only the cached "current GL state" — every binding (program / buffers /
118
129
  * textures / VAO / framebuffer) and render-state (blend / depth / stencil /
@@ -120,7 +131,9 @@ export declare function createGLState(maxTextureUnits: number): GLState;
120
131
  * deferred render-state array (BOTH the actual applied values and the DESIRED
121
132
  * twins) plus `statesDirty` — to its unset sentinel, WITHOUT discarding owned
122
133
  * GPU resources (the shared quad). After this, the next setter in each category
123
- * is re-issued rather than elided.
134
+ * is re-issued rather than elided. The VAO and framebuffer bindings become
135
+ * `undefined` (unknown), NOT `null`: `null` is a real binding (default VAO /
136
+ * canvas) and would elide the rebind while the host's object is still bound.
124
137
  *
125
138
  * Used by `resetGLState` (context-lost) and by `wipeGLStateCache` (a host that
126
139
  * shares the GL context calling in after mutating raw `gl.*` state). The shared
package/state.js CHANGED
@@ -74,26 +74,27 @@ function resetRenderStateArray(rs) {
74
74
  rs.fill(0);
75
75
  applyRenderStateSentinels(rs);
76
76
  }
77
- /** Allocate a fresh, fully-null GLState sized for `maxTextureUnits`. */
77
+ /** Allocate a fresh GLState with unknown texture, VAO and framebuffer bindings
78
+ * (the canvas context may already be in use by a host), sized for `maxTextureUnits`. */
78
79
  export function createGLState(maxTextureUnits) {
79
80
  return {
80
81
  currentProgram: null,
81
- activeTextureUnit: 0,
82
- boundTextures: new Array(maxTextureUnits).fill(null),
82
+ activeTextureUnit: -1,
83
+ boundTextures: new Array(maxTextureUnits),
83
84
  boundArrayBuffer: null,
84
85
  boundElementBuffer: null,
85
- boundVao: null,
86
+ boundVao: undefined,
86
87
  viewportX: 0,
87
88
  viewportY: 0,
88
89
  viewportW: 0,
89
90
  viewportH: 0,
90
- boundFramebuffer: null,
91
+ boundFramebuffer: undefined,
91
92
  rs: createRenderStateArray(),
92
93
  statesDirty: false,
93
94
  scissorEnabled: -1,
94
95
  scissorX: 0,
95
96
  scissorY: 0,
96
- scissorW: 0,
97
+ scissorW: -1,
97
98
  scissorH: 0,
98
99
  unpackAlignment: -1,
99
100
  unpackFlipY: -1,
@@ -111,7 +112,9 @@ export function createGLState(maxTextureUnits) {
111
112
  * deferred render-state array (BOTH the actual applied values and the DESIRED
112
113
  * twins) plus `statesDirty` — to its unset sentinel, WITHOUT discarding owned
113
114
  * GPU resources (the shared quad). After this, the next setter in each category
114
- * is re-issued rather than elided.
115
+ * is re-issued rather than elided. The VAO and framebuffer bindings become
116
+ * `undefined` (unknown), NOT `null`: `null` is a real binding (default VAO /
117
+ * canvas) and would elide the rebind while the host's object is still bound.
115
118
  *
116
119
  * Used by `resetGLState` (context-lost) and by `wipeGLStateCache` (a host that
117
120
  * shares the GL context calling in after mutating raw `gl.*` state). The shared
@@ -119,23 +122,20 @@ export function createGLState(maxTextureUnits) {
119
122
  * here to avoid leaking + needlessly rebuilding them every render scope. */
120
123
  export function resetGLStateCache(state) {
121
124
  state.currentProgram = null;
122
- state.activeTextureUnit = 0;
123
- state.boundTextures.fill(null);
125
+ state.activeTextureUnit = -1;
126
+ state.boundTextures.fill(undefined);
124
127
  state.boundArrayBuffer = null;
125
128
  state.boundElementBuffer = null;
126
- state.boundVao = null;
129
+ state.boundVao = undefined;
127
130
  state.viewportX = 0;
128
131
  state.viewportY = 0;
129
132
  state.viewportW = 0;
130
133
  state.viewportH = 0;
131
- state.boundFramebuffer = null;
134
+ state.boundFramebuffer = undefined;
132
135
  resetRenderStateArray(state.rs);
133
136
  state.statesDirty = false;
134
137
  state.scissorEnabled = -1;
135
- state.scissorX = 0;
136
- state.scissorY = 0;
137
- state.scissorW = 0;
138
- state.scissorH = 0;
138
+ state.scissorW = -1;
139
139
  state.unpackAlignment = -1;
140
140
  state.unpackFlipY = -1;
141
141
  state.unpackPremultiplyAlpha = -1;
package/state.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"state.js","sourceRoot":"","sources":["../src/state.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;kFAekF;AAClF,gBAAgB,CAAC,MAAM,CAAC,MAAM,gBAAgB,GAAG,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AC,CAAC;IACpB,KAAK,CAAC,SAAS,GAAG,CAAC,CAAC;IACpB,KAAK,CAAC,SAAS,GAAG,CAAC,CAAC;IACpB,KAAK,CAAC,gBAAgB,GAAG,IAAI,CAAC;IAC9B,qBAAqB,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IAChC,KAAK,CAAC,WAAW,GAAG,KAAK,CAAC;IAC1B,KAAK,CAAC,cAAc,GAAG,CAAC,CAAC,CAAC;IAC1B,KAAK,CAAC,QAAQ,GAAG,CAAC,CAAC;IACnB,KAAK,CAAC,QAAQ,GAAG,CAAC,CAAC;IACnB,KAAK,CAAC,QAAQ,GAAG,CAAC,CAAC;IACnB,KAAK,CAAC,QAAQ,GAAG,CAAC,CAAC;IACnB,KAAK,CAAC,eAAe,GAAG,CAAC,CAAC,CAAC;IAC3B,KAAK,CAAC,WAAW,GAAG,CAAC,CAAC,CAAC;IACvB,KAAK,CAAC,sBAAsB,GAAG,CAAC,CAAC,CAAC;IAClC,KAAK,CAAC,cAAc,CAAC,MAAM,GAAG,CAAC,CAAC;IAChC,KAAK,CAAC,iBAAiB,CAAC,MAAM,GAAG,CAAC,CAAC;AACvC,CAAC;AAED;;;wDAGwD;AACxD,MAAM,UAAU,YAAY,CAAC,KAAc;IACvC,iBAAiB,CAAC,KAAK,CAAC,CAAC;IACzB,KAAK,CAAC,OAAO,GAAG,IAAI,CAAC;IACrB,KAAK,CAAC,OAAO,GAAG,IAAI,CAAC;IACrB,KAAK,CAAC,OAAO,GAAG,IAAI,CAAC;AACzB,CAAC","sourcesContent":["import type { GLEngineContext } from \"./context.js\";\n\n/* ─── Deferred render-state index-array layout ────────────────────────────────\n * The deferred render-state (blend / depth / cull / stencil / color-mask) lives\n * in a flat `Float64Array(46)` on `GLState.rs`: slots `0..20` hold the ACTUAL\n * applied GL state, slots `21..41` (`RS_X + RS_DESIRED`) the DESIRED twin, and\n * slots `42..45` the standalone (no-desired-twin) cached `gl.clearColor` RGBA.\n * `setStencilOpSeparate` lazily expands it to 52 slots for back-face operations.\n *\n * These `@internal` index consts are imported by blend.ts / depth-stencil.ts /\n * apply-states.ts. Because they are plain `const` integers, esbuild inlines each\n * to a 1–2 char literal (`rs[RS_BLEND_SRC_RGB + RS_DESIRED]` → `rs[22]`) when\n * bundling a scene — far smaller than the old cross-module `.dBlendSrcRGB` named\n * props, which could not be mangled and shipped verbatim in every bundle.\n *\n * Float64Array (NOT Int32Array) is required: `RS_STENCIL_MASK` /\n * `RS_STENCIL_FUNC_MASK` can be `0xFFFFFFFF`, which Int32 would store as `-1` and\n * collide with the `-1` \"unset\" sentinel; Float64 keeps `4294967295` distinct. */\n/** @internal */ export const RS_BLEND_ENABLED = 0;\n/** @internal */ export const RS_BLEND_SRC_RGB = 1;\n/** @internal */ export const RS_BLEND_DST_RGB = 2;\n/** @internal */ export const RS_BLEND_SRC_A = 3;\n/** @internal */ export const RS_BLEND_DST_A = 4;\n/** @internal */ export const RS_BLEND_EQ_RGB = 5;\n/** @internal */ export const RS_BLEND_EQ_A = 6;\n/** @internal */ export const RS_DEPTH_TEST = 7;\n/** @internal */ export const RS_DEPTH_MASK = 8;\n/** @internal */ export const RS_DEPTH_FUNC = 9;\n/** @internal */ export const RS_CULL_ENABLED = 10;\n/** @internal */ export const RS_CULL_FACE = 11;\n/** @internal */ export const RS_STENCIL_TEST = 12;\n/** @internal */ export const RS_STENCIL_MASK = 13;\n/** @internal */ export const RS_STENCIL_FUNC_FUNC = 14;\n/** @internal */ export const RS_STENCIL_FUNC_REF = 15;\n/** @internal */ export const RS_STENCIL_FUNC_MASK = 16;\n/** @internal */ export const RS_STENCIL_OP_FAIL = 17;\n/** @internal */ export const RS_STENCIL_OP_ZFAIL = 18;\n/** @internal */ export const RS_STENCIL_OP_ZPASS = 19;\n/** @internal */ export const RS_COLOR_MASK = 20;\n/** @internal Offset from an ACTUAL slot (`0..20`) to its DESIRED twin (`21..41`). */\nexport const RS_DESIRED = 21;\n/* Standalone cached gl.clearColor RGBA slots (`42..45`) — NO desired twin; a\n * simple apply-on-clear cache like viewport/scissor, stored in `rs` (not as named\n * GLState fields) so the index access mangles small instead of shipping\n * `.clearColorR` verbatim in every bundle. */\n/** @internal */ export const RS_CLEAR_R = 42;\n/** @internal */ export const RS_CLEAR_G = 43;\n/** @internal */ export const RS_CLEAR_B = 44;\n/** @internal */ export const RS_CLEAR_A = 45;\n\n/**\n * GL-state cache type. Owned by `GLEngineContext._state`.\n *\n * Two flavours of cached state coexist here:\n *\n * - **Eager bindings** (program / buffers / textures / VAO / framebuffer /\n * viewport / scissor / unpack). Each binding setter issues its `gl.*` call\n * immediately and updates the matching field in lock-step, eliding the call\n * when the cache already matches.\n * - **Deferred render-state** (blend / depth / cull / stencil / color-mask),\n * stored in the {@link GLState.rs} index-array. These follow Babylon's\n * `applyStates()` model: each setter records only the DESIRED slot\n * (`rs[RS_X + RS_DESIRED]`) and sets `statesDirty`; the real `gl.*` calls are\n * flushed by {@link applyGLStates} (apply-states.ts) immediately before each\n * draw / clear, reconciling DESIRED → ACTUAL and writing the actual slots\n * (`rs[RS_X]`) in lock-step. Both halves keep their `-1`/`0` unset sentinels.\n *\n * See `00-lite-gl.md` §4 for the full table of cached operations and the\n * deferred-state flush sites.\n *\n * INVARIANTS:\n * - The cache is the source of truth. If consumers poke `engine.gl.*` directly\n * they will silently corrupt this state.\n * - On `webglcontextlost` the whole `rs` array (both the actual and desired\n * halves) is reset to its initial sentinels (handles are dead anyway;\n * subsequent setters bail out on `engine._isLost`, and a post-restore setter\n * re-marks `statesDirty`).\n */\nexport interface GLState {\n currentProgram: WebGLProgram | null;\n activeTextureUnit: number;\n /** Per-unit TEXTURE_2D binding; length === caps.maxTextureUnits. */\n boundTextures: (WebGLTexture | null)[];\n /** Per-unit TEXTURE_3D binding, allocated only when first used. @internal */\n _boundTextures3D?: (WebGLTexture | null | undefined)[];\n /** Cached zero WebGL2 unpack row/image/skip layout for 3D uploads. @internal */\n _unpack3DLayoutKnown?: boolean;\n boundArrayBuffer: WebGLBuffer | null;\n boundElementBuffer: WebGLBuffer | null;\n boundVao: WebGLVertexArrayObject | null;\n viewportX: number;\n viewportY: number;\n viewportW: number;\n viewportH: number;\n /**\n * Currently-bound draw framebuffer, or `null` for the default (canvas)\n * framebuffer. Owned by the render-target module's `bindRenderTarget`\n * (binding `null` returns to the canvas). Reset to `null` on context-lost.\n */\n boundFramebuffer: WebGLFramebuffer | null;\n /**\n * Deferred render-state (blend / depth / cull / stencil / color-mask) packed\n * into a flat `Float64Array(46)`. Slots `0..20` (indexed by the `RS_*`\n * consts) are the ACTUAL applied GL state — what {@link applyGLStates} last\n * wrote to the context; slots `21..41` (`rs[RS_X + RS_DESIRED]`) are the\n * DESIRED twin the setters record. The setters write ONLY the desired half\n * (never `gl.*`, never the actual half) and raise `statesDirty`;\n * `applyGLStates` reconciles each desired → its actual twin right before a\n * draw / clear, issuing only the GL calls that changed and updating the\n * actual half in lock-step. Both preset and arbitrary blend paths feed the\n * same desired slots, so they can never desync.\n *\n * Sentinels (identical for both halves): `-1` for the tri-state enables\n * (`RS_BLEND_ENABLED` / `RS_DEPTH_TEST` / `RS_DEPTH_MASK` / `RS_CULL_ENABLED`\n * / `RS_STENCIL_TEST`) and the mask caches (`RS_STENCIL_MASK` /\n * `RS_COLOR_MASK`), plus the leading stencil-op slot\n * (`RS_STENCIL_OP_FAIL`); `0` for every other func / equation / op / ref\n * slot. The leading op sentinel lets the first op\n * setter seed omitted fields to WebGL's `KEEP` defaults before merging. An\n * unset desired equals its unset actual and is never flushed; the `-1`\n * blend/test sentinels guarantee the first applied state is never elided.\n * The blend func/equation slots are only trusted while `RS_BLEND_ENABLED` is\n * `1` — the disabled→enabled transition re-issues both (matching Babylon's\n * `AlphaState`, which does not track them while blending is off).\n *\n * `setStencilOpSeparate` lazily replaces this array with a 52-slot copy; the\n * six appended slots cache actual and desired back-face operations without\n * moving any base index.\n *\n * Float64 (not Int32): `RS_STENCIL_MASK` / `RS_STENCIL_FUNC_MASK` can be\n * `0xFFFFFFFF`, which Int32 stores as `-1` — colliding with the `-1` unset\n * sentinel. Reset on context-lost. */\n rs: Float64Array;\n /** `true` when at least one deferred-state setter ran since the last\n * {@link applyGLStates}. Gates the flush so an unchanged frame issues no\n * reconciliation work. */\n statesDirty: boolean;\n /* ─── Deferred render-state appliers (per-category, lazily installed) ──────\n * Each category's reconciler (blend / depth+cull / stencil / color-mask) is\n * installed onto its slot the first time the matching setter runs — a runtime\n * assignment, NOT a module-level side effect. `applyGLStates` dispatches ONLY\n * through these slots, so the reconcilers (and their GL reconciliation code)\n * are reachable only when their setter is in the bundle: a scene that never\n * touches a category tree-shakes its reconciler out entirely (e.g. a clear-\n * only scene drops all four). Left undefined until installed; never cleared on\n * context-lost (a post-restore setter re-installs idempotently). */\n /** @internal Blend reconciler (Babylon's `_alphaState`). */\n _flushBlend?: (engine: GLEngineContext) => void;\n /** @internal Depth + cull reconciler (Babylon's `_depthCullingState`). */\n _flushDepthCull?: (engine: GLEngineContext) => void;\n /** @internal Stencil reconciler (Babylon's `_stencilState`). */\n _flushStencil?: (engine: GLEngineContext) => void;\n /** @internal Lazy hook that mirrors shared stencil operations to the back face. */\n _setStencilBack?: (cache: GLState, state: { opFail?: GLenum; opZFail?: GLenum; opZPass?: GLenum }) => void;\n /** @internal Color-write-mask reconciler (Babylon's `setColorWrite`). */\n _flushColorMask?: (engine: GLEngineContext) => void;\n /** Scissor-test enable tri-state (`-1` unset, `0` off, `1` on). */\n scissorEnabled: number;\n scissorX: number;\n scissorY: number;\n scissorW: number;\n scissorH: number;\n /** Cached `gl.pixelStorei(UNPACK_ALIGNMENT)`, or `-1` when unset. */\n unpackAlignment: number;\n /** Cached `gl.pixelStorei(UNPACK_FLIP_Y_WEBGL)`, or `-1` when unset. */\n unpackFlipY: number;\n /** Cached `gl.pixelStorei(UNPACK_PREMULTIPLY_ALPHA_WEBGL)`, or `-1` unset. */\n unpackPremultiplyAlpha: number;\n /**\n * Per-location vertex-attribute enable flags for the DEFAULT (null) VAO —\n * the mesh / instancing path (mirrors Babylon's `_vertexAttribArraysEnabled`).\n * Index is the attribute location. lite-gl's quad / sprite paths use their\n * own VAOs and do not touch this. Cleared on context-lost.\n */\n enabledAttribs: boolean[];\n /**\n * Attribute locations currently configured with a non-default vertex divisor\n * (instanced attributes), mirroring Babylon's `_currentInstanceLocations`.\n * Each location is recorded once, so repeated binds without an unbind stay bounded.\n * `unbindInstanceAttributes` resets each back to divisor 0 and clears this.\n */\n instanceLocations: number[];\n /** Shared fullscreen quad — lazily created on first `drawEffect`. */\n quadVbo: WebGLBuffer | null;\n quadIbo: WebGLBuffer | null;\n quadVao: WebGLVertexArrayObject | null;\n}\n\n/** Indices in `rs` whose unset sentinel is `-1` (the tri-state enables, the\n * `stencilMask` / `colorMask` caches, and the leading shared stencil-op slot).\n * Every other slot defaults to `0`. The sentinel is written to BOTH\n * the actual (`i`) and desired (`i + RS_DESIRED`) halves. Kept as a\n * function-local literal so it stays a runtime value (no module-level\n * allocation / side effect). */\nfunction applyRenderStateSentinels(rs: Float64Array): void {\n for (const i of [RS_BLEND_ENABLED, RS_DEPTH_TEST, RS_DEPTH_MASK, RS_CULL_ENABLED, RS_STENCIL_TEST, RS_STENCIL_MASK, RS_STENCIL_OP_FAIL, RS_COLOR_MASK]) {\n rs[i] = -1;\n rs[i + RS_DESIRED] = -1;\n }\n // clearColor RGBA (standalone, no DESIRED twin) — `-1` forces the first clear\n // to issue gl.clearColor (valid components are 0..1).\n rs[RS_CLEAR_R] = rs[RS_CLEAR_G] = rs[RS_CLEAR_B] = rs[RS_CLEAR_A] = -1;\n}\n\n/** Allocate the 46-slot deferred render-state array (21 actual + 21 desired + 4\n * standalone clearColor) initialised to its unset sentinels — a fresh\n * `Float64Array` is already all `0`, so only the `-1` slots need writing. */\nfunction createRenderStateArray(): Float64Array {\n const rs = new Float64Array(46);\n applyRenderStateSentinels(rs);\n return rs;\n}\n\n/** Re-initialise a live render-state array in place: zero every slot, then\n * restore the `-1` sentinels. */\nfunction resetRenderStateArray(rs: Float64Array): void {\n rs.fill(0);\n applyRenderStateSentinels(rs);\n}\n\n/** Allocate a fresh, fully-null GLState sized for `maxTextureUnits`. */\nexport function createGLState(maxTextureUnits: number): GLState {\n return {\n currentProgram: null,\n activeTextureUnit: 0,\n boundTextures: new Array<WebGLTexture | null>(maxTextureUnits).fill(null),\n boundArrayBuffer: null,\n boundElementBuffer: null,\n boundVao: null,\n viewportX: 0,\n viewportY: 0,\n viewportW: 0,\n viewportH: 0,\n boundFramebuffer: null,\n rs: createRenderStateArray(),\n statesDirty: false,\n scissorEnabled: -1,\n scissorX: 0,\n scissorY: 0,\n scissorW: 0,\n scissorH: 0,\n unpackAlignment: -1,\n unpackFlipY: -1,\n unpackPremultiplyAlpha: -1,\n enabledAttribs: [],\n instanceLocations: [],\n quadVbo: null,\n quadIbo: null,\n quadVao: null,\n };\n}\n\n/** Reset only the cached \"current GL state\" — every binding (program / buffers /\n * textures / VAO / framebuffer) and render-state (blend / depth / stencil /\n * scissor / color-mask / viewport / unpack) field, including the whole `rs`\n * deferred render-state array (BOTH the actual applied values and the DESIRED\n * twins) plus `statesDirty` — to its unset sentinel, WITHOUT discarding owned\n * GPU resources (the shared quad). After this, the next setter in each category\n * is re-issued rather than elided.\n *\n * Used by `resetGLState` (context-lost) and by `wipeGLStateCache` (a host that\n * shares the GL context calling in after mutating raw `gl.*` state). The shared\n * quad's GL objects are still alive in the latter case, so they are preserved\n * here to avoid leaking + needlessly rebuilding them every render scope. */\nexport function resetGLStateCache(state: GLState): void {\n state.currentProgram = null;\n state.activeTextureUnit = 0;\n state.boundTextures.fill(null);\n state.boundArrayBuffer = null;\n state.boundElementBuffer = null;\n state.boundVao = null;\n state.viewportX = 0;\n state.viewportY = 0;\n state.viewportW = 0;\n state.viewportH = 0;\n state.boundFramebuffer = null;\n resetRenderStateArray(state.rs);\n state.statesDirty = false;\n state.scissorEnabled = -1;\n state.scissorX = 0;\n state.scissorY = 0;\n state.scissorW = 0;\n state.scissorH = 0;\n state.unpackAlignment = -1;\n state.unpackFlipY = -1;\n state.unpackPremultiplyAlpha = -1;\n state.enabledAttribs.length = 0;\n state.instanceLocations.length = 0;\n}\n\n/** Zero the cache in-place. Used by the context-lost handler — GL handles are\n * already dead per WebGL spec; we forget what we knew about them (including the\n * shared quad, whose GL objects are gone and must be rebuilt) so the next\n * bind/use after restore is NOT incorrectly elided. */\nexport function resetGLState(state: GLState): void {\n resetGLStateCache(state);\n state.quadVbo = null;\n state.quadIbo = null;\n state.quadVao = null;\n}\n"]}
1
+ {"version":3,"file":"state.js","sourceRoot":"","sources":["../src/state.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;kFAekF;AAClF,gBAAgB,CAAC,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,CAAC;AACnD,gBAAgB,CAAC,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,CAAC;AACnD,gBAAgB,CAAC,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,CAAC;AACnD,gBAAgB,CAAC,MAAM,CAAC,MAAM,cAAc,GAAG,CAAC,CAAC;AACjD,gBAAgB,CAAC,MAAM,CAAC,MAAM,cAAc,GAAG,CAAC,CAAC;AACjD,gBAAgB,CAAC,MAAM,CAAC,MAAM,eAAe,GAAG,CAAC,CAAC;AAClD,gBAAgB,CAAC,MAAM,CAAC,MAAM,aAAa,GAAG,CAAC,CAAC;AAChD,gBAAgB,CAAC,MAAM,CAAC,MAAM,aAAa,GAAG,CAAC,CAAC;AAChD,gBAAgB,CAAC,MAAM,CAAC,MAAM,aAAa,GAAG,CAAC,CAAC;AAChD,gBAAgB,CAAC,MAAM,CAAC,MAAM,aAAa,GAAG,CAAC,CAAC;AAChD,gBAAgB,CAAC,MAAM,CAAC,MAAM,eAAe,GAAG,EAAE,CAAC;AACnD,gBAAgB,CAAC,MAAM,CAAC,MAAM,YAAY,GAAG,EAAE,CAAC;AAChD,gBAAgB,CAAC,MAAM,CAAC,MAAM,eAAe,GAAG,E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,IAAI,CAAC;IACrB,KAAK,CAAC,OAAO,GAAG,IAAI,CAAC;AACzB,CAAC","sourcesContent":["import type { GLEngineContext } from \"./context.js\";\n\n/* ─── Deferred render-state index-array layout ────────────────────────────────\n * The deferred render-state (blend / depth / cull / stencil / color-mask) lives\n * in a flat `Float64Array(46)` on `GLState.rs`: slots `0..20` hold the ACTUAL\n * applied GL state, slots `21..41` (`RS_X + RS_DESIRED`) the DESIRED twin, and\n * slots `42..45` the standalone (no-desired-twin) cached `gl.clearColor` RGBA.\n * `setStencilOpSeparate` lazily expands it to 52 slots for back-face operations.\n *\n * These `@internal` index consts are imported by blend.ts / depth-stencil.ts /\n * apply-states.ts. Because they are plain `const` integers, esbuild inlines each\n * to a 1–2 char literal (`rs[RS_BLEND_SRC_RGB + RS_DESIRED]` → `rs[22]`) when\n * bundling a scene — far smaller than the old cross-module `.dBlendSrcRGB` named\n * props, which could not be mangled and shipped verbatim in every bundle.\n *\n * Float64Array (NOT Int32Array) is required: `RS_STENCIL_MASK` /\n * `RS_STENCIL_FUNC_MASK` can be `0xFFFFFFFF`, which Int32 would store as `-1` and\n * collide with the `-1` \"unset\" sentinel; Float64 keeps `4294967295` distinct. */\n/** @internal */ export const RS_BLEND_ENABLED = 0;\n/** @internal */ export const RS_BLEND_SRC_RGB = 1;\n/** @internal */ export const RS_BLEND_DST_RGB = 2;\n/** @internal */ export const RS_BLEND_SRC_A = 3;\n/** @internal */ export const RS_BLEND_DST_A = 4;\n/** @internal */ export const RS_BLEND_EQ_RGB = 5;\n/** @internal */ export const RS_BLEND_EQ_A = 6;\n/** @internal */ export const RS_DEPTH_TEST = 7;\n/** @internal */ export const RS_DEPTH_MASK = 8;\n/** @internal */ export const RS_DEPTH_FUNC = 9;\n/** @internal */ export const RS_CULL_ENABLED = 10;\n/** @internal */ export const RS_CULL_FACE = 11;\n/** @internal */ export const RS_STENCIL_TEST = 12;\n/** @internal */ export const RS_STENCIL_MASK = 13;\n/** @internal */ export const RS_STENCIL_FUNC_FUNC = 14;\n/** @internal */ export const RS_STENCIL_FUNC_REF = 15;\n/** @internal */ export const RS_STENCIL_FUNC_MASK = 16;\n/** @internal */ export const RS_STENCIL_OP_FAIL = 17;\n/** @internal */ export const RS_STENCIL_OP_ZFAIL = 18;\n/** @internal */ export const RS_STENCIL_OP_ZPASS = 19;\n/** @internal */ export const RS_COLOR_MASK = 20;\n/** @internal Offset from an ACTUAL slot (`0..20`) to its DESIRED twin (`21..41`). */\nexport const RS_DESIRED = 21;\n/* Standalone cached gl.clearColor RGBA slots (`42..45`) — NO desired twin; a\n * simple apply-on-clear cache like viewport/scissor, stored in `rs` (not as named\n * GLState fields) so the index access mangles small instead of shipping\n * `.clearColorR` verbatim in every bundle. */\n/** @internal */ export const RS_CLEAR_R = 42;\n/** @internal */ export const RS_CLEAR_G = 43;\n/** @internal */ export const RS_CLEAR_B = 44;\n/** @internal */ export const RS_CLEAR_A = 45;\n\n/**\n * GL-state cache type. Owned by `GLEngineContext._state`.\n *\n * Two flavours of cached state coexist here:\n *\n * - **Eager bindings** (program / buffers / textures / VAO / framebuffer /\n * viewport / scissor / unpack). Each binding setter issues its `gl.*` call\n * immediately and updates the matching field in lock-step, eliding the call\n * when the cache already matches.\n * - **Deferred render-state** (blend / depth / cull / stencil / color-mask),\n * stored in the {@link GLState.rs} index-array. These follow Babylon's\n * `applyStates()` model: each setter records only the DESIRED slot\n * (`rs[RS_X + RS_DESIRED]`) and sets `statesDirty`; the real `gl.*` calls are\n * flushed by {@link applyGLStates} (apply-states.ts) immediately before each\n * draw / clear, reconciling DESIRED → ACTUAL and writing the actual slots\n * (`rs[RS_X]`) in lock-step. Both halves keep their `-1`/`0` unset sentinels.\n *\n * See `00-lite-gl.md` §4 for the full table of cached operations and the\n * deferred-state flush sites.\n *\n * INVARIANTS:\n * - The cache is the source of truth. If consumers poke `engine.gl.*` directly\n * they will silently corrupt this state.\n * - On `webglcontextlost` the whole `rs` array (both the actual and desired\n * halves) is reset to its initial sentinels (handles are dead anyway;\n * subsequent setters bail out on `engine._isLost`, and a post-restore setter\n * re-marks `statesDirty`).\n */\nexport interface GLState {\n currentProgram: WebGLProgram | null;\n /** Active texture unit, or -1 when unknown. */\n activeTextureUnit: number;\n /** Default-VAO pointer format/stride/offset/divisor quadruples\n * (`MAX_VERTEX_ATTRIBS * 4`), allocated once on first bindAttributesCached.\n * Buffer identity and enable state live together in enabledAttribs. @internal */\n _attributePointers?: Float64Array;\n /** Per-unit TEXTURE_2D binding; undefined = unknown, null = confirmed unbound.\n * Length === caps.maxTextureUnits. */\n boundTextures: (WebGLTexture | null | undefined)[];\n /** Per-unit TEXTURE_3D binding, allocated only when first used. @internal */\n _boundTextures3D?: (WebGLTexture | null | undefined)[];\n /** Cached zero WebGL2 unpack row/image/skip layout for 3D uploads. @internal */\n _unpack3DLayoutKnown?: boolean;\n boundArrayBuffer: WebGLBuffer | null;\n boundElementBuffer: WebGLBuffer | null;\n /** Bound VAO; `null` = the default VAO, `undefined` = unknown (fresh or wiped\n * cache, context loss), so the next VAO bind is always issued. */\n boundVao: WebGLVertexArrayObject | null | undefined;\n viewportX: number;\n viewportY: number;\n viewportW: number;\n viewportH: number;\n /**\n * Currently-bound draw framebuffer, `null` for the default (canvas)\n * framebuffer, or `undefined` when unknown (fresh or wiped cache — the\n * context may be shared with a host that left its own framebuffer bound).\n * Owned by the render-target module's `bindRenderTarget` (binding `null`\n * returns to the canvas). Reset to `undefined` by `wipeGLStateCache` and on\n * context loss.\n */\n boundFramebuffer: WebGLFramebuffer | null | undefined;\n /**\n * Deferred render-state (blend / depth / cull / stencil / color-mask) packed\n * into a flat `Float64Array(46)`. Slots `0..20` (indexed by the `RS_*`\n * consts) are the ACTUAL applied GL state — what {@link applyGLStates} last\n * wrote to the context; slots `21..41` (`rs[RS_X + RS_DESIRED]`) are the\n * DESIRED twin the setters record. The setters write ONLY the desired half\n * (never `gl.*`, never the actual half) and raise `statesDirty`;\n * `applyGLStates` reconciles each desired → its actual twin right before a\n * draw / clear, issuing only the GL calls that changed and updating the\n * actual half in lock-step. Both preset and arbitrary blend paths feed the\n * same desired slots, so they can never desync.\n *\n * Sentinels (identical for both halves): `-1` for the tri-state enables\n * (`RS_BLEND_ENABLED` / `RS_DEPTH_TEST` / `RS_DEPTH_MASK` / `RS_CULL_ENABLED`\n * / `RS_STENCIL_TEST`) and the mask caches (`RS_STENCIL_MASK` /\n * `RS_COLOR_MASK`), plus the leading stencil-op slot\n * (`RS_STENCIL_OP_FAIL`); `0` for every other func / equation / op / ref\n * slot. The leading op sentinel lets the first op\n * setter seed omitted fields to WebGL's `KEEP` defaults before merging. An\n * unset desired equals its unset actual and is never flushed; the `-1`\n * blend/test sentinels guarantee the first applied state is never elided.\n * The blend func/equation slots are only trusted while `RS_BLEND_ENABLED` is\n * `1` — the disabled→enabled transition re-issues both (matching Babylon's\n * `AlphaState`, which does not track them while blending is off).\n *\n * `setStencilOpSeparate` lazily replaces this array with a 52-slot copy; the\n * six appended slots cache actual and desired back-face operations without\n * moving any base index.\n *\n * Float64 (not Int32): `RS_STENCIL_MASK` / `RS_STENCIL_FUNC_MASK` can be\n * `0xFFFFFFFF`, which Int32 stores as `-1` — colliding with the `-1` unset\n * sentinel. Reset on context-lost. */\n rs: Float64Array;\n /** `true` when at least one deferred-state setter ran since the last\n * {@link applyGLStates}. Gates the flush so an unchanged frame issues no\n * reconciliation work. */\n statesDirty: boolean;\n /* ─── Deferred render-state appliers (per-category, lazily installed) ──────\n * Each category's reconciler (blend / depth+cull / stencil / color-mask) is\n * installed onto its slot the first time the matching setter runs — a runtime\n * assignment, NOT a module-level side effect. `applyGLStates` dispatches ONLY\n * through these slots, so the reconcilers (and their GL reconciliation code)\n * are reachable only when their setter is in the bundle: a scene that never\n * touches a category tree-shakes its reconciler out entirely (e.g. a clear-\n * only scene drops all four). Left undefined until installed; never cleared on\n * context-lost (a post-restore setter re-installs idempotently). */\n /** @internal Blend reconciler (Babylon's `_alphaState`). */\n _flushBlend?: (engine: GLEngineContext) => void;\n /** @internal Depth + cull reconciler (Babylon's `_depthCullingState`). */\n _flushDepthCull?: (engine: GLEngineContext) => void;\n /** @internal Stencil reconciler (Babylon's `_stencilState`). */\n _flushStencil?: (engine: GLEngineContext) => void;\n /** @internal Lazy hook that mirrors shared stencil operations to the back face. */\n _setStencilBack?: (cache: GLState, state: { opFail?: GLenum; opZFail?: GLenum; opZPass?: GLenum }) => void;\n /** @internal Color-write-mask reconciler (Babylon's `setColorWrite`). */\n _flushColorMask?: (engine: GLEngineContext) => void;\n /** Scissor-test enable tri-state (`-1` unset, `0` off, `1` on). */\n scissorEnabled: number;\n /** Cached scissor rectangle; a `scissorW` of `-1` marks it unknown. */\n scissorX: number;\n scissorY: number;\n scissorW: number;\n scissorH: number;\n /** Cached `gl.pixelStorei(UNPACK_ALIGNMENT)`, or `-1` when unset. */\n unpackAlignment: number;\n /** Cached `gl.pixelStorei(UNPACK_FLIP_Y_WEBGL)`, or `-1` when unset. */\n unpackFlipY: number;\n /** Cached `gl.pixelStorei(UNPACK_PREMULTIPLY_ALPHA_WEBGL)`, or `-1` unset. */\n unpackPremultiplyAlpha: number;\n /**\n * Per-location vertex-attribute bindings for the DEFAULT (null) VAO —\n * the mesh / instancing path (mirrors Babylon's `_vertexAttribArraysEnabled`).\n * A buffer handle means enabled with that pointer; true means enabled with\n * an invalidated pointer; null means confirmed disabled; undefined means\n * disabled — or unknown while `_unknownAttribs` is set. Index is the\n * attribute location. Cleared on context loss or cache wipe.\n */\n enabledAttribs: (WebGLBuffer | true | null)[];\n /** Set by a plain (non-brute-force) cache wipe: unrecorded default-VAO\n * attribute slots may have been enabled by the host, so disables must not\n * elide them until `unbindAllAttributes` normalizes every slot. @internal */\n _unknownAttribs?: boolean;\n /**\n * Attribute locations currently configured with a non-default vertex divisor\n * (instanced attributes), mirroring Babylon's `_currentInstanceLocations`.\n * Each location is recorded once, so repeated binds without an unbind stay bounded.\n * `unbindInstanceAttributes` resets each back to divisor 0 and clears this.\n */\n instanceLocations: number[];\n /** Shared fullscreen quad — lazily created on first `drawEffect`. */\n quadVbo: WebGLBuffer | null;\n quadIbo: WebGLBuffer | null;\n quadVao: WebGLVertexArrayObject | null;\n}\n\n/** Indices in `rs` whose unset sentinel is `-1` (the tri-state enables, the\n * `stencilMask` / `colorMask` caches, and the leading shared stencil-op slot).\n * Every other slot defaults to `0`. The sentinel is written to BOTH\n * the actual (`i`) and desired (`i + RS_DESIRED`) halves. Kept as a\n * function-local literal so it stays a runtime value (no module-level\n * allocation / side effect). */\nfunction applyRenderStateSentinels(rs: Float64Array): void {\n for (const i of [RS_BLEND_ENABLED, RS_DEPTH_TEST, RS_DEPTH_MASK, RS_CULL_ENABLED, RS_STENCIL_TEST, RS_STENCIL_MASK, RS_STENCIL_OP_FAIL, RS_COLOR_MASK]) {\n rs[i] = -1;\n rs[i + RS_DESIRED] = -1;\n }\n // clearColor RGBA (standalone, no DESIRED twin) — `-1` forces the first clear\n // to issue gl.clearColor (valid components are 0..1).\n rs[RS_CLEAR_R] = rs[RS_CLEAR_G] = rs[RS_CLEAR_B] = rs[RS_CLEAR_A] = -1;\n}\n\n/** Allocate the 46-slot deferred render-state array (21 actual + 21 desired + 4\n * standalone clearColor) initialised to its unset sentinels — a fresh\n * `Float64Array` is already all `0`, so only the `-1` slots need writing. */\nfunction createRenderStateArray(): Float64Array {\n const rs = new Float64Array(46);\n applyRenderStateSentinels(rs);\n return rs;\n}\n\n/** Re-initialise a live render-state array in place: zero every slot, then\n * restore the `-1` sentinels. */\nfunction resetRenderStateArray(rs: Float64Array): void {\n rs.fill(0);\n applyRenderStateSentinels(rs);\n}\n\n/** Allocate a fresh GLState with unknown texture, VAO and framebuffer bindings\n * (the canvas context may already be in use by a host), sized for `maxTextureUnits`. */\nexport function createGLState(maxTextureUnits: number): GLState {\n return {\n currentProgram: null,\n activeTextureUnit: -1,\n boundTextures: new Array<WebGLTexture | null | undefined>(maxTextureUnits),\n boundArrayBuffer: null,\n boundElementBuffer: null,\n boundVao: undefined,\n viewportX: 0,\n viewportY: 0,\n viewportW: 0,\n viewportH: 0,\n boundFramebuffer: undefined,\n rs: createRenderStateArray(),\n statesDirty: false,\n scissorEnabled: -1,\n scissorX: 0,\n scissorY: 0,\n scissorW: -1,\n scissorH: 0,\n unpackAlignment: -1,\n unpackFlipY: -1,\n unpackPremultiplyAlpha: -1,\n enabledAttribs: [],\n instanceLocations: [],\n quadVbo: null,\n quadIbo: null,\n quadVao: null,\n };\n}\n\n/** Reset only the cached \"current GL state\" — every binding (program / buffers /\n * textures / VAO / framebuffer) and render-state (blend / depth / stencil /\n * scissor / color-mask / viewport / unpack) field, including the whole `rs`\n * deferred render-state array (BOTH the actual applied values and the DESIRED\n * twins) plus `statesDirty` — to its unset sentinel, WITHOUT discarding owned\n * GPU resources (the shared quad). After this, the next setter in each category\n * is re-issued rather than elided. The VAO and framebuffer bindings become\n * `undefined` (unknown), NOT `null`: `null` is a real binding (default VAO /\n * canvas) and would elide the rebind while the host's object is still bound.\n *\n * Used by `resetGLState` (context-lost) and by `wipeGLStateCache` (a host that\n * shares the GL context calling in after mutating raw `gl.*` state). The shared\n * quad's GL objects are still alive in the latter case, so they are preserved\n * here to avoid leaking + needlessly rebuilding them every render scope. */\nexport function resetGLStateCache(state: GLState): void {\n state.currentProgram = null;\n state.activeTextureUnit = -1;\n state.boundTextures.fill(undefined);\n state.boundArrayBuffer = null;\n state.boundElementBuffer = null;\n state.boundVao = undefined;\n state.viewportX = 0;\n state.viewportY = 0;\n state.viewportW = 0;\n state.viewportH = 0;\n state.boundFramebuffer = undefined;\n resetRenderStateArray(state.rs);\n state.statesDirty = false;\n state.scissorEnabled = -1;\n state.scissorW = -1;\n state.unpackAlignment = -1;\n state.unpackFlipY = -1;\n state.unpackPremultiplyAlpha = -1;\n state.enabledAttribs.length = 0;\n state.instanceLocations.length = 0;\n}\n\n/** Zero the cache in-place. Used by the context-lost handler — GL handles are\n * already dead per WebGL spec; we forget what we knew about them (including the\n * shared quad, whose GL objects are gone and must be rebuilt) so the next\n * bind/use after restore is NOT incorrectly elided. */\nexport function resetGLState(state: GLState): void {\n resetGLStateCache(state);\n state.quadVbo = null;\n state.quadIbo = null;\n state.quadVao = null;\n}\n"]}
@@ -26,7 +26,7 @@ export function ensureTextDataGpu(engine, data) {
26
26
  throw error;
27
27
  }
28
28
  }
29
- else if (gpu._instanceBuf._data !== data._instances) {
29
+ else if (gpu._instanceBuf.byteLength !== data._instances.byteLength) {
30
30
  // Retain the live CPU pool, including partial edits, for context restoration.
31
31
  const buffer = createVertexBuffer(engine, data._instances, true);
32
32
  disposeBuffer(gpu._instanceBuf);
@@ -1 +1 @@
1
- {"version":3,"file":"text-instances.js","sourceRoot":"","sources":["../../../src/text/_gpu/text-instances.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAEtF,OAAO,EAAE,mBAAmB,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAC/F,OAAO,EAAE,iBAAiB,EAAE,SAAS,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAElG,uFAAuF;AACvF,MAAM,UAAU,iBAAiB,CAAC,MAAuB,EAAE,IAAgB;IACvE,IAAI,GAAG,GAAG,IAAI,CAAC,IAAI,CAAC;IACpB,IAAI,GAAG,IAAI,GAAG,CAAC,OAAO,KAAK,MAAM,EAAE,CAAC;QAChC,MAAM,IAAI,KAAK,CAAC,oGAAoG,CAAC,CAAC;IAC1H,CAAC;IACD,IAAI,CAAC,GAAG,EAAE,CAAC;QACP,MAAM,MAAM,GAAG,SAAS,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,WAAW,GAAG,iBAAiB,CAAC,CAAC;QAC7E,MAAM,MAAM,GAAG,kBAAkB,CAAC,MAAM,EAAE,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;QACjE,IAAI,CAAC;YACD,GAAG,G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C,UAAU,CAAC,QAAQ,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;YACtH,kBAAkB,CAAC,GAAG,CAAC,YAAY,EAAE,MAAM,EAAE,IAAI,CAAC,WAAW,GAAG,mBAAmB,CAAC,CAAC;QACzF,CAAC;aAAM,CAAC;YACJ,kBAAkB,CAAC,GAAG,CAAC,YAAY,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC;QAC1D,CAAC;QACD,GAAG,CAAC,gBAAgB,GAAG,IAAI,CAAC,QAAQ,CAAC;IACzC,CAAC;IACD,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC,SAAS,GAAG,CAAC,CAAC;IACtC,IAAI,GAAG,CAAC,qBAAqB,KAAK,IAAI,CAAC,aAAa,EAAE,CAAC;QACnD,MAAM,MAAM,GAAG,SAAS,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,WAAW,GAAG,iBAAiB,EAAE,GAAG,CAAC,YAAY,CAAC,CAAC;QAC/F,iBAAiB,CAAC,MAAM,EAAE,GAAG,CAAC,SAAS,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,CAAC,MAAM,GAAG,CAAC,WAAW,GAAG,CAAC,CAAC,CAAC,CAAC;QACjG,GAAG,CAAC,YAAY,GAAG,MAAM,CAAC;QAC1B,GAAG,CAAC,qBAAqB,GAAG,IAAI,CAAC,aAAa,CAAC;IACnD,CAAC;IACD,OAAO,GAAG,CAAC;AACf,CAAC","sourcesContent":["import type { GLEngineContext } from \"../../context.js\";\nimport { createVertexBuffer, disposeBuffer, updateVertexBuffer } from \"../../mesh.js\";\nimport type { GLTextData, TextDataGpu } from \"../text-data.js\";\nimport { TEXT_INSTANCE_BYTES, TEXT_INSTANCE_FLOATS, TEXT_STYLE_FLOATS } from \"../text-data.js\";\nimport { createTextTexture, packTable, TABLE_WIDTH, uploadTextTexture } from \"./text-textures.js\";\n\n/** @internal One upload per data mutation, even when several layers share the data. */\nexport function ensureTextDataGpu(engine: GLEngineContext, data: GLTextData): TextDataGpu {\n let gpu = data._gpu;\n if (gpu && gpu._engine !== engine) {\n throw new Error(\"lite-gl: text data cannot be drawn on multiple engines. Create separate text data for each engine.\");\n }\n if (!gpu) {\n const pixels = packTable(data._styles, data._styleCount * TEXT_STYLE_FLOATS);\n const buffer = createVertexBuffer(engine, data._instances, true);\n try {\n gpu = {\n _engine: engine,\n _instanceBuf: buffer,\n _styleTex: createTextTexture(engine, pixels, TABLE_WIDTH, pixels.length / (TABLE_WIDTH * 4)),\n _stylePixels: pixels,\n _uploadedVersion: data._version,\n _uploadedStyleVersion: data._styleVersion,\n };\n data._gpu = gpu;\n } catch (error) {\n disposeBuffer(buffer);\n throw error;\n }\n } else if (gpu._instanceBuf._data !== data._instances) {\n // Retain the live CPU pool, including partial edits, for context restoration.\n const buffer = createVertexBuffer(engine, data._instances, true);\n disposeBuffer(gpu._instanceBuf);\n gpu._instanceBuf = buffer;\n gpu._uploadedVersion = data._version;\n } else if (gpu._uploadedVersion !== data._version) {\n if (data._dirtyEnd > data._dirtyStart) {\n const start = data._dirtyStart * TEXT_INSTANCE_FLOATS;\n const end = data._dirtyEnd * TEXT_INSTANCE_FLOATS;\n const source = start === 0 && end === data._instances.length ? data._instances : data._instances.subarray(start, end);\n updateVertexBuffer(gpu._instanceBuf, source, data._dirtyStart * TEXT_INSTANCE_BYTES);\n } else {\n updateVertexBuffer(gpu._instanceBuf, data._instances);\n }\n gpu._uploadedVersion = data._version;\n }\n data._dirtyStart = data._dirtyEnd = 0;\n if (gpu._uploadedStyleVersion !== data._styleVersion) {\n const pixels = packTable(data._styles, data._styleCount * TEXT_STYLE_FLOATS, gpu._stylePixels);\n uploadTextTexture(engine, gpu._styleTex, pixels, TABLE_WIDTH, pixels.length / (TABLE_WIDTH * 4));\n gpu._stylePixels = pixels;\n gpu._uploadedStyleVersion = data._styleVersion;\n }\n return gpu;\n}\n"]}
1
+ {"version":3,"file":"text-instances.js","sourceRoot":"","sources":["../../../src/text/_gpu/text-instances.ts"],"names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AAC,aAAa,EAAE,CAAC;QACnD,MAAM,MAAM,GAAG,SAAS,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,WAAW,GAAG,iBAAiB,EAAE,GAAG,CAAC,YAAY,CAAC,CAAC;QAC/F,iBAAiB,CAAC,MAAM,EAAE,GAAG,CAAC,SAAS,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,CAAC,MAAM,GAAG,CAAC,WAAW,GAAG,CAAC,CAAC,CAAC,CAAC;QACjG,GAAG,CAAC,YAAY,GAAG,MAAM,CAAC;QAC1B,GAAG,CAAC,qBAAqB,GAAG,IAAI,CAAC,aAAa,CAAC;IACnD,CAAC;IACD,OAAO,GAAG,CAAC;AACf,CAAC","sourcesContent":["import type { GLEngineContext } from \"../../context.js\";\nimport { createVertexBuffer, disposeBuffer, updateVertexBuffer } from \"../../mesh.js\";\nimport type { GLTextData, TextDataGpu } from \"../text-data.js\";\nimport { TEXT_INSTANCE_BYTES, TEXT_INSTANCE_FLOATS, TEXT_STYLE_FLOATS } from \"../text-data.js\";\nimport { createTextTexture, packTable, TABLE_WIDTH, uploadTextTexture } from \"./text-textures.js\";\n\n/** @internal One upload per data mutation, even when several layers share the data. */\nexport function ensureTextDataGpu(engine: GLEngineContext, data: GLTextData): TextDataGpu {\n let gpu = data._gpu;\n if (gpu && gpu._engine !== engine) {\n throw new Error(\"lite-gl: text data cannot be drawn on multiple engines. Create separate text data for each engine.\");\n }\n if (!gpu) {\n const pixels = packTable(data._styles, data._styleCount * TEXT_STYLE_FLOATS);\n const buffer = createVertexBuffer(engine, data._instances, true);\n try {\n gpu = {\n _engine: engine,\n _instanceBuf: buffer,\n _styleTex: createTextTexture(engine, pixels, TABLE_WIDTH, pixels.length / (TABLE_WIDTH * 4)),\n _stylePixels: pixels,\n _uploadedVersion: data._version,\n _uploadedStyleVersion: data._styleVersion,\n };\n data._gpu = gpu;\n } catch (error) {\n disposeBuffer(buffer);\n throw error;\n }\n } else if (gpu._instanceBuf.byteLength !== data._instances.byteLength) {\n // Retain the live CPU pool, including partial edits, for context restoration.\n const buffer = createVertexBuffer(engine, data._instances, true);\n disposeBuffer(gpu._instanceBuf);\n gpu._instanceBuf = buffer;\n gpu._uploadedVersion = data._version;\n } else if (gpu._uploadedVersion !== data._version) {\n if (data._dirtyEnd > data._dirtyStart) {\n const start = data._dirtyStart * TEXT_INSTANCE_FLOATS;\n const end = data._dirtyEnd * TEXT_INSTANCE_FLOATS;\n const source = start === 0 && end === data._instances.length ? data._instances : data._instances.subarray(start, end);\n updateVertexBuffer(gpu._instanceBuf, source, data._dirtyStart * TEXT_INSTANCE_BYTES);\n } else {\n updateVertexBuffer(gpu._instanceBuf, data._instances);\n }\n gpu._uploadedVersion = data._version;\n }\n data._dirtyStart = data._dirtyEnd = 0;\n if (gpu._uploadedStyleVersion !== data._styleVersion) {\n const pixels = packTable(data._styles, data._styleCount * TEXT_STYLE_FLOATS, gpu._stylePixels);\n uploadTextTexture(engine, gpu._styleTex, pixels, TABLE_WIDTH, pixels.length / (TABLE_WIDTH * 4));\n gpu._stylePixels = pixels;\n gpu._uploadedStyleVersion = data._styleVersion;\n }\n return gpu;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"text-renderer.js","sourceRoot":"","sources":["../../src/text/text-renderer.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAC9D,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAC9E,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAE/D,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC1D,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAE7F,OAAO,EAAE,WAA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,CAAC,CAAC;QACnD,QAAQ,CAAC,OAAO,GAAG,IAAI,CAAC;IAC5B,CAAC;AACL,CAAC;AAED,oFAAoF;AACpF,MAAM,UAAU,mBAAmB,CAAC,QAAwB;IACxD,IAAI,QAAQ,CAAC,SAAS,EAAE,CAAC;QACrB,OAAO;IACX,CAAC;IACD,sBAAsB,CAAC,QAAQ,CAAC,CAAC;IACjC,QAAQ,CAAC,SAAS,GAAG,IAAI,CAAC;IAC1B,MAAM,MAAM,GAAG,QAAQ,CAAC,OAAO,CAAC;IAChC,cAAc,CAAC,MAAM,EAAE,QAAQ,CAAC,OAAO,CAAC,CAAC;IACzC,KAAK,MAAM,KAAK,IAAI,QAAQ,CAAC,UAAU,CAAC,MAAM,EAAE,EAAE,CAAC;QAC/C,KAAK,MAAM,GAAG,IAAI,KAAK,CAAC,KAAK,EAAE,CAAC;YAC5B,IAAI,GAAG,EAAE,CAAC;gBACN,cAAc,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;YAChC,CAAC;QACL,CAAC;IACL,CAAC;IACD,QAAQ,CAAC,UAAU,CAAC,KAAK,EAAE,CAAC;IAC5B,aAAa,CAAC,QAAQ,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IACtC,IAAI,QAAQ,CAAC,QAAQ,EAAE,CAAC;QACpB,aAAa,CAAC,QAAQ,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;IAC7C,CAAC;IACD,aAAa,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;IAC9B,QAAQ,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC;AAChC,CAAC","sourcesContent":["import type { GLEngineContext } from \"../context.js\";\nimport { offContextLost, onContextLost } from \"../context.js\";\nimport { disposeEffect, isEffectReady, setEffectTexture } from \"../effect.js\";\nimport { createVertexBuffer, disposeBuffer } from \"../mesh.js\";\nimport type { GLVertexBuffer } from \"../mesh.js\";\nimport { disableBlend, setBlendState } from \"../blend.js\";\nimport { applyGLStates } from \"../apply-states.js\";\nimport { clearEngine, setColorMask, setCullState, setDepthState } from \"../depth-stencil.js\";\nimport type { GLClearOptions } from \"../depth-stencil.js\";\nimport { setViewport } from \"../effect-renderer.js\";\nimport type { GLViewport } from \"../effect-renderer.js\";\nimport { runRenderLoop, stopRenderLoop } from \"../render-loop.js\";\nimport type { GLTextData } from \"./text-data.js\";\nimport { ensureSharedAtlasGpu } from \"./_gpu/text-textures.js\";\nimport { ensureTextDataGpu } from \"./_gpu/text-instances.js\";\nimport { _createTextVariant, createTextProgram, uploadTextUniforms } from \"./_gpu/text-effect.js\";\nimport type { TextProgram } from \"./_gpu/text-effect.js\";\nimport { bindTextVao, disposeTextVao } from \"./_gpu/text-vao.js\";\nimport type { TextVao } from \"./_gpu/text-vao.js\";\n\n/** Pixel-space placement and compositing of one text block. */\nexport interface GLTextLayerOptions {\n readonly positionPx?: { readonly x: number; readonly y: number };\n readonly rotationRad?: number;\n readonly scale?: number;\n readonly order?: number;\n readonly opacity?: number;\n /** Raises analytic coverage to 1/gamma. Default 1; values above 1 darken edges. */\n readonly coverageGamma?: number;\n readonly visible?: boolean;\n}\n\n/** Mutable placement of borrowed text data. Positions are in target pixels, not CSS pixels. */\nexport interface GLTextLayer {\n readonly data: GLTextData;\n positionPx: { x: number; y: number };\n rotationRad: number;\n scale: number;\n order: number;\n opacity: number;\n coverageGamma: number;\n visible: boolean;\n}\n\n/** Create a pure-data layer; rendering does not transfer ownership of its text data. */\nexport function createTextLayer(data: GLTextData, options?: GLTextLayerOptions): GLTextLayer {\n return {\n data,\n positionPx: { x: options?.positionPx?.x ?? 0, y: options?.positionPx?.y ?? 0 },\n rotationRad: options?.rotationRad ?? 0,\n scale: options?.scale ?? 1,\n order: options?.order ?? 0,\n opacity: options?.opacity ?? 1,\n coverageGamma: options?.coverageGamma ?? 1,\n visible: options?.visible ?? true,\n };\n}\n\n/** Set the layer's baseline origin in target pixels. */\nexport function setTextLayerPosition(layer: GLTextLayer, x: number, y: number): void {\n layer.positionPx.x = x;\n layer.positionPx.y = y;\n}\n\n/** Options for drawing text to the currently bound canvas or render target. */\nexport interface GLTextRendererOptions {\n layers: readonly GLTextLayer[];\n /** Default true. Disable to draw an overlay without clearing existing color. */\n clear?: boolean;\n /** Default opaque black. */\n clearValue?: { r: number; g: number; b: number; a?: number };\n}\n\n/** @internal */\ninterface DataDrawState {\n _layoutVersion: number;\n _hasVariant: boolean;\n _vaos: (TextVao | undefined)[];\n}\n\n/** Standalone WebGL2 analytic text renderer; owns programs/VAOs, not its layers' data. */\nexport interface GLTextRenderer {\n readonly layers: readonly GLTextLayer[];\n /** @internal */ _layers: GLTextLayer[];\n /** @internal */ _engine: GLEngineContext;\n /** @internal */ _base: TextProgram;\n /** @internal */ _variant: TextProgram | null;\n /** @internal */ _quad: GLVertexBuffer;\n /** @internal */ _drawState: Map<GLTextData, DataDrawState>;\n /** @internal */ _viewport: GLViewport;\n /** @internal */ _clearOptions: GLClearOptions | null;\n /** @internal */ _loopFn: ((dt: number) => void) | null;\n /** @internal */ _onLost: () => void;\n /** @internal */ _disposed: boolean;\n}\n\nconst QUAD_CORNERS = new Float32Array([-1, -1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1]);\nconst TEXT_DEPTH_STATE = { test: false, write: false };\n// Premultiplied source-over, including alpha (the general GL preset accumulates alpha).\nconst TEXT_BLEND_STATE = { srcRGB: 1, dstRGB: 0x0303, srcAlpha: 1, dstAlpha: 0x0303 };\n\n/** Create a renderer. Poll readiness before relying on its first draw. */\nexport function createTextRenderer(engine: GLEngineContext, options: GLTextRendererOptions): GLTextRenderer {\n if (engine._isLost || engine._disposed) {\n throw new Error(\"lite-gl: cannot create a text renderer on a lost or disposed engine.\");\n }\n const base = createTextProgram(engine);\n let quad: GLVertexBuffer;\n try {\n quad = createVertexBuffer(engine, QUAD_CORNERS);\n } catch (error) {\n disposeEffect(base._effect);\n throw error;\n }\n const layers = options.layers.slice();\n const drawState = new Map<GLTextData, DataDrawState>();\n const onLost = (): void => drawState.clear();\n const renderer: GLTextRenderer = {\n layers,\n _layers: layers,\n _engine: engine,\n _base: base,\n _variant: null,\n _quad: quad,\n _drawState: drawState,\n _viewport: { x: 0, y: 0, w: 0, h: 0 },\n _clearOptions: options.clear === false ? null : { color: options.clearValue ?? { r: 0, g: 0, b: 0, a: 1 } },\n _loopFn: null,\n _onLost: onLost,\n _disposed: false,\n };\n onContextLost(engine, onLost);\n return renderer;\n}\n\nfunction getDrawState(renderer: GLTextRenderer, data: GLTextData): DataDrawState {\n let state = renderer._drawState.get(data);\n if (!state) {\n state = { _layoutVersion: -1, _hasVariant: false, _vaos: [] };\n renderer._drawState.set(data, state);\n }\n if (state._layoutVersion !== data._layoutVersion) {\n state._hasVariant = false;\n for (const group of data._groups) {\n state._hasVariant ||= group._groupKey !== group._curveSetId;\n }\n for (let i = data._groups.length; i < state._vaos.length; i++) {\n const vao = state._vaos[i];\n if (vao) {\n disposeTextVao(renderer._engine, vao);\n }\n }\n state._vaos.length = Math.min(state._vaos.length, data._groups.length);\n state._layoutVersion = data._layoutVersion;\n }\n return state;\n}\n\n/** True only when all shader variants needed by visible layers have linked. */\nexport function isTextRendererReady(renderer: GLTextRenderer): boolean {\n const engine = renderer._engine;\n if (renderer._disposed || engine._isLost || engine._disposed || !isEffectReady(renderer._base._effect)) {\n return false;\n }\n if (!renderer._variant && _createTextVariant) {\n for (const layer of renderer._layers) {\n if (layer.visible && getDrawState(renderer, layer.data)._hasVariant) {\n renderer._variant = _createTextVariant(engine);\n break;\n }\n }\n }\n return !renderer._variant || isEffectReady(renderer._variant._effect);\n}\n\nfunction compareLayers(a: GLTextLayer, b: GLTextLayer): number {\n return a.order - b.order;\n}\n\n/** Draw visible layers to the bound target, respecting existing scissor/stencil clipping.\n * Returns draw-call count. An unfinished shader or lost/disposed context draws nothing. */\nexport function renderText(renderer: GLTextRenderer): number {\n if (!isTextRendererReady(renderer)) {\n return 0;\n }\n const engine = renderer._engine;\n const gl = engine.gl;\n const target = engine._currentRenderTarget;\n const width = target?.width ?? engine.canvas.width;\n const height = target?.height ?? engine.canvas.height;\n if (width === 0 || height === 0) {\n return 0;\n }\n renderer._viewport.w = width;\n renderer._viewport.h = height;\n setViewport(engine, renderer._viewport);\n setDepthState(engine, TEXT_DEPTH_STATE);\n setCullState(engine, false);\n setColorMask(engine, true, true, true, true);\n setBlendState(engine, TEXT_BLEND_STATE);\n gl.frontFace(gl.CCW);\n if (renderer._clearOptions) {\n clearEngine(engine, renderer._clearOptions);\n }\n applyGLStates(engine);\n if (renderer._layers.length > 1) {\n renderer._layers.sort(compareLayers);\n }\n let draws = 0;\n for (const layer of renderer._layers) {\n if (!layer.visible || layer.data._instanceCount === 0) {\n continue;\n }\n const data = layer.data;\n const gpu = ensureTextDataGpu(engine, data);\n const state = getDrawState(renderer, data);\n let currentProgram: TextProgram | null = null;\n for (let i = 0; i < data._groups.length; i++) {\n const group = data._groups[i]!;\n if (group._slotCount === 0) {\n continue;\n }\n const program = group._groupKey === group._curveSetId ? renderer._base : renderer._variant!;\n if (currentProgram !== program) {\n uploadTextUniforms(program, layer, width, height);\n setEffectTexture(program._effect, \"styles\", gpu._styleTex);\n currentProgram = program;\n }\n const atlas = ensureSharedAtlasGpu(engine, group._curveSet._atlas);\n setEffectTexture(program._effect, \"curveTex\", atlas._curveTex);\n setEffectTexture(program._effect, \"bandTex\", atlas._bandTex);\n setEffectTexture(program._effect, \"glyphMetadata\", atlas._metaTex);\n state._vaos[i] = bindTextVao(engine, renderer._quad, gpu._instanceBuf, group._slotStart, state._vaos[i]);\n gl.drawArraysInstanced(gl.TRIANGLES, 0, 6, group._slotCount);\n draws++;\n }\n }\n disableBlend(engine);\n return draws;\n}\n\n/** Append a layer without transferring ownership. Duplicate references are ignored. */\nexport function addTextRendererLayer(renderer: GLTextRenderer, layer: GLTextLayer): void {\n if (!renderer._disposed && !renderer._layers.includes(layer)) {\n renderer._layers.push(layer);\n }\n}\n\n/** Remove a layer and release VAOs no longer used by any remaining layer. */\nexport function removeTextRendererLayer(renderer: GLTextRenderer, layer: GLTextLayer): boolean {\n const index = renderer._layers.indexOf(layer);\n if (index < 0) {\n return false;\n }\n renderer._layers.splice(index, 1);\n if (!renderer._layers.some((remaining) => remaining.data === layer.data)) {\n const state = renderer._drawState.get(layer.data);\n if (state) {\n for (const vao of state._vaos) {\n if (vao) {\n disposeTextVao(renderer._engine, vao);\n }\n }\n renderer._drawState.delete(layer.data);\n }\n }\n return true;\n}\n\n/** Register one automatic draw callback with the engine's render loop. Idempotent. */\nexport function registerTextRenderer(renderer: GLTextRenderer): void {\n if (renderer._disposed || renderer._loopFn !== null) {\n return;\n }\n renderer._loopFn = (): void => {\n renderText(renderer);\n };\n runRenderLoop(renderer._engine, renderer._loopFn);\n}\n\n/** Remove only this renderer's automatic draw callback. */\nexport function unregisterTextRenderer(renderer: GLTextRenderer): void {\n if (renderer._loopFn) {\n stopRenderLoop(renderer._engine, renderer._loopFn);\n renderer._loopFn = null;\n }\n}\n\n/** Release owned programs, quad and VAOs. Borrowed text data/storage stay alive. */\nexport function disposeTextRenderer(renderer: GLTextRenderer): void {\n if (renderer._disposed) {\n return;\n }\n unregisterTextRenderer(renderer);\n renderer._disposed = true;\n const engine = renderer._engine;\n offContextLost(engine, renderer._onLost);\n for (const state of renderer._drawState.values()) {\n for (const vao of state._vaos) {\n if (vao) {\n disposeTextVao(engine, vao);\n }\n }\n }\n renderer._drawState.clear();\n disposeEffect(renderer._base._effect);\n if (renderer._variant) {\n disposeEffect(renderer._variant._effect);\n }\n disposeBuffer(renderer._quad);\n renderer._layers.length = 0;\n}\n"]}
1
+ {"version":3,"file":"text-renderer.js","sourceRoot":"","sources":["../../src/text/text-renderer.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAC9D,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAC9E,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAA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CAAC","sourcesContent":["import type { GLEngineContext } from \"../context.js\";\nimport { offContextLost, onContextLost } from \"../context.js\";\nimport { disposeEffect, isEffectReady, setEffectTexture } from \"../effect.js\";\nimport { createVertexBuffer, disposeBuffer } from \"../mesh.js\";\nimport type { GLVertexBuffer } from \"../mesh.js\";\nimport { disableBlend, setBlendState } from \"../blend.js\";\nimport { applyGLStates } from \"../apply-states.js\";\nimport { clearEngine, setColorMask, setCullState, setDepthState } from \"../depth-stencil.js\";\nimport { setViewport } from \"../effect-renderer.js\";\nimport type { GLClearOptions, GLViewport } from \"../family.js\";\nimport { runRenderLoop, stopRenderLoop } from \"../render-loop.js\";\nimport type { GLTextData } from \"./text-data.js\";\nimport { ensureSharedAtlasGpu } from \"./_gpu/text-textures.js\";\nimport { ensureTextDataGpu } from \"./_gpu/text-instances.js\";\nimport { _createTextVariant, createTextProgram, uploadTextUniforms } from \"./_gpu/text-effect.js\";\nimport type { TextProgram } from \"./_gpu/text-effect.js\";\nimport { bindTextVao, disposeTextVao } from \"./_gpu/text-vao.js\";\nimport type { TextVao } from \"./_gpu/text-vao.js\";\n\n/** Pixel-space placement and compositing of one text block. */\nexport interface GLTextLayerOptions {\n readonly positionPx?: { readonly x: number; readonly y: number };\n readonly rotationRad?: number;\n readonly scale?: number;\n readonly order?: number;\n readonly opacity?: number;\n /** Raises analytic coverage to 1/gamma. Default 1; values above 1 darken edges. */\n readonly coverageGamma?: number;\n readonly visible?: boolean;\n}\n\n/** Mutable placement of borrowed text data. Positions are in target pixels, not CSS pixels. */\nexport interface GLTextLayer {\n readonly data: GLTextData;\n positionPx: { x: number; y: number };\n rotationRad: number;\n scale: number;\n order: number;\n opacity: number;\n coverageGamma: number;\n visible: boolean;\n}\n\n/** Create a pure-data layer; rendering does not transfer ownership of its text data. */\nexport function createTextLayer(data: GLTextData, options?: GLTextLayerOptions): GLTextLayer {\n return {\n data,\n positionPx: { x: options?.positionPx?.x ?? 0, y: options?.positionPx?.y ?? 0 },\n rotationRad: options?.rotationRad ?? 0,\n scale: options?.scale ?? 1,\n order: options?.order ?? 0,\n opacity: options?.opacity ?? 1,\n coverageGamma: options?.coverageGamma ?? 1,\n visible: options?.visible ?? true,\n };\n}\n\n/** Set the layer's baseline origin in target pixels. */\nexport function setTextLayerPosition(layer: GLTextLayer, x: number, y: number): void {\n layer.positionPx.x = x;\n layer.positionPx.y = y;\n}\n\n/** Options for drawing text to the currently bound canvas or render target. */\nexport interface GLTextRendererOptions {\n layers: readonly GLTextLayer[];\n /** Default true. Disable to draw an overlay without clearing existing color. */\n clear?: boolean;\n /** Default opaque black. */\n clearValue?: { r: number; g: number; b: number; a?: number };\n}\n\n/** @internal */\ninterface DataDrawState {\n _layoutVersion: number;\n _hasVariant: boolean;\n _vaos: (TextVao | undefined)[];\n}\n\n/** Standalone WebGL2 analytic text renderer; owns programs/VAOs, not its layers' data. */\nexport interface GLTextRenderer {\n readonly layers: readonly GLTextLayer[];\n /** @internal */ _layers: GLTextLayer[];\n /** @internal */ _engine: GLEngineContext;\n /** @internal */ _base: TextProgram;\n /** @internal */ _variant: TextProgram | null;\n /** @internal */ _quad: GLVertexBuffer;\n /** @internal */ _drawState: Map<GLTextData, DataDrawState>;\n /** @internal */ _viewport: GLViewport;\n /** @internal */ _clearOptions: GLClearOptions | null;\n /** @internal */ _loopFn: ((dt: number) => void) | null;\n /** @internal */ _onLost: () => void;\n /** @internal */ _disposed: boolean;\n}\n\nconst QUAD_CORNERS = new Float32Array([-1, -1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1]);\nconst TEXT_DEPTH_STATE = { test: false, write: false };\n// Premultiplied source-over, including alpha (the general GL preset accumulates alpha).\nconst TEXT_BLEND_STATE = { srcRGB: 1, dstRGB: 0x0303, srcAlpha: 1, dstAlpha: 0x0303 };\n\n/** Create a renderer. Poll readiness before relying on its first draw. */\nexport function createTextRenderer(engine: GLEngineContext, options: GLTextRendererOptions): GLTextRenderer {\n if (engine._isLost || engine._disposed) {\n throw new Error(\"lite-gl: cannot create a text renderer on a lost or disposed engine.\");\n }\n const base = createTextProgram(engine);\n let quad: GLVertexBuffer;\n try {\n quad = createVertexBuffer(engine, QUAD_CORNERS);\n } catch (error) {\n disposeEffect(base._effect);\n throw error;\n }\n const layers = options.layers.slice();\n const drawState = new Map<GLTextData, DataDrawState>();\n const onLost = (): void => drawState.clear();\n const renderer: GLTextRenderer = {\n layers,\n _layers: layers,\n _engine: engine,\n _base: base,\n _variant: null,\n _quad: quad,\n _drawState: drawState,\n _viewport: { x: 0, y: 0, w: 0, h: 0 },\n _clearOptions: options.clear === false ? null : { color: options.clearValue ?? { r: 0, g: 0, b: 0, a: 1 } },\n _loopFn: null,\n _onLost: onLost,\n _disposed: false,\n };\n onContextLost(engine, onLost);\n return renderer;\n}\n\nfunction getDrawState(renderer: GLTextRenderer, data: GLTextData): DataDrawState {\n let state = renderer._drawState.get(data);\n if (!state) {\n state = { _layoutVersion: -1, _hasVariant: false, _vaos: [] };\n renderer._drawState.set(data, state);\n }\n if (state._layoutVersion !== data._layoutVersion) {\n state._hasVariant = false;\n for (const group of data._groups) {\n state._hasVariant ||= group._groupKey !== group._curveSetId;\n }\n for (let i = data._groups.length; i < state._vaos.length; i++) {\n const vao = state._vaos[i];\n if (vao) {\n disposeTextVao(renderer._engine, vao);\n }\n }\n state._vaos.length = Math.min(state._vaos.length, data._groups.length);\n state._layoutVersion = data._layoutVersion;\n }\n return state;\n}\n\n/** True only when all shader variants needed by visible layers have linked. */\nexport function isTextRendererReady(renderer: GLTextRenderer): boolean {\n const engine = renderer._engine;\n if (renderer._disposed || engine._isLost || engine._disposed || !isEffectReady(renderer._base._effect)) {\n return false;\n }\n if (!renderer._variant && _createTextVariant) {\n for (const layer of renderer._layers) {\n if (layer.visible && getDrawState(renderer, layer.data)._hasVariant) {\n renderer._variant = _createTextVariant(engine);\n break;\n }\n }\n }\n return !renderer._variant || isEffectReady(renderer._variant._effect);\n}\n\nfunction compareLayers(a: GLTextLayer, b: GLTextLayer): number {\n return a.order - b.order;\n}\n\n/** Draw visible layers to the bound target, respecting existing scissor/stencil clipping.\n * Returns draw-call count. An unfinished shader or lost/disposed context draws nothing. */\nexport function renderText(renderer: GLTextRenderer): number {\n if (!isTextRendererReady(renderer)) {\n return 0;\n }\n const engine = renderer._engine;\n const gl = engine.gl;\n const target = engine._currentRenderTarget;\n const width = target?.width ?? engine.canvas.width;\n const height = target?.height ?? engine.canvas.height;\n if (width === 0 || height === 0) {\n return 0;\n }\n renderer._viewport.w = width;\n renderer._viewport.h = height;\n setViewport(engine, renderer._viewport);\n setDepthState(engine, TEXT_DEPTH_STATE);\n setCullState(engine, false);\n setColorMask(engine, true, true, true, true);\n setBlendState(engine, TEXT_BLEND_STATE);\n gl.frontFace(gl.CCW);\n if (renderer._clearOptions) {\n clearEngine(engine, renderer._clearOptions);\n }\n applyGLStates(engine);\n if (renderer._layers.length > 1) {\n renderer._layers.sort(compareLayers);\n }\n let draws = 0;\n for (const layer of renderer._layers) {\n if (!layer.visible || layer.data._instanceCount === 0) {\n continue;\n }\n const data = layer.data;\n const gpu = ensureTextDataGpu(engine, data);\n const state = getDrawState(renderer, data);\n let currentProgram: TextProgram | null = null;\n for (let i = 0; i < data._groups.length; i++) {\n const group = data._groups[i]!;\n if (group._slotCount === 0) {\n continue;\n }\n const program = group._groupKey === group._curveSetId ? renderer._base : renderer._variant!;\n if (currentProgram !== program) {\n uploadTextUniforms(program, layer, width, height);\n setEffectTexture(program._effect, \"styles\", gpu._styleTex);\n currentProgram = program;\n }\n const atlas = ensureSharedAtlasGpu(engine, group._curveSet._atlas);\n setEffectTexture(program._effect, \"curveTex\", atlas._curveTex);\n setEffectTexture(program._effect, \"bandTex\", atlas._bandTex);\n setEffectTexture(program._effect, \"glyphMetadata\", atlas._metaTex);\n state._vaos[i] = bindTextVao(engine, renderer._quad, gpu._instanceBuf, group._slotStart, state._vaos[i]);\n gl.drawArraysInstanced(gl.TRIANGLES, 0, 6, group._slotCount);\n draws++;\n }\n }\n disableBlend(engine);\n return draws;\n}\n\n/** Append a layer without transferring ownership. Duplicate references are ignored. */\nexport function addTextRendererLayer(renderer: GLTextRenderer, layer: GLTextLayer): void {\n if (!renderer._disposed && !renderer._layers.includes(layer)) {\n renderer._layers.push(layer);\n }\n}\n\n/** Remove a layer and release VAOs no longer used by any remaining layer. */\nexport function removeTextRendererLayer(renderer: GLTextRenderer, layer: GLTextLayer): boolean {\n const index = renderer._layers.indexOf(layer);\n if (index < 0) {\n return false;\n }\n renderer._layers.splice(index, 1);\n if (!renderer._layers.some((remaining) => remaining.data === layer.data)) {\n const state = renderer._drawState.get(layer.data);\n if (state) {\n for (const vao of state._vaos) {\n if (vao) {\n disposeTextVao(renderer._engine, vao);\n }\n }\n renderer._drawState.delete(layer.data);\n }\n }\n return true;\n}\n\n/** Register one automatic draw callback with the engine's render loop. Idempotent. */\nexport function registerTextRenderer(renderer: GLTextRenderer): void {\n if (renderer._disposed || renderer._loopFn !== null) {\n return;\n }\n renderer._loopFn = (): void => {\n renderText(renderer);\n };\n runRenderLoop(renderer._engine, renderer._loopFn);\n}\n\n/** Remove only this renderer's automatic draw callback. */\nexport function unregisterTextRenderer(renderer: GLTextRenderer): void {\n if (renderer._loopFn) {\n stopRenderLoop(renderer._engine, renderer._loopFn);\n renderer._loopFn = null;\n }\n}\n\n/** Release owned programs, quad and VAOs. Borrowed text data/storage stay alive. */\nexport function disposeTextRenderer(renderer: GLTextRenderer): void {\n if (renderer._disposed) {\n return;\n }\n unregisterTextRenderer(renderer);\n renderer._disposed = true;\n const engine = renderer._engine;\n offContextLost(engine, renderer._onLost);\n for (const state of renderer._drawState.values()) {\n for (const vao of state._vaos) {\n if (vao) {\n disposeTextVao(engine, vao);\n }\n }\n }\n renderer._drawState.clear();\n disposeEffect(renderer._base._effect);\n if (renderer._variant) {\n disposeEffect(renderer._variant._effect);\n }\n disposeBuffer(renderer._quad);\n renderer._layers.length = 0;\n}\n"]}