summaryrefslogtreecommitdiffstats
path: root/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.h
blob: 201fc75d60efc86e33b35d98178ec48df7cc61e8 (plain)
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
/*
 * 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 WebGLRenderingContextBase_h
#define WebGLRenderingContextBase_h

#include "bindings/core/v8/Nullable.h"
#include "bindings/core/v8/ScriptState.h"
#include "bindings/core/v8/ScriptValue.h"
#include "bindings/core/v8/ScriptWrappable.h"
#include "core/CoreExport.h"
#include "core/dom/DOMTypedArray.h"
#include "core/dom/TypedFlexibleArrayBufferView.h"
#include "core/html/canvas/CanvasRenderingContext.h"
#include "core/layout/LayoutBoxModelObject.h"
#include "core/page/Page.h"
#include "modules/webgl/WebGLContextAttributes.h"
#include "modules/webgl/WebGLExtensionName.h"
#include "modules/webgl/WebGLTexture.h"
#include "modules/webgl/WebGLVertexArrayObjectBase.h"
#include "platform/Timer.h"
#include "platform/graphics/GraphicsTypes3D.h"
#include "platform/graphics/ImageBuffer.h"
#include "platform/graphics/gpu/DrawingBuffer.h"
#include "platform/graphics/gpu/Extensions3DUtil.h"
#include "platform/graphics/gpu/WebGLImageConversion.h"
#include "public/platform/WebGraphicsContext3D.h"
#include "wtf/OwnPtr.h"
#include "wtf/text/WTFString.h"

#include <set>

namespace blink {
class WebLayer;
}

namespace blink {

class ANGLEInstancedArrays;
class CHROMIUMSubscribeUniform;
class CHROMIUMValuebuffer;
class EXTBlendMinMax;
class EXTDisjointTimerQuery;
class EXTFragDepth;
class EXTShaderTextureLOD;
class EXTsRGB;
class EXTTextureFilterAnisotropic;
class ExceptionState;
class HTMLImageElement;
class HTMLVideoElement;
class ImageBuffer;
class ImageData;
class IntSize;
class OESElementIndexUint;
class OESStandardDerivatives;
class OESTextureFloat;
class OESTextureFloatLinear;
class OESTextureHalfFloat;
class OESTextureHalfFloatLinear;
class OESVertexArrayObject;
class WebGLActiveInfo;
class WebGLBuffer;
class WebGLCompressedTextureASTC;
class WebGLCompressedTextureATC;
class WebGLCompressedTextureETC1;
class WebGLCompressedTexturePVRTC;
class WebGLCompressedTextureS3TC;
class WebGLContextGroup;
class WebGLContextObject;
class WebGLDebugRendererInfo;
class WebGLDebugShaders;
class WebGLDepthTexture;
class WebGLDrawBuffers;
class WebGLExtension;
class WebGLFramebuffer;
class WebGLLoseContext;
class WebGLObject;
class WebGLProgram;
class WebGLRenderbuffer;
class WebGLShader;
class WebGLShaderPrecisionFormat;
class WebGLSharedObject;
class WebGLUniformLocation;
class WebGLVertexArrayObjectBase;

class WebGLRenderingContextLostCallback;
class WebGLRenderingContextErrorMessageCallback;

struct FormatType {
    GLenum internalformat;
    GLenum format;
    GLenum type;
};

struct FormatTypeCompare {
    bool operator() (const FormatType& lhs, const FormatType& rhs) const
    {
        return (lhs.internalformat < rhs.internalformat
            || ((lhs.internalformat == rhs.internalformat) && (lhs.format < rhs.format))
            || ((lhs.internalformat == rhs.internalformat) && (lhs.format == rhs.format) && (lhs.type < rhs.type)));
    }
};

// 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.
class ScopedDrawingBufferBinder {
    STACK_ALLOCATED();
public:
    ScopedDrawingBufferBinder(DrawingBuffer* drawingBuffer, WebGLFramebuffer* framebufferBinding)
        : m_drawingBuffer(drawingBuffer)
        , m_readFramebufferBinding(framebufferBinding)
    {
        // Commit DrawingBuffer if needed (e.g., for multisampling)
        if (!m_readFramebufferBinding && m_drawingBuffer)
            m_drawingBuffer->commit();
    }

    ~ScopedDrawingBufferBinder()
    {
        // Restore DrawingBuffer if needed
        if (!m_readFramebufferBinding && m_drawingBuffer)
            m_drawingBuffer->restoreFramebufferBindings();
    }

private:
    DrawingBuffer* m_drawingBuffer;
    Member<WebGLFramebuffer> m_readFramebufferBinding;
};

class MODULES_EXPORT WebGLRenderingContextBase : public CanvasRenderingContext, public Page::MultisamplingChangedObserver {
    WILL_BE_USING_GARBAGE_COLLECTED_MIXIN(WebGLRenderingContextBase);
public:
    ~WebGLRenderingContextBase() override;

    virtual unsigned version() const = 0;
    virtual String contextName() const = 0;
    virtual void registerContextExtensions() = 0;

    virtual void initializeNewContext();

    static unsigned getWebGLVersion(const CanvasRenderingContext*);

    static PassOwnPtr<WebGraphicsContext3D> createWebGraphicsContext3D(HTMLCanvasElement*, WebGLContextAttributes, unsigned webGLVersion);
    static void forceNextWebGLContextCreationToFail();

    int drawingBufferWidth() const;
    int drawingBufferHeight() const;

    void activeTexture(GLenum texture);
    void attachShader(ScriptState*, WebGLProgram*, WebGLShader*);
    void bindAttribLocation(WebGLProgram*, GLuint index, const String& name);
    void bindBuffer(ScriptState*, GLenum target, WebGLBuffer*);
    virtual void bindFramebuffer(ScriptState*, GLenum target, WebGLFramebuffer*);
    void bindRenderbuffer(ScriptState*, GLenum target, WebGLRenderbuffer*);
    void bindTexture(ScriptState*, GLenum target, WebGLTexture*);
    void blendColor(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
    void blendEquation(GLenum mode);
    void blendEquationSeparate(GLenum modeRGB, GLenum modeAlpha);
    void blendFunc(GLenum sfactor, GLenum dfactor);
    void blendFuncSeparate(GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha);

    void bufferData(GLenum target, long long size, GLenum usage);
    void bufferData(GLenum target, DOMArrayBuffer* data, GLenum usage);
    void bufferData(GLenum target, DOMArrayBufferView* data, GLenum usage);
    void bufferSubData(GLenum target, long long offset, DOMArrayBuffer* data);
    void bufferSubData(GLenum target, long long offset, const FlexibleArrayBufferView& 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, DOMArrayBufferView* data);
    void compressedTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, 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 zNear, GLfloat zFar);
    void detachShader(ScriptState*, 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, long long offset);

    void drawArraysInstancedANGLE(GLenum mode, GLint first, GLsizei count, GLsizei primcount);
    void drawElementsInstancedANGLE(GLenum mode, GLsizei count, GLenum type, long long offset, GLsizei primcount);

    void enable(GLenum cap);
    void enableVertexAttribArray(GLuint index);
    void finish();
    void flush();
    void framebufferRenderbuffer(ScriptState*, GLenum target, GLenum attachment, GLenum renderbuffertarget, WebGLRenderbuffer*);
    void framebufferTexture2D(ScriptState*, 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>>&);
    Nullable<HeapVector<Member<WebGLShader>>> getAttachedShaders(WebGLProgram*);
    GLint getAttribLocation(WebGLProgram*, const String& name);
    ScriptValue getBufferParameter(ScriptState*, GLenum target, GLenum pname);
    void getContextAttributes(Nullable<WebGLContextAttributes>&);
    GLenum getError();
    ScriptValue 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 shaderType, GLenum precisionType);
    String getShaderSource(WebGLShader*);
    Nullable<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);
    long long getVertexAttribOffset(GLuint index, GLenum pname);

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

    void lineWidth(GLfloat);
    void linkProgram(WebGLProgram*);
    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, 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, GLenum internalformat,
        GLsizei width, GLsizei height, GLint border,
        GLenum format, GLenum type, DOMArrayBufferView*);
    void texImage2D(GLenum target, GLint level, GLenum internalformat,
        GLenum format, GLenum type, ImageData*);
    void texImage2D(GLenum target, GLint level, GLenum internalformat,
        GLenum format, GLenum type, HTMLImageElement*, ExceptionState&);
    void texImage2D(GLenum target, GLint level, GLenum internalformat,
        GLenum format, GLenum type, HTMLCanvasElement*, ExceptionState&);
    void texImage2D(GLenum target, GLint level, GLenum internalformat,
        GLenum format, GLenum type, HTMLVideoElement*, ExceptionState&);

    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, DOMArrayBufferView*);
    void texSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset,
        GLenum format, GLenum type, ImageData*);
    void texSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset,
        GLenum format, GLenum type, HTMLImageElement*, ExceptionState&);
    void texSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset,
        GLenum format, GLenum type, HTMLCanvasElement*, ExceptionState&);
    void texSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset,
        GLenum format, GLenum type, HTMLVideoElement*, ExceptionState&);

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

    void useProgram(ScriptState*, WebGLProgram*);
    void validateProgram(WebGLProgram*);

    void vertexAttrib1f(GLuint index, GLfloat x);
    void vertexAttrib1fv(GLuint index, const DOMFloat32Array* values);
    void vertexAttrib1fv(GLuint index, const Vector<GLfloat>& values);
    void vertexAttrib2f(GLuint index, GLfloat x, GLfloat y);
    void vertexAttrib2fv(GLuint index, const DOMFloat32Array* values);
    void vertexAttrib2fv(GLuint index, const Vector<GLfloat>& values);
    void vertexAttrib3f(GLuint index, GLfloat x, GLfloat y, GLfloat z);
    void vertexAttrib3fv(GLuint index, const DOMFloat32Array* values);
    void vertexAttrib3fv(GLuint index, const Vector<GLfloat>& values);
    void vertexAttrib4f(GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
    void vertexAttrib4fv(GLuint index, const DOMFloat32Array* values);
    void vertexAttrib4fv(GLuint index, const Vector<GLfloat>& values);
    void vertexAttribPointer(ScriptState*, GLuint index, GLint size, GLenum type, GLboolean normalized,
        GLsizei stride, long long 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.
        Manual,

        // Restore when resources are available.
        WhenAvailable,

        // Restore as soon as possible.
        Auto
    };
    void loseContext(LostContextMode) override;
    void forceLostContext(LostContextMode, AutoRecoveryMethod);
    void forceRestoreContext();
    void loseContextImpl(LostContextMode, AutoRecoveryMethod);

    WebGraphicsContext3D* webContext() const { return drawingBuffer()->context(); }
    WebGLContextGroup* contextGroup() const { return m_contextGroup.get(); }
    Extensions3DUtil* extensionsUtil();

    void reshape(int width, int height) override;

    void markLayerComposited() override;
    ImageData* paintRenderingResultsToImageData(SourceDrawingBuffer) override;

    void removeSharedObject(WebGLSharedObject*);
    void removeContextObject(WebGLContextObject*);

    unsigned maxVertexAttribs() const { return m_maxVertexAttribs; }

    // GL_CHROMIUM_subscribe_uniform
    CHROMIUMValuebuffer* createValuebufferCHROMIUM();
    void deleteValuebufferCHROMIUM(CHROMIUMValuebuffer*);
    GLboolean isValuebufferCHROMIUM(CHROMIUMValuebuffer*);
    void bindValuebufferCHROMIUM(GLenum target, CHROMIUMValuebuffer*);
    void subscribeValueCHROMIUM(GLenum target, GLenum subscription);
    void populateSubscribedValuesCHROMIUM(GLenum target);
    void uniformValuebufferCHROMIUM(const WebGLUniformLocation*, GLenum target, GLenum subscription);

    // Eagerly finalize WebGLRenderingContextBase in order for it
    // to (first) be able to detach its WebGLContextObjects, before
    // they're later swept and finalized.
    EAGERLY_FINALIZE();
    DECLARE_VIRTUAL_TRACE();

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

    class TextureUnitState {
        DISALLOW_NEW_EXCEPT_PLACEMENT_NEW();
    public:
        Member<WebGLTexture> m_texture2DBinding;
        Member<WebGLTexture> m_textureCubeMapBinding;
        Member<WebGLTexture> m_texture3DBinding;
        Member<WebGLTexture> m_texture2DArrayBinding;

        DECLARE_TRACE();
    };

    void setFilterQuality(SkFilterQuality) override;
    bool isWebGL2OrHigher() { return version() >= 2; }

protected:
    friend class EXTDisjointTimerQuery;
    friend class WebGLDrawBuffers;
    friend class WebGLFramebuffer;
    friend class WebGLObject;
    friend class WebGLContextObject;
    friend class OESVertexArrayObject;
    friend class WebGLDebugShaders;
    friend class WebGLCompressedTextureASTC;
    friend class WebGLCompressedTextureATC;
    friend class WebGLCompressedTextureETC1;
    friend class WebGLCompressedTexturePVRTC;
    friend class WebGLCompressedTextureS3TC;
    friend class WebGLRenderingContextErrorMessageCallback;
    friend class WebGLVertexArrayObjectBase;
    friend class ScopedTexture2DRestorer;
    friend class ScopedFramebufferRestorer;

    WebGLRenderingContextBase(HTMLCanvasElement*, PassOwnPtr<WebGraphicsContext3D>, const WebGLContextAttributes&);
    PassRefPtr<DrawingBuffer> createDrawingBuffer(PassOwnPtr<WebGraphicsContext3D>);
    void setupFlags();

    // CanvasRenderingContext implementation.
    bool is3d() const override { return true; }
    bool isAccelerated() const override { return true; }
    void setIsHidden(bool) override;
    bool paintRenderingResultsToCanvas(SourceDrawingBuffer) override;
    WebLayer* platformLayer() const override;
    void stop() override;

    void addSharedObject(WebGLSharedObject*);
    void addContextObject(WebGLContextObject*);
    void detachAndRemoveAllObjects();

    void destroyContext();
    void markContextChanged(ContentChangeType);

    // Query if the context is NPOT strict.
    bool isNPOTStrict() { return !isWebGL2OrHigher(); }
    // Query if depth_stencil buffer is supported.
    bool isDepthStencilSupported() { return m_isDepthStencilSupported; }

    // Helper to return the size in bytes of OpenGL data types
    // like GL_FLOAT, GL_INT, etc.
    unsigned sizeInBytes(GLenum type);

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

    bool validateWebGLObject(const char*, WebGLObject*);

    // Adds a compressed texture format.
    void addCompressedTextureFormat(GLenum);
    void removeAllCompressedTextureFormats();

    PassRefPtr<Image> drawImageIntoBuffer(PassRefPtr<Image>, int width, int height, const char* functionName);

    PassRefPtr<Image> videoFrameToImage(HTMLVideoElement*);

    WebGLRenderbuffer* ensureEmulatedStencilBuffer(GLenum target, WebGLRenderbuffer*);

    // Structure for rendering to a DrawingBuffer, instead of directly
    // to the back-buffer of m_context.
    RefPtr<DrawingBuffer> m_drawingBuffer;
    DrawingBuffer* drawingBuffer() const;

    RefPtr<WebGLContextGroup> m_contextGroup;

    LostContextMode m_contextLostMode;
    AutoRecoveryMethod m_autoRecoveryMethod;
    // 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.
    Timer<WebGLRenderingContextBase> m_dispatchContextLostEventTimer;
    bool m_restoreAllowed;
    Timer<WebGLRenderingContextBase> m_restoreTimer;

    bool m_markedCanvasDirty;
#if ENABLE(OILPAN)
    HeapHashSet<WeakMember<WebGLContextObject>> m_contextObjects;
#else
    // The hash set isn't traced, hence the references are effectively
    // weakly kept. Each WebGLContextObject is responsible for detaching
    // itself upon finalization if the WebGLRenderingContextBase hasn't been
    // finalized already and detached them via detachAndRemoveAllObjects().
    // See http://crbug.com/534524 for the details.
    HashSet<UntracedMember<WebGLContextObject>> m_contextObjects;
#endif

    PersistentWillBeMember<WebGLRenderingContextLostCallback> m_contextLostCallbackAdapter;
    PersistentWillBeMember<WebGLRenderingContextErrorMessageCallback> m_errorMessageCallbackAdapter;

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

    PersistentWillBeMember<WebGLVertexArrayObjectBase> m_defaultVertexArrayObject;
    PersistentWillBeMember<WebGLVertexArrayObjectBase> m_boundVertexArrayObject;
    bool m_preservedDefaultVAOObjectWrapper;
    void setBoundVertexArrayObject(ScriptState*, WebGLVertexArrayObjectBase*);

    enum VertexAttribValueType {
        Float32ArrayType,
        Int32ArrayType,
        Uint32ArrayType,
    };

    class VertexAttribValue {
    public:
        VertexAttribValue()
            : type(Float32ArrayType)
        {
            initValue();
        }

        void initValue()
        {
            value.floatValue[0] = 0.0f;
            value.floatValue[1] = 0.0f;
            value.floatValue[2] = 0.0f;
            value.floatValue[3] = 1.0f;
        }

        VertexAttribValueType type;
        union {
            GLfloat floatValue[4];
            GLint intValue[4];
            GLuint uintValue[4];
        } value;
    };
    Vector<VertexAttribValue> m_vertexAttribValue;
    unsigned m_maxVertexAttribs;
    PersistentWillBeMember<WebGLBuffer> m_vertexAttrib0Buffer;
    long m_vertexAttrib0BufferSize;
    GLfloat m_vertexAttrib0BufferValue[4];
    bool m_forceAttrib0BufferRefill;
    bool m_vertexAttrib0UsedBefore;

    PersistentWillBeMember<WebGLProgram> m_currentProgram;
    PersistentWillBeMember<WebGLFramebuffer> m_framebufferBinding;
    PersistentWillBeMember<WebGLRenderbuffer> m_renderbufferBinding;
    PersistentWillBeMember<CHROMIUMValuebuffer> m_valuebufferBinding;

    PersistentHeapVectorWillBeHeapVector<TextureUnitState> m_textureUnits;
    unsigned long m_activeTextureUnit;

    PersistentWillBeMember<WebGLTexture> m_blackTexture2D;
    PersistentWillBeMember<WebGLTexture> m_blackTextureCubeMap;

    Vector<GLenum> m_compressedTextureFormats;

    // Fixed-size cache of reusable image buffers for video texImage2D calls.
    class LRUImageBufferCache {
    public:
        LRUImageBufferCache(int capacity);
        // The pointer returned is owned by the image buffer map.
        ImageBuffer* imageBuffer(const IntSize&);
    private:
        void bubbleToFront(int idx);
        OwnPtr<OwnPtr<ImageBuffer>[]> m_buffers;
        int m_capacity;
    };
    LRUImageBufferCache m_generatedImageCache;

    GLint m_maxTextureSize;
    GLint m_maxCubeMapTextureSize;
    GLint m_max3DTextureSize;
    GLint m_maxRenderbufferSize;
    GLint m_maxViewportDims[2];
    GLint m_maxTextureLevel;
    GLint m_maxCubeMapTextureLevel;
    GLint m_max3DTextureLevel;

    GLint m_maxDrawBuffers;
    GLint m_maxColorAttachments;
    GLenum m_backDrawBuffer;
    bool m_drawBuffersWebGLRequirementsChecked;
    bool m_drawBuffersSupported;

    GLenum m_readBufferOfDefaultFramebuffer;

    GLint m_packAlignment;
    GLint m_unpackAlignment;
    bool m_unpackFlipY;
    bool m_unpackPremultiplyAlpha;
    GLenum m_unpackColorspaceConversion;
    WebGLContextAttributes m_requestedAttributes;

    GLfloat m_clearColor[4];
    bool m_scissorEnabled;
    GLfloat m_clearDepth;
    GLint m_clearStencil;
    GLboolean m_colorMask[4];
    GLboolean m_depthMask;

    bool m_stencilEnabled;
    GLuint m_stencilMask, m_stencilMaskBack;
    GLint m_stencilFuncRef, m_stencilFuncRefBack; // Note that these are the user specified values, not the internal clamped value.
    GLuint m_stencilFuncMask, m_stencilFuncMaskBack;

    bool m_isDepthStencilSupported;

    bool m_synthesizedErrorsToConsole;
    int m_numGLErrorsToConsoleAllowed;

    bool m_multisamplingAllowed;
    bool m_multisamplingObserverRegistered;

    unsigned long m_onePlusMaxNonDefaultTextureUnit;

    OwnPtr<Extensions3DUtil> m_extensionsUtil;

    enum ExtensionFlags {
        ApprovedExtension               = 0x00,
        // Extension that is behind the draft extensions runtime flag:
        DraftExtension                  = 0x01,
    };

    class ExtensionTracker : public GarbageCollected<ExtensionTracker> {
    public:
        ExtensionTracker(ExtensionFlags flags, const char* const* prefixes)
            : m_draft(flags & DraftExtension)
            , m_prefixes(prefixes)
        {
        }

        bool draft() const
        {
            return m_draft;
        }

        const char* const* prefixes() const;
        bool matchesNameWithPrefixes(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;

        DEFINE_INLINE_VIRTUAL_TRACE() { }

    private:
        bool m_draft;
        const char* const* m_prefixes;
    };

    template <typename T>
    class TypedExtensionTracker final : public ExtensionTracker {
    public:
        static TypedExtensionTracker<T>* create(PersistentWillBeMember<T>& extensionField, ExtensionFlags flags, const char* const* prefixes)
        {
            return new TypedExtensionTracker<T>(extensionField, flags, prefixes);
        }

        WebGLExtension* getExtension(WebGLRenderingContextBase* context) override
        {
            if (!m_extension) {
                m_extension = T::create(context);
                m_extensionField = m_extension;
            }

            return m_extension;
        }

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

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

        void loseExtension(bool force) override
        {
            if (m_extension) {
                m_extension->lose(force);
                if (m_extension->isLost())
                    m_extension = nullptr;
            }
        }

        DEFINE_INLINE_VIRTUAL_TRACE()
        {
            visitor->trace(m_extension);
            ExtensionTracker::trace(visitor);
        }

    private:
        TypedExtensionTracker(PersistentWillBeMember<T>& extensionField, ExtensionFlags flags, const char* const* prefixes)
            : ExtensionTracker(flags, prefixes)
            , m_extensionField(extensionField)
        {
        }

        GC_PLUGIN_IGNORE("http://crbug.com/519953")
        PersistentWillBeMember<T>& m_extensionField;
        // 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> m_extension;
    };

    bool m_extensionEnabled[WebGLExtensionNameCount];
    PersistentHeapVectorWillBeHeapVector<Member<ExtensionTracker>> m_extensions;

    template <typename T>
    void registerExtension(PersistentWillBeMember<T>& extensionPtr, ExtensionFlags flags = ApprovedExtension, const char* const* prefixes = nullptr)
    {
        m_extensions.append(TypedExtensionTracker<T>::create(extensionPtr, flags, prefixes));
    }

    bool extensionSupportedAndAllowed(const ExtensionTracker*);

    inline bool extensionEnabled(WebGLExtensionName name)
    {
        return m_extensionEnabled[name];
    }

    // 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.
    class ScopedDrawingBufferBinder {
        STACK_ALLOCATED();
    public:
        ScopedDrawingBufferBinder(DrawingBuffer* drawingBuffer, WebGLFramebuffer* framebufferBinding)
            : m_drawingBuffer(drawingBuffer)
            , m_readFramebufferBinding(framebufferBinding)
        {
            // Commit DrawingBuffer if needed (e.g., for multisampling)
            if (!m_readFramebufferBinding && m_drawingBuffer)
                m_drawingBuffer->commit();
        }

        ~ScopedDrawingBufferBinder()
        {
            // Restore DrawingBuffer if needed
            if (!m_readFramebufferBinding && m_drawingBuffer)
                m_drawingBuffer->restoreFramebufferBindings();
        }

    private:
        DrawingBuffer* m_drawingBuffer;
        Member<WebGLFramebuffer> m_readFramebufferBinding;
    };

    // Errors raised by synthesizeGLError() while the context is lost.
    Vector<GLenum> m_lostContextErrors;

    bool m_isWebGL2FormatsTypesAdded;
    bool m_isOESTextureFloatFormatsTypesAdded;
    bool m_isOESTextureHalfFloatFormatsTypesAdded;
    bool m_isWebGLDepthTextureFormatsTypesAdded;
    bool m_isEXTsRGBFormatsTypesAdded;

    std::set<GLenum> m_supportedInternalFormats;
    std::set<GLenum> m_supportedFormats;
    std::set<GLenum> m_supportedTypes;
    std::set<FormatType, FormatTypeCompare> m_supportedFormatTypeCombinations;

    // 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.
        Skipped,
        // Clear the backbuffer.
        JustClear,
        // Combine webgl.clear() API with the backbuffer clear, so webgl.clear()
        // doesn't have to call glClear() again.
        CombinedClear
    };
    HowToClear clearIfComposited(GLbitfield clearMask = 0);

    // Helper to restore state that clearing the framebuffer may destroy.
    void restoreStateAfterClear();

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

    void texImage2DBase(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void* pixels);
    void texImage2DImpl(GLenum target, GLint level, GLenum internalformat, GLenum format, GLenum type, Image*, WebGLImageConversion::ImageHtmlDomSource, bool flipY, bool premultiplyAlpha);
    void texSubImage2DBase(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void* pixels);
    void texSubImage2DImpl(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLenum format, GLenum type, Image*, WebGLImageConversion::ImageHtmlDomSource, bool flipY, bool premultiplyAlpha);

    enum TexImageFunctionType {
        NotTexSubImage2D,
        TexSubImage2D
    };
    enum TexImageByGPUType {
        TexImage2DByGPU,
        TexSubImage2DByGPU,
        TexSubImage3DByGPU
    };
    // Copy from the canvas element directly to the texture via the GPU, without a read-back to system memory.
    void texImageCanvasByGPU(TexImageByGPUType, WebGLTexture*, GLenum target, GLint level,
        GLenum internalformat, GLenum type, GLint xoffset, GLint yoffset, GLint zoffset, HTMLCanvasElement*);
    bool canUseTexImageCanvasByGPU(GLenum internalformat, GLenum type);

    void handleTextureCompleteness(const char*, bool);
    void createFallbackBlackTextures1x1();

    // 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 texInternalFormat, GLenum colorBufferFormat);

    // Helper function to get the bound framebuffer's color buffer format.
    virtual GLenum boundFramebufferColorFormat();

    // Helper function to verify limits on the length of uniform and attribute locations.
    virtual unsigned getMaxWebGLLocationLength() const { return 256; }
    bool validateLocationLength(const char* functionName, 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* functionName, GLint x, GLint y, GLint z = 0);

    // 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* functionName, const String&);

    // Helper function to check 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.
    virtual WebGLTexture* validateTextureBinding(const char* functionName, GLenum target, bool useSixEnumsForCubeMap);

    // Helper function to check input internalformat/format/type for functions {copy}Tex{Sub}Image.
    // Generates GL error and returns false if parameters are invalid.
    bool validateTexFuncFormatAndType(const char* functionName, GLenum internalformat, GLenum format, GLenum type, GLint level);

    // Helper function to check readbuffer validity for readPixels and copyTex{Sub}Image.
    // If yes, obtains the readbuffer's format, type, the bound read framebuffer, returns true.
    // If not, generates a GL error, returns false.
    // Note: it's OK to pass format == nullptr and type == nullptr.
    bool validateReadBufferAndGetInfo(const char* functionName, WebGLFramebuffer*& readFramebufferBinding, GLenum* format, GLenum* type);

    // Helper function to check format/type enums for readPixels.
    // Generates INVALID_ENUM and returns false if parameters are invalid.
    virtual bool validateReadPixelsFormatAndType(GLenum format, GLenum type);

    // Helper function to get expected ArrayBuffer view type for readPixels.
    virtual DOMArrayBufferView::ViewType readPixelsExpectedArrayBufferViewType(GLenum type);

    // Helper function to check format/type combination for readPixels.
    // Generates INVALID_OPERATION and returns false if the combination is unsupported.
    bool validateReadPixelsFormatTypeCombination(GLenum format, GLenum type, GLenum readBufferInternalFormat, GLenum readBufferType);

    // 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, long long bufferSize);

    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* functionName, 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* functionName, const char* paramName, long long value);

    enum TexFuncValidationSourceType {
        SourceArrayBufferView,
        SourceImageData,
        SourceHTMLImageElement,
        SourceHTMLCanvasElement,
        SourceHTMLVideoElement,
    };

    // Helper function for tex{Sub}Image2D to check if the input format/type/level/target/width/height/border/xoffset/yoffset are valid.
    // Otherwise, it would return quickly without doing other work.
    bool validateTexFunc(const char* functionName, TexImageFunctionType, TexFuncValidationSourceType, GLenum target, GLint level, GLenum internalformat, GLsizei width,
        GLsizei height, GLint border, GLenum format, GLenum type, GLint xoffset, GLint yoffset);

    // Helper function to check input width and height for functions {copy, compressed}Tex{Sub}Image.
    // Generates GL error and returns false if width or height is invalid.
    bool validateTexFuncDimensions(const char* functionName, 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 char* functionName, TexImageFunctionType, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type);

    enum NullDisposition {
        NullAllowed,
        NullNotAllowed
    };

    // 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 char* functionName, GLint level, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, DOMArrayBufferView* pixels, NullDisposition);

    // Helper function to validate that a copyTexSubImage call is valid.
    bool validateCopyTexSubImage(const char* functionName, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height);

    // 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* functionName, GLenum format);

    // Helper function to validate compressed texture data is correct size
    // for the given format and dimensions.
    bool validateCompressedTexFuncData(const char* functionName, GLsizei width, GLsizei height, GLenum format, DOMArrayBufferView* pixels);

    // Helper function for validating compressed texture formats.
    bool validateCompressedTexFormat(GLenum format);

    // Helper function to validate compressed texture dimensions are valid for
    // the given format.
    bool validateCompressedTexDimensions(const char* functionName, TexImageFunctionType, GLenum target, GLint level, GLsizei width, GLsizei height, GLenum format);

    // Helper function to validate compressed texture dimensions are valid for
    // the given format.
    bool validateCompressedTexSubDimensions(const char* functionName, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, WebGLTexture*);

    // Helper function to validate mode for draw{Arrays/Elements}.
    bool validateDrawMode(const char* functionName, GLenum);

    // Helper function to validate if front/back stencilMask and stencilFunc settings are the same.
    bool validateStencilSettings(const char* functionName);

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

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

    // 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&);

    // 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);

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

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

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

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

    // Helper function to validate input parameters for uniform functions.
    bool validateUniformParameters(const char* functionName, const WebGLUniformLocation*, DOMFloat32Array*, GLsizei mod);
    bool validateUniformParameters(const char* functionName, const WebGLUniformLocation*, DOMInt32Array*, GLsizei mod);
    bool validateUniformParameters(const char* functionName, const WebGLUniformLocation*, void*, GLsizei, GLsizei mod);
    bool validateUniformMatrixParameters(const char* functionName, const WebGLUniformLocation*, GLboolean transpose, DOMFloat32Array*, GLsizei mod);
    bool validateUniformMatrixParameters(const char* functionName, const WebGLUniformLocation*, GLboolean transpose, void*, GLsizei, GLsizei mod);

    template<typename WTFTypedArray>
    bool validateUniformParameters(const char* functionName, const WebGLUniformLocation* location, const TypedFlexibleArrayBufferView<WTFTypedArray>& v, GLsizei requiredMinSize)
    {
        if (!v.dataMaybeOnStack()) {
            synthesizeGLError(GL_INVALID_VALUE, functionName, "no array");
            return false;
        }
        return validateUniformMatrixParameters(functionName, location, false, v.dataMaybeOnStack(), v.length(), requiredMinSize);
    }

    // Helper function to validate the target for bufferData and getBufferParameter.
    virtual bool validateBufferTarget(const char* functionName, 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* functionName, GLenum target);
    // Helper function to validate the usage for bufferData.
    virtual bool validateBufferDataUsage(const char* functionName, GLenum usage);

    virtual bool validateAndUpdateBufferBindTarget(const char* functionName, 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 char* functionName, HTMLImageElement*, ExceptionState&);

    // Helper function for tex{Sub}Image2D to make sure canvas is ready and wouldn't taint Origin.
    bool validateHTMLCanvasElement(const char* functionName, HTMLCanvasElement*, ExceptionState&);

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

    // Helper function to validate drawArrays(Instanced) calls
    bool validateDrawArrays(const char* functionName, GLenum mode, GLint first, GLsizei count);

    // Helper function to validate drawElements(Instanced) calls
    bool validateDrawElements(const char* functionName, GLenum mode, GLsizei count, GLenum type, long long offset);

    // Helper function to validate draw*Instanced calls
    bool validateDrawInstanced(const char* functionName, GLsizei primcount);

    // Helper functions for vertexAttribNf{v}.
    void vertexAttribfImpl(const char* functionName, GLuint index, GLsizei expectedSize, GLfloat, GLfloat, GLfloat, GLfloat);
    void vertexAttribfvImpl(const char* functionName, GLuint index, const DOMFloat32Array*, GLsizei expectedSize);
    void vertexAttribfvImpl(const char* functionName, GLuint index, const GLfloat*, GLsizei, GLsizei expectedSize);

    // Helper functions to bufferData() and bufferSubData().
    void bufferDataImpl(GLenum target, long long size, const void* data, GLenum usage);
    void bufferSubDataImpl(GLenum target, long long offset, GLsizeiptr, const void* data);

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

    // Helper function for bind* (bindBuffer, bindTexture, etc) and useProgram.
    // If the object has already been deleted, set deleted to true upon return.
    // Return false if caller should return without further processing.
    bool checkObjectToBeBound(const char* functionName, WebGLObject*, bool& deleted);

    void dispatchContextLostEvent(Timer<WebGLRenderingContextBase>*);
    // Helper for restoration after context lost.
    void maybeRestoreContext(Timer<WebGLRenderingContextBase>*);

    enum ConsoleDisplayPreference {
        DisplayInConsole,
        DontDisplayInConsole
    };

    // Wrapper for WebGraphicsContext3D::synthesizeGLError that sends a message
    // to the JavaScript console.
    void synthesizeGLError(GLenum, const char* functionName, const char* description, ConsoleDisplayPreference = DisplayInConsole);
    void emitGLWarning(const char* function, const char* reason);

    String ensureNotNull(const String&) const;

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

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

    // Clamp the width and height to GL_MAX_VIEWPORT_DIMS.
    IntSize clampedCanvasSize();

    // 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 multisamplingChanged(bool) override;

    void findNewMaxNonDefaultTextureUnit();

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

    // Ensures that the JavaScript wrappers for objects that are
    // latched into the context's state, or which are implicitly
    // linked together (like programs and their attached shaders), are
    // not garbage collected before they should be.
    static void preserveObjectWrapper(ScriptState*, ScriptWrappable* sourceObject, const char* baseName, unsigned long index, ScriptWrappable* targetObject);
    // Called to lazily instantiate the wrapper for the default VAO
    // during calls to bindBuffer and vertexAttribPointer (from
    // JavaScript).
    void maybePreserveDefaultVAOObjectWrapper(ScriptState*);

    friend class WebGLStateRestorer;
    friend class WebGLRenderingContextEvictionManager;

    static void activateContext(WebGLRenderingContextBase*);
    static void deactivateContext(WebGLRenderingContextBase*);
    static void addToEvictedList(WebGLRenderingContextBase*);
    static void removeFromEvictedList(WebGLRenderingContextBase*);
    static void willDestroyContext(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();
};

DEFINE_TYPE_CASTS(WebGLRenderingContextBase, CanvasRenderingContext, context, context->is3d(), context.is3d());

} // namespace blink

WTF_ALLOW_MOVE_INIT_AND_COMPARE_WITH_MEM_FUNCTIONS(blink::WebGLRenderingContextBase::TextureUnitState);

#endif // WebGLRenderingContextBase_h