Debian Codegraph @

src/gpu/ganesh/gl/GrGLGpu.h

raw
1 /*
2 * Copyright 2011 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 #ifndef GrGLGpu_DEFINED
9 #define GrGLGpu_DEFINED
10
11 #include "include/core/SkRefCnt.h"
12 #include "include/core/SkSamplingOptions.h"
13 #include "include/core/SkTypes.h"
14 #include "include/gpu/ganesh/GrBackendSurface.h"
15 #include "include/gpu/ganesh/GrTypes.h"
16 #include "include/gpu/ganesh/gl/GrGLBackendSurface.h"
17 #include "include/gpu/ganesh/gl/GrGLFunctions.h"
18 #include "include/gpu/ganesh/gl/GrGLInterface.h"
19 #include "include/gpu/ganesh/gl/GrGLTypes.h"
20 #include "include/private/base/SkDebug.h"
21 #include "include/private/base/SkSpan_impl.h"
22 #include "include/private/base/SkTArray.h"
23 #include "include/private/base/SkTemplates.h"
24 #include "include/private/base/SkTo.h"
25 #include "include/private/gpu/ganesh/GrTypesPriv.h"
26 #include "src/core/SkChecksum.h"
27 #include "src/core/SkColorData.h"
28 #include "src/core/SkLRUCache.h"
29 #include "src/gpu/Blend.h"
30 #include "src/gpu/ganesh/GrCaps.h"
31 #include "src/gpu/ganesh/GrGpu.h"
32 #include "src/gpu/ganesh/GrGpuResource.h"
33 #include "src/gpu/ganesh/GrNativeRect.h"
34 #include "src/gpu/ganesh/GrOpsRenderPass.h"
35 #include "src/gpu/ganesh/GrProgramDesc.h"
36 #include "src/gpu/ganesh/GrSamplerState.h"
37 #include "src/gpu/ganesh/GrScissorState.h"
38 #include "src/gpu/ganesh/GrShaderCaps.h"
39 #include "src/gpu/ganesh/GrStencilSettings.h"
40 #include "src/gpu/ganesh/GrThreadSafePipelineBuilder.h"
41 #include "src/gpu/ganesh/GrWindowRectsState.h"
42 #include "src/gpu/ganesh/GrXferProcessor.h"
43 #include "src/gpu/ganesh/gl/GrGLCaps.h"
44 #include "src/gpu/ganesh/gl/GrGLContext.h"
45 #include "src/gpu/ganesh/gl/GrGLDefines.h"
46 #include "src/gpu/ganesh/gl/GrGLFinishCallbacks.h"
47 #include "src/gpu/ganesh/gl/GrGLRenderTarget.h"
48 #include "src/gpu/ganesh/gl/GrGLTexture.h"
49 #include "src/gpu/ganesh/gl/GrGLTypesPriv.h"
50 #include "src/gpu/ganesh/gl/GrGLUtil.h"
51 #include "src/gpu/ganesh/gl/GrGLVertexArray.h"
52
53 #include <array>
54 #include <cstddef>
55 #include <cstdint>
56 #include <memory>
57 #include <optional>
58 #include <string_view>
59
60 class GrAttachment;
61 class GrBackendSemaphore;
62 class GrBuffer;
63 class GrDirectContext;
64 class GrGLBuffer;
65 class GrGLOpsRenderPass;
66 class GrGLProgram;
67 class GrGpuBuffer;
68 class GrProgramInfo;
69 class GrRenderTarget;
70 class GrSemaphore;
71 class GrStagingBufferManager;
72 class GrSurface;
73 class GrSurfaceProxy;
74 class GrTexture;
75 class SkData;
76 enum class SkTextureCompressionType;
77 struct GrContextOptions;
78 struct SkIPoint;
79 struct SkIRect;
80 struct SkISize;
81
82 namespace SkSL { enum class GLSLGeneration; }
83
84 namespace SkSurfaces { enum class BackendSurfaceAccess; }
85
86 namespace skgpu {
87 class AutoCallback;
88 class MutableTextureState;
89 class RefCntedCallback;
90 class Swizzle;
91 enum class Budgeted : bool;
92 enum class Mipmapped : bool;
93 }
94
95 class GrGLGpu final : public GrGpu {
96 public:
97 static std::unique_ptr<GrGpu> Make(sk_sp<const GrGLInterface>,
98 const GrContextOptions&,
99 GrDirectContext*);
100 ~GrGLGpu() override;
101
102 void disconnect(DisconnectType) override;
103
104 GrThreadSafePipelineBuilder* pipelineBuilder() override;
105 sk_sp<GrThreadSafePipelineBuilder> refPipelineBuilder() override;
106
107 const GrGLContext& glContext() const { return *fGLContext; }
108
109 const GrGLInterface* glInterface() const { return fGLContext->glInterface(); }
110 const GrGLContextInfo& ctxInfo() const { return *fGLContext; }
111 GrGLStandard glStandard() const { return fGLContext->standard(); }
112 GrGLVersion glVersion() const { return fGLContext->version(); }
113 SkSL::GLSLGeneration glslGeneration() const { return fGLContext->glslGeneration(); }
114 const GrGLCaps& glCaps() const { return *fGLContext->caps(); }
115
116 GrStagingBufferManager* stagingBufferManager() override { return fStagingBufferManager.get(); }
117
118 // Used by GrGLProgram to configure OpenGL state.
119 void bindTexture(int unitIdx, GrSamplerState samplerState, const skgpu::Swizzle&, GrGLTexture*);
120
121 // These functions should be used to bind GL objects. They track the GL state and skip redundant
122 // bindings. Making the equivalent glBind calls directly will confuse the state tracking.
123 void bindVertexArray(GrGLuint id) {
124 fHWVertexArrayState.setVertexArrayID(this, id);
125 }
126
127 // These callbacks update state tracking when GL objects are deleted. They are called from
128 // GrGLResource onRelease functions.
129 void notifyVertexArrayDelete(GrGLuint id) {
130 fHWVertexArrayState.notifyVertexArrayDelete(id);
131 }
132
133 // Binds a buffer to the GL target corresponding to 'type', updates internal state tracking, and
134 // returns the GL target the buffer was bound to.
135 // When 'type' is kIndex_GrBufferType, this function will also implicitly bind the default VAO.
136 // If the caller wishes to bind an index buffer to a specific VAO, it can call glBind directly.
137 GrGLenum bindBuffer(GrGpuBufferType type, const GrBuffer*);
138
139 // Flushes state from GrProgramInfo to GL. Returns false if the state couldn't be set.
140 bool flushGLState(GrRenderTarget*, bool useMultisampleFBO, const GrProgramInfo&);
141 void flushScissorRect(const SkIRect& scissor, int rtHeight, GrSurfaceOrigin);
142
143 // The flushRenderTarget methods will all set the initial viewport to the full extent of the
144 // backing render target.
145 void flushViewport(const SkIRect& viewport, int rtHeight, GrSurfaceOrigin);
146
147 // Returns the last program bound by flushGLState(), or nullptr if a different program has since
148 // been put into use via some other method (e.g., resetContext, copySurfaceAsDraw).
149 // The returned GrGLProgram can be used for binding textures and vertex attributes.
150 GrGLProgram* currentProgram() {
151 this->handleDirtyContext();
152 return fHWProgram.get();
153 }
154
155 // Binds the vertex array that should be used for internal draws, enables 'numAttribs' vertex
156 // arrays, and flushes the desired primitive restart settings. If an index buffer is provided,
157 // it will be bound to the vertex array. Otherwise the index buffer binding will be left
158 // unchanged.
159 //
160 // NOTE: This binds the default VAO (ID=zero) unless we are on a core profile, in which case we
161 // use a placeholder array instead.
162 GrGLAttribArrayState* bindInternalVertexArray(const GrBuffer* indexBuffer, int numAttribs,
163 GrPrimitiveRestart primitiveRestart) {
164 auto* attribState = fHWVertexArrayState.bindInternalVertexArray(this, indexBuffer);
165 attribState->enableVertexArrays(this, numAttribs, primitiveRestart);
166 return attribState;
167 }
168
169 // Applies any necessary workarounds and returns the GL primitive type to use in draw calls.
170 GrGLenum prepareToDraw(GrPrimitiveType primitiveType);
171
172 using ResolveDirection = GrGLRenderTarget::ResolveDirection;
173
174 // Resolves the render target's single sample FBO into the MSAA, or vice versa.
175 // If glCaps.framebufferResolvesMustBeFullSize() is true, resolveRect must be equal the render
176 // target's bounds rect.
177 // If blitting single to MSAA, glCaps.canResolveSingleToMSAA() must be true.
178 void resolveRenderFBOs(GrGLRenderTarget*, const SkIRect& resolveRect, ResolveDirection,
179 bool invalidateReadBufferAfterBlit = false);
180
181 // For loading a dynamic MSAA framebuffer when glCaps.canResolveSingleToMSAA() is false.
182 // NOTE: If glCaps.framebufferResolvesMustBeFullSize() is also true, the drawBounds should be
183 // equal to the proxy bounds. This is because the render pass will have to do a full size
184 // resolve back into the single sample FBO when rendering is complete.
185 void drawSingleIntoMSAAFBO(GrGLRenderTarget* rt, const SkIRect& drawBounds) {
186 this->copySurfaceAsDraw(rt, true/*drawToMultisampleFBO*/, rt, drawBounds, drawBounds,
187 GrSamplerState::Filter::kNearest);
188 }
189
190 // The GrGLOpsRenderPass does not buffer up draws before submitting them to the gpu.
191 // Thus this is the implementation of the clear call for the corresponding passthrough function
192 // on GrGLOpsRenderPass.
193 void clear(const GrScissorState&, std::array<float, 4> color, GrRenderTarget*,
194 bool useMultisampleFBO, GrSurfaceOrigin);
195
196 // The GrGLOpsRenderPass does not buffer up draws before submitting them to the gpu.
197 // Thus this is the implementation of the clearStencil call for the corresponding passthrough
198 // function on GrGLOpsrenderPass.
199 void clearStencilClip(const GrScissorState&, bool insideStencilMask,
200 GrRenderTarget*, bool useMultisampleFBO, GrSurfaceOrigin);
201
202 void beginCommandBuffer(GrGLRenderTarget*, bool useMultisampleFBO,
203 const SkIRect& bounds, GrSurfaceOrigin,
204 const GrOpsRenderPass::LoadAndStoreInfo& colorLoadStore,
205 const GrOpsRenderPass::StencilLoadAndStoreInfo& stencilLoadStore);
206
207 void endCommandBuffer(GrGLRenderTarget*, bool useMultisampleFBO,
208 const GrOpsRenderPass::LoadAndStoreInfo& colorLoadStore,
209 const GrOpsRenderPass::StencilLoadAndStoreInfo& stencilLoadStore);
210
211 void invalidateBoundRenderTarget() {
212 fHWBoundRenderTargetUniqueID.makeInvalid();
213 }
214
215 sk_sp<GrAttachment> makeStencilAttachment(const GrBackendFormat& colorFormat,
216 SkISize dimensions, int numStencilSamples) override;
217
218 sk_sp<GrAttachment> makeMSAAAttachment(SkISize dimensions,
219 const GrBackendFormat& format,
220 int numSamples,
221 GrProtected isProtected,
222 GrMemoryless) override;
223
224 void deleteBackendTexture(const GrBackendTexture&) override;
225
226 bool compile(const GrProgramDesc&, const GrProgramInfo&) override;
227
228 bool precompileShader(const SkData& key, const SkData& data) override {
229 return fProgramCache->precompileShader(this->getContext(), key, data);
230 }
231
232 #if defined(GPU_TEST_UTILS)
233 bool isTestingOnlyBackendTexture(const GrBackendTexture&) const override;
234
235 GrBackendRenderTarget createTestingOnlyBackendRenderTarget(SkISize dimensions,
236 GrColorType,
237 int sampleCnt,
238 GrProtected) override;
239 void deleteTestingOnlyBackendRenderTarget(const GrBackendRenderTarget&) override;
240
241 const GrGLContext* glContextForTesting() const override { return &this->glContext(); }
242
243 void resetShaderCacheForTesting() const override { fProgramCache->reset(); }
244 #endif
245
246 void willExecute() override;
247
248 void submit(GrOpsRenderPass* renderPass) override;
249
250 [[nodiscard]] GrGLsync insertSync();
251 bool testSync(GrGLsync);
252 void deleteSync(GrGLsync);
253
254 [[nodiscard]] std::unique_ptr<GrSemaphore> makeSemaphore(bool isOwned) override;
255 std::unique_ptr<GrSemaphore> wrapBackendSemaphore(const GrBackendSemaphore&,
256 GrSemaphoreWrapType,
257 GrWrapOwnership) override;
258 void insertSemaphore(GrSemaphore* semaphore) override;
259 void waitSemaphore(GrSemaphore* semaphore) override;
260
261 std::optional<GrTimerQuery> startTimerQuery() override;
262 uint64_t getTimerQueryResult(GrGLuint);
263
264 void checkFinishedCallbacks() override;
265 void finishOutstandingGpuWork() override;
266
267 // Calls glGetError() until no errors are reported. Also looks for OOMs.
268 void clearErrorsAndCheckForOOM();
269 // Calls glGetError() once and returns the result. Also looks for an OOM.
270 GrGLenum getErrorAndCheckForOOM();
271
272 std::unique_ptr<GrSemaphore> prepareTextureForCrossContextUsage(GrTexture*) override;
273
274 void bindFramebuffer(GrGLenum fboTarget, GrGLuint fboid);
275 void deleteFramebuffer(GrGLuint fboid);
276
277 void flushProgram(sk_sp<GrGLProgram>);
278
279 // Version for programs that aren't GrGLProgram.
280 void flushProgram(GrGLuint);
281
282 // GrGLOpsRenderPass directly makes GL draws. GrGLGpu uses this notification to mark the
283 // destination surface dirty if color writes are enabled.
284 void didDrawTo(GrRenderTarget*);
285
286 private:
287 GrGLGpu(std::unique_ptr<GrGLContext>, GrDirectContext*);
288
289 // GrGpu overrides
290 void endTimerQuery(const GrTimerQuery&) override;
291
292 GrBackendTexture onCreateBackendTexture(SkISize dimensions,
293 const GrBackendFormat&,
294 GrRenderable,
295 skgpu::Mipmapped,
296 GrProtected,
297 std::string_view label) override;
298
299 GrBackendTexture onCreateCompressedBackendTexture(SkISize dimensions,
300 const GrBackendFormat&,
301 skgpu::Mipmapped,
302 GrProtected) override;
303
304 bool onClearBackendTexture(const GrBackendTexture&,
305 sk_sp<skgpu::RefCntedCallback> finishedCallback,
306 std::array<float, 4> color) override;
307
308 bool onUpdateCompressedBackendTexture(const GrBackendTexture&,
309 sk_sp<skgpu::RefCntedCallback> finishedCallback,
310 const void* data,
311 size_t length) override;
312
313 void onResetContext(uint32_t resetBits) override;
314
315 void onResetTextureBindings() override;
316
317 void xferBarrier(GrRenderTarget*, GrXferBarrierType) override;
318
319 sk_sp<GrTexture> onCreateTexture(SkISize dimensions,
320 const GrBackendFormat&,
321 GrRenderable,
322 int renderTargetSampleCnt,
323 skgpu::Budgeted,
324 GrProtected,
325 int mipLevelCount,
326 uint32_t levelClearMask,
327 std::string_view label) override;
328 sk_sp<GrTexture> onCreateCompressedTexture(SkISize dimensions,
329 const GrBackendFormat&,
330 skgpu::Budgeted,
331 skgpu::Mipmapped,
332 GrProtected,
333 const void* data,
334 size_t dataSize) override;
335
336 sk_sp<GrGpuBuffer> onCreateBuffer(size_t size, GrGpuBufferType, GrAccessPattern) override;
337
338 sk_sp<GrTexture> onWrapBackendTexture(const GrBackendTexture&,
339 GrWrapOwnership,
340 GrWrapCacheable,
341 GrIOType) override;
342 sk_sp<GrTexture> onWrapCompressedBackendTexture(const GrBackendTexture&,
343 GrWrapOwnership,
344 GrWrapCacheable) override;
345 sk_sp<GrTexture> onWrapRenderableBackendTexture(const GrBackendTexture&,
346 int sampleCnt,
347 GrWrapOwnership,
348 GrWrapCacheable) override;
349 sk_sp<GrRenderTarget> onWrapBackendRenderTarget(const GrBackendRenderTarget&) override;
350
351 // Given a GL format return the index into the stencil format array on GrGLCaps to a
352 // compatible stencil format, or negative if there is no compatible stencil format.
353 int getCompatibleStencilIndex(GrGLFormat format);
354
355 GrBackendFormat getPreferredStencilFormat(const GrBackendFormat& format) override {
356 int idx = this->getCompatibleStencilIndex(GrBackendFormats::AsGLFormat(format));
357 if (idx < 0) {
358 return {};
359 }
360 return GrBackendFormats::MakeGL(GrGLFormatToEnum(this->glCaps().stencilFormats()[idx]),
361 GR_GL_TEXTURE_NONE);
362 }
363
364 void onFBOChanged();
365
366 // Returns whether the texture is successfully created. On success, a non-zero texture ID is
367 // returned. On failure, zero is returned.
368 // The texture is populated with |texels|, if it is non-null.
369 // The texture parameters are cached in |initialTexParams|.
370 GrGLuint createTexture(SkISize dimensions,
371 GrGLFormat,
372 GrGLenum target,
373 GrRenderable,
374 GrGLTextureParameters::SamplerOverriddenState*,
375 int mipLevelCount,
376 GrProtected isProtected,
377 std::string_view label);
378
379 GrGLuint createCompressedTexture2D(SkISize dimensions,
380 SkTextureCompressionType compression,
381 GrGLFormat,
382 skgpu::Mipmapped,
383 GrProtected,
384 GrGLTextureParameters::SamplerOverriddenState*);
385
386 bool onReadPixels(GrSurface*,
387 SkIRect,
388 GrColorType surfaceColorType,
389 GrColorType dstColorType,
390 void*,
391 size_t rowBytes) override;
392
393 bool onWritePixels(GrSurface*,
394 SkIRect,
395 GrColorType surfaceColorType,
396 GrColorType srcColorType,
397 const GrMipLevel[],
398 int mipLevelCount,
399 bool prepForTexSampling) override;
400
401 bool onTransferFromBufferToBuffer(sk_sp<GrGpuBuffer> src,
402 size_t srcOffset,
403 sk_sp<GrGpuBuffer> dst,
404 size_t dstOffset,
405 size_t size) override;
406
407 bool onTransferPixelsTo(GrTexture*,
408 SkIRect,
409 GrColorType textureColorType,
410 GrColorType bufferColorType,
411 sk_sp<GrGpuBuffer>,
412 size_t offset,
413 size_t rowBytes) override;
414
415 bool onTransferPixelsFrom(GrSurface*,
416 SkIRect,
417 GrColorType surfaceColorType,
418 GrColorType bufferColorType,
419 sk_sp<GrGpuBuffer>,
420 size_t offset) override;
421
422 bool readOrTransferPixelsFrom(GrSurface*,
423 SkIRect rect,
424 GrColorType surfaceColorType,
425 GrColorType dstColorType,
426 void* offsetOrPtr,
427 int rowWidthInPixels);
428
429 // Unbinds xfer buffers from GL for operations that don't need them.
430 // Before calling any variation of TexImage, TexSubImage, etc..., call this with
431 // GrGpuBufferType::kXferCpuToGpu to ensure that the PIXEL_UNPACK_BUFFER is unbound.
432 // Before calling ReadPixels and reading back into cpu memory call this with
433 // GrGpuBufferType::kXferGpuToCpu to ensure that the PIXEL_PACK_BUFFER is unbound.
434 void unbindXferBuffer(GrGpuBufferType type);
435
436 void onResolveRenderTarget(GrRenderTarget* target, const SkIRect& resolveRect) override;
437
438 bool onRegenerateMipMapLevels(GrTexture*) override;
439
440 bool onCopySurface(GrSurface* dst, const SkIRect& dstRect,
441 GrSurface* src, const SkIRect& srcRect,
442 GrSamplerState::Filter) override;
443
444 // binds texture unit in GL
445 void setTextureUnit(int unitIdx);
446
447 void flushBlendAndColorWrite(const skgpu::BlendInfo&, const skgpu::Swizzle&);
448
449 void addFinishedCallback(skgpu::AutoCallback callback, std::optional<GrTimerQuery>) override;
450
451 GrOpsRenderPass* onGetOpsRenderPass(
452 GrRenderTarget*,
453 bool useMultisampleFBO,
454 GrAttachment*,
455 GrSurfaceOrigin,
456 const SkIRect&,
457 const GrOpsRenderPass::LoadAndStoreInfo&,
458 const GrOpsRenderPass::StencilLoadAndStoreInfo&,
459 const skia_private::TArray<GrSurfaceProxy*, true>& sampledProxies,
460 GrXferBarrierFlags renderPassXferBarriers) override;
461
462 void prepareSurfacesForBackendAccessAndStateUpdates(
463 SkSpan<GrSurfaceProxy*> proxies,
464 SkSurfaces::BackendSurfaceAccess access,
465 const skgpu::MutableTextureState* newState) override;
466
467 bool onSubmitToGpu(const GrSubmitInfo& info) override;
468
469 bool copySurfaceAsDraw(GrSurface* dst, bool drawToMultisampleFBO, GrSurface* src,
470 const SkIRect& srcRect, const SkIRect& dstRect, GrSamplerState::Filter);
471 void copySurfaceAsCopyTexSubImage(GrSurface* dst, GrSurface* src, const SkIRect& srcRect,
472 const SkIPoint& dstPoint);
473 bool copySurfaceAsBlitFramebuffer(GrSurface* dst, GrSurface* src, const SkIRect& srcRect,
474 const SkIRect& dstRect, GrSamplerState::Filter);
475
476 class ProgramCache : public GrThreadSafePipelineBuilder {
477 public:
478 explicit ProgramCache(int runtimeProgramCacheSize);
479 ~ProgramCache() override;
480
481 void abandon();
482 void reset();
483 sk_sp<GrGLProgram> findOrCreateProgram(GrDirectContext*,
484 const GrProgramInfo&);
485 sk_sp<GrGLProgram> findOrCreateProgram(GrDirectContext*,
486 const GrProgramDesc&,
487 const GrProgramInfo&,
488 Stats::ProgramCacheResult*);
489 bool precompileShader(GrDirectContext*, const SkData& key, const SkData& data);
490
491 private:
492 struct Entry;
493
494 sk_sp<GrGLProgram> findOrCreateProgramImpl(GrDirectContext*,
495 const GrProgramDesc&,
496 const GrProgramInfo&,
497 Stats::ProgramCacheResult*);
498
499 struct DescHash {
500 uint32_t operator()(const GrProgramDesc& desc) const {
501 return SkChecksum::Hash32(desc.asKey(), desc.keyLength());
502 }
503 };
504
505 SkLRUCache<GrProgramDesc, std::unique_ptr<Entry>, DescHash> fMap;
506 };
507
508 void flushColorWrite(bool writeColor);
509 void flushClearColor(std::array<float, 4>);
510
511 // flushes the scissor. see the note on flushBoundTextureAndParams about
512 // flushing the scissor after that function is called.
513 void flushScissor(const GrScissorState& scissorState, int rtHeight, GrSurfaceOrigin rtOrigin) {
514 this->flushScissorTest(GrScissorTest(scissorState.enabled()));
515 if (scissorState.enabled()) {
516 this->flushScissorRect(scissorState.rect(), rtHeight, rtOrigin);
517 }
518 }
519 void flushScissorTest(GrScissorTest);
520
521 void flushWindowRectangles(const GrWindowRectsState&, const GrGLRenderTarget*, GrSurfaceOrigin);
522 void disableWindowRectangles();
523
524 int numTextureUnits() const { return this->caps()->shaderCaps()->fMaxFragmentSamplers; }
525
526 // Binds a texture to a target on the "scratch" texture unit to use for texture operations
527 // other than usual draw flow (i.e. a GrGLProgram derived from a GrPipeline used to draw). It
528 // ensures that such operations don't negatively interact with draws. The active texture unit
529 // and the binding for 'target' will change.
530 void bindTextureToScratchUnit(GrGLenum target, GrGLint textureID);
531
532 void flushRenderTarget(GrGLRenderTarget*, bool useMultisampleFBO);
533
534 void flushStencil(const GrStencilSettings&, GrSurfaceOrigin);
535 void disableStencil();
536
537 void flushConservativeRasterState(bool enable);
538
539 void flushWireframeState(bool enable);
540
541 void flushFramebufferSRGB(bool enable);
542
543 // Uploads src data of a color type to the currently bound texture on the active texture unit.
544 // The caller specifies color type that the texture is being used with, which may be different
545 // than the src color type. This fails if the combination of texture format, texture color type,
546 // and src data color type are not valid. No conversion is performed on the data before passing
547 // it to GL. 'dstRect' must be the texture bounds if mipLevelCount is greater than 1.
548 bool uploadColorTypeTexData(GrGLFormat textureFormat,
549 GrColorType textureColorType,
550 SkISize texDims,
551 GrGLenum target,
552 SkIRect dstRect,
553 GrColorType srcColorType,
554 const GrMipLevel texels[],
555 int mipLevelCount);
556
557 // Uploads a constant color to a texture using the "default" format and color type. Overwrites
558 // entire levels. Bit n in 'levelMask' indicates whether level n should be written. This
559 // function doesn't know if MIP levels have been allocated, thus levelMask should not have bits
560 // beyond the low bit set if the texture is not MIP mapped.
561 bool uploadColorToTex(GrGLFormat textureFormat,
562 SkISize texDims,
563 GrGLenum target,
564 std::array<float, 4> color,
565 uint32_t levelMask);
566
567 // Pushes data to the currently bound texture to the currently active unit. 'dstRect' must be
568 // the texture bounds if mipLevelCount is greater than 1.
569 void uploadTexData(SkISize dimensions,
570 GrGLenum target,
571 SkIRect dstRect,
572 GrGLenum externalFormat,
573 GrGLenum externalType,
574 size_t bpp,
575 const GrMipLevel texels[],
576 int mipLevelCount);
577
578 // Helper for onCreateCompressedTexture. Compressed textures are read-only so we only use this
579 // to populate a new texture. Returns false if we failed to create and upload the texture.
580 bool uploadCompressedTexData(SkTextureCompressionType compressionType,
581 GrGLFormat,
582 SkISize dimensions,
583 skgpu::Mipmapped,
584 GrGLenum target,
585 const void* data,
586 size_t dataSize);
587
588 // Calls one of various versions of renderBufferStorageMultisample.
589 bool renderbufferStorageMSAA(const GrGLContext& ctx, int sampleCount, GrGLenum format,
590 int width, int height);
591
592 bool createRenderTargetObjects(const GrGLTexture::Desc&,
593 int sampleCount,
594 GrGLRenderTarget::IDs*);
595 enum TempFBOTarget {
596 kSrc_TempFBOTarget,
597 kDst_TempFBOTarget
598 };
599
600 // Binds a surface as a FBO for copying, reading, or clearing. If the surface already owns an
601 // FBO ID then that ID is bound. If not the surface is temporarily bound to a FBO and that FBO
602 // is bound. This must be paired with a call to unbindSurfaceFBOForPixelOps().
603 void bindSurfaceFBOForPixelOps(GrSurface* surface, int mipLevel, GrGLenum fboTarget,
604 TempFBOTarget tempFBOTarget);
605
606 // Must be called if bindSurfaceFBOForPixelOps was used to bind a surface for copying.
607 void unbindSurfaceFBOForPixelOps(GrSurface* surface, int mipLevel, GrGLenum fboTarget);
608
609 #ifdef SK_ENABLE_DUMP_GPU
610 void onDumpJSON(SkJSONWriter*) const override;
611 #endif
612
613 bool createCopyProgram(GrTexture* srcTexture);
614 bool createMipmapProgram(int progIdx);
615
616 std::unique_ptr<GrGLContext> fGLContext;
617
618 // GL program-related state
619 sk_sp<ProgramCache> fProgramCache;
620
621 ///////////////////////////////////////////////////////////////////////////
622 ///@name Caching of GL State
623 ///@{
624 int fHWActiveTextureUnitIdx;
625
626 GrGLuint fHWProgramID;
627 sk_sp<GrGLProgram> fHWProgram;
628
629 enum TriState {
630 kNo_TriState,
631 kYes_TriState,
632 kUnknown_TriState
633 };
634
635 GrGLuint fTempSrcFBOID;
636 GrGLuint fTempDstFBOID;
637
638 GrGLuint fStencilClearFBOID;
639
640 // last scissor / viewport scissor state seen by the GL.
641 struct {
642 TriState fEnabled;
643 GrNativeRect fRect;
644 void invalidate() {
645 fEnabled = kUnknown_TriState;
646 fRect.invalidate();
647 }
648 } fHWScissorSettings;
649
650 class HWWindowRectsState {
651 public:
652 bool valid() const { return kInvalidSurfaceOrigin != fRTOrigin; }
653 void invalidate() { fRTOrigin = kInvalidSurfaceOrigin; }
654 bool knownDisabled() const { return this->valid() && !fWindowState.enabled(); }
655 void setDisabled() {
656 fRTOrigin = kTopLeft_GrSurfaceOrigin;
657 fWindowState.setDisabled();
658 }
659
660 void set(GrSurfaceOrigin rtOrigin, int width, int height,
661 const GrWindowRectsState& windowState) {
662 fRTOrigin = rtOrigin;
663 fWidth = width;
664 fHeight = height;
665 fWindowState = windowState;
666 }
667
668 bool knownEqualTo(GrSurfaceOrigin rtOrigin, int width, int height,
669 const GrWindowRectsState& windowState) const {
670 if (!this->valid()) {
671 return false;
672 }
673 if (fWindowState.numWindows() &&
674 (fRTOrigin != rtOrigin || fWidth != width || fHeight != height)) {
675 return false;
676 }
677 return fWindowState == windowState;
678 }
679
680 private:
681 static constexpr int kInvalidSurfaceOrigin = -1;
682
683 int fRTOrigin;
684 int fWidth;
685 int fHeight;
686 GrWindowRectsState fWindowState;
687 };
688 HWWindowRectsState fHWWindowRectsState;
689
690 GrNativeRect fHWViewport;
691
692 /**
693 * Tracks vertex attrib array state.
694 */
695 class HWVertexArrayState {
696 public:
697 HWVertexArrayState() : fCoreProfileVertexArray(nullptr) { this->invalidate(); }
698
699 ~HWVertexArrayState() { delete fCoreProfileVertexArray; }
700
701 void invalidate() {
702 fBoundVertexArrayIDIsValid = false;
703 fDefaultVertexArrayAttribState.invalidate();
704 if (fCoreProfileVertexArray) {
705 fCoreProfileVertexArray->invalidateCachedState();
706 }
707 }
708
709 void notifyVertexArrayDelete(GrGLuint id) {
710 if (fBoundVertexArrayIDIsValid && fBoundVertexArrayID == id) {
711 // Does implicit bind to 0
712 fBoundVertexArrayID = 0;
713 }
714 }
715
716 void setVertexArrayID(GrGLGpu* gpu, GrGLuint arrayID) {
717 if (!gpu->glCaps().vertexArrayObjectSupport()) {
718 SkASSERT(0 == arrayID);
719 return;
720 }
721 if (!fBoundVertexArrayIDIsValid || arrayID != fBoundVertexArrayID) {
722 GR_GL_CALL(gpu->glInterface(), BindVertexArray(arrayID));
723 fBoundVertexArrayIDIsValid = true;
724 fBoundVertexArrayID = arrayID;
725 }
726 }
727
728 /**
729 * Binds the vertex array that should be used for internal draws, and returns its attrib
730 * state. This binds the default VAO (ID=zero) unless we are on a core profile, in which
731 * case we use a placeholder array instead.
732 *
733 * If an index buffer is provided, it will be bound to the vertex array. Otherwise the
734 * index buffer binding will be left unchanged.
735 *
736 * The returned GrGLAttribArrayState should be used to set vertex attribute arrays.
737 */
738 GrGLAttribArrayState* bindInternalVertexArray(GrGLGpu*, const GrBuffer* ibuff = nullptr);
739
740 private:
741 GrGLuint fBoundVertexArrayID;
742 bool fBoundVertexArrayIDIsValid;
743
744 // We return a non-const pointer to this from bindArrayAndBuffersToDraw when vertex array 0
745 // is bound. However, this class is internal to GrGLGpu and this object never leaks out of
746 // GrGLGpu.
747 GrGLAttribArrayState fDefaultVertexArrayAttribState;
748
749 // This is used when we're using a core profile.
750 GrGLVertexArray* fCoreProfileVertexArray;
751 } fHWVertexArrayState;
752
753 struct {
754 GrGLenum fGLTarget;
755 GrGpuResource::UniqueID fBoundBufferUniqueID;
756 bool fBufferZeroKnownBound;
757
758 void invalidate() {
759 fBoundBufferUniqueID.makeInvalid();
760 fBufferZeroKnownBound = false;
761 }
762 } fHWBufferState[kGrGpuBufferTypeCount];
763
764 auto* hwBufferState(GrGpuBufferType type) {
765 unsigned typeAsUInt = static_cast<unsigned>(type);
766 SkASSERT(typeAsUInt < std::size(fHWBufferState));
767 SkASSERT(type != GrGpuBufferType::kUniform);
768 return &fHWBufferState[typeAsUInt];
769 }
770
771 enum class FlushType {
772 kIfRequired,
773 kForce,
774 };
775
776 // This calls glFlush if it is required for previous operations or kForce is passed.
777 void flush(FlushType flushType = FlushType::kIfRequired);
778
779 void setNeedsFlush() { fNeedsGLFlush = true; }
780
781 struct {
782 skgpu::BlendEquation fEquation;
783 skgpu::BlendCoeff fSrcCoeff;
784 skgpu::BlendCoeff fDstCoeff;
785 SkPMColor4f fConstColor;
786 bool fConstColorValid;
787 TriState fEnabled;
788
789 void invalidate() {
790 fEquation = skgpu::BlendEquation::kIllegal;
791 fSrcCoeff = skgpu::BlendCoeff::kIllegal;
792 fDstCoeff = skgpu::BlendCoeff::kIllegal;
793 fConstColorValid = false;
794 fEnabled = kUnknown_TriState;
795 }
796 } fHWBlendState;
797
798 TriState fHWConservativeRasterEnabled;
799
800 TriState fHWWireframeEnabled;
801
802 GrStencilSettings fHWStencilSettings;
803 GrSurfaceOrigin fHWStencilOrigin;
804 TriState fHWStencilTestEnabled;
805
806 TriState fHWWriteToColor;
807 GrGpuResource::UniqueID fHWBoundRenderTargetUniqueID;
808 bool fHWBoundFramebufferIsMSAA;
809 TriState fHWSRGBFramebuffer;
810
811 class TextureUnitBindings {
812 public:
813 TextureUnitBindings() = default;
814 TextureUnitBindings(const TextureUnitBindings&) = delete;
815 TextureUnitBindings& operator=(const TextureUnitBindings&) = delete;
816
817 GrGpuResource::UniqueID boundID(GrGLenum target) const;
818 bool hasBeenModified(GrGLenum target) const;
819 void setBoundID(GrGLenum target, GrGpuResource::UniqueID);
820 void invalidateForScratchUse(GrGLenum target);
821 void invalidateAllTargets(bool markUnmodified);
822
823 private:
824 struct TargetBinding {
825 GrGpuResource::UniqueID fBoundResourceID;
826 bool fHasBeenModified = false;
827 };
828 TargetBinding fTargetBindings[3];
829 };
830 skia_private::AutoTArray<TextureUnitBindings> fHWTextureUnitBindings;
831
832 GrGLfloat fHWClearColor[4];
833
834 GrGLuint fBoundDrawFramebuffer = 0;
835
836 /** IDs for copy surface program. (3 sampler types) */
837 struct {
838 GrGLuint fProgram = 0;
839 GrGLint fTextureUniform = 0;
840 GrGLint fTexCoordXformUniform = 0;
841 GrGLint fPosXformUniform = 0;
842 } fCopyPrograms[3];
843 sk_sp<GrGLBuffer> fCopyProgramArrayBuffer;
844
845 /** IDs for texture mipmap program. (4 filter configurations) */
846 struct {
847 GrGLuint fProgram = 0;
848 GrGLint fTextureUniform = 0;
849 GrGLint fTexCoordXformUniform = 0;
850 } fMipmapPrograms[4];
851 sk_sp<GrGLBuffer> fMipmapProgramArrayBuffer;
852
853 static int TextureToCopyProgramIdx(GrTexture* texture);
854
855 static int TextureSizeToMipmapProgramIdx(int width, int height) {
856 const bool wide = (width > 1) && SkToBool(width & 0x1);
857 const bool tall = (height > 1) && SkToBool(height & 0x1);
858 return (wide ? 0x2 : 0x0) | (tall ? 0x1 : 0x0);
859 }
860
861 GrPrimitiveType fLastPrimitiveType;
862
863 GrGLTextureParameters::ResetTimestamp fResetTimestampForTextureParameters = 0;
864
865 class SamplerObjectCache;
866 std::unique_ptr<SamplerObjectCache> fSamplerObjectCache;
867
868 std::unique_ptr<GrGLOpsRenderPass> fCachedOpsRenderPass;
869
870 std::unique_ptr<GrStagingBufferManager> fStagingBufferManager;
871
872 GrGLFinishCallbacks fFinishCallbacks;
873
874 // If we've called a command that requires us to call glFlush than this will be set to true
875 // since we defer calling flush until submit time. When we call submitToGpu if this is true then
876 // we call glFlush and reset this to false.
877 bool fNeedsGLFlush = false;
878
879 SkDEBUGCODE(bool fIsExecutingCommandBuffer_DebugOnly = false;)
880
881 friend class GrGLPathRendering; // For accessing setTextureUnit.
882
883 using INHERITED = GrGpu;
884 };
885
886 #endif