@babylonjs/addons 9.25.0 → 9.26.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 (46) hide show
  1. package/index.d.ts +1 -0
  2. package/index.js +1 -0
  3. package/index.js.map +1 -1
  4. package/multiTexture/Shaders/multiTextureCompositeAdd.fragment.d.ts +5 -0
  5. package/multiTexture/Shaders/multiTextureCompositeAdd.fragment.js +13 -0
  6. package/multiTexture/Shaders/multiTextureCompositeAdd.fragment.js.map +1 -0
  7. package/multiTexture/Shaders/multiTextureCompositeAlphaBlend.fragment.d.ts +5 -0
  8. package/multiTexture/Shaders/multiTextureCompositeAlphaBlend.fragment.js +19 -0
  9. package/multiTexture/Shaders/multiTextureCompositeAlphaBlend.fragment.js.map +1 -0
  10. package/multiTexture/Shaders/multiTextureCompositeAlphaMax.fragment.d.ts +5 -0
  11. package/multiTexture/Shaders/multiTextureCompositeAlphaMax.fragment.js +13 -0
  12. package/multiTexture/Shaders/multiTextureCompositeAlphaMax.fragment.js.map +1 -0
  13. package/multiTexture/Shaders/multiTextureCompositeMultiply.fragment.d.ts +5 -0
  14. package/multiTexture/Shaders/multiTextureCompositeMultiply.fragment.js +13 -0
  15. package/multiTexture/Shaders/multiTextureCompositeMultiply.fragment.js.map +1 -0
  16. package/multiTexture/Shaders/multiTextureCompositeScreen.fragment.d.ts +5 -0
  17. package/multiTexture/Shaders/multiTextureCompositeScreen.fragment.js +13 -0
  18. package/multiTexture/Shaders/multiTextureCompositeScreen.fragment.js.map +1 -0
  19. package/multiTexture/Shaders/multiTextureCompositeSubtract.fragment.d.ts +5 -0
  20. package/multiTexture/Shaders/multiTextureCompositeSubtract.fragment.js +13 -0
  21. package/multiTexture/Shaders/multiTextureCompositeSubtract.fragment.js.map +1 -0
  22. package/multiTexture/ShadersWGSL/multiTextureCompositeAdd.fragment.d.ts +5 -0
  23. package/multiTexture/ShadersWGSL/multiTextureCompositeAdd.fragment.js +17 -0
  24. package/multiTexture/ShadersWGSL/multiTextureCompositeAdd.fragment.js.map +1 -0
  25. package/multiTexture/ShadersWGSL/multiTextureCompositeAlphaBlend.fragment.d.ts +5 -0
  26. package/multiTexture/ShadersWGSL/multiTextureCompositeAlphaBlend.fragment.js +23 -0
  27. package/multiTexture/ShadersWGSL/multiTextureCompositeAlphaBlend.fragment.js.map +1 -0
  28. package/multiTexture/ShadersWGSL/multiTextureCompositeAlphaMax.fragment.d.ts +5 -0
  29. package/multiTexture/ShadersWGSL/multiTextureCompositeAlphaMax.fragment.js +17 -0
  30. package/multiTexture/ShadersWGSL/multiTextureCompositeAlphaMax.fragment.js.map +1 -0
  31. package/multiTexture/ShadersWGSL/multiTextureCompositeMultiply.fragment.d.ts +5 -0
  32. package/multiTexture/ShadersWGSL/multiTextureCompositeMultiply.fragment.js +16 -0
  33. package/multiTexture/ShadersWGSL/multiTextureCompositeMultiply.fragment.js.map +1 -0
  34. package/multiTexture/ShadersWGSL/multiTextureCompositeScreen.fragment.d.ts +5 -0
  35. package/multiTexture/ShadersWGSL/multiTextureCompositeScreen.fragment.js +17 -0
  36. package/multiTexture/ShadersWGSL/multiTextureCompositeScreen.fragment.js.map +1 -0
  37. package/multiTexture/ShadersWGSL/multiTextureCompositeSubtract.fragment.d.ts +5 -0
  38. package/multiTexture/ShadersWGSL/multiTextureCompositeSubtract.fragment.js +17 -0
  39. package/multiTexture/ShadersWGSL/multiTextureCompositeSubtract.fragment.js.map +1 -0
  40. package/multiTexture/index.d.ts +1 -0
  41. package/multiTexture/index.js +2 -0
  42. package/multiTexture/index.js.map +1 -0
  43. package/multiTexture/multiTexture.d.ts +346 -0
  44. package/multiTexture/multiTexture.js +1051 -0
  45. package/multiTexture/multiTexture.js.map +1 -0
  46. package/package.json +2 -2
