@vunk/plus 1.10.3 → 1.11.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/components/agent-chat-provider/index.mjs +1 -1
  2. package/components/avatar/index.mjs +1 -1
  3. package/components/broadcasting-markdown/index.mjs +25 -16
  4. package/components/broadcasting-markdown/src/ctx.d.ts +7 -0
  5. package/components/broadcasting-markdown/src/index.vue.d.ts +84 -1
  6. package/components/bubble-list/index.mjs +4 -4
  7. package/components/bubble-templates/index.mjs +1 -1
  8. package/components/chat-independent/index.mjs +1 -1
  9. package/components/drawer/index.css +92 -92
  10. package/components/drawer/index.mjs +2 -2
  11. package/components/index2.mjs +64 -26444
  12. package/components/lottie-animation/index.mjs +1 -1
  13. package/components/metahuman-broadcasting/index.mjs +28 -3062
  14. package/components/metahuman-broadcasting/src/ctx.d.ts +4 -0
  15. package/components/metahuman-broadcasting/src/index.vue.d.ts +102 -9
  16. package/components/monaco-editor/index.mjs +1 -1
  17. package/components/monaco-environment/index.mjs +1 -1
  18. package/components/pixi-frame/index.mjs +1988 -7
  19. package/components/pixi-frame/src/bitmap.vue.d.ts +4 -5
  20. package/components/pixi-frame/src/index.vue.d.ts +4 -5
  21. package/components/recorder-button/index.mjs +1 -1
  22. package/components/routes-menu-content/index.mjs +3 -3
  23. package/components/scrollbar/index.mjs +3 -3
  24. package/components/sender/index.mjs +2 -2
  25. package/components/speech-button/index.mjs +3 -3
  26. package/components/table-columns/index.mjs +1 -1
  27. package/components/tables-v1/index.mjs +1 -1
  28. package/components/tables-v1-checkbox/index.mjs +1 -1
  29. package/components/text/index.mjs +1 -1
  30. package/components/typing-markdown/index.mjs +1 -1
  31. package/components/vditor/index.mjs +3 -3
  32. package/components/xgplayer/index.mjs +2 -2
  33. package/icons/end/index.mjs +1 -1
  34. package/icons/keyboard/index.mjs +1 -1
  35. package/icons/start/index.mjs +1 -1
  36. package/icons/voice/index.mjs +1 -1
  37. package/index.css +92 -92
  38. package/package.json +1 -1
  39. package/components/SharedSystems.mjs +0 -3413
  40. package/components/WebGLRenderer.mjs +0 -3631
  41. package/components/WebGPURenderer.mjs +0 -2143
  42. package/components/browserAll.mjs +0 -2960
  43. package/components/colorToUniform.mjs +0 -268
  44. package/components/index3.mjs +0 -78
  45. package/components/init.mjs +0 -4505
  46. package/components/webworkerAll.mjs +0 -10
