xref: /aosp_15_r20/external/skia/src/gpu/ganesh/gl/GrGLCaps.h (revision c8dee2aa9b3f27cf6c858bd81872bdeb2c07ed17)
1 /*
2  * Copyright 2012 Google Inc.
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7 
8 
9 #ifndef GrGLCaps_DEFINED
10 #define GrGLCaps_DEFINED
11 
12 #include "include/gpu/ganesh/GrBackendSurface.h"
13 #include "include/gpu/ganesh/gl/GrGLBackendSurface.h"
14 #include "include/gpu/ganesh/gl/GrGLTypes.h"
15 #include "include/private/base/SkAssert.h"
16 #include "include/private/base/SkTArray.h"
17 #include "include/private/base/SkTDArray.h"
18 #include "include/private/gpu/ganesh/GrTypesPriv.h"
19 #include "src/gpu/Swizzle.h"
20 #include "src/gpu/ganesh/GrCaps.h"
21 #include "src/gpu/ganesh/GrProgramDesc.h"
22 #include "src/gpu/ganesh/gl/GrGLTypesPriv.h"
23 
24 #include <cstdint>
25 #include <memory>
26 #include <vector>
27 
28 class GrGLContextInfo;
29 class GrProgramInfo;
30 class GrRenderTarget;
31 class GrRenderTargetProxy;
32 class GrSurface;
33 class GrSurfaceProxy;
34 class SkJSONWriter;
35 enum class SkTextureCompressionType;
36 struct GrContextOptions;
37 struct GrGLInterface;
38 struct GrShaderCaps;
39 struct SkIRect;
40 struct SkRect;
41 
42 namespace GrTest { struct TestFormatColorTypeCombination; }
43 
44 /**
45  * Stores some capabilities of a GL context. Most are determined by the GL
46  * version and the extensions string. It also tracks formats that have passed
47  * the FBO completeness test.
48  */
49 class GrGLCaps : public GrCaps {
50 public:
51     /**
52      * The type of MSAA for FBOs supported. Different extensions have different
53      * semantics of how / when a resolve is performed.
54      */
55     enum MSFBOType {
56         /**
57          * no support for MSAA FBOs
58          */
59         kNone_MSFBOType = 0,
60         /**
61          * OpenGL 3.0+, OpenGL ES 3.0+, GL_ARB_framebuffer_object,
62          * GL_CHROMIUM_framebuffer_multisample, GL_ANGLE_framebuffer_multisample,
63          * or GL_EXT_framebuffer_multisample
64          */
65         kStandard_MSFBOType,
66         /**
67          * GL_APPLE_framebuffer_multisample ES extension
68          */
69         kES_Apple_MSFBOType,
70         /**
71          * GL_IMG_multisampled_render_to_texture. This variation does not have MSAA renderbuffers.
72          * Instead the texture is multisampled when bound to the FBO and then resolved automatically
73          * when read. It also defines an alternate value for GL_MAX_SAMPLES (which we call
74          * GR_GL_MAX_SAMPLES_IMG).
75          */
76         kES_IMG_MsToTexture_MSFBOType,
77         /**
78          * GL_EXT_multisampled_render_to_texture. Same as the IMG one above but uses the standard
79          * GL_MAX_SAMPLES value.
80          */
81         kES_EXT_MsToTexture_MSFBOType,
82     };
83 
84     enum BlitFramebufferFlags {
85         kNoSupport_BlitFramebufferFlag                    = 1 << 0,
86         kNoScalingOrMirroring_BlitFramebufferFlag         = 1 << 1,
87         kResolveMustBeFull_BlitFrambufferFlag             = 1 << 2,
88         kNoMSAADst_BlitFramebufferFlag                    = 1 << 3,
89         kNoFormatConversion_BlitFramebufferFlag           = 1 << 4,
90         kNoFormatConversionForMSAASrc_BlitFramebufferFlag = 1 << 5,
91         kRectsMustMatchForMSAASrc_BlitFramebufferFlag     = 1 << 6,
92     };
93 
94     enum InvalidateFBType {
95         kNone_InvalidateFBType,
96         kDiscard_InvalidateFBType,     //<! glDiscardFramebuffer()
97         kInvalidate_InvalidateFBType,  //<! glInvalidateFramebuffer()
98     };
99 
100     enum class InvalidateBufferType {
101         kNone,
102         kNullData,   // Call glBufferData with a null data pointer.
103         kInvalidate  // glInvalidateBufferData
104     };
105 
106     enum MapBufferType {
107         kNone_MapBufferType,
108         kMapBuffer_MapBufferType,       // glMapBuffer()
109         kMapBufferRange_MapBufferType,  // glMapBufferRange()
110         kChromium_MapBufferType,        // GL_CHROMIUM_map_sub
111     };
112 
113     enum class TransferBufferType {
114         kNone,
115         kNV_PBO,    // NV_pixel_buffer_object
116         kARB_PBO,   // ARB_pixel_buffer_object
117         kChromium,  // CHROMIUM_pixel_transfer_buffer_object
118     };
119 
120     enum class FenceType {
121         kNone,
122         kSyncObject,
123         kNVFence
124     };
125 
126     enum class MultiDrawType {
127         kNone,
128         kMultiDrawIndirect,  // ARB_multi_draw_indirect, EXT_multi_draw_indirect, or GL 4.3 core.
129         kANGLEOrWebGL  // ANGLE_base_vertex_base_instance or
130                        // WEBGL_draw_instanced_base_vertex_base_instance
131     };
132 
133     enum class RegenerateMipmapType {
134         kBaseLevel,
135         kBasePlusMaxLevel,
136         kBasePlusSync
137     };
138 
139     enum class TimerQueryType {
140         kNone,
141         kRegular,
142         kDisjoint,
143     };
144 
145     /**
146      * Initializes the GrGLCaps to the set of features supported in the current
147      * OpenGL context accessible via ctxInfo.
148      */
149     GrGLCaps(const GrContextOptions& contextOptions, const GrGLContextInfo& ctxInfo,
150              const GrGLInterface* glInterface);
151 
152     bool isFormatSRGB(const GrBackendFormat&) const override;
153 
154     bool isFormatTexturable(const GrBackendFormat&, GrTextureType) const override;
155     bool isFormatTexturable(GrGLFormat) const;
156 
157     bool isFormatAsColorTypeRenderable(GrColorType ct, const GrBackendFormat& format,
158                                        int sampleCount = 1) const override;
159     bool isFormatRenderable(const GrBackendFormat& format, int sampleCount) const override;
isFormatRenderable(GrGLFormat format,int sampleCount)160     bool isFormatRenderable(GrGLFormat format, int sampleCount) const {
161         return sampleCount <= this->maxRenderTargetSampleCount(format);
162     }
163 
getRenderTargetSampleCount(int requestedCount,const GrBackendFormat & format)164     int getRenderTargetSampleCount(int requestedCount,
165                                    const GrBackendFormat& format) const override {
166         return this->getRenderTargetSampleCount(requestedCount,
167                                                 GrBackendFormats::AsGLFormat(format));
168     }
169     int getRenderTargetSampleCount(int requestedCount, GrGLFormat) const;
170 
maxRenderTargetSampleCount(const GrBackendFormat & format)171     int maxRenderTargetSampleCount(const GrBackendFormat& format) const override {
172         return this->maxRenderTargetSampleCount(GrBackendFormats::AsGLFormat(format));
173     }
174     int maxRenderTargetSampleCount(GrGLFormat) const;
175 
maxTextureMaxAnisotropy()176     float maxTextureMaxAnisotropy() const { return fMaxTextureMaxAnisotropy; }
177 
178     bool isFormatCopyable(const GrBackendFormat&) const override;
179 
180     bool canFormatBeFBOColorAttachment(GrGLFormat) const;
181 
getFormatFromColorType(GrColorType colorType)182     GrGLFormat getFormatFromColorType(GrColorType colorType) const {
183         int idx = static_cast<int>(colorType);
184         return fColorTypeToFormatTable[idx];
185     }
186 
187     /**
188      * Gets the internal format to use with glTexImage...() and glTexStorage...(). May be sized or
189      * base depending upon the GL. Not applicable to compressed textures.
190      */
getTexImageOrStorageInternalFormat(GrGLFormat format)191     GrGLenum getTexImageOrStorageInternalFormat(GrGLFormat format) const {
192         return this->getFormatInfo(format).fInternalFormatForTexImageOrStorage;
193     }
194 
195     /**
196      * Gets the external format and type to pass to glTexImage2D with nullptr to create an
197      * uninitialized texture. See getTexImageOrStorageInternalFormat() for the internal format.
198      */
199     void getTexImageExternalFormatAndType(GrGLFormat surfaceFormat, GrGLenum* externalFormat,
200                                           GrGLenum* externalType) const;
201 
202     /**
203      * Given a src data color type and a color type interpretation for a texture of a given format
204      * this provides the external GL format and type to use with glTexSubImage2d. The color types
205      * should originate from supportedWritePixelsColorType().
206      */
207     void getTexSubImageExternalFormatAndType(GrGLFormat surfaceFormat, GrColorType surfaceColorType,
208                                              GrColorType memoryColorType, GrGLenum* externalFormat,
209                                              GrGLenum* externalType) const;
210 
211     /**
212      * Gets the external format, type, and bytes per pixel to use when uploading solid color data
213      * via glTexSubImage...() to clear the texture at creation.
214      */
215     void getTexSubImageDefaultFormatTypeAndColorType(GrGLFormat format,
216                                                      GrGLenum* externalFormat,
217                                                      GrGLenum* externalType,
218                                                      GrColorType* colorType) const;
219 
220     void getReadPixelsFormat(GrGLFormat surfaceFormat, GrColorType surfaceColorType,
221                              GrColorType memoryColorType, GrGLenum* externalFormat,
222                              GrGLenum* externalType) const;
223 
224     /**
225     * Gets an array of legal stencil formats. These formats are not guaranteed
226     * to be supported by the driver but are legal GLenum names given the GL
227     * version and extensions supported.
228     */
stencilFormats()229     const skia_private::TArray<GrGLFormat, true>& stencilFormats() const {
230         return fStencilFormats;
231     }
232 
233     bool formatSupportsTexStorage(GrGLFormat) const;
234 
235     /**
236      * Would it be useful to check GL_IMPLEMENTATION_READ_FORMAT and _TYPE for this format to
237      * detect more efficient glReadPixels arguments?
238      */
239     bool shouldQueryImplementationReadSupport(GrGLFormat format) const;
240 
241     /**
242      * Let caps know the result of GL_IMPLEMENTATION_READ_FORMAT and _TYPE query for a format
243      * to update supported glReadPixels arguments.
244      */
245     void didQueryImplementationReadSupport(GrGLFormat format,
246                                            GrGLenum readFormat,
247                                            GrGLenum readType) const;
248 
249     /**
250      * Gets the internal format to use with glRenderbufferStorageMultisample...(). May be sized or
251      * base depending upon the GL. Not applicable to compressed textures.
252      */
getRenderbufferInternalFormat(GrGLFormat format)253     GrGLenum getRenderbufferInternalFormat(GrGLFormat format) const {
254         return this->getFormatInfo(format).fInternalFormatForRenderbuffer;
255     }
256 
257     /**
258      * Gets the default external type to use with glTex[Sub]Image... when the data pointer is null.
259      */
getFormatDefaultExternalType(GrGLFormat format)260     GrGLenum getFormatDefaultExternalType(GrGLFormat format) const {
261         return this->getFormatInfo(format).fDefaultExternalType;
262     }
263 
264     /**
265      * Has a stencil format index been found for the format (or we've found that no format works).
266      */
hasStencilFormatBeenDeterminedForFormat(GrGLFormat format)267     bool hasStencilFormatBeenDeterminedForFormat(GrGLFormat format) const {
268         return this->getFormatInfo(format).fStencilFormatIndex != FormatInfo::kUnknown_StencilIndex;
269     }
270 
271     /**
272      * Gets the stencil format index for the format. This assumes
273      * hasStencilFormatBeenDeterminedForFormat has already been checked. Returns a value < 0 if
274      * no stencil format is supported with the format. Otherwise, returned index refers to the array
275      * returned by stencilFormats().
276      */
getStencilFormatIndexForFormat(GrGLFormat format)277     int getStencilFormatIndexForFormat(GrGLFormat format) const {
278         SkASSERT(this->hasStencilFormatBeenDeterminedForFormat(format));
279         return this->getFormatInfo(format).fStencilFormatIndex;
280     }
281 
282     /**
283      * If index is >= 0 this records an index into stencilFormats() as the best stencil format for
284      * the format. If < 0 it records that the format has no supported stencil format index.
285      */
286     void setStencilFormatIndexForFormat(GrGLFormat, int index);
287 
288     /**
289      * Reports the type of MSAA FBO support.
290      */
msFBOType()291     MSFBOType msFBOType() const { return fMSFBOType; }
292 
293     /**
294      * Does the preferred MSAA FBO extension have MSAA renderbuffers?
295      */
usesMSAARenderBuffers()296     bool usesMSAARenderBuffers() const {
297         return kNone_MSFBOType != fMSFBOType &&
298                kES_IMG_MsToTexture_MSFBOType != fMSFBOType &&
299                kES_EXT_MsToTexture_MSFBOType != fMSFBOType;
300     }
301 
302     /**
303      * Is it unsupported to only resolve a sub-rectangle of a framebuffer?
304      */
framebufferResolvesMustBeFullSize()305     bool framebufferResolvesMustBeFullSize() const {
306         SkASSERT(fMSFBOType != kNone_MSFBOType);
307         return fMSFBOType == kES_Apple_MSFBOType ||
308                (fBlitFramebufferFlags & kResolveMustBeFull_BlitFrambufferFlag);
309     }
310 
311     /**
312      * Can we resolve a single-sample framebuffer into an MSAA framebuffer?
313      */
canResolveSingleToMSAA()314     bool canResolveSingleToMSAA() const {
315         SkASSERT(fMSFBOType != kNone_MSFBOType);
316         return fMSFBOType != kES_Apple_MSFBOType &&
317                !(fBlitFramebufferFlags & GrGLCaps::kNoMSAADst_BlitFramebufferFlag);
318     }
319 
320     /**
321      * Is the MSAA FBO extension one where the texture is multisampled when bound to an FBO and
322      * then implicitly resolved when read.
323      */
usesImplicitMSAAResolve()324     bool usesImplicitMSAAResolve() const {
325         return kES_IMG_MsToTexture_MSFBOType == fMSFBOType ||
326                kES_EXT_MsToTexture_MSFBOType == fMSFBOType;
327     }
328 
invalidateFBType()329     InvalidateFBType invalidateFBType() const { return fInvalidateFBType; }
330 
331     /// What type of buffer mapping is supported?
mapBufferType()332     MapBufferType mapBufferType() const { return fMapBufferType; }
333 
334     /// What type of transfer buffer is supported?
transferBufferType()335     TransferBufferType transferBufferType() const { return fTransferBufferType; }
336 
337     /** Supports using GrGLsync. */
fenceSyncSupport()338     bool fenceSyncSupport() const { return fFenceSyncSupport; }
339 
340     /// How is GrGLsync implemented?
fenceType()341     FenceType fenceType() const { return fFenceType; }
342 
343     /// What type of timer queries are supported
timerQueryType()344     TimerQueryType timerQueryType() const { return fTimerQueryType; }
345 
346     /// How are multi draws implemented (if at all)?
multiDrawType()347     MultiDrawType multiDrawType() const { return fMultiDrawType; }
348 
349     /// How is restricting sampled miplevels in onRegenerateMipmapLevels implemented?
regenerateMipmapType()350     RegenerateMipmapType regenerateMipmapType() const { return fRegenerateMipmapType; }
351 
352     /// The maximum number of fragment uniform vectors (GLES has min. 16).
maxFragmentUniformVectors()353     int maxFragmentUniformVectors() const { return fMaxFragmentUniformVectors; }
354 
355     /// Is there support for GL_PACK_REVERSE_ROW_ORDER
packFlipYSupport()356     bool packFlipYSupport() const { return fPackFlipYSupport; }
357 
358     /// Is there support for texture parameter GL_TEXTURE_USAGE
textureUsageSupport()359     bool textureUsageSupport() const { return fTextureUsageSupport; }
360 
361     /// Is GL_ARB_IMAGING supported
imagingSupport()362     bool imagingSupport() const { return fImagingSupport; }
363 
364     /// Is there support for Vertex Array Objects?
vertexArrayObjectSupport()365     bool vertexArrayObjectSupport() const { return fVertexArrayObjectSupport; }
366 
367     /// Is there support for GL_KHR_debug?
debugSupport()368     bool debugSupport() const { return fDebugSupport; }
369 
370     /// Is there support for ES2 compatability?
ES2CompatibilitySupport()371     bool ES2CompatibilitySupport() const { return fES2CompatibilitySupport; }
372 
373     // Should OpenGL Protectedness handling be Vulkan-like
strictProtectedness()374     bool strictProtectedness() const { return fStrictProtectedness; }
375 
376     /// Is there support for glDrawRangeElements?
drawRangeElementsSupport()377     bool drawRangeElementsSupport() const { return fDrawRangeElementsSupport; }
378 
379     /// Are the glDraw*Base(VertexBase)Instance methods, and baseInstance fields in indirect draw
380     //commands supported?
baseVertexBaseInstanceSupport()381     bool baseVertexBaseInstanceSupport() const { return fBaseVertexBaseInstanceSupport; }
382 
383     SurfaceReadPixelsSupport surfaceSupportsReadPixels(const GrSurface*) const override;
384 
385     SupportedWrite supportedWritePixelsColorType(GrColorType surfaceColorType,
386                                                  const GrBackendFormat& surfaceFormat,
387                                                  GrColorType srcColorType) const override;
388 
isCoreProfile()389     bool isCoreProfile() const { return fIsCoreProfile; }
390 
bindFragDataLocationSupport()391     bool bindFragDataLocationSupport() const { return fBindFragDataLocationSupport; }
392 
bindUniformLocationSupport()393     bool bindUniformLocationSupport() const { return fBindUniformLocationSupport; }
394 
395     /// Are textures with GL_TEXTURE_RECTANGLE type supported.
rectangleTextureSupport()396     bool rectangleTextureSupport() const { return fRectangleTextureSupport; }
397 
398     /// Can set the BASE and MAX mip map level.
mipmapLevelControlSupport()399     bool mipmapLevelControlSupport() const { return fMipmapLevelControlSupport; }
400 
401     /// Can set the MIN/MAX LOD value.
mipmapLodControlSupport()402     bool mipmapLodControlSupport() const { return fMipmapLodControlSupport; }
403 
doManualMipmapping()404     bool doManualMipmapping() const { return fDoManualMipmapping; }
405 
406     void onDumpJSON(SkJSONWriter*) const override;
407 
invalidateBufferType()408     InvalidateBufferType invalidateBufferType() const { return fInvalidateBufferType; }
409 
410     // Certain Intel GPUs on Mac fail to clear if the glClearColor is made up of only 1s and 0s.
clearToBoundaryValuesIsBroken()411     bool clearToBoundaryValuesIsBroken() const { return fClearToBoundaryValuesIsBroken; }
412 
413     /// glClearTex(Sub)Image support
clearTextureSupport()414     bool clearTextureSupport() const { return fClearTextureSupport; }
415 
416     // Adreno/MSAA drops a draw on the imagefiltersbase GM if the base vertex param to
417     // glDrawArrays is nonzero.
418     // https://bugs.chromium.org/p/skia/issues/detail?id=6650
drawArraysBaseVertexIsBroken()419     bool drawArraysBaseVertexIsBroken() const { return fDrawArraysBaseVertexIsBroken; }
420 
421     // If true then we must use an intermediate surface to perform partial updates to unorm textures
422     // that have ever been bound to a FBO.
disallowTexSubImageForUnormConfigTexturesEverBoundToFBO()423     bool disallowTexSubImageForUnormConfigTexturesEverBoundToFBO() const {
424         return fDisallowTexSubImageForUnormConfigTexturesEverBoundToFBO;
425     }
426 
427     // Use an intermediate surface to write pixels (full or partial overwrite) to into a texture
428     // that is bound to an FBO.
useDrawInsteadOfAllRenderTargetWrites()429     bool useDrawInsteadOfAllRenderTargetWrites() const {
430         return fUseDrawInsteadOfAllRenderTargetWrites;
431     }
432 
433     // At least some Adreno 3xx drivers draw lines incorrectly after drawing non-lines. Toggling
434     // face culling on and off seems to resolve this.
requiresCullFaceEnableDisableWhenDrawingLinesAfterNonLines()435     bool requiresCullFaceEnableDisableWhenDrawingLinesAfterNonLines() const {
436         return fRequiresCullFaceEnableDisableWhenDrawingLinesAfterNonLines;
437     }
438 
439     // Older Android versions seem to have an issue with setting GL_TEXTURE_BASE_LEVEL or
440     // GL_TEXTURE_MAX_LEVEL for GL_TEXTURE_EXTERNAL_OES textures.
dontSetBaseOrMaxLevelForExternalTextures()441     bool dontSetBaseOrMaxLevelForExternalTextures() const {
442         return fDontSetBaseOrMaxLevelForExternalTextures;
443     }
444 
445     // PowerVRGX6250 drops every pixel if we modify the sample mask while color writes are disabled.
neverDisableColorWrites()446     bool neverDisableColorWrites() const { return fNeverDisableColorWrites; }
447 
448     // Texture parameters must be used to enable MIP mapping even when a sampler object is used.
mustSetAnyTexParameterToEnableMipmapping()449     bool mustSetAnyTexParameterToEnableMipmapping() const {
450         return fMustSetAnyTexParameterToEnableMipmapping;
451     }
452 
453     // Whether we must reset the blend function to not reference src2 when disabling blending after
454     // previously referencing src2.
mustResetBlendFuncBetweenDualSourceAndDisable()455     bool mustResetBlendFuncBetweenDualSourceAndDisable() const {
456         return fMustResetBlendFuncBetweenDualSourceAndDisable;
457     }
458 
459     // Before changing the sample count of a texture bound to an FBO with
460     // glFramebufferTexture2DMultisample() temporarily bind texture 0 to avoid corruption int the
461     // texture contents.
bindTexture0WhenChangingTextureFBOMultisampleCount()462     bool bindTexture0WhenChangingTextureFBOMultisampleCount() const {
463         return fBindTexture0WhenChangingTextureFBOMultisampleCount;
464     }
465 
466     // After using glCheckFramebufferStatus() bind 0 to the color attachment and then rebind the
467     // original color attachment.
rebindColorAttachmentAfterCheckFramebufferStatus()468     bool rebindColorAttachmentAfterCheckFramebufferStatus() const {
469         return fRebindColorAttachmentAfterCheckFramebufferStatus;
470     }
471 
472     // During writePixels, call glFlush() before issuing glTexSubImage2D().
flushBeforeWritePixels()473     bool flushBeforeWritePixels() const {
474         return fFlushBeforeWritePixels;
475     }
476 
477     // Returns the observed maximum number of instances the driver can handle in a single draw call
478     // without crashing, or 'pendingInstanceCount' if this workaround is not necessary.
479     // NOTE: the return value may be larger than pendingInstanceCount.
maxInstancesPerDrawWithoutCrashing(int pendingInstanceCount)480     int maxInstancesPerDrawWithoutCrashing(int pendingInstanceCount) const {
481         return (fMaxInstancesPerDrawWithoutCrashing)
482                 ? fMaxInstancesPerDrawWithoutCrashing : pendingInstanceCount;
483     }
484 
485     bool canCopyTexSubImage(GrGLFormat dstFormat, bool dstHasMSAARenderBuffer,
486                             const GrTextureType* dstTypeIfTexture,
487                             GrGLFormat srcFormat, bool srcHasMSAARenderBuffer,
488                             const GrTextureType* srcTypeIfTexture) const;
489     bool canCopyAsBlit(GrGLFormat dstFormat, int dstSampleCnt,
490                        const GrTextureType* dstTypeIfTexture,
491                        GrGLFormat srcFormat, int srcSampleCnt,
492                        const GrTextureType* srcTypeIfTexture,
493                        const SkRect& srcBounds, bool srcBoundsExact,
494                        const SkIRect& srcRect, const SkIRect& dstRect) const;
495     bool canCopyAsDraw(GrGLFormat dstFormat, bool srcIsTexturable, bool scalingCopy) const;
496 
497     DstCopyRestrictions getDstCopyRestrictions(const GrRenderTargetProxy* src,
498                                                GrColorType) const override;
499 
programBinarySupport()500     bool programBinarySupport() const { return fProgramBinarySupport; }
programParameterSupport()501     bool programParameterSupport() const { return fProgramParameterSupport; }
502     bool programBinaryFormatIsValid(GrGLenum binaryFormat) const;
503 
504     /** Are sampler objects available in this GL? */
samplerObjectSupport()505     bool samplerObjectSupport() const { return fSamplerObjectSupport; }
506 
507     /**
508      * Are we using sampler objects in favor of texture parameters? (This will only be true if
509      * samplerObjectSupport()).
510      */
useSamplerObjects()511     bool useSamplerObjects() const { return fUseSamplerObjects; }
512 
textureSwizzleSupport()513     bool textureSwizzleSupport() const { return fTextureSwizzleSupport; }
514 
tiledRenderingSupport()515     bool tiledRenderingSupport() const { return fTiledRenderingSupport; }
516 
fbFetchRequiresEnablePerSample()517     bool fbFetchRequiresEnablePerSample() const { return fFBFetchRequiresEnablePerSample; }
518 
519     /* Is there support for enabling/disabling sRGB writes for sRGB-capable color buffers? */
srgbWriteControl()520     bool srgbWriteControl() const { return fSRGBWriteControl; }
521 
522     /**
523      * Skip checks for GL errors and framebuffer completeness. Note that this does not skip
524      *  checking shader compilation and program linking status.
525      */
skipErrorChecks()526     bool skipErrorChecks() const { return fSkipErrorChecks; }
527 
clientCanDisableMultisample()528     bool clientCanDisableMultisample() const { return fClientCanDisableMultisample; }
529 
530     GrBackendFormat getBackendFormatFromCompressionType(SkTextureCompressionType) const override;
531 
532     skgpu::Swizzle getWriteSwizzle(const GrBackendFormat&, GrColorType) const override;
533 
534     uint64_t computeFormatKey(const GrBackendFormat&) const override;
535 
536     GrProgramDesc makeDesc(GrRenderTarget*,
537                            const GrProgramInfo&,
538                            ProgramDescOverrideFlags) const override;
539 
540 #if defined(GPU_TEST_UTILS)
standard()541     GrGLStandard standard() const { return fStandard; }
542 
543     std::vector<GrTest::TestFormatColorTypeCombination> getTestingCombinations() const override;
544 #endif
545 
546 private:
547     enum ExternalFormatUsage {
548         kTexImage_ExternalFormatUsage,
549         kReadPixels_ExternalFormatUsage,
550     };
551     void getExternalFormat(GrGLFormat surfaceFormat, GrColorType surfaceColorType,
552                            GrColorType memoryColorType, ExternalFormatUsage usage,
553                            GrGLenum* externalFormat, GrGLenum* externalType) const;
554 
555     void init(const GrContextOptions&, const GrGLContextInfo&, const GrGLInterface*);
556     void initGLSL(const GrGLContextInfo&, const GrGLInterface*);
557 
558     struct FormatWorkarounds {
559         bool fDisableSRGBRenderWithMSAAForMacAMD = false;
560         bool fDisableRGBA16FTexStorageForCrBug1008003 = false;
561         bool fDisableBGRATextureStorageForIntelWindowsES = false;
562         bool fDisableLuminance16F = false;
563         bool fDisableTexStorage = false;
564         bool fDisallowDirectRG8ReadPixels = false;
565         bool fDisallowBGRA8ReadPixels = false;
566         bool fDisallowR8ForPowerVRSGX54x = false;
567         bool fDisallowUnorm16Transfers = false;
568         bool fDisallowTextureUnorm16 = false;
569         bool fDisallowETC2Compression = false;
570     };
571 
572     void applyDriverCorrectnessWorkarounds(const GrGLContextInfo&, const GrContextOptions&,
573                                            const GrGLInterface*,
574                                            GrShaderCaps*, FormatWorkarounds*);
575 
576     void onApplyOptionsOverrides(const GrContextOptions& options) override;
577 
578     bool onIsWindowRectanglesSupportedForRT(const GrBackendRenderTarget&) const override;
579 
580     void initFSAASupport(const GrContextOptions& contextOptions, const GrGLContextInfo&,
581                          const GrGLInterface*);
582     void initBlendEqationSupport(const GrGLContextInfo&);
583     void initStencilSupport(const GrGLContextInfo&);
584     // This must be called after initFSAASupport().
585     void initFormatTable(const GrGLContextInfo&, const GrGLInterface*, const FormatWorkarounds&);
586     void setupSampleCounts(const GrGLContextInfo&, const GrGLInterface*);
587     bool onSurfaceSupportsWritePixels(const GrSurface*) const override;
588     bool onCanCopySurface(const GrSurfaceProxy* dst, const SkIRect& dstRect,
589                           const GrSurfaceProxy* src, const SkIRect& srcRect) const override;
590     GrBackendFormat onGetDefaultBackendFormat(GrColorType) const override;
591     bool onAreColorTypeAndFormatCompatible(GrColorType, const GrBackendFormat&) const override;
592 
593     SupportedRead onSupportedReadPixelsColorType(GrColorType, const GrBackendFormat&,
594                                                  GrColorType) const override;
595 
596     skgpu::Swizzle onGetReadSwizzle(const GrBackendFormat&, GrColorType) const override;
597 
598     GrDstSampleFlags onGetDstSampleFlagsForProxy(const GrRenderTargetProxy*) const override;
599 
600     bool onSupportsDynamicMSAA(const GrRenderTargetProxy*) const override;
601 
602     GrGLStandard fStandard = kNone_GrGLStandard;
603 
604     skia_private::TArray<GrGLFormat, true> fStencilFormats;
605     skia_private::TArray<GrGLenum, true> fProgramBinaryFormats;
606 
607     int fMaxFragmentUniformVectors = 0;
608     float fMaxTextureMaxAnisotropy = 1.f;
609 
610     MSFBOType            fMSFBOType            = kNone_MSFBOType;
611     InvalidateFBType     fInvalidateFBType     = kNone_InvalidateFBType;
612     InvalidateBufferType fInvalidateBufferType = InvalidateBufferType::kNone;
613     MapBufferType        fMapBufferType        = kNone_MapBufferType;
614     TransferBufferType   fTransferBufferType   = TransferBufferType::kNone;
615     FenceType            fFenceType            = FenceType::kNone;
616     TimerQueryType       fTimerQueryType       = TimerQueryType::kNone;
617     MultiDrawType        fMultiDrawType        = MultiDrawType::kNone;
618     RegenerateMipmapType fRegenerateMipmapType = RegenerateMipmapType::kBaseLevel;
619 
620     bool fPackFlipYSupport : 1;
621     bool fTextureUsageSupport : 1;
622     bool fImagingSupport  : 1;
623     bool fVertexArrayObjectSupport : 1;
624     bool fDebugSupport : 1;
625     bool fES2CompatibilitySupport : 1;
626     bool fStrictProtectedness     : 1;
627     bool fDrawRangeElementsSupport : 1;
628     bool fBaseVertexBaseInstanceSupport : 1;
629     bool fIsCoreProfile : 1;
630     bool fBindFragDataLocationSupport : 1;
631     bool fBindUniformLocationSupport : 1;
632     bool fRectangleTextureSupport : 1;
633     bool fMipmapLevelControlSupport : 1;
634     bool fMipmapLodControlSupport : 1;
635     bool fClearTextureSupport : 1;
636     bool fProgramBinarySupport : 1;
637     bool fProgramParameterSupport : 1;
638     bool fSamplerObjectSupport : 1;
639     bool fUseSamplerObjects : 1;
640     bool fTextureSwizzleSupport : 1;
641     bool fTiledRenderingSupport : 1;
642     bool fFenceSyncSupport : 1;
643     bool fFBFetchRequiresEnablePerSample : 1;
644     bool fSRGBWriteControl : 1;
645     bool fSkipErrorChecks : 1;
646     bool fClientCanDisableMultisample : 1;
647 
648     // Driver workarounds
649     bool fDoManualMipmapping : 1;
650     bool fClearToBoundaryValuesIsBroken : 1;
651     bool fDrawArraysBaseVertexIsBroken : 1;
652     bool fDisallowTexSubImageForUnormConfigTexturesEverBoundToFBO : 1;
653     bool fUseDrawInsteadOfAllRenderTargetWrites : 1;
654     bool fRequiresCullFaceEnableDisableWhenDrawingLinesAfterNonLines : 1;
655     bool fDontSetBaseOrMaxLevelForExternalTextures : 1;
656     bool fNeverDisableColorWrites : 1;
657     bool fMustSetAnyTexParameterToEnableMipmapping : 1;
658     bool fAllowBGRA8CopyTexSubImage : 1;
659     bool fAllowSRGBCopyTexSubImage : 1;
660     bool fDisallowDynamicMSAA : 1;
661     bool fMustResetBlendFuncBetweenDualSourceAndDisable : 1;
662     bool fBindTexture0WhenChangingTextureFBOMultisampleCount : 1;
663     bool fRebindColorAttachmentAfterCheckFramebufferStatus : 1;
664     bool fFlushBeforeWritePixels : 1;
665     bool fDisableScalingCopyAsDraws : 1;
666     bool fPadRG88TransferAlignment : 1;
667     int fMaxInstancesPerDrawWithoutCrashing = 0;
668 
669     uint32_t fBlitFramebufferFlags = kNoSupport_BlitFramebufferFlag;
670 
671     struct ReadPixelsFormat {
ReadPixelsFormatReadPixelsFormat672         ReadPixelsFormat() : fFormat(0), fType(0) {}
673         GrGLenum fFormat;
674         GrGLenum fType;
675     };
676 
677     /** Number type of the components (with out considering number of bits.) */
678     enum class FormatType {
679         kUnknown,
680         kNormalizedFixedPoint,
681         kFloat,
682     };
683 
684     // ColorTypeInfo for a specific format
685     struct ColorTypeInfo {
686         GrColorType fColorType = GrColorType::kUnknown;
687         enum {
688             kUploadData_Flag = 0x1,
689             // Does Ganesh itself support rendering to this colorType & format pair. Renderability
690             // still additionally depends on if the format can be an FBO color attachment.
691             kRenderable_Flag = 0x2,
692         };
693         uint32_t fFlags = 0;
694 
695         skgpu::Swizzle fReadSwizzle;
696         skgpu::Swizzle fWriteSwizzle;
697 
698         struct ExternalIOFormats {
699             GrColorType fColorType = GrColorType::kUnknown;
700 
701             /** The external format and type are to be used when uploading/downloading data using
702                 data of fColorType and uploading to a texture of a given GrGLFormat and its
703                 intended GrColorType. The fExternalTexImageFormat is the format to use for TexImage
704                 calls. The fExternalReadFormat is used when calling ReadPixels. If either is zero
705                 that signals that either TexImage or ReadPixels is not supported for the combination
706                 of format and color types. */
707             GrGLenum fExternalType = 0;
708             GrGLenum fExternalTexImageFormat = 0;
709             GrGLenum fExternalReadFormat = 0;
710             /**
711              * Must check whether GL_IMPLEMENTATION_COLOR_READ_FORMAT and _TYPE match
712              * fExternalReadFormat and fExternalType before using with glReadPixels.
713              */
714             bool fRequiresImplementationReadQuery = false;
715         };
716 
externalFormatColorTypeInfo717         GrGLenum externalFormat(GrColorType externalColorType, ExternalFormatUsage usage,
718                                 bool haveQueriedImplementationReadFormat) const {
719             for (int i = 0; i < fExternalIOFormatCount; ++i) {
720                 if (fExternalIOFormats[i].fColorType == externalColorType) {
721                     if (usage == kTexImage_ExternalFormatUsage) {
722                         return fExternalIOFormats[i].fExternalTexImageFormat;
723                     } else {
724                         SkASSERT(usage == kReadPixels_ExternalFormatUsage);
725                         if (!haveQueriedImplementationReadFormat &&
726                             fExternalIOFormats[i].fRequiresImplementationReadQuery) {
727                             return 0;
728                         }
729                         return fExternalIOFormats[i].fExternalReadFormat;
730                     }
731                 }
732             }
733             return 0;
734         }
735 
externalTypeColorTypeInfo736         GrGLenum externalType(GrColorType externalColorType) const {
737             for (int i = 0; i < fExternalIOFormatCount; ++i) {
738                 if (fExternalIOFormats[i].fColorType == externalColorType) {
739                     return fExternalIOFormats[i].fExternalType;
740                 }
741             }
742             return 0;
743         }
744 
745         std::unique_ptr<ExternalIOFormats[]> fExternalIOFormats;
746         int fExternalIOFormatCount = 0;
747     };
748 
749     struct FormatInfo {
colorTypeFlagsFormatInfo750         uint32_t colorTypeFlags(GrColorType colorType) const {
751             for (int i = 0; i < fColorTypeInfoCount; ++i) {
752                 if (fColorTypeInfos[i].fColorType == colorType) {
753                     return fColorTypeInfos[i].fFlags;
754                 }
755             }
756             return 0;
757         }
758 
externalFormatFormatInfo759         GrGLenum externalFormat(GrColorType surfaceColorType, GrColorType externalColorType,
760                                 ExternalFormatUsage usage) const {
761             for (int i = 0; i < fColorTypeInfoCount; ++i) {
762                 if (fColorTypeInfos[i].fColorType == surfaceColorType) {
763                     return fColorTypeInfos[i].externalFormat(externalColorType, usage,
764                                                              fHaveQueriedImplementationReadSupport);
765                 }
766             }
767             return 0;
768         }
769 
externalTypeFormatInfo770         GrGLenum externalType(GrColorType surfaceColorType, GrColorType externalColorType) const {
771             for (int i = 0; i < fColorTypeInfoCount; ++i) {
772                 if (fColorTypeInfos[i].fColorType == surfaceColorType) {
773                     return fColorTypeInfos[i].externalType(externalColorType);
774                 }
775             }
776             return 0;
777         }
778 
779         enum {
780             kTexturable_Flag                 = 0x01,
781             /** kFBOColorAttachment means that even if the format cannot be a GrRenderTarget, we can
782                 still attach it to a FBO for blitting or reading pixels. */
783             kFBOColorAttachment_Flag         = 0x02,
784             kFBOColorAttachmentWithMSAA_Flag = 0x04,
785             kUseTexStorage_Flag              = 0x08,
786             /**
787              * Are pixel buffer objects supported in/out of this format? Ignored if PBOs are not
788              * supported at all.
789              */
790             kTransfers_Flag                  = 0x10,
791         };
792         uint32_t fFlags = 0;
793 
794         FormatType fFormatType = FormatType::kUnknown;
795 
796         // Not defined for uncompressed formats. Passed to glCompressedTexImage...
797         GrGLenum fCompressedInternalFormat = 0;
798 
799         // Value to uses as the "internalformat" argument to glTexImage or glTexStorage. It is
800         // initialized in coordination with the presence/absence of the kUseTexStorage flag. In
801         // other words, it is only guaranteed to be compatible with glTexImage if the flag is not
802         // set and or with glTexStorage if the flag is set.
803         GrGLenum fInternalFormatForTexImageOrStorage = 0;
804 
805         // Value to uses as the "internalformat" argument to glRenderbufferStorageMultisample...
806         GrGLenum fInternalFormatForRenderbuffer = 0;
807 
808         // Default values to use along with fInternalFormatForTexImageOrStorage for function
809         // glTexImage2D when not input providing data (passing nullptr) or when clearing it by
810         // uploading a block of solid color data. Not defined for compressed formats.
811         GrGLenum fDefaultExternalFormat = 0;
812         GrGLenum fDefaultExternalType = 0;
813         // When the above two values are used to initialize a texture by uploading cleared data to
814         // it the data should be of this color type.
815         GrColorType fDefaultColorType = GrColorType::kUnknown;
816 
817         bool fHaveQueriedImplementationReadSupport = false;
818 
819         // This indicates that a stencil format has not yet been determined for the config.
820         static constexpr int kUnknown_StencilIndex = -1;
821         // This indicates that there is no supported stencil format for the config.
822         static constexpr int kUnsupported_StencilFormatIndex = -2;
823 
824         // Index fStencilFormats.
825         int fStencilFormatIndex = kUnknown_StencilIndex;
826 
827         SkTDArray<int> fColorSampleCounts;
828 
829         std::unique_ptr<ColorTypeInfo[]> fColorTypeInfos;
830         int fColorTypeInfoCount = 0;
831     };
832 
833     FormatInfo fFormatTable[kGrGLColorFormatCount];
834 
getFormatInfo(GrGLFormat format)835     FormatInfo& getFormatInfo(GrGLFormat format) { return fFormatTable[static_cast<int>(format)]; }
getFormatInfo(GrGLFormat format)836     const FormatInfo& getFormatInfo(GrGLFormat format) const {
837         return fFormatTable[static_cast<int>(format)];
838     }
839 
840     GrGLFormat fColorTypeToFormatTable[kGrColorTypeCnt];
841     void setColorTypeFormat(GrColorType, GrGLFormat);
842 
843     using INHERITED = GrCaps;
844 };
845 
846 #endif
847