@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/CHANGELOG.md CHANGED
@@ -1,5 +1,39 @@
1
1
  # Changelog
2
2
 
3
+ ## @babylonjs/lite-gl v1.24.1
4
+
5
+ ### ⚠️ BREAKING CHANGES
6
+
7
+ - **particle:** NPE value, math and sprite-cell blocks ([#939](https://github.com/BabylonJS/Babylon-Lite/pull/939))
8
+
9
+ ### ✨ Features
10
+
11
+ - **lite-gl:** context-loss opt-out, attribute-pointer cache and correctness fixes ([#936](https://github.com/BabylonJS/Babylon-Lite/pull/936))
12
+ - **compat:** advance upstream sync watermarks ([#940](https://github.com/BabylonJS/Babylon-Lite/pull/940))
13
+
14
+ ### 🐛 Bug Fixes
15
+
16
+ - break lazy-import cycles that made Vite 8 emit unused chunks ([#941](https://github.com/BabylonJS/Babylon-Lite/pull/941))
17
+ - **shadow:** compose CSM and ESM/PCF receivers in mixed scenes ([#937](https://github.com/BabylonJS/Babylon-Lite/pull/937))
18
+
19
+ ### 🧪 Tests
20
+
21
+ - **gl:** guard against import cycles in the shipped dist ([#942](https://github.com/BabylonJS/Babylon-Lite/pull/942))
22
+
23
+ **Full Changelog**: https://github.com/BabylonJS/Babylon-Lite/compare/npm-lite-gl-v1.24.0...npm-lite-gl-v1.24.1
24
+
25
+ ## @babylonjs/lite-gl v1.24.0
26
+
27
+ ### ✨ Features
28
+
29
+ - **gl:** add an experimental native backend ([#922](https://github.com/BabylonJS/Babylon-Lite/pull/922))
30
+
31
+ ### 🔧 Other Changes
32
+
33
+ - Fix native texture creation when the host limit is unavailable ([#938](https://github.com/BabylonJS/Babylon-Lite/pull/938))
34
+
35
+ **Full Changelog**: https://github.com/BabylonJS/Babylon-Lite/compare/npm-lite-gl-v1.23.0...npm-lite-gl-v1.24.0
36
+
3
37
  ## @babylonjs/lite-gl v1.23.0
4
38
 
5
39
  ### ⚠️ BREAKING CHANGES
package/README.md CHANGED
@@ -9,8 +9,7 @@ bundler keeps only what you import.
9
9
  It is a focused subset of Babylon.js' rendering primitives, validated to render
10
10
  **near-identically** (within ±1–2 LSB ANGLE / SwiftShader codegen noise) to
11
11
  Babylon's `ThinEngine` / `EffectRenderer` / `SpriteRenderer` / `HtmlElementTexture`
12
- path — every feature has a side-by-side parity scene in `tests/gl/parity/` (and,
13
- downstream, the NeonBrush effect suite). Swapping `@babylonjs/core` for lite-gl
12
+ path — every feature has a side-by-side parity scene in `tests/gl/parity/`. Swapping `@babylonjs/core` for lite-gl
14
13
  typically shrinks an effect's shipped bundle **~10–16×** (≈4–6 KB gzip vs
15
14
  ≈40–80 KB).
16
15
 
@@ -120,20 +119,26 @@ still compile but alter behavior, so check them by hand:
120
119
 
121
120
  ## Entry points
122
121
 
123
- The entire public API is available from the single `@babylonjs/lite-gl` entry:
122
+ The entire WebGL2 API is available from the `@babylonjs/lite-gl` entry:
124
123
  engine + render loop, effects & uniform setters, textures (incl. float / HDR +
125
124
  dynamic), the `EffectWrapper` fullscreen-quad renderer, render targets, meshes /
126
125
  vertex-index buffers + instancing, depth / stencil / color-mask / clear, scissor,
127
126
  blend modes, the sprite renderer, and HTML-element textures. The package is
128
127
  `sideEffects: false`, so a bundler tree-shakes away whichever features you don't
129
- use.
128
+ use. A separate, **experimental and temporary** `@babylonjs/lite-gl/native` entry targets Babylon Native (see
129
+ [below](#babylon-native-babylonjslite-glnative)); the two entries share no
130
+ modules, so importing one never bundles the other. The type-only
131
+ `@babylonjs/lite-gl/family` entry describes the operations both backends share,
132
+ so code can be written once for either backend
133
+ ([below](#shared-code-for-both-backends-babylonjslite-glfamily)).
130
134
 
131
135
  ### Core API (`@babylonjs/lite-gl`)
132
136
 
133
137
  - **Engine / lifecycle** — `createGLEngine`, `disposeGLEngine`, `resizeGLEngine`,
134
138
  `getRenderWidth`, `getRenderHeight`, `get/setHardwareScalingLevel`,
135
139
  `getRenderingCanvas`, and `on/offContextLost` + `on/offContextRestored`
136
- (context-loss is handled: effects and textures are rebuilt on restore).
140
+ (context-loss is handled: effects and textures are rebuilt on restore;
141
+ `createHostOwnedGLEngine` opts out for hosts that recreate everything themselves).
137
142
  - **Render loop** — `runRenderLoop`, `stopRenderLoop`, plus `beginFrame` /
138
143
  `endFrame` for hosts that drive their own frame.
139
144
  - **GPU frame timing (optional)** — `captureGPUFrameTime`,
@@ -179,7 +184,8 @@ use.
179
184
  `readRenderTargetPixelsToBuffer` (same, into a `PIXEL_PACK_BUFFER` at a byte
180
185
  `offset`), `disposeRenderTarget`.
181
186
  - **Meshes / buffers** — `createVertexBuffer`, `updateVertexBuffer`,
182
- `createIndexBuffer`, `bindAttributes`, `drawIndexed` (instanced), `disposeBuffer`.
187
+ `createIndexBuffer`, `bindAttributes` (or `bindAttributesCached` to elide unchanged
188
+ pointers and divisors when rebinding every draw), `drawIndexed` (instanced), `disposeBuffer`.
183
189
  - **Depth / stencil / scissor** — `setDepthState`, `setStencilState`,
184
190
  `setStencilOpSeparate` (independent front/back operations), `setCullState`,
185
191
  `setColorMask`, `clearEngine`; `setScissor`, `disableScissor`.
@@ -253,6 +259,97 @@ back to transparent black for that texture only. Mipmaps requested with
253
259
  `generateTextureMipMaps` are rebuilt after the restored upload. No source is
254
260
  closed by lite-gl.
255
261
 
262
+ ### Babylon Native (`@babylonjs/lite-gl/native`)
263
+
264
+ > **Experimental and temporary.** This backend is a temporary implementation
265
+ > for evaluation, not a stable API or a long-term backend commitment. Its API
266
+ > and implementation may change, be replaced, or be removed.
267
+
268
+ The same function-based style, encoded into the Babylon Native engine protocol
269
+ (protocol 9) instead of a `WebGL2RenderingContext`. The native runtime is read
270
+ only when `createNativeEngine()` is called, never at import time. For the
271
+ operations it implements, the entry uses the web entry's `GL*` type names and
272
+ options; `NativeGLFamily` records where its signatures are narrower than the
273
+ web backend's. Engine creation, frames, and borrowed host textures are
274
+ native-specific.
275
+
276
+ ```ts
277
+ import { createNativeEngine, beginFrame, endFrame, createEffect, setEffectFloat, createVertexBuffer, createIndexBuffer, createMeshVao, drawMesh } from "@babylonjs/lite-gl/native";
278
+
279
+ const engine = createNativeEngine();
280
+ const effect = createEffect(engine, { name: "gradient", vertexSource, fragmentSource, attributeNames: ["position"], uniformNames: ["uTime"], samplerNames: [] });
281
+ const vertices = createVertexBuffer(engine, new Float32Array([-1, -1, 1, -1, 1, 1, -1, 1]));
282
+ const indices = createIndexBuffer(engine, new Uint16Array([0, 1, 2, 0, 2, 3]));
283
+ const quad = createMeshVao(engine, [{ buffer: vertices, attributes: [{ name: "position", size: 2, divisor: 0 }] }], indices, effect);
284
+
285
+ beginFrame(engine);
286
+ setEffectFloat(effect, "uTime", time);
287
+ drawMesh(quad);
288
+ endFrame(engine);
289
+ ```
290
+
291
+ - **Engine / frames** — `createNativeEngine`, `disposeNativeEngine`,
292
+ `beginFrame` / `endFrame` (`endFrame` submits the remaining commands),
293
+ `getRenderWidth`, `getRenderHeight` (native output size),
294
+ `getCurrentRenderTarget`, and `engine.caps.maxTextureSize`.
295
+ - **Effects** — `createEffect` (accepts Lite GL `#version 300 es` sources;
296
+ uniform setters affect only declared names),
297
+ `useEffect`, `isEffectReady`, `getEffectCompilationError` (always `null`:
298
+ compilation errors throw from `createEffect`), `disposeEffect`,
299
+ and the cached setters `setEffectFloat` / `…Float2` / `…Float3` / `…Float4` /
300
+ `…Int` / `…Matrix` / `…FloatArray` / `…FloatArray2` / `…FloatArray3` /
301
+ `…FloatArray4` / `…Texture`.
302
+ - **Geometry** — `createVertexBuffer`, `createIndexBuffer`, `createMeshVao`,
303
+ `bindMeshVao`, `drawMesh` (non-instanced: `instanceCount` must be `0`),
304
+ `disposeBuffer`, `disposeMeshVao`. A mesh vertex array owns only itself, so
305
+ several meshes can share one vertex/index buffer.
306
+ - **Textures / targets** — `wrapNativeTexture` (borrows host storage),
307
+ `createRawTexture` (owns sampled-only storage; `RGBA` / `UNSIGNED_BYTE` only;
308
+ creating one inside a frame first submits the commands recorded so far, so create raw
309
+ textures before `beginFrame` when the submission count matters), `disposeTexture`
310
+ (owned storage is deleted after the commands already recorded are submitted),
311
+ `createRenderTarget` (`width, height, { colorTexture? }`; not a raw texture), `bindRenderTarget` /
312
+ `restoreDefaultFramebuffer` (also set a full-target viewport), `updateWrappedNativeTexture`
313
+ (replaces a borrowed handle and rebuilds its framebuffers; call it only when the host storage changed;
314
+ if it throws, retry it or restore the host storage before using the texture or its targets),
315
+ `disposeRenderTarget`.
316
+ - **State** — `setViewport` (pixel `GLViewport`), `setScissor` (an empty rectangle
317
+ clips everything, as in WebGL), `disableScissor`,
318
+ `setBlendMode`, `clearEngine` (`GLClearOptions`).
319
+
320
+ The ownership and device-reset contract is documented in
321
+ `docs/gl/architecture/03-native-lite-gl.md`.
322
+
323
+ ### Shared code for both backends (`@babylonjs/lite-gl/family`)
324
+
325
+ The `family` entry is types only and needs no DOM library. `GLOps<F>` describes
326
+ every backend-neutral operation over a backend family `F` (`WebGLFamily` from
327
+ the web entry, `NativeGLFamily` from the native entry). Shared code names the
328
+ operations it uses as a `GLKit`, and each composition root fills the kit with
329
+ direct references to one backend's functions, so bundles keep only those
330
+ functions:
331
+
332
+ ```ts
333
+ import type { GLFamily, GLKit } from "@babylonjs/lite-gl/family";
334
+
335
+ type QuadOps = "useEffect" | "setEffectTexture" | "drawMesh";
336
+ function drawLayer<F extends GLFamily>(gl: GLKit<F, QuadOps>, effect: F["effect"], mesh: F["meshVao"], layer: F["texture"]) {
337
+ gl.useEffect(effect);
338
+ gl.setEffectTexture(effect, "layer", layer);
339
+ gl.drawMesh(mesh);
340
+ }
341
+
342
+ // Browser root; a native root imports the same names from "@babylonjs/lite-gl/native" with NativeGLFamily.
343
+ import { useEffect, setEffectTexture, drawMesh, type WebGLFamily } from "@babylonjs/lite-gl";
344
+ const webKit: GLKit<WebGLFamily, QuadOps> = { useEffect, setEffectTexture, drawMesh };
345
+ ```
346
+
347
+ Each backend keeps its own signatures: for example the native `drawMesh` is
348
+ non-instanced and its `setEffectTexture` does not accept `null`. Engine creation
349
+ and host interop such as `createGLEngine` or `wrapNativeTexture` are
350
+ backend-specific and listed in `WebGLHostOps` / `NativeGLHostOps`. See
351
+ `docs/gl/architecture/04-backend-family.md`.
352
+
256
353
  ## Demos
257
354
 
258
355
  Runnable scenes for every feature live in the repo's GL **lab**
package/blend.d.ts CHANGED
@@ -98,7 +98,7 @@ export declare function setBlendMode(engine: GLEngineContext, mode: GLBlendMode)
98
98
  * `setAlphaBlendFunctionParameters` + `setAlphaEquationParameters`.
99
99
  *
100
100
  * Supports every WebGL2 blend equation, including `MIN`, `MAX`,
101
- * `FUNC_SUBTRACT` and `FUNC_REVERSE_SUBTRACT` (used by ShapeBuilder's darken /
101
+ * `FUNC_SUBTRACT` and `FUNC_REVERSE_SUBTRACT` (e.g. for darken /
102
102
  * cutout blend modes). Records the desired config (flushed by `applyGLStates`
103
103
  * before the next draw); at flush time the enable flag, the equation and the func
104
104
  * are each cached independently, so a redundant state is fully elided and only
package/blend.js CHANGED
@@ -77,7 +77,7 @@ export function setBlendMode(engine, mode) {
77
77
  * `setAlphaBlendFunctionParameters` + `setAlphaEquationParameters`.
78
78
  *
79
79
  * Supports every WebGL2 blend equation, including `MIN`, `MAX`,
80
- * `FUNC_SUBTRACT` and `FUNC_REVERSE_SUBTRACT` (used by ShapeBuilder's darken /
80
+ * `FUNC_SUBTRACT` and `FUNC_REVERSE_SUBTRACT` (e.g. for darken /
81
81
  * cutout blend modes). Records the desired config (flushed by `applyGLStates`
82
82
  * before the next draw); at flush time the enable flag, the equation and the func
83
83
  * are each cached independently, so a redundant state is fully elided and only
package/blend.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"blend.js","sourceRoot":"","sources":["../src/blend.ts"],"names":[],"mappings":"AAqBA,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,aAAa,EAAE,eAAe,EAAE,cAAc,EAAE,gBAAgB,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAE9J;;;GAGG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG;IACvB,wEAAwE;IACxE,OAAO,EAAE,CAAC;IACV,yFAAyF;IACzF,GAAG,EAAE,CAAC;IACN,sIAAsI;IACtI,KAAK,EAAE,CAAC;IACR,uHAAuH;IACvH,aAAa,EAAE,CAAC;CACV,CAAC;AAKX;;;;;GAKG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG;IAC3B,oCAAoC;IACpC,GAAG,EAAE,MAAM;IACX,mBAAmB;IACnB,QAAQ,EAAE,MAAM;IAChB,mBAAmB;IACnB,gBA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CAAC,CAAC;QACrC,EAAE,CAAC,eAAe,CAAC,GAAG,KAAK,CAAC;QAC5B,EAAE,CAAC,aAAa,CAAC,GAAG,GAAG,CAAC;IAC5B,CAAC;IACD,6DAA6D;IAC7D,MAAM,MAAM,GAAG,EAAE,CAAC,gBAAgB,GAAG,UAAU,CAAE,CAAC;IAClD,MAAM,MAAM,GAAG,EAAE,CAAC,gBAAgB,GAAG,UAAU,CAAE,CAAC;IAClD,MAAM,IAAI,GAAG,EAAE,CAAC,cAAc,GAAG,UAAU,CAAE,CAAC;IAC9C,MAAM,IAAI,GAAG,EAAE,CAAC,cAAc,GAAG,UAAU,CAAE,CAAC;IAC9C,IAAI,EAAE,CAAC,gBAAgB,CAAC,KAAK,MAAM,IAAI,EAAE,CAAC,gBAAgB,CAAC,KAAK,MAAM,IAAI,EAAE,CAAC,cAAc,CAAC,KAAK,IAAI,IAAI,EAAE,CAAC,cAAc,CAAC,KAAK,IAAI,EAAE,CAAC;QACnI,EAAE,CAAC,iBAAiB,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;QACjD,EAAE,CAAC,gBAAgB,CAAC,GAAG,MAAM,CAAC;QAC9B,EAAE,CAAC,gBAAgB,CAAC,GAAG,MAAM,CAAC;QAC9B,EAAE,CAAC,cAAc,CAAC,GAAG,IAAI,CAAC;QAC1B,EAAE,CAAC,cAAc,CAAC,GAAG,IAAI,CAAC;IAC9B,CAAC;AACL,CAAC","sourcesContent":["/**\n * Blend-mode state — the WebGL counterpart of Babylon's `Engine.setAlphaMode`\n * (presets) and `AlphaState.setAlphaBlendFunctionParameters` /\n * `setAlphaEquationParameters` (the arbitrary separate func + equation path).\n *\n * The numeric {@link GLBlendMode} values intentionally match Babylon's\n * `Constants.ALPHA_*` (`ALPHA_DISABLE = 0`, `ALPHA_ADD = 1`, `ALPHA_COMBINE = 2`,\n * `ALPHA_PREMULTIPLIED = 7`) so a consumer can forward raw Babylon constants\n * without a translation table.\n *\n * DEFERRED MODEL (matches Babylon's `AlphaState`): these setters do NOT touch\n * `gl.*`. They record only the DESIRED blend config into the `d*` mirror fields\n * of `GLState` and raise `statesDirty`; `applyGLStates` (apply-states.ts) flushes\n * the diff to GL right before each draw / clear. Setting blend A then B then A\n * with no draw in between therefore applies exactly one blend state (A), and a\n * blend left unchanged across frames re-issues nothing.\n *\n * Both {@link setBlendMode} and {@link setBlendState} feed the same desired\n * fields, so the preset and arbitrary paths can never desync.\n */\nimport { type GLEngineContext } from \"./context.js\";\nimport { RS_BLEND_DST_A, RS_BLEND_DST_RGB, RS_BLEND_ENABLED, RS_BLEND_EQ_A, RS_BLEND_EQ_RGB, RS_BLEND_SRC_A, RS_BLEND_SRC_RGB, RS_DESIRED } from \"./state.js\";\n\n/**\n * Supported blend presets. Values mirror Babylon's `Constants.ALPHA_*` so the\n * raw Babylon integers can be passed straight through.\n */\nexport const GLBlendMode = {\n /** No blending — `gl.disable(gl.BLEND)`. (`Constants.ALPHA_DISABLE`) */\n DISABLE: 0,\n /** Additive — `blendFuncSeparate(SRC_ALPHA, ONE, ZERO, ONE)`. (`Constants.ALPHA_ADD`) */\n ADD: 1,\n /** Standard (non-premultiplied) alpha — `blendFuncSeparate(SRC_ALPHA, ONE_MINUS_SRC_ALPHA, ONE, ONE)`. (`Constants.ALPHA_COMBINE`) */\n ALPHA: 2,\n /** Premultiplied alpha — `blendFuncSeparate(ONE, ONE_MINUS_SRC_ALPHA, ONE, ONE)`. (`Constants.ALPHA_PREMULTIPLIED`) */\n PREMULTIPLIED: 7,\n} as const;\n\n/** One of the {@link GLBlendMode} preset values (`0`, `1`, `2` or `7`). */\nexport type GLBlendMode = (typeof GLBlendMode)[keyof typeof GLBlendMode];\n\n/**\n * Blend equation presets — the values WebGL2 accepts for\n * `gl.blendEquationSeparate`. Numeric values equal the GL enums so raw GL\n * integers (or Babylon's identical `Constants.GL_ALPHA_EQUATION_*`) pass\n * straight through.\n */\nexport const GLBlendEquation = {\n /** `src + dst` (the GL default). */\n ADD: 0x8006,\n /** `src - dst`. */\n SUBTRACT: 0x800a,\n /** `dst - src`. */\n REVERSE_SUBTRACT: 0x800b,\n /** `min(src, dst)`. */\n MIN: 0x8007,\n /** `max(src, dst)`. */\n MAX: 0x8008,\n} as const;\n\n/** One of the {@link GLBlendEquation} preset values. */\nexport type GLBlendEquation = (typeof GLBlendEquation)[keyof typeof GLBlendEquation];\n\n/**\n * Arbitrary separate-channel blend configuration — the lite-gl equivalent of\n * Babylon's `AlphaState.setAlphaBlendFunctionParameters` +\n * `setAlphaEquationParameters`. All factor / equation fields are raw WebGL2\n * enums (`gl.ONE`, `gl.SRC_ALPHA`, `gl.MIN`, …); use {@link GLBlendEquation} for\n * the equations if you prefer named presets.\n */\nexport interface GLBlendState {\n /** RGB source factor (`gl.blendFuncSeparate` arg 1). */\n srcRGB: GLenum;\n /** RGB destination factor (`gl.blendFuncSeparate` arg 2). */\n dstRGB: GLenum;\n /** Alpha source factor (`gl.blendFuncSeparate` arg 3). */\n srcAlpha: GLenum;\n /** Alpha destination factor (`gl.blendFuncSeparate` arg 4). */\n dstAlpha: GLenum;\n /** RGB blend equation. Defaults to `FUNC_ADD`. */\n equationRGB?: GLenum;\n /** Alpha blend equation. Defaults to `FUNC_ADD`. */\n equationAlpha?: GLenum;\n}\n\n/** GL `FUNC_ADD` — the implicit equation used by the {@link GLBlendMode}\n * presets (matching Babylon's `setAlphaMode`, which leaves it at the default). */\nconst FUNC_ADD = 0x8006;\n/** GL `gl.BLEND`. */\nconst BLEND = 0x0be2;\n\n/**\n * Set the GL blend state to match Babylon's `setAlphaMode(mode)` exactly.\n *\n * | Mode | `gl.blendFuncSeparate(srcRGB, dstRGB, srcA, dstA)` |\n * |--------------------|------------------------------------------------------------|\n * | `DISABLE` (0) | — (`gl.disable(gl.BLEND)`) |\n * | `ADD` (1) | `SRC_ALPHA, ONE, ZERO, ONE` |\n * | `ALPHA` (2) | `SRC_ALPHA, ONE_MINUS_SRC_ALPHA, ONE, ONE` |\n * | `PREMULTIPLIED` (7)| `ONE, ONE_MINUS_SRC_ALPHA, ONE, ONE` |\n *\n * No-op when the context is lost or disposed.\n *\n * @param engine - The engine whose GL blend state is updated.\n * @param mode - The {@link GLBlendMode} preset to apply.\n */\nexport function setBlendMode(engine: GLEngineContext, mode: GLBlendMode): void {\n if (engine._isLost || engine._disposed) {\n return;\n }\n const gl = engine.gl;\n switch (mode) {\n case GLBlendMode.DISABLE:\n disableBlend(engine);\n return;\n case GLBlendMode.ADD:\n applyBlend(engine, gl.SRC_ALPHA, gl.ONE, gl.ZERO, gl.ONE, FUNC_ADD, FUNC_ADD);\n return;\n case GLBlendMode.ALPHA:\n applyBlend(engine, gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE, FUNC_ADD, FUNC_ADD);\n return;\n case GLBlendMode.PREMULTIPLIED:\n applyBlend(engine, gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE, FUNC_ADD, FUNC_ADD);\n return;\n }\n}\n\n/**\n * Enable blending with an arbitrary separate-channel function and equation —\n * the lite-gl equivalent of Babylon's `AlphaState` with\n * `setAlphaBlendFunctionParameters` + `setAlphaEquationParameters`.\n *\n * Supports every WebGL2 blend equation, including `MIN`, `MAX`,\n * `FUNC_SUBTRACT` and `FUNC_REVERSE_SUBTRACT` (used by ShapeBuilder's darken /\n * cutout blend modes). Records the desired config (flushed by `applyGLStates`\n * before the next draw); at flush time the enable flag, the equation and the func\n * are each cached independently, so a redundant state is fully elided and only\n * the call whose params changed is re-issued — mirroring Babylon's `AlphaState`\n * dirty flags. Because GL keeps the equation + func across `gl.disable(BLEND)`,\n * re-enabling with unchanged params re-issues neither.\n *\n * No-op when the context is lost or disposed.\n *\n * @param engine - The engine whose desired blend state is updated.\n * @param state - The separate-channel blend factors + equations to apply.\n */\nexport function setBlendState(engine: GLEngineContext, state: GLBlendState): void {\n if (engine._isLost || engine._disposed) {\n return;\n }\n applyBlend(engine, state.srcRGB, state.dstRGB, state.srcAlpha, state.dstAlpha, state.equationRGB ?? FUNC_ADD, state.equationAlpha ?? FUNC_ADD);\n}\n\n/**\n * Disable blending — the equivalent of Babylon's `AlphaState.alphaBlend = false`.\n * Records the desired \"blend off\" state (flushed by `applyGLStates` before the\n * next draw); the actual `gl.disable(gl.BLEND)` is elided when blending is\n * already off at flush time. No-op when the context is lost or disposed.\n *\n * @param engine - The engine whose desired blend state is updated.\n */\nexport function disableBlend(engine: GLEngineContext): void {\n if (engine._isLost || engine._disposed) {\n return;\n }\n const s = engine._state;\n s.rs[RS_BLEND_ENABLED + RS_DESIRED] = 0;\n s._flushBlend = flushBlend;\n s.statesDirty = true;\n}\n\n/* ──────────────────────────── internal apply ──────────────────────────── */\n\n/** Record a granular blend config into the DESIRED (`rs[RS_* + RS_DESIRED]`)\n * slots and mark it dirty. No `gl.*` here — `applyGLStates` reconciles\n * desired→actual at the next flush, caching the enable flag, equation and func\n * independently so each is re-issued only when its params change (and never on a\n * bare re-enable). */\nfunction applyBlend(engine: GLEngineContext, srcRGB: number, dstRGB: number, srcAlpha: number, dstAlpha: number, eqRGB: number, eqAlpha: number): void {\n const rs = engine._state.rs;\n rs[RS_BLEND_ENABLED + RS_DESIRED] = 1;\n rs[RS_BLEND_SRC_RGB + RS_DESIRED] = srcRGB;\n rs[RS_BLEND_DST_RGB + RS_DESIRED] = dstRGB;\n rs[RS_BLEND_SRC_A + RS_DESIRED] = srcAlpha;\n rs[RS_BLEND_DST_A + RS_DESIRED] = dstAlpha;\n rs[RS_BLEND_EQ_RGB + RS_DESIRED] = eqRGB;\n rs[RS_BLEND_EQ_A + RS_DESIRED] = eqAlpha;\n engine._state._flushBlend = flushBlend;\n engine._state.statesDirty = true;\n}\n\n/**\n * Reconcile the deferred blend state DESIRED → ACTUAL — the per-category half of\n * Babylon's `_alphaState.apply`. Installed onto `_state._flushBlend` by the blend\n * setters and dispatched by {@link applyGLStates}; co-located here so a scene that\n * never sets a blend mode tree-shakes both this reconciler and its GL code out of\n * the bundle.\n *\n * The enable flag, the equation and the func are reconciled as THREE independent\n * cached sub-states (mirroring Babylon's `_AlphaState` `_isAlphaBlendDirty` /\n * `_isBlendEquationParametersDirty` / `_isBlendFunctionParametersDirty`). GL\n * retains the blend equation + func across `gl.disable(BLEND)`, so their cached\n * actual values stay valid while blending is off — re-enabling with unchanged\n * params therefore issues ONLY `gl.enable(BLEND)` and re-issues neither\n * `blendEquationSeparate` nor `blendFuncSeparate`. A desired `-1` (never\n * requested) leaves GL untouched. @internal\n */\nfunction flushBlend(engine: GLEngineContext): void {\n const gl = engine.gl;\n const rs = engine._state.rs;\n const dBlend = rs[RS_BLEND_ENABLED + RS_DESIRED]!;\n if (dBlend === -1) {\n return;\n }\n // 1. enable / disable — independent of the func + equation cache below.\n if (dBlend !== rs[RS_BLEND_ENABLED]) {\n rs[RS_BLEND_ENABLED] = dBlend;\n if (dBlend === 1) {\n gl.enable(BLEND);\n } else {\n gl.disable(BLEND);\n }\n }\n // While blending is off the equation/func are not observable and GL keeps the\n // last values, so leave their cache untouched (Babylon does the same) — the\n // next enable with identical params then re-issues nothing.\n if (dBlend !== 1) {\n return;\n }\n // 2. equation — re-issued only when the params actually changed.\n const eqRGB = rs[RS_BLEND_EQ_RGB + RS_DESIRED]!;\n const eqA = rs[RS_BLEND_EQ_A + RS_DESIRED]!;\n if (rs[RS_BLEND_EQ_RGB] !== eqRGB || rs[RS_BLEND_EQ_A] !== eqA) {\n gl.blendEquationSeparate(eqRGB, eqA);\n rs[RS_BLEND_EQ_RGB] = eqRGB;\n rs[RS_BLEND_EQ_A] = eqA;\n }\n // 3. func — re-issued only when the params actually changed.\n const srcRGB = rs[RS_BLEND_SRC_RGB + RS_DESIRED]!;\n const dstRGB = rs[RS_BLEND_DST_RGB + RS_DESIRED]!;\n const srcA = rs[RS_BLEND_SRC_A + RS_DESIRED]!;\n const dstA = rs[RS_BLEND_DST_A + RS_DESIRED]!;\n if (rs[RS_BLEND_SRC_RGB] !== srcRGB || rs[RS_BLEND_DST_RGB] !== dstRGB || rs[RS_BLEND_SRC_A] !== srcA || rs[RS_BLEND_DST_A] !== dstA) {\n gl.blendFuncSeparate(srcRGB, dstRGB, srcA, dstA);\n rs[RS_BLEND_SRC_RGB] = srcRGB;\n rs[RS_BLEND_DST_RGB] = dstRGB;\n rs[RS_BLEND_SRC_A] = srcA;\n rs[RS_BLEND_DST_A] = dstA;\n }\n}\n"]}
1
+ {"version":3,"file":"blend.js","sourceRoot":"","sources":["../src/blend.ts"],"names":[],"mappings":"AAqBA,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,aAAa,EAAE,eAAe,EAAE,cAAc,EAAE,gBAAgB,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAE9J;;;GAGG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG;IACvB,wEAAwE;IACxE,OAAO,EAAE,CAAC;IACV,yFAAyF;IACzF,GAAG,EAAE,CAAC;IACN,sIAAsI;IACtI,KAAK,EAAE,CAAC;IACR,uHAAuH;IACvH,aAAa,EAAE,CAAC;CACV,CAAC;AAKX;;;;;GAKG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG;IAC3B,oCAAoC;IACpC,GAAG,EAAE,MAAM;IACX,mBAAmB;IACnB,QAAQ,EAAE,MAAM;IAChB,mBAAmB;IACnB,gBAAgB,EAAE,MAAM;IACxB,uBAAuB;IACvB,GAAG,EAAE,MAAM;IACX,uBAAuB;IACvB,GAAG,EAAE,MAAM;CACL,CAAC;AA2BX;mFACmF;AACnF,MAAM,QAAQ,GAAG,MAAM,CAAC;AACxB,qBAAqB;AACrB,MAAM,KAAK,GAAG,MAAM,CAAC;AAErB;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,YAAY,CAAC,MAAuB,EAAE,IAAiB;IACnE,IAAI,MAAM,CAAC,OAAO,IAAI,MAAM,CAAC,SAAS,EAAE,CAAC;QACrC,OAAO;IACX,CAAC;IACD,MAAM,EAAE,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,UAAU,CAAE,CAAC;IAC9C,IAAI,EAAE,CAAC,gBAAgB,CAAC,KAAK,MAAM,IAAI,EAAE,CAAC,gBAAgB,CAAC,KAAK,MAAM,IAAI,EAAE,CAAC,cAAc,CAAC,KAAK,IAAI,IAAI,EAAE,CAAC,cAAc,CAAC,KAAK,IAAI,EAAE,CAAC;QACnI,EAAE,CAAC,iBAAiB,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;QACjD,EAAE,CAAC,gBAAgB,CAAC,GAAG,MAAM,CAAC;QAC9B,EAAE,CAAC,gBAAgB,CAAC,GAAG,MAAM,CAAC;QAC9B,EAAE,CAAC,cAAc,CAAC,GAAG,IAAI,CAAC;QAC1B,EAAE,CAAC,cAAc,CAAC,GAAG,IAAI,CAAC;IAC9B,CAAC;AACL,CAAC","sourcesContent":["/**\n * Blend-mode state — the WebGL counterpart of Babylon's `Engine.setAlphaMode`\n * (presets) and `AlphaState.setAlphaBlendFunctionParameters` /\n * `setAlphaEquationParameters` (the arbitrary separate func + equation path).\n *\n * The numeric {@link GLBlendMode} values intentionally match Babylon's\n * `Constants.ALPHA_*` (`ALPHA_DISABLE = 0`, `ALPHA_ADD = 1`, `ALPHA_COMBINE = 2`,\n * `ALPHA_PREMULTIPLIED = 7`) so a consumer can forward raw Babylon constants\n * without a translation table.\n *\n * DEFERRED MODEL (matches Babylon's `AlphaState`): these setters do NOT touch\n * `gl.*`. They record only the DESIRED blend config into the `d*` mirror fields\n * of `GLState` and raise `statesDirty`; `applyGLStates` (apply-states.ts) flushes\n * the diff to GL right before each draw / clear. Setting blend A then B then A\n * with no draw in between therefore applies exactly one blend state (A), and a\n * blend left unchanged across frames re-issues nothing.\n *\n * Both {@link setBlendMode} and {@link setBlendState} feed the same desired\n * fields, so the preset and arbitrary paths can never desync.\n */\nimport { type GLEngineContext } from \"./context.js\";\nimport { RS_BLEND_DST_A, RS_BLEND_DST_RGB, RS_BLEND_ENABLED, RS_BLEND_EQ_A, RS_BLEND_EQ_RGB, RS_BLEND_SRC_A, RS_BLEND_SRC_RGB, RS_DESIRED } from \"./state.js\";\n\n/**\n * Supported blend presets. Values mirror Babylon's `Constants.ALPHA_*` so the\n * raw Babylon integers can be passed straight through.\n */\nexport const GLBlendMode = {\n /** No blending — `gl.disable(gl.BLEND)`. (`Constants.ALPHA_DISABLE`) */\n DISABLE: 0,\n /** Additive — `blendFuncSeparate(SRC_ALPHA, ONE, ZERO, ONE)`. (`Constants.ALPHA_ADD`) */\n ADD: 1,\n /** Standard (non-premultiplied) alpha — `blendFuncSeparate(SRC_ALPHA, ONE_MINUS_SRC_ALPHA, ONE, ONE)`. (`Constants.ALPHA_COMBINE`) */\n ALPHA: 2,\n /** Premultiplied alpha — `blendFuncSeparate(ONE, ONE_MINUS_SRC_ALPHA, ONE, ONE)`. (`Constants.ALPHA_PREMULTIPLIED`) */\n PREMULTIPLIED: 7,\n} as const;\n\n/** One of the {@link GLBlendMode} preset values (`0`, `1`, `2` or `7`). */\nexport type GLBlendMode = (typeof GLBlendMode)[keyof typeof GLBlendMode];\n\n/**\n * Blend equation presets — the values WebGL2 accepts for\n * `gl.blendEquationSeparate`. Numeric values equal the GL enums so raw GL\n * integers (or Babylon's identical `Constants.GL_ALPHA_EQUATION_*`) pass\n * straight through.\n */\nexport const GLBlendEquation = {\n /** `src + dst` (the GL default). */\n ADD: 0x8006,\n /** `src - dst`. */\n SUBTRACT: 0x800a,\n /** `dst - src`. */\n REVERSE_SUBTRACT: 0x800b,\n /** `min(src, dst)`. */\n MIN: 0x8007,\n /** `max(src, dst)`. */\n MAX: 0x8008,\n} as const;\n\n/** One of the {@link GLBlendEquation} preset values. */\nexport type GLBlendEquation = (typeof GLBlendEquation)[keyof typeof GLBlendEquation];\n\n/**\n * Arbitrary separate-channel blend configuration — the lite-gl equivalent of\n * Babylon's `AlphaState.setAlphaBlendFunctionParameters` +\n * `setAlphaEquationParameters`. All factor / equation fields are raw WebGL2\n * enums (`gl.ONE`, `gl.SRC_ALPHA`, `gl.MIN`, …); use {@link GLBlendEquation} for\n * the equations if you prefer named presets.\n */\nexport interface GLBlendState {\n /** RGB source factor (`gl.blendFuncSeparate` arg 1). */\n srcRGB: GLenum;\n /** RGB destination factor (`gl.blendFuncSeparate` arg 2). */\n dstRGB: GLenum;\n /** Alpha source factor (`gl.blendFuncSeparate` arg 3). */\n srcAlpha: GLenum;\n /** Alpha destination factor (`gl.blendFuncSeparate` arg 4). */\n dstAlpha: GLenum;\n /** RGB blend equation. Defaults to `FUNC_ADD`. */\n equationRGB?: GLenum;\n /** Alpha blend equation. Defaults to `FUNC_ADD`. */\n equationAlpha?: GLenum;\n}\n\n/** GL `FUNC_ADD` — the implicit equation used by the {@link GLBlendMode}\n * presets (matching Babylon's `setAlphaMode`, which leaves it at the default). */\nconst FUNC_ADD = 0x8006;\n/** GL `gl.BLEND`. */\nconst BLEND = 0x0be2;\n\n/**\n * Set the GL blend state to match Babylon's `setAlphaMode(mode)` exactly.\n *\n * | Mode | `gl.blendFuncSeparate(srcRGB, dstRGB, srcA, dstA)` |\n * |--------------------|------------------------------------------------------------|\n * | `DISABLE` (0) | — (`gl.disable(gl.BLEND)`) |\n * | `ADD` (1) | `SRC_ALPHA, ONE, ZERO, ONE` |\n * | `ALPHA` (2) | `SRC_ALPHA, ONE_MINUS_SRC_ALPHA, ONE, ONE` |\n * | `PREMULTIPLIED` (7)| `ONE, ONE_MINUS_SRC_ALPHA, ONE, ONE` |\n *\n * No-op when the context is lost or disposed.\n *\n * @param engine - The engine whose GL blend state is updated.\n * @param mode - The {@link GLBlendMode} preset to apply.\n */\nexport function setBlendMode(engine: GLEngineContext, mode: GLBlendMode): void {\n if (engine._isLost || engine._disposed) {\n return;\n }\n const gl = engine.gl;\n switch (mode) {\n case GLBlendMode.DISABLE:\n disableBlend(engine);\n return;\n case GLBlendMode.ADD:\n applyBlend(engine, gl.SRC_ALPHA, gl.ONE, gl.ZERO, gl.ONE, FUNC_ADD, FUNC_ADD);\n return;\n case GLBlendMode.ALPHA:\n applyBlend(engine, gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE, FUNC_ADD, FUNC_ADD);\n return;\n case GLBlendMode.PREMULTIPLIED:\n applyBlend(engine, gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE, FUNC_ADD, FUNC_ADD);\n return;\n }\n}\n\n/**\n * Enable blending with an arbitrary separate-channel function and equation —\n * the lite-gl equivalent of Babylon's `AlphaState` with\n * `setAlphaBlendFunctionParameters` + `setAlphaEquationParameters`.\n *\n * Supports every WebGL2 blend equation, including `MIN`, `MAX`,\n * `FUNC_SUBTRACT` and `FUNC_REVERSE_SUBTRACT` (e.g. for darken /\n * cutout blend modes). Records the desired config (flushed by `applyGLStates`\n * before the next draw); at flush time the enable flag, the equation and the func\n * are each cached independently, so a redundant state is fully elided and only\n * the call whose params changed is re-issued — mirroring Babylon's `AlphaState`\n * dirty flags. Because GL keeps the equation + func across `gl.disable(BLEND)`,\n * re-enabling with unchanged params re-issues neither.\n *\n * No-op when the context is lost or disposed.\n *\n * @param engine - The engine whose desired blend state is updated.\n * @param state - The separate-channel blend factors + equations to apply.\n */\nexport function setBlendState(engine: GLEngineContext, state: GLBlendState): void {\n if (engine._isLost || engine._disposed) {\n return;\n }\n applyBlend(engine, state.srcRGB, state.dstRGB, state.srcAlpha, state.dstAlpha, state.equationRGB ?? FUNC_ADD, state.equationAlpha ?? FUNC_ADD);\n}\n\n/**\n * Disable blending — the equivalent of Babylon's `AlphaState.alphaBlend = false`.\n * Records the desired \"blend off\" state (flushed by `applyGLStates` before the\n * next draw); the actual `gl.disable(gl.BLEND)` is elided when blending is\n * already off at flush time. No-op when the context is lost or disposed.\n *\n * @param engine - The engine whose desired blend state is updated.\n */\nexport function disableBlend(engine: GLEngineContext): void {\n if (engine._isLost || engine._disposed) {\n return;\n }\n const s = engine._state;\n s.rs[RS_BLEND_ENABLED + RS_DESIRED] = 0;\n s._flushBlend = flushBlend;\n s.statesDirty = true;\n}\n\n/* ──────────────────────────── internal apply ──────────────────────────── */\n\n/** Record a granular blend config into the DESIRED (`rs[RS_* + RS_DESIRED]`)\n * slots and mark it dirty. No `gl.*` here — `applyGLStates` reconciles\n * desired→actual at the next flush, caching the enable flag, equation and func\n * independently so each is re-issued only when its params change (and never on a\n * bare re-enable). */\nfunction applyBlend(engine: GLEngineContext, srcRGB: number, dstRGB: number, srcAlpha: number, dstAlpha: number, eqRGB: number, eqAlpha: number): void {\n const rs = engine._state.rs;\n rs[RS_BLEND_ENABLED + RS_DESIRED] = 1;\n rs[RS_BLEND_SRC_RGB + RS_DESIRED] = srcRGB;\n rs[RS_BLEND_DST_RGB + RS_DESIRED] = dstRGB;\n rs[RS_BLEND_SRC_A + RS_DESIRED] = srcAlpha;\n rs[RS_BLEND_DST_A + RS_DESIRED] = dstAlpha;\n rs[RS_BLEND_EQ_RGB + RS_DESIRED] = eqRGB;\n rs[RS_BLEND_EQ_A + RS_DESIRED] = eqAlpha;\n engine._state._flushBlend = flushBlend;\n engine._state.statesDirty = true;\n}\n\n/**\n * Reconcile the deferred blend state DESIRED → ACTUAL — the per-category half of\n * Babylon's `_alphaState.apply`. Installed onto `_state._flushBlend` by the blend\n * setters and dispatched by {@link applyGLStates}; co-located here so a scene that\n * never sets a blend mode tree-shakes both this reconciler and its GL code out of\n * the bundle.\n *\n * The enable flag, the equation and the func are reconciled as THREE independent\n * cached sub-states (mirroring Babylon's `_AlphaState` `_isAlphaBlendDirty` /\n * `_isBlendEquationParametersDirty` / `_isBlendFunctionParametersDirty`). GL\n * retains the blend equation + func across `gl.disable(BLEND)`, so their cached\n * actual values stay valid while blending is off — re-enabling with unchanged\n * params therefore issues ONLY `gl.enable(BLEND)` and re-issues neither\n * `blendEquationSeparate` nor `blendFuncSeparate`. A desired `-1` (never\n * requested) leaves GL untouched. @internal\n */\nfunction flushBlend(engine: GLEngineContext): void {\n const gl = engine.gl;\n const rs = engine._state.rs;\n const dBlend = rs[RS_BLEND_ENABLED + RS_DESIRED]!;\n if (dBlend === -1) {\n return;\n }\n // 1. enable / disable — independent of the func + equation cache below.\n if (dBlend !== rs[RS_BLEND_ENABLED]) {\n rs[RS_BLEND_ENABLED] = dBlend;\n if (dBlend === 1) {\n gl.enable(BLEND);\n } else {\n gl.disable(BLEND);\n }\n }\n // While blending is off the equation/func are not observable and GL keeps the\n // last values, so leave their cache untouched (Babylon does the same) — the\n // next enable with identical params then re-issues nothing.\n if (dBlend !== 1) {\n return;\n }\n // 2. equation — re-issued only when the params actually changed.\n const eqRGB = rs[RS_BLEND_EQ_RGB + RS_DESIRED]!;\n const eqA = rs[RS_BLEND_EQ_A + RS_DESIRED]!;\n if (rs[RS_BLEND_EQ_RGB] !== eqRGB || rs[RS_BLEND_EQ_A] !== eqA) {\n gl.blendEquationSeparate(eqRGB, eqA);\n rs[RS_BLEND_EQ_RGB] = eqRGB;\n rs[RS_BLEND_EQ_A] = eqA;\n }\n // 3. func — re-issued only when the params actually changed.\n const srcRGB = rs[RS_BLEND_SRC_RGB + RS_DESIRED]!;\n const dstRGB = rs[RS_BLEND_DST_RGB + RS_DESIRED]!;\n const srcA = rs[RS_BLEND_SRC_A + RS_DESIRED]!;\n const dstA = rs[RS_BLEND_DST_A + RS_DESIRED]!;\n if (rs[RS_BLEND_SRC_RGB] !== srcRGB || rs[RS_BLEND_DST_RGB] !== dstRGB || rs[RS_BLEND_SRC_A] !== srcA || rs[RS_BLEND_DST_A] !== dstA) {\n gl.blendFuncSeparate(srcRGB, dstRGB, srcA, dstA);\n rs[RS_BLEND_SRC_RGB] = srcRGB;\n rs[RS_BLEND_DST_RGB] = dstRGB;\n rs[RS_BLEND_SRC_A] = srcA;\n rs[RS_BLEND_DST_A] = dstA;\n }\n}\n"]}
package/context.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { GLRenderTarget } from "./render-target.js";
1
2
  /** Constructor options forwarded to `canvas.getContext('webgl2', …)`. */
2
3
  export interface GLEngineOptions {
3
4
  /** Default: true. */
@@ -70,8 +71,30 @@ export interface GLEngineContext {
70
71
  /** Acquire a WebGL2 context on the canvas and build the pure-state handle.
71
72
  * Accepts an `HTMLCanvasElement` or an `OffscreenCanvas` (worker render paths —
72
73
  * e.g. the Lottie player — which size the drawing buffer via `setGLEngineSize`).
73
- * Throws if WebGL2 is unsupported. */
74
+ * Throws if WebGL2 is unsupported. Resources recover automatically after
75
+ * context loss; use `createHostOwnedGLEngine` when the host recreates instead. */
74
76
  export declare function createGLEngine(canvas: HTMLCanvasElement | OffscreenCanvas, options?: GLEngineOptions): GLEngineContext;
77
+ /**
78
+ * Create an engine whose context-loss recovery is owned by the host, matching
79
+ * ThinEngine's `doNotHandleContextLost: true`. Same canvas/options contract as
80
+ * {@link createGLEngine}, except:
81
+ * - `webglcontextlost` still stops rendering, marks the engine lost and fires
82
+ * `onContextLost` callbacks, but never calls `preventDefault()`, so the
83
+ * browser does not restore the context; `onContextRestored` never fires;
84
+ * - resources created on this engine retain no CPU replay sources (buffer
85
+ * data, texture pixels, sprite indices) and install no restore hooks,
86
+ * saving memory. Effects still keep their public `options` (including the
87
+ * shader sources) and source-derived cache key, which serve readiness
88
+ * diagnostics and effect deduplication rather than replay.
89
+ *
90
+ * After a loss the engine stays lost: dispose it and recreate the engine and
91
+ * every resource (on a fresh canvas or once the host has a new context).
92
+ *
93
+ * @param canvas - An `HTMLCanvasElement` or `OffscreenCanvas`.
94
+ * @param options - WebGL2 context attributes, as for {@link createGLEngine}.
95
+ * @returns The engine. Throws if WebGL2 is unsupported.
96
+ */
97
+ export declare function createHostOwnedGLEngine(canvas: HTMLCanvasElement | OffscreenCanvas, options?: GLEngineOptions): GLEngineContext;
75
98
  /** Stops the render loop, removes DOM listeners, releases all known effects
76
99
  * and textures, then marks the context disposed. The browser-owned canvas
77
100
  * is left intact. */
@@ -105,15 +128,39 @@ export declare function setGLEngineSize(engine: GLEngineContext, width: number,
105
128
  * skip the state changes needed to re-establish the scope, producing corrupted
106
129
  * output. Owned GPU resources (the shared quad, render targets, meshes,
107
130
  * effects, textures) are preserved — only the cached "current GL state" is
108
- * reset. Mirrors Babylon's `Engine.wipeCaches()`.
131
+ * reset. Mirrors Babylon's `Engine.wipeCaches(bruteForce)`.
132
+ *
133
+ * After a wipe the VAO / framebuffer bindings are UNKNOWN (not assumed to be
134
+ * the defaults), so the next mesh / render-target call rebinds them even if the
135
+ * host left its own objects bound. The current program is forgotten: call
136
+ * `useEffect` again before drawing.
137
+ *
138
+ * `bruteForce` additionally normalizes, with raw GL calls, state lite-gl relies
139
+ * on but never caches, back to WebGL2 defaults: the default VAO with every
140
+ * vertex attribute array disabled, sampler objects unbound from every texture
141
+ * unit, no `PIXEL_PACK` / `PIXEL_UNPACK` buffer, zero pack / unpack row and
142
+ * skip layout, browser-default unpack colorspace conversion, `frontFace(CCW)`,
143
+ * `depthRange(0, 1)`, `clearDepth(1)`, `clearStencil(0)`, `blendColor(0, 0, 0, 0)`
144
+ * and `POLYGON_OFFSET_FILL` / `RASTERIZER_DISCARD` / `SAMPLE_COVERAGE` /
145
+ * `SAMPLE_ALPHA_TO_COVERAGE` disabled. Use it when the host may leave arbitrary
146
+ * state behind (it costs roughly `MAX_VERTEX_ATTRIBS + maxTextureUnits + 20`
147
+ * GL calls); per-draw hand-offs with a known host should prefer the plain wipe
148
+ * plus targeted resets.
109
149
  *
110
150
  * No-op while the context is lost or the engine is disposed.
151
+ *
152
+ * @param engine - The engine.
153
+ * @param bruteForce - Also normalize untracked GL state (see above). Default `false`.
111
154
  */
112
- export declare function wipeGLStateCache(engine: GLEngineContext): void;
155
+ export declare function wipeGLStateCache(engine: GLEngineContext, bruteForce?: boolean): void;
113
156
  /** Drawing-buffer width in physical pixels (`canvas.width`). */
114
157
  export declare function getRenderWidth(engine: GLEngineContext): number;
115
158
  /** Drawing-buffer height in physical pixels (`canvas.height`). */
116
159
  export declare function getRenderHeight(engine: GLEngineContext): number;
160
+ /** Number of live sampled textures managed by the context. */
161
+ export declare function getTextureCount(engine: GLEngineContext): number;
162
+ /** Current drawing target, or null for the canvas framebuffer. */
163
+ export declare function getCurrentRenderTarget(engine: GLEngineContext): GLRenderTarget | null;
117
164
  /** Current hardware-scaling factor — drawing-buffer = clientSize × dpr / level. */
118
165
  export declare function getHardwareScalingLevel(engine: GLEngineContext): number;
119
166
  /** Updates the hardware-scaling factor and triggers a resize. */
@@ -125,7 +172,8 @@ export declare function getRenderingCanvas(engine: GLEngineContext): HTMLCanvasE
125
172
  export declare function onContextLost(engine: GLEngineContext, cb: () => void): void;
126
173
  /** Remove a previously-registered context-lost callback. */
127
174
  export declare function offContextLost(engine: GLEngineContext, cb: () => void): void;
128
- /** Register a `webglcontextrestored` callback. Duplicate registrations are ignored. */
175
+ /** Register an automatic `webglcontextrestored` callback. Never fires on an
176
+ * engine from `createHostOwnedGLEngine`. Duplicate registrations are ignored. */
129
177
  export declare function onContextRestored(engine: GLEngineContext, cb: () => void): void;
130
178
  /** Remove a previously-registered context-restored callback. */
131
179
  export declare function offContextRestored(engine: GLEngineContext, cb: () => void): void;
package/context.js CHANGED
@@ -2,7 +2,8 @@ import { createGLState, resetGLState, resetGLStateCache } from "./state.js";
2
2
  /** Acquire a WebGL2 context on the canvas and build the pure-state handle.
3
3
  * Accepts an `HTMLCanvasElement` or an `OffscreenCanvas` (worker render paths —
4
4
  * e.g. the Lottie player — which size the drawing buffer via `setGLEngineSize`).
5
- * Throws if WebGL2 is unsupported. */
5
+ * Throws if WebGL2 is unsupported. Resources recover automatically after
6
+ * context loss; use `createHostOwnedGLEngine` when the host recreates instead. */
6
7
  export function createGLEngine(canvas, options) {
7
8
  const o = options ?? {};
8
9
  const attrs = {
@@ -39,17 +40,44 @@ export function createGLEngine(canvas, options) {
39
40
  _onRestored: [],
40
41
  _isLost: false,
41
42
  _disposed: false,
42
- _lostHandler: () => { },
43
- _restoredHandler: () => { },
43
+ _lostHandler: (e) => handleContextLost(engine, e),
44
+ _restoredHandler: () => handleContextRestored(engine),
44
45
  _wasLoopActive: false,
45
46
  _scheduleFrame: null,
46
47
  };
47
- engine._lostHandler = (e) => handleContextLost(engine, e);
48
- engine._restoredHandler = () => handleContextRestored(engine);
49
48
  canvas.addEventListener("webglcontextlost", engine._lostHandler, false);
50
49
  canvas.addEventListener("webglcontextrestored", engine._restoredHandler, false);
51
50
  return engine;
52
51
  }
52
+ /**
53
+ * Create an engine whose context-loss recovery is owned by the host, matching
54
+ * ThinEngine's `doNotHandleContextLost: true`. Same canvas/options contract as
55
+ * {@link createGLEngine}, except:
56
+ * - `webglcontextlost` still stops rendering, marks the engine lost and fires
57
+ * `onContextLost` callbacks, but never calls `preventDefault()`, so the
58
+ * browser does not restore the context; `onContextRestored` never fires;
59
+ * - resources created on this engine retain no CPU replay sources (buffer
60
+ * data, texture pixels, sprite indices) and install no restore hooks,
61
+ * saving memory. Effects still keep their public `options` (including the
62
+ * shader sources) and source-derived cache key, which serve readiness
63
+ * diagnostics and effect deduplication rather than replay.
64
+ *
65
+ * After a loss the engine stays lost: dispose it and recreate the engine and
66
+ * every resource (on a fresh canvas or once the host has a new context).
67
+ *
68
+ * @param canvas - An `HTMLCanvasElement` or `OffscreenCanvas`.
69
+ * @param options - WebGL2 context attributes, as for {@link createGLEngine}.
70
+ * @returns The engine. Throws if WebGL2 is unsupported.
71
+ */
72
+ export function createHostOwnedGLEngine(canvas, options) {
73
+ const engine = createGLEngine(canvas, options);
74
+ engine._noRestore = true;
75
+ canvas.removeEventListener("webglcontextlost", engine._lostHandler, false);
76
+ canvas.removeEventListener("webglcontextrestored", engine._restoredHandler, false);
77
+ engine._lostHandler = () => handleContextLost(engine);
78
+ canvas.addEventListener("webglcontextlost", engine._lostHandler, false);
79
+ return engine;
80
+ }
53
81
  /** Stops the render loop, removes DOM listeners, releases all known effects
54
82
  * and textures, then marks the context disposed. The browser-owned canvas
55
83
  * is left intact. */
@@ -105,6 +133,7 @@ export function disposeGLEngine(engine) {
105
133
  if (!buf._disposed) {
106
134
  buf._disposed = true;
107
135
  buf._deleteGpu(gl);
136
+ buf._data = buf._restore = undefined;
108
137
  }
109
138
  }
110
139
  engine._buffers.length = 0;
@@ -175,21 +204,80 @@ export function setGLEngineSize(engine, width, height) {
175
204
  * skip the state changes needed to re-establish the scope, producing corrupted
176
205
  * output. Owned GPU resources (the shared quad, render targets, meshes,
177
206
  * effects, textures) are preserved — only the cached "current GL state" is
178
- * reset. Mirrors Babylon's `Engine.wipeCaches()`.
207
+ * reset. Mirrors Babylon's `Engine.wipeCaches(bruteForce)`.
208
+ *
209
+ * After a wipe the VAO / framebuffer bindings are UNKNOWN (not assumed to be
210
+ * the defaults), so the next mesh / render-target call rebinds them even if the
211
+ * host left its own objects bound. The current program is forgotten: call
212
+ * `useEffect` again before drawing.
213
+ *
214
+ * `bruteForce` additionally normalizes, with raw GL calls, state lite-gl relies
215
+ * on but never caches, back to WebGL2 defaults: the default VAO with every
216
+ * vertex attribute array disabled, sampler objects unbound from every texture
217
+ * unit, no `PIXEL_PACK` / `PIXEL_UNPACK` buffer, zero pack / unpack row and
218
+ * skip layout, browser-default unpack colorspace conversion, `frontFace(CCW)`,
219
+ * `depthRange(0, 1)`, `clearDepth(1)`, `clearStencil(0)`, `blendColor(0, 0, 0, 0)`
220
+ * and `POLYGON_OFFSET_FILL` / `RASTERIZER_DISCARD` / `SAMPLE_COVERAGE` /
221
+ * `SAMPLE_ALPHA_TO_COVERAGE` disabled. Use it when the host may leave arbitrary
222
+ * state behind (it costs roughly `MAX_VERTEX_ATTRIBS + maxTextureUnits + 20`
223
+ * GL calls); per-draw hand-offs with a known host should prefer the plain wipe
224
+ * plus targeted resets.
179
225
  *
180
226
  * No-op while the context is lost or the engine is disposed.
227
+ *
228
+ * @param engine - The engine.
229
+ * @param bruteForce - Also normalize untracked GL state (see above). Default `false`.
181
230
  */
182
- export function wipeGLStateCache(engine) {
231
+ export function wipeGLStateCache(engine, bruteForce = false) {
183
232
  if (engine._disposed || engine._isLost) {
184
233
  return;
185
234
  }
186
- resetGLStateCache(engine._state);
235
+ const s = engine._state;
236
+ resetGLStateCache(s);
237
+ // Brute force disables every attribute array below; a plain wipe leaves
238
+ // host-enabled arrays unknown (ThinEngine's `_mustWipeVertexAttributes`).
239
+ s._unknownAttribs = !bruteForce;
187
240
  const invalidators = engine._stateCacheInvalidators;
188
241
  if (invalidators) {
189
242
  for (const invalidate of invalidators) {
190
243
  invalidate();
191
244
  }
192
245
  }
246
+ if (bruteForce) {
247
+ const gl = engine.gl;
248
+ gl.bindVertexArray(null);
249
+ s.boundVao = null;
250
+ const attribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
251
+ for (let i = 0; i < attribs; i++) {
252
+ gl.disableVertexAttribArray(i);
253
+ }
254
+ for (let u = 0; u < s.boundTextures.length; u++) {
255
+ gl.bindSampler(u, null);
256
+ }
257
+ gl.bindBuffer(gl.PIXEL_UNPACK_BUFFER, null);
258
+ gl.bindBuffer(gl.PIXEL_PACK_BUFFER, null);
259
+ for (const p of [
260
+ gl.UNPACK_ROW_LENGTH,
261
+ gl.UNPACK_IMAGE_HEIGHT,
262
+ gl.UNPACK_SKIP_PIXELS,
263
+ gl.UNPACK_SKIP_ROWS,
264
+ gl.UNPACK_SKIP_IMAGES,
265
+ gl.PACK_ROW_LENGTH,
266
+ gl.PACK_SKIP_PIXELS,
267
+ gl.PACK_SKIP_ROWS,
268
+ ]) {
269
+ gl.pixelStorei(p, 0);
270
+ }
271
+ gl.pixelStorei(gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.BROWSER_DEFAULT_WEBGL);
272
+ gl.frontFace(gl.CCW);
273
+ gl.depthRange(0, 1);
274
+ gl.clearDepth(1);
275
+ gl.clearStencil(0);
276
+ gl.blendColor(0, 0, 0, 0);
277
+ for (const cap of [gl.POLYGON_OFFSET_FILL, gl.RASTERIZER_DISCARD, gl.SAMPLE_COVERAGE, gl.SAMPLE_ALPHA_TO_COVERAGE]) {
278
+ gl.disable(cap);
279
+ }
280
+ }
193
281
  }
194
282
  /** Drawing-buffer width in physical pixels (`canvas.width`). */
195
283
  export function getRenderWidth(engine) {
@@ -199,6 +287,14 @@ export function getRenderWidth(engine) {
199
287
  export function getRenderHeight(engine) {
200
288
  return engine.canvas.height;
201
289
  }
290
+ /** Number of live sampled textures managed by the context. */
291
+ export function getTextureCount(engine) {
292
+ return engine._textures.size;
293
+ }
294
+ /** Current drawing target, or null for the canvas framebuffer. */
295
+ export function getCurrentRenderTarget(engine) {
296
+ return engine._currentRenderTarget;
297
+ }
202
298
  /** Current hardware-scaling factor — drawing-buffer = clientSize × dpr / level. */
203
299
  export function getHardwareScalingLevel(engine) {
204
300
  return engine._hsl;
@@ -229,7 +325,8 @@ export function offContextLost(engine, cb) {
229
325
  engine._onLost.splice(i, 1);
230
326
  }
231
327
  }
232
- /** Register a `webglcontextrestored` callback. Duplicate registrations are ignored. */
328
+ /** Register an automatic `webglcontextrestored` callback. Never fires on an
329
+ * engine from `createHostOwnedGLEngine`. Duplicate registrations are ignored. */
233
330
  export function onContextRestored(engine, cb) {
234
331
  if (engine._onRestored.indexOf(cb) === -1) {
235
332
  engine._onRestored.push(cb);
@@ -245,8 +342,8 @@ export function offContextRestored(engine, cb) {
245
342
  /* ───────────────────────── internal: loss / restore ───────────────────── */
246
343
  function handleContextLost(engine, e) {
247
344
  // Opt-in to restore. Without preventDefault() the browser will NOT fire
248
- // webglcontextrestored later.
249
- e.preventDefault();
345
+ // webglcontextrestored later. Host-owned engines pass no event.
346
+ e?.preventDefault();
250
347
  if (engine._isLost || engine._disposed) {
251
348
  return;
252
349
  }