@@ -0,0 +1,1051 @@
1
+ /**
2
+ * MultiTexture: composes an array of image files into a single TEXTURE_2D_ARRAY that can be
3
+ * assigned to a material slot like any other texture.
4
+ *
5
+ * Lives in @babylonjs/addons (not core) because it is an application-oriented, optional feature
6
+ * with WebGL2/WebGPU requirements, URL polling, and a non-trivial memory footprint.
7
+ */
8
+ import { Constants } from "@babylonjs/core/Engines/constants.js";
9
+ // Import the side-effect-free registration functions (the .pure variants), not the non-pure
10
+ // wrappers: a wrapper runs its top-level registration at module load, which would eagerly mutate
11
+ // the engine prototypes for every @babylonjs/addons consumer and double-register with the lazy
12
+ // call below. RegisterMultiTexture() invokes them lazily on first MultiTexture construction.
13
+ import { RegisterEnginesExtensionsEngineTexture2DArrayImageSource } from "@babylonjs/core/Engines/Extensions/engine.texture2DArrayImageSource.pure.js";
14
+ import { RegisterEnginesWebGPUExtensionsEngineTexture2DArrayImageSource } from "@babylonjs/core/Engines/WebGPU/Extensions/engine.texture2DArrayImageSource.pure.js";
15
+ import { Logger } from "@babylonjs/core/Misc/logger.js";
16
+ import { Observable } from "@babylonjs/core/Misc/observable.js";
17
+ import { BaseTexture } from "@babylonjs/core/Materials/Textures/baseTexture.pure.js";
18
+ import { ProceduralTexture } from "@babylonjs/core/Materials/Textures/Procedurals/proceduralTexture.pure.js";
19
+ import { RawTexture2DArray } from "@babylonjs/core/Materials/Textures/rawTexture2DArray.js";
20
+ import { UploadImageToTexture2DArrayLayer } from "@babylonjs/core/Materials/Textures/rawTexture2DArray.functions.js";
21
+ import { Texture } from "@babylonjs/core/Materials/Textures/texture.pure.js";
22
+ /** Composite fragment shader name per blend mode (index aligned with MultiBlendMode). */
23
+ const FRAGMENT_NAMES = [
24
+ "multiTextureCompositeAlphaBlend",
25
+ "multiTextureCompositeAlphaMax",
26
+ "multiTextureCompositeAdd",
27
+ "multiTextureCompositeMultiply",
28
+ "multiTextureCompositeSubtract",
29
+ "multiTextureCompositeScreen",
30
+ ];
31
+ /** Defines flag token per blend mode (index aligned with MultiBlendMode). Cache key only - referenced by no shader line. */
32
+ const MODE_FLAGS = ["ALPHA_BLEND", "ALPHA_MAX", "ADD", "MULTIPLY", "SUBTRACT", "SCREEN"];
33
+ /** Maximum number of in-flight decodes during initialization and watch polling. */
34
+ const DECODE_CONCURRENCY = 4;
35
+ /** Default watch-mode poll interval in milliseconds when options.pollInterval is omitted. */
36
+ const DEFAULT_POLL_INTERVAL_MS = 2000;
37
+ let _Registered = false;
38
+ /**
39
+ * Register side effects for MultiTexture.
40
+ * Registers the core 2D-array image-source extensions for both backends (the WebGL2
41
+ * `engine.texture2DArrayImageSource` and its WebGPU counterpart) lazily at first use, matching
42
+ * the Atmosphere addon's convention. Safe to call multiple times; only the first call has an effect.
43
+ */
44
+ export function RegisterMultiTexture() {
45
+ if (_Registered) {
46
+ return;
47
+ }
48
+ _Registered = true;
49
+ RegisterEnginesExtensionsEngineTexture2DArrayImageSource();
50
+ RegisterEnginesWebGPUExtensionsEngineTexture2DArrayImageSource();
51
+ }
52
+ /**
53
+ * Composes an array of image files into a single TEXTURE_2D_ARRAY and blends the layers per pixel
54
+ * according to a selectable {@link MultiBlendMode}. The blended result is written to a render-target
55
+ * texture that can be assigned to materials like any other texture.
56
+ *
57
+ * Requires a WebGL2 or WebGPU engine (TEXTURE_2D_ARRAY + sampler2DArray). The constructor throws
58
+ * synchronously on WebGL1.
59
+ *
60
+ * Supported source formats are the raster formats your browser can decode with createImageBitmap
61
+ * (PNG, JPEG, WebP, AVIF, GIF first frame, BMP). Compressed/container formats such as KTX2 are NOT
62
+ * supported: the existing KTX2 transcode path goes straight to the GPU (which would bypass the
63
+ * CPU pixel cache this class maintains), and KTX2 containers hold the whole array in a single file
64
+ * (which conflicts with the one-file-per-layer-index update model).
65
+ *
66
+ * Notes:
67
+ * - `url` is null (the base texture loader is not used); the `urls` property is the source of truth.
68
+ * - By default every decoded layer is read back into a CPU `Uint8ClampedArray` (see `pixels`). This
69
+ * costs one canvas readback (and a full-width×height RGBA CPU copy) per (re)load of a layer — it
70
+ * runs on every initial load, `updateLayerAsync` reload, and watch-triggered reload, so frequent
71
+ * reloads or large layers carry a CPU/memory cost (roughly `width × height × 4` bytes per layer).
72
+ * - With `premultiplyAlpha: true` the GPU layers are stored premultiplied, but the CPU `pixels`
73
+ * cache still holds the raw decoded (non-premultiplied) bytes.
74
+ * - The default ALPHA_BLEND mode composites the layers with standard source-over blending: each
75
+ * layer is drawn over the accumulated result, so later layers cover earlier ones and a fully
76
+ * opaque layer hides everything below it. With straight-alpha layers (premultiplyAlpha: false)
77
+ * the fold is the source-over `over` operator (`outA = layer.a + outA * (1 - layer.a)`); with
78
+ * the premultiplied form (`out = layer + out * (1 - layer.a)`). The composite always outputs
79
+ * straight RGBA, so materials see identical pixels regardless of `premultiplyAlpha` (which
80
+ * only controls the layer storage/fold).
81
+ * - ALPHA_MAX picks the sample with the highest alpha; ties (equal alpha) resolve to the highest
82
+ * layer index (last input draws over earlier ones).
83
+ * - With zero active layers, ALPHA_BLEND/ALPHA_MAX/ADD/SUBTRACT/SCREEN output transparent black
84
+ * and MULTIPLY outputs white (empty-product identity).
85
+ * - Compositing is performed independently of the scene render loop: MultiTexture re-composites
86
+ * its internal render target explicitly after every mutation (layer add/insert/remove/update,
87
+ * blend-mode change, array growth), so `scene.proceduralTexturesEnabled` has no effect on it.
88
+ * - How the composite samples the layer array depends on the engine backend, but both are
89
+ * filtered and honour `samplingMode`. On WebGL2 the GLSL composite shader reads the layers
90
+ * through the array sampler (`texture(...)`), so `samplingMode` affects the output, `rttScale`
91
+ * other than 1 produces a filtered bilinear rescale, and (with `generateMipMaps: true`)
92
+ * trilinear minification can use the layer mips. On WebGPU the WGSL composite shader samples
93
+ * the layer array through its sampler at mip 0 (`textureSampleLevel(..., 0.0)`), so `samplingMode`
94
+ * affects the output but only mip-0 filtering applies (no mip-level selection) and `rttScale`
95
+ * rescale is filtered at mip 0. The `_arrayTexture` sampler that materials use to read the
96
+ * per-layer array is unaffected by this backend difference.
97
+ * - `MultiTexture` lives in `@babylonjs/addons` and lazily registers the core 2D-array
98
+ * image-source extensions on first construction, matching the `Atmosphere` addon's convention.
99
+ * No engine mutation occurs at addons import time. `RegisterMultiTexture()` calls both the WebGL2
100
+ * (`engine.texture2DArrayImageSource`) and WebGPU pure registration functions, so a pure/tree-shaken
101
+ * WebGPU build receives `updateTextureArrayLayerFromImageSource` without any extra consumer import.
102
+ * - The allocated array depth (options.maxLayers ?? urls.length) must be a positive integer and no
103
+ * larger than the device limit getCaps().texture2DArrayMaxLayerCount. Empty urls are only accepted
104
+ * together with an explicit options.maxLayers. addLayerAsync/insertLayerAsync double the depth when it is
105
+ * full and throw a RangeError if the doubled depth would exceed that limit.
106
+ */
107
+ export class MultiTexture extends BaseTexture {
108
+ /**
109
+ * The internal ProceduralTexture that composites the layers into the render-target texture
110
+ * assigned to materials. MultiTexture composes, rather than extends, ProceduralTexture: it
111
+ * creates this composite with `skipSceneRegistration: true` so the scene render loop does not
112
+ * drive it, and calls {@link _renderComposite} explicitly after each mutation. All texture
113
+ * surface methods (isReady/getInternalTexture) forward to it.
114
+ */
115
+ get composite() {
116
+ return this._compositeInternal;
117
+ }
118
+ /**
119
+ * Number of active layers (drives the uLayerCount uniform). Changes only via addLayerAsync/removeLayerAsync.
120
+ */
121
+ get layerCount() {
122
+ return this._layerCount;
123
+ }
124
+ /**
125
+ * The underlying TEXTURE_2D_ARRAY, for users who want to sample individual layers directly.
126
+ */
127
+ get arrayTexture() {
128
+ return this._arrayTexture;
129
+ }
130
+ /**
131
+ * Forwards to the internal composite: the render-target texture that composites the layers is
132
+ * owned by the composite, so the material samples it through here.
133
+ * @returns The composite's internal texture.
134
+ */
135
+ getInternalTexture() {
136
+ return this.composite.getInternalTexture();
137
+ }
138
+ /**
139
+ * Forwards to the internal composite: ready once the composite's render-target texture is ready.
140
+ * @returns True if the composite's render-target texture is ready, otherwise false.
141
+ */
142
+ isReady() {
143
+ return this.composite.isReady();
144
+ }
145
+ /**
146
+ * Renders the internal composite, applying the current layer uploads and blend mode.
147
+ * The composite only draws once its effect is compiled (shaders load asynchronously), so the
148
+ * first render is deferred to the compiled callback instead of drawing a stale/empty target.
149
+ */
150
+ _renderComposite() {
151
+ // Kick off effect creation / definition refresh, and ensure getEffect() is populated.
152
+ this.composite.isReady();
153
+ this.composite.executeWhenReady(() => {
154
+ if (!this._disposed) {
155
+ this.composite.render();
156
+ }
157
+ });
158
+ }
159
+ /**
160
+ * Forwards to the composite: the composite render-target is what materials sample.
161
+ * @returns The composite render-target size.
162
+ */
163
+ getSize() {
164
+ return this.composite.getSize();
165
+ }
166
+ /**
167
+ * Forwards to the composite: the composite render-target base size is what materials sample.
168
+ * @returns The composite render-target base size.
169
+ */
170
+ getBaseSize() {
171
+ return this.composite.getBaseSize();
172
+ }
173
+ /**
174
+ * Forwards to the composite's sampling mode.
175
+ * @returns the composite render-target's sampling mode.
176
+ */
177
+ get samplingMode() {
178
+ return this.composite.samplingMode;
179
+ }
180
+ /**
181
+ * Forwards to the composite, which owns the render-target texture the material binds.
182
+ * @param samplingMode the new sampling mode
183
+ * @param generateMipMaps whether to generate mip maps
184
+ */
185
+ updateSamplingMode(samplingMode, generateMipMaps = false) {
186
+ this.composite.updateSamplingMode(samplingMode, generateMipMaps);
187
+ }
188
+ /**
189
+ * Forwards to the composite's render-target texture.
190
+ * @param faceIndex defines the face of the texture to read (in case of cube texture)
191
+ * @param level defines the LOD level of the texture to read (in case of Mip Maps)
192
+ * @param buffer defines a user defined buffer to fill with data (can be null)
193
+ * @param flushRenderer true to flush the renderer from the pending commands before reading the pixels
194
+ * @param noDataConversion false to convert the data to Uint8Array (if texture type is UNSIGNED_BYTE) or to Float32Array (if texture type is anything but UNSIGNED_BYTE). If true, the type of the generated buffer (if buffer==null) will depend on the type of the texture
195
+ * @param x defines the region x coordinates to start reading from (default to 0)
196
+ * @param y defines the region y coordinates to start reading from (default to 0)
197
+ * @param width defines the region width to read from (default to the texture size at level)
198
+ * @param height defines the region width to read from (default to the texture size at level)
199
+ * @returns the composite render-target's pixel buffer promise.
200
+ */
201
+ readPixels(faceIndex, level, buffer, flushRenderer, noDataConversion, x, y, width, height) {
202
+ return this.composite.readPixels(faceIndex, level, buffer, flushRenderer, noDataConversion, x, y, width, height);
203
+ }
204
+ /**
205
+ * Forwards to the composite's render-target texture.
206
+ * @param faceIndex defines the face of the texture to read (in case of cube texture)
207
+ * @param level defines the LOD level of the texture to read (in case of Mip Maps)
208
+ * @param buffer defines a user defined buffer to fill with data (can be null)
209
+ * @param flushRenderer true to flush the renderer from the pending commands before reading the pixels
210
+ * @param noDataConversion false to convert the data to Uint8Array (if texture type is UNSIGNED_BYTE) or to Float32Array (if texture type is anything but UNSIGNED_BYTE). If true, the type of the generated buffer (if buffer==null) will depend on the type of the texture
211
+ * @returns the composite render-target's pixel buffer.
212
+ */
213
+ _readPixelsSync(faceIndex, level, buffer, flushRenderer, noDataConversion) {
214
+ return this.composite._readPixelsSync(faceIndex, level, buffer, flushRenderer, noDataConversion);
215
+ }
216
+ /**
217
+ * Forwards to the composite render-target's format.
218
+ * @returns the composite render-target's internal format.
219
+ */
220
+ get textureFormat() {
221
+ return this.composite.textureFormat;
222
+ }
223
+ /**
224
+ * Forwards to the composite render-target's type.
225
+ * @returns the composite render-target's internal type.
226
+ */
227
+ get textureType() {
228
+ return this.composite.textureType;
229
+ }
230
+ /**
231
+ * Creates a new MultiTexture.
232
+ * @param name defines the name of the texture
233
+ * @param urls defines the array of image URLs to load as layers
234
+ * @param scene defines the hosting scene
235
+ * @param options defines the creation options (width/height required)
236
+ */
237
+ constructor(name, urls, scene, options) {
238
+ super(scene);
239
+ /** Fired once after all initial layers have settled (success or failure). */
240
+ this.onLoadObservable = new Observable();
241
+ this._pollTimer = null;
242
+ /** True while a _poll() tick is in flight; overlapping interval firings early-return so a slow tick never double-fetches. */
243
+ this._pollInFlight = false;
244
+ this._disposed = false;
245
+ /** Number of in-flight mip-suppressed operations (init pool + mutations). See _suppressArrayMips. */
246
+ this._mipSuppressCount = 0;
247
+ RegisterMultiTexture();
248
+ // The two child GPU resources are allocated mid-construction and must be released if the
249
+ // constructor throws (see the catch below): without them a failure after allocation leaves
250
+ // scene-registered textures whose GPU memory is never freed.
251
+ let compositeAllocated = false;
252
+ let arrayAllocated = false;
253
+ try {
254
+ const engine = scene.getEngine();
255
+ if (!engine || (!engine.isWebGPU && engine.webGLVersion < 2)) {
256
+ throw new Error("MultiTexture requires WebGL2 (TEXTURE_2D_ARRAY + sampler2DArray) or WebGPU. " +
257
+ "This context is WebGL1 or unavailable. Create the engine with WebGL2 enabled, e.g. " +
258
+ "new Engine(canvas, { webglVersion: 2 }).");
259
+ }
260
+ if (!Number.isInteger(options.width) || options.width <= 0 || !Number.isInteger(options.height) || options.height <= 0) {
261
+ throw new Error("MultiTexture: width and height must be positive integers.");
262
+ }
263
+ const deviceMaxLayerCap = engine.getCaps().texture2DArrayMaxLayerCount;
264
+ if (options.maxLayers !== undefined && (!Number.isInteger(options.maxLayers) || options.maxLayers < 1)) {
265
+ throw new Error(`MultiTexture: maxLayers must be a positive integer (got ${options.maxLayers}).`);
266
+ }
267
+ if (options.maxLayers === undefined && urls.length === 0) {
268
+ throw new Error(`MultiTexture: urls is empty; pass options.maxLayers (positive integer, <= device limit ${deviceMaxLayerCap}) to define the array depth.`);
269
+ }
270
+ if (options.maxLayers !== undefined && options.maxLayers < urls.length) {
271
+ throw new Error(`MultiTexture: maxLayers (${options.maxLayers}) must be >= urls.length (${urls.length}).`);
272
+ }
273
+ const blendMode = options.blendMode ?? MultiBlendMode.ALPHA_BLEND;
274
+ const maxLayers = options.maxLayers ?? urls.length;
275
+ if (maxLayers > deviceMaxLayerCap) {
276
+ throw new Error(`MultiTexture: array depth ${maxLayers} exceeds the device limit texture2DArrayMaxLayerCount (${deviceMaxLayerCap}). Pass a smaller maxLayers (or fewer urls) or use a device with a higher limit.`);
277
+ }
278
+ const rttW = Math.max(1, Math.round(options.width * (options.rttScale ?? 1)));
279
+ const rttH = Math.max(1, Math.round(options.height * (options.rttScale ?? 1)));
280
+ const generateMipMaps = options.generateMipMaps ?? false;
281
+ const shaderLanguage = engine.isWebGPU ? 1 /* ShaderLanguage.WGSL */ : 0 /* ShaderLanguage.GLSL */;
282
+ const extraInitializationsAsync = async () => {
283
+ // Import ALL six fragment companions for this language so any later blend-mode swap
284
+ // finds its source in the store. Static import list - do not build dynamic import paths from variables.
285
+ if (shaderLanguage === 1 /* ShaderLanguage.WGSL */) {
286
+ await Promise.all([
287
+ import("./ShadersWGSL/multiTextureCompositeAlphaBlend.fragment.js"),
288
+ import("./ShadersWGSL/multiTextureCompositeAlphaMax.fragment.js"),
289
+ import("./ShadersWGSL/multiTextureCompositeAdd.fragment.js"),
290
+ import("./ShadersWGSL/multiTextureCompositeMultiply.fragment.js"),
291
+ import("./ShadersWGSL/multiTextureCompositeSubtract.fragment.js"),
292
+ import("./ShadersWGSL/multiTextureCompositeScreen.fragment.js"),
293
+ ]);
294
+ }
295
+ else {
296
+ await Promise.all([
297
+ import("./Shaders/multiTextureCompositeAlphaBlend.fragment.js"),
298
+ import("./Shaders/multiTextureCompositeAlphaMax.fragment.js"),
299
+ import("./Shaders/multiTextureCompositeAdd.fragment.js"),
300
+ import("./Shaders/multiTextureCompositeMultiply.fragment.js"),
301
+ import("./Shaders/multiTextureCompositeSubtract.fragment.js"),
302
+ import("./Shaders/multiTextureCompositeScreen.fragment.js"),
303
+ ]);
304
+ }
305
+ };
306
+ const creationOptions = {
307
+ shaderLanguage,
308
+ extraInitializationsAsync,
309
+ };
310
+ this._compositeInternal = new ProceduralTexture(name, { width: rttW, height: rttH }, FRAGMENT_NAMES[blendMode], scene, {
311
+ ...creationOptions,
312
+ skipSceneRegistration: true,
313
+ },
314
+ /*generateMipMaps*/ false,
315
+ /*isCube*/ false, Constants.TEXTURETYPE_UNSIGNED_BYTE);
316
+ compositeAllocated = true;
317
+ // Ensure texture-surface forwarding reaches the composite and this class behaves as a
318
+ // self-contained BaseTexture (dedicated single-slot texture, scene-aware, render-target).
319
+ this.name = name;
320
+ this.isRenderTarget = true;
321
+ this._mtOptions = {
322
+ ...options,
323
+ maxLayers,
324
+ blendMode,
325
+ generateMipMaps,
326
+ samplingMode: options.samplingMode ?? Texture.TRILINEAR_SAMPLINGMODE,
327
+ premultiplyAlpha: options.premultiplyAlpha ?? false,
328
+ fit: options.fit ?? "resize",
329
+ rttScale: options.rttScale ?? 1,
330
+ watch: options.watch ?? false,
331
+ pollInterval: options.pollInterval ?? DEFAULT_POLL_INTERVAL_MS,
332
+ };
333
+ this._maxLayers = maxLayers;
334
+ this._deviceMaxLayerCap = deviceMaxLayerCap;
335
+ this._blendMode = blendMode;
336
+ this._arrayTexture = new RawTexture2DArray(null, options.width, options.height, maxLayers, Constants.TEXTUREFORMAT_RGBA, scene, generateMipMaps,
337
+ /*invertY*/ false, options.samplingMode ?? Texture.TRILINEAR_SAMPLINGMODE, Constants.TEXTURETYPE_UNSIGNED_BYTE);
338
+ this._arrayTexture.name = `${this.name}_2DArray`;
339
+ arrayAllocated = true;
340
+ this._layers = urls.map((url) => this._createLayerEntry(url));
341
+ this._layerCount = this._layers.length;
342
+ this.urls = urls.slice();
343
+ this.pixels = new Array(this._layerCount).fill(null);
344
+ this.composite.defines = this._buildDefines(MODE_FLAGS[blendMode]);
345
+ this.composite.setTexture("uLayers", this._arrayTexture);
346
+ this.composite.setInt("uLayerCount", this._layerCount);
347
+ let canvas = null;
348
+ if (typeof OffscreenCanvas !== "undefined") {
349
+ canvas = new OffscreenCanvas(options.width, options.height);
350
+ }
351
+ else if (typeof document !== "undefined") {
352
+ canvas = document.createElement("canvas");
353
+ canvas.width = options.width;
354
+ canvas.height = options.height;
355
+ }
356
+ if (!canvas) {
357
+ throw new Error("MultiTexture: no 2D canvas surface available (requires DOM or OffscreenCanvas).");
358
+ }
359
+ this._canvas = canvas;
360
+ // The union overload of getContext can surface non-2D context types (e.g. ImageBitmapRenderingContext)
361
+ // that the "2d" id never actually returns; narrow for the field's declared type.
362
+ this._ctx = (canvas.getContext("2d", { willReadFrequently: true }) ?? null);
363
+ void this._initialize();
364
+ }
365
+ catch (e) {
366
+ // A failed constructor must not leak the child GPU resources allocated mid-build: the
367
+ // composite render target and the 2D-array are still scene-registered at this point, so
368
+ // abandon them before rethrowing. Cannot delegate to dispose() here because _layers and
369
+ // name may not be assigned yet when the throw predates them.
370
+ if (compositeAllocated) {
371
+ try {
372
+ this._compositeInternal.dispose();
373
+ }
374
+ catch {
375
+ /* disposal of a partially-built composite must not mask the original error */
376
+ }
377
+ }
378
+ if (arrayAllocated) {
379
+ try {
380
+ this._arrayTexture.dispose();
381
+ }
382
+ catch {
383
+ /* disposal of a partially-built array must not mask the original error */
384
+ }
385
+ }
386
+ // A failed constructor must not leave a half-built texture registered in the scene
387
+ // (BaseTexture registers `this` via addTexture in super). Roll that back before rethrowing.
388
+ if (scene.textures) {
389
+ const index = scene.textures.indexOf(this);
390
+ if (index >= 0) {
391
+ scene.textures.splice(index, 1);
392
+ scene.onTextureRemovedObservable.notifyObservers(this);
393
+ }
394
+ }
395
+ throw e;
396
+ }
397
+ }
398
+ /**
399
+ * How the layers combine. Setting it swaps the composite fragment shader and triggers one
400
+ * re-composite.
401
+ */
402
+ get blendMode() {
403
+ return this._blendMode;
404
+ }
405
+ set blendMode(value) {
406
+ if (value === this._blendMode) {
407
+ return;
408
+ }
409
+ this._blendMode = value;
410
+ // Both lines are required: setFragment alone would keep the stale cached effect, because the
411
+ // composite only rebuilds its effect when `defines` changes.
412
+ this.composite.setFragment(FRAGMENT_NAMES[value]);
413
+ this.composite.defines = this._buildDefines(MODE_FLAGS[value]);
414
+ this._renderComposite();
415
+ }
416
+ /**
417
+ * Replaces a layer by URL. Fetches, decodes and uploads layer i only.
418
+ * Exactly one texSubImage3D is issued for the target layer; uLayerCount is unchanged.
419
+ * @param index defines the layer index to replace
420
+ * @param url defines the new source for the layer
421
+ * @returns a promise resolving once the layer has been uploaded
422
+ */
423
+ async updateLayerAsync(index, url) {
424
+ if (!Number.isInteger(index) || index < 0 || index >= this._layerCount) {
425
+ throw new RangeError(`MultiTexture: layer index ${index} out of range [0, ${this._layerCount}).`);
426
+ }
427
+ const entry = this._layers[index];
428
+ entry.url = url;
429
+ entry.etag = null;
430
+ entry.lastModified = null;
431
+ entry.warnedLoadFailure = false;
432
+ this.urls[index] = url;
433
+ await this._loadEntryOrThrow(entry);
434
+ }
435
+ /**
436
+ * Appends a new layer at the end and returns its index. Grows the underlying array (doubling its
437
+ * depth and re-uploading the existing layers from their retained bitmaps) when the current depth
438
+ * is exhausted. Throws a RangeError if the doubled depth would exceed the device's
439
+ * texture2DArrayMaxLayerCount.
440
+ * @param url defines the URL of the image to load as the new layer
441
+ * @returns a promise resolving to the index of the new layer
442
+ */
443
+ async addLayerAsync(url) {
444
+ const newIndex = this._layerCount;
445
+ let entry;
446
+ // Rebuilding the mip chain once per upload would make a grow (N shifted layers) +
447
+ // the new layer's decode regenerate the whole chain N+1 times. Suppress generation for
448
+ // the entire mutation and build the chain exactly once in the finally below.
449
+ this._suppressArrayMips();
450
+ try {
451
+ if (newIndex >= this._maxLayers) {
452
+ this._growArray();
453
+ }
454
+ entry = this._pushLayerEntry(url);
455
+ // The fragment shader only samples the first uLayerCount layers, so the uniform must
456
+ // track the internal count or the freshly appended layer is never composited.
457
+ this.composite.setInt("uLayerCount", this._layerCount);
458
+ }
459
+ catch (e) {
460
+ // Release the mip suppression BEFORE reporting: the onError callback may throw, and the
461
+ // release must not be skippable, or later mip regeneration stays disabled.
462
+ this._generateArrayMips();
463
+ this._reportError(e);
464
+ throw e;
465
+ }
466
+ // The load reports its own failure (see _loadEntryOrThrow) and rethrows; restore the mip
467
+ // chain in finally so a failed decode still leaves the shifted/available layers mipped.
468
+ try {
469
+ await this._loadEntryOrThrow(entry);
470
+ }
471
+ finally {
472
+ this._generateArrayMips();
473
+ }
474
+ return newIndex;
475
+ }
476
+ /**
477
+ * Inserts a new layer at the given index and returns it. Layers at index and above shift up by
478
+ * one: loaded layers are re-uploaded from their retained bitmaps, and a shifted layer that is
479
+ * still loading lands in its new slot when its in-flight load settles (loads resolve against
480
+ * their layer entry, never against a stale index). uLayerCount is incremented. Inserting at
481
+ * `layerCount` appends (addLayerAsync-equivalent). Grows the underlying array (doubling its depth)
482
+ * when the current depth is exhausted, same as addLayerAsync, and throws a RangeError if the doubled
483
+ * depth would exceed the device's texture2DArrayMaxLayerCount.
484
+ * @param index defines the layer index to insert at (0..layerCount, inclusive)
485
+ * @param url defines the URL of the image to load as the new layer
486
+ * @returns a promise resolving to the index of the inserted layer
487
+ */
488
+ async insertLayerAsync(index, url) {
489
+ if (!Number.isInteger(index) || index < 0 || index > this._layerCount) {
490
+ throw new RangeError(`MultiTexture: layer index ${index} out of range [0, ${this._layerCount}].`);
491
+ }
492
+ let entry;
493
+ // Same batching as addLayerAsync: suppression spans the grow/shift uploads AND the new
494
+ // layer's decode, with one final chain generation.
495
+ this._suppressArrayMips();
496
+ try {
497
+ if (this._layerCount + 1 > this._maxLayers) {
498
+ this._growArray();
499
+ }
500
+ entry = this._createLayerEntry(url);
501
+ this._layers.splice(index, 0, entry);
502
+ this.pixels.splice(index, 0, null);
503
+ this.urls.splice(index, 0, url);
504
+ this._layerCount++;
505
+ // Move the shifted layers up on the GPU before the new layer is decoded, top-down so no
506
+ // slot is overwritten before its old content is re-read.
507
+ for (let j = this._layerCount - 1; j > index; j--) {
508
+ this._reuploadSlot(j);
509
+ }
510
+ // The fragment shader only samples the first uLayerCount layers, so the uniform must
511
+ // track the internal count or the freshly inserted layer is never composited.
512
+ this.composite.setInt("uLayerCount", this._layerCount);
513
+ // Re-composite even if the load below fails: the shift above already moved GPU slots.
514
+ this._renderComposite();
515
+ }
516
+ catch (e) {
517
+ // Release the mip suppression BEFORE reporting: the onError callback may throw, and the
518
+ // release must not be skippable, or later mip regeneration stays disabled.
519
+ this._generateArrayMips();
520
+ this._reportError(e);
521
+ throw e;
522
+ }
523
+ // The load reports its own failure (see _loadEntryOrThrow) and rethrows; restore the mip
524
+ // chain in finally so a failed decode still leaves the shifted/available layers mipped.
525
+ try {
526
+ await this._loadEntryOrThrow(entry);
527
+ }
528
+ finally {
529
+ this._generateArrayMips();
530
+ }
531
+ return index;
532
+ }
533
+ /**
534
+ * Removes a layer. Higher indices shift down (re-uploaded from their retained bitmaps) and
535
+ * uLayerCount is decremented.
536
+ * @param index defines the layer index to remove
537
+ * @returns a promise resolving once the shift is done
538
+ */
539
+ async removeLayerAsync(index) {
540
+ if (!Number.isInteger(index) || index < 0 || index >= this._layerCount) {
541
+ throw new RangeError(`MultiTexture: layer index ${index} out of range [0, ${this._layerCount}).`);
542
+ }
543
+ const removed = this._layers.splice(index, 1)[0];
544
+ this.pixels.splice(index, 1);
545
+ this.urls.splice(index, 1);
546
+ if (removed.bitmap) {
547
+ removed.bitmap.close();
548
+ }
549
+ this._layerCount--;
550
+ // Same batching as the other mutations: suppress mip generation for the shift uploads and
551
+ // rebuild the chain exactly once.
552
+ this._suppressArrayMips();
553
+ try {
554
+ for (let j = index; j < this._layerCount; j++) {
555
+ this._reuploadSlot(j);
556
+ }
557
+ // The splice moved every live entry down one slot, so the highest GPU slot (== the new
558
+ // layerCount) is now vacated but still holds the removed layer's pixels. Clear it, or a
559
+ // later addLayerAsync that lands there with a failed load would resurrect the stale
560
+ // layer, and SUBTRACT (which samples layer 0 unconditionally) would show leftover pixel
561
+ // data once the last layer is removed.
562
+ this._clearLayerSlot(this._arrayTexture, this._layerCount);
563
+ this.composite.setInt("uLayerCount", this._layerCount);
564
+ this._renderComposite();
565
+ }
566
+ finally {
567
+ this._generateArrayMips();
568
+ }
569
+ }
570
+ /**
571
+ * Disposes the texture: stops the watch poller, closes every retained bitmap, disposes the layer
572
+ * array and releases the composite render target through the standard procedural-texture path.
573
+ */
574
+ dispose() {
575
+ if (this._disposed) {
576
+ return;
577
+ }
578
+ this._disposed = true;
579
+ if (this._pollTimer !== null) {
580
+ clearInterval(this._pollTimer);
581
+ this._pollTimer = null;
582
+ }
583
+ for (let i = 0; i < this._layers.length; i++) {
584
+ const entry = this._layers[i];
585
+ if (entry.bitmap) {
586
+ entry.bitmap.close();
587
+ entry.bitmap = null;
588
+ }
589
+ }
590
+ for (let i = 0; i < this.pixels.length; i++) {
591
+ this.pixels[i] = null;
592
+ }
593
+ this._layers.length = 0;
594
+ this._canvas = null;
595
+ this._ctx = null;
596
+ this._arrayTexture.dispose();
597
+ this.composite.dispose();
598
+ // Honor the base-texture dispose contract: fires onDisposeObservable, clears metadata and
599
+ // tears down scene registration. The inherited _texture is null (never set), so the
600
+ // ThinTexture.dispose path is a safe no-op and the array/composite above are the real GPU
601
+ // owners.
602
+ super.dispose();
603
+ }
604
+ /**
605
+ * Clones the texture: builds a fresh MultiTexture in the same scene with the same name, the
606
+ * current layer urls and the resolved options (layer resolution, current array capacity,
607
+ * current blend mode, sampling mode, mipmap generation, RTT scale, fit and watch settings).
608
+ * The clone re-fetches and re-decodes its layers from scratch; it never shares the 2D array
609
+ * texture, the pixel cache or the load callbacks (onLoad/onError are not inherited).
610
+ * @returns the cloned texture
611
+ */
612
+ clone() {
613
+ const newTexture = new MultiTexture(this.name, this.urls.slice(), this.getScene(), {
614
+ width: this._mtOptions.width,
615
+ height: this._mtOptions.height,
616
+ maxLayers: this._maxLayers,
617
+ blendMode: this._blendMode,
618
+ generateMipMaps: this._mtOptions.generateMipMaps,
619
+ samplingMode: this._mtOptions.samplingMode,
620
+ premultiplyAlpha: this._mtOptions.premultiplyAlpha,
621
+ fit: this._mtOptions.fit,
622
+ rttScale: this._mtOptions.rttScale,
623
+ watch: this._mtOptions.watch,
624
+ pollInterval: this._mtOptions.pollInterval,
625
+ });
626
+ // Base texture state carried over per the ProceduralTexture.clone() contract.
627
+ newTexture.hasAlpha = this.hasAlpha;
628
+ newTexture.level = this.level;
629
+ newTexture.coordinatesMode = this.coordinatesMode;
630
+ return newTexture;
631
+ }
632
+ /**
633
+ * MultiTexture is intentionally not scene-serializable: the scene loader has no parser for it,
634
+ * so the payload produced by the inherited base serialization could never be reconstructed
635
+ * (urls, capacity, blend mode and watch options have no serialized fields). Fails explicitly
636
+ * instead of returning a misleading JSON object.
637
+ * @param _allowEmptyName accepted for signature compatibility; ignored
638
+ * @throws Error always
639
+ */
640
+ serialize(_allowEmptyName = false) {
641
+ throw new Error("MultiTexture: serialize() is not supported. The scene loader has no MultiTexture parser (urls, capacity, blend mode and watch options cannot round-trip). Use clone() for an in-memory copy, or persist your urls/options to rebuild it.");
642
+ }
643
+ _buildDefines(flag) {
644
+ return (
645
+ // The loop bound is baked to the device cap, not the current layer count, so growing the
646
+ // array never changes the effect defines (no shader rebuild on addLayerAsync/insertLayerAsync).
647
+ // The uLayerCount uniform bounds sampling, so layers beyond the active count are never read.
648
+ "#define MULTITEXTURE_MAXLAYERS " +
649
+ this._deviceMaxLayerCap +
650
+ "\n#define MULTITEXTURE_WIDTH " +
651
+ this._mtOptions.width +
652
+ "\n#define MULTITEXTURE_HEIGHT " +
653
+ this._mtOptions.height +
654
+ "\n#define MULTITEXTURE_BLEND_" +
655
+ flag +
656
+ // ALPHA_BLEND's source-over fold differs for straight-alpha vs premultiplied layers.
657
+ (this._mtOptions.premultiplyAlpha ? "\n#define MULTITEXTURE_PREMULTIPLY" : ""));
658
+ }
659
+ _bitmapOptions() {
660
+ // Straight layers decode at native size and let _uploadToLayer resize via the 2D canvas
661
+ // (which preserves straight RGBA); only premultiplied storage resizes here. "strict" fit
662
+ // checks the native size.
663
+ //
664
+ // Memory tradeoff (deliberate): the native-resolution bitmap is retained on each entry for
665
+ // the texture's lifetime so insert/remove shifts re-upload via the same 2D-canvas resize
666
+ // that guarantees straight bytes on both backends. createImageBitmap's resize option is not
667
+ // used here because Chromium premultiplies a resized straight decode, which would silently
668
+ // corrupt the alpha after the first mutation. A straight 1024^2 source targeting 128^2 thus
669
+ // holds ~4 MB per layer instead of ~64 KB; use options.fit "resize" together with
670
+ // premultiplyAlpha:true if per-layer memory must shrink (premultiplied storage resizes at
671
+ // decode). Retaining the native bitmap is what keeps the WebGL2/WebGPU byte parity intact.
672
+ const options = { premultiplyAlpha: this._mtOptions.premultiplyAlpha ? "premultiply" : "none" };
673
+ if (this._mtOptions.fit === "resize" && this._mtOptions.premultiplyAlpha) {
674
+ options.resizeWidth = this._mtOptions.width;
675
+ options.resizeHeight = this._mtOptions.height;
676
+ options.resizeQuality = "high";
677
+ }
678
+ return options;
679
+ }
680
+ _reportError(error) {
681
+ const message = String(error?.message ?? error);
682
+ Logger.Error(message);
683
+ this._mtOptions.onError?.(message, error);
684
+ }
685
+ _createLayerEntry(url) {
686
+ return { url, etag: null, lastModified: null, bitmap: null, loaded: false, generation: 0, warnedLoadFailure: false };
687
+ }
688
+ // eslint-disable-next-line @typescript-eslint/naming-convention
689
+ async _loadEntryOrThrow(entry) {
690
+ // Public addLayer/insertLayer/updateLayerAsync contract: report the failure and rethrow.
691
+ try {
692
+ await this._loadEntry(entry);
693
+ }
694
+ catch (e) {
695
+ this._reportError(e);
696
+ throw e;
697
+ }
698
+ }
699
+ // eslint-disable-next-line @typescript-eslint/naming-convention
700
+ async _loadEntryAndReport(entry) {
701
+ // Internal pools (init, watch): report the failure and keep going.
702
+ try {
703
+ await this._loadEntry(entry);
704
+ }
705
+ catch (e) {
706
+ this._reportError(e);
707
+ }
708
+ }
709
+ _warnWatchFailure(entry, detail) {
710
+ if (entry.warnedLoadFailure) {
711
+ return;
712
+ }
713
+ // The entry may have been removed while this tick was running: nothing left to warn about.
714
+ const index = this._layers.indexOf(entry);
715
+ if (index === -1) {
716
+ return;
717
+ }
718
+ entry.warnedLoadFailure = true;
719
+ const message = `MultiTexture: watched layer ${index} (${entry.url}) ${detail}`;
720
+ Logger.Error(message);
721
+ this._mtOptions.onError?.(message);
722
+ }
723
+ _uploadToLayer(target, index, bitmap) {
724
+ if (this._mtOptions.premultiplyAlpha) {
725
+ UploadImageToTexture2DArrayLayer(target, bitmap, index, { premultiplyAlpha: true });
726
+ return;
727
+ }
728
+ // Straight storage must not resize through createImageBitmap (Chromium premultiplies a
729
+ // resized decode even with premultiplyAlpha "none"), so upload the native-sized bitmap and
730
+ // only scale via the 2D canvas drawImage, which preserves straight RGBA.
731
+ const canvas = this._canvas;
732
+ const ctx = this._ctx;
733
+ if (canvas && ctx && (bitmap.width !== this._mtOptions.width || bitmap.height !== this._mtOptions.height)) {
734
+ ctx.clearRect(0, 0, this._mtOptions.width, this._mtOptions.height);
735
+ ctx.drawImage(bitmap, 0, 0, this._mtOptions.width, this._mtOptions.height);
736
+ UploadImageToTexture2DArrayLayer(target, canvas, index, { premultiplyAlpha: false });
737
+ }
738
+ else {
739
+ UploadImageToTexture2DArrayLayer(target, bitmap, index, { premultiplyAlpha: false });
740
+ }
741
+ }
742
+ _reuploadSlot(index, target = this._arrayTexture) {
743
+ const bitmap = this._layers[index].bitmap;
744
+ if (bitmap !== null) {
745
+ this._uploadToLayer(target, index, bitmap);
746
+ }
747
+ else {
748
+ // A shifted layer with no decoded bitmap (still loading, or its load failed) must not
749
+ // leave the GPU slot holding the PREVIOUS layer: urls/pixels describe a transparent
750
+ // layer here, so upload a cleared canvas (a valid cross-backend ImageSource).
751
+ this._clearLayerSlot(target, index);
752
+ }
753
+ }
754
+ _clearLayerSlot(target, index) {
755
+ if (!this._canvas || !this._ctx) {
756
+ // No drawable surface to clear from: leave the slot untouched.
757
+ return;
758
+ }
759
+ // Clears a slot to transparent when the shifted layer has no decoded bitmap, so insert/remove
760
+ // never leaves the previous layer's pixels there. A cleared canvas is a valid ImageSource on
761
+ // both backends (unlike raw ImageData).
762
+ this._ctx.clearRect(0, 0, this._mtOptions.width, this._mtOptions.height);
763
+ UploadImageToTexture2DArrayLayer(target, this._canvas, index, { premultiplyAlpha: false });
764
+ }
765
+ // eslint-disable-next-line @typescript-eslint/naming-convention
766
+ async _loadEntry(entry) {
767
+ // Body runs across awaits; if dispose() wins the race, skip the fetch entirely.
768
+ if (this._disposed) {
769
+ return;
770
+ }
771
+ // Per-layer generation token: every new load for this entry (init, updateLayerAsync,
772
+ // watch reload) supersedes the previous one. The settling load revalidates it in
773
+ // _uploadBitmap before committing any state.
774
+ const generation = ++entry.generation;
775
+ const url = entry.url;
776
+ const response = await fetch(url);
777
+ if (!response.ok) {
778
+ throw new Error(`MultiTexture: failed to fetch ${url}: ${response.status} ${response.statusText}`);
779
+ }
780
+ const etag = response.headers.get("etag");
781
+ const lastModified = response.headers.get("last-modified");
782
+ const blob = await response.blob();
783
+ const bitmap = await createImageBitmap(blob, this._bitmapOptions());
784
+ if (this._mtOptions.fit === "strict") {
785
+ const width = bitmap.width;
786
+ const height = bitmap.height;
787
+ if (width !== this._mtOptions.width || height !== this._mtOptions.height) {
788
+ bitmap.close();
789
+ const index = this._layers.indexOf(entry);
790
+ throw new Error(`MultiTexture: layer ${index} (${url}) is ${width}x${height}, expected ${this._mtOptions.width}x${this._mtOptions.height}. Use fit: "resize" to auto-scale.`);
791
+ }
792
+ }
793
+ this._uploadBitmap(entry, bitmap, { etag, lastModified, generation });
794
+ }
795
+ _uploadBitmap(entry, bitmap, meta) {
796
+ // The load resolved across awaits, so revalidate before committing: dispose() may have
797
+ // destroyed the arrays, a mutation may have removed or moved this entry, or a newer load
798
+ // for the same entry may have superseded this one's generation token.
799
+ if (this._disposed) {
800
+ bitmap.close();
801
+ return;
802
+ }
803
+ const index = this._layers.indexOf(entry);
804
+ if (index === -1 || entry.generation !== meta.generation) {
805
+ bitmap.close();
806
+ return;
807
+ }
808
+ this._uploadToLayer(this._arrayTexture, index, bitmap);
809
+ if (this._canvas && this._ctx) {
810
+ this._ctx.clearRect(0, 0, this._mtOptions.width, this._mtOptions.height);
811
+ this._ctx.drawImage(bitmap, 0, 0, this._mtOptions.width, this._mtOptions.height);
812
+ this.pixels[index] = this._ctx.getImageData(0, 0, this._mtOptions.width, this._mtOptions.height).data.slice();
813
+ }
814
+ else {
815
+ this.pixels[index] = null;
816
+ }
817
+ if (entry.bitmap !== null) {
818
+ entry.bitmap.close();
819
+ }
820
+ entry.bitmap = bitmap;
821
+ entry.loaded = true;
822
+ entry.etag = meta.etag;
823
+ entry.lastModified = meta.lastModified;
824
+ entry.warnedLoadFailure = false;
825
+ this._renderComposite();
826
+ }
827
+ // eslint-disable-next-line @typescript-eslint/naming-convention
828
+ async _initialize() {
829
+ try {
830
+ if (this._disposed) {
831
+ // Dispose won the init race; leave the texture as-is, the object is dead.
832
+ return;
833
+ }
834
+ // Suppress mip generation for the whole decode pool so per-layer uploads never rebuild
835
+ // the chain; a single rebuild happens once the pool (and any concurrent mutation) settles.
836
+ this._suppressArrayMips();
837
+ // Snapshot the entries so the pool always loads exactly the layers the texture was
838
+ // constructed with: insertLayerAsync/removeLayerAsync may splice _layers while the pool is
839
+ // running, and following live indices would skip a layer or load one twice. Each
840
+ // entry decides its own landing slot when its load settles (see _uploadBitmap).
841
+ const initial = this._layers.slice();
842
+ let next = 0;
843
+ const count = initial.length;
844
+ const workerAsync = async () => {
845
+ let i;
846
+ while ((i = next++) < count) {
847
+ // eslint-disable-next-line no-await-in-loop -- decode pool: each worker processes layers sequentially.
848
+ await this._loadEntryAndReport(initial[i]);
849
+ }
850
+ };
851
+ const workers = [];
852
+ for (let w = 0; w < DECODE_CONCURRENCY; w++) {
853
+ workers.push(workerAsync());
854
+ }
855
+ await Promise.all(workers);
856
+ if (!this._disposed) {
857
+ this.onLoadObservable.notifyObservers(this);
858
+ this._mtOptions.onLoad?.();
859
+ this._renderComposite();
860
+ }
861
+ if (this._mtOptions.watch) {
862
+ this._startPolling();
863
+ }
864
+ }
865
+ catch (e) {
866
+ this._reportError(e);
867
+ }
868
+ finally {
869
+ // Build the chain once over every upload that landed while generation was suppressed,
870
+ // on both the success and error paths (a throwing onLoad/onError must not leave the
871
+ // suppression stuck). The gate re-resolves the LIVE array texture after the pool
872
+ // (mutations may have grown and replaced this._arrayTexture mid-pool), so it never
873
+ // targets a disposed capture.
874
+ this._generateArrayMips();
875
+ }
876
+ }
877
+ _pushLayerEntry(url) {
878
+ const entry = this._createLayerEntry(url);
879
+ this._layers.push(entry);
880
+ this.pixels.push(null);
881
+ this.urls.push(url);
882
+ this._layerCount++;
883
+ return entry;
884
+ }
885
+ _growArray() {
886
+ const scene = this.getScene();
887
+ const newDepth = this._maxLayers * 2;
888
+ if (newDepth > this._deviceMaxLayerCap) {
889
+ throw new RangeError(`MultiTexture: cannot grow the array from depth ${this._maxLayers} to ${newDepth}: the device limit texture2DArrayMaxLayerCount is ${this._deviceMaxLayerCap}. Remove a layer, or recreate the MultiTexture with a larger options.maxLayers (<= ${this._deviceMaxLayerCap}) to allow more growth headroom.`);
890
+ }
891
+ const newRaw = new RawTexture2DArray(null, this._mtOptions.width, this._mtOptions.height, newDepth, Constants.TEXTUREFORMAT_RGBA, scene, this._mtOptions.generateMipMaps ?? false,
892
+ /*invertY*/ false, this._mtOptions.samplingMode ?? Texture.TRILINEAR_SAMPLINGMODE, Constants.TEXTURETYPE_UNSIGNED_BYTE);
893
+ const newInternal = newRaw.getInternalTexture();
894
+ // UploadImageToTexture2DArrayLayer regenerates the WHOLE array's mip chain per upload when
895
+ // texture.generateMipMaps is set. Re-uploading N shifted layers would therefore rebuild the
896
+ // full mip chain N times. Suppress generation here and leave the array suppressed: the
897
+ // calling mutation (addLayerAsync/insertLayerAsync) holds the flag off across THIS grow AND
898
+ // the new layer's decode, then rebuilds the chain exactly once via _generateArrayMips.
899
+ if ((this._mtOptions.generateMipMaps ?? false) && newInternal) {
900
+ newInternal.generateMipMaps = false;
901
+ }
902
+ for (let i = 0; i < this._layerCount; i++) {
903
+ this._reuploadSlot(i, newRaw);
904
+ }
905
+ this._arrayTexture.dispose();
906
+ this._arrayTexture = newRaw;
907
+ this.composite.setTexture("uLayers", newRaw);
908
+ this._maxLayers = newDepth;
909
+ // No defines change on growth: MAXLAYERS is baked to the device cap and uLayerCount bounds
910
+ // sampling, so the composite effect is reused and only re-rendered against the grown array.
911
+ this._renderComposite();
912
+ }
913
+ // The upload extension regenerates the array's whole mip chain per upload when generateMipMaps
914
+ // is set, so a multi-upload mutation would rebuild it once per upload. Suppress it for the whole
915
+ // mutation and rebuild once (see _generateArrayMips); a counter rather than a boolean lets the
916
+ // init pool and concurrent mutations nest safely.
917
+ _suppressArrayMips() {
918
+ if (!(this._mtOptions.generateMipMaps ?? false) || this._disposed) {
919
+ return;
920
+ }
921
+ const internal = this._arrayTexture.getInternalTexture();
922
+ if (internal) {
923
+ internal.generateMipMaps = false;
924
+ }
925
+ this._mipSuppressCount++;
926
+ }
927
+ // Restores mip generation and rebuilds the chain when the last suppressor finishes (count 0);
928
+ // the array was allocated with mip support, so one generateMipmaps covers every upload that ran
929
+ // while generation was suppressed.
930
+ _generateArrayMips() {
931
+ if (this._mipSuppressCount > 0) {
932
+ this._mipSuppressCount--;
933
+ }
934
+ if (this._mipSuppressCount > 0 || !(this._mtOptions.generateMipMaps ?? false) || this._disposed) {
935
+ // Still suppressed by another in-flight op (it will rebuild), or mips are disabled /
936
+ // the object was disposed, so there is nothing to (re)build.
937
+ return;
938
+ }
939
+ const internal = this._arrayTexture.getInternalTexture();
940
+ if (internal) {
941
+ internal.generateMipMaps = true;
942
+ this.getScene().getEngine().generateMipmaps(internal);
943
+ }
944
+ }
945
+ _startPolling() {
946
+ if (this._pollTimer !== null || this._disposed) {
947
+ return;
948
+ }
949
+ this._pollTimer = setInterval(() => {
950
+ void this._poll();
951
+ }, this._mtOptions.pollInterval);
952
+ }
953
+ // eslint-disable-next-line @typescript-eslint/naming-convention
954
+ async _poll() {
955
+ if (this._pollInFlight) {
956
+ return;
957
+ }
958
+ this._pollInFlight = true;
959
+ if (this._disposed) {
960
+ this._pollInFlight = false;
961
+ return;
962
+ }
963
+ if (typeof document !== "undefined" && document.visibilityState === "hidden") {
964
+ this._pollInFlight = false;
965
+ return;
966
+ }
967
+ const entries = this._layers.slice();
968
+ let next = 0;
969
+ const count = entries.length;
970
+ const workerAsync = async () => {
971
+ let i;
972
+ while ((i = next++) < count) {
973
+ const entry = entries[i];
974
+ try {
975
+ if (entry.etag === null && entry.lastModified === null) {
976
+ // No etag/last-modified recorded for this entry — either it never loaded or
977
+ // the server sends no validators. HEAD-based change detection cannot apply,
978
+ // so retry a direct full load (a 404 at startup that is published later
979
+ // recovers this way instead of being skipped forever).
980
+ try {
981
+ // eslint-disable-next-line no-await-in-loop -- full-load retry, same pool as the HEAD checks below.
982
+ await this._loadEntry(entry);
983
+ }
984
+ catch (e) {
985
+ // Persistently failing layer: warn once, retry on the next tick.
986
+ this._warnWatchFailure(entry, `failed to load: ${String(e?.message ?? e)}`);
987
+ }
988
+ continue;
989
+ }
990
+ // eslint-disable-next-line no-await-in-loop -- poll pool: each worker checks layers sequentially.
991
+ const response = await fetch(entry.url, { method: "HEAD" });
992
+ if (response.status === 404) {
993
+ this._warnWatchFailure(entry, "returned 404.");
994
+ continue;
995
+ }
996
+ if (!response.ok) {
997
+ // Transient failure: ignore for this tick.
998
+ continue;
999
+ }
1000
+ const etag = response.headers.get("etag");
1001
+ const lastModified = response.headers.get("last-modified");
1002
+ if (etag === null && lastModified === null) {
1003
+ // Change detection is unavailable for this entry (server sends no
1004
+ // etag/last-modified); nothing to compare against — skip.
1005
+ continue;
1006
+ }
1007
+ if ((etag !== null && etag !== entry.etag) || (lastModified !== null && lastModified !== entry.lastModified)) {
1008
+ // eslint-disable-next-line no-await-in-loop -- reload happens after the HEAD check above.
1009
+ await this._loadEntryAndReport(entry);
1010
+ }
1011
+ }
1012
+ catch {
1013
+ // Transient fetch failure: ignore for this tick.
1014
+ }
1015
+ }
1016
+ };
1017
+ const workers = [];
1018
+ for (let w = 0; w < DECODE_CONCURRENCY; w++) {
1019
+ workers.push(workerAsync());
1020
+ }
1021
+ await Promise.all(workers);
1022
+ this._pollInFlight = false;
1023
+ }
1024
+ }
1025
+ /**
1026
+ * Blend modes controlling how the layers of a MultiTexture are combined per pixel.
1027
+ */
1028
+ export var MultiBlendMode;
1029
+ (function (MultiBlendMode) {
1030
+ /**
1031
+ * Default. Composites the layers with standard source-over alpha blending: each layer is drawn
1032
+ * over the accumulated result, so later layers cover earlier ones and a fully opaque layer
1033
+ * (a = 1) completely hides everything below it. With straight-alpha layers (premultiplyAlpha:
1034
+ * false) the fold is `outA = layer.a + outA * (1 - layer.a)`; with premultiplied layers it is
1035
+ * the premultiplied form `out = layer + out * (1 - layer.a)`. The composite always outputs
1036
+ * straight RGBA, so materials see identical pixels regardless of `premultiplyAlpha` (which
1037
+ * only controls the layer storage/fold). Zero active layers output transparent black.
1038
+ */
1039
+ MultiBlendMode[MultiBlendMode["ALPHA_BLEND"] = 0] = "ALPHA_BLEND";
1040
+ /** Keeps the sample with the highest alpha among the layers (ties: highest index wins). Zero active layers output transparent black. */
1041
+ MultiBlendMode[MultiBlendMode["ALPHA_MAX"] = 1] = "ALPHA_MAX";
1042
+ /** Adds all layers per channel, clamped to 1. */
1043
+ MultiBlendMode[MultiBlendMode["ADD"] = 2] = "ADD";
1044
+ /** Multiplies all layers per channel (empty product is 1). */
1045
+ MultiBlendMode[MultiBlendMode["MULTIPLY"] = 3] = "MULTIPLY";
1046
+ /** Starts from layer 0 and subtracts every following layer, clamped to 0. */
1047
+ MultiBlendMode[MultiBlendMode["SUBTRACT"] = 4] = "SUBTRACT";
1048
+ /** Screens all layers per channel. */
1049
+ MultiBlendMode[MultiBlendMode["SCREEN"] = 5] = "SCREEN";
1050
+ })(MultiBlendMode || (MultiBlendMode = {}));
1051
+ //# sourceMappingURL=multiTexture.js.map