File: webgl_rendering_context_base.h

package info (click to toggle)
chromium 138.0.7204.183-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,908 kB
  • sloc: cpp: 34,937,088; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (2043 lines) | stat: -rw-r--r-- 83,878 bytes parent folder | download | duplicates (2)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
/*
 * Copyright (C) 2009 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_WEBGL_WEBGL_RENDERING_CONTEXT_BASE_H_
#define THIRD_PARTY_BLINK_RENDERER_MODULES_WEBGL_WEBGL_RENDERING_CONTEXT_BASE_H_

#include <array>
#include <memory>
#include <optional>

#include "base/check_op.h"
#include "base/memory/raw_ptr_exclusion.h"
#include "base/memory/scoped_refptr.h"
#include "base/numerics/checked_math.h"
#include "device/vr/public/mojom/vr_service.mojom-blink-forward.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/web_graphics_context_3d_provider.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h"
#include "third_party/blink/renderer/bindings/core/v8/script_value.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_webgl_context_attributes.h"
#include "third_party/blink/renderer/core/html/canvas/canvas_context_creation_attributes_core.h"
#include "third_party/blink/renderer/core/html/canvas/canvas_rendering_context.h"
#include "third_party/blink/renderer/core/html/canvas/ukm_parameters.h"
#include "third_party/blink/renderer/core/layout/content_change_type.h"
#include "third_party/blink/renderer/core/typed_arrays/array_buffer_view_helpers.h"
#include "third_party/blink/renderer/core/typed_arrays/dom_typed_array.h"
#include "third_party/blink/renderer/modules/webgl/webgl_context_object_support.h"
#include "third_party/blink/renderer/modules/webgl/webgl_texture.h"
#include "third_party/blink/renderer/modules/webgl/webgl_uniform_location.h"
#include "third_party/blink/renderer/modules/webgl/webgl_vertex_array_object_base.h"
#include "third_party/blink/renderer/platform/bindings/name_client.h"
#include "third_party/blink/renderer/platform/graphics/gpu/drawing_buffer.h"
#include "third_party/blink/renderer/platform/graphics/gpu/extensions_3d_util.h"
#include "third_party/blink/renderer/platform/graphics/gpu/webgl_image_conversion.h"
#include "third_party/blink/renderer/platform/heap/collection_support/heap_hash_map.h"
#include "third_party/blink/renderer/platform/heap/collection_support/heap_vector.h"
#include "third_party/blink/renderer/platform/scheduler/public/frame_or_worker_scheduler.h"
#include "third_party/blink/renderer/platform/timer.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#include "third_party/skia/include/core/SkData.h"

namespace cc {
class Layer;
}

namespace media {
class PaintCanvasVideoRenderer;
}

namespace blink {

class AcceleratedStaticBitmapImage;
class CanvasResourceProvider;
class EXTDisjointTimerQuery;
class EXTDisjointTimerQueryWebGL2;
class Element;
class ExceptionState;
class HTMLCanvasElement;
class HTMLImageElement;
class HTMLVideoElement;
class ImageBitmap;
class ImageData;
class OESVertexArrayObject;
class ScriptState;
class V8PredefinedColorSpace;
class V8UnionHTMLCanvasElementOrOffscreenCanvas;
class VideoFrame;
class WebGLActiveInfo;
class WebGLBuffer;
class WebGLCompressedTextureASTC;
class WebGLCompressedTextureETC;
class WebGLCompressedTextureETC1;
class WebGLCompressedTexturePVRTC;
class WebGLCompressedTextureS3TC;
class WebGLCompressedTextureS3TCsRGB;
class WebGLDebugShaders;
class WebGLDrawBuffers;
class WebGLExtension;
class WebGLFramebuffer;
class WebGLObject;
class WebGLProgram;
class WebGLRenderbuffer;
class WebGLRenderingContextBase;
class WebGLShader;
class WebGLShaderPrecisionFormat;
class WebGLVertexArrayObjectBase;
class XRSystem;

using GLenumHashSet = HashSet<GLenum, AlreadyHashedWithZeroKeyTraits>;

// This class uses the color mask to prevent drawing to the alpha channel, if
// the DrawingBuffer requires RGB emulation.
class ScopedRGBEmulationColorMask {
  STACK_ALLOCATED();

 public:
  ScopedRGBEmulationColorMask(WebGLRenderingContextBase*,
                              GLboolean* color_mask,
                              DrawingBuffer*);
  ~ScopedRGBEmulationColorMask();

 private:
  WebGLRenderingContextBase* context_;
  std::array<GLboolean, 4> color_mask_;
  const bool requires_emulation_;
};

class MODULES_EXPORT WebGLRenderingContextBase
    : public WebGLContextObjectSupport,
      public CanvasRenderingContext,
      public DrawingBuffer::Client {
 public:
  WebGLRenderingContextBase(const WebGLRenderingContextBase&) = delete;
  WebGLRenderingContextBase& operator=(const WebGLRenderingContextBase&) =
      delete;

  ~WebGLRenderingContextBase() override;

  HTMLCanvasElement* canvas() const;

  const UkmParameters GetUkmParameters() const {
    return Host()->GetUkmParameters();
  }

  virtual String ContextName() const = 0;
  virtual void RegisterContextExtensions() = 0;

  virtual void InitializeNewContext();

  static unsigned GetWebGLVersion(const CanvasRenderingContext*);

  static std::unique_ptr<WebGraphicsContext3DProvider>
  CreateWebGraphicsContext3DProvider(CanvasRenderingContextHost*,
                                     const CanvasContextCreationAttributesCore&,
                                     Platform::ContextType context_type,
                                     Platform::GraphicsInfo* graphics_info);
  static void ForceNextWebGLContextCreationToFail();

  Platform::ContextType ContextType() const { return context_type_; }

  int drawingBufferWidth() const;
  int drawingBufferHeight() const;
  GLenum drawingBufferFormat() const;
  V8PredefinedColorSpace drawingBufferColorSpace() const;
  void setDrawingBufferColorSpace(const V8PredefinedColorSpace& color_space,
                                  ExceptionState&);

  V8PredefinedColorSpace unpackColorSpace() const;
  void setUnpackColorSpace(const V8PredefinedColorSpace& color_space,
                           ExceptionState&);

  void activeTexture(GLenum texture);
  void attachShader(WebGLProgram*, WebGLShader*);
  void bindAttribLocation(WebGLProgram*, GLuint index, const String& name);
  void bindBuffer(GLenum target, WebGLBuffer* buffer);
  virtual void bindFramebuffer(GLenum target, WebGLFramebuffer*);
  void bindRenderbuffer(GLenum target, WebGLRenderbuffer*);
  void bindTexture(GLenum target, WebGLTexture*);
  void blendColor(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
  void blendEquation(GLenum mode);
  void blendEquationSeparate(GLenum mode_rgb, GLenum mode_alpha);
  void blendFunc(GLenum sfactor, GLenum dfactor);
  void blendFuncSeparate(GLenum src_rgb,
                         GLenum dst_rgb,
                         GLenum src_alpha,
                         GLenum dst_alpha);

  void bufferData(GLenum target, int64_t size, GLenum usage);
  void bufferData(GLenum target, DOMArrayBufferBase* data, GLenum usage);
  void bufferData(GLenum target,
                  MaybeShared<DOMArrayBufferView> data,
                  GLenum usage);
  void bufferSubData(GLenum target,
                     int64_t offset,
                     base::span<const uint8_t> data);

  GLenum checkFramebufferStatus(GLenum target);
  void clear(GLbitfield mask);
  void clearColor(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
  void clearDepth(GLfloat);
  void clearStencil(GLint);
  void colorMask(GLboolean red,
                 GLboolean green,
                 GLboolean blue,
                 GLboolean alpha);
  void compileShader(WebGLShader*);

  void compressedTexImage2D(GLenum target,
                            GLint level,
                            GLenum internalformat,
                            GLsizei width,
                            GLsizei height,
                            GLint border,
                            MaybeShared<DOMArrayBufferView> data);
  void compressedTexSubImage2D(GLenum target,
                               GLint level,
                               GLint xoffset,
                               GLint yoffset,
                               GLsizei width,
                               GLsizei height,
                               GLenum format,
                               MaybeShared<DOMArrayBufferView> data);

  void copyTexImage2D(GLenum target,
                      GLint level,
                      GLenum internalformat,
                      GLint x,
                      GLint y,
                      GLsizei width,
                      GLsizei height,
                      GLint border);
  void copyTexSubImage2D(GLenum target,
                         GLint level,
                         GLint xoffset,
                         GLint yoffset,
                         GLint x,
                         GLint y,
                         GLsizei width,
                         GLsizei height);

  WebGLBuffer* createBuffer();
  WebGLFramebuffer* createFramebuffer();
  WebGLProgram* createProgram();
  WebGLRenderbuffer* createRenderbuffer();
  WebGLShader* createShader(GLenum type);
  WebGLTexture* createTexture();

  void cullFace(GLenum mode);

  void deleteBuffer(WebGLBuffer*);
  virtual void deleteFramebuffer(WebGLFramebuffer*);
  void deleteProgram(WebGLProgram*);
  void deleteRenderbuffer(WebGLRenderbuffer*);
  void deleteShader(WebGLShader*);
  void deleteTexture(WebGLTexture*);

  void depthFunc(GLenum);
  void depthMask(GLboolean);
  void depthRange(GLfloat z_near, GLfloat z_far);
  void detachShader(WebGLProgram*, WebGLShader*);
  void disable(GLenum cap);
  void disableVertexAttribArray(GLuint index);

  void drawArrays(GLenum mode, GLint first, GLsizei count);

  void drawElements(GLenum mode, GLsizei count, GLenum type, int64_t offset);

  void DrawArraysInstancedANGLE(GLenum mode,
                                GLint first,
                                GLsizei count,
                                GLsizei primcount);
  void DrawElementsInstancedANGLE(GLenum mode,
                                  GLsizei count,
                                  GLenum type,
                                  int64_t offset,
                                  GLsizei primcount);

  void enable(GLenum cap);
  void enableVertexAttribArray(GLuint index);
  void finish();
  void flush();
  void framebufferRenderbuffer(GLenum target,
                               GLenum attachment,
                               GLenum renderbuffertarget,
                               WebGLRenderbuffer*);
  void framebufferTexture2D(GLenum target,
                            GLenum attachment,
                            GLenum textarget,
                            WebGLTexture*,
                            GLint level);
  void frontFace(GLenum mode);
  void generateMipmap(GLenum target);

  WebGLActiveInfo* getActiveAttrib(WebGLProgram*, GLuint index);
  WebGLActiveInfo* getActiveUniform(WebGLProgram*, GLuint index);
  bool getAttachedShaders(WebGLProgram*, HeapVector<Member<WebGLShader>>&);
  std::optional<HeapVector<Member<WebGLShader>>> getAttachedShaders(
      WebGLProgram*);
  GLint getAttribLocation(WebGLProgram*, const String& name);
  ScriptValue getBufferParameter(ScriptState*, GLenum target, GLenum pname);
  WebGLContextAttributes* getContextAttributes() const;
  GLenum getError();
  ScriptObject getExtension(ScriptState*, const String& name);
  virtual ScriptValue getFramebufferAttachmentParameter(ScriptState*,
                                                        GLenum target,
                                                        GLenum attachment,
                                                        GLenum pname);
  virtual ScriptValue getParameter(ScriptState*, GLenum pname);
  ScriptValue getProgramParameter(ScriptState*, WebGLProgram*, GLenum pname);
  String getProgramInfoLog(WebGLProgram*);
  ScriptValue getRenderbufferParameter(ScriptState*,
                                       GLenum target,
                                       GLenum pname);
  ScriptValue getShaderParameter(ScriptState*, WebGLShader*, GLenum pname);
  String getShaderInfoLog(WebGLShader*);
  WebGLShaderPrecisionFormat* getShaderPrecisionFormat(GLenum shader_type,
                                                       GLenum precision_type);
  String getShaderSource(WebGLShader*);
  std::optional<Vector<String>> getSupportedExtensions();
  virtual ScriptValue getTexParameter(ScriptState*,
                                      GLenum target,
                                      GLenum pname);
  ScriptValue getUniform(ScriptState*,
                         WebGLProgram*,
                         const WebGLUniformLocation*);
  WebGLUniformLocation* getUniformLocation(WebGLProgram*, const String&);
  ScriptValue getVertexAttrib(ScriptState*, GLuint index, GLenum pname);
  int64_t getVertexAttribOffset(GLuint index, GLenum pname);

  void hint(GLenum target, GLenum mode);
  bool isBuffer(WebGLBuffer*);
  bool isContextLost() const override;
  bool isEnabled(GLenum cap);
  bool isFramebuffer(WebGLFramebuffer*);
  bool isProgram(WebGLProgram*);
  bool isRenderbuffer(WebGLRenderbuffer*);
  bool isShader(WebGLShader*);
  bool isTexture(WebGLTexture*);

  void lineWidth(GLfloat);
  void linkProgram(WebGLProgram*);
  virtual void pixelStorei(GLenum pname, GLint param);
  void polygonOffset(GLfloat factor, GLfloat units);
  virtual void readPixels(GLint x,
                          GLint y,
                          GLsizei width,
                          GLsizei height,
                          GLenum format,
                          GLenum type,
                          MaybeShared<DOMArrayBufferView> pixels);
  void renderbufferStorage(GLenum target,
                           GLenum internalformat,
                           GLsizei width,
                           GLsizei height);
  void sampleCoverage(GLfloat value, GLboolean invert);
  void scissor(GLint x, GLint y, GLsizei width, GLsizei height);
  void shaderSource(WebGLShader*, const String&);
  void stencilFunc(GLenum func, GLint ref, GLuint mask);
  void stencilFuncSeparate(GLenum face, GLenum func, GLint ref, GLuint mask);
  void stencilMask(GLuint);
  void stencilMaskSeparate(GLenum face, GLuint mask);
  void stencilOp(GLenum fail, GLenum zfail, GLenum zpass);
  void stencilOpSeparate(GLenum face, GLenum fail, GLenum zfail, GLenum zpass);

  void texImage2D(GLenum target,
                  GLint level,
                  GLint internalformat,
                  GLsizei width,
                  GLsizei height,
                  GLint border,
                  GLenum format,
                  GLenum type,
                  MaybeShared<DOMArrayBufferView>);
  void texImage2D(GLenum target,
                  GLint level,
                  GLint internalformat,
                  GLenum format,
                  GLenum type,
                  ImageData*);
  void texImage2D(ScriptState*,
                  GLenum target,
                  GLint level,
                  GLint internalformat,
                  GLenum format,
                  GLenum type,
                  HTMLImageElement*,
                  ExceptionState&);
  void texImage2D(ScriptState*,
                  GLenum target,
                  GLint level,
                  GLint internalformat,
                  GLenum format,
                  GLenum type,
                  CanvasRenderingContextHost*,
                  ExceptionState&);
  void texImage2D(ScriptState*,
                  GLenum target,
                  GLint level,
                  GLint internalformat,
                  GLenum format,
                  GLenum type,
                  HTMLVideoElement*,
                  ExceptionState&);
  void texImage2D(ScriptState*,
                  GLenum target,
                  GLint level,
                  GLint internalformat,
                  GLenum format,
                  GLenum type,
                  VideoFrame*,
                  ExceptionState&);
  void texImage2D(GLenum target,
                  GLint level,
                  GLint internalformat,
                  GLenum format,
                  GLenum type,
                  ImageBitmap*,
                  ExceptionState&);

  void texElement2D(ScriptState* script_state,
                    GLenum target,
                    GLint level,
                    GLint internalformat,
                    GLenum format,
                    GLenum type,
                    Element* element,
                    ExceptionState& exception_state);

  void texParameterf(GLenum target, GLenum pname, GLfloat param);
  void texParameteri(GLenum target, GLenum pname, GLint param);

  void texSubImage2D(GLenum target,
                     GLint level,
                     GLint xoffset,
                     GLint yoffset,
                     GLsizei width,
                     GLsizei height,
                     GLenum format,
                     GLenum type,
                     MaybeShared<DOMArrayBufferView>);
  void texSubImage2D(GLenum target,
                     GLint level,
                     GLint xoffset,
                     GLint yoffset,
                     GLenum format,
                     GLenum type,
                     ImageData*);
  void texSubImage2D(ScriptState*,
                     GLenum target,
                     GLint level,
                     GLint xoffset,
                     GLint yoffset,
                     GLenum format,
                     GLenum type,
                     HTMLImageElement*,
                     ExceptionState&);
  void texSubImage2D(ScriptState*,
                     GLenum target,
                     GLint level,
                     GLint xoffset,
                     GLint yoffset,
                     GLenum format,
                     GLenum type,
                     CanvasRenderingContextHost*,
                     ExceptionState&);
  void texSubImage2D(ScriptState*,
                     GLenum target,
                     GLint level,
                     GLint xoffset,
                     GLint yoffset,
                     GLenum format,
                     GLenum type,
                     HTMLVideoElement*,
                     ExceptionState&);
  void texSubImage2D(ScriptState*,
                     GLenum target,
                     GLint level,
                     GLint xoffset,
                     GLint yoffset,
                     GLenum format,
                     GLenum type,
                     VideoFrame*,
                     ExceptionState&);
  void texSubImage2D(GLenum target,
                     GLint level,
                     GLint xoffset,
                     GLint yoffset,
                     GLenum format,
                     GLenum type,
                     ImageBitmap*,
                     ExceptionState&);

  void uniform1f(const WebGLUniformLocation*, GLfloat x);
  void uniform1fv(const WebGLUniformLocation*, base::span<const GLfloat>);
  void uniform1i(const WebGLUniformLocation*, GLint x);
  void uniform1iv(const WebGLUniformLocation*, base::span<const GLint>);
  void uniform2f(const WebGLUniformLocation*, GLfloat x, GLfloat y);
  void uniform2fv(const WebGLUniformLocation*, base::span<const GLfloat>);
  void uniform2i(const WebGLUniformLocation*, GLint x, GLint y);
  void uniform2iv(const WebGLUniformLocation*, base::span<const GLint>);
  void uniform3f(const WebGLUniformLocation*, GLfloat x, GLfloat y, GLfloat z);
  void uniform3fv(const WebGLUniformLocation*, base::span<const GLfloat>);
  void uniform3i(const WebGLUniformLocation*, GLint x, GLint y, GLint z);
  void uniform3iv(const WebGLUniformLocation*, base::span<const GLint>);
  void uniform4f(const WebGLUniformLocation*,
                 GLfloat x,
                 GLfloat y,
                 GLfloat z,
                 GLfloat w);
  void uniform4fv(const WebGLUniformLocation*, base::span<const GLfloat>);
  void uniform4i(const WebGLUniformLocation*,
                 GLint x,
                 GLint y,
                 GLint z,
                 GLint w);
  void uniform4iv(const WebGLUniformLocation*, base::span<const GLint>);
  void uniformMatrix2fv(const WebGLUniformLocation*,
                        GLboolean transpose,
                        base::span<const GLfloat> value);
  void uniformMatrix3fv(const WebGLUniformLocation*,
                        GLboolean transpose,
                        base::span<const GLfloat> value);
  void uniformMatrix4fv(const WebGLUniformLocation*,
                        GLboolean transpose,
                        base::span<const GLfloat> value);

  virtual void useProgram(WebGLProgram*);
  void validateProgram(WebGLProgram*);

  void vertexAttrib1f(GLuint index, GLfloat x);
  void vertexAttrib1fv(GLuint index, base::span<const GLfloat> values);
  void vertexAttrib2f(GLuint index, GLfloat x, GLfloat y);
  void vertexAttrib2fv(GLuint index, base::span<const GLfloat> values);
  void vertexAttrib3f(GLuint index, GLfloat x, GLfloat y, GLfloat z);
  void vertexAttrib3fv(GLuint index, base::span<const GLfloat> values);
  void vertexAttrib4f(GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
  void vertexAttrib4fv(GLuint index, base::span<const GLfloat> values);
  void vertexAttribPointer(GLuint index,
                           GLint size,
                           GLenum type,
                           GLboolean normalized,
                           GLsizei stride,
                           int64_t offset);

  void VertexAttribDivisorANGLE(GLuint index, GLuint divisor);

  void viewport(GLint x, GLint y, GLsizei width, GLsizei height);

  // WEBGL_lose_context support
  enum AutoRecoveryMethod {
    // Don't restore automatically.
    kManual,

    // Restore when resources are available.
    kWhenAvailable,

    // Restore as soon as possible, but only when
    // the canvas is visible.
    kAuto
  };
  void LoseContext(LostContextMode) override;
  void ForceLostContext(LostContextMode, AutoRecoveryMethod);
  void ForceRestoreContext();

  // Utilities to restore GL state to match the rendering context's
  // saved state. Use these after contextGL()-based state changes that
  // bypass the rendering context.
  void RestoreScissorEnabled();
  void RestoreScissorBox();
  void RestoreClearColor();
  void RestoreColorMask();
  void RestoreVertexArrayObjectBinding();
  void RestoreProgram();
  void RestoreActiveTexture();

  const gpu::Capabilities& ContextGLCapabilities() const {
    // This should only be called in contexts where ContextGL() is guaranteed
    // to exist.
    CHECK(ContextGL());
    // Note: DrawingBuffer::ContextGL() comes from
    // DrawingBuffer::ContextProvider::ContextGL().
    return GetDrawingBuffer()->ContextProvider()->GetCapabilities();
  }
  gpu::SharedImageInterface* SharedImageInterface() const {
    DrawingBuffer* d = GetDrawingBuffer();
    if (!d)
      return nullptr;
    return d->ContextProvider()->SharedImageInterface();
  }

  Extensions3DUtil* ExtensionsUtil();

  void Reshape(int width, int height) override;

  void MarkLayerComposited() override;

  scoped_refptr<StaticBitmapImage> GetRGBAUnacceleratedStaticBitmapImage(
      SourceDrawingBuffer source_buffer) override;

  unsigned MaxVertexAttribs() const { return max_vertex_attribs_; }

  void Trace(Visitor*) const override;

  // Returns approximate gpu memory allocated per pixel.
  int ExternallyAllocatedBufferCountPerPixel() override;

  // Returns the drawing buffer size after it is, probably, has scaled down
  // to the maximum supported canvas size.
  gfx::Size DrawingBufferSize() const override;
  DrawingBuffer* GetDrawingBuffer() const;

  class TextureUnitState {
    DISALLOW_NEW();

   public:
    Member<WebGLTexture> texture2d_binding_;
    Member<WebGLTexture> texture_cube_map_binding_;
    Member<WebGLTexture> texture3d_binding_;
    Member<WebGLTexture> texture2d_array_binding_;
    Member<WebGLTexture> texture_video_image_binding_;
    Member<WebGLTexture> texture_external_oes_binding_;
    Member<WebGLTexture> texture_rectangle_arb_binding_;

    void Trace(Visitor*) const;
  };

  SkAlphaType GetAlphaType() const override;
  viz::SharedImageFormat GetSharedImageFormat() const override;
  gfx::ColorSpace GetColorSpace() const override;
  scoped_refptr<StaticBitmapImage> GetImage(FlushReason) override;
  void SetHdrMetadata(const gfx::HDRMetadata& hdr_metadata) override;

  V8UnionHTMLCanvasElementOrOffscreenCanvas* getHTMLOrOffscreenCanvas() const;

  void drawingBufferStorage(GLenum sizedformat, GLsizei width, GLsizei height);

  void commit();

  ScriptPromise<IDLUndefined> makeXRCompatible(ScriptState*, ExceptionState&);
  bool IsXRCompatible() const;

  void UpdateNumberOfUserAllocatedMultisampledRenderbuffers(int delta);

  // The maximum supported size of an ArrayBuffer is the maximum size that can
  // be allocated in JavaScript. This maximum is defined by the maximum size
  // PartitionAlloc can allocate.
  // We limit the maximum size of ArrayBuffers we support to avoid integer
  // overflows in the WebGL implementation. WebGL stores the data size as
  // uint32_t, so if sizes just below uint32_t::max() were passed in, integer
  // overflows could happen. The limit defined here is (2GB-2MB), which should
  // be enough buffer to avoid integer overflow.
  // This limit should restrict the usability of WebGL2 only insignificantly, as
  // JavaScript cannot allocate bigger ArrayBuffers anyways. Only with
  // WebAssembly it is possible to allocate bigger ArrayBuffers.
  static constexpr size_t kMaximumSupportedArrayBufferSize =
      ::partition_alloc::internal::MaxDirectMapped();

 protected:
  // Implementation helpers.
  friend class ScopedPixelLocalStorageInterrupt;
  friend class ScopedDrawingBufferBinder;
  friend class ScopedFramebufferRestorer;
  friend class ScopedTexture2DRestorer;
  friend class ScopedUnpackParametersResetRestore;

  // WebGL extensions.
  friend class EXTColorBufferFloat;
  friend class EXTColorBufferHalfFloat;
  friend class EXTDisjointTimerQuery;
  friend class EXTDisjointTimerQueryWebGL2;
  friend class EXTTextureCompressionBPTC;
  friend class EXTTextureCompressionRGTC;
  friend class OESDrawBuffersIndexed;
  friend class OESTextureFloat;
  friend class OESVertexArrayObject;
  friend class OVRMultiview2;
  friend class WebGLColorBufferFloat;
  friend class WebGLCompressedTextureASTC;
  friend class WebGLCompressedTextureETC;
  friend class WebGLCompressedTextureETC1;
  friend class WebGLCompressedTexturePVRTC;
  friend class WebGLCompressedTextureS3TC;
  friend class WebGLCompressedTextureS3TCsRGB;
  friend class WebGLContextFactory;
  friend class WebGLDebugShaders;
  friend class WebGLDrawBuffers;
  friend class WebGLDrawInstancedBaseVertexBaseInstance;
  friend class WebGLFramebuffer;
  friend class WebGLMultiDraw;
  friend class WebGLMultiDrawCommon;
  friend class WebGLMultiDrawInstancedBaseVertexBaseInstance;
  friend class WebGLPolygonMode;
  friend class WebGLShaderPixelLocalStorage;

  WebGLRenderingContextBase(CanvasRenderingContextHost*,
                            std::unique_ptr<WebGraphicsContext3DProvider>,
                            const Platform::GraphicsInfo& graphics_info,
                            const CanvasContextCreationAttributesCore&,
                            Platform::ContextType);
  scoped_refptr<DrawingBuffer> CreateDrawingBuffer(
      std::unique_ptr<WebGraphicsContext3DProvider>,
      const Platform::GraphicsInfo& graphics_info);
  void SetupFlags();
  bool CopyRenderingResultsFromDrawingBuffer(CanvasResourceProvider*,
                                             SourceDrawingBuffer);

  // CanvasRenderingContext implementation.
  bool IsComposited() const override { return true; }
  bool UsingSwapChain() const override;
  void PageVisibilityChanged() override;
  CanvasResourceProvider* PaintRenderingResultsToCanvas(
      SourceDrawingBuffer) override;
  bool CopyRenderingResultsToVideoFrame(
      WebGraphicsContext3DVideoFramePool*,
      SourceDrawingBuffer,
      const gfx::ColorSpace&,
      VideoFrameCopyCompletedCallback) override;

  cc::Layer* CcLayer() const override;
  void Stop() override;
  void FinalizeFrame(FlushReason) override;
  bool PushFrame() override;

  // DrawingBuffer::Client implementation.
  bool DrawingBufferClientIsBoundForDraw() override;
  void DrawingBufferClientInterruptPixelLocalStorage() override;
  void DrawingBufferClientRestorePixelLocalStorage() override;
  void DrawingBufferClientRestoreScissorTest() override;
  void DrawingBufferClientRestoreMaskAndClearValues() override;
  void DrawingBufferClientRestorePixelPackParameters() override;
  void DrawingBufferClientRestoreTexture2DBinding() override;
  void DrawingBufferClientRestoreTexture2DArrayBinding() override;
  void DrawingBufferClientRestoreTextureCubeMapBinding() override;
  void DrawingBufferClientRestoreRenderbufferBinding() override;
  void DrawingBufferClientRestoreFramebufferBinding() override;
  void DrawingBufferClientRestorePixelUnpackBufferBinding() override;
  void DrawingBufferClientRestorePixelPackBufferBinding() override;
  bool DrawingBufferClientUserAllocatedMultisampledRenderbuffers() override;
  void DrawingBufferClientForceLostContextWithAutoRecovery(
      const char* reason) override;
  void DrawingBufferClientInitializeLayer(cc::Layer* layer) override;

  // All draw calls should go through this wrapper so that various
  // bookkeeping related to compositing and preserveDrawingBuffer
  // can happen.
  template <typename Func>
  void DrawWrapper(const char* func_name,
                   CanvasPerformanceMonitor::DrawType draw_type,
                   Func draw_func) {
    if (!bound_vertex_array_object_->IsAllEnabledAttribBufferBound()) {
      SynthesizeGLError(GL_INVALID_OPERATION, func_name,
                        "no buffer is bound to enabled attribute");
      return;
    }

    ScopedRGBEmulationColorMask emulation_color_mask(this, color_mask_.data(),
                                                     drawing_buffer_.get());
    OnBeforeDrawCall(draw_type);
    draw_func();
    if (!has_been_drawn_to_) {
      // At first draw call, record
      // Canvas/OffscreenCanvas.RenderingContextDrawnTo and what the ANGLE
      // implementation is.
      has_been_drawn_to_ = true;
      RecordUKMCanvasDrawnToRenderingAPI();
      RecordANGLEImplementation();
    }
  }

  virtual void DestroyContext();
  void MarkContextChanged(ContentChangeType,
                          CanvasPerformanceMonitor::DrawType);

  void OnErrorMessage(const char*, int32_t id);

  // Query if depth_stencil buffer is supported.
  bool IsDepthStencilSupported() { return is_depth_stencil_supported_; }

  // Check if each enabled vertex attribute is bound to a buffer.
  bool ValidateRenderingState(const char*);

  // Helper function for APIs which can legally receive null objects, including
  // the bind* calls (bindBuffer, bindTexture, etc.) and useProgram. Checks that
  // the object belongs to this context and that it's not marked for deletion.
  // Returns false if the caller should return without further processing.
  // Performs a context loss check internally.
  // This returns true for null WebGLObject arguments!
  bool ValidateNullableWebGLObject(const char* function_name, WebGLObject*);

  // Validates the incoming WebGL object, which is assumed to be non-null.
  // Checks that the object belongs to this context and that it's not marked for
  // deletion. Performs a context loss check internally.
  bool ValidateWebGLObject(const char* function_name, WebGLObject*);

  // Validates the incoming WebGL program or shader, which is assumed to be
  // non-null. OpenGL ES's validation rules differ for these types of objetcts
  // compared to others. Performs a context loss check internally.
  bool ValidateWebGLProgramOrShader(const char* function_name, WebGLObject*);

  // Adds a compressed texture format.
  void AddCompressedTextureFormat(GLenum);
  void RemoveAllCompressedTextureFormats();

  // Set UNPACK_ALIGNMENT to 1, all other parameters to 0.
  virtual void ResetUnpackParameters();
  // Restore the client unpack parameters.
  virtual void RestoreUnpackParameters();

  // Draw the specified image into a new image. Used for a workaround when
  // uploading SVG images (see the caller).
  scoped_refptr<Image> DrawImageIntoBufferForTexImage(
      scoped_refptr<Image>,
      int width,
      int height,
      const char* function_name);

  // Structure for rendering to a DrawingBuffer, instead of directly
  // to the back-buffer of m_context.
  scoped_refptr<DrawingBuffer> drawing_buffer_;

  LostContextMode context_lost_mode_ = kNotLostContext;
  AutoRecoveryMethod auto_recovery_method_ = kManual;
  // Dispatches a context lost event once it is determined that one is needed.
  // This is used for synthetic, WEBGL_lose_context and real context losses. For
  // real ones, it's likely that there's no JavaScript on the stack, but that
  // might be dependent on how exactly the platform discovers that the context
  // was lost. For better portability we always defer the dispatch of the event.
  HeapTaskRunnerTimer<WebGLRenderingContextBase>
      dispatch_context_lost_event_timer_;
  bool restore_allowed_ = false;
  HeapTaskRunnerTimer<WebGLRenderingContextBase> restore_timer_;

  bool destruction_in_progress_ = false;
  bool marked_canvas_dirty_;
  // For performance reasons we must separately track whether we've
  // copied WebGL's drawing buffer to the canvas's backing store, for
  // example for printing.
  bool must_paint_to_canvas_;

  // List of bound VBO's. Used to maintain info about sizes for ARRAY_BUFFER and
  // stored values for ELEMENT_ARRAY_BUFFER
  Member<WebGLBuffer> bound_array_buffer_;

  Member<WebGLVertexArrayObjectBase> default_vertex_array_object_;
  Member<WebGLVertexArrayObjectBase> bound_vertex_array_object_;
  void SetBoundVertexArrayObject(WebGLVertexArrayObjectBase*);

  enum VertexAttribValueType {
    kFloat32ArrayType,
    kInt32ArrayType,
    kUint32ArrayType,
  };

  Vector<VertexAttribValueType> vertex_attrib_type_;
  unsigned max_vertex_attribs_;
  void SetVertexAttribType(GLuint index, VertexAttribValueType);

  Member<WebGLProgram> current_program_;
  Member<WebGLFramebuffer> framebuffer_binding_;
  Member<WebGLRenderbuffer> renderbuffer_binding_;

  static bool MakeXrCompatibleSync(CanvasRenderingContextHost* host);
  static bool IsXrCompatibleFromResult(
      device::mojom::blink::XrCompatibleResult result);
  static bool DidGpuRestart(device::mojom::blink::XrCompatibleResult result);
  static XRSystem* GetXrSystemFromHost(CanvasRenderingContextHost* host);
  void MakeXrCompatibleAsync();
  void OnMakeXrCompatibleFinished(
      device::mojom::blink::XrCompatibleResult xr_compatible_result);
  void CompleteXrCompatiblePromiseIfPending(DOMExceptionCode exception_code);
  bool xr_compatible_;
  Member<ScriptPromiseResolver<IDLUndefined>> make_xr_compatible_resolver_;

  HeapVector<TextureUnitState> texture_units_;
  wtf_size_t active_texture_unit_;

  Vector<GLenum> compressed_texture_formats_;

  // Fixed-size cache of reusable resource providers for image and video
  // texImage2D calls.
  class LRUCanvasResourceProviderCache {
   public:
    enum class CacheType { kImage, kVideo };
    LRUCanvasResourceProviderCache(wtf_size_t capacity, CacheType type);
    // The pointer returned is owned by the image buffer map.
    CanvasResourceProvider* GetCanvasResourceProvider(
        gfx::Size size,
        viz::SharedImageFormat format,
        SkAlphaType alpha_type,
        const gfx::ColorSpace& color_space);

   private:
    void BubbleToFront(wtf_size_t idx);
    const wtf_size_t capacity_;
    const CacheType type_;
    Vector<std::unique_ptr<CanvasResourceProvider>> resource_providers_;
    // The returned CanvasResourceProvider may have a different format from the
    // one requested (e.g, BGRA vs RGBA). Ensure this doesn't cause cache
    // misses by recording also the requested format.
    Vector<viz::SharedImageFormat> requested_formats_;
  };
  LRUCanvasResourceProviderCache generated_image_cache_{
      4, LRUCanvasResourceProviderCache::CacheType::kImage};
  LRUCanvasResourceProviderCache generated_video_cache_{
      4, LRUCanvasResourceProviderCache::CacheType::kVideo};

  GLint max_texture_size_;
  GLint max_cube_map_texture_size_;
  GLint max3d_texture_size_;
  GLint max_array_texture_layers_;
  GLint max_renderbuffer_size_;
  std::array<GLint, 2> max_viewport_dims_;
  GLint max_texture_level_;
  GLint max_cube_map_texture_level_;
  GLint max3d_texture_level_;

  GLint max_draw_buffers_;
  GLint max_color_attachments_;
  GLenum back_draw_buffer_;
  bool draw_buffers_web_gl_requirements_checked_;
  bool draw_buffers_supported_;

  GLenum read_buffer_of_default_framebuffer_;

  GLint pack_alignment_ = 4;
  GLint unpack_alignment_ = 4;
  bool unpack_flip_y_ = false;
  bool unpack_premultiply_alpha_ = false;
  GLenum unpack_colorspace_conversion_ = GC3D_BROWSER_DEFAULT_WEBGL;
  // The following three unpack params belong to WebGL2 only.
  GLint unpack_skip_pixels_ = 0;
  GLint unpack_skip_rows_ = 0;
  GLint unpack_row_length_ = 0;

  std::array<GLfloat, 4> clear_color_;
  bool scissor_enabled_;
  std::array<GLint, 4> scissor_box_;
  GLfloat clear_depth_;
  GLint clear_stencil_;
  // State of the color mask - or the zeroth indexed color mask, if
  // OES_draw_buffers_indexed is enabled.
  std::array<GLboolean, 4> color_mask_;
  GLboolean depth_mask_;

  bool depth_enabled_;
  bool stencil_enabled_;
  GLuint stencil_mask_, stencil_mask_back_;
  GLint stencil_func_ref_,
      stencil_func_ref_back_;  // Note that these are the user specified values,
                               // not the internal clamped value.
  GLuint stencil_func_mask_, stencil_func_mask_back_;

  // WebGL 2.0 only, but putting it here saves multiple virtual functions.
  bool rasterizer_discard_enabled_;

  bool is_depth_stencil_supported_;

  bool synthesized_errors_to_console_ = true;
  int num_gl_errors_to_console_allowed_;

  wtf_size_t one_plus_max_non_default_texture_unit_ = 0;

  std::unique_ptr<Extensions3DUtil> extensions_util_;

  enum ExtensionFlags {
    kApprovedExtension = 0x00,
    // Extension that is behind the draft extensions runtime flag:
    kDraftExtension = 0x01,
    // Extension that is intended for development rather than
    // deployment time.
    kDeveloperExtension = 0x02,
  };

  class ExtensionTracker : public GarbageCollected<ExtensionTracker>,
                           public NameClient {
   public:
    explicit ExtensionTracker(ExtensionFlags flags)
        : draft_(flags & kDraftExtension),
          developer_(flags & kDeveloperExtension) {}
    ~ExtensionTracker() override = default;

    bool Draft() const { return draft_; }
    bool Developer() const { return developer_; }

    bool MatchesName(const String&) const;

    virtual WebGLExtension* GetExtension(WebGLRenderingContextBase*) = 0;
    virtual bool Supported(WebGLRenderingContextBase*) const = 0;
    virtual const char* ExtensionName() const = 0;
    virtual void LoseExtension(bool) = 0;

    // This is only used for keeping the JS wrappers of extensions alive.
    virtual WebGLExtension* GetExtensionObjectIfAlreadyEnabled() = 0;

    virtual void Trace(Visitor* visitor) const {}
    const char* NameInHeapSnapshot() const override {
      return "ExtensionTracker";
    }

   private:
    bool draft_;
    bool developer_;
  };

  template <typename T>
  class TypedExtensionTracker final : public ExtensionTracker {
   public:
    explicit TypedExtensionTracker(ExtensionFlags flags)
        : ExtensionTracker(flags) {}

    WebGLExtension* GetExtension(WebGLRenderingContextBase* context) override {
      if (!extension_) {
        extension_ = MakeGarbageCollected<T>(context);
      }

      return extension_.Get();
    }

    bool Supported(WebGLRenderingContextBase* context) const override {
      return T::Supported(context);
    }

    const char* ExtensionName() const override { return T::ExtensionName(); }

    void LoseExtension(bool force) override {
      if (extension_) {
        extension_->Lose(force);
        if (extension_->IsLost())
          extension_ = nullptr;
      }
    }

    WebGLExtension* GetExtensionObjectIfAlreadyEnabled() override {
      return extension_.Get();
    }

    void Trace(Visitor* visitor) const override {
      visitor->Trace(extension_);
      ExtensionTracker::Trace(visitor);
    }

   private:
    // ExtensionTracker holds it's own reference to the extension to ensure
    // that it is not deleted before this object's destructor is called
    Member<T> extension_;
  };

  std::array<bool, kWebGLExtensionNameCount> extension_enabled_;
  HeapVector<Member<ExtensionTracker>> extensions_;
  HashSet<String> disabled_extensions_;

  template <typename T>
  void RegisterExtension(ExtensionFlags flags = kApprovedExtension) {
    extensions_.push_back(
        MakeGarbageCollected<TypedExtensionTracker<T>>(flags));
  }

  bool ExtensionSupportedAndAllowed(const ExtensionTracker*);
  WebGLExtension* EnableExtensionIfSupported(const String& name);

  bool TimerQueryExtensionsEnabled();

  // ScopedDrawingBufferBinder is used for
  // ReadPixels/CopyTexImage2D/CopySubImage2D to read from a multisampled
  // DrawingBuffer. In this situation, we need to blit to a single sampled
  // buffer for reading, during which the bindings could be changed and need to
  // be recovered.
  //
  // It is possible for the binding operation to fail, in which case
  // the context will have been lost. Users must check the Succeeded()
  // status before proceeding.
  class ScopedDrawingBufferBinder {
    STACK_ALLOCATED();

   public:
    ScopedDrawingBufferBinder(DrawingBuffer* drawing_buffer,
                              WebGLFramebuffer* framebuffer_binding)
        : drawing_buffer_(drawing_buffer),
          read_framebuffer_binding_(framebuffer_binding),
          succeeded_(true) {
      // Commit DrawingBuffer if needed (e.g., for multisampling)
      if (!read_framebuffer_binding_ && drawing_buffer_)
        succeeded_ = drawing_buffer_->ResolveAndBindForReadAndDraw();
    }

    // Users must check this before proceeding with their logic.
    [[nodiscard]] bool Succeeded() { return succeeded_; }

    ~ScopedDrawingBufferBinder() {
      // Restore DrawingBuffer if needed
      if (!read_framebuffer_binding_ && drawing_buffer_ && succeeded_) {
        drawing_buffer_->RestoreFramebufferBindings();
      }
    }

   private:
    DrawingBuffer* drawing_buffer_;
    WebGLFramebuffer* read_framebuffer_binding_;
    bool succeeded_;
  };

  // Errors raised by synthesizeGLError() while the context is lost.
  Vector<GLenum> lost_context_errors_;
  // Other errors raised by synthesizeGLError().
  Vector<GLenum> synthetic_errors_;

  bool is_web_gl2_formats_types_added_ = false;
  bool is_web_gl2_tex_image_source_formats_types_added_ = false;
  bool is_web_gl2_internal_formats_copy_tex_image_added_ = false;
  bool is_oes_texture_float_formats_types_added_ = false;
  bool is_oes_texture_half_float_formats_types_added_ = false;
  bool is_web_gl_depth_texture_formats_types_added_ = false;
  bool is_ext_srgb_formats_types_added_ = false;
  bool is_ext_color_buffer_float_formats_added_ = false;
  bool is_ext_color_buffer_half_float_formats_added_ = false;
  bool is_ext_texture_norm16_added_ = false;

  GLenumHashSet supported_internal_formats_;
  GLenumHashSet supported_tex_image_source_internal_formats_;
  GLenumHashSet supported_internal_formats_copy_tex_image_;
  GLenumHashSet supported_formats_;
  GLenumHashSet supported_tex_image_source_formats_;
  GLenumHashSet supported_types_;
  GLenumHashSet supported_tex_image_source_types_;

  // Helpers for getParameter and others
  ScriptValue GetBooleanParameter(ScriptState*, GLenum);
  ScriptValue GetBooleanArrayParameter(ScriptState*, GLenum);
  ScriptValue GetFloatParameter(ScriptState*, GLenum);
  ScriptValue GetIntParameter(ScriptState*, GLenum);
  ScriptValue GetInt64Parameter(ScriptState*, GLenum);
  ScriptValue GetUnsignedIntParameter(ScriptState*, GLenum);
  ScriptValue GetWebGLFloatArrayParameter(ScriptState*, GLenum);
  ScriptValue GetWebGLIntArrayParameter(ScriptState*, GLenum);

  // Clear the backbuffer if it was composited since the last operation.
  // clearMask is set to the bitfield of any clear that would happen anyway at
  // this time and the function returns |CombinedClear| if that clear is now
  // unnecessary.
  enum HowToClear {
    // Skip clearing the backbuffer.
    kSkipped,
    // Clear the backbuffer.
    kJustClear,
    // Combine webgl.clear() API with the backbuffer clear, so webgl.clear()
    // doesn't have to call glClear() again.
    kCombinedClear
  };
  enum ClearCaller {
    // Caller of ClearIfComposited is a user-level draw or clear call.
    kClearCallerDrawOrClear,
    // Caller of ClearIfComposited is anything else, including
    // readbacks or copies.
    kClearCallerOther,
  };

  HowToClear ClearIfComposited(ClearCaller caller, GLbitfield clear_mask = 0);

  // Convert texture internal format.
  GLenum ConvertTexInternalFormat(GLenum internalformat, GLenum type);

  enum TexImageSourceType {
    kSourceArrayBufferView,
    kSourceImageData,
    kSourceHTMLImageElement,
    kSourceHTMLCanvasElement,
    kSourceHTMLVideoElement,
    kSourceImageBitmap,
    kSourceUnpackBuffer,
    kSourceVideoFrame,
  };

  enum TexImageFunctionType {
    kTexImage,
    kTexSubImage,
    kCopyTexImage,
    kCompressedTexImage
  };

  // This must stay in sync with WebMediaPlayer::TexImageFunctionID.
  enum TexImageFunctionID {
    kTexImage2D,
    kTexSubImage2D,
    kTexImage3D,
    kTexSubImage3D
  };

  enum TexImageDimension { kTex2D, kTex3D };

  // Parameters for all TexImage functions.
  struct TexImageParams {
    TexImageSourceType source_type = kSourceArrayBufferView;
    TexImageFunctionID function_id = kTexImage2D;
    GLenum target = 0;
    GLint level = 0;

    // The internal format for the texture to create, only applies to
    // TexImage calls.
    GLint internalformat = 0;

    // The offset into the destination in which to do the copy, only applies
    // to TexSubImage calls.
    GLint xoffset = 0;
    GLint yoffset = 0;
    GLint zoffset = 0;

    // The volume to copy. This is always specified by TexSubImage calls, and
    // is sometimes specified by TexImage calls. For TexImage calls where this
    // is not specified, it must be populated with the native size of the source
    // of the texture upload.
    std::optional<GLsizei> width;
    std::optional<GLsizei> height;
    std::optional<GLsizei> depth;

    // The border parameter, only applies to TexImage calls.
    GLint border = 0;

    // The format and type of the source texel data.
    GLenum format = 0;
    GLenum type = 0;

    // If true, then the input should be converted to premultiplied before
    // being uploaded (and if false, then the input should be converted to
    // unpremultiplied). For ImageBitmap sources, this must be set in such a way
    // that it will have no effect.
    bool unpack_premultiply_alpha = false;

    // If true, then the input should be flipped vertically before being
    // uploaded. For ImageBitmap sources, this must be set in such a way that it
    // will have no effect.
    bool unpack_flip_y = false;

    // The offset into the source from which to do the copy (the terminology
    // used here is pixels,rows,images instead of x,y,z).
    GLint unpack_skip_pixels = 0;
    GLint unpack_skip_rows = 0;
    GLint unpack_skip_images = 0;

    // Returns sub rect of the source based on `unpack_*` params above. This
    // rect is always in top-left coordinate space.
    gfx::Rect GetSourceRect(gfx::Size source_size) const;

    // Returns GrSurfaceOrigin of the destination texture for this operation.
    // Note, that textures don't have persistent orientation (e.g unlike
    // SharedImages), so this value doesn't affect the data in the texture
    // before the operation, only operation itself. This is helper because
    // everything else operates in terms of GrSurfaceOrigin.
    GrSurfaceOrigin GetDestinationOrigin() const;

    // Returns desired alpha type of the uploaded data.
    SkAlphaType GetDestinationAlphaType() const;

    // The source's height for 3D copies. If we are doing a 3D copy, then we
    // interpret the 2D source as 3D by treating it as vertical sequence of
    // images with this height.
    GLint unpack_image_height = 0;

    // If true, then the source should be converted to the unpack color space.
    bool unpack_colorspace_conversion = true;
  };

  // Populate the unpack state based on the context's current state. This is
  // virtual because some state is only tracked in WebGL 2.
  virtual void GetCurrentUnpackState(TexImageParams& params);

  // Upload `image` to the specified texture.
  void TexImageSkImage(TexImageParams params, sk_sp<SkImage> image);

  // Call the underlying Tex[Sub]Image{2D|3D} function. Always replace
  // `params.internalformat` with the result from ConvertTexInternalFormat.
  void TexImageBase(const TexImageParams& params, const void* pixels);

  // Upload `image` to the specified texture. If `allow_copy_via_gpu` is
  // true and `image` is an AcceleratedBitmapImage, then the copy may be
  // performed using TexImageViaGPU. Otherwise, the copy will be be performed
  // using TexImageSkImage.
  void TexImageStaticBitmapImage(TexImageParams params,
                                 StaticBitmapImage* image,
                                 bool allow_copy_via_gpu);
  template <typename T>
  gfx::Rect GetTextureSourceSize(T* texture_source) {
    return gfx::Rect(0, 0, texture_source->width(), texture_source->height());
  }

  template <typename T>
  bool ValidateTexImageSubRectangle(const TexImageParams& params,
                                    T* image,
                                    bool* selecting_sub_rectangle) {
    const char* function_name = GetTexImageFunctionName(params.function_id);
    DCHECK(function_name);
    DCHECK(selecting_sub_rectangle);
    if (!image) {
      // Probably indicates a failure to allocate the image.
      SynthesizeGLError(GL_OUT_OF_MEMORY, function_name, "out of memory");
      return false;
    }

    const int image_width = static_cast<int>(image->width());
    const int image_height = static_cast<int>(image->height());
    const gfx::Rect sub_rect(params.unpack_skip_pixels, params.unpack_skip_rows,
                             params.width.value_or(image_width),
                             params.height.value_or(image_height));
    const GLsizei depth = params.depth.value_or(1);
    *selecting_sub_rectangle =
        !(sub_rect.x() == 0 && sub_rect.y() == 0 &&
          sub_rect.width() == image_width && sub_rect.height() == image_height);
    // If the source image rect selects anything except the entire
    // contents of the image, assert that we're running WebGL 2.0 or
    // higher, since this should never happen for WebGL 1.0 (even though
    // the code could support it). If the image is null, that will be
    // signaled as an error later.
    DCHECK(!*selecting_sub_rectangle || IsWebGL2())
        << "subRect = (" << sub_rect.width() << " x " << sub_rect.height()
        << ") @ (" << sub_rect.x() << ", " << sub_rect.y() << "), image = ("
        << image_width << " x " << image_height << ")";

    if (sub_rect.x() < 0 || sub_rect.y() < 0 ||
        sub_rect.right() > image_width || sub_rect.bottom() > image_height ||
        sub_rect.width() < 0 || sub_rect.height() < 0) {
      SynthesizeGLError(GL_INVALID_OPERATION, function_name,
                        "source sub-rectangle specified via pixel unpack "
                        "parameters is invalid");
      return false;
    }

    if (params.function_id == kTexImage3D ||
        params.function_id == kTexSubImage3D) {
      DCHECK_GE(params.unpack_image_height, 0);

      if (depth < 1) {
        SynthesizeGLError(GL_INVALID_OPERATION, function_name,
                          "Can't define a 3D texture with depth < 1");
        return false;
      }

      // According to the WebGL 2.0 spec, specifying depth > 1 means
      // to select multiple rectangles stacked vertically.
      base::CheckedNumeric<GLint> max_y_accessed;
      if (params.unpack_image_height) {
        max_y_accessed = params.unpack_image_height;
      } else {
        max_y_accessed = sub_rect.height();
      }
      max_y_accessed *= depth - 1;
      max_y_accessed += sub_rect.height();
      max_y_accessed += sub_rect.y();

      if (!max_y_accessed.IsValid()) {
        SynthesizeGLError(GL_INVALID_OPERATION, function_name,
                          "Out-of-range parameters passed for 3D texture "
                          "upload");
        return false;
      }

      if (max_y_accessed.ValueOrDie() > image_height) {
        SynthesizeGLError(GL_INVALID_OPERATION, function_name,
                          "Not enough data supplied to upload to a 3D texture "
                          "with depth > 1");
        return false;
      }
    } else {
      DCHECK_EQ(depth, 1);
      DCHECK_EQ(params.unpack_image_height, 0);
    }
    return true;
  }

  virtual WebGLImageConversion::PixelStoreParams GetPackPixelStoreParams();
  virtual WebGLImageConversion::PixelStoreParams GetUnpackPixelStoreParams(
      TexImageDimension);

  // Helper function for copyTex{Sub}Image, check whether the internalformat
  // and the color buffer format of the current bound framebuffer combination
  // is valid.
  bool IsTexInternalFormatColorBufferCombinationValid(
      GLenum tex_internal_format,
      GLenum color_buffer_format);

  // Helper function to verify limits on the length of uniform and attribute
  // locations.
  virtual unsigned GetMaxWebGLLocationLength() const { return 256; }
  bool ValidateLocationLength(const char* function_name, const String&);

  // Helper function to check if size is non-negative.
  // Generate GL error and return false for negative inputs; otherwise, return
  // true.
  bool ValidateSize(const char* function_name, GLint x, GLint y, GLint z = 0);

  // Helper function to check if a character belongs to the ASCII subset as
  // defined in GLSL ES 1.0 spec section 3.1.
  bool ValidateCharacter(unsigned char c);

  // Helper function to check if all characters in the string belong to the
  // ASCII subset as defined in GLSL ES 1.0 spec section 3.1.
  bool ValidateString(const char* function_name, const String&);

  // Helper function to check if an identifier starts with reserved prefixes.
  bool IsPrefixReserved(const String& name);

  virtual bool ValidateShaderType(const char* function_name,
                                  GLenum shader_type);

  // Helper function to check texture binding target and texture bound to the
  // target.  Generates GL errors and returns 0 if target is invalid or texture
  // bound is null.  Otherwise, returns the texture bound to the target.
  WebGLTexture* ValidateTextureBinding(const char* function_name,
                                       GLenum target);

  // Wrapper function for validateTexture2D(3D)Binding, used in TexImageHelper
  // functions.
  virtual WebGLTexture* ValidateTexImageBinding(const TexImageParams& params);

  // Helper function to check texture 2D target and texture bound to the target.
  // Generate GL errors and return 0 if target is invalid or texture bound is
  // null.  Otherwise, return the texture bound to the target.
  // If |validate_opaque_textures| is true, the helper will also generate a GL
  // error when the texture bound to the target is opaque.
  // See https://www.w3.org/TR/webxrlayers-1/#opaque-texture for details about
  // opaque textures.
  WebGLTexture* ValidateTexture2DBinding(const char* function_name,
                                         GLenum target,
                                         bool validate_opaque_textures = false);

  void AddExtensionSupportedFormatsTypes();
  void AddExtensionSupportedFormatsTypesWebGL2();

  // Helper function to check input internalformat/format/type for functions
  // Tex{Sub}Image taking TexImageSource source data.  Generates GL error and
  // returns false if parameters are invalid.
  bool ValidateTexImageSourceFormatAndType(const TexImageParams& params);

  // Helper function to check input internalformat/format/type for functions
  // Tex{Sub}Image.  Generates GL error and returns false if parameters are
  // invalid.
  bool ValidateTexFuncFormatAndType(const TexImageParams& params);

  // Helper function to check readbuffer validity for copyTex{Sub}Image.
  // If yes, obtains the bound read framebuffer, returns true.
  // If not, generates a GL error, returns false.
  bool ValidateReadBufferAndGetInfo(
      const char* function_name,
      WebGLFramebuffer*& read_framebuffer_binding);

  // Helper function to check format/type and ArrayBuffer view type for
  // readPixels.
  // Generates INVALID_ENUM and returns false if parameters are invalid.
  // Generates INVALID_OPERATION if ArrayBuffer view type is incompatible with
  // type.
  virtual bool ValidateReadPixelsFormatAndType(GLenum format,
                                               GLenum type,
                                               DOMArrayBufferView*);

  // Helper function to check parameters of readPixels. Returns true if all
  // parameters are valid. Otherwise, generates appropriate error and returns
  // false.
  bool ValidateReadPixelsFuncParameters(GLsizei width,
                                        GLsizei height,
                                        GLenum format,
                                        GLenum type,
                                        DOMArrayBufferView*,
                                        int64_t buffer_size);

  virtual GLint GetMaxTextureLevelForTarget(GLenum target);

  // Helper function to check input level for functions {copy}Tex{Sub}Image.
  // Generates GL error and returns false if level is invalid.
  bool ValidateTexFuncLevel(const char* function_name,
                            GLenum target,
                            GLint level);

  // Helper function to check if a 64-bit value is non-negative and can fit into
  // a 32-bit integer.  Generates GL error and returns false if not.
  bool ValidateValueFitNonNegInt32(const char* function_name,
                                   const char* param_name,
                                   int64_t value);

  // Helper function for tex{Sub}Image{2|3}D to check if the input params'
  // format/type/level/target/width/height/depth/border/xoffset/yoffset/zoffset
  // are valid.  Otherwise, it would return quickly without doing other work.
  // If `source_width` and `source_height` are specified, then overwrite
  // params.width and params.height with those values before performing
  // validation.
  bool ValidateTexFunc(TexImageParams params,
                       std::optional<GLsizei> source_width,
                       std::optional<GLsizei> source_height);

  // Helper function to check input width and height for functions {copy,
  // compressed}Tex{Sub}Image.  Generates GL error and returns false if width,
  // height, or depth is invalid.
  bool ValidateTexFuncDimensions(const char* function_name,
                                 TexImageFunctionType,
                                 GLenum target,
                                 GLint level,
                                 GLsizei width,
                                 GLsizei height,
                                 GLsizei depth);

  // Helper function to check input parameters for functions
  // {copy}Tex{Sub}Image.  Generates GL error and returns false if parameters
  // are invalid.
  bool ValidateTexFuncParameters(const TexImageParams& params);

  enum NullDisposition { kNullAllowed, kNullNotAllowed, kNullNotReachable };

  // Helper function to validate that the given ArrayBufferView
  // is of the correct type and contains enough data for the texImage call.
  // Generates GL error and returns false if parameters are invalid.
  bool ValidateTexFuncData(const TexImageParams& params,
                           DOMArrayBufferView* pixels,
                           NullDisposition,
                           int64_t src_offset);

  // Helper function to validate a given texture format is settable as in
  // you can supply data to texImage2D, or call texImage2D, copyTexImage2D and
  // copyTexSubImage2D.
  // Generates GL error and returns false if the format is not settable.
  bool ValidateSettableTexFormat(const char* function_name, GLenum format);

  // Helper function to validate format for CopyTexImage.
  bool ValidateCopyTexFormat(const char* function_name, GLenum format);

  // Helper function for validating compressed texture formats.
  bool ValidateCompressedTexFormat(const char* function_name, GLenum format);

  // Helper function to validate stencil or depth func.
  bool ValidateStencilOrDepthFunc(const char* function_name, GLenum);

  // Helper function for texParameterf and texParameteri.
  void TexParameter(GLenum target,
                    GLenum pname,
                    GLfloat paramf,
                    GLint parami,
                    bool is_float);

  // Helper function to print GL errors to console.
  void PrintGLErrorToConsole(const String&);

  // Helper function to print warnings to console. Currently
  // used only to warn about use of obsolete functions.
  void PrintWarningToConsole(const String&);

  // Wrap probe::DidFireWebGLErrorOrWarning and friends, but defer inside a
  // FastCall.
  void NotifyWebGLErrorOrWarning(const String& message);
  void NotifyWebGLError(const String& error_type);
  void NotifyWebGLWarning();

  // Helper function to validate the target for checkFramebufferStatus and
  // validateFramebufferFuncParameters.
  virtual bool ValidateFramebufferTarget(GLenum target);

  // Get the framebuffer bound to given target
  virtual WebGLFramebuffer* GetFramebufferBinding(GLenum target);

  virtual WebGLFramebuffer* GetReadFramebufferBinding();

  // Helper function to validate input parameters for framebuffer functions.
  // Generate GL error if parameters are illegal.
  bool ValidateFramebufferFuncParameters(const char* function_name,
                                         GLenum target,
                                         GLenum attachment);

  // Helper function to validate blend equation mode.
  bool ValidateBlendEquation(const char* function_name, GLenum);

  // Helper function to validate blend func factors.
  bool ValidateBlendFuncFactors(const char* function_name,
                                GLenum src,
                                GLenum dst);

  // Helper function to validate WEBGL_blend_func_extended
  // factors. Needed only to make negative tests pass on the
  // validating command decoder.
  bool ValidateBlendFuncExtendedFactors(const char* function_name,
                                        GLenum src,
                                        GLenum dst);

  // Helper function to validate a GL capability.
  virtual bool ValidateCapability(const char* function_name, GLenum);

  bool ValidateUniformLocation(const char* function_name,
                               const WebGLUniformLocation* location,
                               const WebGLProgram* program) {
    const WebGLProgram* loc_program = location->Program();
    if (!loc_program) {
      SynthesizeGLError(GL_INVALID_OPERATION, function_name,
                        "location has been invalidated");
      return false;
    }
    if (loc_program != program) {
      SynthesizeGLError(GL_INVALID_OPERATION, function_name,
                        "location is not from the associated program");
      return false;
    }
    return true;
  }

  // Helper function to validate input parameters for uniform functions.
  template <typename T>
  bool ValidateUniformMatrixParameters(const char* function_name,
                                       const WebGLUniformLocation* location,
                                       GLboolean transpose,
                                       base::span<const GLfloat> v,
                                       GLsizei required_min_size,
                                       GLuint src_offset,
                                       size_t src_length,
                                       const T** out_data,
                                       GLuint* out_length) {
    *out_data = nullptr;
    *out_length = 0;
    if (v.empty()) {
      SynthesizeGLError(GL_INVALID_VALUE, function_name, "no array");
      return false;
    }
    if (!base::CheckedNumeric<GLuint>(src_length).IsValid()) {
      SynthesizeGLError(GL_INVALID_VALUE, function_name,
                        "src_length exceeds the maximum supported length");
      return false;
    }
    return ValidateUniformMatrixParameters(
        function_name, location, transpose, v.data(), v.size(),
        required_min_size, src_offset, static_cast<GLuint>(src_length),
        out_data, out_length);
  }

  template <typename T>
  bool ValidateUniformMatrixParameters(const char* function_name,
                                       const WebGLUniformLocation* location,
                                       GLboolean transpose,
                                       const T* v,
                                       size_t size,
                                       GLsizei required_min_size,
                                       GLuint src_offset,
                                       GLuint src_length,
                                       const T** out_data,
                                       GLuint* out_length) {
    *out_data = nullptr;
    *out_length = 0;
    DCHECK(size >= 0 && required_min_size > 0);
    if (!location)
      return false;
    if (!ValidateUniformLocation(function_name, location, current_program_)) {
      return false;
    }
    if (!v) {
      SynthesizeGLError(GL_INVALID_VALUE, function_name, "no array");
      return false;
    }
    if (!base::CheckedNumeric<GLsizei>(size).IsValid()) {
      SynthesizeGLError(GL_INVALID_VALUE, function_name,
                        "array exceeds the maximum supported size");
      return false;
    }
    if (transpose && !IsWebGL2()) {
      SynthesizeGLError(GL_INVALID_VALUE, function_name, "transpose not FALSE");
      return false;
    }
    if (src_offset >= static_cast<GLuint>(size)) {
      SynthesizeGLError(GL_INVALID_VALUE, function_name, "invalid srcOffset");
      return false;
    }
    GLsizei actual_size = static_cast<GLsizei>(size) - src_offset;
    if (src_length > 0) {
      if (src_length > static_cast<GLuint>(actual_size)) {
        SynthesizeGLError(GL_INVALID_VALUE, function_name,
                          "invalid srcOffset + srcLength");
        return false;
      }
      actual_size = src_length;
    }
    if (actual_size < required_min_size || (actual_size % required_min_size)) {
      SynthesizeGLError(GL_INVALID_VALUE, function_name, "invalid size");
      return false;
    }
    // By design the command buffer has an internal (signed) 32-bit
    // limit, so ensure that the amount of data passed down to it
    // doesn't exceed what it can handle. Only integer or float typed
    // arrays can be passed into the uniform*v or uniformMatrix*v
    // functions; each has 4-byte elements.
    base::CheckedNumeric<int32_t> total_size(actual_size);
    total_size *= 4;
    // Add on a fixed constant to account for internal metadata in the
    // command buffer.
    constexpr int32_t kExtraCommandSize = 1024;
    total_size += kExtraCommandSize;
    int32_t total_size_val;
    if (!total_size.AssignIfValid(&total_size_val) ||
        static_cast<size_t>(total_size_val) >
            kMaximumSupportedArrayBufferSize) {
      SynthesizeGLError(GL_INVALID_VALUE, function_name,
                        "size * elementSize, plus a constant, is too large");
      return false;
    }
    *out_data = UNSAFE_TODO(v + src_offset);
    *out_length = actual_size / required_min_size;
    return true;
  }

  template <typename T>
  bool ValidateUniformParameters(const char* function_name,
                                 const WebGLUniformLocation* location,
                                 base::span<const T> v,
                                 GLsizei required_min_size,
                                 GLuint src_offset,
                                 size_t src_length,
                                 const T** out_data,
                                 GLuint* out_length) {
    GLuint length;
    if (!base::CheckedNumeric<GLuint>(src_length).AssignIfValid(&length)) {
      SynthesizeGLError(GL_INVALID_VALUE, function_name,
                        "src_length is too big");
      return false;
    }
    GLuint array_length;
    if (!base::CheckedNumeric<GLuint>(v.size()).AssignIfValid(&array_length)) {
      SynthesizeGLError(GL_INVALID_VALUE, function_name, "array is too big");
      return false;
    }
    if (v.empty()) {
      SynthesizeGLError(GL_INVALID_VALUE, function_name, "no array");
      return false;
    }
    return ValidateUniformMatrixParameters(
        function_name, location, false, v.data(), array_length,
        required_min_size, src_offset, length, out_data, out_length);
  }

  // Helper function to validate the target for bufferData and
  // getBufferParameter.
  virtual bool ValidateBufferTarget(const char* function_name, GLenum target);

  // Helper function to validate the target for bufferData.
  // Return the current bound buffer to target, or 0 if the target is invalid.
  virtual WebGLBuffer* ValidateBufferDataTarget(const char* function_name,
                                                GLenum target);
  // Helper function to validate the usage for bufferData.
  virtual bool ValidateBufferDataUsage(const char* function_name, GLenum usage);

  virtual bool ValidateAndUpdateBufferBindTarget(const char* function_name,
                                                 GLenum target,
                                                 WebGLBuffer*);

  virtual void RemoveBoundBuffer(WebGLBuffer*);

  // Helper function for tex{Sub}Image2D to make sure image is ready and
  // wouldn't taint Origin.

  bool ValidateHTMLImageElement(const SecurityOrigin*,
                                const char* function_name,
                                HTMLImageElement*,
                                ExceptionState&);

  // Helper function for tex{Sub}Image2D to make sure canvas or OffscreenCanvas
  // is ready and wouldn't taint Origin.
  bool ValidateCanvasRenderingContextHost(const SecurityOrigin*,
                                          const char* function_name,
                                          CanvasRenderingContextHost*,
                                          ExceptionState&);

  // Helper function for tex{Sub}Image2D to make sure video is ready wouldn't
  // taint Origin.
  bool ValidateHTMLVideoElement(const SecurityOrigin*,
                                const char* function_name,
                                HTMLVideoElement*,
                                ExceptionState&);

  // Helper function for tex{Sub}Image2D to make sure imagebitmap is ready and
  // wouldn't taint Origin.
  bool ValidateImageBitmap(const char* function_name,
                           ImageBitmap*,
                           ExceptionState&);

  // Helper function to validate drawArrays(Instanced) calls
  bool ValidateDrawArrays(const char* function_name);

  // Helper function to validate drawElements(Instanced) calls
  bool ValidateDrawElements(const char* function_name,
                            GLenum type,
                            int64_t offset);

  // Helper function to check if the byte length of {data} fits into an integer
  // of type {T.} If so, the byte length is stored in {data_length}.
  template <typename T>
  bool ExtractDataLengthIfValid(const char* function_name,
                                MaybeShared<DOMArrayBufferView> data,
                                T* data_length) {
    if (base::CheckedNumeric<T>(data->byteLength())
            .AssignIfValid(data_length)) {
      return true;
    }
    SynthesizeGLError(GL_INVALID_VALUE, function_name,
                      "provided data exceeds the maximum supported length");
    return false;
  }

  // State updates and operations necessary before or at draw call time.
  virtual void OnBeforeDrawCall(CanvasPerformanceMonitor::DrawType);

  // Helper functions to bufferData() and bufferSubData().
  bool ValidateBufferDataBufferSize(const char* function_name, int64_t size);

  void BufferDataImpl(GLenum target,
                      int64_t size,
                      const void* data,
                      GLenum usage);
  void BufferSubDataImpl(GLenum target,
                         int64_t offset,
                         int64_t size,
                         const void* data);

  // Helper function for delete* (deleteBuffer, deleteProgram, etc) functions.
  // Return false if caller should return without further processing.
  bool DeleteObject(WebGLObject*);

  void DispatchContextLostEvent(TimerBase*);
  // Helper for restoration after context lost.
  void MaybeRestoreContext(TimerBase*);

  enum ConsoleDisplayPreference { kDisplayInConsole, kDontDisplayInConsole };

  // Reports an error to glGetError, sends a message to the JavaScript
  // console.
  void SynthesizeGLError(GLenum,
                         const char* function_name,
                         const char* description,
                         ConsoleDisplayPreference = kDisplayInConsole);
  void EmitGLWarning(const char* function, const char* reason);

  String EnsureNotNull(const String&) const;

  // Enable or disable the depth and stencil test based on the user's
  // setting and whether the current FBO has a depth and stencil
  // buffer.
  void ApplyDepthAndStencilTest();

  // Helper for enabling or disabling a capability.
  void EnableOrDisable(GLenum capability, bool enable);

  // Clamp the width and height to GL_MAX_VIEWPORT_DIMS.
  gfx::Size ClampedCanvasSize() const;

  // First time called, if EXT_draw_buffers is supported, query the value;
  // otherwise return 0.  Later, return the cached value.
  GLint MaxDrawBuffers();
  GLint MaxColorAttachments();

  void SetBackDrawBuffer(GLenum);
  void SetFramebuffer(GLenum, WebGLFramebuffer*);

  virtual void RestoreCurrentFramebuffer();
  void RestoreCurrentTexture2D();
  void RestoreCurrentTexture2DArray();
  void RestoreCurrentTextureCubeMap();

  void FindNewMaxNonDefaultTextureUnit();

  virtual void RenderbufferStorageImpl(GLenum target,
                                       GLsizei samples,
                                       GLenum internalformat,
                                       GLsizei width,
                                       GLsizei height,
                                       const char* function_name);

  friend class WebGLStateRestorer;
  friend class WebGLRenderingContextEvictionManager;

  static void ActivateContext(WebGLRenderingContextBase*);
  static void DeactivateContext(WebGLRenderingContextBase*);
  static void AddToEvictedList(WebGLRenderingContextBase*);
  static void RemoveFromEvictedList(WebGLRenderingContextBase*);
  static void RestoreEvictedContext(WebGLRenderingContextBase*);
  static void ForciblyLoseOldestContext(const String& reason);
  // Return the least recently used context's position in the active context
  // vector.  If the vector is empty, return the maximum allowed active context
  // number.
  static WebGLRenderingContextBase* OldestContext();
  static WebGLRenderingContextBase* OldestEvictedContext();

  friend class ScopedRGBEmulationColorMask;
  unsigned active_scoped_rgb_emulation_color_masks_;

  ImageBitmap* TransferToImageBitmapBase(ScriptState*, ExceptionState&);

  // Helper functions for tex(Sub)Image2D && texSubImage3D
  void TexImageHelperDOMArrayBufferView(TexImageParams params,
                                        DOMArrayBufferView*,
                                        NullDisposition,
                                        int64_t src_offset);
  void TexImageHelperImageData(TexImageParams, ImageData*);

  void TexImageHelperHTMLImageElement(const SecurityOrigin*,
                                      const TexImageParams& params,
                                      HTMLImageElement*,
                                      ExceptionState&);

  void DrawElementImage(scoped_refptr<Image> image,
                        TexImageParams params,
                        ExceptionState& exception_state);

  void TexImageHelperCanvasRenderingContextHost(const SecurityOrigin*,
                                                TexImageParams params,
                                                CanvasRenderingContextHost*,
                                                ExceptionState&);

  void TexImageHelperHTMLVideoElement(const SecurityOrigin*,
                                      TexImageParams,
                                      HTMLVideoElement*,
                                      ExceptionState&);

  void TexImageHelperVideoFrame(const SecurityOrigin*,
                                TexImageParams,
                                VideoFrame*,
                                ExceptionState&);

  void TexImageHelperImageBitmap(TexImageParams params,
                                 ImageBitmap*,
                                 ExceptionState&);
  static const char* GetTexImageFunctionName(TexImageFunctionID);
  static TexImageFunctionType GetTexImageFunctionType(TexImageFunctionID);
  gfx::Rect SafeGetImageSize(Image*);
  gfx::Rect GetImageDataSize(ImageData*);

  // Helper implementing readPixels for WebGL 1.0 and 2.0.
  void ReadPixelsHelper(GLint x,
                        GLint y,
                        GLsizei width,
                        GLsizei height,
                        GLenum format,
                        GLenum type,
                        DOMArrayBufferView* pixels,
                        int64_t offset);

  void RecordANGLEImplementation();

 private:
  WebGLRenderingContextBase(CanvasRenderingContextHost*,
                            scoped_refptr<base::SingleThreadTaskRunner>,
                            std::unique_ptr<WebGraphicsContext3DProvider>,
                            const Platform::GraphicsInfo& graphics_info,
                            const CanvasContextCreationAttributesCore&,
                            Platform::ContextType);
  static std::unique_ptr<WebGraphicsContext3DProvider>
  CreateContextProviderInternal(CanvasRenderingContextHost*,
                                const CanvasContextCreationAttributesCore&,
                                Platform::ContextType context_type,
                                Platform::GraphicsInfo* graphics_info);

  CanvasResourceProvider* PaintRenderingResultsToCanvasInternal(
      SourceDrawingBuffer source_buffer,
      bool& resource_provider_was_updated);
  void TexImageHelperMediaVideoFrame(
      TexImageParams,
      WebGLTexture*,
      scoped_refptr<media::VideoFrame> media_video_frame,
      media::PaintCanvasVideoRenderer* video_renderer);

  // Copy from the source directly to texture target specified by `params` via
  // the gpu, without a read-back to system memory. Source can be an
  // AcceleratedStaticBitmapImage or WebGLRenderingContextBase.
  void TexImageViaGPU(TexImageParams,
                      AcceleratedStaticBitmapImage*,
                      WebGLRenderingContextBase*);
  bool CanUseTexImageViaGPU(const TexImageParams&);

  const Platform::ContextType context_type_;

  bool IsPaintable() const final { return GetDrawingBuffer(); }

  void HoldReferenceToDrawingBuffer(DrawingBuffer*);

  static void InitializeWebGLContextLimits(
      WebGraphicsContext3DProvider* context_provider);
  static unsigned CurrentMaxGLContexts();

  void RecordIdentifiableGLParameterDigest(GLenum pname,
                                           IdentifiableToken value);

  void RecordShaderPrecisionFormatForStudy(GLenum shader_type,
                                           GLenum precision_type,
                                           WebGLShaderPrecisionFormat* format);

  // PushFrameWithCopy will make a potential copy if the resource is accelerated
  // or a drawImage if the resource is non accelerated.
  bool PushFrameWithCopy();
  // PushFrameNoCopy will try and export the content of the DrawingBuffer as a
  // ExtenralCanvasResource.
  bool PushFrameNoCopy();

  // Returns true if the given element can be used in a texElement2D call.
  // Return false and adds relevant exceptions to `exception_state` if that's
  // not the case.
  bool IsDrawElementEligible(Element* element,
                             GLenum target,
                             ExceptionState& exception_state);

  static bool webgl_context_limits_initialized_;
  static unsigned max_active_webgl_contexts_;
  static unsigned max_active_webgl_contexts_on_worker_;

  void addProgramCompletionQuery(WebGLProgram* program, GLuint query);
  void clearProgramCompletionQueries();
  bool checkProgramCompletionQueryAvailable(WebGLProgram* program,
                                            bool* completed);
  static constexpr unsigned int kMaxProgramCompletionQueries = 128u;

  // Support for KHR_parallel_shader_compile.
  //
  // TODO(crbug.com/1474141): once a HeapLinkedHashMap is available,
  // convert these two fields to use that instead.
  HeapVector<Member<WebGLProgram>> program_completion_query_list_;
  HeapHashMap<Member<WebGLProgram>, GLuint> program_completion_query_map_;

  int number_of_user_allocated_multisampled_renderbuffers_;

  bool has_been_drawn_to_ = false;

  uint32_t number_of_context_losses_ = 0;

  // Tracks if the context has ever called glBeginPixelLocalStorageANGLE. If it
  // has, we need to start using the pixel local storage interrupt mechanism
  // when we take over the client's context.
  bool has_activated_pixel_local_storage_ = false;

  PredefinedColorSpace drawing_buffer_color_space_ =
      PredefinedColorSpace::kSRGB;
  PredefinedColorSpace unpack_color_space_ = PredefinedColorSpace::kSRGB;
};

template <>
struct DowncastTraits<WebGLRenderingContextBase> {
  static bool AllowFrom(const CanvasRenderingContext& context) {
    return context.IsWebGL();
  }
};

}  // namespace blink

WTF_ALLOW_MOVE_INIT_AND_COMPARE_WITH_MEM_FUNCTIONS(
    blink::WebGLRenderingContextBase::TextureUnitState)

#endif  // THIRD_PARTY_BLINK_RENDERER_MODULES_WEBGL_WEBGL_RENDERING_CONTEXT_BASE_H_