@@ -1,3631 +0,0 @@
1
- import { E as ExtensionType, B as BufferUsage, w as warn, D as DOMAdapter, J as getAttributeInfoFromFormat, a2 as Geometry, t as GlProgram, q as Shader, s as Texture, j as TextureSource, a3 as checkMaxIfStatementsInShader, S as STENCIL_MODES, N as Rectangle, i as CanvasSource, h as CLEAR, k as UniformGroup, M as Matrix, a4 as compileHighShaderGlProgram, a5 as colorBitGl, a6 as generateTextureBatchBitGl, a7 as roundPixelsBitGl, a8 as getBatchSamplersUniformGroup, e as extensions, A as AbstractRenderer, R as RendererType } from './index2.mjs';
2
- import { S as State, b as localUniformBitGl } from './colorToUniform.mjs';
3
- import { e as ensureAttributes, G as GpuStencilModesToPixi, c as createUboSyncFunction, b as uboSyncFunctionsSTD40, U as UboSystem, R as RenderTargetSystem, B as BufferResource, d as uniformParsers, f as textureBitGl, S as SharedSystems, a as SharedRenderPipes } from './SharedSystems.mjs';
4
- import 'vue';
5
- import '@vunk/shared/enum';
6
- import '@vunk/shared/promise';
7
- import './_commonjsHelpers.mjs';
8
- import './_plugin-vue_export-helper.mjs';
9
- import '@vunk/shared/object';
10
- import '@vunk/core/composables';
11
-
12
- class GlBatchAdaptor {
13
- constructor() {
14
- this._tempState = State.for2d();
15
- /**
16
- * We only want to sync the a batched shaders uniforms once on first use
17
- * this is a hash of shader uids to a boolean value. When the shader is first bound
18
- * we set the value to true. When the shader is bound again we check the value and
19
- * if it is true we know that the uniforms have already been synced and we skip it.
20
- */
21
- this._didUploadHash = {};
22
- }
23
- init(batcherPipe) {
24
- batcherPipe.renderer.runners.contextChange.add(this);
25
- }
26
- contextChange() {
27
- this._didUploadHash = {};
28
- }
29
- start(batchPipe, geometry, shader) {
30
- const renderer = batchPipe.renderer;
31
- const didUpload = this._didUploadHash[shader.uid];
32
- renderer.shader.bind(shader, didUpload);
33
- if (!didUpload) {
34
- this._didUploadHash[shader.uid] = true;
35
- }
36
- renderer.shader.updateUniformGroup(renderer.globalUniforms.uniformGroup);
37
- renderer.geometry.bind(geometry, shader.glProgram);
38
- }
39
- execute(batchPipe, batch) {
40
- const renderer = batchPipe.renderer;
41
- this._tempState.blendMode = batch.blendMode;
42
- renderer.state.set(this._tempState);
43
- const textures = batch.textures.textures;
44
- for (let i = 0; i < batch.textures.count; i++) {
45
- renderer.texture.bind(textures[i], i);
46
- }
47
- renderer.geometry.draw(batch.topology, batch.size, batch.start);
48
- }
49
- }
50
- /** @ignore */
51
- GlBatchAdaptor.extension = {
52
- type: [
53
- ExtensionType.WebGLPipesAdaptor
54
- ],
55
- name: "batch"
56
- };
57
-
58
- var BUFFER_TYPE = /* @__PURE__ */ ((BUFFER_TYPE2) => {
59
- BUFFER_TYPE2[BUFFER_TYPE2["ELEMENT_ARRAY_BUFFER"] = 34963] = "ELEMENT_ARRAY_BUFFER";
60
- BUFFER_TYPE2[BUFFER_TYPE2["ARRAY_BUFFER"] = 34962] = "ARRAY_BUFFER";
61
- BUFFER_TYPE2[BUFFER_TYPE2["UNIFORM_BUFFER"] = 35345] = "UNIFORM_BUFFER";
62
- return BUFFER_TYPE2;
63
- })(BUFFER_TYPE || {});
64
-
65
- class GlBuffer {
66
- constructor(buffer, type) {
67
- this._lastBindBaseLocation = -1;
68
- this._lastBindCallId = -1;
69
- this.buffer = buffer || null;
70
- this.updateID = -1;
71
- this.byteLength = -1;
72
- this.type = type;
73
- }
74
- }
75
-
76
- class GlBufferSystem {
77
- /**
78
- * @param {Renderer} renderer - The renderer this System works for.
79
- */
80
- constructor(renderer) {
81
- this._gpuBuffers = /* @__PURE__ */ Object.create(null);
82
- /** Cache keeping track of the base bound buffer bases */
83
- this._boundBufferBases = /* @__PURE__ */ Object.create(null);
84
- this._minBaseLocation = 0;
85
- this._nextBindBaseIndex = this._minBaseLocation;
86
- this._bindCallId = 0;
87
- this._renderer = renderer;
88
- this._renderer.renderableGC.addManagedHash(this, "_gpuBuffers");
89
- }
90
- /** @ignore */
91
- destroy() {
92
- this._renderer = null;
93
- this._gl = null;
94
- this._gpuBuffers = null;
95
- this._boundBufferBases = null;
96
- }
97
- /** Sets up the renderer context and necessary buffers. */
98
- contextChange() {
99
- this._gl = this._renderer.gl;
100
- this._gpuBuffers = /* @__PURE__ */ Object.create(null);
101
- this._maxBindings = this._renderer.limits.maxUniformBindings;
102
- }
103
- getGlBuffer(buffer) {
104
- return this._gpuBuffers[buffer.uid] || this.createGLBuffer(buffer);
105
- }
106
- /**
107
- * This binds specified buffer. On first run, it will create the webGL buffers for the context too
108
- * @param buffer - the buffer to bind to the renderer
109
- */
110
- bind(buffer) {
111
- const { _gl: gl } = this;
112
- const glBuffer = this.getGlBuffer(buffer);
113
- gl.bindBuffer(glBuffer.type, glBuffer.buffer);
114
- }
115
- /**
116
- * Binds an uniform buffer to at the given index.
117
- *
118
- * A cache is used so a buffer will not be bound again if already bound.
119
- * @param glBuffer - the buffer to bind
120
- * @param index - the base index to bind it to.
121
- */
122
- bindBufferBase(glBuffer, index) {
123
- const { _gl: gl } = this;
124
- if (this._boundBufferBases[index] !== glBuffer) {
125
- this._boundBufferBases[index] = glBuffer;
126
- glBuffer._lastBindBaseLocation = index;
127
- gl.bindBufferBase(gl.UNIFORM_BUFFER, index, glBuffer.buffer);
128
- }
129
- }
130
- nextBindBase(hasTransformFeedback) {
131
- this._bindCallId++;
132
- this._minBaseLocation = 0;
133
- if (hasTransformFeedback) {
134
- this._boundBufferBases[0] = null;
135
- this._minBaseLocation = 1;
136
- if (this._nextBindBaseIndex < 1) {
137
- this._nextBindBaseIndex = 1;
138
- }
139
- }
140
- }
141
- freeLocationForBufferBase(glBuffer) {
142
- let freeIndex = this.getLastBindBaseLocation(glBuffer);
143
- if (freeIndex >= this._minBaseLocation) {
144
- glBuffer._lastBindCallId = this._bindCallId;
145
- return freeIndex;
146
- }
147
- let loop = 0;
148
- let nextIndex = this._nextBindBaseIndex;
149
- while (loop < 2) {
150
- if (nextIndex >= this._maxBindings) {
151
- nextIndex = this._minBaseLocation;
152
- loop++;
153
- }
154
- const curBuf = this._boundBufferBases[nextIndex];
155
- if (curBuf && curBuf._lastBindCallId === this._bindCallId) {
156
- nextIndex++;
157
- continue;
158
- }
159
- break;
160
- }
161
- freeIndex = nextIndex;
162
- this._nextBindBaseIndex = nextIndex + 1;
163
- if (loop >= 2) {
164
- return -1;
165
- }
166
- glBuffer._lastBindCallId = this._bindCallId;
167
- this._boundBufferBases[freeIndex] = null;
168
- return freeIndex;
169
- }
170
- getLastBindBaseLocation(glBuffer) {
171
- const index = glBuffer._lastBindBaseLocation;
172
- if (this._boundBufferBases[index] === glBuffer) {
173
- return index;
174
- }
175
- return -1;
176
- }
177
- /**
178
- * Binds a buffer whilst also binding its range.
179
- * This will make the buffer start from the offset supplied rather than 0 when it is read.
180
- * @param glBuffer - the buffer to bind
181
- * @param index - the base index to bind at, defaults to 0
182
- * @param offset - the offset to bind at (this is blocks of 256). 0 = 0, 1 = 256, 2 = 512 etc
183
- * @param size - the size to bind at (this is blocks of 256).
184
- */
185
- bindBufferRange(glBuffer, index, offset, size) {
186
- const { _gl: gl } = this;
187
- offset || (offset = 0);
188
- index || (index = 0);
189
- this._boundBufferBases[index] = null;
190
- gl.bindBufferRange(gl.UNIFORM_BUFFER, index || 0, glBuffer.buffer, offset * 256, size || 256);
191
- }
192
- /**
193
- * Will ensure the data in the buffer is uploaded to the GPU.
194
- * @param {Buffer} buffer - the buffer to update
195
- */
196
- updateBuffer(buffer) {
197
- const { _gl: gl } = this;
198
- const glBuffer = this.getGlBuffer(buffer);
199
- if (buffer._updateID === glBuffer.updateID) {
200
- return glBuffer;
201
- }
202
- glBuffer.updateID = buffer._updateID;
203
- gl.bindBuffer(glBuffer.type, glBuffer.buffer);
204
- const data = buffer.data;
205
- const drawType = buffer.descriptor.usage & BufferUsage.STATIC ? gl.STATIC_DRAW : gl.DYNAMIC_DRAW;
206
- if (data) {
207
- if (glBuffer.byteLength >= data.byteLength) {
208
- gl.bufferSubData(glBuffer.type, 0, data, 0, buffer._updateSize / data.BYTES_PER_ELEMENT);
209
- } else {
210
- glBuffer.byteLength = data.byteLength;
211
- gl.bufferData(glBuffer.type, data, drawType);
212
- }
213
- } else {
214
- glBuffer.byteLength = buffer.descriptor.size;
215
- gl.bufferData(glBuffer.type, glBuffer.byteLength, drawType);
216
- }
217
- return glBuffer;
218
- }
219
- /** dispose all WebGL resources of all managed buffers */
220
- destroyAll() {
221
- const gl = this._gl;
222
- for (const id in this._gpuBuffers) {
223
- gl.deleteBuffer(this._gpuBuffers[id].buffer);
224
- }
225
- this._gpuBuffers = /* @__PURE__ */ Object.create(null);
226
- }
227
- /**
228
- * Disposes buffer
229
- * @param {Buffer} buffer - buffer with data
230
- * @param {boolean} [contextLost=false] - If context was lost, we suppress deleteVertexArray
231
- */
232
- onBufferDestroy(buffer, contextLost) {
233
- const glBuffer = this._gpuBuffers[buffer.uid];
234
- const gl = this._gl;
235
- if (!contextLost) {
236
- gl.deleteBuffer(glBuffer.buffer);
237
- }
238
- this._gpuBuffers[buffer.uid] = null;
239
- }
240
- /**
241
- * creates and attaches a GLBuffer object tied to the current context.
242
- * @param buffer
243
- * @protected
244
- */
245
- createGLBuffer(buffer) {
246
- const { _gl: gl } = this;
247
- let type = BUFFER_TYPE.ARRAY_BUFFER;
248
- if (buffer.descriptor.usage & BufferUsage.INDEX) {
249
- type = BUFFER_TYPE.ELEMENT_ARRAY_BUFFER;
250
- } else if (buffer.descriptor.usage & BufferUsage.UNIFORM) {
251
- type = BUFFER_TYPE.UNIFORM_BUFFER;
252
- }
253
- const glBuffer = new GlBuffer(gl.createBuffer(), type);
254
- this._gpuBuffers[buffer.uid] = glBuffer;
255
- buffer.on("destroy", this.onBufferDestroy, this);
256
- return glBuffer;
257
- }
258
- resetState() {
259
- this._boundBufferBases = /* @__PURE__ */ Object.create(null);
260
- }
261
- }
262
- /** @ignore */
263
- GlBufferSystem.extension = {
264
- type: [
265
- ExtensionType.WebGLSystem
266
- ],
267
- name: "buffer"
268
- };
269
-
270
- const _GlContextSystem = class _GlContextSystem {
271
- /** @param renderer - The renderer this System works for. */
272
- constructor(renderer) {
273
- /**
274
- * Features supported by current renderer.
275
- * @type {object}
276
- * @readonly
277
- */
278
- this.supports = {
279
- /** Support for 32-bit indices buffer. */
280
- uint32Indices: true,
281
- /** Support for UniformBufferObjects */
282
- uniformBufferObject: true,
283
- /** Support for VertexArrayObjects */
284
- vertexArrayObject: true,
285
- /** Support for SRGB texture format */
286
- srgbTextures: true,
287
- /** Support for wrapping modes if a texture is non-power of two */
288
- nonPowOf2wrapping: true,
289
- /** Support for MSAA (antialiasing of dynamic textures) */
290
- msaa: true,
291
- /** Support for mipmaps if a texture is non-power of two */
292
- nonPowOf2mipmaps: true
293
- };
294
- this._renderer = renderer;
295
- this.extensions = /* @__PURE__ */ Object.create(null);
296
- this.handleContextLost = this.handleContextLost.bind(this);
297
- this.handleContextRestored = this.handleContextRestored.bind(this);
298
- }
299
- /**
300
- * `true` if the context is lost
301
- * @readonly
302
- */
303
- get isLost() {
304
- return !this.gl || this.gl.isContextLost();
305
- }
306
- /**
307
- * Handles the context change event.
308
- * @param {WebGLRenderingContext} gl - New WebGL context.
309
- */
310
- contextChange(gl) {
311
- this.gl = gl;
312
- this._renderer.gl = gl;
313
- }
314
- init(options) {
315
- options = { ..._GlContextSystem.defaultOptions, ...options };
316
- let multiView = this.multiView = options.multiView;
317
- if (options.context && multiView) {
318
- warn("Renderer created with both a context and multiview enabled. Disabling multiView as both cannot work together.");
319
- multiView = false;
320
- }
321
- if (multiView) {
322
- this.canvas = DOMAdapter.get().createCanvas(this._renderer.canvas.width, this._renderer.canvas.height);
323
- } else {
324
- this.canvas = this._renderer.view.canvas;
325
- }
326
- if (options.context) {
327
- this.initFromContext(options.context);
328
- } else {
329
- const alpha = this._renderer.background.alpha < 1;
330
- const premultipliedAlpha = options.premultipliedAlpha ?? true;
331
- const antialias = options.antialias && !this._renderer.backBuffer.useBackBuffer;
332
- this.createContext(options.preferWebGLVersion, {
333
- alpha,
334
- premultipliedAlpha,
335
- antialias,
336
- stencil: true,
337
- preserveDrawingBuffer: options.preserveDrawingBuffer,
338
- powerPreference: options.powerPreference ?? "default"
339
- });
340
- }
341
- }
342
- ensureCanvasSize(targetCanvas) {
343
- if (!this.multiView) {
344
- if (targetCanvas !== this.canvas) {
345
- warn("multiView is disabled, but targetCanvas is not the main canvas");
346
- }
347
- return;
348
- }
349
- const { canvas } = this;
350
- if (canvas.width < targetCanvas.width || canvas.height < targetCanvas.height) {
351
- canvas.width = Math.max(targetCanvas.width, targetCanvas.width);
352
- canvas.height = Math.max(targetCanvas.height, targetCanvas.height);
353
- }
354
- }
355
- /**
356
- * Initializes the context.
357
- * @protected
358
- * @param {WebGLRenderingContext} gl - WebGL context
359
- */
360
- initFromContext(gl) {
361
- this.gl = gl;
362
- this.webGLVersion = gl instanceof DOMAdapter.get().getWebGLRenderingContext() ? 1 : 2;
363
- this.getExtensions();
364
- this.validateContext(gl);
365
- this._renderer.runners.contextChange.emit(gl);
366
- const element = this._renderer.view.canvas;
367
- element.addEventListener("webglcontextlost", this.handleContextLost, false);
368
- element.addEventListener("webglcontextrestored", this.handleContextRestored, false);
369
- }
370
- /**
371
- * Initialize from context options
372
- * @protected
373
- * @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/getContext
374
- * @param preferWebGLVersion
375
- * @param {object} options - context attributes
376
- */
377
- createContext(preferWebGLVersion, options) {
378
- let gl;
379
- const canvas = this.canvas;
380
- if (preferWebGLVersion === 2) {
381
- gl = canvas.getContext("webgl2", options);
382
- }
383
- if (!gl) {
384
- gl = canvas.getContext("webgl", options);
385
- if (!gl) {
386
- throw new Error("This browser does not support WebGL. Try using the canvas renderer");
387
- }
388
- }
389
- this.gl = gl;
390
- this.initFromContext(this.gl);
391
- }
392
- /** Auto-populate the {@link GlContextSystem.extensions extensions}. */
393
- getExtensions() {
394
- const { gl } = this;
395
- const common = {
396
- anisotropicFiltering: gl.getExtension("EXT_texture_filter_anisotropic"),
397
- floatTextureLinear: gl.getExtension("OES_texture_float_linear"),
398
- s3tc: gl.getExtension("WEBGL_compressed_texture_s3tc"),
399
- s3tc_sRGB: gl.getExtension("WEBGL_compressed_texture_s3tc_srgb"),
400
- // eslint-disable-line camelcase
401
- etc: gl.getExtension("WEBGL_compressed_texture_etc"),
402
- etc1: gl.getExtension("WEBGL_compressed_texture_etc1"),
403
- pvrtc: gl.getExtension("WEBGL_compressed_texture_pvrtc") || gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),
404
- atc: gl.getExtension("WEBGL_compressed_texture_atc"),
405
- astc: gl.getExtension("WEBGL_compressed_texture_astc"),
406
- bptc: gl.getExtension("EXT_texture_compression_bptc"),
407
- rgtc: gl.getExtension("EXT_texture_compression_rgtc"),
408
- loseContext: gl.getExtension("WEBGL_lose_context")
409
- };
410
- if (this.webGLVersion === 1) {
411
- this.extensions = {
412
- ...common,
413
- drawBuffers: gl.getExtension("WEBGL_draw_buffers"),
414
- depthTexture: gl.getExtension("WEBGL_depth_texture"),
415
- vertexArrayObject: gl.getExtension("OES_vertex_array_object") || gl.getExtension("MOZ_OES_vertex_array_object") || gl.getExtension("WEBKIT_OES_vertex_array_object"),
416
- uint32ElementIndex: gl.getExtension("OES_element_index_uint"),
417
- // Floats and half-floats
418
- floatTexture: gl.getExtension("OES_texture_float"),
419
- floatTextureLinear: gl.getExtension("OES_texture_float_linear"),
420
- textureHalfFloat: gl.getExtension("OES_texture_half_float"),
421
- textureHalfFloatLinear: gl.getExtension("OES_texture_half_float_linear"),
422
- vertexAttribDivisorANGLE: gl.getExtension("ANGLE_instanced_arrays"),
423
- srgb: gl.getExtension("EXT_sRGB")
424
- };
425
- } else {
426
- this.extensions = {
427
- ...common,
428
- colorBufferFloat: gl.getExtension("EXT_color_buffer_float")
429
- };
430
- const provokeExt = gl.getExtension("WEBGL_provoking_vertex");
431
- if (provokeExt) {
432
- provokeExt.provokingVertexWEBGL(provokeExt.FIRST_VERTEX_CONVENTION_WEBGL);
433
- }
434
- }
435
- }
436
- /**
437
- * Handles a lost webgl context
438
- * @param {WebGLContextEvent} event - The context lost event.
439
- */
440
- handleContextLost(event) {
441
- event.preventDefault();
442
- if (this._contextLossForced) {
443
- this._contextLossForced = false;
444
- setTimeout(() => {
445
- if (this.gl.isContextLost()) {
446
- this.extensions.loseContext?.restoreContext();
447
- }
448
- }, 0);
449
- }
450
- }
451
- /** Handles a restored webgl context. */
452
- handleContextRestored() {
453
- this.getExtensions();
454
- this._renderer.runners.contextChange.emit(this.gl);
455
- }
456
- destroy() {
457
- const element = this._renderer.view.canvas;
458
- this._renderer = null;
459
- element.removeEventListener("webglcontextlost", this.handleContextLost);
460
- element.removeEventListener("webglcontextrestored", this.handleContextRestored);
461
- this.gl.useProgram(null);
462
- this.extensions.loseContext?.loseContext();
463
- }
464
- /**
465
- * this function can be called to force a webGL context loss
466
- * this will release all resources on the GPU.
467
- * Useful if you need to put Pixi to sleep, and save some GPU memory
468
- *
469
- * As soon as render is called - all resources will be created again.
470
- */
471
- forceContextLoss() {
472
- this.extensions.loseContext?.loseContext();
473
- this._contextLossForced = true;
474
- }
475
- /**
476
- * Validate context.
477
- * @param {WebGLRenderingContext} gl - Render context.
478
- */
479
- validateContext(gl) {
480
- const attributes = gl.getContextAttributes();
481
- if (attributes && !attributes.stencil) {
482
- warn("Provided WebGL context does not have a stencil buffer, masks may not render correctly");
483
- }
484
- const supports = this.supports;
485
- const isWebGl2 = this.webGLVersion === 2;
486
- const extensions = this.extensions;
487
- supports.uint32Indices = isWebGl2 || !!extensions.uint32ElementIndex;
488
- supports.uniformBufferObject = isWebGl2;
489
- supports.vertexArrayObject = isWebGl2 || !!extensions.vertexArrayObject;
490
- supports.srgbTextures = isWebGl2 || !!extensions.srgb;
491
- supports.nonPowOf2wrapping = isWebGl2;
492
- supports.nonPowOf2mipmaps = isWebGl2;
493
- supports.msaa = isWebGl2;
494
- if (!supports.uint32Indices) {
495
- warn("Provided WebGL context does not support 32 index buffer, large scenes may not render correctly");
496
- }
497
- }
498
- };
499
- /** @ignore */
500
- _GlContextSystem.extension = {
501
- type: [
502
- ExtensionType.WebGLSystem
503
- ],
504
- name: "context"
505
- };
506
- /** The default options for the system. */
507
- _GlContextSystem.defaultOptions = {
508
- /**
509
- * {@link WebGLOptions.context}
510
- * @default null
511
- */
512
- context: null,
513
- /**
514
- * {@link WebGLOptions.premultipliedAlpha}
515
- * @default true
516
- */
517
- premultipliedAlpha: true,
518
- /**
519
- * {@link WebGLOptions.preserveDrawingBuffer}
520
- * @default false
521
- */
522
- preserveDrawingBuffer: false,
523
- /**
524
- * {@link WebGLOptions.powerPreference}
525
- * @default default
526
- */
527
- powerPreference: void 0,
528
- /**
529
- * {@link WebGLOptions.webGLVersion}
530
- * @default 2
531
- */
532
- preferWebGLVersion: 2,
533
- /**
534
- * {@link WebGLOptions.multiView}
535
- * @default false
536
- */
537
- multiView: false
538
- };
539
- let GlContextSystem = _GlContextSystem;
540
-
541
- var GL_FORMATS = /* @__PURE__ */ ((GL_FORMATS2) => {
542
- GL_FORMATS2[GL_FORMATS2["RGBA"] = 6408] = "RGBA";
543
- GL_FORMATS2[GL_FORMATS2["RGB"] = 6407] = "RGB";
544
- GL_FORMATS2[GL_FORMATS2["RG"] = 33319] = "RG";
545
- GL_FORMATS2[GL_FORMATS2["RED"] = 6403] = "RED";
546
- GL_FORMATS2[GL_FORMATS2["RGBA_INTEGER"] = 36249] = "RGBA_INTEGER";
547
- GL_FORMATS2[GL_FORMATS2["RGB_INTEGER"] = 36248] = "RGB_INTEGER";
548
- GL_FORMATS2[GL_FORMATS2["RG_INTEGER"] = 33320] = "RG_INTEGER";
549
- GL_FORMATS2[GL_FORMATS2["RED_INTEGER"] = 36244] = "RED_INTEGER";
550
- GL_FORMATS2[GL_FORMATS2["ALPHA"] = 6406] = "ALPHA";
551
- GL_FORMATS2[GL_FORMATS2["LUMINANCE"] = 6409] = "LUMINANCE";
552
- GL_FORMATS2[GL_FORMATS2["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
553
- GL_FORMATS2[GL_FORMATS2["DEPTH_COMPONENT"] = 6402] = "DEPTH_COMPONENT";
554
- GL_FORMATS2[GL_FORMATS2["DEPTH_STENCIL"] = 34041] = "DEPTH_STENCIL";
555
- return GL_FORMATS2;
556
- })(GL_FORMATS || {});
557
- var GL_TARGETS = /* @__PURE__ */ ((GL_TARGETS2) => {
558
- GL_TARGETS2[GL_TARGETS2["TEXTURE_2D"] = 3553] = "TEXTURE_2D";
559
- GL_TARGETS2[GL_TARGETS2["TEXTURE_CUBE_MAP"] = 34067] = "TEXTURE_CUBE_MAP";
560
- GL_TARGETS2[GL_TARGETS2["TEXTURE_2D_ARRAY"] = 35866] = "TEXTURE_2D_ARRAY";
561
- GL_TARGETS2[GL_TARGETS2["TEXTURE_CUBE_MAP_POSITIVE_X"] = 34069] = "TEXTURE_CUBE_MAP_POSITIVE_X";
562
- GL_TARGETS2[GL_TARGETS2["TEXTURE_CUBE_MAP_NEGATIVE_X"] = 34070] = "TEXTURE_CUBE_MAP_NEGATIVE_X";
563
- GL_TARGETS2[GL_TARGETS2["TEXTURE_CUBE_MAP_POSITIVE_Y"] = 34071] = "TEXTURE_CUBE_MAP_POSITIVE_Y";
564
- GL_TARGETS2[GL_TARGETS2["TEXTURE_CUBE_MAP_NEGATIVE_Y"] = 34072] = "TEXTURE_CUBE_MAP_NEGATIVE_Y";
565
- GL_TARGETS2[GL_TARGETS2["TEXTURE_CUBE_MAP_POSITIVE_Z"] = 34073] = "TEXTURE_CUBE_MAP_POSITIVE_Z";
566
- GL_TARGETS2[GL_TARGETS2["TEXTURE_CUBE_MAP_NEGATIVE_Z"] = 34074] = "TEXTURE_CUBE_MAP_NEGATIVE_Z";
567
- return GL_TARGETS2;
568
- })(GL_TARGETS || {});
569
- var GL_TYPES = /* @__PURE__ */ ((GL_TYPES2) => {
570
- GL_TYPES2[GL_TYPES2["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
571
- GL_TYPES2[GL_TYPES2["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
572
- GL_TYPES2[GL_TYPES2["UNSIGNED_SHORT_5_6_5"] = 33635] = "UNSIGNED_SHORT_5_6_5";
573
- GL_TYPES2[GL_TYPES2["UNSIGNED_SHORT_4_4_4_4"] = 32819] = "UNSIGNED_SHORT_4_4_4_4";
574
- GL_TYPES2[GL_TYPES2["UNSIGNED_SHORT_5_5_5_1"] = 32820] = "UNSIGNED_SHORT_5_5_5_1";
575
- GL_TYPES2[GL_TYPES2["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
576
- GL_TYPES2[GL_TYPES2["UNSIGNED_INT_10F_11F_11F_REV"] = 35899] = "UNSIGNED_INT_10F_11F_11F_REV";
577
- GL_TYPES2[GL_TYPES2["UNSIGNED_INT_2_10_10_10_REV"] = 33640] = "UNSIGNED_INT_2_10_10_10_REV";
578
- GL_TYPES2[GL_TYPES2["UNSIGNED_INT_24_8"] = 34042] = "UNSIGNED_INT_24_8";
579
- GL_TYPES2[GL_TYPES2["UNSIGNED_INT_5_9_9_9_REV"] = 35902] = "UNSIGNED_INT_5_9_9_9_REV";
580
- GL_TYPES2[GL_TYPES2["BYTE"] = 5120] = "BYTE";
581
- GL_TYPES2[GL_TYPES2["SHORT"] = 5122] = "SHORT";
582
- GL_TYPES2[GL_TYPES2["INT"] = 5124] = "INT";
583
- GL_TYPES2[GL_TYPES2["FLOAT"] = 5126] = "FLOAT";
584
- GL_TYPES2[GL_TYPES2["FLOAT_32_UNSIGNED_INT_24_8_REV"] = 36269] = "FLOAT_32_UNSIGNED_INT_24_8_REV";
585
- GL_TYPES2[GL_TYPES2["HALF_FLOAT"] = 36193] = "HALF_FLOAT";
586
- return GL_TYPES2;
587
- })(GL_TYPES || {});
588
-
589
- const infoMap = {
590
- uint8x2: GL_TYPES.UNSIGNED_BYTE,
591
- uint8x4: GL_TYPES.UNSIGNED_BYTE,
592
- sint8x2: GL_TYPES.BYTE,
593
- sint8x4: GL_TYPES.BYTE,
594
- unorm8x2: GL_TYPES.UNSIGNED_BYTE,
595
- unorm8x4: GL_TYPES.UNSIGNED_BYTE,
596
- snorm8x2: GL_TYPES.BYTE,
597
- snorm8x4: GL_TYPES.BYTE,
598
- uint16x2: GL_TYPES.UNSIGNED_SHORT,
599
- uint16x4: GL_TYPES.UNSIGNED_SHORT,
600
- sint16x2: GL_TYPES.SHORT,
601
- sint16x4: GL_TYPES.SHORT,
602
- unorm16x2: GL_TYPES.UNSIGNED_SHORT,
603
- unorm16x4: GL_TYPES.UNSIGNED_SHORT,
604
- snorm16x2: GL_TYPES.SHORT,
605
- snorm16x4: GL_TYPES.SHORT,
606
- float16x2: GL_TYPES.HALF_FLOAT,
607
- float16x4: GL_TYPES.HALF_FLOAT,
608
- float32: GL_TYPES.FLOAT,
609
- float32x2: GL_TYPES.FLOAT,
610
- float32x3: GL_TYPES.FLOAT,
611
- float32x4: GL_TYPES.FLOAT,
612
- uint32: GL_TYPES.UNSIGNED_INT,
613
- uint32x2: GL_TYPES.UNSIGNED_INT,
614
- uint32x3: GL_TYPES.UNSIGNED_INT,
615
- uint32x4: GL_TYPES.UNSIGNED_INT,
616
- sint32: GL_TYPES.INT,
617
- sint32x2: GL_TYPES.INT,
618
- sint32x3: GL_TYPES.INT,
619
- sint32x4: GL_TYPES.INT
620
- };
621
- function getGlTypeFromFormat(format) {
622
- return infoMap[format] ?? infoMap.float32;
623
- }
624
-
625
- const topologyToGlMap = {
626
- "point-list": 0,
627
- "line-list": 1,
628
- "line-strip": 3,
629
- "triangle-list": 4,
630
- "triangle-strip": 5
631
- };
632
- class GlGeometrySystem {
633
- /** @param renderer - The renderer this System works for. */
634
- constructor(renderer) {
635
- this._geometryVaoHash = /* @__PURE__ */ Object.create(null);
636
- this._renderer = renderer;
637
- this._activeGeometry = null;
638
- this._activeVao = null;
639
- this.hasVao = true;
640
- this.hasInstance = true;
641
- this._renderer.renderableGC.addManagedHash(this, "_geometryVaoHash");
642
- }
643
- /** Sets up the renderer context and necessary buffers. */
644
- contextChange() {
645
- const gl = this.gl = this._renderer.gl;
646
- if (!this._renderer.context.supports.vertexArrayObject) {
647
- throw new Error("[PixiJS] Vertex Array Objects are not supported on this device");
648
- }
649
- const nativeVaoExtension = this._renderer.context.extensions.vertexArrayObject;
650
- if (nativeVaoExtension) {
651
- gl.createVertexArray = () => nativeVaoExtension.createVertexArrayOES();
652
- gl.bindVertexArray = (vao) => nativeVaoExtension.bindVertexArrayOES(vao);
653
- gl.deleteVertexArray = (vao) => nativeVaoExtension.deleteVertexArrayOES(vao);
654
- }
655
- const nativeInstancedExtension = this._renderer.context.extensions.vertexAttribDivisorANGLE;
656
- if (nativeInstancedExtension) {
657
- gl.drawArraysInstanced = (a, b, c, d) => {
658
- nativeInstancedExtension.drawArraysInstancedANGLE(a, b, c, d);
659
- };
660
- gl.drawElementsInstanced = (a, b, c, d, e) => {
661
- nativeInstancedExtension.drawElementsInstancedANGLE(a, b, c, d, e);
662
- };
663
- gl.vertexAttribDivisor = (a, b) => nativeInstancedExtension.vertexAttribDivisorANGLE(a, b);
664
- }
665
- this._activeGeometry = null;
666
- this._activeVao = null;
667
- this._geometryVaoHash = /* @__PURE__ */ Object.create(null);
668
- }
669
- /**
670
- * Binds geometry so that is can be drawn. Creating a Vao if required
671
- * @param geometry - Instance of geometry to bind.
672
- * @param program - Instance of program to use vao for.
673
- */
674
- bind(geometry, program) {
675
- const gl = this.gl;
676
- this._activeGeometry = geometry;
677
- const vao = this.getVao(geometry, program);
678
- if (this._activeVao !== vao) {
679
- this._activeVao = vao;
680
- gl.bindVertexArray(vao);
681
- }
682
- this.updateBuffers();
683
- }
684
- /** Reset and unbind any active VAO and geometry. */
685
- resetState() {
686
- this.unbind();
687
- }
688
- /** Update buffers of the currently bound geometry. */
689
- updateBuffers() {
690
- const geometry = this._activeGeometry;
691
- const bufferSystem = this._renderer.buffer;
692
- for (let i = 0; i < geometry.buffers.length; i++) {
693
- const buffer = geometry.buffers[i];
694
- bufferSystem.updateBuffer(buffer);
695
- }
696
- }
697
- /**
698
- * Check compatibility between a geometry and a program
699
- * @param geometry - Geometry instance.
700
- * @param program - Program instance.
701
- */
702
- checkCompatibility(geometry, program) {
703
- const geometryAttributes = geometry.attributes;
704
- const shaderAttributes = program._attributeData;
705
- for (const j in shaderAttributes) {
706
- if (!geometryAttributes[j]) {
707
- throw new Error(`shader and geometry incompatible, geometry missing the "${j}" attribute`);
708
- }
709
- }
710
- }
711
- /**
712
- * Takes a geometry and program and generates a unique signature for them.
713
- * @param geometry - To get signature from.
714
- * @param program - To test geometry against.
715
- * @returns - Unique signature of the geometry and program
716
- */
717
- getSignature(geometry, program) {
718
- const attribs = geometry.attributes;
719
- const shaderAttributes = program._attributeData;
720
- const strings = ["g", geometry.uid];
721
- for (const i in attribs) {
722
- if (shaderAttributes[i]) {
723
- strings.push(i, shaderAttributes[i].location);
724
- }
725
- }
726
- return strings.join("-");
727
- }
728
- getVao(geometry, program) {
729
- return this._geometryVaoHash[geometry.uid]?.[program._key] || this.initGeometryVao(geometry, program);
730
- }
731
- /**
732
- * Creates or gets Vao with the same structure as the geometry and stores it on the geometry.
733
- * If vao is created, it is bound automatically. We use a shader to infer what and how to set up the
734
- * attribute locations.
735
- * @param geometry - Instance of geometry to to generate Vao for.
736
- * @param program
737
- * @param _incRefCount - Increment refCount of all geometry buffers.
738
- */
739
- initGeometryVao(geometry, program, _incRefCount = true) {
740
- const gl = this._renderer.gl;
741
- const bufferSystem = this._renderer.buffer;
742
- this._renderer.shader._getProgramData(program);
743
- this.checkCompatibility(geometry, program);
744
- const signature = this.getSignature(geometry, program);
745
- if (!this._geometryVaoHash[geometry.uid]) {
746
- this._geometryVaoHash[geometry.uid] = /* @__PURE__ */ Object.create(null);
747
- geometry.on("destroy", this.onGeometryDestroy, this);
748
- }
749
- const vaoObjectHash = this._geometryVaoHash[geometry.uid];
750
- let vao = vaoObjectHash[signature];
751
- if (vao) {
752
- vaoObjectHash[program._key] = vao;
753
- return vao;
754
- }
755
- ensureAttributes(geometry, program._attributeData);
756
- const buffers = geometry.buffers;
757
- vao = gl.createVertexArray();
758
- gl.bindVertexArray(vao);
759
- for (let i = 0; i < buffers.length; i++) {
760
- const buffer = buffers[i];
761
- bufferSystem.bind(buffer);
762
- }
763
- this.activateVao(geometry, program);
764
- vaoObjectHash[program._key] = vao;
765
- vaoObjectHash[signature] = vao;
766
- gl.bindVertexArray(null);
767
- return vao;
768
- }
769
- /**
770
- * Disposes geometry.
771
- * @param geometry - Geometry with buffers. Only VAO will be disposed
772
- * @param [contextLost=false] - If context was lost, we suppress deleteVertexArray
773
- */
774
- onGeometryDestroy(geometry, contextLost) {
775
- const vaoObjectHash = this._geometryVaoHash[geometry.uid];
776
- const gl = this.gl;
777
- if (vaoObjectHash) {
778
- if (contextLost) {
779
- for (const i in vaoObjectHash) {
780
- if (this._activeVao !== vaoObjectHash[i]) {
781
- this.unbind();
782
- }
783
- gl.deleteVertexArray(vaoObjectHash[i]);
784
- }
785
- }
786
- this._geometryVaoHash[geometry.uid] = null;
787
- }
788
- }
789
- /**
790
- * Dispose all WebGL resources of all managed geometries.
791
- * @param [contextLost=false] - If context was lost, we suppress `gl.delete` calls
792
- */
793
- destroyAll(contextLost = false) {
794
- const gl = this.gl;
795
- for (const i in this._geometryVaoHash) {
796
- if (contextLost) {
797
- for (const j in this._geometryVaoHash[i]) {
798
- const vaoObjectHash = this._geometryVaoHash[i];
799
- if (this._activeVao !== vaoObjectHash) {
800
- this.unbind();
801
- }
802
- gl.deleteVertexArray(vaoObjectHash[j]);
803
- }
804
- }
805
- this._geometryVaoHash[i] = null;
806
- }
807
- }
808
- /**
809
- * Activate vertex array object.
810
- * @param geometry - Geometry instance.
811
- * @param program - Shader program instance.
812
- */
813
- activateVao(geometry, program) {
814
- const gl = this._renderer.gl;
815
- const bufferSystem = this._renderer.buffer;
816
- const attributes = geometry.attributes;
817
- if (geometry.indexBuffer) {
818
- bufferSystem.bind(geometry.indexBuffer);
819
- }
820
- let lastBuffer = null;
821
- for (const j in attributes) {
822
- const attribute = attributes[j];
823
- const buffer = attribute.buffer;
824
- const glBuffer = bufferSystem.getGlBuffer(buffer);
825
- const programAttrib = program._attributeData[j];
826
- if (programAttrib) {
827
- if (lastBuffer !== glBuffer) {
828
- bufferSystem.bind(buffer);
829
- lastBuffer = glBuffer;
830
- }
831
- const location = programAttrib.location;
832
- gl.enableVertexAttribArray(location);
833
- const attributeInfo = getAttributeInfoFromFormat(attribute.format);
834
- const type = getGlTypeFromFormat(attribute.format);
835
- if (programAttrib.format?.substring(1, 4) === "int") {
836
- gl.vertexAttribIPointer(
837
- location,
838
- attributeInfo.size,
839
- type,
840
- attribute.stride,
841
- attribute.offset
842
- );
843
- } else {
844
- gl.vertexAttribPointer(
845
- location,
846
- attributeInfo.size,
847
- type,
848
- attributeInfo.normalised,
849
- attribute.stride,
850
- attribute.offset
851
- );
852
- }
853
- if (attribute.instance) {
854
- if (this.hasInstance) {
855
- const divisor = attribute.divisor ?? 1;
856
- gl.vertexAttribDivisor(location, divisor);
857
- } else {
858
- throw new Error("geometry error, GPU Instancing is not supported on this device");
859
- }
860
- }
861
- }
862
- }
863
- }
864
- /**
865
- * Draws the currently bound geometry.
866
- * @param topology - The type primitive to render.
867
- * @param size - The number of elements to be rendered. If not specified, all vertices after the
868
- * starting vertex will be drawn.
869
- * @param start - The starting vertex in the geometry to start drawing from. If not specified,
870
- * drawing will start from the first vertex.
871
- * @param instanceCount - The number of instances of the set of elements to execute. If not specified,
872
- * all instances will be drawn.
873
- */
874
- draw(topology, size, start, instanceCount) {
875
- const { gl } = this._renderer;
876
- const geometry = this._activeGeometry;
877
- const glTopology = topologyToGlMap[topology || geometry.topology];
878
- instanceCount ?? (instanceCount = geometry.instanceCount);
879
- if (geometry.indexBuffer) {
880
- const byteSize = geometry.indexBuffer.data.BYTES_PER_ELEMENT;
881
- const glType = byteSize === 2 ? gl.UNSIGNED_SHORT : gl.UNSIGNED_INT;
882
- if (instanceCount > 1) {
883
- gl.drawElementsInstanced(glTopology, size || geometry.indexBuffer.data.length, glType, (start || 0) * byteSize, instanceCount);
884
- } else {
885
- gl.drawElements(glTopology, size || geometry.indexBuffer.data.length, glType, (start || 0) * byteSize);
886
- }
887
- } else if (instanceCount > 1) {
888
- gl.drawArraysInstanced(glTopology, start || 0, size || geometry.getSize(), instanceCount);
889
- } else {
890
- gl.drawArrays(glTopology, start || 0, size || geometry.getSize());
891
- }
892
- return this;
893
- }
894
- /** Unbind/reset everything. */
895
- unbind() {
896
- this.gl.bindVertexArray(null);
897
- this._activeVao = null;
898
- this._activeGeometry = null;
899
- }
900
- destroy() {
901
- this._renderer = null;
902
- this.gl = null;
903
- this._activeVao = null;
904
- this._activeGeometry = null;
905
- }
906
- }
907
- /** @ignore */
908
- GlGeometrySystem.extension = {
909
- type: [
910
- ExtensionType.WebGLSystem
911
- ],
912
- name: "geometry"
913
- };
914
-
915
- const bigTriangleGeometry = new Geometry({
916
- attributes: {
917
- aPosition: [
918
- -1,
919
- -1,
920
- // Bottom left corner
921
- 3,
922
- -1,
923
- // Bottom right corner, extending beyond right edge
924
- -1,
925
- 3
926
- // Top left corner, extending beyond top edge
927
- ]
928
- }
929
- });
930
- const _GlBackBufferSystem = class _GlBackBufferSystem {
931
- constructor(renderer) {
932
- /** if true, the back buffer is used */
933
- this.useBackBuffer = false;
934
- this._useBackBufferThisRender = false;
935
- this._renderer = renderer;
936
- }
937
- init(options = {}) {
938
- const { useBackBuffer, antialias } = { ..._GlBackBufferSystem.defaultOptions, ...options };
939
- this.useBackBuffer = useBackBuffer;
940
- this._antialias = antialias;
941
- if (!this._renderer.context.supports.msaa) {
942
- warn("antialiasing, is not supported on when using the back buffer");
943
- this._antialias = false;
944
- }
945
- this._state = State.for2d();
946
- const bigTriangleProgram = new GlProgram({
947
- vertex: `
948
- attribute vec2 aPosition;
949
- out vec2 vUv;
950
-
951
- void main() {
952
- gl_Position = vec4(aPosition, 0.0, 1.0);
953
-
954
- vUv = (aPosition + 1.0) / 2.0;
955
-
956
- // flip dem UVs
957
- vUv.y = 1.0 - vUv.y;
958
- }`,
959
- fragment: `
960
- in vec2 vUv;
961
- out vec4 finalColor;
962
-
963
- uniform sampler2D uTexture;
964
-
965
- void main() {
966
- finalColor = texture(uTexture, vUv);
967
- }`,
968
- name: "big-triangle"
969
- });
970
- this._bigTriangleShader = new Shader({
971
- glProgram: bigTriangleProgram,
972
- resources: {
973
- uTexture: Texture.WHITE.source
974
- }
975
- });
976
- }
977
- /**
978
- * This is called before the RenderTargetSystem is started. This is where
979
- * we replace the target with the back buffer if required.
980
- * @param options - The options for this render.
981
- */
982
- renderStart(options) {
983
- const renderTarget = this._renderer.renderTarget.getRenderTarget(options.target);
984
- this._useBackBufferThisRender = this.useBackBuffer && !!renderTarget.isRoot;
985
- if (this._useBackBufferThisRender) {
986
- const renderTarget2 = this._renderer.renderTarget.getRenderTarget(options.target);
987
- this._targetTexture = renderTarget2.colorTexture;
988
- options.target = this._getBackBufferTexture(renderTarget2.colorTexture);
989
- }
990
- }
991
- renderEnd() {
992
- this._presentBackBuffer();
993
- }
994
- _presentBackBuffer() {
995
- const renderer = this._renderer;
996
- renderer.renderTarget.finishRenderPass();
997
- if (!this._useBackBufferThisRender)
998
- return;
999
- renderer.renderTarget.bind(this._targetTexture, false);
1000
- this._bigTriangleShader.resources.uTexture = this._backBufferTexture.source;
1001
- renderer.encoder.draw({
1002
- geometry: bigTriangleGeometry,
1003
- shader: this._bigTriangleShader,
1004
- state: this._state
1005
- });
1006
- }
1007
- _getBackBufferTexture(targetSourceTexture) {
1008
- this._backBufferTexture = this._backBufferTexture || new Texture({
1009
- source: new TextureSource({
1010
- width: targetSourceTexture.width,
1011
- height: targetSourceTexture.height,
1012
- resolution: targetSourceTexture._resolution,
1013
- antialias: this._antialias
1014
- })
1015
- });
1016
- this._backBufferTexture.source.resize(
1017
- targetSourceTexture.width,
1018
- targetSourceTexture.height,
1019
- targetSourceTexture._resolution
1020
- );
1021
- return this._backBufferTexture;
1022
- }
1023
- /** destroys the back buffer */
1024
- destroy() {
1025
- if (this._backBufferTexture) {
1026
- this._backBufferTexture.destroy();
1027
- this._backBufferTexture = null;
1028
- }
1029
- }
1030
- };
1031
- /** @ignore */
1032
- _GlBackBufferSystem.extension = {
1033
- type: [
1034
- ExtensionType.WebGLSystem
1035
- ],
1036
- name: "backBuffer",
1037
- priority: 1
1038
- };
1039
- /** default options for the back buffer system */
1040
- _GlBackBufferSystem.defaultOptions = {
1041
- /** if true will use the back buffer where required */
1042
- useBackBuffer: false
1043
- };
1044
- let GlBackBufferSystem = _GlBackBufferSystem;
1045
-
1046
- class GlColorMaskSystem {
1047
- constructor(renderer) {
1048
- this._colorMaskCache = 15;
1049
- this._renderer = renderer;
1050
- }
1051
- setMask(colorMask) {
1052
- if (this._colorMaskCache === colorMask)
1053
- return;
1054
- this._colorMaskCache = colorMask;
1055
- this._renderer.gl.colorMask(
1056
- !!(colorMask & 8),
1057
- !!(colorMask & 4),
1058
- !!(colorMask & 2),
1059
- !!(colorMask & 1)
1060
- );
1061
- }
1062
- }
1063
- /** @ignore */
1064
- GlColorMaskSystem.extension = {
1065
- type: [
1066
- ExtensionType.WebGLSystem
1067
- ],
1068
- name: "colorMask"
1069
- };
1070
-
1071
- class GlEncoderSystem {
1072
- constructor(renderer) {
1073
- this.commandFinished = Promise.resolve();
1074
- this._renderer = renderer;
1075
- }
1076
- setGeometry(geometry, shader) {
1077
- this._renderer.geometry.bind(geometry, shader.glProgram);
1078
- }
1079
- finishRenderPass() {
1080
- }
1081
- draw(options) {
1082
- const renderer = this._renderer;
1083
- const { geometry, shader, state, skipSync, topology: type, size, start, instanceCount } = options;
1084
- renderer.shader.bind(shader, skipSync);
1085
- renderer.geometry.bind(geometry, renderer.shader._activeProgram);
1086
- if (state) {
1087
- renderer.state.set(state);
1088
- }
1089
- renderer.geometry.draw(type, size, start, instanceCount ?? geometry.instanceCount);
1090
- }
1091
- destroy() {
1092
- this._renderer = null;
1093
- }
1094
- }
1095
- /** @ignore */
1096
- GlEncoderSystem.extension = {
1097
- type: [
1098
- ExtensionType.WebGLSystem
1099
- ],
1100
- name: "encoder"
1101
- };
1102
-
1103
- class GlLimitsSystem {
1104
- constructor(renderer) {
1105
- this._renderer = renderer;
1106
- }
1107
- contextChange() {
1108
- const gl = this._renderer.gl;
1109
- this.maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
1110
- this.maxBatchableTextures = checkMaxIfStatementsInShader(this.maxTextures, gl);
1111
- this.maxUniformBindings = gl.getParameter(gl.MAX_UNIFORM_BUFFER_BINDINGS);
1112
- }
1113
- destroy() {
1114
- }
1115
- }
1116
- /** @ignore */
1117
- GlLimitsSystem.extension = {
1118
- type: [
1119
- ExtensionType.WebGLSystem
1120
- ],
1121
- name: "limits"
1122
- };
1123
-
1124
- class GlRenderTarget {
1125
- constructor() {
1126
- this.width = -1;
1127
- this.height = -1;
1128
- this.msaa = false;
1129
- this.msaaRenderBuffer = [];
1130
- }
1131
- }
1132
-
1133
- class GlStencilSystem {
1134
- constructor(renderer) {
1135
- this._stencilCache = {
1136
- enabled: false,
1137
- stencilReference: 0,
1138
- stencilMode: STENCIL_MODES.NONE
1139
- };
1140
- this._renderTargetStencilState = /* @__PURE__ */ Object.create(null);
1141
- renderer.renderTarget.onRenderTargetChange.add(this);
1142
- }
1143
- contextChange(gl) {
1144
- this._gl = gl;
1145
- this._comparisonFuncMapping = {
1146
- always: gl.ALWAYS,
1147
- never: gl.NEVER,
1148
- equal: gl.EQUAL,
1149
- "not-equal": gl.NOTEQUAL,
1150
- less: gl.LESS,
1151
- "less-equal": gl.LEQUAL,
1152
- greater: gl.GREATER,
1153
- "greater-equal": gl.GEQUAL
1154
- };
1155
- this._stencilOpsMapping = {
1156
- keep: gl.KEEP,
1157
- zero: gl.ZERO,
1158
- replace: gl.REPLACE,
1159
- invert: gl.INVERT,
1160
- "increment-clamp": gl.INCR,
1161
- "decrement-clamp": gl.DECR,
1162
- "increment-wrap": gl.INCR_WRAP,
1163
- "decrement-wrap": gl.DECR_WRAP
1164
- };
1165
- this.resetState();
1166
- }
1167
- onRenderTargetChange(renderTarget) {
1168
- if (this._activeRenderTarget === renderTarget)
1169
- return;
1170
- this._activeRenderTarget = renderTarget;
1171
- let stencilState = this._renderTargetStencilState[renderTarget.uid];
1172
- if (!stencilState) {
1173
- stencilState = this._renderTargetStencilState[renderTarget.uid] = {
1174
- stencilMode: STENCIL_MODES.DISABLED,
1175
- stencilReference: 0
1176
- };
1177
- }
1178
- this.setStencilMode(stencilState.stencilMode, stencilState.stencilReference);
1179
- }
1180
- resetState() {
1181
- this._stencilCache.enabled = false;
1182
- this._stencilCache.stencilMode = STENCIL_MODES.NONE;
1183
- this._stencilCache.stencilReference = 0;
1184
- }
1185
- setStencilMode(stencilMode, stencilReference) {
1186
- const stencilState = this._renderTargetStencilState[this._activeRenderTarget.uid];
1187
- const gl = this._gl;
1188
- const mode = GpuStencilModesToPixi[stencilMode];
1189
- const _stencilCache = this._stencilCache;
1190
- stencilState.stencilMode = stencilMode;
1191
- stencilState.stencilReference = stencilReference;
1192
- if (stencilMode === STENCIL_MODES.DISABLED) {
1193
- if (this._stencilCache.enabled) {
1194
- this._stencilCache.enabled = false;
1195
- gl.disable(gl.STENCIL_TEST);
1196
- }
1197
- return;
1198
- }
1199
- if (!this._stencilCache.enabled) {
1200
- this._stencilCache.enabled = true;
1201
- gl.enable(gl.STENCIL_TEST);
1202
- }
1203
- if (stencilMode !== _stencilCache.stencilMode || _stencilCache.stencilReference !== stencilReference) {
1204
- _stencilCache.stencilMode = stencilMode;
1205
- _stencilCache.stencilReference = stencilReference;
1206
- gl.stencilFunc(this._comparisonFuncMapping[mode.stencilBack.compare], stencilReference, 255);
1207
- gl.stencilOp(gl.KEEP, gl.KEEP, this._stencilOpsMapping[mode.stencilBack.passOp]);
1208
- }
1209
- }
1210
- }
1211
- /** @ignore */
1212
- GlStencilSystem.extension = {
1213
- type: [
1214
- ExtensionType.WebGLSystem
1215
- ],
1216
- name: "stencil"
1217
- };
1218
-
1219
- const WGSL_TO_STD40_SIZE = {
1220
- f32: 4,
1221
- i32: 4,
1222
- "vec2<f32>": 8,
1223
- "vec3<f32>": 12,
1224
- "vec4<f32>": 16,
1225
- "vec2<i32>": 8,
1226
- "vec3<i32>": 12,
1227
- "vec4<i32>": 16,
1228
- "mat2x2<f32>": 16 * 2,
1229
- "mat3x3<f32>": 16 * 3,
1230
- "mat4x4<f32>": 16 * 4
1231
- // TODO - not essential for now but support these in the future
1232
- // int: 4,
1233
- // ivec2: 8,
1234
- // ivec3: 12,
1235
- // ivec4: 16,
1236
- // uint: 4,
1237
- // uvec2: 8,
1238
- // uvec3: 12,
1239
- // uvec4: 16,
1240
- // bool: 4,
1241
- // bvec2: 8,
1242
- // bvec3: 12,
1243
- // bvec4: 16,
1244
- // mat2: 16 * 2,
1245
- // mat3: 16 * 3,
1246
- // mat4: 16 * 4,
1247
- };
1248
- function createUboElementsSTD40(uniformData) {
1249
- const uboElements = uniformData.map((data) => ({
1250
- data,
1251
- offset: 0,
1252
- size: 0
1253
- }));
1254
- const chunkSize = 16;
1255
- let size = 0;
1256
- let offset = 0;
1257
- for (let i = 0; i < uboElements.length; i++) {
1258
- const uboElement = uboElements[i];
1259
- size = WGSL_TO_STD40_SIZE[uboElement.data.type];
1260
- if (!size) {
1261
- throw new Error(`Unknown type ${uboElement.data.type}`);
1262
- }
1263
- if (uboElement.data.size > 1) {
1264
- size = Math.max(size, chunkSize) * uboElement.data.size;
1265
- }
1266
- const boundary = size === 12 ? 16 : size;
1267
- uboElement.size = size;
1268
- const curOffset = offset % chunkSize;
1269
- if (curOffset > 0 && chunkSize - curOffset < boundary) {
1270
- offset += (chunkSize - curOffset) % 16;
1271
- } else {
1272
- offset += (size - curOffset % size) % size;
1273
- }
1274
- uboElement.offset = offset;
1275
- offset += size;
1276
- }
1277
- offset = Math.ceil(offset / 16) * 16;
1278
- return { uboElements, size: offset };
1279
- }
1280
-
1281
- function generateArraySyncSTD40(uboElement, offsetToAdd) {
1282
- const rowSize = Math.max(WGSL_TO_STD40_SIZE[uboElement.data.type] / 16, 1);
1283
- const elementSize = uboElement.data.value.length / uboElement.data.size;
1284
- const remainder = (4 - elementSize % 4) % 4;
1285
- const data = uboElement.data.type.indexOf("i32") >= 0 ? "dataInt32" : "data";
1286
- return `
1287
- v = uv.${uboElement.data.name};
1288
- offset += ${offsetToAdd};
1289
-
1290
- arrayOffset = offset;
1291
-
1292
- t = 0;
1293
-
1294
- for(var i=0; i < ${uboElement.data.size * rowSize}; i++)
1295
- {
1296
- for(var j = 0; j < ${elementSize}; j++)
1297
- {
1298
- ${data}[arrayOffset++] = v[t++];
1299
- }
1300
- ${remainder !== 0 ? `arrayOffset += ${remainder};` : ""}
1301
- }
1302
- `;
1303
- }
1304
-
1305
- function createUboSyncFunctionSTD40(uboElements) {
1306
- return createUboSyncFunction(
1307
- uboElements,
1308
- "uboStd40",
1309
- generateArraySyncSTD40,
1310
- uboSyncFunctionsSTD40
1311
- );
1312
- }
1313
-
1314
- class GlUboSystem extends UboSystem {
1315
- constructor() {
1316
- super({
1317
- createUboElements: createUboElementsSTD40,
1318
- generateUboSync: createUboSyncFunctionSTD40
1319
- });
1320
- }
1321
- }
1322
- /** @ignore */
1323
- GlUboSystem.extension = {
1324
- type: [ExtensionType.WebGLSystem],
1325
- name: "ubo"
1326
- };
1327
-
1328
- class GlRenderTargetAdaptor {
1329
- constructor() {
1330
- this._clearColorCache = [0, 0, 0, 0];
1331
- this._viewPortCache = new Rectangle();
1332
- }
1333
- init(renderer, renderTargetSystem) {
1334
- this._renderer = renderer;
1335
- this._renderTargetSystem = renderTargetSystem;
1336
- renderer.runners.contextChange.add(this);
1337
- }
1338
- contextChange() {
1339
- this._clearColorCache = [0, 0, 0, 0];
1340
- this._viewPortCache = new Rectangle();
1341
- }
1342
- copyToTexture(sourceRenderSurfaceTexture, destinationTexture, originSrc, size, originDest) {
1343
- const renderTargetSystem = this._renderTargetSystem;
1344
- const renderer = this._renderer;
1345
- const glRenderTarget = renderTargetSystem.getGpuRenderTarget(sourceRenderSurfaceTexture);
1346
- const gl = renderer.gl;
1347
- this.finishRenderPass(sourceRenderSurfaceTexture);
1348
- gl.bindFramebuffer(gl.FRAMEBUFFER, glRenderTarget.resolveTargetFramebuffer);
1349
- renderer.texture.bind(destinationTexture, 0);
1350
- gl.copyTexSubImage2D(
1351
- gl.TEXTURE_2D,
1352
- 0,
1353
- originDest.x,
1354
- originDest.y,
1355
- originSrc.x,
1356
- originSrc.y,
1357
- size.width,
1358
- size.height
1359
- );
1360
- return destinationTexture;
1361
- }
1362
- startRenderPass(renderTarget, clear = true, clearColor, viewport) {
1363
- const renderTargetSystem = this._renderTargetSystem;
1364
- const source = renderTarget.colorTexture;
1365
- const gpuRenderTarget = renderTargetSystem.getGpuRenderTarget(renderTarget);
1366
- let viewPortY = viewport.y;
1367
- if (renderTarget.isRoot) {
1368
- viewPortY = source.pixelHeight - viewport.height;
1369
- }
1370
- renderTarget.colorTextures.forEach((texture) => {
1371
- this._renderer.texture.unbind(texture);
1372
- });
1373
- const gl = this._renderer.gl;
1374
- gl.bindFramebuffer(gl.FRAMEBUFFER, gpuRenderTarget.framebuffer);
1375
- const viewPortCache = this._viewPortCache;
1376
- if (viewPortCache.x !== viewport.x || viewPortCache.y !== viewPortY || viewPortCache.width !== viewport.width || viewPortCache.height !== viewport.height) {
1377
- viewPortCache.x = viewport.x;
1378
- viewPortCache.y = viewPortY;
1379
- viewPortCache.width = viewport.width;
1380
- viewPortCache.height = viewport.height;
1381
- gl.viewport(
1382
- viewport.x,
1383
- viewPortY,
1384
- viewport.width,
1385
- viewport.height
1386
- );
1387
- }
1388
- if (!gpuRenderTarget.depthStencilRenderBuffer && (renderTarget.stencil || renderTarget.depth)) {
1389
- this._initStencil(gpuRenderTarget);
1390
- }
1391
- this.clear(renderTarget, clear, clearColor);
1392
- }
1393
- finishRenderPass(renderTarget) {
1394
- const renderTargetSystem = this._renderTargetSystem;
1395
- const glRenderTarget = renderTargetSystem.getGpuRenderTarget(renderTarget);
1396
- if (!glRenderTarget.msaa)
1397
- return;
1398
- const gl = this._renderer.gl;
1399
- gl.bindFramebuffer(gl.FRAMEBUFFER, glRenderTarget.resolveTargetFramebuffer);
1400
- gl.bindFramebuffer(gl.READ_FRAMEBUFFER, glRenderTarget.framebuffer);
1401
- gl.blitFramebuffer(
1402
- 0,
1403
- 0,
1404
- glRenderTarget.width,
1405
- glRenderTarget.height,
1406
- 0,
1407
- 0,
1408
- glRenderTarget.width,
1409
- glRenderTarget.height,
1410
- gl.COLOR_BUFFER_BIT,
1411
- gl.NEAREST
1412
- );
1413
- gl.bindFramebuffer(gl.FRAMEBUFFER, glRenderTarget.framebuffer);
1414
- }
1415
- initGpuRenderTarget(renderTarget) {
1416
- const renderer = this._renderer;
1417
- const gl = renderer.gl;
1418
- const glRenderTarget = new GlRenderTarget();
1419
- const colorTexture = renderTarget.colorTexture;
1420
- if (colorTexture instanceof CanvasSource) {
1421
- this._renderer.context.ensureCanvasSize(renderTarget.colorTexture.resource);
1422
- glRenderTarget.framebuffer = null;
1423
- return glRenderTarget;
1424
- }
1425
- this._initColor(renderTarget, glRenderTarget);
1426
- gl.bindFramebuffer(gl.FRAMEBUFFER, null);
1427
- return glRenderTarget;
1428
- }
1429
- destroyGpuRenderTarget(gpuRenderTarget) {
1430
- const gl = this._renderer.gl;
1431
- if (gpuRenderTarget.framebuffer) {
1432
- gl.deleteFramebuffer(gpuRenderTarget.framebuffer);
1433
- gpuRenderTarget.framebuffer = null;
1434
- }
1435
- if (gpuRenderTarget.resolveTargetFramebuffer) {
1436
- gl.deleteFramebuffer(gpuRenderTarget.resolveTargetFramebuffer);
1437
- gpuRenderTarget.resolveTargetFramebuffer = null;
1438
- }
1439
- if (gpuRenderTarget.depthStencilRenderBuffer) {
1440
- gl.deleteRenderbuffer(gpuRenderTarget.depthStencilRenderBuffer);
1441
- gpuRenderTarget.depthStencilRenderBuffer = null;
1442
- }
1443
- gpuRenderTarget.msaaRenderBuffer.forEach((renderBuffer) => {
1444
- gl.deleteRenderbuffer(renderBuffer);
1445
- });
1446
- gpuRenderTarget.msaaRenderBuffer = null;
1447
- }
1448
- clear(_renderTarget, clear, clearColor) {
1449
- if (!clear)
1450
- return;
1451
- const renderTargetSystem = this._renderTargetSystem;
1452
- if (typeof clear === "boolean") {
1453
- clear = clear ? CLEAR.ALL : CLEAR.NONE;
1454
- }
1455
- const gl = this._renderer.gl;
1456
- if (clear & CLEAR.COLOR) {
1457
- clearColor ?? (clearColor = renderTargetSystem.defaultClearColor);
1458
- const clearColorCache = this._clearColorCache;
1459
- const clearColorArray = clearColor;
1460
- if (clearColorCache[0] !== clearColorArray[0] || clearColorCache[1] !== clearColorArray[1] || clearColorCache[2] !== clearColorArray[2] || clearColorCache[3] !== clearColorArray[3]) {
1461
- clearColorCache[0] = clearColorArray[0];
1462
- clearColorCache[1] = clearColorArray[1];
1463
- clearColorCache[2] = clearColorArray[2];
1464
- clearColorCache[3] = clearColorArray[3];
1465
- gl.clearColor(clearColorArray[0], clearColorArray[1], clearColorArray[2], clearColorArray[3]);
1466
- }
1467
- }
1468
- gl.clear(clear);
1469
- }
1470
- resizeGpuRenderTarget(renderTarget) {
1471
- if (renderTarget.isRoot)
1472
- return;
1473
- const renderTargetSystem = this._renderTargetSystem;
1474
- const glRenderTarget = renderTargetSystem.getGpuRenderTarget(renderTarget);
1475
- this._resizeColor(renderTarget, glRenderTarget);
1476
- if (renderTarget.stencil || renderTarget.depth) {
1477
- this._resizeStencil(glRenderTarget);
1478
- }
1479
- }
1480
- _initColor(renderTarget, glRenderTarget) {
1481
- const renderer = this._renderer;
1482
- const gl = renderer.gl;
1483
- const resolveTargetFramebuffer = gl.createFramebuffer();
1484
- glRenderTarget.resolveTargetFramebuffer = resolveTargetFramebuffer;
1485
- gl.bindFramebuffer(gl.FRAMEBUFFER, resolveTargetFramebuffer);
1486
- glRenderTarget.width = renderTarget.colorTexture.source.pixelWidth;
1487
- glRenderTarget.height = renderTarget.colorTexture.source.pixelHeight;
1488
- renderTarget.colorTextures.forEach((colorTexture, i) => {
1489
- const source = colorTexture.source;
1490
- if (source.antialias) {
1491
- if (renderer.context.supports.msaa) {
1492
- glRenderTarget.msaa = true;
1493
- } else {
1494
- warn("[RenderTexture] Antialiasing on textures is not supported in WebGL1");
1495
- }
1496
- }
1497
- renderer.texture.bindSource(source, 0);
1498
- const glSource = renderer.texture.getGlSource(source);
1499
- const glTexture = glSource.texture;
1500
- gl.framebufferTexture2D(
1501
- gl.FRAMEBUFFER,
1502
- gl.COLOR_ATTACHMENT0 + i,
1503
- 3553,
1504
- // texture.target,
1505
- glTexture,
1506
- 0
1507
- );
1508
- });
1509
- if (glRenderTarget.msaa) {
1510
- const viewFramebuffer = gl.createFramebuffer();
1511
- glRenderTarget.framebuffer = viewFramebuffer;
1512
- gl.bindFramebuffer(gl.FRAMEBUFFER, viewFramebuffer);
1513
- renderTarget.colorTextures.forEach((_, i) => {
1514
- const msaaRenderBuffer = gl.createRenderbuffer();
1515
- glRenderTarget.msaaRenderBuffer[i] = msaaRenderBuffer;
1516
- });
1517
- } else {
1518
- glRenderTarget.framebuffer = resolveTargetFramebuffer;
1519
- }
1520
- this._resizeColor(renderTarget, glRenderTarget);
1521
- }
1522
- _resizeColor(renderTarget, glRenderTarget) {
1523
- const source = renderTarget.colorTexture.source;
1524
- glRenderTarget.width = source.pixelWidth;
1525
- glRenderTarget.height = source.pixelHeight;
1526
- renderTarget.colorTextures.forEach((colorTexture, i) => {
1527
- if (i === 0)
1528
- return;
1529
- colorTexture.source.resize(source.width, source.height, source._resolution);
1530
- });
1531
- if (glRenderTarget.msaa) {
1532
- const renderer = this._renderer;
1533
- const gl = renderer.gl;
1534
- const viewFramebuffer = glRenderTarget.framebuffer;
1535
- gl.bindFramebuffer(gl.FRAMEBUFFER, viewFramebuffer);
1536
- renderTarget.colorTextures.forEach((colorTexture, i) => {
1537
- const source2 = colorTexture.source;
1538
- renderer.texture.bindSource(source2, 0);
1539
- const glSource = renderer.texture.getGlSource(source2);
1540
- const glInternalFormat = glSource.internalFormat;
1541
- const msaaRenderBuffer = glRenderTarget.msaaRenderBuffer[i];
1542
- gl.bindRenderbuffer(
1543
- gl.RENDERBUFFER,
1544
- msaaRenderBuffer
1545
- );
1546
- gl.renderbufferStorageMultisample(
1547
- gl.RENDERBUFFER,
1548
- 4,
1549
- glInternalFormat,
1550
- source2.pixelWidth,
1551
- source2.pixelHeight
1552
- );
1553
- gl.framebufferRenderbuffer(
1554
- gl.FRAMEBUFFER,
1555
- gl.COLOR_ATTACHMENT0 + i,
1556
- gl.RENDERBUFFER,
1557
- msaaRenderBuffer
1558
- );
1559
- });
1560
- }
1561
- }
1562
- _initStencil(glRenderTarget) {
1563
- if (glRenderTarget.framebuffer === null)
1564
- return;
1565
- const gl = this._renderer.gl;
1566
- const depthStencilRenderBuffer = gl.createRenderbuffer();
1567
- glRenderTarget.depthStencilRenderBuffer = depthStencilRenderBuffer;
1568
- gl.bindRenderbuffer(
1569
- gl.RENDERBUFFER,
1570
- depthStencilRenderBuffer
1571
- );
1572
- gl.framebufferRenderbuffer(
1573
- gl.FRAMEBUFFER,
1574
- gl.DEPTH_STENCIL_ATTACHMENT,
1575
- gl.RENDERBUFFER,
1576
- depthStencilRenderBuffer
1577
- );
1578
- this._resizeStencil(glRenderTarget);
1579
- }
1580
- _resizeStencil(glRenderTarget) {
1581
- const gl = this._renderer.gl;
1582
- gl.bindRenderbuffer(
1583
- gl.RENDERBUFFER,
1584
- glRenderTarget.depthStencilRenderBuffer
1585
- );
1586
- if (glRenderTarget.msaa) {
1587
- gl.renderbufferStorageMultisample(
1588
- gl.RENDERBUFFER,
1589
- 4,
1590
- gl.DEPTH24_STENCIL8,
1591
- glRenderTarget.width,
1592
- glRenderTarget.height
1593
- );
1594
- } else {
1595
- gl.renderbufferStorage(
1596
- gl.RENDERBUFFER,
1597
- this._renderer.context.webGLVersion === 2 ? gl.DEPTH24_STENCIL8 : gl.DEPTH_STENCIL,
1598
- glRenderTarget.width,
1599
- glRenderTarget.height
1600
- );
1601
- }
1602
- }
1603
- prerender(renderTarget) {
1604
- const resource = renderTarget.colorTexture.resource;
1605
- if (this._renderer.context.multiView && CanvasSource.test(resource)) {
1606
- this._renderer.context.ensureCanvasSize(resource);
1607
- }
1608
- }
1609
- postrender(renderTarget) {
1610
- if (!this._renderer.context.multiView)
1611
- return;
1612
- if (CanvasSource.test(renderTarget.colorTexture.resource)) {
1613
- const contextCanvas = this._renderer.context.canvas;
1614
- const canvasSource = renderTarget.colorTexture;
1615
- canvasSource.context2D.drawImage(
1616
- contextCanvas,
1617
- 0,
1618
- canvasSource.pixelHeight - contextCanvas.height
1619
- );
1620
- }
1621
- }
1622
- }
1623
-
1624
- class GlRenderTargetSystem extends RenderTargetSystem {
1625
- constructor(renderer) {
1626
- super(renderer);
1627
- this.adaptor = new GlRenderTargetAdaptor();
1628
- this.adaptor.init(renderer, this);
1629
- }
1630
- }
1631
- /** @ignore */
1632
- GlRenderTargetSystem.extension = {
1633
- type: [ExtensionType.WebGLSystem],
1634
- name: "renderTarget"
1635
- };
1636
-
1637
- function generateShaderSyncCode(shader, shaderSystem) {
1638
- const funcFragments = [];
1639
- const headerFragments = [`
1640
- var g = s.groups;
1641
- var sS = r.shader;
1642
- var p = s.glProgram;
1643
- var ugS = r.uniformGroup;
1644
- var resources;
1645
- `];
1646
- let addedTextreSystem = false;
1647
- let textureCount = 0;
1648
- const programData = shaderSystem._getProgramData(shader.glProgram);
1649
- for (const i in shader.groups) {
1650
- const group = shader.groups[i];
1651
- funcFragments.push(`
1652
- resources = g[${i}].resources;
1653
- `);
1654
- for (const j in group.resources) {
1655
- const resource = group.resources[j];
1656
- if (resource instanceof UniformGroup) {
1657
- if (resource.ubo) {
1658
- const resName = shader._uniformBindMap[i][Number(j)];
1659
- funcFragments.push(`
1660
- sS.bindUniformBlock(
1661
- resources[${j}],
1662
- '${resName}',
1663
- ${shader.glProgram._uniformBlockData[resName].index}
1664
- );
1665
- `);
1666
- } else {
1667
- funcFragments.push(`
1668
- ugS.updateUniformGroup(resources[${j}], p, sD);
1669
- `);
1670
- }
1671
- } else if (resource instanceof BufferResource) {
1672
- const resName = shader._uniformBindMap[i][Number(j)];
1673
- funcFragments.push(`
1674
- sS.bindUniformBlock(
1675
- resources[${j}],
1676
- '${resName}',
1677
- ${shader.glProgram._uniformBlockData[resName].index}
1678
- );
1679
- `);
1680
- } else if (resource instanceof TextureSource) {
1681
- const uniformName = shader._uniformBindMap[i][j];
1682
- const uniformData = programData.uniformData[uniformName];
1683
- if (uniformData) {
1684
- if (!addedTextreSystem) {
1685
- addedTextreSystem = true;
1686
- headerFragments.push(`
1687
- var tS = r.texture;
1688
- `);
1689
- }
1690
- shaderSystem._gl.uniform1i(uniformData.location, textureCount);
1691
- funcFragments.push(`
1692
- tS.bind(resources[${j}], ${textureCount});
1693
- `);
1694
- textureCount++;
1695
- }
1696
- }
1697
- }
1698
- }
1699
- const functionSource = [...headerFragments, ...funcFragments].join("\n");
1700
- return new Function("r", "s", "sD", functionSource);
1701
- }
1702
-
1703
- class GlProgramData {
1704
- /**
1705
- * Makes a new Pixi program.
1706
- * @param program - webgl program
1707
- * @param uniformData - uniforms
1708
- */
1709
- constructor(program, uniformData) {
1710
- this.program = program;
1711
- this.uniformData = uniformData;
1712
- this.uniformGroups = {};
1713
- this.uniformDirtyGroups = {};
1714
- this.uniformBlockBindings = {};
1715
- }
1716
- /** Destroys this program. */
1717
- destroy() {
1718
- this.uniformData = null;
1719
- this.uniformGroups = null;
1720
- this.uniformDirtyGroups = null;
1721
- this.uniformBlockBindings = null;
1722
- this.program = null;
1723
- }
1724
- }
1725
-
1726
- function compileShader(gl, type, src) {
1727
- const shader = gl.createShader(type);
1728
- gl.shaderSource(shader, src);
1729
- gl.compileShader(shader);
1730
- return shader;
1731
- }
1732
-
1733
- function booleanArray(size) {
1734
- const array = new Array(size);
1735
- for (let i = 0; i < array.length; i++) {
1736
- array[i] = false;
1737
- }
1738
- return array;
1739
- }
1740
- function defaultValue(type, size) {
1741
- switch (type) {
1742
- case "float":
1743
- return 0;
1744
- case "vec2":
1745
- return new Float32Array(2 * size);
1746
- case "vec3":
1747
- return new Float32Array(3 * size);
1748
- case "vec4":
1749
- return new Float32Array(4 * size);
1750
- case "int":
1751
- case "uint":
1752
- case "sampler2D":
1753
- case "sampler2DArray":
1754
- return 0;
1755
- case "ivec2":
1756
- return new Int32Array(2 * size);
1757
- case "ivec3":
1758
- return new Int32Array(3 * size);
1759
- case "ivec4":
1760
- return new Int32Array(4 * size);
1761
- case "uvec2":
1762
- return new Uint32Array(2 * size);
1763
- case "uvec3":
1764
- return new Uint32Array(3 * size);
1765
- case "uvec4":
1766
- return new Uint32Array(4 * size);
1767
- case "bool":
1768
- return false;
1769
- case "bvec2":
1770
- return booleanArray(2 * size);
1771
- case "bvec3":
1772
- return booleanArray(3 * size);
1773
- case "bvec4":
1774
- return booleanArray(4 * size);
1775
- case "mat2":
1776
- return new Float32Array([
1777
- 1,
1778
- 0,
1779
- 0,
1780
- 1
1781
- ]);
1782
- case "mat3":
1783
- return new Float32Array([
1784
- 1,
1785
- 0,
1786
- 0,
1787
- 0,
1788
- 1,
1789
- 0,
1790
- 0,
1791
- 0,
1792
- 1
1793
- ]);
1794
- case "mat4":
1795
- return new Float32Array([
1796
- 1,
1797
- 0,
1798
- 0,
1799
- 0,
1800
- 0,
1801
- 1,
1802
- 0,
1803
- 0,
1804
- 0,
1805
- 0,
1806
- 1,
1807
- 0,
1808
- 0,
1809
- 0,
1810
- 0,
1811
- 1
1812
- ]);
1813
- }
1814
- return null;
1815
- }
1816
-
1817
- let GL_TABLE = null;
1818
- const GL_TO_GLSL_TYPES = {
1819
- FLOAT: "float",
1820
- FLOAT_VEC2: "vec2",
1821
- FLOAT_VEC3: "vec3",
1822
- FLOAT_VEC4: "vec4",
1823
- INT: "int",
1824
- INT_VEC2: "ivec2",
1825
- INT_VEC3: "ivec3",
1826
- INT_VEC4: "ivec4",
1827
- UNSIGNED_INT: "uint",
1828
- UNSIGNED_INT_VEC2: "uvec2",
1829
- UNSIGNED_INT_VEC3: "uvec3",
1830
- UNSIGNED_INT_VEC4: "uvec4",
1831
- BOOL: "bool",
1832
- BOOL_VEC2: "bvec2",
1833
- BOOL_VEC3: "bvec3",
1834
- BOOL_VEC4: "bvec4",
1835
- FLOAT_MAT2: "mat2",
1836
- FLOAT_MAT3: "mat3",
1837
- FLOAT_MAT4: "mat4",
1838
- SAMPLER_2D: "sampler2D",
1839
- INT_SAMPLER_2D: "sampler2D",
1840
- UNSIGNED_INT_SAMPLER_2D: "sampler2D",
1841
- SAMPLER_CUBE: "samplerCube",
1842
- INT_SAMPLER_CUBE: "samplerCube",
1843
- UNSIGNED_INT_SAMPLER_CUBE: "samplerCube",
1844
- SAMPLER_2D_ARRAY: "sampler2DArray",
1845
- INT_SAMPLER_2D_ARRAY: "sampler2DArray",
1846
- UNSIGNED_INT_SAMPLER_2D_ARRAY: "sampler2DArray"
1847
- };
1848
- const GLSL_TO_VERTEX_TYPES = {
1849
- float: "float32",
1850
- vec2: "float32x2",
1851
- vec3: "float32x3",
1852
- vec4: "float32x4",
1853
- int: "sint32",
1854
- ivec2: "sint32x2",
1855
- ivec3: "sint32x3",
1856
- ivec4: "sint32x4",
1857
- uint: "uint32",
1858
- uvec2: "uint32x2",
1859
- uvec3: "uint32x3",
1860
- uvec4: "uint32x4",
1861
- bool: "uint32",
1862
- bvec2: "uint32x2",
1863
- bvec3: "uint32x3",
1864
- bvec4: "uint32x4"
1865
- };
1866
- function mapType(gl, type) {
1867
- if (!GL_TABLE) {
1868
- const typeNames = Object.keys(GL_TO_GLSL_TYPES);
1869
- GL_TABLE = {};
1870
- for (let i = 0; i < typeNames.length; ++i) {
1871
- const tn = typeNames[i];
1872
- GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn];
1873
- }
1874
- }
1875
- return GL_TABLE[type];
1876
- }
1877
- function mapGlToVertexFormat(gl, type) {
1878
- const typeValue = mapType(gl, type);
1879
- return GLSL_TO_VERTEX_TYPES[typeValue] || "float32";
1880
- }
1881
-
1882
- function extractAttributesFromGlProgram(program, gl, sortAttributes = false) {
1883
- const attributes = {};
1884
- const totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
1885
- for (let i = 0; i < totalAttributes; i++) {
1886
- const attribData = gl.getActiveAttrib(program, i);
1887
- if (attribData.name.startsWith("gl_")) {
1888
- continue;
1889
- }
1890
- const format = mapGlToVertexFormat(gl, attribData.type);
1891
- attributes[attribData.name] = {
1892
- location: 0,
1893
- // set further down..
1894
- format,
1895
- stride: getAttributeInfoFromFormat(format).stride,
1896
- offset: 0,
1897
- instance: false,
1898
- start: 0
1899
- };
1900
- }
1901
- const keys = Object.keys(attributes);
1902
- if (sortAttributes) {
1903
- keys.sort((a, b) => a > b ? 1 : -1);
1904
- for (let i = 0; i < keys.length; i++) {
1905
- attributes[keys[i]].location = i;
1906
- gl.bindAttribLocation(program, i, keys[i]);
1907
- }
1908
- gl.linkProgram(program);
1909
- } else {
1910
- for (let i = 0; i < keys.length; i++) {
1911
- attributes[keys[i]].location = gl.getAttribLocation(program, keys[i]);
1912
- }
1913
- }
1914
- return attributes;
1915
- }
1916
-
1917
- function getUboData(program, gl) {
1918
- if (!gl.ACTIVE_UNIFORM_BLOCKS)
1919
- return {};
1920
- const uniformBlocks = {};
1921
- const totalUniformsBlocks = gl.getProgramParameter(program, gl.ACTIVE_UNIFORM_BLOCKS);
1922
- for (let i = 0; i < totalUniformsBlocks; i++) {
1923
- const name = gl.getActiveUniformBlockName(program, i);
1924
- const uniformBlockIndex = gl.getUniformBlockIndex(program, name);
1925
- const size = gl.getActiveUniformBlockParameter(program, i, gl.UNIFORM_BLOCK_DATA_SIZE);
1926
- uniformBlocks[name] = {
1927
- name,
1928
- index: uniformBlockIndex,
1929
- size
1930
- };
1931
- }
1932
- return uniformBlocks;
1933
- }
1934
-
1935
- function getUniformData(program, gl) {
1936
- const uniforms = {};
1937
- const totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
1938
- for (let i = 0; i < totalUniforms; i++) {
1939
- const uniformData = gl.getActiveUniform(program, i);
1940
- const name = uniformData.name.replace(/\[.*?\]$/, "");
1941
- const isArray = !!uniformData.name.match(/\[.*?\]$/);
1942
- const type = mapType(gl, uniformData.type);
1943
- uniforms[name] = {
1944
- name,
1945
- index: i,
1946
- type,
1947
- size: uniformData.size,
1948
- isArray,
1949
- value: defaultValue(type, uniformData.size)
1950
- };
1951
- }
1952
- return uniforms;
1953
- }
1954
-
1955
- function logPrettyShaderError(gl, shader) {
1956
- const shaderSrc = gl.getShaderSource(shader).split("\n").map((line, index) => `${index}: ${line}`);
1957
- const shaderLog = gl.getShaderInfoLog(shader);
1958
- const splitShader = shaderLog.split("\n");
1959
- const dedupe = {};
1960
- const lineNumbers = splitShader.map((line) => parseFloat(line.replace(/^ERROR\: 0\:([\d]+)\:.*$/, "$1"))).filter((n) => {
1961
- if (n && !dedupe[n]) {
1962
- dedupe[n] = true;
1963
- return true;
1964
- }
1965
- return false;
1966
- });
1967
- const logArgs = [""];
1968
- lineNumbers.forEach((number) => {
1969
- shaderSrc[number - 1] = `%c${shaderSrc[number - 1]}%c`;
1970
- logArgs.push("background: #FF0000; color:#FFFFFF; font-size: 10px", "font-size: 10px");
1971
- });
1972
- const fragmentSourceToLog = shaderSrc.join("\n");
1973
- logArgs[0] = fragmentSourceToLog;
1974
- console.error(shaderLog);
1975
- console.groupCollapsed("click to view full shader code");
1976
- console.warn(...logArgs);
1977
- console.groupEnd();
1978
- }
1979
- function logProgramError(gl, program, vertexShader, fragmentShader) {
1980
- if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
1981
- if (!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)) {
1982
- logPrettyShaderError(gl, vertexShader);
1983
- }
1984
- if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)) {
1985
- logPrettyShaderError(gl, fragmentShader);
1986
- }
1987
- console.error("PixiJS Error: Could not initialize shader.");
1988
- if (gl.getProgramInfoLog(program) !== "") {
1989
- console.warn("PixiJS Warning: gl.getProgramInfoLog()", gl.getProgramInfoLog(program));
1990
- }
1991
- }
1992
- }
1993
-
1994
- function generateProgram(gl, program) {
1995
- const glVertShader = compileShader(gl, gl.VERTEX_SHADER, program.vertex);
1996
- const glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, program.fragment);
1997
- const webGLProgram = gl.createProgram();
1998
- gl.attachShader(webGLProgram, glVertShader);
1999
- gl.attachShader(webGLProgram, glFragShader);
2000
- const transformFeedbackVaryings = program.transformFeedbackVaryings;
2001
- if (transformFeedbackVaryings) {
2002
- if (typeof gl.transformFeedbackVaryings !== "function") {
2003
- warn(`TransformFeedback is not supported but TransformFeedbackVaryings are given.`);
2004
- } else {
2005
- gl.transformFeedbackVaryings(
2006
- webGLProgram,
2007
- transformFeedbackVaryings.names,
2008
- transformFeedbackVaryings.bufferMode === "separate" ? gl.SEPARATE_ATTRIBS : gl.INTERLEAVED_ATTRIBS
2009
- );
2010
- }
2011
- }
2012
- gl.linkProgram(webGLProgram);
2013
- if (!gl.getProgramParameter(webGLProgram, gl.LINK_STATUS)) {
2014
- logProgramError(gl, webGLProgram, glVertShader, glFragShader);
2015
- }
2016
- program._attributeData = extractAttributesFromGlProgram(
2017
- webGLProgram,
2018
- gl,
2019
- !/^[ \t]*#[ \t]*version[ \t]+300[ \t]+es[ \t]*$/m.test(program.vertex)
2020
- );
2021
- program._uniformData = getUniformData(webGLProgram, gl);
2022
- program._uniformBlockData = getUboData(webGLProgram, gl);
2023
- gl.deleteShader(glVertShader);
2024
- gl.deleteShader(glFragShader);
2025
- const uniformData = {};
2026
- for (const i in program._uniformData) {
2027
- const data = program._uniformData[i];
2028
- uniformData[i] = {
2029
- location: gl.getUniformLocation(webGLProgram, i),
2030
- value: defaultValue(data.type, data.size)
2031
- };
2032
- }
2033
- const glProgram = new GlProgramData(webGLProgram, uniformData);
2034
- return glProgram;
2035
- }
2036
-
2037
- const defaultSyncData = {
2038
- textureCount: 0,
2039
- blockIndex: 0
2040
- };
2041
- class GlShaderSystem {
2042
- constructor(renderer) {
2043
- /** @internal */
2044
- this._activeProgram = null;
2045
- this._programDataHash = /* @__PURE__ */ Object.create(null);
2046
- this._shaderSyncFunctions = /* @__PURE__ */ Object.create(null);
2047
- this._renderer = renderer;
2048
- this._renderer.renderableGC.addManagedHash(this, "_programDataHash");
2049
- }
2050
- contextChange(gl) {
2051
- this._gl = gl;
2052
- this._programDataHash = /* @__PURE__ */ Object.create(null);
2053
- this._shaderSyncFunctions = /* @__PURE__ */ Object.create(null);
2054
- this._activeProgram = null;
2055
- }
2056
- /**
2057
- * Changes the current shader to the one given in parameter.
2058
- * @param shader - the new shader
2059
- * @param skipSync - false if the shader should automatically sync its uniforms.
2060
- * @returns the glProgram that belongs to the shader.
2061
- */
2062
- bind(shader, skipSync) {
2063
- this._setProgram(shader.glProgram);
2064
- if (skipSync)
2065
- return;
2066
- defaultSyncData.textureCount = 0;
2067
- defaultSyncData.blockIndex = 0;
2068
- let syncFunction = this._shaderSyncFunctions[shader.glProgram._key];
2069
- if (!syncFunction) {
2070
- syncFunction = this._shaderSyncFunctions[shader.glProgram._key] = this._generateShaderSync(shader, this);
2071
- }
2072
- this._renderer.buffer.nextBindBase(!!shader.glProgram.transformFeedbackVaryings);
2073
- syncFunction(this._renderer, shader, defaultSyncData);
2074
- }
2075
- /**
2076
- * Updates the uniform group.
2077
- * @param uniformGroup - the uniform group to update
2078
- */
2079
- updateUniformGroup(uniformGroup) {
2080
- this._renderer.uniformGroup.updateUniformGroup(uniformGroup, this._activeProgram, defaultSyncData);
2081
- }
2082
- /**
2083
- * Binds a uniform block to the shader.
2084
- * @param uniformGroup - the uniform group to bind
2085
- * @param name - the name of the uniform block
2086
- * @param index - the index of the uniform block
2087
- */
2088
- bindUniformBlock(uniformGroup, name, index = 0) {
2089
- const bufferSystem = this._renderer.buffer;
2090
- const programData = this._getProgramData(this._activeProgram);
2091
- const isBufferResource = uniformGroup._bufferResource;
2092
- if (!isBufferResource) {
2093
- this._renderer.ubo.updateUniformGroup(uniformGroup);
2094
- }
2095
- const buffer = uniformGroup.buffer;
2096
- const glBuffer = bufferSystem.updateBuffer(buffer);
2097
- const boundLocation = bufferSystem.freeLocationForBufferBase(glBuffer);
2098
- if (isBufferResource) {
2099
- const { offset, size } = uniformGroup;
2100
- if (offset === 0 && size === buffer.data.byteLength) {
2101
- bufferSystem.bindBufferBase(glBuffer, boundLocation);
2102
- } else {
2103
- bufferSystem.bindBufferRange(glBuffer, boundLocation, offset);
2104
- }
2105
- } else if (bufferSystem.getLastBindBaseLocation(glBuffer) !== boundLocation) {
2106
- bufferSystem.bindBufferBase(glBuffer, boundLocation);
2107
- }
2108
- const uniformBlockIndex = this._activeProgram._uniformBlockData[name].index;
2109
- if (programData.uniformBlockBindings[index] === boundLocation)
2110
- return;
2111
- programData.uniformBlockBindings[index] = boundLocation;
2112
- this._renderer.gl.uniformBlockBinding(programData.program, uniformBlockIndex, boundLocation);
2113
- }
2114
- _setProgram(program) {
2115
- if (this._activeProgram === program)
2116
- return;
2117
- this._activeProgram = program;
2118
- const programData = this._getProgramData(program);
2119
- this._gl.useProgram(programData.program);
2120
- }
2121
- /**
2122
- * @param program - the program to get the data for
2123
- * @internal
2124
- */
2125
- _getProgramData(program) {
2126
- return this._programDataHash[program._key] || this._createProgramData(program);
2127
- }
2128
- _createProgramData(program) {
2129
- const key = program._key;
2130
- this._programDataHash[key] = generateProgram(this._gl, program);
2131
- return this._programDataHash[key];
2132
- }
2133
- destroy() {
2134
- for (const key of Object.keys(this._programDataHash)) {
2135
- const programData = this._programDataHash[key];
2136
- programData.destroy();
2137
- this._programDataHash[key] = null;
2138
- }
2139
- this._programDataHash = null;
2140
- }
2141
- /**
2142
- * Creates a function that can be executed that will sync the shader as efficiently as possible.
2143
- * Overridden by the unsafe eval package if you don't want eval used in your project.
2144
- * @param shader - the shader to generate the sync function for
2145
- * @param shaderSystem - the shader system to use
2146
- * @returns - the generated sync function
2147
- * @ignore
2148
- */
2149
- _generateShaderSync(shader, shaderSystem) {
2150
- return generateShaderSyncCode(shader, shaderSystem);
2151
- }
2152
- resetState() {
2153
- this._activeProgram = null;
2154
- }
2155
- }
2156
- /** @ignore */
2157
- GlShaderSystem.extension = {
2158
- type: [
2159
- ExtensionType.WebGLSystem
2160
- ],
2161
- name: "shader"
2162
- };
2163
-
2164
- const UNIFORM_TO_SINGLE_SETTERS = {
2165
- f32: `if (cv !== v) {
2166
- cu.value = v;
2167
- gl.uniform1f(location, v);
2168
- }`,
2169
- "vec2<f32>": `if (cv[0] !== v[0] || cv[1] !== v[1]) {
2170
- cv[0] = v[0];
2171
- cv[1] = v[1];
2172
- gl.uniform2f(location, v[0], v[1]);
2173
- }`,
2174
- "vec3<f32>": `if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2]) {
2175
- cv[0] = v[0];
2176
- cv[1] = v[1];
2177
- cv[2] = v[2];
2178
- gl.uniform3f(location, v[0], v[1], v[2]);
2179
- }`,
2180
- "vec4<f32>": `if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3]) {
2181
- cv[0] = v[0];
2182
- cv[1] = v[1];
2183
- cv[2] = v[2];
2184
- cv[3] = v[3];
2185
- gl.uniform4f(location, v[0], v[1], v[2], v[3]);
2186
- }`,
2187
- i32: `if (cv !== v) {
2188
- cu.value = v;
2189
- gl.uniform1i(location, v);
2190
- }`,
2191
- "vec2<i32>": `if (cv[0] !== v[0] || cv[1] !== v[1]) {
2192
- cv[0] = v[0];
2193
- cv[1] = v[1];
2194
- gl.uniform2i(location, v[0], v[1]);
2195
- }`,
2196
- "vec3<i32>": `if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2]) {
2197
- cv[0] = v[0];
2198
- cv[1] = v[1];
2199
- cv[2] = v[2];
2200
- gl.uniform3i(location, v[0], v[1], v[2]);
2201
- }`,
2202
- "vec4<i32>": `if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3]) {
2203
- cv[0] = v[0];
2204
- cv[1] = v[1];
2205
- cv[2] = v[2];
2206
- cv[3] = v[3];
2207
- gl.uniform4i(location, v[0], v[1], v[2], v[3]);
2208
- }`,
2209
- u32: `if (cv !== v) {
2210
- cu.value = v;
2211
- gl.uniform1ui(location, v);
2212
- }`,
2213
- "vec2<u32>": `if (cv[0] !== v[0] || cv[1] !== v[1]) {
2214
- cv[0] = v[0];
2215
- cv[1] = v[1];
2216
- gl.uniform2ui(location, v[0], v[1]);
2217
- }`,
2218
- "vec3<u32>": `if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2]) {
2219
- cv[0] = v[0];
2220
- cv[1] = v[1];
2221
- cv[2] = v[2];
2222
- gl.uniform3ui(location, v[0], v[1], v[2]);
2223
- }`,
2224
- "vec4<u32>": `if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3]) {
2225
- cv[0] = v[0];
2226
- cv[1] = v[1];
2227
- cv[2] = v[2];
2228
- cv[3] = v[3];
2229
- gl.uniform4ui(location, v[0], v[1], v[2], v[3]);
2230
- }`,
2231
- bool: `if (cv !== v) {
2232
- cu.value = v;
2233
- gl.uniform1i(location, v);
2234
- }`,
2235
- "vec2<bool>": `if (cv[0] !== v[0] || cv[1] !== v[1]) {
2236
- cv[0] = v[0];
2237
- cv[1] = v[1];
2238
- gl.uniform2i(location, v[0], v[1]);
2239
- }`,
2240
- "vec3<bool>": `if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2]) {
2241
- cv[0] = v[0];
2242
- cv[1] = v[1];
2243
- cv[2] = v[2];
2244
- gl.uniform3i(location, v[0], v[1], v[2]);
2245
- }`,
2246
- "vec4<bool>": `if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3]) {
2247
- cv[0] = v[0];
2248
- cv[1] = v[1];
2249
- cv[2] = v[2];
2250
- cv[3] = v[3];
2251
- gl.uniform4i(location, v[0], v[1], v[2], v[3]);
2252
- }`,
2253
- "mat2x2<f32>": `gl.uniformMatrix2fv(location, false, v);`,
2254
- "mat3x3<f32>": `gl.uniformMatrix3fv(location, false, v);`,
2255
- "mat4x4<f32>": `gl.uniformMatrix4fv(location, false, v);`
2256
- };
2257
- const UNIFORM_TO_ARRAY_SETTERS = {
2258
- f32: `gl.uniform1fv(location, v);`,
2259
- "vec2<f32>": `gl.uniform2fv(location, v);`,
2260
- "vec3<f32>": `gl.uniform3fv(location, v);`,
2261
- "vec4<f32>": `gl.uniform4fv(location, v);`,
2262
- "mat2x2<f32>": `gl.uniformMatrix2fv(location, false, v);`,
2263
- "mat3x3<f32>": `gl.uniformMatrix3fv(location, false, v);`,
2264
- "mat4x4<f32>": `gl.uniformMatrix4fv(location, false, v);`,
2265
- i32: `gl.uniform1iv(location, v);`,
2266
- "vec2<i32>": `gl.uniform2iv(location, v);`,
2267
- "vec3<i32>": `gl.uniform3iv(location, v);`,
2268
- "vec4<i32>": `gl.uniform4iv(location, v);`,
2269
- u32: `gl.uniform1iv(location, v);`,
2270
- "vec2<u32>": `gl.uniform2iv(location, v);`,
2271
- "vec3<u32>": `gl.uniform3iv(location, v);`,
2272
- "vec4<u32>": `gl.uniform4iv(location, v);`,
2273
- bool: `gl.uniform1iv(location, v);`,
2274
- "vec2<bool>": `gl.uniform2iv(location, v);`,
2275
- "vec3<bool>": `gl.uniform3iv(location, v);`,
2276
- "vec4<bool>": `gl.uniform4iv(location, v);`
2277
- };
2278
-
2279
- function generateUniformsSync(group, uniformData) {
2280
- const funcFragments = [`
2281
- var v = null;
2282
- var cv = null;
2283
- var cu = null;
2284
- var t = 0;
2285
- var gl = renderer.gl;
2286
- var name = null;
2287
- `];
2288
- for (const i in group.uniforms) {
2289
- if (!uniformData[i]) {
2290
- if (group.uniforms[i] instanceof UniformGroup) {
2291
- if (group.uniforms[i].ubo) {
2292
- funcFragments.push(`
2293
- renderer.shader.bindUniformBlock(uv.${i}, "${i}");
2294
- `);
2295
- } else {
2296
- funcFragments.push(`
2297
- renderer.shader.updateUniformGroup(uv.${i});
2298
- `);
2299
- }
2300
- } else if (group.uniforms[i] instanceof BufferResource) {
2301
- funcFragments.push(`
2302
- renderer.shader.bindBufferResource(uv.${i}, "${i}");
2303
- `);
2304
- }
2305
- continue;
2306
- }
2307
- const uniform = group.uniformStructures[i];
2308
- let parsed = false;
2309
- for (let j = 0; j < uniformParsers.length; j++) {
2310
- const parser = uniformParsers[j];
2311
- if (uniform.type === parser.type && parser.test(uniform)) {
2312
- funcFragments.push(`name = "${i}";`, uniformParsers[j].uniform);
2313
- parsed = true;
2314
- break;
2315
- }
2316
- }
2317
- if (!parsed) {
2318
- const templateType = uniform.size === 1 ? UNIFORM_TO_SINGLE_SETTERS : UNIFORM_TO_ARRAY_SETTERS;
2319
- const template = templateType[uniform.type].replace("location", `ud["${i}"].location`);
2320
- funcFragments.push(`
2321
- cu = ud["${i}"];
2322
- cv = cu.value;
2323
- v = uv["${i}"];
2324
- ${template};`);
2325
- }
2326
- }
2327
- return new Function("ud", "uv", "renderer", "syncData", funcFragments.join("\n"));
2328
- }
2329
-
2330
- class GlUniformGroupSystem {
2331
- /** @param renderer - The renderer this System works for. */
2332
- constructor(renderer) {
2333
- /** Cache to holds the generated functions. Stored against UniformObjects unique signature. */
2334
- this._cache = {};
2335
- this._uniformGroupSyncHash = {};
2336
- this._renderer = renderer;
2337
- this.gl = null;
2338
- this._cache = {};
2339
- }
2340
- contextChange(gl) {
2341
- this.gl = gl;
2342
- }
2343
- /**
2344
- * Uploads the uniforms values to the currently bound shader.
2345
- * @param group - the uniforms values that be applied to the current shader
2346
- * @param program
2347
- * @param syncData
2348
- * @param syncData.textureCount
2349
- */
2350
- updateUniformGroup(group, program, syncData) {
2351
- const programData = this._renderer.shader._getProgramData(program);
2352
- if (!group.isStatic || group._dirtyId !== programData.uniformDirtyGroups[group.uid]) {
2353
- programData.uniformDirtyGroups[group.uid] = group._dirtyId;
2354
- const syncFunc = this._getUniformSyncFunction(group, program);
2355
- syncFunc(programData.uniformData, group.uniforms, this._renderer, syncData);
2356
- }
2357
- }
2358
- /**
2359
- * Overridable by the pixi.js/unsafe-eval package to use static syncUniforms instead.
2360
- * @param group
2361
- * @param program
2362
- */
2363
- _getUniformSyncFunction(group, program) {
2364
- return this._uniformGroupSyncHash[group._signature]?.[program._key] || this._createUniformSyncFunction(group, program);
2365
- }
2366
- _createUniformSyncFunction(group, program) {
2367
- const uniformGroupSyncHash = this._uniformGroupSyncHash[group._signature] || (this._uniformGroupSyncHash[group._signature] = {});
2368
- const id = this._getSignature(group, program._uniformData, "u");
2369
- if (!this._cache[id]) {
2370
- this._cache[id] = this._generateUniformsSync(group, program._uniformData);
2371
- }
2372
- uniformGroupSyncHash[program._key] = this._cache[id];
2373
- return uniformGroupSyncHash[program._key];
2374
- }
2375
- _generateUniformsSync(group, uniformData) {
2376
- return generateUniformsSync(group, uniformData);
2377
- }
2378
- /**
2379
- * Takes a uniform group and data and generates a unique signature for them.
2380
- * @param group - The uniform group to get signature of
2381
- * @param group.uniforms
2382
- * @param uniformData - Uniform information generated by the shader
2383
- * @param preFix
2384
- * @returns Unique signature of the uniform group
2385
- */
2386
- _getSignature(group, uniformData, preFix) {
2387
- const uniforms = group.uniforms;
2388
- const strings = [`${preFix}-`];
2389
- for (const i in uniforms) {
2390
- strings.push(i);
2391
- if (uniformData[i]) {
2392
- strings.push(uniformData[i].type);
2393
- }
2394
- }
2395
- return strings.join("-");
2396
- }
2397
- /** Destroys this System and removes all its textures. */
2398
- destroy() {
2399
- this._renderer = null;
2400
- this._cache = null;
2401
- }
2402
- }
2403
- /** @ignore */
2404
- GlUniformGroupSystem.extension = {
2405
- type: [
2406
- ExtensionType.WebGLSystem
2407
- ],
2408
- name: "uniformGroup"
2409
- };
2410
-
2411
- function mapWebGLBlendModesToPixi(gl) {
2412
- const blendMap = {};
2413
- blendMap.normal = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
2414
- blendMap.add = [gl.ONE, gl.ONE];
2415
- blendMap.multiply = [gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
2416
- blendMap.screen = [gl.ONE, gl.ONE_MINUS_SRC_COLOR, gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
2417
- blendMap.none = [0, 0];
2418
- blendMap["normal-npm"] = [gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
2419
- blendMap["add-npm"] = [gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE];
2420
- blendMap["screen-npm"] = [gl.SRC_ALPHA, gl.ONE_MINUS_SRC_COLOR, gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
2421
- blendMap.erase = [gl.ZERO, gl.ONE_MINUS_SRC_ALPHA];
2422
- const isWebGl2 = !(gl instanceof DOMAdapter.get().getWebGLRenderingContext());
2423
- if (isWebGl2) {
2424
- blendMap.min = [gl.ONE, gl.ONE, gl.ONE, gl.ONE, gl.MIN, gl.MIN];
2425
- blendMap.max = [gl.ONE, gl.ONE, gl.ONE, gl.ONE, gl.MAX, gl.MAX];
2426
- } else {
2427
- const ext = gl.getExtension("EXT_blend_minmax");
2428
- if (ext) {
2429
- blendMap.min = [gl.ONE, gl.ONE, gl.ONE, gl.ONE, ext.MIN_EXT, ext.MIN_EXT];
2430
- blendMap.max = [gl.ONE, gl.ONE, gl.ONE, gl.ONE, ext.MAX_EXT, ext.MAX_EXT];
2431
- }
2432
- }
2433
- return blendMap;
2434
- }
2435
-
2436
- const BLEND = 0;
2437
- const OFFSET = 1;
2438
- const CULLING = 2;
2439
- const DEPTH_TEST = 3;
2440
- const WINDING = 4;
2441
- const DEPTH_MASK = 5;
2442
- const _GlStateSystem = class _GlStateSystem {
2443
- constructor(renderer) {
2444
- /**
2445
- * Whether to invert the front face when rendering
2446
- * This is used for render textures where the Y-coordinate is flipped
2447
- * @default false
2448
- */
2449
- this._invertFrontFace = false;
2450
- this.gl = null;
2451
- this.stateId = 0;
2452
- this.polygonOffset = 0;
2453
- this.blendMode = "none";
2454
- this._blendEq = false;
2455
- this.map = [];
2456
- this.map[BLEND] = this.setBlend;
2457
- this.map[OFFSET] = this.setOffset;
2458
- this.map[CULLING] = this.setCullFace;
2459
- this.map[DEPTH_TEST] = this.setDepthTest;
2460
- this.map[WINDING] = this.setFrontFace;
2461
- this.map[DEPTH_MASK] = this.setDepthMask;
2462
- this.checks = [];
2463
- this.defaultState = State.for2d();
2464
- renderer.renderTarget.onRenderTargetChange.add(this);
2465
- }
2466
- onRenderTargetChange(renderTarget) {
2467
- this._invertFrontFace = !renderTarget.isRoot;
2468
- if (this._cullFace) {
2469
- this.setFrontFace(this._frontFace);
2470
- } else {
2471
- this._frontFaceDirty = true;
2472
- }
2473
- }
2474
- contextChange(gl) {
2475
- this.gl = gl;
2476
- this.blendModesMap = mapWebGLBlendModesToPixi(gl);
2477
- this.resetState();
2478
- }
2479
- /**
2480
- * Sets the current state
2481
- * @param {*} state - The state to set.
2482
- */
2483
- set(state) {
2484
- state || (state = this.defaultState);
2485
- if (this.stateId !== state.data) {
2486
- let diff = this.stateId ^ state.data;
2487
- let i = 0;
2488
- while (diff) {
2489
- if (diff & 1) {
2490
- this.map[i].call(this, !!(state.data & 1 << i));
2491
- }
2492
- diff >>= 1;
2493
- i++;
2494
- }
2495
- this.stateId = state.data;
2496
- }
2497
- for (let i = 0; i < this.checks.length; i++) {
2498
- this.checks[i](this, state);
2499
- }
2500
- }
2501
- /**
2502
- * Sets the state, when previous state is unknown.
2503
- * @param {*} state - The state to set
2504
- */
2505
- forceState(state) {
2506
- state || (state = this.defaultState);
2507
- for (let i = 0; i < this.map.length; i++) {
2508
- this.map[i].call(this, !!(state.data & 1 << i));
2509
- }
2510
- for (let i = 0; i < this.checks.length; i++) {
2511
- this.checks[i](this, state);
2512
- }
2513
- this.stateId = state.data;
2514
- }
2515
- /**
2516
- * Sets whether to enable or disable blending.
2517
- * @param value - Turn on or off WebGl blending.
2518
- */
2519
- setBlend(value) {
2520
- this._updateCheck(_GlStateSystem._checkBlendMode, value);
2521
- this.gl[value ? "enable" : "disable"](this.gl.BLEND);
2522
- }
2523
- /**
2524
- * Sets whether to enable or disable polygon offset fill.
2525
- * @param value - Turn on or off webgl polygon offset testing.
2526
- */
2527
- setOffset(value) {
2528
- this._updateCheck(_GlStateSystem._checkPolygonOffset, value);
2529
- this.gl[value ? "enable" : "disable"](this.gl.POLYGON_OFFSET_FILL);
2530
- }
2531
- /**
2532
- * Sets whether to enable or disable depth test.
2533
- * @param value - Turn on or off webgl depth testing.
2534
- */
2535
- setDepthTest(value) {
2536
- this.gl[value ? "enable" : "disable"](this.gl.DEPTH_TEST);
2537
- }
2538
- /**
2539
- * Sets whether to enable or disable depth mask.
2540
- * @param value - Turn on or off webgl depth mask.
2541
- */
2542
- setDepthMask(value) {
2543
- this.gl.depthMask(value);
2544
- }
2545
- /**
2546
- * Sets whether to enable or disable cull face.
2547
- * @param {boolean} value - Turn on or off webgl cull face.
2548
- */
2549
- setCullFace(value) {
2550
- this._cullFace = value;
2551
- this.gl[value ? "enable" : "disable"](this.gl.CULL_FACE);
2552
- if (this._cullFace && this._frontFaceDirty) {
2553
- this.setFrontFace(this._frontFace);
2554
- }
2555
- }
2556
- /**
2557
- * Sets the gl front face.
2558
- * @param {boolean} value - true is clockwise and false is counter-clockwise
2559
- */
2560
- setFrontFace(value) {
2561
- this._frontFace = value;
2562
- this._frontFaceDirty = false;
2563
- const faceMode = this._invertFrontFace ? !value : value;
2564
- if (this._glFrontFace !== faceMode) {
2565
- this._glFrontFace = faceMode;
2566
- this.gl.frontFace(this.gl[faceMode ? "CW" : "CCW"]);
2567
- }
2568
- }
2569
- /**
2570
- * Sets the blend mode.
2571
- * @param {number} value - The blend mode to set to.
2572
- */
2573
- setBlendMode(value) {
2574
- if (!this.blendModesMap[value]) {
2575
- value = "normal";
2576
- }
2577
- if (value === this.blendMode) {
2578
- return;
2579
- }
2580
- this.blendMode = value;
2581
- const mode = this.blendModesMap[value];
2582
- const gl = this.gl;
2583
- if (mode.length === 2) {
2584
- gl.blendFunc(mode[0], mode[1]);
2585
- } else {
2586
- gl.blendFuncSeparate(mode[0], mode[1], mode[2], mode[3]);
2587
- }
2588
- if (mode.length === 6) {
2589
- this._blendEq = true;
2590
- gl.blendEquationSeparate(mode[4], mode[5]);
2591
- } else if (this._blendEq) {
2592
- this._blendEq = false;
2593
- gl.blendEquationSeparate(gl.FUNC_ADD, gl.FUNC_ADD);
2594
- }
2595
- }
2596
- /**
2597
- * Sets the polygon offset.
2598
- * @param {number} value - the polygon offset
2599
- * @param {number} scale - the polygon offset scale
2600
- */
2601
- setPolygonOffset(value, scale) {
2602
- this.gl.polygonOffset(value, scale);
2603
- }
2604
- /** Resets all the logic and disables the VAOs. */
2605
- resetState() {
2606
- this._glFrontFace = false;
2607
- this._frontFace = false;
2608
- this._cullFace = false;
2609
- this._frontFaceDirty = false;
2610
- this._invertFrontFace = false;
2611
- this.gl.frontFace(this.gl.CCW);
2612
- this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL, false);
2613
- this.forceState(this.defaultState);
2614
- this._blendEq = true;
2615
- this.blendMode = "";
2616
- this.setBlendMode("normal");
2617
- }
2618
- /**
2619
- * Checks to see which updates should be checked based on which settings have been activated.
2620
- *
2621
- * For example, if blend is enabled then we should check the blend modes each time the state is changed
2622
- * or if polygon fill is activated then we need to check if the polygon offset changes.
2623
- * The idea is that we only check what we have too.
2624
- * @param func - the checking function to add or remove
2625
- * @param value - should the check function be added or removed.
2626
- */
2627
- _updateCheck(func, value) {
2628
- const index = this.checks.indexOf(func);
2629
- if (value && index === -1) {
2630
- this.checks.push(func);
2631
- } else if (!value && index !== -1) {
2632
- this.checks.splice(index, 1);
2633
- }
2634
- }
2635
- /**
2636
- * A private little wrapper function that we call to check the blend mode.
2637
- * @param system - the System to perform the state check on
2638
- * @param state - the state that the blendMode will pulled from
2639
- */
2640
- static _checkBlendMode(system, state) {
2641
- system.setBlendMode(state.blendMode);
2642
- }
2643
- /**
2644
- * A private little wrapper function that we call to check the polygon offset.
2645
- * @param system - the System to perform the state check on
2646
- * @param state - the state that the blendMode will pulled from
2647
- */
2648
- static _checkPolygonOffset(system, state) {
2649
- system.setPolygonOffset(1, state.polygonOffset);
2650
- }
2651
- /** @ignore */
2652
- destroy() {
2653
- this.gl = null;
2654
- this.checks.length = 0;
2655
- }
2656
- };
2657
- /** @ignore */
2658
- _GlStateSystem.extension = {
2659
- type: [
2660
- ExtensionType.WebGLSystem
2661
- ],
2662
- name: "state"
2663
- };
2664
- let GlStateSystem = _GlStateSystem;
2665
-
2666
- class GlTexture {
2667
- constructor(texture) {
2668
- this.target = GL_TARGETS.TEXTURE_2D;
2669
- this.texture = texture;
2670
- this.width = -1;
2671
- this.height = -1;
2672
- this.type = GL_TYPES.UNSIGNED_BYTE;
2673
- this.internalFormat = GL_FORMATS.RGBA;
2674
- this.format = GL_FORMATS.RGBA;
2675
- this.samplerType = 0;
2676
- }
2677
- }
2678
-
2679
- const glUploadBufferImageResource = {
2680
- id: "buffer",
2681
- upload(source, glTexture, gl) {
2682
- if (glTexture.width === source.width || glTexture.height === source.height) {
2683
- gl.texSubImage2D(
2684
- gl.TEXTURE_2D,
2685
- 0,
2686
- 0,
2687
- 0,
2688
- source.width,
2689
- source.height,
2690
- glTexture.format,
2691
- glTexture.type,
2692
- source.resource
2693
- );
2694
- } else {
2695
- gl.texImage2D(
2696
- glTexture.target,
2697
- 0,
2698
- glTexture.internalFormat,
2699
- source.width,
2700
- source.height,
2701
- 0,
2702
- glTexture.format,
2703
- glTexture.type,
2704
- source.resource
2705
- );
2706
- }
2707
- glTexture.width = source.width;
2708
- glTexture.height = source.height;
2709
- }
2710
- };
2711
-
2712
- const compressedFormatMap = {
2713
- "bc1-rgba-unorm": true,
2714
- "bc1-rgba-unorm-srgb": true,
2715
- "bc2-rgba-unorm": true,
2716
- "bc2-rgba-unorm-srgb": true,
2717
- "bc3-rgba-unorm": true,
2718
- "bc3-rgba-unorm-srgb": true,
2719
- "bc4-r-unorm": true,
2720
- "bc4-r-snorm": true,
2721
- "bc5-rg-unorm": true,
2722
- "bc5-rg-snorm": true,
2723
- "bc6h-rgb-ufloat": true,
2724
- "bc6h-rgb-float": true,
2725
- "bc7-rgba-unorm": true,
2726
- "bc7-rgba-unorm-srgb": true,
2727
- // ETC2 compressed formats usable if "texture-compression-etc2" is both
2728
- // supported by the device/user agent and enabled in requestDevice.
2729
- "etc2-rgb8unorm": true,
2730
- "etc2-rgb8unorm-srgb": true,
2731
- "etc2-rgb8a1unorm": true,
2732
- "etc2-rgb8a1unorm-srgb": true,
2733
- "etc2-rgba8unorm": true,
2734
- "etc2-rgba8unorm-srgb": true,
2735
- "eac-r11unorm": true,
2736
- "eac-r11snorm": true,
2737
- "eac-rg11unorm": true,
2738
- "eac-rg11snorm": true,
2739
- // ASTC compressed formats usable if "texture-compression-astc" is both
2740
- // supported by the device/user agent and enabled in requestDevice.
2741
- "astc-4x4-unorm": true,
2742
- "astc-4x4-unorm-srgb": true,
2743
- "astc-5x4-unorm": true,
2744
- "astc-5x4-unorm-srgb": true,
2745
- "astc-5x5-unorm": true,
2746
- "astc-5x5-unorm-srgb": true,
2747
- "astc-6x5-unorm": true,
2748
- "astc-6x5-unorm-srgb": true,
2749
- "astc-6x6-unorm": true,
2750
- "astc-6x6-unorm-srgb": true,
2751
- "astc-8x5-unorm": true,
2752
- "astc-8x5-unorm-srgb": true,
2753
- "astc-8x6-unorm": true,
2754
- "astc-8x6-unorm-srgb": true,
2755
- "astc-8x8-unorm": true,
2756
- "astc-8x8-unorm-srgb": true,
2757
- "astc-10x5-unorm": true,
2758
- "astc-10x5-unorm-srgb": true,
2759
- "astc-10x6-unorm": true,
2760
- "astc-10x6-unorm-srgb": true,
2761
- "astc-10x8-unorm": true,
2762
- "astc-10x8-unorm-srgb": true,
2763
- "astc-10x10-unorm": true,
2764
- "astc-10x10-unorm-srgb": true,
2765
- "astc-12x10-unorm": true,
2766
- "astc-12x10-unorm-srgb": true,
2767
- "astc-12x12-unorm": true,
2768
- "astc-12x12-unorm-srgb": true
2769
- };
2770
- const glUploadCompressedTextureResource = {
2771
- id: "compressed",
2772
- upload(source, glTexture, gl) {
2773
- gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
2774
- let mipWidth = source.pixelWidth;
2775
- let mipHeight = source.pixelHeight;
2776
- const compressed = !!compressedFormatMap[source.format];
2777
- for (let i = 0; i < source.resource.length; i++) {
2778
- const levelBuffer = source.resource[i];
2779
- if (compressed) {
2780
- gl.compressedTexImage2D(
2781
- gl.TEXTURE_2D,
2782
- i,
2783
- glTexture.internalFormat,
2784
- mipWidth,
2785
- mipHeight,
2786
- 0,
2787
- levelBuffer
2788
- );
2789
- } else {
2790
- gl.texImage2D(
2791
- gl.TEXTURE_2D,
2792
- i,
2793
- glTexture.internalFormat,
2794
- mipWidth,
2795
- mipHeight,
2796
- 0,
2797
- glTexture.format,
2798
- glTexture.type,
2799
- levelBuffer
2800
- );
2801
- }
2802
- mipWidth = Math.max(mipWidth >> 1, 1);
2803
- mipHeight = Math.max(mipHeight >> 1, 1);
2804
- }
2805
- }
2806
- };
2807
-
2808
- const glUploadImageResource = {
2809
- id: "image",
2810
- upload(source, glTexture, gl, webGLVersion) {
2811
- const glWidth = glTexture.width;
2812
- const glHeight = glTexture.height;
2813
- const textureWidth = source.pixelWidth;
2814
- const textureHeight = source.pixelHeight;
2815
- const resourceWidth = source.resourceWidth;
2816
- const resourceHeight = source.resourceHeight;
2817
- if (resourceWidth < textureWidth || resourceHeight < textureHeight) {
2818
- if (glWidth !== textureWidth || glHeight !== textureHeight) {
2819
- gl.texImage2D(
2820
- glTexture.target,
2821
- 0,
2822
- glTexture.internalFormat,
2823
- textureWidth,
2824
- textureHeight,
2825
- 0,
2826
- glTexture.format,
2827
- glTexture.type,
2828
- null
2829
- );
2830
- }
2831
- if (webGLVersion === 2) {
2832
- gl.texSubImage2D(
2833
- gl.TEXTURE_2D,
2834
- 0,
2835
- 0,
2836
- 0,
2837
- resourceWidth,
2838
- resourceHeight,
2839
- glTexture.format,
2840
- glTexture.type,
2841
- source.resource
2842
- );
2843
- } else {
2844
- gl.texSubImage2D(
2845
- gl.TEXTURE_2D,
2846
- 0,
2847
- 0,
2848
- 0,
2849
- glTexture.format,
2850
- glTexture.type,
2851
- source.resource
2852
- );
2853
- }
2854
- } else if (glWidth === textureWidth && glHeight === textureHeight) {
2855
- gl.texSubImage2D(
2856
- gl.TEXTURE_2D,
2857
- 0,
2858
- 0,
2859
- 0,
2860
- glTexture.format,
2861
- glTexture.type,
2862
- source.resource
2863
- );
2864
- } else if (webGLVersion === 2) {
2865
- gl.texImage2D(
2866
- glTexture.target,
2867
- 0,
2868
- glTexture.internalFormat,
2869
- textureWidth,
2870
- textureHeight,
2871
- 0,
2872
- glTexture.format,
2873
- glTexture.type,
2874
- source.resource
2875
- );
2876
- } else {
2877
- gl.texImage2D(
2878
- glTexture.target,
2879
- 0,
2880
- glTexture.internalFormat,
2881
- glTexture.format,
2882
- glTexture.type,
2883
- source.resource
2884
- );
2885
- }
2886
- glTexture.width = textureWidth;
2887
- glTexture.height = textureHeight;
2888
- }
2889
- };
2890
-
2891
- const glUploadVideoResource = {
2892
- id: "video",
2893
- upload(source, glTexture, gl, webGLVersion) {
2894
- if (!source.isValid) {
2895
- gl.texImage2D(
2896
- glTexture.target,
2897
- 0,
2898
- glTexture.internalFormat,
2899
- 1,
2900
- 1,
2901
- 0,
2902
- glTexture.format,
2903
- glTexture.type,
2904
- null
2905
- );
2906
- return;
2907
- }
2908
- glUploadImageResource.upload(source, glTexture, gl, webGLVersion);
2909
- }
2910
- };
2911
-
2912
- const scaleModeToGlFilter = {
2913
- linear: 9729,
2914
- nearest: 9728
2915
- };
2916
- const mipmapScaleModeToGlFilter = {
2917
- linear: {
2918
- linear: 9987,
2919
- nearest: 9985
2920
- },
2921
- nearest: {
2922
- linear: 9986,
2923
- nearest: 9984
2924
- }
2925
- };
2926
- const wrapModeToGlAddress = {
2927
- "clamp-to-edge": 33071,
2928
- repeat: 10497,
2929
- "mirror-repeat": 33648
2930
- };
2931
- const compareModeToGlCompare = {
2932
- never: 512,
2933
- less: 513,
2934
- equal: 514,
2935
- "less-equal": 515,
2936
- greater: 516,
2937
- "not-equal": 517,
2938
- "greater-equal": 518,
2939
- always: 519
2940
- };
2941
-
2942
- function applyStyleParams(style, gl, mipmaps, anisotropicExt, glFunctionName, firstParam, forceClamp, firstCreation) {
2943
- const castParam = firstParam;
2944
- if (!firstCreation || style.addressModeU !== "repeat" || style.addressModeV !== "repeat" || style.addressModeW !== "repeat") {
2945
- const wrapModeS = wrapModeToGlAddress[forceClamp ? "clamp-to-edge" : style.addressModeU];
2946
- const wrapModeT = wrapModeToGlAddress[forceClamp ? "clamp-to-edge" : style.addressModeV];
2947
- const wrapModeR = wrapModeToGlAddress[forceClamp ? "clamp-to-edge" : style.addressModeW];
2948
- gl[glFunctionName](castParam, gl.TEXTURE_WRAP_S, wrapModeS);
2949
- gl[glFunctionName](castParam, gl.TEXTURE_WRAP_T, wrapModeT);
2950
- if (gl.TEXTURE_WRAP_R)
2951
- gl[glFunctionName](castParam, gl.TEXTURE_WRAP_R, wrapModeR);
2952
- }
2953
- if (!firstCreation || style.magFilter !== "linear") {
2954
- gl[glFunctionName](castParam, gl.TEXTURE_MAG_FILTER, scaleModeToGlFilter[style.magFilter]);
2955
- }
2956
- if (mipmaps) {
2957
- if (!firstCreation || style.mipmapFilter !== "linear") {
2958
- const glFilterMode = mipmapScaleModeToGlFilter[style.minFilter][style.mipmapFilter];
2959
- gl[glFunctionName](castParam, gl.TEXTURE_MIN_FILTER, glFilterMode);
2960
- }
2961
- } else {
2962
- gl[glFunctionName](castParam, gl.TEXTURE_MIN_FILTER, scaleModeToGlFilter[style.minFilter]);
2963
- }
2964
- if (anisotropicExt && style.maxAnisotropy > 1) {
2965
- const level = Math.min(style.maxAnisotropy, gl.getParameter(anisotropicExt.MAX_TEXTURE_MAX_ANISOTROPY_EXT));
2966
- gl[glFunctionName](castParam, anisotropicExt.TEXTURE_MAX_ANISOTROPY_EXT, level);
2967
- }
2968
- if (style.compare) {
2969
- gl[glFunctionName](castParam, gl.TEXTURE_COMPARE_FUNC, compareModeToGlCompare[style.compare]);
2970
- }
2971
- }
2972
-
2973
- function mapFormatToGlFormat(gl) {
2974
- return {
2975
- // 8-bit formats
2976
- r8unorm: gl.RED,
2977
- r8snorm: gl.RED,
2978
- r8uint: gl.RED,
2979
- r8sint: gl.RED,
2980
- // 16-bit formats
2981
- r16uint: gl.RED,
2982
- r16sint: gl.RED,
2983
- r16float: gl.RED,
2984
- rg8unorm: gl.RG,
2985
- rg8snorm: gl.RG,
2986
- rg8uint: gl.RG,
2987
- rg8sint: gl.RG,
2988
- // 32-bit formats
2989
- r32uint: gl.RED,
2990
- r32sint: gl.RED,
2991
- r32float: gl.RED,
2992
- rg16uint: gl.RG,
2993
- rg16sint: gl.RG,
2994
- rg16float: gl.RG,
2995
- rgba8unorm: gl.RGBA,
2996
- "rgba8unorm-srgb": gl.RGBA,
2997
- // Packed 32-bit formats
2998
- rgba8snorm: gl.RGBA,
2999
- rgba8uint: gl.RGBA,
3000
- rgba8sint: gl.RGBA,
3001
- bgra8unorm: gl.RGBA,
3002
- "bgra8unorm-srgb": gl.RGBA,
3003
- rgb9e5ufloat: gl.RGB,
3004
- rgb10a2unorm: gl.RGBA,
3005
- rg11b10ufloat: gl.RGB,
3006
- // 64-bit formats
3007
- rg32uint: gl.RG,
3008
- rg32sint: gl.RG,
3009
- rg32float: gl.RG,
3010
- rgba16uint: gl.RGBA,
3011
- rgba16sint: gl.RGBA,
3012
- rgba16float: gl.RGBA,
3013
- // 128-bit formats
3014
- rgba32uint: gl.RGBA,
3015
- rgba32sint: gl.RGBA,
3016
- rgba32float: gl.RGBA,
3017
- // Depth/stencil formats
3018
- stencil8: gl.STENCIL_INDEX8,
3019
- depth16unorm: gl.DEPTH_COMPONENT,
3020
- depth24plus: gl.DEPTH_COMPONENT,
3021
- "depth24plus-stencil8": gl.DEPTH_STENCIL,
3022
- depth32float: gl.DEPTH_COMPONENT,
3023
- "depth32float-stencil8": gl.DEPTH_STENCIL
3024
- };
3025
- }
3026
-
3027
- function mapFormatToGlInternalFormat(gl, extensions) {
3028
- let srgb = {};
3029
- let bgra8unorm = gl.RGBA;
3030
- if (!(gl instanceof DOMAdapter.get().getWebGLRenderingContext())) {
3031
- srgb = {
3032
- "rgba8unorm-srgb": gl.SRGB8_ALPHA8,
3033
- "bgra8unorm-srgb": gl.SRGB8_ALPHA8
3034
- };
3035
- bgra8unorm = gl.RGBA8;
3036
- } else if (extensions.srgb) {
3037
- srgb = {
3038
- "rgba8unorm-srgb": extensions.srgb.SRGB8_ALPHA8_EXT,
3039
- "bgra8unorm-srgb": extensions.srgb.SRGB8_ALPHA8_EXT
3040
- };
3041
- }
3042
- return {
3043
- // 8-bit formats
3044
- r8unorm: gl.R8,
3045
- r8snorm: gl.R8_SNORM,
3046
- r8uint: gl.R8UI,
3047
- r8sint: gl.R8I,
3048
- // 16-bit formats
3049
- r16uint: gl.R16UI,
3050
- r16sint: gl.R16I,
3051
- r16float: gl.R16F,
3052
- rg8unorm: gl.RG8,
3053
- rg8snorm: gl.RG8_SNORM,
3054
- rg8uint: gl.RG8UI,
3055
- rg8sint: gl.RG8I,
3056
- // 32-bit formats
3057
- r32uint: gl.R32UI,
3058
- r32sint: gl.R32I,
3059
- r32float: gl.R32F,
3060
- rg16uint: gl.RG16UI,
3061
- rg16sint: gl.RG16I,
3062
- rg16float: gl.RG16F,
3063
- rgba8unorm: gl.RGBA,
3064
- ...srgb,
3065
- // Packed 32-bit formats
3066
- rgba8snorm: gl.RGBA8_SNORM,
3067
- rgba8uint: gl.RGBA8UI,
3068
- rgba8sint: gl.RGBA8I,
3069
- bgra8unorm,
3070
- rgb9e5ufloat: gl.RGB9_E5,
3071
- rgb10a2unorm: gl.RGB10_A2,
3072
- rg11b10ufloat: gl.R11F_G11F_B10F,
3073
- // 64-bit formats
3074
- rg32uint: gl.RG32UI,
3075
- rg32sint: gl.RG32I,
3076
- rg32float: gl.RG32F,
3077
- rgba16uint: gl.RGBA16UI,
3078
- rgba16sint: gl.RGBA16I,
3079
- rgba16float: gl.RGBA16F,
3080
- // 128-bit formats
3081
- rgba32uint: gl.RGBA32UI,
3082
- rgba32sint: gl.RGBA32I,
3083
- rgba32float: gl.RGBA32F,
3084
- // Depth/stencil formats
3085
- stencil8: gl.STENCIL_INDEX8,
3086
- depth16unorm: gl.DEPTH_COMPONENT16,
3087
- depth24plus: gl.DEPTH_COMPONENT24,
3088
- "depth24plus-stencil8": gl.DEPTH24_STENCIL8,
3089
- depth32float: gl.DEPTH_COMPONENT32F,
3090
- "depth32float-stencil8": gl.DEPTH32F_STENCIL8,
3091
- // Compressed formats
3092
- ...extensions.s3tc ? {
3093
- "bc1-rgba-unorm": extensions.s3tc.COMPRESSED_RGBA_S3TC_DXT1_EXT,
3094
- "bc2-rgba-unorm": extensions.s3tc.COMPRESSED_RGBA_S3TC_DXT3_EXT,
3095
- "bc3-rgba-unorm": extensions.s3tc.COMPRESSED_RGBA_S3TC_DXT5_EXT
3096
- } : {},
3097
- ...extensions.s3tc_sRGB ? {
3098
- "bc1-rgba-unorm-srgb": extensions.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,
3099
- "bc2-rgba-unorm-srgb": extensions.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT,
3100
- "bc3-rgba-unorm-srgb": extensions.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT
3101
- } : {},
3102
- ...extensions.rgtc ? {
3103
- "bc4-r-unorm": extensions.rgtc.COMPRESSED_RED_RGTC1_EXT,
3104
- "bc4-r-snorm": extensions.rgtc.COMPRESSED_SIGNED_RED_RGTC1_EXT,
3105
- "bc5-rg-unorm": extensions.rgtc.COMPRESSED_RED_GREEN_RGTC2_EXT,
3106
- "bc5-rg-snorm": extensions.rgtc.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT
3107
- } : {},
3108
- ...extensions.bptc ? {
3109
- "bc6h-rgb-float": extensions.bptc.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT,
3110
- "bc6h-rgb-ufloat": extensions.bptc.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT,
3111
- "bc7-rgba-unorm": extensions.bptc.COMPRESSED_RGBA_BPTC_UNORM_EXT,
3112
- "bc7-rgba-unorm-srgb": extensions.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT
3113
- } : {},
3114
- ...extensions.etc ? {
3115
- "etc2-rgb8unorm": extensions.etc.COMPRESSED_RGB8_ETC2,
3116
- "etc2-rgb8unorm-srgb": extensions.etc.COMPRESSED_SRGB8_ETC2,
3117
- "etc2-rgb8a1unorm": extensions.etc.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2,
3118
- "etc2-rgb8a1unorm-srgb": extensions.etc.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2,
3119
- "etc2-rgba8unorm": extensions.etc.COMPRESSED_RGBA8_ETC2_EAC,
3120
- "etc2-rgba8unorm-srgb": extensions.etc.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC,
3121
- "eac-r11unorm": extensions.etc.COMPRESSED_R11_EAC,
3122
- // 'eac-r11snorm'
3123
- "eac-rg11unorm": extensions.etc.COMPRESSED_SIGNED_RG11_EAC
3124
- // 'eac-rg11snorm'
3125
- } : {},
3126
- ...extensions.astc ? {
3127
- "astc-4x4-unorm": extensions.astc.COMPRESSED_RGBA_ASTC_4x4_KHR,
3128
- "astc-4x4-unorm-srgb": extensions.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR,
3129
- "astc-5x4-unorm": extensions.astc.COMPRESSED_RGBA_ASTC_5x4_KHR,
3130
- "astc-5x4-unorm-srgb": extensions.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR,
3131
- "astc-5x5-unorm": extensions.astc.COMPRESSED_RGBA_ASTC_5x5_KHR,
3132
- "astc-5x5-unorm-srgb": extensions.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR,
3133
- "astc-6x5-unorm": extensions.astc.COMPRESSED_RGBA_ASTC_6x5_KHR,
3134
- "astc-6x5-unorm-srgb": extensions.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR,
3135
- "astc-6x6-unorm": extensions.astc.COMPRESSED_RGBA_ASTC_6x6_KHR,
3136
- "astc-6x6-unorm-srgb": extensions.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR,
3137
- "astc-8x5-unorm": extensions.astc.COMPRESSED_RGBA_ASTC_8x5_KHR,
3138
- "astc-8x5-unorm-srgb": extensions.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR,
3139
- "astc-8x6-unorm": extensions.astc.COMPRESSED_RGBA_ASTC_8x6_KHR,
3140
- "astc-8x6-unorm-srgb": extensions.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR,
3141
- "astc-8x8-unorm": extensions.astc.COMPRESSED_RGBA_ASTC_8x8_KHR,
3142
- "astc-8x8-unorm-srgb": extensions.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR,
3143
- "astc-10x5-unorm": extensions.astc.COMPRESSED_RGBA_ASTC_10x5_KHR,
3144
- "astc-10x5-unorm-srgb": extensions.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR,
3145
- "astc-10x6-unorm": extensions.astc.COMPRESSED_RGBA_ASTC_10x6_KHR,
3146
- "astc-10x6-unorm-srgb": extensions.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR,
3147
- "astc-10x8-unorm": extensions.astc.COMPRESSED_RGBA_ASTC_10x8_KHR,
3148
- "astc-10x8-unorm-srgb": extensions.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR,
3149
- "astc-10x10-unorm": extensions.astc.COMPRESSED_RGBA_ASTC_10x10_KHR,
3150
- "astc-10x10-unorm-srgb": extensions.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR,
3151
- "astc-12x10-unorm": extensions.astc.COMPRESSED_RGBA_ASTC_12x10_KHR,
3152
- "astc-12x10-unorm-srgb": extensions.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR,
3153
- "astc-12x12-unorm": extensions.astc.COMPRESSED_RGBA_ASTC_12x12_KHR,
3154
- "astc-12x12-unorm-srgb": extensions.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR
3155
- } : {}
3156
- };
3157
- }
3158
-
3159
- function mapFormatToGlType(gl) {
3160
- return {
3161
- // 8-bit formats
3162
- r8unorm: gl.UNSIGNED_BYTE,
3163
- r8snorm: gl.BYTE,
3164
- r8uint: gl.UNSIGNED_BYTE,
3165
- r8sint: gl.BYTE,
3166
- // 16-bit formats
3167
- r16uint: gl.UNSIGNED_SHORT,
3168
- r16sint: gl.SHORT,
3169
- r16float: gl.HALF_FLOAT,
3170
- rg8unorm: gl.UNSIGNED_BYTE,
3171
- rg8snorm: gl.BYTE,
3172
- rg8uint: gl.UNSIGNED_BYTE,
3173
- rg8sint: gl.BYTE,
3174
- // 32-bit formats
3175
- r32uint: gl.UNSIGNED_INT,
3176
- r32sint: gl.INT,
3177
- r32float: gl.FLOAT,
3178
- rg16uint: gl.UNSIGNED_SHORT,
3179
- rg16sint: gl.SHORT,
3180
- rg16float: gl.HALF_FLOAT,
3181
- rgba8unorm: gl.UNSIGNED_BYTE,
3182
- "rgba8unorm-srgb": gl.UNSIGNED_BYTE,
3183
- // Packed 32-bit formats
3184
- rgba8snorm: gl.BYTE,
3185
- rgba8uint: gl.UNSIGNED_BYTE,
3186
- rgba8sint: gl.BYTE,
3187
- bgra8unorm: gl.UNSIGNED_BYTE,
3188
- "bgra8unorm-srgb": gl.UNSIGNED_BYTE,
3189
- rgb9e5ufloat: gl.UNSIGNED_INT_5_9_9_9_REV,
3190
- rgb10a2unorm: gl.UNSIGNED_INT_2_10_10_10_REV,
3191
- rg11b10ufloat: gl.UNSIGNED_INT_10F_11F_11F_REV,
3192
- // 64-bit formats
3193
- rg32uint: gl.UNSIGNED_INT,
3194
- rg32sint: gl.INT,
3195
- rg32float: gl.FLOAT,
3196
- rgba16uint: gl.UNSIGNED_SHORT,
3197
- rgba16sint: gl.SHORT,
3198
- rgba16float: gl.HALF_FLOAT,
3199
- // 128-bit formats
3200
- rgba32uint: gl.UNSIGNED_INT,
3201
- rgba32sint: gl.INT,
3202
- rgba32float: gl.FLOAT,
3203
- // Depth/stencil formats
3204
- stencil8: gl.UNSIGNED_BYTE,
3205
- depth16unorm: gl.UNSIGNED_SHORT,
3206
- depth24plus: gl.UNSIGNED_INT,
3207
- "depth24plus-stencil8": gl.UNSIGNED_INT_24_8,
3208
- depth32float: gl.FLOAT,
3209
- "depth32float-stencil8": gl.FLOAT_32_UNSIGNED_INT_24_8_REV
3210
- };
3211
- }
3212
-
3213
- const BYTES_PER_PIXEL = 4;
3214
- class GlTextureSystem {
3215
- constructor(renderer) {
3216
- this.managedTextures = [];
3217
- this._glTextures = /* @__PURE__ */ Object.create(null);
3218
- this._glSamplers = /* @__PURE__ */ Object.create(null);
3219
- this._boundTextures = [];
3220
- this._activeTextureLocation = -1;
3221
- this._boundSamplers = /* @__PURE__ */ Object.create(null);
3222
- this._uploads = {
3223
- image: glUploadImageResource,
3224
- buffer: glUploadBufferImageResource,
3225
- video: glUploadVideoResource,
3226
- compressed: glUploadCompressedTextureResource
3227
- };
3228
- this._premultiplyAlpha = false;
3229
- // TODO - separate samplers will be a cool thing to add, but not right now!
3230
- this._useSeparateSamplers = false;
3231
- this._renderer = renderer;
3232
- this._renderer.renderableGC.addManagedHash(this, "_glTextures");
3233
- this._renderer.renderableGC.addManagedHash(this, "_glSamplers");
3234
- }
3235
- contextChange(gl) {
3236
- this._gl = gl;
3237
- if (!this._mapFormatToInternalFormat) {
3238
- this._mapFormatToInternalFormat = mapFormatToGlInternalFormat(gl, this._renderer.context.extensions);
3239
- this._mapFormatToType = mapFormatToGlType(gl);
3240
- this._mapFormatToFormat = mapFormatToGlFormat(gl);
3241
- }
3242
- this._glTextures = /* @__PURE__ */ Object.create(null);
3243
- this._glSamplers = /* @__PURE__ */ Object.create(null);
3244
- this._boundSamplers = /* @__PURE__ */ Object.create(null);
3245
- this._premultiplyAlpha = false;
3246
- for (let i = 0; i < 16; i++) {
3247
- this.bind(Texture.EMPTY, i);
3248
- }
3249
- }
3250
- initSource(source) {
3251
- this.bind(source);
3252
- }
3253
- bind(texture, location = 0) {
3254
- const source = texture.source;
3255
- if (texture) {
3256
- this.bindSource(source, location);
3257
- if (this._useSeparateSamplers) {
3258
- this._bindSampler(source.style, location);
3259
- }
3260
- } else {
3261
- this.bindSource(null, location);
3262
- if (this._useSeparateSamplers) {
3263
- this._bindSampler(null, location);
3264
- }
3265
- }
3266
- }
3267
- bindSource(source, location = 0) {
3268
- const gl = this._gl;
3269
- source._touched = this._renderer.textureGC.count;
3270
- if (this._boundTextures[location] !== source) {
3271
- this._boundTextures[location] = source;
3272
- this._activateLocation(location);
3273
- source || (source = Texture.EMPTY.source);
3274
- const glTexture = this.getGlSource(source);
3275
- gl.bindTexture(glTexture.target, glTexture.texture);
3276
- }
3277
- }
3278
- _bindSampler(style, location = 0) {
3279
- const gl = this._gl;
3280
- if (!style) {
3281
- this._boundSamplers[location] = null;
3282
- gl.bindSampler(location, null);
3283
- return;
3284
- }
3285
- const sampler = this._getGlSampler(style);
3286
- if (this._boundSamplers[location] !== sampler) {
3287
- this._boundSamplers[location] = sampler;
3288
- gl.bindSampler(location, sampler);
3289
- }
3290
- }
3291
- unbind(texture) {
3292
- const source = texture.source;
3293
- const boundTextures = this._boundTextures;
3294
- const gl = this._gl;
3295
- for (let i = 0; i < boundTextures.length; i++) {
3296
- if (boundTextures[i] === source) {
3297
- this._activateLocation(i);
3298
- const glTexture = this.getGlSource(source);
3299
- gl.bindTexture(glTexture.target, null);
3300
- boundTextures[i] = null;
3301
- }
3302
- }
3303
- }
3304
- _activateLocation(location) {
3305
- if (this._activeTextureLocation !== location) {
3306
- this._activeTextureLocation = location;
3307
- this._gl.activeTexture(this._gl.TEXTURE0 + location);
3308
- }
3309
- }
3310
- _initSource(source) {
3311
- const gl = this._gl;
3312
- const glTexture = new GlTexture(gl.createTexture());
3313
- glTexture.type = this._mapFormatToType[source.format];
3314
- glTexture.internalFormat = this._mapFormatToInternalFormat[source.format];
3315
- glTexture.format = this._mapFormatToFormat[source.format];
3316
- if (source.autoGenerateMipmaps && (this._renderer.context.supports.nonPowOf2mipmaps || source.isPowerOfTwo)) {
3317
- const biggestDimension = Math.max(source.width, source.height);
3318
- source.mipLevelCount = Math.floor(Math.log2(biggestDimension)) + 1;
3319
- }
3320
- this._glTextures[source.uid] = glTexture;
3321
- if (!this.managedTextures.includes(source)) {
3322
- source.on("update", this.onSourceUpdate, this);
3323
- source.on("resize", this.onSourceUpdate, this);
3324
- source.on("styleChange", this.onStyleChange, this);
3325
- source.on("destroy", this.onSourceDestroy, this);
3326
- source.on("unload", this.onSourceUnload, this);
3327
- source.on("updateMipmaps", this.onUpdateMipmaps, this);
3328
- this.managedTextures.push(source);
3329
- }
3330
- this.onSourceUpdate(source);
3331
- this.updateStyle(source, false);
3332
- return glTexture;
3333
- }
3334
- onStyleChange(source) {
3335
- this.updateStyle(source, false);
3336
- }
3337
- updateStyle(source, firstCreation) {
3338
- const gl = this._gl;
3339
- const glTexture = this.getGlSource(source);
3340
- gl.bindTexture(gl.TEXTURE_2D, glTexture.texture);
3341
- this._boundTextures[this._activeTextureLocation] = source;
3342
- applyStyleParams(
3343
- source.style,
3344
- gl,
3345
- source.mipLevelCount > 1,
3346
- this._renderer.context.extensions.anisotropicFiltering,
3347
- "texParameteri",
3348
- gl.TEXTURE_2D,
3349
- // will force a clamp to edge if the texture is not a power of two
3350
- !this._renderer.context.supports.nonPowOf2wrapping && !source.isPowerOfTwo,
3351
- firstCreation
3352
- );
3353
- }
3354
- onSourceUnload(source) {
3355
- const glTexture = this._glTextures[source.uid];
3356
- if (!glTexture)
3357
- return;
3358
- this.unbind(source);
3359
- this._glTextures[source.uid] = null;
3360
- this._gl.deleteTexture(glTexture.texture);
3361
- }
3362
- onSourceUpdate(source) {
3363
- const gl = this._gl;
3364
- const glTexture = this.getGlSource(source);
3365
- gl.bindTexture(gl.TEXTURE_2D, glTexture.texture);
3366
- this._boundTextures[this._activeTextureLocation] = source;
3367
- const premultipliedAlpha = source.alphaMode === "premultiply-alpha-on-upload";
3368
- if (this._premultiplyAlpha !== premultipliedAlpha) {
3369
- this._premultiplyAlpha = premultipliedAlpha;
3370
- gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, premultipliedAlpha);
3371
- }
3372
- if (this._uploads[source.uploadMethodId]) {
3373
- this._uploads[source.uploadMethodId].upload(source, glTexture, gl, this._renderer.context.webGLVersion);
3374
- } else {
3375
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, source.pixelWidth, source.pixelHeight, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
3376
- }
3377
- if (source.autoGenerateMipmaps && source.mipLevelCount > 1) {
3378
- this.onUpdateMipmaps(source, false);
3379
- }
3380
- }
3381
- onUpdateMipmaps(source, bind = true) {
3382
- if (bind)
3383
- this.bindSource(source, 0);
3384
- const glTexture = this.getGlSource(source);
3385
- this._gl.generateMipmap(glTexture.target);
3386
- }
3387
- onSourceDestroy(source) {
3388
- source.off("destroy", this.onSourceDestroy, this);
3389
- source.off("update", this.onSourceUpdate, this);
3390
- source.off("resize", this.onSourceUpdate, this);
3391
- source.off("unload", this.onSourceUnload, this);
3392
- source.off("styleChange", this.onStyleChange, this);
3393
- source.off("updateMipmaps", this.onUpdateMipmaps, this);
3394
- this.managedTextures.splice(this.managedTextures.indexOf(source), 1);
3395
- this.onSourceUnload(source);
3396
- }
3397
- _initSampler(style) {
3398
- const gl = this._gl;
3399
- const glSampler = this._gl.createSampler();
3400
- this._glSamplers[style._resourceId] = glSampler;
3401
- applyStyleParams(
3402
- style,
3403
- gl,
3404
- this._boundTextures[this._activeTextureLocation].mipLevelCount > 1,
3405
- this._renderer.context.extensions.anisotropicFiltering,
3406
- "samplerParameteri",
3407
- glSampler,
3408
- false,
3409
- true
3410
- );
3411
- return this._glSamplers[style._resourceId];
3412
- }
3413
- _getGlSampler(sampler) {
3414
- return this._glSamplers[sampler._resourceId] || this._initSampler(sampler);
3415
- }
3416
- getGlSource(source) {
3417
- return this._glTextures[source.uid] || this._initSource(source);
3418
- }
3419
- generateCanvas(texture) {
3420
- const { pixels, width, height } = this.getPixels(texture);
3421
- const canvas = DOMAdapter.get().createCanvas();
3422
- canvas.width = width;
3423
- canvas.height = height;
3424
- const ctx = canvas.getContext("2d");
3425
- if (ctx) {
3426
- const imageData = ctx.createImageData(width, height);
3427
- imageData.data.set(pixels);
3428
- ctx.putImageData(imageData, 0, 0);
3429
- }
3430
- return canvas;
3431
- }
3432
- getPixels(texture) {
3433
- const resolution = texture.source.resolution;
3434
- const frame = texture.frame;
3435
- const width = Math.max(Math.round(frame.width * resolution), 1);
3436
- const height = Math.max(Math.round(frame.height * resolution), 1);
3437
- const pixels = new Uint8Array(BYTES_PER_PIXEL * width * height);
3438
- const renderer = this._renderer;
3439
- const renderTarget = renderer.renderTarget.getRenderTarget(texture);
3440
- const glRenterTarget = renderer.renderTarget.getGpuRenderTarget(renderTarget);
3441
- const gl = renderer.gl;
3442
- gl.bindFramebuffer(gl.FRAMEBUFFER, glRenterTarget.resolveTargetFramebuffer);
3443
- gl.readPixels(
3444
- Math.round(frame.x * resolution),
3445
- Math.round(frame.y * resolution),
3446
- width,
3447
- height,
3448
- gl.RGBA,
3449
- gl.UNSIGNED_BYTE,
3450
- pixels
3451
- );
3452
- return { pixels: new Uint8ClampedArray(pixels.buffer), width, height };
3453
- }
3454
- destroy() {
3455
- this.managedTextures.slice().forEach((source) => this.onSourceDestroy(source));
3456
- this.managedTextures = null;
3457
- this._renderer = null;
3458
- }
3459
- resetState() {
3460
- this._activeTextureLocation = -1;
3461
- this._boundTextures.fill(Texture.EMPTY.source);
3462
- this._boundSamplers = /* @__PURE__ */ Object.create(null);
3463
- const gl = this._gl;
3464
- this._premultiplyAlpha = false;
3465
- gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this._premultiplyAlpha);
3466
- }
3467
- }
3468
- /** @ignore */
3469
- GlTextureSystem.extension = {
3470
- type: [
3471
- ExtensionType.WebGLSystem
3472
- ],
3473
- name: "texture"
3474
- };
3475
-
3476
- class GlGraphicsAdaptor {
3477
- contextChange(renderer) {
3478
- const uniforms = new UniformGroup({
3479
- uColor: { value: new Float32Array([1, 1, 1, 1]), type: "vec4<f32>" },
3480
- uTransformMatrix: { value: new Matrix(), type: "mat3x3<f32>" },
3481
- uRound: { value: 0, type: "f32" }
3482
- });
3483
- const maxTextures = renderer.limits.maxBatchableTextures;
3484
- const glProgram = compileHighShaderGlProgram({
3485
- name: "graphics",
3486
- bits: [
3487
- colorBitGl,
3488
- generateTextureBatchBitGl(maxTextures),
3489
- localUniformBitGl,
3490
- roundPixelsBitGl
3491
- ]
3492
- });
3493
- this.shader = new Shader({
3494
- glProgram,
3495
- resources: {
3496
- localUniforms: uniforms,
3497
- batchSamplers: getBatchSamplersUniformGroup(maxTextures)
3498
- }
3499
- });
3500
- }
3501
- execute(graphicsPipe, renderable) {
3502
- const context = renderable.context;
3503
- const shader = context.customShader || this.shader;
3504
- const renderer = graphicsPipe.renderer;
3505
- const contextSystem = renderer.graphicsContext;
3506
- const {
3507
- batcher,
3508
- instructions
3509
- } = contextSystem.getContextRenderData(context);
3510
- shader.groups[0] = renderer.globalUniforms.bindGroup;
3511
- renderer.state.set(graphicsPipe.state);
3512
- renderer.shader.bind(shader);
3513
- renderer.geometry.bind(batcher.geometry, shader.glProgram);
3514
- const batches = instructions.instructions;
3515
- for (let i = 0; i < instructions.instructionSize; i++) {
3516
- const batch = batches[i];
3517
- if (batch.size) {
3518
- for (let j = 0; j < batch.textures.count; j++) {
3519
- renderer.texture.bind(batch.textures.textures[j], j);
3520
- }
3521
- renderer.geometry.draw(batch.topology, batch.size, batch.start);
3522
- }
3523
- }
3524
- }
3525
- destroy() {
3526
- this.shader.destroy(true);
3527
- this.shader = null;
3528
- }
3529
- }
3530
- /** @ignore */
3531
- GlGraphicsAdaptor.extension = {
3532
- type: [
3533
- ExtensionType.WebGLPipesAdaptor
3534
- ],
3535
- name: "graphics"
3536
- };
3537
-
3538
- class GlMeshAdaptor {
3539
- init() {
3540
- const glProgram = compileHighShaderGlProgram({
3541
- name: "mesh",
3542
- bits: [
3543
- localUniformBitGl,
3544
- textureBitGl,
3545
- roundPixelsBitGl
3546
- ]
3547
- });
3548
- this._shader = new Shader({
3549
- glProgram,
3550
- resources: {
3551
- uTexture: Texture.EMPTY.source,
3552
- textureUniforms: {
3553
- uTextureMatrix: { type: "mat3x3<f32>", value: new Matrix() }
3554
- }
3555
- }
3556
- });
3557
- }
3558
- execute(meshPipe, mesh) {
3559
- const renderer = meshPipe.renderer;
3560
- let shader = mesh._shader;
3561
- if (!shader) {
3562
- shader = this._shader;
3563
- const texture = mesh.texture;
3564
- const source = texture.source;
3565
- shader.resources.uTexture = source;
3566
- shader.resources.uSampler = source.style;
3567
- shader.resources.textureUniforms.uniforms.uTextureMatrix = texture.textureMatrix.mapCoord;
3568
- } else if (!shader.glProgram) {
3569
- warn("Mesh shader has no glProgram", mesh.shader);
3570
- return;
3571
- }
3572
- shader.groups[100] = renderer.globalUniforms.bindGroup;
3573
- shader.groups[101] = meshPipe.localUniformsBindGroup;
3574
- renderer.encoder.draw({
3575
- geometry: mesh._geometry,
3576
- shader,
3577
- state: mesh.state
3578
- });
3579
- }
3580
- destroy() {
3581
- this._shader.destroy(true);
3582
- this._shader = null;
3583
- }
3584
- }
3585
- GlMeshAdaptor.extension = {
3586
- type: [
3587
- ExtensionType.WebGLPipesAdaptor
3588
- ],
3589
- name: "mesh"
3590
- };
3591
-
3592
- const DefaultWebGLSystems = [
3593
- ...SharedSystems,
3594
- GlUboSystem,
3595
- GlBackBufferSystem,
3596
- GlContextSystem,
3597
- GlLimitsSystem,
3598
- GlBufferSystem,
3599
- GlTextureSystem,
3600
- GlRenderTargetSystem,
3601
- GlGeometrySystem,
3602
- GlUniformGroupSystem,
3603
- GlShaderSystem,
3604
- GlEncoderSystem,
3605
- GlStateSystem,
3606
- GlStencilSystem,
3607
- GlColorMaskSystem
3608
- ];
3609
- const DefaultWebGLPipes = [...SharedRenderPipes];
3610
- const DefaultWebGLAdapters = [GlBatchAdaptor, GlMeshAdaptor, GlGraphicsAdaptor];
3611
- const systems = [];
3612
- const renderPipes = [];
3613
- const renderPipeAdaptors = [];
3614
- extensions.handleByNamedList(ExtensionType.WebGLSystem, systems);
3615
- extensions.handleByNamedList(ExtensionType.WebGLPipes, renderPipes);
3616
- extensions.handleByNamedList(ExtensionType.WebGLPipesAdaptor, renderPipeAdaptors);
3617
- extensions.add(...DefaultWebGLSystems, ...DefaultWebGLPipes, ...DefaultWebGLAdapters);
3618
- class WebGLRenderer extends AbstractRenderer {
3619
- constructor() {
3620
- const systemConfig = {
3621
- name: "webgl",
3622
- type: RendererType.WEBGL,
3623
- systems,
3624
- renderPipes,
3625
- renderPipeAdaptors
3626
- };
3627
- super(systemConfig);
3628
- }
3629
- }
3630
-
3631
- export { WebGLRenderer };