-
Notifications
You must be signed in to change notification settings - Fork 3.3k
/
library_webgl.js
4368 lines (3971 loc) · 170 KB
/
library_webgl.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @license
* Copyright 2010 The Emscripten Authors
* SPDX-License-Identifier: MIT
*/
// Specifies the size of the GL temp buffer pool, in bytes. Must be a multiple
// of 9 and 16.
{{{ GL_POOL_TEMP_BUFFERS_SIZE = 2*9*16 }}} // = 288
{{{
globalThis.isCurrentContextWebGL2 = () => {
// This function should only be called inside of `#if MAX_WEBGL_VERSION >= 2` blocks
assert(MAX_WEBGL_VERSION >= 2, 'isCurrentContextWebGL2 called without webgl2 support');
if (MIN_WEBGL_VERSION >= 2) return 'true';
return 'GL.currentContext.version >= 2';
};
null;
}}}
var LibraryGL = {
// For functions such as glDrawBuffers, glInvalidateFramebuffer and
// glInvalidateSubFramebuffer that need to pass a short array to the WebGL
// API, create a set of short fixed-length arrays to avoid having to generate
// any garbage when calling those functions.
$tempFixedLengthArray__postset: 'for (var i = 0; i < 32; ++i) tempFixedLengthArray.push(new Array(i));',
$tempFixedLengthArray: [],
$miniTempWebGLFloatBuffers: [],
$miniTempWebGLFloatBuffers__postset: `var miniTempWebGLFloatBuffersStorage = new Float32Array({{{ GL_POOL_TEMP_BUFFERS_SIZE }}});
// Create GL_POOL_TEMP_BUFFERS_SIZE+1 temporary buffers, for uploads of size 0 through GL_POOL_TEMP_BUFFERS_SIZE inclusive
for (/**@suppress{duplicate}*/var i = 0; i <= {{{ GL_POOL_TEMP_BUFFERS_SIZE }}}; ++i) {
miniTempWebGLFloatBuffers[i] = miniTempWebGLFloatBuffersStorage.subarray(0, i);
}`,
$miniTempWebGLIntBuffers: [],
$miniTempWebGLIntBuffers__postset: `var miniTempWebGLIntBuffersStorage = new Int32Array({{{ GL_POOL_TEMP_BUFFERS_SIZE }}});
// Create GL_POOL_TEMP_BUFFERS_SIZE+1 temporary buffers, for uploads of size 0 through GL_POOL_TEMP_BUFFERS_SIZE inclusive
for (/**@suppress{duplicate}*/var i = 0; i <= {{{ GL_POOL_TEMP_BUFFERS_SIZE }}}; ++i) {
miniTempWebGLIntBuffers[i] = miniTempWebGLIntBuffersStorage.subarray(0, i);
}`,
$heapObjectForWebGLType: (type) => {
// Micro-optimization for size: Subtract lowest GL enum number (0x1400/* GL_BYTE */) from type to compare
// smaller values for the heap, for shorter generated code size.
// Also the type HEAPU16 is not tested for explicitly, but any unrecognized type will return out HEAPU16.
// (since most types are HEAPU16)
type -= 0x1400;
#if MAX_WEBGL_VERSION >= 2
if (type == {{{ 0x1400 - 0x1400/* GL_BYTE */ }}}) return HEAP8;
#endif
if (type == {{{ 0x1401 - 0x1400/* GL_UNSIGNED_BYTE */ }}}) return HEAPU8;
#if MAX_WEBGL_VERSION >= 2
if (type == {{{ 0x1402 - 0x1400/* GL_SHORT */ }}}) return HEAP16;
#endif
if (type == {{{ 0x1404 - 0x1400/* GL_INT */ }}}) return HEAP32;
if (type == {{{ 0x1406 - 0x1400/* GL_FLOAT */ }}}) return HEAPF32;
if (type == {{{ 0x1405 - 0x1400 /* GL_UNSIGNED_INT */ }}}
|| type == {{{ 0x84FA - 0x1400 /* GL_UNSIGNED_INT_24_8_WEBGL/GL_UNSIGNED_INT_24_8 */ }}}
#if MAX_WEBGL_VERSION >= 2
|| type == {{{ 0x8368 - 0x1400 /* GL_UNSIGNED_INT_2_10_10_10_REV */ }}}
|| type == {{{ 0x8C3B - 0x1400 /* GL_UNSIGNED_INT_10F_11F_11F_REV */ }}}
|| type == {{{ 0x8C3E - 0x1400 /* GL_UNSIGNED_INT_5_9_9_9_REV */ }}}
#endif
)
return HEAPU32;
#if GL_ASSERTIONS
if (type != {{{ 0x1403 - 0x1400 /* GL_UNSIGNED_SHORT */ }}}
#if MAX_WEBGL_VERSION >= 2
&& type != {{{ 0x140B - 0x1400 /* GL_HALF_FLOAT */ }}}
#endif
&& type != {{{ 0x8033 - 0x1400 /* GL_UNSIGNED_SHORT_4_4_4_4 */ }}}
&& type != {{{ 0x8034 - 0x1400 /* GL_UNSIGNED_SHORT_5_5_5_1 */ }}}
&& type != {{{ 0x8363 - 0x1400 /* GL_UNSIGNED_SHORT_5_6_5 */ }}}
&& type != {{{ 0x8D61 - 0x1400 /* GL_HALF_FLOAT_OES */ }}}) {
err(`Invalid WebGL type 0x${(type+0x1400).toString()} passed to $heapObjectForWebGLType!`);
}
#endif
return HEAPU16;
},
$toTypedArrayIndex: (pointer, heap) =>
#if MEMORY64
pointer / heap.BYTES_PER_ELEMENT,
#else
pointer >>> (31 - Math.clz32(heap.BYTES_PER_ELEMENT)),
#endif
#if MIN_WEBGL_VERSION == 1
$webgl_enable_ANGLE_instanced_arrays: (ctx) => {
// Extension available in WebGL 1 from Firefox 26 and Google Chrome 30 onwards. Core feature in WebGL 2.
var ext = ctx.getExtension('ANGLE_instanced_arrays');
// Because this extension is a core function in WebGL 2, assign the extension entry points in place of
// where the core functions will reside in WebGL 2. This way the calling code can call these without
// having to dynamically branch depending if running against WebGL 1 or WebGL 2.
if (ext) {
ctx['vertexAttribDivisor'] = (index, divisor) => ext['vertexAttribDivisorANGLE'](index, divisor);
ctx['drawArraysInstanced'] = (mode, first, count, primcount) => ext['drawArraysInstancedANGLE'](mode, first, count, primcount);
ctx['drawElementsInstanced'] = (mode, count, type, indices, primcount) => ext['drawElementsInstancedANGLE'](mode, count, type, indices, primcount);
return 1;
}
},
emscripten_webgl_enable_ANGLE_instanced_arrays__deps: ['$webgl_enable_ANGLE_instanced_arrays'],
emscripten_webgl_enable_ANGLE_instanced_arrays: (ctx) => webgl_enable_ANGLE_instanced_arrays(GL.contexts[ctx].GLctx),
$webgl_enable_OES_vertex_array_object: (ctx) => {
// Extension available in WebGL 1 from Firefox 25 and WebKit 536.28/desktop Safari 6.0.3 onwards. Core feature in WebGL 2.
var ext = ctx.getExtension('OES_vertex_array_object');
if (ext) {
ctx['createVertexArray'] = () => ext['createVertexArrayOES']();
ctx['deleteVertexArray'] = (vao) => ext['deleteVertexArrayOES'](vao);
ctx['bindVertexArray'] = (vao) => ext['bindVertexArrayOES'](vao);
ctx['isVertexArray'] = (vao) => ext['isVertexArrayOES'](vao);
return 1;
}
},
emscripten_webgl_enable_OES_vertex_array_object__deps: ['$webgl_enable_OES_vertex_array_object'],
emscripten_webgl_enable_OES_vertex_array_object: (ctx) => webgl_enable_OES_vertex_array_object(GL.contexts[ctx].GLctx),
$webgl_enable_WEBGL_draw_buffers: (ctx) => {
// Extension available in WebGL 1 from Firefox 28 onwards. Core feature in WebGL 2.
var ext = ctx.getExtension('WEBGL_draw_buffers');
if (ext) {
ctx['drawBuffers'] = (n, bufs) => ext['drawBuffersWEBGL'](n, bufs);
return 1;
}
},
emscripten_webgl_enable_WEBGL_draw_buffers__deps: ['$webgl_enable_WEBGL_draw_buffers'],
emscripten_webgl_enable_WEBGL_draw_buffers: (ctx) => webgl_enable_WEBGL_draw_buffers(GL.contexts[ctx].GLctx),
#endif
$webgl_enable_WEBGL_multi_draw: (ctx) => {
// Closure is expected to be allowed to minify the '.multiDrawWebgl' property, so not accessing it quoted.
return !!(ctx.multiDrawWebgl = ctx.getExtension('WEBGL_multi_draw'));
},
emscripten_webgl_enable_WEBGL_multi_draw__deps: ['$webgl_enable_WEBGL_multi_draw'],
emscripten_webgl_enable_WEBGL_multi_draw: (ctx) => webgl_enable_WEBGL_multi_draw(GL.contexts[ctx].GLctx),
$webgl_enable_EXT_polygon_offset_clamp: (ctx) => {
return !!(ctx.extPolygonOffsetClamp = ctx.getExtension('EXT_polygon_offset_clamp'));
},
emscripten_webgl_enable_EXT_polygon_offset_clamp__deps: ['$webgl_enable_EXT_polygon_offset_clamp'],
emscripten_webgl_enable_EXT_polygon_offset_clamp: (ctx) => webgl_enable_EXT_polygon_offset_clamp(GL.contexts[ctx].GLctx),
$webgl_enable_EXT_clip_control: (ctx) => {
return !!(ctx.extClipControl = ctx.getExtension('EXT_clip_control'));
},
emscripten_webgl_enable_EXT_clip_control__deps: ['$webgl_enable_EXT_clip_control'],
emscripten_webgl_enable_EXT_clip_control: (ctx) => webgl_enable_EXT_clip_control(GL.contexts[ctx].GLctx),
$webgl_enable_WEBGL_polygon_mode: (ctx) => {
return !!(ctx.webglPolygonMode = ctx.getExtension('WEBGL_polygon_mode'));
},
emscripten_webgl_enable_WEBGL_polygon_mode__deps: ['$webgl_enable_WEBGL_polygon_mode'],
emscripten_webgl_enable_WEBGL_polygon_mode: (ctx) => webgl_enable_WEBGL_polygon_mode(GL.contexts[ctx].GLctx),
$getEmscriptenSupportedExtensions__internal: true,
$getEmscriptenSupportedExtensions: (ctx) => {
// Restrict the list of advertised extensions to those that we actually
// support.
var supportedExtensions = [
#if MIN_WEBGL_VERSION == 1
// WebGL 1 extensions
'ANGLE_instanced_arrays',
'EXT_blend_minmax',
'EXT_disjoint_timer_query',
'EXT_frag_depth',
'EXT_shader_texture_lod',
'EXT_sRGB',
'OES_element_index_uint',
'OES_fbo_render_mipmap',
'OES_standard_derivatives',
'OES_texture_float',
'OES_texture_half_float',
'OES_texture_half_float_linear',
'OES_vertex_array_object',
'WEBGL_color_buffer_float',
'WEBGL_depth_texture',
'WEBGL_draw_buffers',
#endif
#if MAX_WEBGL_VERSION >= 2
// WebGL 2 extensions
'EXT_color_buffer_float',
'EXT_conservative_depth',
'EXT_disjoint_timer_query_webgl2',
'EXT_texture_norm16',
'NV_shader_noperspective_interpolation',
'WEBGL_clip_cull_distance',
#endif
// WebGL 1 and WebGL 2 extensions
'EXT_clip_control',
'EXT_color_buffer_half_float',
'EXT_depth_clamp',
'EXT_float_blend',
'EXT_polygon_offset_clamp',
'EXT_texture_compression_bptc',
'EXT_texture_compression_rgtc',
'EXT_texture_filter_anisotropic',
'KHR_parallel_shader_compile',
'OES_texture_float_linear',
'WEBGL_blend_func_extended',
'WEBGL_compressed_texture_astc',
'WEBGL_compressed_texture_etc',
'WEBGL_compressed_texture_etc1',
'WEBGL_compressed_texture_s3tc',
'WEBGL_compressed_texture_s3tc_srgb',
'WEBGL_debug_renderer_info',
'WEBGL_debug_shaders',
'WEBGL_lose_context',
'WEBGL_multi_draw',
'WEBGL_polygon_mode'
];
// .getSupportedExtensions() can return null if context is lost, so coerce to empty array.
return (ctx.getSupportedExtensions() || []).filter(ext => supportedExtensions.includes(ext));
},
$GLctx__internal: true,
$GLctx: undefined,
$GL__deps: [
'$GLctx',
#if GL_SUPPORT_AUTOMATIC_ENABLE_EXTENSIONS
// If GL_SUPPORT_AUTOMATIC_ENABLE_EXTENSIONS is enabled, GL.initExtensions() will call to initialize these.
#if PTHREADS
'malloc', // Needed by registerContext
'free', // Needed by deleteContext
#endif
#if MIN_WEBGL_VERSION == 1
'$webgl_enable_ANGLE_instanced_arrays',
'$webgl_enable_OES_vertex_array_object',
'$webgl_enable_WEBGL_draw_buffers',
#endif
#if MAX_WEBGL_VERSION >= 2
'$webgl_enable_WEBGL_draw_instanced_base_vertex_base_instance',
'$webgl_enable_WEBGL_multi_draw_instanced_base_vertex_base_instance',
#endif
'$webgl_enable_EXT_polygon_offset_clamp',
'$webgl_enable_EXT_clip_control',
'$webgl_enable_WEBGL_polygon_mode',
'$webgl_enable_WEBGL_multi_draw',
'$getEmscriptenSupportedExtensions',
#endif // GL_SUPPORT_AUTOMATIC_ENABLE_EXTENSIONS
#if FULL_ES2 || LEGACY_GL_EMULATION
'$registerPreMainLoop',
#endif
],
#if FULL_ES2 || LEGACY_GL_EMULATION
$GL__postset: `
// Signal GL rendering layer that processing of a new frame is about to
// start. This helps it optimize VBO double-buffering and reduce GPU stalls.
registerPreMainLoop(() => GL.newRenderingFrameStarted());
`,
#endif
$GL: {
#if GL_DEBUG
debug: true,
#endif
/* We do not depend on the exact initial values of falsey member fields - these
fields can be populated on-demand to save code size.
(but still documented here to keep track of what is supposed to be present)
#if GL_TRACK_ERRORS
lastError: 0,
#endif
currentContext: null,
#if FULL_ES2 || LEGACY_GL_EMULATION
currArrayBuffer: 0,
currElementArrayBuffer: 0,
#endif
*/
counter: 1, // 0 is reserved as 'null' in gl
buffers: [],
#if FULL_ES3
mappedBuffers: {},
#endif
programs: [],
framebuffers: [],
renderbuffers: [],
textures: [],
shaders: [],
vaos: [],
#if PTHREADS // with pthreads a context is a location in memory with some synchronized data between threads
contexts: {},
#else // without pthreads, it's just an integer ID
contexts: [],
#endif
// DOM ID -> OffscreenCanvas mappings of <canvas> elements that have their
// rendering control transferred to offscreen.
offscreenCanvases: {},
// on WebGL1 stores WebGLTimerQueryEXT, on WebGL2 WebGLQuery
queries: [],
#if MAX_WEBGL_VERSION >= 2
samplers: [],
transformFeedbacks: [],
syncs: [],
#endif
#if FULL_ES2 || LEGACY_GL_EMULATION
byteSizeByTypeRoot: 0x1400, // GL_BYTE
byteSizeByType: [
1, // GL_BYTE
1, // GL_UNSIGNED_BYTE
2, // GL_SHORT
2, // GL_UNSIGNED_SHORT
4, // GL_INT
4, // GL_UNSIGNED_INT
4, // GL_FLOAT
2, // GL_2_BYTES
3, // GL_3_BYTES
4, // GL_4_BYTES
8 // GL_DOUBLE
],
#endif
stringCache: {},
#if MAX_WEBGL_VERSION >= 2
stringiCache: {},
#endif
unpackAlignment: 4, // default alignment is 4 bytes
unpackRowLength: 0,
// Records a GL error condition that occurred, stored until user calls
// glGetError() to fetch it. As per GLES2 spec, only the first error is
// remembered, and subsequent errors are discarded until the user has
// cleared the stored error by a call to glGetError().
recordError: (errorCode) => {
#if GL_TRACK_ERRORS
if (!GL.lastError) {
GL.lastError = errorCode;
}
#endif
},
// Get a new ID for a texture/buffer/etc., while keeping the table dense and
// fast. Creation is fairly rare so it is worth optimizing lookups later.
getNewId: (table) => {
var ret = GL.counter++;
for (var i = table.length; i < ret; i++) {
table[i] = null;
}
return ret;
},
// The code path for creating textures, buffers, framebuffers and other
// objects the same (and not in fast path), so we merge the functions
// together.
// 'createFunction' refers to the WebGL context function name to do the actual
// creation, 'objectTable' points to the GL object table where to populate the
// created objects, and 'functionName' carries the name of the caller for
// debug information.
genObject: (n, buffers, createFunction, objectTable
#if GL_ASSERTIONS
, functionName
#endif
) => {
for (var i = 0; i < n; i++) {
var buffer = GLctx[createFunction]();
var id = buffer && GL.getNewId(objectTable);
if (buffer) {
buffer.name = id;
objectTable[id] = buffer;
} else {
GL.recordError(0x502 /* GL_INVALID_OPERATION */);
#if GL_ASSERTIONS
err(`GL_INVALID_OPERATION in ${functionName}: GLctx.${createFunction} returned null - most likely GL context is lost!`);
#endif
}
{{{ makeSetValue('buffers', 'i*4', 'id', 'i32') }}};
}
},
#if FULL_ES2 || LEGACY_GL_EMULATION
// When user GL code wants to render from client-side memory, we need to
// upload the vertex data to a temp VBO for rendering. Maintain a set of
// temp VBOs that are created-on-demand to appropriate sizes, and never
// destroyed. Also, for best performance the VBOs are double-buffered, i.e.
// every second frame we switch the set of VBOs we upload to, so that
// rendering from the previous frame is not disturbed by uploading from new
// data to it, which could cause a GPU-CPU pipeline stall.
// Note that index buffers are not double-buffered (at the moment) in this
// manner.
MAX_TEMP_BUFFER_SIZE: {{{ GL_MAX_TEMP_BUFFER_SIZE }}},
// Maximum number of temp VBOs of one size to maintain, after that we start
// reusing old ones, which is safe but can give a performance impact. If
// CPU-GPU stalls are a problem, increasing this might help.
numTempVertexBuffersPerSize: 64, // (const)
// Precompute a lookup table for the function ceil(log2(x)), i.e. how many
// bits are needed to represent x, or, if x was rounded up to next pow2,
// which index is the single '1' bit at?
// Then log2ceilLookup[x] returns ceil(log2(x)).
log2ceilLookup: (i) => 32 - Math.clz32(i === 0 ? 0 : i - 1),
generateTempBuffers: (quads, context) => {
var largestIndex = GL.log2ceilLookup(GL.MAX_TEMP_BUFFER_SIZE);
context.tempVertexBufferCounters1 = [];
context.tempVertexBufferCounters2 = [];
context.tempVertexBufferCounters1.length = context.tempVertexBufferCounters2.length = largestIndex+1;
context.tempVertexBuffers1 = [];
context.tempVertexBuffers2 = [];
context.tempVertexBuffers1.length = context.tempVertexBuffers2.length = largestIndex+1;
context.tempIndexBuffers = [];
context.tempIndexBuffers.length = largestIndex+1;
for (var i = 0; i <= largestIndex; ++i) {
context.tempIndexBuffers[i] = null; // Created on-demand
context.tempVertexBufferCounters1[i] = context.tempVertexBufferCounters2[i] = 0;
var ringbufferLength = GL.numTempVertexBuffersPerSize;
context.tempVertexBuffers1[i] = [];
context.tempVertexBuffers2[i] = [];
var ringbuffer1 = context.tempVertexBuffers1[i];
var ringbuffer2 = context.tempVertexBuffers2[i];
ringbuffer1.length = ringbuffer2.length = ringbufferLength;
for (var j = 0; j < ringbufferLength; ++j) {
ringbuffer1[j] = ringbuffer2[j] = null; // Created on-demand
}
}
if (quads) {
// GL_QUAD indexes can be precalculated
context.tempQuadIndexBuffer = GLctx.createBuffer();
context.GLctx.bindBuffer(0x8893 /*GL_ELEMENT_ARRAY_BUFFER*/, context.tempQuadIndexBuffer);
var numIndexes = GL.MAX_TEMP_BUFFER_SIZE >> 1;
var quadIndexes = new Uint16Array(numIndexes);
var i = 0, v = 0;
while (1) {
quadIndexes[i++] = v;
if (i >= numIndexes) break;
quadIndexes[i++] = v+1;
if (i >= numIndexes) break;
quadIndexes[i++] = v+2;
if (i >= numIndexes) break;
quadIndexes[i++] = v;
if (i >= numIndexes) break;
quadIndexes[i++] = v+2;
if (i >= numIndexes) break;
quadIndexes[i++] = v+3;
if (i >= numIndexes) break;
v += 4;
}
context.GLctx.bufferData(0x8893 /*GL_ELEMENT_ARRAY_BUFFER*/, quadIndexes, 0x88E4 /*GL_STATIC_DRAW*/);
context.GLctx.bindBuffer(0x8893 /*GL_ELEMENT_ARRAY_BUFFER*/, null);
}
},
getTempVertexBuffer: (sizeBytes) => {
var idx = GL.log2ceilLookup(sizeBytes);
var ringbuffer = GL.currentContext.tempVertexBuffers1[idx];
var nextFreeBufferIndex = GL.currentContext.tempVertexBufferCounters1[idx];
GL.currentContext.tempVertexBufferCounters1[idx] = (GL.currentContext.tempVertexBufferCounters1[idx]+1) & (GL.numTempVertexBuffersPerSize-1);
var vbo = ringbuffer[nextFreeBufferIndex];
if (vbo) {
return vbo;
}
var prevVBO = GLctx.getParameter(0x8894 /*GL_ARRAY_BUFFER_BINDING*/);
ringbuffer[nextFreeBufferIndex] = GLctx.createBuffer();
GLctx.bindBuffer(0x8892 /*GL_ARRAY_BUFFER*/, ringbuffer[nextFreeBufferIndex]);
GLctx.bufferData(0x8892 /*GL_ARRAY_BUFFER*/, 1 << idx, 0x88E8 /*GL_DYNAMIC_DRAW*/);
GLctx.bindBuffer(0x8892 /*GL_ARRAY_BUFFER*/, prevVBO);
return ringbuffer[nextFreeBufferIndex];
},
getTempIndexBuffer: (sizeBytes) => {
var idx = GL.log2ceilLookup(sizeBytes);
var ibo = GL.currentContext.tempIndexBuffers[idx];
if (ibo) {
return ibo;
}
var prevIBO = GLctx.getParameter(0x8895 /*ELEMENT_ARRAY_BUFFER_BINDING*/);
GL.currentContext.tempIndexBuffers[idx] = GLctx.createBuffer();
GLctx.bindBuffer(0x8893 /*GL_ELEMENT_ARRAY_BUFFER*/, GL.currentContext.tempIndexBuffers[idx]);
GLctx.bufferData(0x8893 /*GL_ELEMENT_ARRAY_BUFFER*/, 1 << idx, 0x88E8 /*GL_DYNAMIC_DRAW*/);
GLctx.bindBuffer(0x8893 /*GL_ELEMENT_ARRAY_BUFFER*/, prevIBO);
return GL.currentContext.tempIndexBuffers[idx];
},
// Called at start of each new WebGL rendering frame. This swaps the
// doublebuffered temp VB memory pointers, so that every second frame
// utilizes different set of temp buffers. The aim is to keep the set of
// buffers being rendered, and the set of buffers being updated disjoint.
newRenderingFrameStarted: () => {
if (!GL.currentContext) {
return;
}
var vb = GL.currentContext.tempVertexBuffers1;
GL.currentContext.tempVertexBuffers1 = GL.currentContext.tempVertexBuffers2;
GL.currentContext.tempVertexBuffers2 = vb;
vb = GL.currentContext.tempVertexBufferCounters1;
GL.currentContext.tempVertexBufferCounters1 = GL.currentContext.tempVertexBufferCounters2;
GL.currentContext.tempVertexBufferCounters2 = vb;
var largestIndex = GL.log2ceilLookup(GL.MAX_TEMP_BUFFER_SIZE);
for (var i = 0; i <= largestIndex; ++i) {
GL.currentContext.tempVertexBufferCounters1[i] = 0;
}
},
#endif
getSource: (shader, count, string, length) => {
var source = '';
for (var i = 0; i < count; ++i) {
var len = length ? {{{ makeGetValue('length', 'i*' + POINTER_SIZE, '*') }}} : undefined;
source += UTF8ToString({{{ makeGetValue('string', 'i*' + POINTER_SIZE, '*') }}}, len);
}
#if LEGACY_GL_EMULATION
// Let's see if we need to enable the standard derivatives extension
var type = GLctx.getShaderParameter(GL.shaders[shader], 0x8B4F /* GL_SHADER_TYPE */);
if (type == 0x8B30 /* GL_FRAGMENT_SHADER */) {
if (GLEmulation.findToken(source, "dFdx") ||
GLEmulation.findToken(source, "dFdy") ||
GLEmulation.findToken(source, "fwidth")) {
source = "#extension GL_OES_standard_derivatives : enable\n" + source;
var extension = GLctx.getExtension("OES_standard_derivatives");
#if GL_DEBUG
if (!extension) {
dbg("Shader attempts to use the standard derivatives extension which is not available.");
}
#endif
}
}
#endif
return source;
},
#if GL_FFP_ONLY
enabledClientAttribIndices: [],
enableVertexAttribArray: (index) => {
if (!GL.enabledClientAttribIndices[index]) {
GL.enabledClientAttribIndices[index] = true;
GLctx.enableVertexAttribArray(index);
}
},
disableVertexAttribArray: (index) => {
if (GL.enabledClientAttribIndices[index]) {
GL.enabledClientAttribIndices[index] = false;
GLctx.disableVertexAttribArray(index);
}
},
#endif
#if FULL_ES2
calcBufLength: (size, type, stride, count) => {
if (stride > 0) {
return count * stride; // XXXvlad this is not exactly correct I don't think
}
var typeSize = GL.byteSizeByType[type - GL.byteSizeByTypeRoot];
return size * typeSize * count;
},
usedTempBuffers: [],
preDrawHandleClientVertexAttribBindings: (count) => {
GL.resetBufferBinding = false;
// TODO: initial pass to detect ranges we need to upload, might not need
// an upload per attrib
for (var i = 0; i < GL.currentContext.maxVertexAttribs; ++i) {
var cb = GL.currentContext.clientBuffers[i];
if (!cb.clientside || !cb.enabled) continue;
GL.resetBufferBinding = true;
var size = GL.calcBufLength(cb.size, cb.type, cb.stride, count);
var buf = GL.getTempVertexBuffer(size);
GLctx.bindBuffer(0x8892 /*GL_ARRAY_BUFFER*/, buf);
GLctx.bufferSubData(0x8892 /*GL_ARRAY_BUFFER*/,
0,
HEAPU8.subarray(cb.ptr, cb.ptr + size));
#if GL_ASSERTIONS
GL.validateVertexAttribPointer(cb.size, cb.type, cb.stride, 0);
#endif
cb.vertexAttribPointerAdaptor.call(GLctx, i, cb.size, cb.type, cb.normalized, cb.stride, 0);
}
},
postDrawHandleClientVertexAttribBindings: () => {
if (GL.resetBufferBinding) {
GLctx.bindBuffer(0x8892 /*GL_ARRAY_BUFFER*/, GL.buffers[GLctx.currentArrayBufferBinding]);
}
},
#endif
#if GL_ASSERTIONS
validateGLObjectID: (objectHandleArray, objectID, callerFunctionName, objectReadableType) => {
if (objectID != 0) {
if (objectHandleArray[objectID] === null) {
err(`${callerFunctionName} called with an already deleted ${objectReadableType} ID ${objectID}!`);
} else if (!(objectID in objectHandleArray)) {
err(`${callerFunctionName} called with a nonexisting ${objectReadableType} ID ${objectID}!`);
}
}
},
// Validates that user obeys GL spec #6.4: http://www.khronos.org/registry/webgl/specs/latest/1.0/#6.4
validateVertexAttribPointer: (dimension, dataType, stride, offset) => {
var sizeBytes = 1;
switch (dataType) {
case 0x1400 /* GL_BYTE */:
case 0x1401 /* GL_UNSIGNED_BYTE */:
sizeBytes = 1;
break;
case 0x1402 /* GL_SHORT */:
case 0x1403 /* GL_UNSIGNED_SHORT */:
sizeBytes = 2;
break;
case 0x1404 /* GL_INT */:
case 0x1405 /* GL_UNSIGNED_INT */:
case 0x1406 /* GL_FLOAT */:
sizeBytes = 4;
break;
case 0x140A /* GL_DOUBLE */:
sizeBytes = 8;
break;
default:
#if MAX_WEBGL_VERSION >= 2
if ({{{ isCurrentContextWebGL2() }}}) {
if (dataType == 0x8368 /* GL_UNSIGNED_INT_2_10_10_10_REV */ || dataType == 0x8D9F /* GL_INT_2_10_10_10_REV */) {
sizeBytes = 4;
break;
} else if (dataType == 0x140B /* GL_HALF_FLOAT */) {
sizeBytes = 2;
break;
} else {
// else fall through
}
}
#endif
err(`Invalid vertex attribute data type GLenum ${dataType} passed to GL function!`);
}
if (dimension == 0x80E1 /* GL_BGRA */) {
err('WebGL does not support size=GL_BGRA in a call to glVertexAttribPointer! Please use size=4 and type=GL_UNSIGNED_BYTE instead!');
} else if (dimension < 1 || dimension > 4) {
err(`Invalid dimension=${dimension} in call to glVertexAttribPointer, must be 1,2,3 or 4.`);
}
if (stride < 0 || stride > 255) {
err(`Invalid stride=${stride} in call to glVertexAttribPointer. Note that maximum supported stride in WebGL is 255!`);
}
if (offset % sizeBytes != 0) {
err(`GL spec section 6.4 error: vertex attribute data offset of ${offset} bytes should have been a multiple of the data type size that was used: GLenum ${dataType} has size of ${sizeBytes} bytes!`);
}
if (stride % sizeBytes != 0) {
err(`GL spec section 6.4 error: vertex attribute data stride of ${stride} bytes should have been a multiple of the data type size that was used: GLenum ${dataType} has size of ${sizeBytes} bytes!`);
}
},
#endif
#if TRACE_WEBGL_CALLS
hookWebGLFunction: (f, glCtx) => {
var orig = glCtx[f];
var contextHandle = glCtx.canvas.GLctxObject.handle;
glCtx[f] = function(...args) {
var ret = orig.apply(this, args);
// Some GL functions take a view of the entire linear memory. Replace
// such arguments with the string 'HEAP' to avoid serializing all of
// memory.
for (var i in args) {
if (ArrayBuffer.isView(args[i]) && args[i].byteLength === HEAPU8.byteLength) {
args[i] = 'HEAP';
}
}
#if PTHREADS
err(`[Thread ${_pthread_self()}, GL ctx: ${contextHandle}]: ${f}(${args}) -> ${ret}`);
#else
err(`[ctx: ${contextHandle}]: ${f}(${args}) -> ${ret}`);
#endif
return ret;
};
},
hookWebGL: function(glCtx) {
glCtx ??= this.detectWebGLContext();
if (!glCtx) return;
if (!((typeof WebGLRenderingContext != 'undefined' && glCtx instanceof WebGLRenderingContext)
|| (typeof WebGL2RenderingContext != 'undefined' && glCtx instanceof WebGL2RenderingContext))) {
return;
}
if (glCtx.webGlTracerAlreadyHooked) return;
glCtx.webGlTracerAlreadyHooked = true;
for (var f in glCtx) {
if (typeof glCtx[f] == 'function') {
this.hookWebGLFunction(f, glCtx);
}
}
},
#endif
// Returns the context handle to the new context.
createContext: (/** @type {HTMLCanvasElement} */ canvas, webGLContextAttributes) => {
#if OFFSCREEN_FRAMEBUFFER
// In proxied operation mode, rAF()/setTimeout() functions do not delimit
// frame boundaries, so can't have WebGL implementation try to detect when
// it's ok to discard contents of the rendered backbuffer.
if (webGLContextAttributes.renderViaOffscreenBackBuffer) webGLContextAttributes['preserveDrawingBuffer'] = true;
#endif
#if GL_TESTING
webGLContextAttributes['preserveDrawingBuffer'] = true;
#endif
#if MAX_WEBGL_VERSION >= 2 && MIN_CHROME_VERSION <= 57
// BUG: Workaround Chrome WebGL 2 issue: the first shipped versions of
// WebGL 2 in Chrome 57 did not actually implement the new garbage free
// WebGL 2 entry points that take an offset and a length to an existing
// heap (instead of having to create a completely new heap view). In
// Chrome the entry points only were added in to Chrome 58 and newer. For
// Chrome 57 (and older), disable WebGL 2 support altogether.
function getChromeVersion() {
var chromeVersion = navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./);
if (chromeVersion) return chromeVersion[2]|0;
// If not chrome, fall through to return undefined. (undefined <= integer will yield false)
}
#endif
#if GL_DEBUG
var errorInfo = '?';
function onContextCreationError(event) {
errorInfo = event.statusMessage || errorInfo;
}
canvas.addEventListener('webglcontextcreationerror', onContextCreationError, false);
#endif
#if GL_PREINITIALIZED_CONTEXT
// If WebGL context has already been preinitialized for the page on the JS
// side, reuse that context instead. This is useful for example when the
// main page precompiles shaders for the application, in which case the
// WebGL context is created already before any Emscripten compiled code
// has been downloaded.
if (Module['preinitializedWebGLContext']) {
var ctx = Module['preinitializedWebGLContext'];
#if MAX_WEBGL_VERSION >= 2
// The ctx object may not be of a known class (e.g. it may be a debug
// wrapper), so we ask it for its version rather than use instanceof.
webGLContextAttributes.majorVersion = Number(ctx.getParameter(ctx.VERSION).match(/^WebGL (\d+).\d+/)[1]);
#else
webGLContextAttributes.majorVersion = 1;
#endif
} else {
#endif
#if MIN_SAFARI_VERSION != TARGET_NOT_SUPPORTED && GL_WORKAROUND_SAFARI_GETCONTEXT_BUG
// BUG: Workaround Safari WebGL issue: After successfully acquiring WebGL
// context on a canvas, calling .getContext() will always return that
// context independent of which 'webgl' or 'webgl2'
// context version was passed. See:
// https://bugs.webkit.org/show_bug.cgi?id=222758
// and:
// https://github.com/emscripten-core/emscripten/issues/13295.
// TODO: Once the bug is fixed and shipped in Safari, adjust the Safari
// version field in above check.
if (!canvas.getContextSafariWebGL2Fixed) {
canvas.getContextSafariWebGL2Fixed = canvas.getContext;
/** @type {function(this:HTMLCanvasElement, string, (Object|null)=): (Object|null)} */
function fixedGetContext(ver, attrs) {
var gl = canvas.getContextSafariWebGL2Fixed(ver, attrs);
return ((ver == 'webgl') == (gl instanceof WebGLRenderingContext)) ? gl : null;
}
canvas.getContext = fixedGetContext;
}
#endif
#if MIN_WEBGL_VERSION >= 2
var ctx = canvas.getContext("webgl2", webGLContextAttributes);
#else
var ctx =
#if MAX_WEBGL_VERSION >= 2
(webGLContextAttributes.majorVersion > 1)
?
#if MIN_CHROME_VERSION <= 57
!(getChromeVersion() <= 57) && canvas.getContext("webgl2", webGLContextAttributes)
#else
canvas.getContext("webgl2", webGLContextAttributes)
#endif
:
#endif
(canvas.getContext("webgl", webGLContextAttributes)
// https://caniuse.com/#feat=webgl
#if MIN_FIREFOX_VERSION <= 23 || MIN_CHROME_VERSION <= 32 || MIN_SAFARI_VERSION <= 70101
|| canvas.getContext("experimental-webgl", webGLContextAttributes)
#endif
);
#endif // MAX_WEBGL_VERSION >= 2
#if GL_PREINITIALIZED_CONTEXT
}
#endif
#if GL_DEBUG
canvas.removeEventListener('webglcontextcreationerror', onContextCreationError, false);
if (!ctx) {
dbg('Could not create canvas: ' + [errorInfo, JSON.stringify(webGLContextAttributes)]);
return 0;
}
#else
if (!ctx) return 0;
#endif
var handle = GL.registerContext(ctx, webGLContextAttributes);
#if TRACE_WEBGL_CALLS
GL.hookWebGL(ctx);
#endif
#if GL_DISABLE_HALF_FLOAT_EXTENSION_IF_BROKEN
const disableHalfFloatExtensionIfBroken = (ctx) => {
var t = ctx.createTexture();
ctx.bindTexture(0xDE1/*GL_TEXTURE_2D*/, t);
for (var i = 0; i < 8 && ctx.getError(); ++i) /*no-op*/;
var ext = ctx.getExtension('OES_texture_half_float');
if (!ext) return; // no half-float extension - nothing needed to fix.
// Bug on Safari on iOS and macOS: texImage2D() and texSubImage2D() do
// not allow uploading pixel data to half float textures, rendering them
// useless.
// See https://bugs.webkit.org/show_bug.cgi?id=183321, https://bugs.webkit.org/show_bug.cgi?id=169999,
// https://stackoverflow.com/questions/54248633/cannot-create-half-float-oes-texture-from-uint16array-on-ipad
ctx.texImage2D(0xDE1/*GL_TEXTURE_2D*/, 0, 0x1908/*GL_RGBA*/, 1, 1, 0, 0x1908/*GL_RGBA*/, 0x8d61/*HALF_FLOAT_OES*/, new Uint16Array(4));
var broken = ctx.getError();
ctx.bindTexture(0xDE1/*GL_TEXTURE_2D*/, null);
ctx.deleteTexture(t);
if (broken) {
ctx.realGetSupportedExtensions = ctx.getSupportedExtensions;
ctx.getSupportedExtensions = function() {
#if GL_ASSERTIONS
warnOnce('Removed broken support for half-float textures. See e.g. https://bugs.webkit.org/show_bug.cgi?id=183321');
#endif
// .getSupportedExtensions() can return null if context is lost, so
// coerce to empty array.
return (this.realGetSupportedExtensions() || []).filter((ext) => !ext.includes('texture_half_float'));
}
}
}
disableHalfFloatExtensionIfBroken(ctx);
#endif
return handle;
},
#if OFFSCREEN_FRAMEBUFFER
enableOffscreenFramebufferAttributes: (webGLContextAttributes) => {
webGLContextAttributes.renderViaOffscreenBackBuffer = true;
webGLContextAttributes.preserveDrawingBuffer = true;
},
// If WebGL is being proxied from a pthread to the main thread, we can't
// directly render to the WebGL default back buffer because of WebGL's
// implicit swap behavior. Therefore in such modes, create an offscreen
// render target surface to which rendering is performed to, and finally
// flipped to the main screen.
createOffscreenFramebuffer: (context) => {
var gl = context.GLctx;
// Create FBO
var fbo = gl.createFramebuffer();
gl.bindFramebuffer(0x8D40 /*GL_FRAMEBUFFER*/, fbo);
context.defaultFbo = fbo;
#if MAX_WEBGL_VERSION >= 2
context.defaultFboForbidBlitFramebuffer = false;
if (gl.getContextAttributes().antialias) {
context.defaultFboForbidBlitFramebuffer = true;
}
#if MIN_FIREFOX_VERSION < 67
else {
// The WebGL 2 blit path doesn't work in Firefox < 67 (except in fullscreen).
// https://bugzilla.mozilla.org/show_bug.cgi?id=1523030
var firefoxMatch = navigator.userAgent.toLowerCase().match(/firefox\/(\d\d)/);
if (firefoxMatch != null) {
var firefoxVersion = firefoxMatch[1];
context.defaultFboForbidBlitFramebuffer = firefoxVersion < 67;
}
}
#endif
#endif
// Create render targets to the FBO
context.defaultColorTarget = gl.createTexture();
context.defaultDepthTarget = gl.createRenderbuffer();
// Size them up correctly (use the same mechanism when resizing on demand)
GL.resizeOffscreenFramebuffer(context);
gl.bindTexture(0xDE1 /*GL_TEXTURE_2D*/, context.defaultColorTarget);
gl.texParameteri(0xDE1 /*GL_TEXTURE_2D*/, 0x2801 /*GL_TEXTURE_MIN_FILTER*/, 0x2600 /*GL_NEAREST*/);
gl.texParameteri(0xDE1 /*GL_TEXTURE_2D*/, 0x2800 /*GL_TEXTURE_MAG_FILTER*/, 0x2600 /*GL_NEAREST*/);
gl.texParameteri(0xDE1 /*GL_TEXTURE_2D*/, 0x2802 /*GL_TEXTURE_WRAP_S*/, 0x812F /*GL_CLAMP_TO_EDGE*/);
gl.texParameteri(0xDE1 /*GL_TEXTURE_2D*/, 0x2803 /*GL_TEXTURE_WRAP_T*/, 0x812F /*GL_CLAMP_TO_EDGE*/);
gl.texImage2D(0xDE1 /*GL_TEXTURE_2D*/, 0, 0x1908 /*GL_RGBA*/, gl.canvas.width, gl.canvas.height, 0, 0x1908 /*GL_RGBA*/, 0x1401 /*GL_UNSIGNED_BYTE*/, null);
gl.framebufferTexture2D(0x8D40 /*GL_FRAMEBUFFER*/, 0x8CE0 /*GL_COLOR_ATTACHMENT0*/, 0xDE1 /*GL_TEXTURE_2D*/, context.defaultColorTarget, 0);
gl.bindTexture(0xDE1 /*GL_TEXTURE_2D*/, null);
// Create depth render target to the FBO
var depthTarget = gl.createRenderbuffer();
gl.bindRenderbuffer(0x8D41 /*GL_RENDERBUFFER*/, context.defaultDepthTarget);
gl.renderbufferStorage(0x8D41 /*GL_RENDERBUFFER*/, 0x81A5 /*GL_DEPTH_COMPONENT16*/, gl.canvas.width, gl.canvas.height);
gl.framebufferRenderbuffer(0x8D40 /*GL_FRAMEBUFFER*/, 0x8D00 /*GL_DEPTH_ATTACHMENT*/, 0x8D41 /*GL_RENDERBUFFER*/, context.defaultDepthTarget);
gl.bindRenderbuffer(0x8D41 /*GL_RENDERBUFFER*/, null);
// Create blitter
var vertices = [
-1, -1,
-1, 1,
1, -1,
1, 1
];
var vb = gl.createBuffer();
gl.bindBuffer(0x8892 /*GL_ARRAY_BUFFER*/, vb);
gl.bufferData(0x8892 /*GL_ARRAY_BUFFER*/, new Float32Array(vertices), 0x88E4 /*GL_STATIC_DRAW*/);
gl.bindBuffer(0x8892 /*GL_ARRAY_BUFFER*/, null);
context.blitVB = vb;
var vsCode =
'attribute vec2 pos;' +
'varying lowp vec2 tex;' +
'void main() { tex = pos * 0.5 + vec2(0.5,0.5); gl_Position = vec4(pos, 0.0, 1.0); }';
var vs = gl.createShader(0x8B31 /*GL_VERTEX_SHADER*/);
gl.shaderSource(vs, vsCode);
gl.compileShader(vs);
var fsCode =
'varying lowp vec2 tex;' +
'uniform sampler2D sampler;' +
'void main() { gl_FragColor = texture2D(sampler, tex); }';
var fs = gl.createShader(0x8B30 /*GL_FRAGMENT_SHADER*/);
gl.shaderSource(fs, fsCode);
gl.compileShader(fs);
var blitProgram = gl.createProgram();
gl.attachShader(blitProgram, vs);
gl.attachShader(blitProgram, fs);
gl.linkProgram(blitProgram);
context.blitProgram = blitProgram;
context.blitPosLoc = gl.getAttribLocation(blitProgram, "pos");
gl.useProgram(blitProgram);
gl.uniform1i(gl.getUniformLocation(blitProgram, "sampler"), 0);
gl.useProgram(null);
context.defaultVao = undefined;
if (gl.createVertexArray) {
context.defaultVao = gl.createVertexArray();
gl.bindVertexArray(context.defaultVao);
gl.enableVertexAttribArray(context.blitPosLoc);
gl.bindVertexArray(null);
}
},
resizeOffscreenFramebuffer: (context) => {
var gl = context.GLctx;
// Resize color buffer
if (context.defaultColorTarget) {
var prevTextureBinding = gl.getParameter(0x8069 /*GL_TEXTURE_BINDING_2D*/);
gl.bindTexture(0xDE1 /*GL_TEXTURE_2D*/, context.defaultColorTarget);
gl.texImage2D(0xDE1 /*GL_TEXTURE_2D*/, 0, 0x1908 /*GL_RGBA*/, gl.drawingBufferWidth, gl.drawingBufferHeight, 0, 0x1908 /*GL_RGBA*/, 0x1401 /*GL_UNSIGNED_BYTE*/, null);
gl.bindTexture(0xDE1 /*GL_TEXTURE_2D*/, prevTextureBinding);
}
// Resize depth buffer
if (context.defaultDepthTarget) {
var prevRenderBufferBinding = gl.getParameter(0x8CA7 /*GL_RENDERBUFFER_BINDING*/);
gl.bindRenderbuffer(0x8D41 /*GL_RENDERBUFFER*/, context.defaultDepthTarget);
gl.renderbufferStorage(0x8D41 /*GL_RENDERBUFFER*/, 0x81A5 /*GL_DEPTH_COMPONENT16*/, gl.drawingBufferWidth, gl.drawingBufferHeight); // TODO: Read context creation parameters for what type of depth and stencil to use
gl.bindRenderbuffer(0x8D41 /*GL_RENDERBUFFER*/, prevRenderBufferBinding);
}
},
// Renders the contents of the offscreen render target onto the visible screen.
blitOffscreenFramebuffer: (context) => {
var gl = context.GLctx;
var prevScissorTest = gl.getParameter(0xC11 /*GL_SCISSOR_TEST*/);
if (prevScissorTest) gl.disable(0xC11 /*GL_SCISSOR_TEST*/);
var prevFbo = gl.getParameter(0x8CA6 /*GL_FRAMEBUFFER_BINDING*/);
#if MAX_WEBGL_VERSION >= 2
if (gl.blitFramebuffer && !context.defaultFboForbidBlitFramebuffer) {
gl.bindFramebuffer(0x8CA8 /*GL_READ_FRAMEBUFFER*/, context.defaultFbo);
gl.bindFramebuffer(0x8CA9 /*GL_DRAW_FRAMEBUFFER*/, null);
gl.blitFramebuffer(0, 0, gl.canvas.width, gl.canvas.height,
0, 0, gl.canvas.width, gl.canvas.height,
0x4000 /*GL_COLOR_BUFFER_BIT*/, 0x2600/*GL_NEAREST*/);
}
else
#endif
{
gl.bindFramebuffer(0x8D40 /*GL_FRAMEBUFFER*/, null);
var prevProgram = gl.getParameter(0x8B8D /*GL_CURRENT_PROGRAM*/);
gl.useProgram(context.blitProgram);