Debian Codegraph @

src/gpu/ganesh/gl/GrGLGpu.cpp

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 #include "src/gpu/ganesh/gl/GrGLGpu.h"
9
10 #include "include/core/SkAlphaType.h"
11 #include "include/core/SkColor.h"
12 #include "include/core/SkColorSpace.h"
13 #include "include/core/SkData.h"
14 #include "include/core/SkRect.h"
15 #include "include/core/SkSize.h"
16 #include "include/core/SkString.h"
17 #include "include/core/SkSurface.h"
18 #include "include/core/SkTextureCompressionType.h"
19 #include "include/core/SkTypes.h"
20 #include "include/gpu/GpuTypes.h"
21 #include "include/gpu/ganesh/GrBackendSurface.h"
22 #include "include/gpu/ganesh/GrContextOptions.h"
23 #include "include/gpu/ganesh/GrDirectContext.h"
24 #include "include/gpu/ganesh/GrDriverBugWorkarounds.h"
25 #include "include/gpu/ganesh/GrTypes.h"
26 #include "include/gpu/ganesh/gl/GrGLConfig.h"
27 #include "include/private/base/SkFloatingPoint.h"
28 #include "include/private/base/SkMath.h"
29 #include "include/private/base/SkPoint_impl.h"
30 #include "include/private/base/SkTemplates.h"
31 #include "include/private/base/SkTo.h"
32 #include "src/base/SkScopeExit.h"
33 #include "src/core/SkCompressedDataUtils.h"
34 #include "src/core/SkLRUCache.h"
35 #include "src/core/SkMipmap.h"
36 #include "src/core/SkSLTypeShared.h"
37 #include "src/core/SkTraceEvent.h"
38 #include "src/gpu/RefCntedCallback.h"
39 #include "src/gpu/SkRenderEngineAbortf.h"
40 #include "src/gpu/Swizzle.h"
41 #include "src/gpu/ganesh/GrAttachment.h"
42 #include "src/gpu/ganesh/GrBackendSurfacePriv.h"
43 #include "src/gpu/ganesh/GrBackendUtils.h"
44 #include "src/gpu/ganesh/GrBuffer.h"
45 #include "src/gpu/ganesh/GrDataUtils.h"
46 #include "src/gpu/ganesh/GrDirectContextPriv.h"
47 #include "src/gpu/ganesh/GrGpuBuffer.h"
48 #include "src/gpu/ganesh/GrImageInfo.h"
49 #include "src/gpu/ganesh/GrPipeline.h"
50 #include "src/gpu/ganesh/GrProgramInfo.h"
51 #include "src/gpu/ganesh/GrRenderTarget.h"
52 #include "src/gpu/ganesh/GrRenderTargetProxy.h"
53 #include "src/gpu/ganesh/GrSemaphore.h"
54 #include "src/gpu/ganesh/GrShaderCaps.h"
55 #include "src/gpu/ganesh/GrShaderVar.h"
56 #include "src/gpu/ganesh/GrStagingBufferManager.h"
57 #include "src/gpu/ganesh/GrSurface.h"
58 #include "src/gpu/ganesh/GrSurfaceProxy.h"
59 #include "src/gpu/ganesh/GrTexture.h"
60 #include "src/gpu/ganesh/GrUtil.h"
61 #include "src/gpu/ganesh/GrWindowRectangles.h"
62 #include "src/gpu/ganesh/gl/GrGLAttachment.h"
63 #include "src/gpu/ganesh/gl/GrGLBackendSurfacePriv.h"
64 #include "src/gpu/ganesh/gl/GrGLBuffer.h"
65 #include "src/gpu/ganesh/gl/GrGLOpsRenderPass.h"
66 #include "src/gpu/ganesh/gl/GrGLProgram.h"
67 #include "src/gpu/ganesh/gl/GrGLSemaphore.h"
68 #include "src/gpu/ganesh/gl/GrGLTextureRenderTarget.h"
69 #include "src/gpu/ganesh/gl/builders/GrGLShaderStringBuilder.h"
70 #include "src/sksl/SkSLProgramKind.h"
71 #include "src/sksl/SkSLProgramSettings.h"
72 #include "src/sksl/codegen/SkSLNativeShader.h"
73 #include "src/sksl/ir/SkSLProgram.h"
74
75 #include <algorithm>
76 #include <cmath>
77 #include <functional>
78 #include <memory>
79 #include <string>
80 #include <utility>
81
82 #if defined(__EMSCRIPTEN__)
83 #include <emscripten/version.h>
84 #endif
85
86 namespace skgpu { class MutableTextureState; }
87
88 using namespace skia_private;
89
90 #define GL_CALL(X) GR_GL_CALL(this->glInterface(), X)
91 #define GL_CALL_RET(RET, X) GR_GL_CALL_RET(this->glInterface(), RET, X)
92
93 #define GL_ALLOC_CALL(call) \
94 [&] { \
95 if (this->glCaps().skipErrorChecks()) { \
96 GR_GL_CALL(this->glInterface(), call); \
97 return static_cast<GrGLenum>(GR_GL_NO_ERROR); \
98 } else { \
99 this->clearErrorsAndCheckForOOM(); \
100 GR_GL_CALL_NOERRCHECK(this->glInterface(), call); \
101 return this->getErrorAndCheckForOOM(); \
102 } \
103 }()
104
105 //#define USE_NSIGHT
106
107 ///////////////////////////////////////////////////////////////////////////////
108
109 static const GrGLenum gXfermodeEquation2Blend[] = {
110 // Basic OpenGL blend equations.
111 GR_GL_FUNC_ADD,
112 GR_GL_FUNC_SUBTRACT,
113 GR_GL_FUNC_REVERSE_SUBTRACT,
114
115 // GL_KHR_blend_equation_advanced.
116 GR_GL_SCREEN,
117 GR_GL_OVERLAY,
118 GR_GL_DARKEN,
119 GR_GL_LIGHTEN,
120 GR_GL_COLORDODGE,
121 GR_GL_COLORBURN,
122 GR_GL_HARDLIGHT,
123 GR_GL_SOFTLIGHT,
124 GR_GL_DIFFERENCE,
125 GR_GL_EXCLUSION,
126 GR_GL_MULTIPLY,
127 GR_GL_HSL_HUE,
128 GR_GL_HSL_SATURATION,
129 GR_GL_HSL_COLOR,
130 GR_GL_HSL_LUMINOSITY,
131
132 // Illegal... needs to map to something.
133 GR_GL_FUNC_ADD,
134 };
135 static_assert(0 == (int)skgpu::BlendEquation::kAdd);
136 static_assert(1 == (int)skgpu::BlendEquation::kSubtract);
137 static_assert(2 == (int)skgpu::BlendEquation::kReverseSubtract);
138 static_assert(3 == (int)skgpu::BlendEquation::kScreen);
139 static_assert(4 == (int)skgpu::BlendEquation::kOverlay);
140 static_assert(5 == (int)skgpu::BlendEquation::kDarken);
141 static_assert(6 == (int)skgpu::BlendEquation::kLighten);
142 static_assert(7 == (int)skgpu::BlendEquation::kColorDodge);
143 static_assert(8 == (int)skgpu::BlendEquation::kColorBurn);
144 static_assert(9 == (int)skgpu::BlendEquation::kHardLight);
145 static_assert(10 == (int)skgpu::BlendEquation::kSoftLight);
146 static_assert(11 == (int)skgpu::BlendEquation::kDifference);
147 static_assert(12 == (int)skgpu::BlendEquation::kExclusion);
148 static_assert(13 == (int)skgpu::BlendEquation::kMultiply);
149 static_assert(14 == (int)skgpu::BlendEquation::kHSLHue);
150 static_assert(15 == (int)skgpu::BlendEquation::kHSLSaturation);
151 static_assert(16 == (int)skgpu::BlendEquation::kHSLColor);
152 static_assert(17 == (int)skgpu::BlendEquation::kHSLLuminosity);
153 static_assert(std::size(gXfermodeEquation2Blend) == skgpu::kBlendEquationCnt);
154
155 static const GrGLenum gXfermodeCoeff2Blend[] = {
156 GR_GL_ZERO,
157 GR_GL_ONE,
158 GR_GL_SRC_COLOR,
159 GR_GL_ONE_MINUS_SRC_COLOR,
160 GR_GL_DST_COLOR,
161 GR_GL_ONE_MINUS_DST_COLOR,
162 GR_GL_SRC_ALPHA,
163 GR_GL_ONE_MINUS_SRC_ALPHA,
164 GR_GL_DST_ALPHA,
165 GR_GL_ONE_MINUS_DST_ALPHA,
166 GR_GL_CONSTANT_COLOR,
167 GR_GL_ONE_MINUS_CONSTANT_COLOR,
168
169 // extended blend coeffs
170 GR_GL_SRC1_COLOR,
171 GR_GL_ONE_MINUS_SRC1_COLOR,
172 GR_GL_SRC1_ALPHA,
173 GR_GL_ONE_MINUS_SRC1_ALPHA,
174
175 // Illegal... needs to map to something.
176 GR_GL_ZERO,
177 };
178
179 //////////////////////////////////////////////////////////////////////////////
180
181 static int gl_target_to_binding_index(GrGLenum target) {
182 switch (target) {
183 case GR_GL_TEXTURE_2D:
184 return 0;
185 case GR_GL_TEXTURE_RECTANGLE:
186 return 1;
187 case GR_GL_TEXTURE_EXTERNAL:
188 return 2;
189 }
190 SK_ABORT("Unexpected GL texture target.");
191 }
192
193 GrGpuResource::UniqueID GrGLGpu::TextureUnitBindings::boundID(GrGLenum target) const {
194 return fTargetBindings[gl_target_to_binding_index(target)].fBoundResourceID;
195 }
196
197 bool GrGLGpu::TextureUnitBindings::hasBeenModified(GrGLenum target) const {
198 return fTargetBindings[gl_target_to_binding_index(target)].fHasBeenModified;
199 }
200
201 void GrGLGpu::TextureUnitBindings::setBoundID(GrGLenum target, GrGpuResource::UniqueID resourceID) {
202 int targetIndex = gl_target_to_binding_index(target);
203 fTargetBindings[targetIndex].fBoundResourceID = resourceID;
204 fTargetBindings[targetIndex].fHasBeenModified = true;
205 }
206
207 void GrGLGpu::TextureUnitBindings::invalidateForScratchUse(GrGLenum target) {
208 this->setBoundID(target, GrGpuResource::UniqueID());
209 }
210
211 void GrGLGpu::TextureUnitBindings::invalidateAllTargets(bool markUnmodified) {
212 for (auto& targetBinding : fTargetBindings) {
213 targetBinding.fBoundResourceID.makeInvalid();
214 if (markUnmodified) {
215 targetBinding.fHasBeenModified = false;
216 }
217 }
218 }
219
220 //////////////////////////////////////////////////////////////////////////////
221
222 static GrGLenum filter_to_gl_mag_filter(GrSamplerState::Filter filter) {
223 switch (filter) {
224 case GrSamplerState::Filter::kNearest: return GR_GL_NEAREST;
225 case GrSamplerState::Filter::kLinear: return GR_GL_LINEAR;
226 }
227 SkUNREACHABLE;
228 }
229
230 static GrGLenum filter_to_gl_min_filter(GrSamplerState::Filter filter,
231 GrSamplerState::MipmapMode mm) {
232 switch (mm) {
233 case GrSamplerState::MipmapMode::kNone:
234 return filter_to_gl_mag_filter(filter);
235 case GrSamplerState::MipmapMode::kNearest:
236 switch (filter) {
237 case GrSamplerState::Filter::kNearest: return GR_GL_NEAREST_MIPMAP_NEAREST;
238 case GrSamplerState::Filter::kLinear: return GR_GL_LINEAR_MIPMAP_NEAREST;
239 }
240 SkUNREACHABLE;
241 case GrSamplerState::MipmapMode::kLinear:
242 switch (filter) {
243 case GrSamplerState::Filter::kNearest: return GR_GL_NEAREST_MIPMAP_LINEAR;
244 case GrSamplerState::Filter::kLinear: return GR_GL_LINEAR_MIPMAP_LINEAR;
245 }
246 SkUNREACHABLE;
247 }
248 SkUNREACHABLE;
249 }
250
251 static inline GrGLenum wrap_mode_to_gl_wrap(GrSamplerState::WrapMode wrapMode,
252 const GrCaps& caps) {
253 switch (wrapMode) {
254 case GrSamplerState::WrapMode::kClamp: return GR_GL_CLAMP_TO_EDGE;
255 case GrSamplerState::WrapMode::kRepeat: return GR_GL_REPEAT;
256 case GrSamplerState::WrapMode::kMirrorRepeat: return GR_GL_MIRRORED_REPEAT;
257 case GrSamplerState::WrapMode::kClampToBorder:
258 // May not be supported but should have been caught earlier
259 SkASSERT(caps.clampToBorderSupport());
260 return GR_GL_CLAMP_TO_BORDER;
261 }
262 SkUNREACHABLE;
263 }
264
265 ///////////////////////////////////////////////////////////////////////////////
266
267 static void cleanup_program(GrGLGpu* gpu,
268 GrGLuint* programID,
269 GrGLuint* vshader,
270 GrGLuint* fshader) {
271 const GrGLInterface* gli = gpu->glInterface();
272 if (programID) {
273 GR_GL_CALL(gli, DeleteProgram(*programID));
274 *programID = 0;
275 }
276 if (vshader) {
277 GR_GL_CALL(gli, DeleteShader(*vshader));
278 *vshader = 0;
279 }
280 if (fshader) {
281 GR_GL_CALL(gli, DeleteShader(*fshader));
282 *fshader = 0;
283 }
284 }
285
286 ///////////////////////////////////////////////////////////////////////////////
287
288 class GrGLGpu::SamplerObjectCache {
289 public:
290 SamplerObjectCache(GrGLGpu* gpu) : fGpu(gpu) {
291 fNumTextureUnits = fGpu->glCaps().shaderCaps()->fMaxFragmentSamplers;
292 fTextureUnitStates = std::make_unique<UnitState[]>(fNumTextureUnits);
293 }
294
295 ~SamplerObjectCache() {
296 if (!fNumTextureUnits) {
297 // We've already been abandoned.
298 return;
299 }
300 }
301
302 void bindSampler(int unitIdx, GrSamplerState state) {
303 if (unitIdx >= fNumTextureUnits) {
304 return;
305 }
306 // In GL the max aniso value is specified in addition to min/mag filters and the driver
307 // is encouraged to consider the other filter settings when doing aniso.
308 uint32_t key = state.asKey(/*anisoIsOrthogonal=*/true);
309 const Sampler* sampler = fSamplers.find(key);
310 if (!sampler) {
311 GrGLuint s;
312 GR_GL_CALL(fGpu->glInterface(), GenSamplers(1, &s));
313 if (!s) {
314 return;
315 }
316 sampler = fSamplers.insert(key, Sampler(s, fGpu->glInterface()));
317 GrGLenum minFilter = filter_to_gl_min_filter(state.filter(), state.mipmapMode());
318 GrGLenum magFilter = filter_to_gl_mag_filter(state.filter());
319 GrGLenum wrapX = wrap_mode_to_gl_wrap(state.wrapModeX(), fGpu->glCaps());
320 GrGLenum wrapY = wrap_mode_to_gl_wrap(state.wrapModeY(), fGpu->glCaps());
321 GR_GL_CALL(fGpu->glInterface(),
322 SamplerParameteri(s, GR_GL_TEXTURE_MIN_FILTER, minFilter));
323 GR_GL_CALL(fGpu->glInterface(),
324 SamplerParameteri(s, GR_GL_TEXTURE_MAG_FILTER, magFilter));
325 GR_GL_CALL(fGpu->glInterface(), SamplerParameteri(s, GR_GL_TEXTURE_WRAP_S, wrapX));
326 GR_GL_CALL(fGpu->glInterface(), SamplerParameteri(s, GR_GL_TEXTURE_WRAP_T, wrapY));
327 SkASSERT(fGpu->glCaps().anisoSupport() || !state.isAniso());
328 if (fGpu->glCaps().anisoSupport()) {
329 float maxAniso = std::min(static_cast<GrGLfloat>(state.maxAniso()),
330 fGpu->glCaps().maxTextureMaxAnisotropy());
331 GR_GL_CALL(fGpu->glInterface(), SamplerParameterf(s,
332 GR_GL_TEXTURE_MAX_ANISOTROPY,
333 maxAniso));
334 }
335 }
336 SkASSERT(sampler && sampler->id());
337 if (!fTextureUnitStates[unitIdx].fKnown ||
338 fTextureUnitStates[unitIdx].fSamplerIDIfKnown != sampler->id()) {
339 GR_GL_CALL(fGpu->glInterface(), BindSampler(unitIdx, sampler->id()));
340 fTextureUnitStates[unitIdx].fSamplerIDIfKnown = sampler->id();
341 fTextureUnitStates[unitIdx].fKnown = true;
342 }
343 }
344
345 void unbindSampler(int unitIdx) {
346 if (!fTextureUnitStates[unitIdx].fKnown ||
347 fTextureUnitStates[unitIdx].fSamplerIDIfKnown != 0) {
348 GR_GL_CALL(fGpu->glInterface(), BindSampler(unitIdx, 0));
349 fTextureUnitStates[unitIdx].fSamplerIDIfKnown = 0;
350 fTextureUnitStates[unitIdx].fKnown = true;
351 }
352 }
353
354 void invalidateBindings() {
355 std::fill_n(fTextureUnitStates.get(), fNumTextureUnits, UnitState{});
356 }
357
358 void abandon() {
359 fSamplers.foreach([](const uint32_t* key, Sampler* sampler) { sampler->abandon(); });
360 fTextureUnitStates.reset();
361 fNumTextureUnits = 0;
362 }
363
364 void release() {
365 if (!fNumTextureUnits) {
366 // We've already been abandoned.
367 return;
368 }
369 fSamplers.reset();
370 // Deleting a bound sampler implicitly binds sampler 0. We just invalidate all of our
371 // knowledge.
372 std::fill_n(fTextureUnitStates.get(), fNumTextureUnits, UnitState{});
373 }
374
375 private:
376 class Sampler {
377 public:
378 Sampler() = default;
379 Sampler(const Sampler&) = delete;
380
381 Sampler(Sampler&& that) {
382 fID = that.fID;
383 fInterface = that.fInterface;
384 that.fID = 0;
385 }
386
387 Sampler(GrGLuint id, const GrGLInterface* interface) : fID(id), fInterface(interface) {}
388
389 ~Sampler() {
390 if (fID) {
391 GR_GL_CALL(fInterface, DeleteSamplers(1, &fID));
392 }
393 }
394
395 GrGLuint id() const { return fID; }
396
397 void abandon() { fID = 0; }
398
399 private:
400 GrGLuint fID = 0;
401 const GrGLInterface* fInterface = nullptr;
402 };
403
404 struct UnitState {
405 bool fKnown = false;
406 GrGLuint fSamplerIDIfKnown = 0;
407 };
408
409 static constexpr int kMaxSamplers = 32;
410
411 SkLRUCache<uint32_t, Sampler> fSamplers{kMaxSamplers};
412 std::unique_ptr<UnitState[]> fTextureUnitStates;
413 GrGLGpu* fGpu;
414 int fNumTextureUnits;
415 };
416
417 ///////////////////////////////////////////////////////////////////////////////
418
419 std::unique_ptr<GrGpu> GrGLGpu::Make(sk_sp<const GrGLInterface> interface,
420 const GrContextOptions& options,
421 GrDirectContext* direct) {
422 #if !defined(SK_DISABLE_LEGACY_GL_MAKE_NATIVE_INTERFACE)
423 if (!interface) {
424 interface = GrGLMakeNativeInterface();
425 if (!interface) {
426 return nullptr;
427 }
428 }
429 #else
430 if (!interface) {
431 return nullptr;
432 }
433 #endif
434 #ifdef USE_NSIGHT
435 const_cast<GrContextOptions&>(options).fSuppressPathRendering = true;
436 #endif
437 auto glContext = GrGLContext::Make(std::move(interface), options);
438 if (!glContext) {
439 return nullptr;
440 }
441 return std::unique_ptr<GrGpu>(new GrGLGpu(std::move(glContext), direct));
442 }
443
444 GrGLGpu::GrGLGpu(std::unique_ptr<GrGLContext> ctx, GrDirectContext* dContext)
445 : GrGpu(dContext)
446 , fGLContext(std::move(ctx))
447 , fProgramCache(new ProgramCache(dContext->priv().options().fRuntimeProgramCacheSize))
448 , fHWProgramID(0)
449 , fTempSrcFBOID(0)
450 , fTempDstFBOID(0)
451 , fStencilClearFBOID(0)
452 , fFinishCallbacks(this) {
453 SkASSERT(fGLContext);
454 // Clear errors so we don't get confused whether we caused an error.
455 this->clearErrorsAndCheckForOOM();
456 // Toss out any pre-existing OOM that was hanging around before we got started.
457 this->checkAndResetOOMed();
458
459 this->initCaps(sk_ref_sp(fGLContext->caps()));
460
461 fHWTextureUnitBindings.reset(this->numTextureUnits());
462
463 this->hwBufferState(GrGpuBufferType::kVertex)->fGLTarget = GR_GL_ARRAY_BUFFER;
464 this->hwBufferState(GrGpuBufferType::kIndex)->fGLTarget = GR_GL_ELEMENT_ARRAY_BUFFER;
465 this->hwBufferState(GrGpuBufferType::kDrawIndirect)->fGLTarget = GR_GL_DRAW_INDIRECT_BUFFER;
466 if (GrGLCaps::TransferBufferType::kChromium == this->glCaps().transferBufferType()) {
467 this->hwBufferState(GrGpuBufferType::kXferCpuToGpu)->fGLTarget =
468 GR_GL_PIXEL_UNPACK_TRANSFER_BUFFER_CHROMIUM;
469 this->hwBufferState(GrGpuBufferType::kXferGpuToCpu)->fGLTarget =
470 GR_GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM;
471 } else {
472 this->hwBufferState(GrGpuBufferType::kXferCpuToGpu)->fGLTarget = GR_GL_PIXEL_UNPACK_BUFFER;
473 this->hwBufferState(GrGpuBufferType::kXferGpuToCpu)->fGLTarget = GR_GL_PIXEL_PACK_BUFFER;
474 }
475 for (int i = 0; i < kGrGpuBufferTypeCount; ++i) {
476 fHWBufferState[i].invalidate();
477 }
478
479 if (this->glCaps().useSamplerObjects()) {
480 fSamplerObjectCache = std::make_unique<SamplerObjectCache>(this);
481 }
482 }
483
484 GrGLGpu::~GrGLGpu() {
485 // Ensure any GrGpuResource objects get deleted first, since they may require a working GrGLGpu
486 // to release the resources held by the objects themselves.
487 fCopyProgramArrayBuffer.reset();
488 fMipmapProgramArrayBuffer.reset();
489 if (fProgramCache) {
490 fProgramCache->reset();
491 }
492
493 fHWProgram.reset();
494 if (fHWProgramID) {
495 // detach the current program so there is no confusion on OpenGL's part
496 // that we want it to be deleted
497 GL_CALL(UseProgram(0));
498 }
499
500 if (fTempSrcFBOID) {
501 this->deleteFramebuffer(fTempSrcFBOID);
502 }
503 if (fTempDstFBOID) {
504 this->deleteFramebuffer(fTempDstFBOID);
505 }
506 if (fStencilClearFBOID) {
507 this->deleteFramebuffer(fStencilClearFBOID);
508 }
509
510 for (size_t i = 0; i < std::size(fCopyPrograms); ++i) {
511 if (0 != fCopyPrograms[i].fProgram) {
512 GL_CALL(DeleteProgram(fCopyPrograms[i].fProgram));
513 }
514 }
515
516 for (size_t i = 0; i < std::size(fMipmapPrograms); ++i) {
517 if (0 != fMipmapPrograms[i].fProgram) {
518 GL_CALL(DeleteProgram(fMipmapPrograms[i].fProgram));
519 }
520 }
521
522 fSamplerObjectCache.reset();
523
524 fFinishCallbacks.callAll(true);
525 }
526
527 void GrGLGpu::disconnect(DisconnectType type) {
528 INHERITED::disconnect(type);
529 if (DisconnectType::kCleanup == type) {
530 if (fHWProgramID) {
531 GL_CALL(UseProgram(0));
532 }
533 if (fTempSrcFBOID) {
534 this->deleteFramebuffer(fTempSrcFBOID);
535 }
536 if (fTempDstFBOID) {
537 this->deleteFramebuffer(fTempDstFBOID);
538 }
539 if (fStencilClearFBOID) {
540 this->deleteFramebuffer(fStencilClearFBOID);
541 }
542 for (size_t i = 0; i < std::size(fCopyPrograms); ++i) {
543 if (fCopyPrograms[i].fProgram) {
544 GL_CALL(DeleteProgram(fCopyPrograms[i].fProgram));
545 }
546 }
547 for (size_t i = 0; i < std::size(fMipmapPrograms); ++i) {
548 if (fMipmapPrograms[i].fProgram) {
549 GL_CALL(DeleteProgram(fMipmapPrograms[i].fProgram));
550 }
551 }
552
553 if (fSamplerObjectCache) {
554 fSamplerObjectCache->release();
555 }
556 } else {
557 if (fProgramCache) {
558 fProgramCache->abandon();
559 }
560 if (fSamplerObjectCache) {
561 fSamplerObjectCache->abandon();
562 }
563 }
564
565 fHWProgram.reset();
566 fProgramCache->reset();
567 fProgramCache.reset();
568
569 fHWProgramID = 0;
570 fTempSrcFBOID = 0;
571 fTempDstFBOID = 0;
572 fStencilClearFBOID = 0;
573 fCopyProgramArrayBuffer.reset();
574 for (size_t i = 0; i < std::size(fCopyPrograms); ++i) {
575 fCopyPrograms[i].fProgram = 0;
576 }
577 fMipmapProgramArrayBuffer.reset();
578 for (size_t i = 0; i < std::size(fMipmapPrograms); ++i) {
579 fMipmapPrograms[i].fProgram = 0;
580 }
581
582 fFinishCallbacks.callAll(/* doDelete */ DisconnectType::kCleanup == type);
583 }
584
585 GrThreadSafePipelineBuilder* GrGLGpu::pipelineBuilder() {
586 return fProgramCache.get();
587 }
588
589 sk_sp<GrThreadSafePipelineBuilder> GrGLGpu::refPipelineBuilder() {
590 return fProgramCache;
591 }
592
593 ///////////////////////////////////////////////////////////////////////////////
594
595 void GrGLGpu::onResetContext(uint32_t resetBits) {
596 if (resetBits & kMisc_GrGLBackendState) {
597 // we don't use the zb at all
598 GL_CALL(Disable(GR_GL_DEPTH_TEST));
599 GL_CALL(DepthMask(GR_GL_FALSE));
600
601 // We don't use face culling.
602 GL_CALL(Disable(GR_GL_CULL_FACE));
603 // We do use separate stencil. Our algorithms don't care which face is front vs. back so
604 // just set this to the default for self-consistency.
605 GL_CALL(FrontFace(GR_GL_CCW));
606
607 this->hwBufferState(GrGpuBufferType::kXferCpuToGpu)->invalidate();
608 this->hwBufferState(GrGpuBufferType::kXferGpuToCpu)->invalidate();
609
610 if (GR_IS_GR_GL(this->glStandard())) {
611 #ifndef USE_NSIGHT
612 // Desktop-only state that we never change
613 if (!this->glCaps().isCoreProfile()) {
614 GL_CALL(Disable(GR_GL_POINT_SMOOTH));
615 GL_CALL(Disable(GR_GL_LINE_SMOOTH));
616 GL_CALL(Disable(GR_GL_POLYGON_SMOOTH));
617 GL_CALL(Disable(GR_GL_POLYGON_STIPPLE));
618 GL_CALL(Disable(GR_GL_COLOR_LOGIC_OP));
619 GL_CALL(Disable(GR_GL_INDEX_LOGIC_OP));
620 }
621 // The windows NVIDIA driver has GL_ARB_imaging in the extension string when using a
622 // core profile. This seems like a bug since the core spec removes any mention of
623 // GL_ARB_imaging.
624 if (this->glCaps().imagingSupport() && !this->glCaps().isCoreProfile()) {
625 GL_CALL(Disable(GR_GL_COLOR_TABLE));
626 }
627 GL_CALL(Disable(GR_GL_POLYGON_OFFSET_FILL));
628
629 fHWWireframeEnabled = kUnknown_TriState;
630 #endif
631 // Since ES doesn't support glPointSize at all we always use the VS to
632 // set the point size
633 GL_CALL(Enable(GR_GL_VERTEX_PROGRAM_POINT_SIZE));
634
635 }
636
637 if (GR_IS_GR_GL_ES(this->glStandard()) &&
638 this->glCaps().fbFetchRequiresEnablePerSample()) {
639 // The arm extension requires specifically enabling MSAA fetching per sample.
640 // On some devices this may have a perf hit. Also multiple render targets are disabled
641 GL_CALL(Enable(GR_GL_FETCH_PER_SAMPLE));
642 }
643 fHWWriteToColor = kUnknown_TriState;
644 // we only ever use lines in hairline mode
645 GL_CALL(LineWidth(1));
646 GL_CALL(Disable(GR_GL_DITHER));
647
648 fHWClearColor[0] = fHWClearColor[1] = fHWClearColor[2] = fHWClearColor[3] = SK_FloatNaN;
649 }
650
651 if (resetBits & kMSAAEnable_GrGLBackendState) {
652 if (this->glCaps().clientCanDisableMultisample()) {
653 // Restore GL_MULTISAMPLE to its initial state. It being enabled has no effect on draws
654 // to non-MSAA targets.
655 GL_CALL(Enable(GR_GL_MULTISAMPLE));
656 }
657 fHWConservativeRasterEnabled = kUnknown_TriState;
658 }
659
660 fHWActiveTextureUnitIdx = -1; // invalid
661 fLastPrimitiveType = static_cast<GrPrimitiveType>(-1);
662
663 if (resetBits & kTextureBinding_GrGLBackendState) {
664 for (int s = 0; s < this->numTextureUnits(); ++s) {
665 fHWTextureUnitBindings[s].invalidateAllTargets(false);
666 }
667 if (fSamplerObjectCache) {
668 fSamplerObjectCache->invalidateBindings();
669 }
670 }
671
672 if (resetBits & kBlend_GrGLBackendState) {
673 fHWBlendState.invalidate();
674 }
675
676 if (resetBits & kView_GrGLBackendState) {
677 fHWScissorSettings.invalidate();
678 fHWWindowRectsState.invalidate();
679 fHWViewport.invalidate();
680 }
681
682 if (resetBits & kStencil_GrGLBackendState) {
683 fHWStencilSettings.invalidate();
684 fHWStencilTestEnabled = kUnknown_TriState;
685 }
686
687 // Vertex
688 if (resetBits & kVertex_GrGLBackendState) {
689 fHWVertexArrayState.invalidate();
690 this->hwBufferState(GrGpuBufferType::kVertex)->invalidate();
691 this->hwBufferState(GrGpuBufferType::kIndex)->invalidate();
692 this->hwBufferState(GrGpuBufferType::kDrawIndirect)->invalidate();
693 }
694
695 if (resetBits & kRenderTarget_GrGLBackendState) {
696 fHWBoundRenderTargetUniqueID.makeInvalid();
697 fHWSRGBFramebuffer = kUnknown_TriState;
698 fBoundDrawFramebuffer = 0;
699 }
700
701 // we assume these values
702 if (resetBits & kPixelStore_GrGLBackendState) {
703 if (this->caps()->writePixelsRowBytesSupport() ||
704 this->caps()->transferPixelsToRowBytesSupport()) {
705 GL_CALL(PixelStorei(GR_GL_UNPACK_ROW_LENGTH, 0));
706 }
707 if (this->glCaps().readPixelsRowBytesSupport()) {
708 GL_CALL(PixelStorei(GR_GL_PACK_ROW_LENGTH, 0));
709 }
710 if (this->glCaps().packFlipYSupport()) {
711 GL_CALL(PixelStorei(GR_GL_PACK_REVERSE_ROW_ORDER, GR_GL_FALSE));
712 }
713 }
714
715 if (resetBits & kProgram_GrGLBackendState) {
716 fHWProgramID = 0;
717 fHWProgram.reset();
718 }
719 ++fResetTimestampForTextureParameters;
720 }
721
722 static bool check_backend_texture(const GrBackendTexture& backendTex,
723 const GrGLCaps& caps,
724 GrGLTexture::Desc* desc,
725 bool skipRectTexSupportCheck = false) {
726 GrGLTextureInfo info;
727 if (!GrBackendTextures::GetGLTextureInfo(backendTex, &info) || !info.fID || !info.fFormat) {
728 return false;
729 }
730
731 if (info.fProtected == skgpu::Protected::kYes && !caps.supportsProtectedContent()) {
732 return false;
733 }
734
735 desc->fSize = {backendTex.width(), backendTex.height()};
736 desc->fTarget = info.fTarget;
737 desc->fID = info.fID;
738 desc->fFormat = GrGLFormatFromGLEnum(info.fFormat);
739 desc->fIsProtected = skgpu::Protected(info.fProtected == skgpu::Protected::kYes ||
740 caps.strictProtectedness());
741
742 if (desc->fFormat == GrGLFormat::kUnknown) {
743 return false;
744 }
745 if (GR_GL_TEXTURE_EXTERNAL == desc->fTarget) {
746 if (!caps.shaderCaps()->fExternalTextureSupport) {
747 return false;
748 }
749 } else if (GR_GL_TEXTURE_RECTANGLE == desc->fTarget) {
750 if (!caps.rectangleTextureSupport() && !skipRectTexSupportCheck) {
751 return false;
752 }
753 } else if (GR_GL_TEXTURE_2D != desc->fTarget) {
754 return false;
755 }
756
757
758 return true;
759 }
760
761 static sk_sp<GrGLTextureParameters> get_gl_texture_params(const GrBackendTexture& backendTex) {
762 const GrBackendTextureData* btd = GrBackendSurfacePriv::GetBackendData(backendTex);
763 auto glTextureData = static_cast<const GrGLBackendTextureData*>(btd);
764 SkASSERT(glTextureData);
765 return glTextureData->info().refParameters();
766 }
767
768 sk_sp<GrTexture> GrGLGpu::onWrapBackendTexture(const GrBackendTexture& backendTex,
769 GrWrapOwnership ownership,
770 GrWrapCacheable cacheable,
771 GrIOType ioType) {
772 GrGLTexture::Desc desc;
773 if (!check_backend_texture(backendTex, this->glCaps(), &desc)) {
774 return nullptr;
775 }
776
777 if (kBorrow_GrWrapOwnership == ownership) {
778 desc.fOwnership = GrBackendObjectOwnership::kBorrowed;
779 } else {
780 desc.fOwnership = GrBackendObjectOwnership::kOwned;
781 }
782
783 GrMipmapStatus mipmapStatus = backendTex.hasMipmaps() ? GrMipmapStatus::kValid
784 : GrMipmapStatus::kNotAllocated;
785
786 auto texture = GrGLTexture::MakeWrapped(this,
787 mipmapStatus,
788 desc,
789 get_gl_texture_params(backendTex),
790 cacheable,
791 ioType,
792 backendTex.getLabel());
793 if (this->glCaps().isFormatRenderable(backendTex.getBackendFormat(), 1)) {
794 // Pessimistically assume this external texture may have been bound to a FBO.
795 texture->baseLevelWasBoundToFBO();
796 }
797 return texture;
798 }
799
800 static bool check_compressed_backend_texture(const GrBackendTexture& backendTex,
801 const GrGLCaps& caps, GrGLTexture::Desc* desc,
802 bool skipRectTexSupportCheck = false) {
803 GrGLTextureInfo info;
804 if (!GrBackendTextures::GetGLTextureInfo(backendTex, &info) || !info.fID || !info.fFormat) {
805 return false;
806 }
807 if (info.fProtected == skgpu::Protected::kYes && !caps.supportsProtectedContent()) {
808 return false;
809 }
810
811 desc->fSize = {backendTex.width(), backendTex.height()};
812 desc->fTarget = info.fTarget;
813 desc->fID = info.fID;
814 desc->fFormat = GrGLFormatFromGLEnum(info.fFormat);
815 desc->fIsProtected = skgpu::Protected(info.fProtected == skgpu::Protected::kYes ||
816 caps.strictProtectedness());
817
818 if (desc->fFormat == GrGLFormat::kUnknown) {
819 return false;
820 }
821
822 if (GR_GL_TEXTURE_2D != desc->fTarget) {
823 return false;
824 }
825
826 return true;
827 }
828
829 sk_sp<GrTexture> GrGLGpu::onWrapCompressedBackendTexture(const GrBackendTexture& backendTex,
830 GrWrapOwnership ownership,
831 GrWrapCacheable cacheable) {
832 GrGLTexture::Desc desc;
833 if (!check_compressed_backend_texture(backendTex, this->glCaps(), &desc)) {
834 return nullptr;
835 }
836
837 if (kBorrow_GrWrapOwnership == ownership) {
838 desc.fOwnership = GrBackendObjectOwnership::kBorrowed;
839 } else {
840 desc.fOwnership = GrBackendObjectOwnership::kOwned;
841 }
842
843 GrMipmapStatus mipmapStatus = backendTex.hasMipmaps() ? GrMipmapStatus::kValid
844 : GrMipmapStatus::kNotAllocated;
845
846 return GrGLTexture::MakeWrapped(this,
847 mipmapStatus,
848 desc,
849 get_gl_texture_params(backendTex),
850 cacheable,
851 kRead_GrIOType,
852 backendTex.getLabel());
853 }
854
855 sk_sp<GrTexture> GrGLGpu::onWrapRenderableBackendTexture(const GrBackendTexture& backendTex,
856 int sampleCnt,
857 GrWrapOwnership ownership,
858 GrWrapCacheable cacheable) {
859 const GrGLCaps& caps = this->glCaps();
860
861 GrGLTexture::Desc desc;
862 if (!check_backend_texture(backendTex, this->glCaps(), &desc)) {
863 return nullptr;
864 }
865 SkASSERT(caps.isFormatRenderable(desc.fFormat, sampleCnt));
866 SkASSERT(caps.isFormatTexturable(desc.fFormat));
867
868 // We don't support rendering to a EXTERNAL texture.
869 if (GR_GL_TEXTURE_EXTERNAL == desc.fTarget) {
870 return nullptr;
871 }
872
873 if (kBorrow_GrWrapOwnership == ownership) {
874 desc.fOwnership = GrBackendObjectOwnership::kBorrowed;
875 } else {
876 desc.fOwnership = GrBackendObjectOwnership::kOwned;
877 }
878
879
880 sampleCnt = caps.getRenderTargetSampleCount(sampleCnt, desc.fFormat);
881 SkASSERT(sampleCnt);
882
883 GrGLRenderTarget::IDs rtIDs;
884 if (!this->createRenderTargetObjects(desc, sampleCnt, &rtIDs)) {
885 return nullptr;
886 }
887
888 GrMipmapStatus mipmapStatus = backendTex.hasMipmaps() ? GrMipmapStatus::kDirty
889 : GrMipmapStatus::kNotAllocated;
890
891 sk_sp<GrGLTextureRenderTarget> texRT(
892 GrGLTextureRenderTarget::MakeWrapped(this,
893 sampleCnt,
894 desc,
895 get_gl_texture_params(backendTex),
896 rtIDs,
897 cacheable,
898 mipmapStatus,
899 backendTex.getLabel()));
900 texRT->baseLevelWasBoundToFBO();
901 return texRT;
902 }
903
904 sk_sp<GrRenderTarget> GrGLGpu::onWrapBackendRenderTarget(const GrBackendRenderTarget& backendRT) {
905 GrGLFramebufferInfo info;
906 if (!GrBackendRenderTargets::GetGLFramebufferInfo(backendRT, &info)) {
907 return nullptr;
908 }
909
910 if (backendRT.isProtected() && !this->glCaps().supportsProtectedContent()) {
911 return nullptr;
912 }
913
914 const auto format = GrBackendFormats::AsGLFormat(backendRT.getBackendFormat());
915 if (!this->glCaps().isFormatRenderable(format, backendRT.sampleCnt())) {
916 return nullptr;
917 }
918
919 int sampleCount = this->glCaps().getRenderTargetSampleCount(backendRT.sampleCnt(), format);
920
921 GrGLRenderTarget::IDs rtIDs;
922 if (sampleCount <= 1) {
923 rtIDs.fSingleSampleFBOID = info.fFBOID;
924 rtIDs.fMultisampleFBOID = GrGLRenderTarget::kUnresolvableFBOID;
925 } else {
926 rtIDs.fSingleSampleFBOID = GrGLRenderTarget::kUnresolvableFBOID;
927 rtIDs.fMultisampleFBOID = info.fFBOID;
928 }
929 rtIDs.fMSColorRenderbufferID = 0;
930 rtIDs.fRTFBOOwnership = GrBackendObjectOwnership::kBorrowed;
931 rtIDs.fTotalMemorySamplesPerPixel = sampleCount;
932
933 return GrGLRenderTarget::MakeWrapped(this,
934 backendRT.dimensions(),
935 format,
936 sampleCount,
937 rtIDs,
938 backendRT.stencilBits(),
939 skgpu::Protected(backendRT.isProtected()),
940 /*label=*/"GLGpu_WrapBackendRenderTarget");
941 }
942
943 static bool check_write_and_transfer_input(GrGLTexture* glTex) {
944 if (!glTex) {
945 return false;
946 }
947
948 // Write or transfer of pixels is not implemented for TEXTURE_EXTERNAL textures
949 if (GR_GL_TEXTURE_EXTERNAL == glTex->target()) {
950 return false;
951 }
952
953 return true;
954 }
955
956 bool GrGLGpu::onWritePixels(GrSurface* surface,
957 SkIRect rect,
958 GrColorType surfaceColorType,
959 GrColorType srcColorType,
960 const GrMipLevel texels[],
961 int mipLevelCount,
962 bool prepForTexSampling) {
963 auto glTex = static_cast<GrGLTexture*>(surface->asTexture());
964
965 if (!check_write_and_transfer_input(glTex)) {
966 return false;
967 }
968
969 this->bindTextureToScratchUnit(glTex->target(), glTex->textureID());
970
971 // If we have mips make sure the base/max levels cover the full range so that the uploads go to
972 // the right levels. We've found some Radeons require this.
973 if (mipLevelCount && this->glCaps().mipmapLevelControlSupport()) {
974 auto params = glTex->parameters();
975 GrGLTextureParameters::NonsamplerState nonsamplerState = params->nonsamplerState();
976 int maxLevel = glTex->maxMipmapLevel();
977 if (params->nonsamplerState().fBaseMipMapLevel != 0) {
978 GL_CALL(TexParameteri(glTex->target(), GR_GL_TEXTURE_BASE_LEVEL, 0));
979 nonsamplerState.fBaseMipMapLevel = 0;
980 }
981 if (params->nonsamplerState().fMaxMipmapLevel != maxLevel) {
982 GL_CALL(TexParameteri(glTex->target(), GR_GL_TEXTURE_MAX_LEVEL, maxLevel));
983 nonsamplerState.fBaseMipMapLevel = maxLevel;
984 }
985 params->set(nullptr, nonsamplerState, fResetTimestampForTextureParameters);
986 }
987
988 if (this->glCaps().flushBeforeWritePixels()) {
989 GL_CALL(Flush());
990 }
991
992 SkASSERT(!GrGLFormatIsCompressed(glTex->format()));
993 return this->uploadColorTypeTexData(glTex->format(),
994 surfaceColorType,
995 glTex->dimensions(),
996 glTex->target(),
997 rect,
998 srcColorType,
999 texels,
1000 mipLevelCount);
1001 }
1002
1003 bool GrGLGpu::onTransferFromBufferToBuffer(sk_sp<GrGpuBuffer> src,
1004 size_t srcOffset,
1005 sk_sp<GrGpuBuffer> dst,
1006 size_t dstOffset,
1007 size_t size) {
1008 SkASSERT(!src->isMapped());
1009 SkASSERT(!dst->isMapped());
1010
1011 auto glSrc = static_cast<const GrGLBuffer*>(src.get());
1012 auto glDst = static_cast<const GrGLBuffer*>(dst.get());
1013
1014 // If we refactored bindBuffer() to use something other than GrGpuBufferType to indicate the
1015 // binding target then we could use the COPY_READ and COPY_WRITE targets here. But
1016 // CopyBufferSubData is documented to work with all the targets so it's not clear it's worth it.
1017 this->bindBuffer(GrGpuBufferType::kXferCpuToGpu, glSrc);
1018 this->bindBuffer(GrGpuBufferType::kXferGpuToCpu, glDst);
1019
1020 GL_CALL(CopyBufferSubData(GR_GL_PIXEL_UNPACK_BUFFER,
1021 GR_GL_PIXEL_PACK_BUFFER,
1022 srcOffset,
1023 dstOffset,
1024 size));
1025 return true;
1026 }
1027
1028 bool GrGLGpu::onTransferPixelsTo(GrTexture* texture,
1029 SkIRect rect,
1030 GrColorType textureColorType,
1031 GrColorType bufferColorType,
1032 sk_sp<GrGpuBuffer> transferBuffer,
1033 size_t offset,
1034 size_t rowBytes) {
1035 GrGLTexture* glTex = static_cast<GrGLTexture*>(texture);
1036
1037 // Can't transfer compressed data
1038 SkASSERT(!GrGLFormatIsCompressed(glTex->format()));
1039
1040 if (!check_write_and_transfer_input(glTex)) {
1041 return false;
1042 }
1043
1044 static_assert(sizeof(int) == sizeof(int32_t), "");
1045
1046 this->bindTextureToScratchUnit(glTex->target(), glTex->textureID());
1047
1048 SkASSERT(!transferBuffer->isMapped());
1049 SkASSERT(!transferBuffer->isCpuBuffer());
1050 const GrGLBuffer* glBuffer = static_cast<const GrGLBuffer*>(transferBuffer.get());
1051 this->bindBuffer(GrGpuBufferType::kXferCpuToGpu, glBuffer);
1052
1053 SkASSERT(SkIRect::MakeSize(texture->dimensions()).contains(rect));
1054
1055 size_t bpp = GrColorTypeBytesPerPixel(bufferColorType);
1056 const size_t trimRowBytes = rect.width() * bpp;
1057 const void* pixels = (void*)offset;
1058
1059 SkASSERT(glBuffer->size() >= offset + rowBytes*(rect.height() - 1) + trimRowBytes);
1060
1061 bool restoreGLRowLength = false;
1062 if (trimRowBytes != rowBytes) {
1063 // we should have checked for this support already
1064 SkASSERT(this->glCaps().transferPixelsToRowBytesSupport());
1065 GL_CALL(PixelStorei(GR_GL_UNPACK_ROW_LENGTH, rowBytes / bpp));
1066 restoreGLRowLength = true;
1067 }
1068
1069 GrGLFormat textureFormat = glTex->format();
1070 // External format and type come from the upload data.
1071 GrGLenum externalFormat = 0;
1072 GrGLenum externalType = 0;
1073 this->glCaps().getTexSubImageExternalFormatAndType(
1074 textureFormat, textureColorType, bufferColorType, &externalFormat, &externalType);
1075 if (!externalFormat || !externalType) {
1076 return false;
1077 }
1078
1079 GL_CALL(PixelStorei(GR_GL_UNPACK_ALIGNMENT, 1));
1080 GL_CALL(TexSubImage2D(glTex->target(),
1081 0,
1082 rect.left(),
1083 rect.top(),
1084 rect.width(),
1085 rect.height(),
1086 externalFormat,
1087 externalType,
1088 pixels));
1089
1090 if (restoreGLRowLength) {
1091 GL_CALL(PixelStorei(GR_GL_UNPACK_ROW_LENGTH, 0));
1092 }
1093
1094 return true;
1095 }
1096
1097 bool GrGLGpu::onTransferPixelsFrom(GrSurface* surface,
1098 SkIRect rect,
1099 GrColorType surfaceColorType,
1100 GrColorType dstColorType,
1101 sk_sp<GrGpuBuffer> transferBuffer,
1102 size_t offset) {
1103 auto* glBuffer = static_cast<GrGLBuffer*>(transferBuffer.get());
1104 SkASSERT(glBuffer->size() >= offset + (rect.width() *
1105 rect.height()*
1106 GrColorTypeBytesPerPixel(dstColorType)));
1107
1108 this->bindBuffer(GrGpuBufferType::kXferGpuToCpu, glBuffer);
1109
1110 auto offsetAsPtr = reinterpret_cast<void*>(offset);
1111 return this->readOrTransferPixelsFrom(surface,
1112 rect,
1113 surfaceColorType,
1114 dstColorType,
1115 offsetAsPtr,
1116 rect.width());
1117 }
1118
1119 void GrGLGpu::unbindXferBuffer(GrGpuBufferType type) {
1120 if (this->glCaps().transferBufferType() != GrGLCaps::TransferBufferType::kARB_PBO &&
1121 this->glCaps().transferBufferType() != GrGLCaps::TransferBufferType::kNV_PBO) {
1122 return;
1123 }
1124 SkASSERT(type == GrGpuBufferType::kXferCpuToGpu || type == GrGpuBufferType::kXferGpuToCpu);
1125 auto* xferBufferState = this->hwBufferState(type);
1126 if (!xferBufferState->fBufferZeroKnownBound) {
1127 GL_CALL(BindBuffer(xferBufferState->fGLTarget, 0));
1128 xferBufferState->fBoundBufferUniqueID.makeInvalid();
1129 xferBufferState->fBufferZeroKnownBound = true;
1130 }
1131 }
1132
1133 bool GrGLGpu::uploadColorTypeTexData(GrGLFormat textureFormat,
1134 GrColorType textureColorType,
1135 SkISize texDims,
1136 GrGLenum target,
1137 SkIRect dstRect,
1138 GrColorType srcColorType,
1139 const GrMipLevel texels[],
1140 int mipLevelCount) {
1141 // If we're uploading compressed data then we should be using uploadCompressedTexData
1142 SkASSERT(!GrGLFormatIsCompressed(textureFormat));
1143
1144 SkASSERT(this->glCaps().isFormatTexturable(textureFormat));
1145
1146 size_t bpp = GrColorTypeBytesPerPixel(srcColorType);
1147
1148 // External format and type come from the upload data.
1149 GrGLenum externalFormat;
1150 GrGLenum externalType;
1151 this->glCaps().getTexSubImageExternalFormatAndType(
1152 textureFormat, textureColorType, srcColorType, &externalFormat, &externalType);
1153 if (!externalFormat || !externalType) {
1154 return false;
1155 }
1156 this->uploadTexData(texDims, target, dstRect, externalFormat, externalType, bpp, texels,
1157 mipLevelCount);
1158 return true;
1159 }
1160
1161 bool GrGLGpu::uploadColorToTex(GrGLFormat textureFormat,
1162 SkISize texDims,
1163 GrGLenum target,
1164 std::array<float, 4> color,
1165 uint32_t levelMask) {
1166 GrColorType colorType;
1167 GrGLenum externalFormat, externalType;
1168 this->glCaps().getTexSubImageDefaultFormatTypeAndColorType(textureFormat, &externalFormat,
1169 &externalType, &colorType);
1170 if (colorType == GrColorType::kUnknown) {
1171 return false;
1172 }
1173
1174 std::unique_ptr<char[]> pixelStorage;
1175 size_t bpp = 0;
1176 int numLevels = SkMipmap::ComputeLevelCount(texDims) + 1;
1177 STArray<16, GrMipLevel> levels;
1178 levels.resize(numLevels);
1179 SkISize levelDims = texDims;
1180 for (int i = 0; i < numLevels; ++i, levelDims = {std::max(levelDims.width() >> 1, 1),
1181 std::max(levelDims.height() >> 1, 1)}) {
1182 if (levelMask & (1 << i)) {
1183 if (!pixelStorage) {
1184 // Make one tight image at the first size and reuse it for smaller levels.
1185 GrImageInfo ii(colorType, kUnpremul_SkAlphaType, nullptr, levelDims);
1186 size_t rb = ii.minRowBytes();
1187 pixelStorage.reset(new char[rb * levelDims.height()]);
1188 if (!GrClearImage(ii, pixelStorage.get(), ii.minRowBytes(), color)) {
1189 return false;
1190 }
1191 bpp = ii.bpp();
1192 }
1193 levels[i] = {pixelStorage.get(), levelDims.width()*bpp, nullptr};
1194 }
1195 }
1196 this->uploadTexData(texDims, target, SkIRect::MakeSize(texDims), externalFormat, externalType,
1197 bpp, levels.begin(), levels.size());
1198 return true;
1199 }
1200
1201 void GrGLGpu::uploadTexData(SkISize texDims,
1202 GrGLenum target,
1203 SkIRect dstRect,
1204 GrGLenum externalFormat,
1205 GrGLenum externalType,
1206 size_t bpp,
1207 const GrMipLevel texels[],
1208 int mipLevelCount) {
1209 SkASSERT(!texDims.isEmpty());
1210 SkASSERT(!dstRect.isEmpty());
1211 SkASSERT(SkIRect::MakeSize(texDims).contains(dstRect));
1212 SkASSERT(mipLevelCount > 0 && mipLevelCount <= SkMipmap::ComputeLevelCount(texDims) + 1);
1213 SkASSERT(mipLevelCount == 1 || dstRect == SkIRect::MakeSize(texDims));
1214
1215 const GrGLCaps& caps = this->glCaps();
1216
1217 bool restoreGLRowLength = false;
1218
1219 this->unbindXferBuffer(GrGpuBufferType::kXferCpuToGpu);
1220 GL_CALL(PixelStorei(GR_GL_UNPACK_ALIGNMENT, 1));
1221
1222 SkISize dims = dstRect.size();
1223 for (int level = 0; level < mipLevelCount; ++level, dims = {std::max(dims.width() >> 1, 1),
1224 std::max(dims.height() >> 1, 1)}) {
1225 if (!texels[level].fPixels) {
1226 continue;
1227 }
1228 const size_t trimRowBytes = dims.width() * bpp;
1229 const size_t rowBytes = texels[level].fRowBytes;
1230
1231 if (caps.writePixelsRowBytesSupport() && (rowBytes != trimRowBytes || restoreGLRowLength)) {
1232 GrGLint rowLength = static_cast<GrGLint>(rowBytes / bpp);
1233 GL_CALL(PixelStorei(GR_GL_UNPACK_ROW_LENGTH, rowLength));
1234 restoreGLRowLength = true;
1235 } else {
1236 SkASSERT(rowBytes == trimRowBytes);
1237 }
1238
1239 GL_CALL(TexSubImage2D(target, level, dstRect.x(), dstRect.y(), dims.width(), dims.height(),
1240 externalFormat, externalType, texels[level].fPixels));
1241 }
1242 if (restoreGLRowLength) {
1243 SkASSERT(caps.writePixelsRowBytesSupport());
1244 GL_CALL(PixelStorei(GR_GL_UNPACK_ROW_LENGTH, 0));
1245 }
1246 }
1247
1248 bool GrGLGpu::uploadCompressedTexData(SkTextureCompressionType compressionType,
1249 GrGLFormat format,
1250 SkISize dimensions,
1251 skgpu::Mipmapped mipmapped,
1252 GrGLenum target,
1253 const void* data,
1254 size_t dataSize) {
1255 SkASSERT(format != GrGLFormat::kUnknown);
1256 const GrGLCaps& caps = this->glCaps();
1257
1258 // We only need the internal format for compressed 2D textures.
1259 GrGLenum internalFormat = caps.getTexImageOrStorageInternalFormat(format);
1260 if (!internalFormat) {
1261 return false;
1262 }
1263
1264 SkASSERT(compressionType != SkTextureCompressionType::kNone);
1265
1266 bool useTexStorage = caps.formatSupportsTexStorage(format);
1267
1268 int numMipLevels = 1;
1269 if (mipmapped == skgpu::Mipmapped::kYes) {
1270 numMipLevels = SkMipmap::ComputeLevelCount(dimensions)+1;
1271 }
1272
1273 this->unbindXferBuffer(GrGpuBufferType::kXferCpuToGpu);
1274
1275 // TODO: Make sure that the width and height that we pass to OpenGL
1276 // is a multiple of the block size.
1277
1278 if (useTexStorage) {
1279 // We never resize or change formats of textures.
1280 GrGLenum error = GL_ALLOC_CALL(TexStorage2D(target, numMipLevels, internalFormat,
1281 dimensions.width(), dimensions.height()));
1282 if (error != GR_GL_NO_ERROR) {
1283 return false;
1284 }
1285
1286 size_t offset = 0;
1287 for (int level = 0; level < numMipLevels; ++level) {
1288
1289 size_t levelDataSize = SkCompressedDataSize(compressionType, dimensions,
1290 nullptr, false);
1291
1292 error = GL_ALLOC_CALL(CompressedTexSubImage2D(target,
1293 level,
1294 0, // left
1295 0, // top
1296 dimensions.width(),
1297 dimensions.height(),
1298 internalFormat,
1299 SkToInt(levelDataSize),
1300 &((const char*)data)[offset]));
1301
1302 if (error != GR_GL_NO_ERROR) {
1303 return false;
1304 }
1305
1306 offset += levelDataSize;
1307 dimensions = {std::max(1, dimensions.width()/2), std::max(1, dimensions.height()/2)};
1308 }
1309 } else {
1310 size_t offset = 0;
1311
1312 for (int level = 0; level < numMipLevels; ++level) {
1313 size_t levelDataSize = SkCompressedDataSize(compressionType, dimensions,
1314 nullptr, false);
1315
1316 const char* rawLevelData = &((const char*)data)[offset];
1317 GrGLenum error = GL_ALLOC_CALL(CompressedTexImage2D(target,
1318 level,
1319 internalFormat,
1320 dimensions.width(),
1321 dimensions.height(),
1322 0, // border
1323 SkToInt(levelDataSize),
1324 rawLevelData));
1325
1326 if (error != GR_GL_NO_ERROR) {
1327 return false;
1328 }
1329
1330 offset += levelDataSize;
1331 dimensions = {std::max(1, dimensions.width()/2), std::max(1, dimensions.height()/2)};
1332 }
1333 }
1334 return true;
1335 }
1336
1337 bool GrGLGpu::renderbufferStorageMSAA(const GrGLContext& ctx, int sampleCount, GrGLenum format,
1338 int width, int height) {
1339 SkASSERT(GrGLCaps::kNone_MSFBOType != ctx.caps()->msFBOType());
1340 GrGLenum error;
1341 switch (ctx.caps()->msFBOType()) {
1342 case GrGLCaps::kStandard_MSFBOType:
1343 error = GL_ALLOC_CALL(RenderbufferStorageMultisample(GR_GL_RENDERBUFFER, sampleCount,
1344 format, width, height));
1345 break;
1346 case GrGLCaps::kES_Apple_MSFBOType:
1347 error = GL_ALLOC_CALL(RenderbufferStorageMultisampleES2APPLE(
1348 GR_GL_RENDERBUFFER, sampleCount, format, width, height));
1349 break;
1350 case GrGLCaps::kES_EXT_MsToTexture_MSFBOType:
1351 case GrGLCaps::kES_IMG_MsToTexture_MSFBOType:
1352 error = GL_ALLOC_CALL(RenderbufferStorageMultisampleES2EXT(
1353 GR_GL_RENDERBUFFER, sampleCount, format, width, height));
1354 break;
1355 case GrGLCaps::kNone_MSFBOType:
1356 SkUNREACHABLE;
1357 }
1358 return error == GR_GL_NO_ERROR;
1359 }
1360
1361 bool GrGLGpu::createRenderTargetObjects(const GrGLTexture::Desc& desc,
1362 int sampleCount,
1363 GrGLRenderTarget::IDs* rtIDs) {
1364 rtIDs->fMSColorRenderbufferID = 0;
1365 rtIDs->fMultisampleFBOID = 0;
1366 rtIDs->fRTFBOOwnership = GrBackendObjectOwnership::kOwned;
1367 rtIDs->fSingleSampleFBOID = 0;
1368 rtIDs->fTotalMemorySamplesPerPixel = 0;
1369
1370 SkScopeExit cleanupOnFail([&] {
1371 if (rtIDs->fMSColorRenderbufferID) {
1372 GL_CALL(DeleteRenderbuffers(1, &rtIDs->fMSColorRenderbufferID));
1373 }
1374 if (rtIDs->fMultisampleFBOID != rtIDs->fSingleSampleFBOID) {
1375 this->deleteFramebuffer(rtIDs->fMultisampleFBOID);
1376 }
1377 if (rtIDs->fSingleSampleFBOID) {
1378 this->deleteFramebuffer(rtIDs->fSingleSampleFBOID);
1379 }
1380 });
1381
1382 GrGLenum colorRenderbufferFormat = 0; // suppress warning
1383
1384 if (desc.fFormat == GrGLFormat::kUnknown) {
1385 return false;
1386 }
1387
1388 if (sampleCount > 1 && GrGLCaps::kNone_MSFBOType == this->glCaps().msFBOType()) {
1389 return false;
1390 }
1391
1392 GL_CALL(GenFramebuffers(1, &rtIDs->fSingleSampleFBOID));
1393 if (!rtIDs->fSingleSampleFBOID) {
1394 RENDERENGINE_ABORTF("%s failed to GenFramebuffers!", __func__);
1395 return false;
1396 }
1397
1398 // If we are using multisampling we will create two FBOS. We render to one and then resolve to
1399 // the texture bound to the other. The exception is the IMG multisample extension. With this
1400 // extension the texture is multisampled when rendered to and then auto-resolves it when it is
1401 // rendered from.
1402 if (sampleCount <= 1) {
1403 rtIDs->fMultisampleFBOID = GrGLRenderTarget::kUnresolvableFBOID;
1404 } else if (this->glCaps().usesImplicitMSAAResolve()) {
1405 // GrGLRenderTarget target will configure the FBO as multisample or not base on need.
1406 rtIDs->fMultisampleFBOID = rtIDs->fSingleSampleFBOID;
1407 } else {
1408 GL_CALL(GenFramebuffers(1, &rtIDs->fMultisampleFBOID));
1409 if (!rtIDs->fMultisampleFBOID) {
1410 return false;
1411 }
1412 GL_CALL(GenRenderbuffers(1, &rtIDs->fMSColorRenderbufferID));
1413 if (!rtIDs->fMSColorRenderbufferID) {
1414 return false;
1415 }
1416 colorRenderbufferFormat = this->glCaps().getRenderbufferInternalFormat(desc.fFormat);
1417 }
1418
1419 #if defined(__has_feature)
1420 #define IS_TSAN __has_feature(thread_sanitizer)
1421 #else
1422 #define IS_TSAN 0
1423 #endif
1424
1425 // below here we may bind the FBO
1426 fHWBoundRenderTargetUniqueID.makeInvalid();
1427 if (rtIDs->fMSColorRenderbufferID) {
1428 SkASSERT(sampleCount > 1);
1429 GL_CALL(BindRenderbuffer(GR_GL_RENDERBUFFER, rtIDs->fMSColorRenderbufferID));
1430 if (!this->renderbufferStorageMSAA(*fGLContext, sampleCount, colorRenderbufferFormat,
1431 desc.fSize.width(), desc.fSize.height())) {
1432 return false;
1433 }
1434 this->bindFramebuffer(GR_GL_FRAMEBUFFER, rtIDs->fMultisampleFBOID);
1435 GL_CALL(FramebufferRenderbuffer(GR_GL_FRAMEBUFFER,
1436 GR_GL_COLOR_ATTACHMENT0,
1437 GR_GL_RENDERBUFFER,
1438 rtIDs->fMSColorRenderbufferID));
1439 // See skbug.com/40043725
1440 #if !IS_TSAN
1441 if (!this->glCaps().skipErrorChecks()) {
1442 GrGLenum status;
1443 GL_CALL_RET(status, CheckFramebufferStatus(GR_GL_FRAMEBUFFER));
1444 if (status != GR_GL_FRAMEBUFFER_COMPLETE) {
1445 return false;
1446 }
1447 if (this->glCaps().rebindColorAttachmentAfterCheckFramebufferStatus()) {
1448 GL_CALL(FramebufferRenderbuffer(GR_GL_FRAMEBUFFER,
1449 GR_GL_COLOR_ATTACHMENT0,
1450 GR_GL_RENDERBUFFER,
1451 0));
1452 GL_CALL(FramebufferRenderbuffer(GR_GL_FRAMEBUFFER,
1453 GR_GL_COLOR_ATTACHMENT0,
1454 GR_GL_RENDERBUFFER,
1455 rtIDs->fMSColorRenderbufferID));
1456 }
1457 }
1458 #endif
1459 rtIDs->fTotalMemorySamplesPerPixel += sampleCount;
1460 }
1461 this->bindFramebuffer(GR_GL_FRAMEBUFFER, rtIDs->fSingleSampleFBOID);
1462 GL_CALL(FramebufferTexture2D(GR_GL_FRAMEBUFFER,
1463 GR_GL_COLOR_ATTACHMENT0,
1464 desc.fTarget,
1465 desc.fID,
1466 0));
1467 // See skbug.com/40043725
1468 #if !IS_TSAN
1469 if (!this->glCaps().skipErrorChecks()) {
1470 GrGLenum status;
1471 GL_CALL_RET(status, CheckFramebufferStatus(GR_GL_FRAMEBUFFER));
1472 if (status != GR_GL_FRAMEBUFFER_COMPLETE) {
1473 return false;
1474 }
1475 if (this->glCaps().rebindColorAttachmentAfterCheckFramebufferStatus()) {
1476 GL_CALL(FramebufferTexture2D(GR_GL_FRAMEBUFFER,
1477 GR_GL_COLOR_ATTACHMENT0,
1478 desc.fTarget,
1479 0,
1480 0));
1481 GL_CALL(FramebufferTexture2D(GR_GL_FRAMEBUFFER,
1482 GR_GL_COLOR_ATTACHMENT0,
1483 desc.fTarget,
1484 desc.fID,
1485 0));
1486 }
1487 }
1488 #endif
1489
1490 #undef IS_TSAN
1491 ++rtIDs->fTotalMemorySamplesPerPixel;
1492
1493 // We did it!
1494 cleanupOnFail.clear();
1495 return true;
1496 }
1497
1498 // good to set a break-point here to know when createTexture fails
1499 static sk_sp<GrTexture> return_null_texture() {
1500 // SkDEBUGFAIL("null texture");
1501 return nullptr;
1502 }
1503
1504 static GrGLTextureParameters::SamplerOverriddenState set_initial_texture_params(
1505 const GrGLInterface* interface,
1506 const GrGLCaps& caps,
1507 GrGLenum target) {
1508 // Some drivers like to know filter/wrap before seeing glTexImage2D. Some
1509 // drivers have a bug where an FBO won't be complete if it includes a
1510 // texture that is not mipmap complete (considering the filter in use).
1511 GrGLTextureParameters::SamplerOverriddenState state;
1512 state.fMinFilter = GR_GL_NEAREST;
1513 state.fMagFilter = GR_GL_NEAREST;
1514 state.fWrapS = GR_GL_CLAMP_TO_EDGE;
1515 state.fWrapT = GR_GL_CLAMP_TO_EDGE;
1516 GR_GL_CALL(interface, TexParameteri(target, GR_GL_TEXTURE_MAG_FILTER, state.fMagFilter));
1517 GR_GL_CALL(interface, TexParameteri(target, GR_GL_TEXTURE_MIN_FILTER, state.fMinFilter));
1518 GR_GL_CALL(interface, TexParameteri(target, GR_GL_TEXTURE_WRAP_S, state.fWrapS));
1519 GR_GL_CALL(interface, TexParameteri(target, GR_GL_TEXTURE_WRAP_T, state.fWrapT));
1520 return state;
1521 }
1522
1523 sk_sp<GrTexture> GrGLGpu::onCreateTexture(SkISize dimensions,
1524 const GrBackendFormat& format,
1525 GrRenderable renderable,
1526 int renderTargetSampleCnt,
1527 skgpu::Budgeted budgeted,
1528 GrProtected isProtected,
1529 int mipLevelCount,
1530 uint32_t levelClearMask,
1531 std::string_view label) {
1532 if (isProtected == GrProtected::kYes && !this->glCaps().supportsProtectedContent()) {
1533 return nullptr;
1534 }
1535 SkASSERT(GrGLCaps::kNone_MSFBOType != this->glCaps().msFBOType() || renderTargetSampleCnt == 1);
1536
1537 SkASSERT(mipLevelCount > 0);
1538 GrMipmapStatus mipmapStatus =
1539 mipLevelCount > 1 ? GrMipmapStatus::kDirty : GrMipmapStatus::kNotAllocated;
1540 GrGLTextureParameters::SamplerOverriddenState initialState;
1541 GrGLTexture::Desc texDesc;
1542 texDesc.fSize = dimensions;
1543 switch (format.textureType()) {
1544 case GrTextureType::kExternal:
1545 case GrTextureType::kNone:
1546 return nullptr;
1547 case GrTextureType::k2D:
1548 texDesc.fTarget = GR_GL_TEXTURE_2D;
1549 break;
1550 case GrTextureType::kRectangle:
1551 if (mipLevelCount > 1 || !this->glCaps().rectangleTextureSupport()) {
1552 return nullptr;
1553 }
1554 texDesc.fTarget = GR_GL_TEXTURE_RECTANGLE;
1555 break;
1556 }
1557 texDesc.fFormat = GrBackendFormats::AsGLFormat(format);
1558 texDesc.fOwnership = GrBackendObjectOwnership::kOwned;
1559 SkASSERT(texDesc.fFormat != GrGLFormat::kUnknown);
1560 SkASSERT(!GrGLFormatIsCompressed(texDesc.fFormat));
1561 texDesc.fIsProtected = skgpu::Protected(isProtected == skgpu::Protected::kYes ||
1562 this->glCaps().strictProtectedness());
1563
1564 texDesc.fID = this->createTexture(dimensions, texDesc.fFormat, texDesc.fTarget, renderable,
1565 &initialState, mipLevelCount, texDesc.fIsProtected, label);
1566 if (!texDesc.fID) {
1567 return return_null_texture();
1568 }
1569
1570 sk_sp<GrGLTexture> tex;
1571 if (renderable == GrRenderable::kYes) {
1572 // unbind the texture from the texture unit before binding it to the frame buffer
1573 GL_CALL(BindTexture(texDesc.fTarget, 0));
1574 GrGLRenderTarget::IDs rtIDDesc;
1575
1576 if (!this->createRenderTargetObjects(texDesc, renderTargetSampleCnt, &rtIDDesc)) {
1577 GL_CALL(DeleteTextures(1, &texDesc.fID));
1578 return return_null_texture();
1579 }
1580 tex = sk_make_sp<GrGLTextureRenderTarget>(this,
1581 budgeted,
1582 renderTargetSampleCnt,
1583 texDesc,
1584 rtIDDesc,
1585 mipmapStatus,
1586 label);
1587 tex->baseLevelWasBoundToFBO();
1588 } else {
1589 tex = sk_make_sp<GrGLTexture>(this, budgeted, texDesc, mipmapStatus, label);
1590 }
1591 // The non-sampler params are still at their default values.
1592 tex->parameters()->set(&initialState, GrGLTextureParameters::NonsamplerState(),
1593 fResetTimestampForTextureParameters);
1594 if (levelClearMask) {
1595 if (this->glCaps().clearTextureSupport()) {
1596 GrGLenum externalFormat, externalType;
1597 GrColorType colorType;
1598 this->glCaps().getTexSubImageDefaultFormatTypeAndColorType(
1599 texDesc.fFormat, &externalFormat, &externalType, &colorType);
1600 for (int i = 0; i < mipLevelCount; ++i) {
1601 if (levelClearMask & (1U << i)) {
1602 GL_CALL(ClearTexImage(tex->textureID(), i, externalFormat, externalType,
1603 nullptr));
1604 }
1605 }
1606 } else if (this->glCaps().canFormatBeFBOColorAttachment(
1607 GrBackendFormats::AsGLFormat(format)) &&
1608 !this->glCaps().performColorClearsAsDraws()) {
1609 this->flushScissorTest(GrScissorTest::kDisabled);
1610 this->disableWindowRectangles();
1611 this->flushColorWrite(true);
1612 this->flushClearColor({0, 0, 0, 0});
1613 for (int i = 0; i < mipLevelCount; ++i) {
1614 if (levelClearMask & (1U << i)) {
1615 this->bindSurfaceFBOForPixelOps(tex.get(), i, GR_GL_FRAMEBUFFER,
1616 kDst_TempFBOTarget);
1617 GL_CALL(Clear(GR_GL_COLOR_BUFFER_BIT));
1618 this->unbindSurfaceFBOForPixelOps(tex.get(), i, GR_GL_FRAMEBUFFER);
1619 }
1620 }
1621 fHWBoundRenderTargetUniqueID.makeInvalid();
1622 } else {
1623 this->bindTextureToScratchUnit(texDesc.fTarget, tex->textureID());
1624 std::array<float, 4> zeros = {};
1625 this->uploadColorToTex(texDesc.fFormat,
1626 texDesc.fSize,
1627 texDesc.fTarget,
1628 zeros,
1629 levelClearMask);
1630 }
1631 }
1632 return tex;
1633 }
1634
1635 sk_sp<GrTexture> GrGLGpu::onCreateCompressedTexture(SkISize dimensions,
1636 const GrBackendFormat& format,
1637 skgpu::Budgeted budgeted,
1638 skgpu::Mipmapped mipmapped,
1639 GrProtected isProtected,
1640 const void* data,
1641 size_t dataSize) {
1642 if (isProtected == GrProtected::kYes && !this->glCaps().supportsProtectedContent()) {
1643 return nullptr;
1644 }
1645 SkTextureCompressionType compression = GrBackendFormatToCompressionType(format);
1646
1647 GrGLTextureParameters::SamplerOverriddenState initialState;
1648 GrGLTexture::Desc desc;
1649 desc.fSize = dimensions;
1650 desc.fTarget = GR_GL_TEXTURE_2D;
1651 desc.fOwnership = GrBackendObjectOwnership::kOwned;
1652 desc.fFormat = GrBackendFormats::AsGLFormat(format);
1653 desc.fIsProtected = skgpu::Protected(isProtected == skgpu::Protected::kYes ||
1654 this->glCaps().strictProtectedness());
1655 desc.fID = this->createCompressedTexture2D(desc.fSize, compression, desc.fFormat,
1656 mipmapped, desc.fIsProtected, &initialState);
1657 if (!desc.fID) {
1658 return nullptr;
1659 }
1660
1661 if (data) {
1662 if (!this->uploadCompressedTexData(compression, desc.fFormat, dimensions, mipmapped,
1663 GR_GL_TEXTURE_2D, data, dataSize)) {
1664 GL_CALL(DeleteTextures(1, &desc.fID));
1665 return nullptr;
1666 }
1667 }
1668
1669 // Unbind this texture from the scratch texture unit.
1670 this->bindTextureToScratchUnit(GR_GL_TEXTURE_2D, 0);
1671
1672 GrMipmapStatus mipmapStatus = mipmapped == skgpu::Mipmapped::kYes
1673 ? GrMipmapStatus::kValid
1674 : GrMipmapStatus::kNotAllocated;
1675
1676 auto tex = sk_make_sp<GrGLTexture>(this, budgeted, desc, mipmapStatus,
1677 /*label=*/"GLGpuCreateCompressedTexture");
1678 // The non-sampler params are still at their default values.
1679 tex->parameters()->set(&initialState, GrGLTextureParameters::NonsamplerState(),
1680 fResetTimestampForTextureParameters);
1681 return tex;
1682 }
1683
1684 GrBackendTexture GrGLGpu::onCreateCompressedBackendTexture(SkISize dimensions,
1685 const GrBackendFormat& format,
1686 skgpu::Mipmapped mipmapped,
1687 GrProtected isProtected) {
1688 if (isProtected == GrProtected::kYes && !this->glCaps().supportsProtectedContent()) {
1689 return {};
1690 }
1691
1692 this->handleDirtyContext();
1693
1694 GrGLFormat glFormat = GrBackendFormats::AsGLFormat(format);
1695 if (glFormat == GrGLFormat::kUnknown) {
1696 return {};
1697 }
1698
1699 SkTextureCompressionType compression = GrBackendFormatToCompressionType(format);
1700
1701 GrGLTextureInfo info;
1702 GrGLTextureParameters::SamplerOverriddenState initialState;
1703
1704 info.fTarget = GR_GL_TEXTURE_2D;
1705 info.fFormat = GrGLFormatToEnum(glFormat);
1706 info.fProtected = skgpu::Protected(isProtected == skgpu::Protected::kYes ||
1707 this->glCaps().strictProtectedness());
1708 info.fID = this->createCompressedTexture2D(dimensions, compression, glFormat,
1709 mipmapped, info.fProtected, &initialState);
1710 if (!info.fID) {
1711 return {};
1712 }
1713
1714 // Unbind this texture from the scratch texture unit.
1715 this->bindTextureToScratchUnit(GR_GL_TEXTURE_2D, 0);
1716
1717 auto parameters = sk_make_sp<GrGLTextureParameters>();
1718 // The non-sampler params are still at their default values.
1719 parameters->set(&initialState, GrGLTextureParameters::NonsamplerState(),
1720 fResetTimestampForTextureParameters);
1721
1722 return GrBackendTextures::MakeGL(
1723 dimensions.width(), dimensions.height(), mipmapped, info, std::move(parameters));
1724 }
1725
1726 bool GrGLGpu::onUpdateCompressedBackendTexture(const GrBackendTexture& backendTexture,
1727 sk_sp<skgpu::RefCntedCallback> finishedCallback,
1728 const void* data,
1729 size_t length) {
1730 GrGLTextureInfo info;
1731 SkAssertResult(GrBackendTextures::GetGLTextureInfo(backendTexture, &info));
1732
1733 GrBackendFormat format = backendTexture.getBackendFormat();
1734 GrGLFormat glFormat = GrBackendFormats::AsGLFormat(format);
1735 if (glFormat == GrGLFormat::kUnknown) {
1736 return false;
1737 }
1738 SkTextureCompressionType compression = GrBackendFormatToCompressionType(format);
1739
1740 skgpu::Mipmapped mipmapped =
1741 backendTexture.hasMipmaps() ? skgpu::Mipmapped::kYes : skgpu::Mipmapped::kNo;
1742
1743 this->bindTextureToScratchUnit(info.fTarget, info.fID);
1744
1745 // If we have mips make sure the base level is set to 0 and the max level set to numMipLevels-1
1746 // so that the uploads go to the right levels.
1747 if (backendTexture.hasMipmaps() && this->glCaps().mipmapLevelControlSupport()) {
1748 auto params = get_gl_texture_params(backendTexture);
1749 GrGLTextureParameters::NonsamplerState nonsamplerState = params->nonsamplerState();
1750 if (params->nonsamplerState().fBaseMipMapLevel != 0) {
1751 GL_CALL(TexParameteri(info.fTarget, GR_GL_TEXTURE_BASE_LEVEL, 0));
1752 nonsamplerState.fBaseMipMapLevel = 0;
1753 }
1754 int numMipLevels =
1755 SkMipmap::ComputeLevelCount(backendTexture.width(), backendTexture.height()) + 1;
1756 if (params->nonsamplerState().fMaxMipmapLevel != (numMipLevels - 1)) {
1757 GL_CALL(TexParameteri(info.fTarget, GR_GL_TEXTURE_MAX_LEVEL, numMipLevels - 1));
1758 nonsamplerState.fBaseMipMapLevel = numMipLevels - 1;
1759 }
1760 params->set(nullptr, nonsamplerState, fResetTimestampForTextureParameters);
1761 }
1762
1763 bool result = this->uploadCompressedTexData(compression,
1764 glFormat,
1765 backendTexture.dimensions(),
1766 mipmapped,
1767 GR_GL_TEXTURE_2D,
1768 data,
1769 length);
1770
1771 // Unbind this texture from the scratch texture unit.
1772 this->bindTextureToScratchUnit(info.fTarget, 0);
1773
1774 return result;
1775 }
1776
1777 int GrGLGpu::getCompatibleStencilIndex(GrGLFormat format) {
1778 if (this->glCaps().avoidStencilBuffers()) {
1779 return -1;
1780 }
1781
1782 static const int kSize = 16;
1783 SkASSERT(this->glCaps().canFormatBeFBOColorAttachment(format));
1784
1785 if (!this->glCaps().hasStencilFormatBeenDeterminedForFormat(format)) {
1786 // Default to unsupported, set this if we find a stencil format that works.
1787 int firstWorkingStencilFormatIndex = -1;
1788
1789 // In the following we're not actually creating the StencilBuffer that will be used but,
1790 // rather, are just determining the correct format to use. We assume that the
1791 // acceptable format will not change between Protected and unProtected stencil buffers and
1792 // that using Protected::kNo here will not cause any issues with strictProtectedness mode
1793 // (since no work is actually submitted to a queue).
1794 const GrProtected kNotProtected = skgpu::Protected::kNo;
1795
1796 GrGLuint colorID = this->createTexture({kSize, kSize}, format, GR_GL_TEXTURE_2D,
1797 GrRenderable::kYes,
1798 nullptr,
1799 1,
1800 kNotProtected,
1801 /*label=*/"Skia");
1802 if (!colorID) {
1803 return -1;
1804 }
1805 // unbind the texture from the texture unit before binding it to the frame buffer
1806 GL_CALL(BindTexture(GR_GL_TEXTURE_2D, 0));
1807
1808 // Create Framebuffer
1809 GrGLuint fb = 0;
1810 GL_CALL(GenFramebuffers(1, &fb));
1811 this->bindFramebuffer(GR_GL_FRAMEBUFFER, fb);
1812 fHWBoundRenderTargetUniqueID.makeInvalid();
1813 GL_CALL(FramebufferTexture2D(GR_GL_FRAMEBUFFER,
1814 GR_GL_COLOR_ATTACHMENT0,
1815 GR_GL_TEXTURE_2D,
1816 colorID,
1817 0));
1818 GrGLuint sbRBID = 0;
1819 GL_CALL(GenRenderbuffers(1, &sbRBID));
1820
1821 // look over formats till I find a compatible one
1822 int stencilFmtCnt = this->glCaps().stencilFormats().size();
1823 if (sbRBID) {
1824 GL_CALL(BindRenderbuffer(GR_GL_RENDERBUFFER, sbRBID));
1825 for (int i = 0; i < stencilFmtCnt && sbRBID; ++i) {
1826 GrGLFormat sFmt = this->glCaps().stencilFormats()[i];
1827 GrGLenum error = GL_ALLOC_CALL(RenderbufferStorage(
1828 GR_GL_RENDERBUFFER, GrGLFormatToEnum(sFmt), kSize, kSize));
1829 if (error == GR_GL_NO_ERROR) {
1830 GL_CALL(FramebufferRenderbuffer(GR_GL_FRAMEBUFFER,
1831 GR_GL_STENCIL_ATTACHMENT,
1832 GR_GL_RENDERBUFFER, sbRBID));
1833 if (GrGLFormatIsPackedDepthStencil(sFmt)) {
1834 GL_CALL(FramebufferRenderbuffer(GR_GL_FRAMEBUFFER,
1835 GR_GL_DEPTH_ATTACHMENT,
1836 GR_GL_RENDERBUFFER, sbRBID));
1837 } else {
1838 GL_CALL(FramebufferRenderbuffer(GR_GL_FRAMEBUFFER,
1839 GR_GL_DEPTH_ATTACHMENT,
1840 GR_GL_RENDERBUFFER, 0));
1841 }
1842 GrGLenum status;
1843 GL_CALL_RET(status, CheckFramebufferStatus(GR_GL_FRAMEBUFFER));
1844 if (status == GR_GL_FRAMEBUFFER_COMPLETE) {
1845 firstWorkingStencilFormatIndex = i;
1846 break;
1847 }
1848 GL_CALL(FramebufferRenderbuffer(GR_GL_FRAMEBUFFER,
1849 GR_GL_STENCIL_ATTACHMENT,
1850 GR_GL_RENDERBUFFER, 0));
1851 if (GrGLFormatIsPackedDepthStencil(sFmt)) {
1852 GL_CALL(FramebufferRenderbuffer(GR_GL_FRAMEBUFFER,
1853 GR_GL_DEPTH_ATTACHMENT,
1854 GR_GL_RENDERBUFFER, 0));
1855 }
1856 }
1857 }
1858 GL_CALL(DeleteRenderbuffers(1, &sbRBID));
1859 }
1860 GL_CALL(DeleteTextures(1, &colorID));
1861 this->bindFramebuffer(GR_GL_FRAMEBUFFER, 0);
1862 this->deleteFramebuffer(fb);
1863 fGLContext->caps()->setStencilFormatIndexForFormat(format, firstWorkingStencilFormatIndex);
1864 }
1865 return this->glCaps().getStencilFormatIndexForFormat(format);
1866 }
1867
1868 static void set_khr_debug_label(GrGLGpu* gpu, const GrGLuint id, std::string_view label) {
1869 const std::string khr_debug_label = label.empty() ? "Skia" : std::string(label);
1870 if (gpu->glCaps().debugSupport()) {
1871 GR_GL_CALL(gpu->glInterface(), ObjectLabel(GR_GL_TEXTURE, id, -1, khr_debug_label.c_str()));
1872 }
1873 }
1874
1875 GrGLuint GrGLGpu::createCompressedTexture2D(
1876 SkISize dimensions,
1877 SkTextureCompressionType compression,
1878 GrGLFormat format,
1879 skgpu::Mipmapped mipmapped,
1880 GrProtected isProtected,
1881 GrGLTextureParameters::SamplerOverriddenState* initialState) {
1882 if (format == GrGLFormat::kUnknown) {
1883 return 0;
1884 }
1885 GrGLuint id = 0;
1886 GL_CALL(GenTextures(1, &id));
1887 if (!id) {
1888 return 0;
1889 }
1890
1891 this->bindTextureToScratchUnit(GR_GL_TEXTURE_2D, id);
1892
1893 set_khr_debug_label(this, id, /*label=*/"Skia");
1894
1895 *initialState = set_initial_texture_params(this->glInterface(),
1896 this->glCaps(),
1897 GR_GL_TEXTURE_2D);
1898
1899 SkASSERT(isProtected == skgpu::Protected::kNo || this->glCaps().supportsProtectedContent());
1900 SkASSERT(!this->glCaps().strictProtectedness() || isProtected == skgpu::Protected::kYes);
1901
1902 if (GrProtected::kYes == isProtected) {
1903 if (this->glCaps().supportsProtectedContent()) {
1904 GL_CALL(TexParameteri(GR_GL_TEXTURE_2D, GR_GL_TEXTURE_PROTECTED_EXT, GR_GL_TRUE));
1905 } else {
1906 GL_CALL(DeleteTextures(1, &id));
1907 return 0;
1908 }
1909 }
1910
1911 return id;
1912 }
1913
1914 GrGLuint GrGLGpu::createTexture(SkISize dimensions,
1915 GrGLFormat format,
1916 GrGLenum target,
1917 GrRenderable renderable,
1918 GrGLTextureParameters::SamplerOverriddenState* initialState,
1919 int mipLevelCount,
1920 GrProtected isProtected,
1921 std::string_view label) {
1922 SkASSERT(format != GrGLFormat::kUnknown);
1923 SkASSERT(!GrGLFormatIsCompressed(format));
1924
1925 GrGLuint id = 0;
1926 GL_CALL(GenTextures(1, &id));
1927
1928 if (!id) {
1929 return 0;
1930 }
1931
1932 this->bindTextureToScratchUnit(target, id);
1933
1934 set_khr_debug_label(this, id, label);
1935
1936 if (GrRenderable::kYes == renderable && this->glCaps().textureUsageSupport()) {
1937 // provides a hint about how this texture will be used
1938 GL_CALL(TexParameteri(target, GR_GL_TEXTURE_USAGE, GR_GL_FRAMEBUFFER_ATTACHMENT));
1939 }
1940
1941 if (initialState) {
1942 *initialState = set_initial_texture_params(this->glInterface(), this->glCaps(), target);
1943 } else {
1944 set_initial_texture_params(this->glInterface(), this->glCaps(), target);
1945 }
1946
1947 SkASSERT(isProtected == skgpu::Protected::kNo || this->glCaps().supportsProtectedContent());
1948 SkASSERT(!this->glCaps().strictProtectedness() || isProtected == skgpu::Protected::kYes);
1949
1950 if (GrProtected::kYes == isProtected) {
1951 if (this->glCaps().supportsProtectedContent()) {
1952 GL_CALL(TexParameteri(target, GR_GL_TEXTURE_PROTECTED_EXT, GR_GL_TRUE));
1953 } else {
1954 GL_CALL(DeleteTextures(1, &id));
1955 return 0;
1956 }
1957 }
1958
1959 GrGLenum internalFormat = this->glCaps().getTexImageOrStorageInternalFormat(format);
1960
1961 bool success = false;
1962 if (internalFormat) {
1963 if (this->glCaps().formatSupportsTexStorage(format)) {
1964 auto levelCount = std::max(mipLevelCount, 1);
1965 GrGLenum error = GL_ALLOC_CALL(TexStorage2D(target, levelCount, internalFormat,
1966 dimensions.width(), dimensions.height()));
1967 success = (error == GR_GL_NO_ERROR);
1968 } else {
1969 GrGLenum externalFormat, externalType;
1970 this->glCaps().getTexImageExternalFormatAndType(format, &externalFormat, &externalType);
1971 GrGLenum error = GR_GL_NO_ERROR;
1972 if (externalFormat && externalType) {
1973 // If we don't unbind here then nullptr is treated as a zero offset into the bound
1974 // transfer buffer rather than an indication that there is no data to copy.
1975 this->unbindXferBuffer(GrGpuBufferType::kXferCpuToGpu);
1976 for (int level = 0; level < mipLevelCount && error == GR_GL_NO_ERROR; level++) {
1977 const int twoToTheMipLevel = 1 << level;
1978 const int currentWidth = std::max(1, dimensions.width() / twoToTheMipLevel);
1979 const int currentHeight = std::max(1, dimensions.height() / twoToTheMipLevel);
1980 error = GL_ALLOC_CALL(TexImage2D(target, level, internalFormat, currentWidth,
1981 currentHeight, 0, externalFormat, externalType,
1982 nullptr));
1983 }
1984 success = (error == GR_GL_NO_ERROR);
1985 }
1986 }
1987 }
1988 if (success) {
1989 return id;
1990 }
1991 GL_CALL(DeleteTextures(1, &id));
1992 return 0;
1993 }
1994
1995 sk_sp<GrAttachment> GrGLGpu::makeStencilAttachment(const GrBackendFormat& colorFormat,
1996 SkISize dimensions, int numStencilSamples) {
1997 int sIdx = this->getCompatibleStencilIndex(GrBackendFormats::AsGLFormat(colorFormat));
1998 if (sIdx < 0) {
1999 return nullptr;
2000 }
2001 GrGLFormat sFmt = this->glCaps().stencilFormats()[sIdx];
2002
2003 auto stencil = GrGLAttachment::MakeStencil(this, dimensions, numStencilSamples, sFmt);
2004 if (stencil) {
2005 fStats.incStencilAttachmentCreates();
2006 }
2007 return stencil;
2008 }
2009
2010 sk_sp<GrAttachment> GrGLGpu::makeMSAAAttachment(SkISize dimensions, const GrBackendFormat& format,
2011 int numSamples, GrProtected isProtected,
2012 GrMemoryless isMemoryless) {
2013 SkASSERT(isMemoryless == GrMemoryless::kNo);
2014 return GrGLAttachment::MakeMSAA(
2015 this, dimensions, numSamples, GrBackendFormats::AsGLFormat(format));
2016 }
2017
2018 ////////////////////////////////////////////////////////////////////////////////
2019
2020 sk_sp<GrGpuBuffer> GrGLGpu::onCreateBuffer(size_t size,
2021 GrGpuBufferType intendedType,
2022 GrAccessPattern accessPattern) {
2023 return GrGLBuffer::Make(this, size, intendedType, accessPattern);
2024 }
2025
2026 void GrGLGpu::flushScissorTest(GrScissorTest scissorTest) {
2027 if (GrScissorTest::kEnabled == scissorTest) {
2028 if (kYes_TriState != fHWScissorSettings.fEnabled) {
2029 GL_CALL(Enable(GR_GL_SCISSOR_TEST));
2030 fHWScissorSettings.fEnabled = kYes_TriState;
2031 }
2032 } else {
2033 if (kNo_TriState != fHWScissorSettings.fEnabled) {
2034 GL_CALL(Disable(GR_GL_SCISSOR_TEST));
2035 fHWScissorSettings.fEnabled = kNo_TriState;
2036 }
2037 }
2038 }
2039
2040 void GrGLGpu::flushScissorRect(const SkIRect& scissor, int rtHeight, GrSurfaceOrigin rtOrigin) {
2041 SkASSERT(fHWScissorSettings.fEnabled == TriState::kYes_TriState);
2042 auto nativeScissor = GrNativeRect::MakeRelativeTo(rtOrigin, rtHeight, scissor);
2043 if (fHWScissorSettings.fRect != nativeScissor) {
2044 GL_CALL(Scissor(nativeScissor.fX, nativeScissor.fY, nativeScissor.fWidth,
2045 nativeScissor.fHeight));
2046 fHWScissorSettings.fRect = nativeScissor;
2047 }
2048 }
2049
2050 void GrGLGpu::flushViewport(const SkIRect& viewport, int rtHeight, GrSurfaceOrigin rtOrigin) {
2051 auto nativeViewport = GrNativeRect::MakeRelativeTo(rtOrigin, rtHeight, viewport);
2052 if (fHWViewport != nativeViewport) {
2053 GL_CALL(Viewport(nativeViewport.fX, nativeViewport.fY,
2054 nativeViewport.fWidth, nativeViewport.fHeight));
2055 fHWViewport = nativeViewport;
2056 }
2057 }
2058
2059 void GrGLGpu::flushWindowRectangles(const GrWindowRectsState& windowState,
2060 const GrGLRenderTarget* rt, GrSurfaceOrigin origin) {
2061 #ifndef USE_NSIGHT
2062 typedef GrWindowRectsState::Mode Mode;
2063 // Window rects can't be used on-screen.
2064 SkASSERT(!windowState.enabled() || !rt->glRTFBOIDis0());
2065 SkASSERT(windowState.numWindows() <= this->caps()->maxWindowRectangles());
2066
2067 if (!this->caps()->maxWindowRectangles() ||
2068 fHWWindowRectsState.knownEqualTo(origin, rt->width(), rt->height(), windowState)) {
2069 return;
2070 }
2071
2072 // This is purely a workaround for a spurious warning generated by gcc. Otherwise the above
2073 // assert would be sufficient. https://gcc.gnu.org/bugzilla/show_bug.cgi?id=5912
2074 int numWindows = std::min(windowState.numWindows(), int(GrWindowRectangles::kMaxWindows));
2075 SkASSERT(windowState.numWindows() == numWindows);
2076
2077 GrNativeRect glwindows[GrWindowRectangles::kMaxWindows];
2078 const SkIRect* skwindows = windowState.windows().data();
2079 for (int i = 0; i < numWindows; ++i) {
2080 glwindows[i].setRelativeTo(origin, rt->height(), skwindows[i]);
2081 }
2082
2083 GrGLenum glmode = (Mode::kExclusive == windowState.mode()) ? GR_GL_EXCLUSIVE : GR_GL_INCLUSIVE;
2084 GL_CALL(WindowRectangles(glmode, numWindows, glwindows->asInts()));
2085
2086 fHWWindowRectsState.set(origin, rt->width(), rt->height(), windowState);
2087 #endif
2088 }
2089
2090 void GrGLGpu::disableWindowRectangles() {
2091 #ifndef USE_NSIGHT
2092 if (!this->caps()->maxWindowRectangles() || fHWWindowRectsState.knownDisabled()) {
2093 return;
2094 }
2095 GL_CALL(WindowRectangles(GR_GL_EXCLUSIVE, 0, nullptr));
2096 fHWWindowRectsState.setDisabled();
2097 #endif
2098 }
2099
2100 bool GrGLGpu::flushGLState(GrRenderTarget* renderTarget, bool useMultisampleFBO,
2101 const GrProgramInfo& programInfo) {
2102 this->handleDirtyContext();
2103
2104 sk_sp<GrGLProgram> program = fProgramCache->findOrCreateProgram(this->getContext(),
2105 programInfo);
2106 if (!program) {
2107 GrCapsDebugf(this->caps(), "Failed to create program!\n");
2108 return false;
2109 }
2110
2111 this->flushProgram(std::move(program));
2112
2113 // Swizzle the blend to match what the shader will output.
2114 this->flushBlendAndColorWrite(programInfo.pipeline().getXferProcessor().getBlendInfo(),
2115 programInfo.pipeline().writeSwizzle());
2116
2117 fHWProgram->updateUniforms(renderTarget, programInfo);
2118
2119 GrGLRenderTarget* glRT = static_cast<GrGLRenderTarget*>(renderTarget);
2120 GrStencilSettings stencil;
2121 if (programInfo.isStencilEnabled()) {
2122 SkASSERT(glRT->getStencilAttachment(useMultisampleFBO));
2123 stencil.reset(*programInfo.userStencilSettings(),
2124 programInfo.pipeline().hasStencilClip(),
2125 glRT->numStencilBits(useMultisampleFBO));
2126 }
2127 this->flushStencil(stencil, programInfo.origin());
2128 this->flushScissorTest(GrScissorTest(programInfo.pipeline().isScissorTestEnabled()));
2129 this->flushWindowRectangles(programInfo.pipeline().getWindowRectsState(),
2130 glRT, programInfo.origin());
2131 this->flushConservativeRasterState(programInfo.pipeline().usesConservativeRaster());
2132 this->flushWireframeState(programInfo.pipeline().isWireframe());
2133
2134 // This must come after textures are flushed because a texture may need
2135 // to be msaa-resolved (which will modify bound FBO state).
2136 this->flushRenderTarget(glRT, useMultisampleFBO);
2137
2138 return true;
2139 }
2140
2141 void GrGLGpu::flushProgram(sk_sp<GrGLProgram> program) {
2142 if (!program) {
2143 fHWProgram.reset();
2144 fHWProgramID = 0;
2145 return;
2146 }
2147 SkASSERT((program == fHWProgram) == (fHWProgramID == program->programID()));
2148 if (program == fHWProgram) {
2149 return;
2150 }
2151 auto id = program->programID();
2152 SkASSERT(id);
2153 GL_CALL(UseProgram(id));
2154 fHWProgram = std::move(program);
2155 fHWProgramID = id;
2156 }
2157
2158 void GrGLGpu::flushProgram(GrGLuint id) {
2159 SkASSERT(id);
2160 if (fHWProgramID == id) {
2161 SkASSERT(!fHWProgram);
2162 return;
2163 }
2164 fHWProgram.reset();
2165 GL_CALL(UseProgram(id));
2166 fHWProgramID = id;
2167 }
2168
2169 void GrGLGpu::didDrawTo(GrRenderTarget* rt) {
2170 SkASSERT(fHWWriteToColor != kUnknown_TriState);
2171 if (fHWWriteToColor == kYes_TriState) {
2172 // The bounds are only used to check for empty and we don't know the bounds. The origin
2173 // is irrelevant if there are no bounds.
2174 this->didWriteToSurface(rt, kTopLeft_GrSurfaceOrigin, /*bounds=*/nullptr);
2175 }
2176 }
2177
2178 GrGLenum GrGLGpu::bindBuffer(GrGpuBufferType type, const GrBuffer* buffer) {
2179 this->handleDirtyContext();
2180
2181 // Index buffer state is tied to the vertex array.
2182 if (GrGpuBufferType::kIndex == type) {
2183 this->bindVertexArray(0);
2184 }
2185
2186 auto* bufferState = this->hwBufferState(type);
2187 if (buffer->isCpuBuffer()) {
2188 if (!bufferState->fBufferZeroKnownBound) {
2189 GL_CALL(BindBuffer(bufferState->fGLTarget, 0));
2190 bufferState->fBufferZeroKnownBound = true;
2191 bufferState->fBoundBufferUniqueID.makeInvalid();
2192 }
2193 } else if (static_cast<const GrGpuBuffer*>(buffer)->uniqueID() !=
2194 bufferState->fBoundBufferUniqueID) {
2195 const GrGLBuffer* glBuffer = static_cast<const GrGLBuffer*>(buffer);
2196 GL_CALL(BindBuffer(bufferState->fGLTarget, glBuffer->bufferID()));
2197 bufferState->fBufferZeroKnownBound = false;
2198 bufferState->fBoundBufferUniqueID = glBuffer->uniqueID();
2199 }
2200
2201 return bufferState->fGLTarget;
2202 }
2203
2204 void GrGLGpu::clear(const GrScissorState& scissor,
2205 std::array<float, 4> color,
2206 GrRenderTarget* target,
2207 bool useMultisampleFBO,
2208 GrSurfaceOrigin origin) {
2209 // parent class should never let us get here with no RT
2210 SkASSERT(target);
2211 SkASSERT(!this->caps()->performColorClearsAsDraws());
2212 SkASSERT(!scissor.enabled() || !this->caps()->performPartialClearsAsDraws());
2213
2214 this->handleDirtyContext();
2215
2216 GrGLRenderTarget* glRT = static_cast<GrGLRenderTarget*>(target);
2217
2218 this->flushRenderTarget(glRT, useMultisampleFBO);
2219 this->flushScissor(scissor, glRT->height(), origin);
2220 this->disableWindowRectangles();
2221 this->flushColorWrite(true);
2222 this->flushClearColor(color);
2223 GL_CALL(Clear(GR_GL_COLOR_BUFFER_BIT));
2224 this->didWriteToSurface(glRT, origin, scissor.enabled() ? &scissor.rect() : nullptr);
2225 }
2226
2227 static bool use_tiled_rendering(const GrGLCaps& glCaps,
2228 const GrOpsRenderPass::StencilLoadAndStoreInfo& stencilLoadStore) {
2229 // Only use the tiled rendering extension if we can explicitly clear and discard the stencil.
2230 // Otherwise it's faster to just not use it.
2231 return glCaps.tiledRenderingSupport() && GrLoadOp::kClear == stencilLoadStore.fLoadOp &&
2232 GrStoreOp::kDiscard == stencilLoadStore.fStoreOp;
2233 }
2234
2235 void GrGLGpu::beginCommandBuffer(GrGLRenderTarget* rt, bool useMultisampleFBO,
2236 const SkIRect& bounds, GrSurfaceOrigin origin,
2237 const GrOpsRenderPass::LoadAndStoreInfo& colorLoadStore,
2238 const GrOpsRenderPass::StencilLoadAndStoreInfo& stencilLoadStore) {
2239 SkASSERT(!fIsExecutingCommandBuffer_DebugOnly);
2240
2241 this->handleDirtyContext();
2242
2243 this->flushRenderTarget(rt, useMultisampleFBO);
2244 SkDEBUGCODE(fIsExecutingCommandBuffer_DebugOnly = true);
2245
2246 if (use_tiled_rendering(this->glCaps(), stencilLoadStore)) {
2247 auto nativeBounds = GrNativeRect::MakeRelativeTo(origin, rt->height(), bounds);
2248 GrGLbitfield preserveMask = (GrLoadOp::kLoad == colorLoadStore.fLoadOp)
2249 ? GR_GL_COLOR_BUFFER_BIT0 : GR_GL_NONE;
2250 SkASSERT(GrLoadOp::kLoad != stencilLoadStore.fLoadOp); // Handled by use_tiled_rendering().
2251 GL_CALL(StartTiling(nativeBounds.fX, nativeBounds.fY, nativeBounds.fWidth,
2252 nativeBounds.fHeight, preserveMask));
2253 }
2254
2255 GrGLbitfield clearMask = 0;
2256 if (GrLoadOp::kClear == colorLoadStore.fLoadOp) {
2257 SkASSERT(!this->caps()->performColorClearsAsDraws());
2258 this->flushClearColor(colorLoadStore.fClearColor);
2259 this->flushColorWrite(true);
2260 clearMask |= GR_GL_COLOR_BUFFER_BIT;
2261 }
2262 if (GrLoadOp::kClear == stencilLoadStore.fLoadOp) {
2263 SkASSERT(!this->caps()->performStencilClearsAsDraws());
2264 GL_CALL(StencilMask(0xffffffff));
2265 GL_CALL(ClearStencil(0));
2266 clearMask |= GR_GL_STENCIL_BUFFER_BIT;
2267 }
2268 if (clearMask) {
2269 this->flushScissorTest(GrScissorTest::kDisabled);
2270 this->disableWindowRectangles();
2271 GL_CALL(Clear(clearMask));
2272 if (clearMask & GR_GL_COLOR_BUFFER_BIT) {
2273 this->didWriteToSurface(rt, origin, nullptr);
2274 }
2275 }
2276 }
2277
2278 void GrGLGpu::endCommandBuffer(GrGLRenderTarget* rt, bool useMultisampleFBO,
2279 const GrOpsRenderPass::LoadAndStoreInfo& colorLoadStore,
2280 const GrOpsRenderPass::StencilLoadAndStoreInfo& stencilLoadStore) {
2281 SkASSERT(fIsExecutingCommandBuffer_DebugOnly);
2282
2283 this->handleDirtyContext();
2284
2285 if (rt->uniqueID() != fHWBoundRenderTargetUniqueID ||
2286 useMultisampleFBO != fHWBoundFramebufferIsMSAA) {
2287 // The framebuffer binding changed in the middle of a command buffer. We should have already
2288 // printed a warning during onFBOChanged.
2289 return;
2290 }
2291
2292 if (GrGLCaps::kNone_InvalidateFBType != this->glCaps().invalidateFBType()) {
2293 STArray<2, GrGLenum> discardAttachments;
2294 if (GrStoreOp::kDiscard == colorLoadStore.fStoreOp) {
2295 discardAttachments.push_back(
2296 rt->isFBO0(useMultisampleFBO) ? GR_GL_COLOR : GR_GL_COLOR_ATTACHMENT0);
2297 }
2298 if (GrStoreOp::kDiscard == stencilLoadStore.fStoreOp) {
2299 discardAttachments.push_back(
2300 rt->isFBO0(useMultisampleFBO) ? GR_GL_STENCIL : GR_GL_STENCIL_ATTACHMENT);
2301 }
2302
2303 if (!discardAttachments.empty()) {
2304 if (GrGLCaps::kInvalidate_InvalidateFBType == this->glCaps().invalidateFBType()) {
2305 GL_CALL(InvalidateFramebuffer(GR_GL_FRAMEBUFFER, discardAttachments.size(),
2306 discardAttachments.begin()));
2307 } else {
2308 SkASSERT(GrGLCaps::kDiscard_InvalidateFBType == this->glCaps().invalidateFBType());
2309 GL_CALL(DiscardFramebuffer(GR_GL_FRAMEBUFFER, discardAttachments.size(),
2310 discardAttachments.begin()));
2311 }
2312 }
2313 }
2314
2315 if (use_tiled_rendering(this->glCaps(), stencilLoadStore)) {
2316 GrGLbitfield preserveMask = (GrStoreOp::kStore == colorLoadStore.fStoreOp)
2317 ? GR_GL_COLOR_BUFFER_BIT0 : GR_GL_NONE;
2318 // Handled by use_tiled_rendering().
2319 SkASSERT(GrStoreOp::kStore != stencilLoadStore.fStoreOp);
2320 GL_CALL(EndTiling(preserveMask));
2321 }
2322
2323 SkDEBUGCODE(fIsExecutingCommandBuffer_DebugOnly = false);
2324 }
2325
2326 void GrGLGpu::clearStencilClip(const GrScissorState& scissor, bool insideStencilMask,
2327 GrRenderTarget* target, bool useMultisampleFBO,
2328 GrSurfaceOrigin origin) {
2329 SkASSERT(target);
2330 SkASSERT(!this->caps()->performStencilClearsAsDraws());
2331 SkASSERT(!scissor.enabled() || !this->caps()->performPartialClearsAsDraws());
2332 this->handleDirtyContext();
2333
2334 GrAttachment* sb = target->getStencilAttachment(useMultisampleFBO);
2335 if (!sb) {
2336 // We should only get here if we marked a proxy as requiring a SB. However,
2337 // the SB creation could later fail. Likely clipping is going to go awry now.
2338 return;
2339 }
2340
2341 GrGLint stencilBitCount = GrBackendFormatStencilBits(sb->backendFormat());
2342 #if 0
2343 SkASSERT(stencilBitCount > 0);
2344 GrGLint clipStencilMask = (1 << (stencilBitCount - 1));
2345 #else
2346 // we could just clear the clip bit but when we go through
2347 // ANGLE a partial stencil mask will cause clears to be
2348 // turned into draws. Our contract on OpsTask says that
2349 // changing the clip between stencil passes may or may not
2350 // zero the client's clip bits. So we just clear the whole thing.
2351 static const GrGLint clipStencilMask = ~0;
2352 #endif
2353 GrGLint value;
2354 if (insideStencilMask) {
2355 value = (1 << (stencilBitCount - 1));
2356 } else {
2357 value = 0;
2358 }
2359 GrGLRenderTarget* glRT = static_cast<GrGLRenderTarget*>(target);
2360 this->flushRenderTarget(glRT, useMultisampleFBO);
2361
2362 this->flushScissor(scissor, glRT->height(), origin);
2363 this->disableWindowRectangles();
2364
2365 GL_CALL(StencilMask((uint32_t) clipStencilMask));
2366 GL_CALL(ClearStencil(value));
2367 GL_CALL(Clear(GR_GL_STENCIL_BUFFER_BIT));
2368 fHWStencilSettings.invalidate();
2369 }
2370
2371 bool GrGLGpu::readOrTransferPixelsFrom(GrSurface* surface,
2372 SkIRect rect,
2373 GrColorType surfaceColorType,
2374 GrColorType dstColorType,
2375 void* offsetOrPtr,
2376 int rowWidthInPixels) {
2377 SkASSERT(surface);
2378
2379 auto format = GrBackendFormats::AsGLFormat(surface->backendFormat());
2380 GrGLRenderTarget* renderTarget = static_cast<GrGLRenderTarget*>(surface->asRenderTarget());
2381 if (!renderTarget && !this->glCaps().isFormatRenderable(format, 1)) {
2382 return false;
2383 }
2384 GrGLenum externalFormat = 0;
2385 GrGLenum externalType = 0;
2386 this->glCaps().getReadPixelsFormat(
2387 format, surfaceColorType, dstColorType, &externalFormat, &externalType);
2388 if (!externalFormat || !externalType) {
2389 return false;
2390 }
2391
2392 if (renderTarget) {
2393 // Always bind the single sample FBO since we can't read pixels from an MSAA framebuffer.
2394 constexpr bool useMultisampleFBO = false;
2395 if (renderTarget->numSamples() > 1 && renderTarget->isFBO0(useMultisampleFBO)) {
2396 return false;
2397 }
2398 this->flushRenderTarget(renderTarget, useMultisampleFBO);
2399 } else {
2400 // Use a temporary FBO.
2401 this->bindSurfaceFBOForPixelOps(surface, 0, GR_GL_FRAMEBUFFER, kSrc_TempFBOTarget);
2402 fHWBoundRenderTargetUniqueID.makeInvalid();
2403 }
2404
2405 // determine if GL can read using the passed rowBytes or if we need a scratch buffer.
2406 if (rowWidthInPixels != rect.width()) {
2407 SkASSERT(this->glCaps().readPixelsRowBytesSupport());
2408 GL_CALL(PixelStorei(GR_GL_PACK_ROW_LENGTH, rowWidthInPixels));
2409 }
2410 GL_CALL(PixelStorei(GR_GL_PACK_ALIGNMENT, 1));
2411
2412 GL_CALL(ReadPixels(rect.left(),
2413 rect.top(),
2414 rect.width(),
2415 rect.height(),
2416 externalFormat,
2417 externalType,
2418 offsetOrPtr));
2419
2420 if (rowWidthInPixels != rect.width()) {
2421 SkASSERT(this->glCaps().readPixelsRowBytesSupport());
2422 GL_CALL(PixelStorei(GR_GL_PACK_ROW_LENGTH, 0));
2423 }
2424
2425 if (!renderTarget) {
2426 this->unbindSurfaceFBOForPixelOps(surface, 0, GR_GL_FRAMEBUFFER);
2427 }
2428 return true;
2429 }
2430
2431 bool GrGLGpu::onReadPixels(GrSurface* surface,
2432 SkIRect rect,
2433 GrColorType surfaceColorType,
2434 GrColorType dstColorType,
2435 void* buffer,
2436 size_t rowBytes) {
2437 SkASSERT(surface);
2438
2439 size_t bytesPerPixel = GrColorTypeBytesPerPixel(dstColorType);
2440
2441 // GL_PACK_ROW_LENGTH is in terms of pixels not bytes.
2442 int rowPixelWidth;
2443
2444 if (rowBytes == SkToSizeT(rect.width()*bytesPerPixel)) {
2445 rowPixelWidth = rect.width();
2446 } else {
2447 SkASSERT(!(rowBytes % bytesPerPixel));
2448 rowPixelWidth = rowBytes / bytesPerPixel;
2449 }
2450 this->unbindXferBuffer(GrGpuBufferType::kXferGpuToCpu);
2451 return this->readOrTransferPixelsFrom(surface,
2452 rect,
2453 surfaceColorType,
2454 dstColorType,
2455 buffer,
2456 rowPixelWidth);
2457 }
2458
2459 GrOpsRenderPass* GrGLGpu::onGetOpsRenderPass(
2460 GrRenderTarget* rt,
2461 bool useMultisampleFBO,
2462 GrAttachment*,
2463 GrSurfaceOrigin origin,
2464 const SkIRect& bounds,
2465 const GrOpsRenderPass::LoadAndStoreInfo& colorInfo,
2466 const GrOpsRenderPass::StencilLoadAndStoreInfo& stencilInfo,
2467 const TArray<GrSurfaceProxy*, true>& sampledProxies,
2468 GrXferBarrierFlags renderPassXferBarriers) {
2469 if (!fCachedOpsRenderPass) {
2470 fCachedOpsRenderPass = std::make_unique<GrGLOpsRenderPass>(this);
2471 }
2472 if (useMultisampleFBO && rt->numSamples() == 1) {
2473 // We will be using dynamic msaa. Ensure there is an attachment.
2474 auto glRT = static_cast<GrGLRenderTarget*>(rt);
2475 if (!glRT->ensureDynamicMSAAAttachment()) {
2476 SkDebugf("WARNING: Failed to make dmsaa attachment. Render pass will be dropped.");
2477 return nullptr;
2478 }
2479 }
2480 fCachedOpsRenderPass->set(rt, useMultisampleFBO, bounds, origin, colorInfo, stencilInfo);
2481 return fCachedOpsRenderPass.get();
2482 }
2483
2484 void GrGLGpu::flushRenderTarget(GrGLRenderTarget* target, bool useMultisampleFBO) {
2485 SkASSERT(target);
2486 GrGpuResource::UniqueID rtID = target->uniqueID();
2487 if (fHWBoundRenderTargetUniqueID != rtID ||
2488 fHWBoundFramebufferIsMSAA != useMultisampleFBO ||
2489 target->mustRebind(useMultisampleFBO)) {
2490 target->bind(useMultisampleFBO);
2491 #ifdef SK_DEBUG
2492 // don't do this check in Chromium -- this is causing
2493 // lots of repeated command buffer flushes when the compositor is
2494 // rendering with Ganesh, which is really slow; even too slow for
2495 // Debug mode.
2496 // Also don't do this when we know glCheckFramebufferStatus() may have side effects.
2497 if (!this->glCaps().skipErrorChecks() &&
2498 !this->glCaps().rebindColorAttachmentAfterCheckFramebufferStatus()) {
2499 GrGLenum status;
2500 GL_CALL_RET(status, CheckFramebufferStatus(GR_GL_FRAMEBUFFER));
2501 if (status != GR_GL_FRAMEBUFFER_COMPLETE) {
2502 SkDebugf("GrGLGpu::flushRenderTargetNoColorWrites glCheckFramebufferStatus %x\n",
2503 status);
2504 }
2505 }
2506 #endif
2507 fHWBoundRenderTargetUniqueID = rtID;
2508 fHWBoundFramebufferIsMSAA = useMultisampleFBO;
2509 this->flushViewport(SkIRect::MakeSize(target->dimensions()),
2510 target->height(),
2511 kTopLeft_GrSurfaceOrigin); // the origin is irrelevant in this case
2512 }
2513 if (this->caps()->workarounds().force_update_scissor_state_when_binding_fbo0) {
2514 // The driver forgets the correct scissor state when using FBO 0.
2515 if (!fHWScissorSettings.fRect.isInvalid()) {
2516 const GrNativeRect& r = fHWScissorSettings.fRect;
2517 GL_CALL(Scissor(r.fX, r.fY, r.fWidth, r.fHeight));
2518 }
2519 if (fHWScissorSettings.fEnabled == kYes_TriState) {
2520 GL_CALL(Disable(GR_GL_SCISSOR_TEST));
2521 GL_CALL(Enable(GR_GL_SCISSOR_TEST));
2522 } else if (fHWScissorSettings.fEnabled == kNo_TriState) {
2523 GL_CALL(Enable(GR_GL_SCISSOR_TEST));
2524 GL_CALL(Disable(GR_GL_SCISSOR_TEST));
2525 }
2526 }
2527
2528 if (this->glCaps().srgbWriteControl()) {
2529 this->flushFramebufferSRGB(this->caps()->isFormatSRGB(target->backendFormat()));
2530 }
2531
2532 if (this->glCaps().shouldQueryImplementationReadSupport(target->format())) {
2533 GrGLint format;
2534 GrGLint type;
2535 GR_GL_GetIntegerv(this->glInterface(), GR_GL_IMPLEMENTATION_COLOR_READ_FORMAT, &format);
2536 GR_GL_GetIntegerv(this->glInterface(), GR_GL_IMPLEMENTATION_COLOR_READ_TYPE, &type);
2537 this->glCaps().didQueryImplementationReadSupport(target->format(), format, type);
2538 }
2539 }
2540
2541 void GrGLGpu::flushFramebufferSRGB(bool enable) {
2542 if (enable && kYes_TriState != fHWSRGBFramebuffer) {
2543 GL_CALL(Enable(GR_GL_FRAMEBUFFER_SRGB));
2544 fHWSRGBFramebuffer = kYes_TriState;
2545 } else if (!enable && kNo_TriState != fHWSRGBFramebuffer) {
2546 GL_CALL(Disable(GR_GL_FRAMEBUFFER_SRGB));
2547 fHWSRGBFramebuffer = kNo_TriState;
2548 }
2549 }
2550
2551 GrGLenum GrGLGpu::prepareToDraw(GrPrimitiveType primitiveType) {
2552 fStats.incNumDraws();
2553
2554 if (this->glCaps().requiresCullFaceEnableDisableWhenDrawingLinesAfterNonLines() &&
2555 GrIsPrimTypeLines(primitiveType) && !GrIsPrimTypeLines(fLastPrimitiveType)) {
2556 GL_CALL(Enable(GR_GL_CULL_FACE));
2557 GL_CALL(Disable(GR_GL_CULL_FACE));
2558 }
2559 fLastPrimitiveType = primitiveType;
2560
2561 switch (primitiveType) {
2562 case GrPrimitiveType::kTriangles:
2563 return GR_GL_TRIANGLES;
2564 case GrPrimitiveType::kTriangleStrip:
2565 return GR_GL_TRIANGLE_STRIP;
2566 case GrPrimitiveType::kPoints:
2567 return GR_GL_POINTS;
2568 case GrPrimitiveType::kLines:
2569 return GR_GL_LINES;
2570 case GrPrimitiveType::kLineStrip:
2571 return GR_GL_LINE_STRIP;
2572 }
2573 SK_ABORT("invalid GrPrimitiveType");
2574 }
2575
2576 void GrGLGpu::onResolveRenderTarget(GrRenderTarget* target, const SkIRect& resolveRect) {
2577 auto glRT = static_cast<GrGLRenderTarget*>(target);
2578 if (this->glCaps().framebufferResolvesMustBeFullSize()) {
2579 this->resolveRenderFBOs(glRT, SkIRect::MakeSize(glRT->dimensions()),
2580 ResolveDirection::kMSAAToSingle);
2581 } else {
2582 this->resolveRenderFBOs(glRT, resolveRect, ResolveDirection::kMSAAToSingle);
2583 }
2584 }
2585
2586 void GrGLGpu::resolveRenderFBOs(GrGLRenderTarget* rt, const SkIRect& resolveRect,
2587 ResolveDirection resolveDirection,
2588 bool invalidateReadBufferAfterBlit) {
2589 this->handleDirtyContext();
2590 rt->bindForResolve(resolveDirection);
2591
2592 const GrGLCaps& caps = this->glCaps();
2593
2594 // make sure we go through flushRenderTarget() since we've modified
2595 // the bound DRAW FBO ID.
2596 fHWBoundRenderTargetUniqueID.makeInvalid();
2597 if (GrGLCaps::kES_Apple_MSFBOType == caps.msFBOType()) {
2598 // The Apple extension doesn't support blitting from single to multisample.
2599 SkASSERT(resolveDirection != ResolveDirection::kSingleToMSAA);
2600 SkASSERT(resolveRect == SkIRect::MakeSize(rt->dimensions()));
2601 // Apple's extension uses the scissor as the blit bounds.
2602 // Passing in kTopLeft_GrSurfaceOrigin will make sure no transformation of the rect
2603 // happens inside flushScissor since resolveRect is already in native device coordinates.
2604 GrScissorState scissor(rt->dimensions());
2605 SkAssertResult(scissor.set(resolveRect));
2606 this->flushScissor(scissor, rt->height(), kTopLeft_GrSurfaceOrigin);
2607 this->disableWindowRectangles();
2608 GL_CALL(ResolveMultisampleFramebuffer());
2609 } else {
2610 SkASSERT(!caps.framebufferResolvesMustBeFullSize() ||
2611 resolveRect == SkIRect::MakeSize(rt->dimensions()));
2612 int l = resolveRect.x();
2613 int b = resolveRect.y();
2614 int r = resolveRect.x() + resolveRect.width();
2615 int t = resolveRect.y() + resolveRect.height();
2616
2617 // BlitFrameBuffer respects the scissor, so disable it.
2618 this->flushScissorTest(GrScissorTest::kDisabled);
2619 this->disableWindowRectangles();
2620 GL_CALL(BlitFramebuffer(l, b, r, t, l, b, r, t, GR_GL_COLOR_BUFFER_BIT, GR_GL_NEAREST));
2621 }
2622
2623 if (caps.invalidateFBType() != GrGLCaps::kNone_InvalidateFBType &&
2624 invalidateReadBufferAfterBlit) {
2625 // Invalidate the read FBO attachment after the blit, in hopes that this allows the driver
2626 // to perform tiling optimizations.
2627 bool readBufferIsMSAA = resolveDirection == ResolveDirection::kMSAAToSingle;
2628 GrGLenum colorDiscardAttachment = rt->isFBO0(readBufferIsMSAA) ? GR_GL_COLOR
2629 : GR_GL_COLOR_ATTACHMENT0;
2630 if (caps.invalidateFBType() == GrGLCaps::kInvalidate_InvalidateFBType) {
2631 GL_CALL(InvalidateFramebuffer(GR_GL_READ_FRAMEBUFFER, 1, &colorDiscardAttachment));
2632 } else {
2633 SkASSERT(caps.invalidateFBType() == GrGLCaps::kDiscard_InvalidateFBType);
2634 // glDiscardFramebuffer only accepts GL_FRAMEBUFFER.
2635 rt->bind(readBufferIsMSAA);
2636 GL_CALL(DiscardFramebuffer(GR_GL_FRAMEBUFFER, 1, &colorDiscardAttachment));
2637 }
2638 }
2639 }
2640
2641 namespace {
2642
2643
2644 GrGLenum gr_to_gl_stencil_op(GrStencilOp op) {
2645 static const GrGLenum gTable[kGrStencilOpCount] = {
2646 GR_GL_KEEP, // kKeep
2647 GR_GL_ZERO, // kZero
2648 GR_GL_REPLACE, // kReplace
2649 GR_GL_INVERT, // kInvert
2650 GR_GL_INCR_WRAP, // kIncWrap
2651 GR_GL_DECR_WRAP, // kDecWrap
2652 GR_GL_INCR, // kIncClamp
2653 GR_GL_DECR, // kDecClamp
2654 };
2655 static_assert(0 == (int)GrStencilOp::kKeep);
2656 static_assert(1 == (int)GrStencilOp::kZero);
2657 static_assert(2 == (int)GrStencilOp::kReplace);
2658 static_assert(3 == (int)GrStencilOp::kInvert);
2659 static_assert(4 == (int)GrStencilOp::kIncWrap);
2660 static_assert(5 == (int)GrStencilOp::kDecWrap);
2661 static_assert(6 == (int)GrStencilOp::kIncClamp);
2662 static_assert(7 == (int)GrStencilOp::kDecClamp);
2663 SkASSERT(op < (GrStencilOp)kGrStencilOpCount);
2664 return gTable[(int)op];
2665 }
2666
2667 void set_gl_stencil(const GrGLInterface* gl,
2668 const GrStencilSettings::Face& face,
2669 GrGLenum glFace) {
2670 GrGLenum glFunc = GrToGLStencilFunc(face.fTest);
2671 GrGLenum glFailOp = gr_to_gl_stencil_op(face.fFailOp);
2672 GrGLenum glPassOp = gr_to_gl_stencil_op(face.fPassOp);
2673
2674 GrGLint ref = face.fRef;
2675 GrGLint mask = face.fTestMask;
2676 GrGLint writeMask = face.fWriteMask;
2677
2678 if (GR_GL_FRONT_AND_BACK == glFace) {
2679 // we call the combined func just in case separate stencil is not
2680 // supported.
2681 GR_GL_CALL(gl, StencilFunc(glFunc, ref, mask));
2682 GR_GL_CALL(gl, StencilMask(writeMask));
2683 GR_GL_CALL(gl, StencilOp(glFailOp, GR_GL_KEEP, glPassOp));
2684 } else {
2685 GR_GL_CALL(gl, StencilFuncSeparate(glFace, glFunc, ref, mask));
2686 GR_GL_CALL(gl, StencilMaskSeparate(glFace, writeMask));
2687 GR_GL_CALL(gl, StencilOpSeparate(glFace, glFailOp, GR_GL_KEEP, glPassOp));
2688 }
2689 }
2690 } // namespace
2691
2692 void GrGLGpu::flushStencil(const GrStencilSettings& stencilSettings, GrSurfaceOrigin origin) {
2693 if (stencilSettings.isDisabled()) {
2694 this->disableStencil();
2695 } else if (fHWStencilSettings != stencilSettings ||
2696 (stencilSettings.isTwoSided() && fHWStencilOrigin != origin)) {
2697 if (kYes_TriState != fHWStencilTestEnabled) {
2698 GL_CALL(Enable(GR_GL_STENCIL_TEST));
2699
2700 fHWStencilTestEnabled = kYes_TriState;
2701 }
2702 if (!stencilSettings.isTwoSided()) {
2703 set_gl_stencil(this->glInterface(), stencilSettings.singleSidedFace(),
2704 GR_GL_FRONT_AND_BACK);
2705 } else {
2706 set_gl_stencil(this->glInterface(), stencilSettings.postOriginCWFace(origin),
2707 GR_GL_FRONT);
2708 set_gl_stencil(this->glInterface(), stencilSettings.postOriginCCWFace(origin),
2709 GR_GL_BACK);
2710 }
2711 fHWStencilSettings = stencilSettings;
2712 fHWStencilOrigin = origin;
2713 }
2714 }
2715
2716 void GrGLGpu::disableStencil() {
2717 if (kNo_TriState != fHWStencilTestEnabled) {
2718 GL_CALL(Disable(GR_GL_STENCIL_TEST));
2719
2720 fHWStencilTestEnabled = kNo_TriState;
2721 fHWStencilSettings.invalidate();
2722 }
2723 }
2724
2725 void GrGLGpu::flushConservativeRasterState(bool enabled) {
2726 if (this->caps()->conservativeRasterSupport()) {
2727 if (enabled) {
2728 if (kYes_TriState != fHWConservativeRasterEnabled) {
2729 GL_CALL(Enable(GR_GL_CONSERVATIVE_RASTERIZATION));
2730 fHWConservativeRasterEnabled = kYes_TriState;
2731 }
2732 } else {
2733 if (kNo_TriState != fHWConservativeRasterEnabled) {
2734 GL_CALL(Disable(GR_GL_CONSERVATIVE_RASTERIZATION));
2735 fHWConservativeRasterEnabled = kNo_TriState;
2736 }
2737 }
2738 }
2739 }
2740
2741 void GrGLGpu::flushWireframeState(bool enabled) {
2742 if (this->caps()->wireframeSupport()) {
2743 if (this->caps()->wireframeMode() || enabled) {
2744 if (kYes_TriState != fHWWireframeEnabled) {
2745 GL_CALL(PolygonMode(GR_GL_FRONT_AND_BACK, GR_GL_LINE));
2746 fHWWireframeEnabled = kYes_TriState;
2747 }
2748 } else {
2749 if (kNo_TriState != fHWWireframeEnabled) {
2750 GL_CALL(PolygonMode(GR_GL_FRONT_AND_BACK, GR_GL_FILL));
2751 fHWWireframeEnabled = kNo_TriState;
2752 }
2753 }
2754 }
2755 }
2756
2757 void GrGLGpu::flushBlendAndColorWrite(const skgpu::BlendInfo& blendInfo,
2758 const skgpu::Swizzle& swizzle) {
2759 if (this->glCaps().neverDisableColorWrites() && !blendInfo.fWritesColor) {
2760 // We need to work around a driver bug by using a blend state that preserves the dst color,
2761 // rather than disabling color writes.
2762 skgpu::BlendInfo preserveDstBlend;
2763 preserveDstBlend.fSrcBlend = skgpu::BlendCoeff::kZero;
2764 preserveDstBlend.fDstBlend = skgpu::BlendCoeff::kOne;
2765 this->flushBlendAndColorWrite(preserveDstBlend, swizzle);
2766 return;
2767 }
2768
2769 skgpu::BlendEquation equation = blendInfo.fEquation;
2770 skgpu::BlendCoeff srcCoeff = blendInfo.fSrcBlend;
2771 skgpu::BlendCoeff dstCoeff = blendInfo.fDstBlend;
2772
2773 // Any optimization to disable blending should have already been applied and
2774 // tweaked the equation to "add "or "subtract", and the coeffs to (1, 0).
2775 bool blendOff = skgpu::BlendShouldDisable(equation, srcCoeff, dstCoeff) ||
2776 !blendInfo.fWritesColor;
2777
2778 if (blendOff) {
2779 if (kNo_TriState != fHWBlendState.fEnabled) {
2780 GL_CALL(Disable(GR_GL_BLEND));
2781
2782 // Workaround for the ARM KHR_blend_equation_advanced disable flags issue
2783 // https://code.google.com/p/skia/issues/detail?id=3943
2784 if (this->ctxInfo().vendor() == GrGLVendor::kARM &&
2785 skgpu::BlendEquationIsAdvanced(fHWBlendState.fEquation)) {
2786 SkASSERT(this->caps()->advancedBlendEquationSupport());
2787 // Set to any basic blending equation.
2788 skgpu::BlendEquation blendEquation = skgpu::BlendEquation::kAdd;
2789 GL_CALL(BlendEquation(gXfermodeEquation2Blend[(int)blendEquation]));
2790 fHWBlendState.fEquation = blendEquation;
2791 }
2792
2793 // Workaround for Adreno 5xx BlendFunc bug. See crbug.com/1241134.
2794 // We must also check to see if the blend coeffs are invalid because the client may have
2795 // reset our gl state and thus we will have forgotten if the previous use was a coeff
2796 // that referenced src2.
2797 if (this->glCaps().mustResetBlendFuncBetweenDualSourceAndDisable() &&
2798 (skgpu::BlendCoeffRefsSrc2(fHWBlendState.fSrcCoeff) ||
2799 skgpu::BlendCoeffRefsSrc2(fHWBlendState.fDstCoeff) ||
2800 fHWBlendState.fSrcCoeff == skgpu::BlendCoeff::kIllegal ||
2801 fHWBlendState.fDstCoeff == skgpu::BlendCoeff::kIllegal)) {
2802 // We just reset the blend func to anything that doesn't reference src2
2803 GL_CALL(BlendFunc(GR_GL_ONE, GR_GL_ZERO));
2804 fHWBlendState.fSrcCoeff = skgpu::BlendCoeff::kOne;
2805 fHWBlendState.fDstCoeff = skgpu::BlendCoeff::kZero;
2806 }
2807
2808 fHWBlendState.fEnabled = kNo_TriState;
2809 }
2810 } else {
2811 if (kYes_TriState != fHWBlendState.fEnabled) {
2812 GL_CALL(Enable(GR_GL_BLEND));
2813
2814 fHWBlendState.fEnabled = kYes_TriState;
2815 }
2816
2817 if (fHWBlendState.fEquation != equation) {
2818 GL_CALL(BlendEquation(gXfermodeEquation2Blend[(int)equation]));
2819 fHWBlendState.fEquation = equation;
2820 }
2821
2822 if (skgpu::BlendEquationIsAdvanced(equation)) {
2823 SkASSERT(this->caps()->advancedBlendEquationSupport());
2824
2825 this->flushColorWrite(blendInfo.fWritesColor);
2826 // Advanced equations have no other blend state.
2827 return;
2828 }
2829
2830 if (fHWBlendState.fSrcCoeff != srcCoeff || fHWBlendState.fDstCoeff != dstCoeff) {
2831 GL_CALL(BlendFunc(gXfermodeCoeff2Blend[(int)srcCoeff],
2832 gXfermodeCoeff2Blend[(int)dstCoeff]));
2833 fHWBlendState.fSrcCoeff = srcCoeff;
2834 fHWBlendState.fDstCoeff = dstCoeff;
2835 }
2836
2837 if (skgpu::BlendCoeffRefsConstant(srcCoeff) || skgpu::BlendCoeffRefsConstant(dstCoeff)) {
2838 SkPMColor4f blendConst = swizzle.applyTo(blendInfo.fBlendConstant);
2839 if (!fHWBlendState.fConstColorValid || fHWBlendState.fConstColor != blendConst) {
2840 GL_CALL(BlendColor(blendConst.fR, blendConst.fG, blendConst.fB, blendConst.fA));
2841 fHWBlendState.fConstColor = blendConst;
2842 fHWBlendState.fConstColorValid = true;
2843 }
2844 }
2845 }
2846
2847 this->flushColorWrite(blendInfo.fWritesColor);
2848 }
2849
2850 void GrGLGpu::bindTexture(int unitIdx, GrSamplerState samplerState, const skgpu::Swizzle& swizzle,
2851 GrGLTexture* texture) {
2852 SkASSERT(texture);
2853
2854 #ifdef SK_DEBUG
2855 if (!this->caps()->npotTextureTileSupport()) {
2856 if (samplerState.isRepeatedX()) {
2857 const int w = texture->width();
2858 SkASSERT(SkIsPow2(w));
2859 }
2860 if (samplerState.isRepeatedY()) {
2861 const int h = texture->height();
2862 SkASSERT(SkIsPow2(h));
2863 }
2864 }
2865 #endif
2866
2867 GrGpuResource::UniqueID textureID = texture->uniqueID();
2868 GrGLenum target = texture->target();
2869 if (fHWTextureUnitBindings[unitIdx].boundID(target) != textureID) {
2870 this->setTextureUnit(unitIdx);
2871 GL_CALL(BindTexture(target, texture->textureID()));
2872 fHWTextureUnitBindings[unitIdx].setBoundID(target, textureID);
2873 }
2874
2875 if (samplerState.mipmapped() == skgpu::Mipmapped::kYes) {
2876 if (!this->caps()->mipmapSupport() || texture->mipmapped() == skgpu::Mipmapped::kNo) {
2877 // We should have caught this already.
2878 SkASSERT(!samplerState.isAniso());
2879 samplerState = GrSamplerState(samplerState.wrapModeX(),
2880 samplerState.wrapModeY(),
2881 samplerState.filter(),
2882 GrSamplerState::MipmapMode::kNone);
2883 } else {
2884 SkASSERT(!texture->mipmapsAreDirty());
2885 }
2886 }
2887
2888 auto timestamp = texture->parameters()->resetTimestamp();
2889 bool setAll = timestamp < fResetTimestampForTextureParameters;
2890 const GrGLTextureParameters::SamplerOverriddenState* samplerStateToRecord = nullptr;
2891 GrGLTextureParameters::SamplerOverriddenState newSamplerState;
2892 if (this->glCaps().useSamplerObjects()) {
2893 fSamplerObjectCache->bindSampler(unitIdx, samplerState);
2894 if (this->glCaps().mustSetAnyTexParameterToEnableMipmapping()) {
2895 if (samplerState.mipmapped() == skgpu::Mipmapped::kYes) {
2896 GrGLenum minFilter = filter_to_gl_min_filter(samplerState.filter(),
2897 samplerState.mipmapMode());
2898 const GrGLTextureParameters::SamplerOverriddenState& oldSamplerState =
2899 texture->parameters()->samplerOverriddenState();
2900 this->setTextureUnit(unitIdx);
2901 GL_CALL(TexParameteri(target, GR_GL_TEXTURE_MIN_FILTER, minFilter));
2902 newSamplerState = oldSamplerState;
2903 newSamplerState.fMinFilter = minFilter;
2904 samplerStateToRecord = &newSamplerState;
2905 }
2906 }
2907 } else {
2908 if (fSamplerObjectCache) {
2909 fSamplerObjectCache->unbindSampler(unitIdx);
2910 }
2911 const GrGLTextureParameters::SamplerOverriddenState& oldSamplerState =
2912 texture->parameters()->samplerOverriddenState();
2913 samplerStateToRecord = &newSamplerState;
2914
2915 newSamplerState.fMinFilter = filter_to_gl_min_filter(samplerState.filter(),
2916 samplerState.mipmapMode());
2917 newSamplerState.fMagFilter = filter_to_gl_mag_filter(samplerState.filter());
2918
2919 newSamplerState.fWrapS = wrap_mode_to_gl_wrap(samplerState.wrapModeX(), this->glCaps());
2920 newSamplerState.fWrapT = wrap_mode_to_gl_wrap(samplerState.wrapModeY(), this->glCaps());
2921
2922 newSamplerState.fMaxAniso = std::min(static_cast<GrGLfloat>(samplerState.maxAniso()),
2923 this->glCaps().maxTextureMaxAnisotropy());
2924
2925 // These are the OpenGL default values.
2926 newSamplerState.fMinLOD = -1000.f;
2927 newSamplerState.fMaxLOD = 1000.f;
2928
2929 if (setAll || newSamplerState.fMagFilter != oldSamplerState.fMagFilter) {
2930 this->setTextureUnit(unitIdx);
2931 GL_CALL(TexParameteri(target, GR_GL_TEXTURE_MAG_FILTER, newSamplerState.fMagFilter));
2932 }
2933 if (setAll || newSamplerState.fMinFilter != oldSamplerState.fMinFilter) {
2934 this->setTextureUnit(unitIdx);
2935 GL_CALL(TexParameteri(target, GR_GL_TEXTURE_MIN_FILTER, newSamplerState.fMinFilter));
2936 }
2937 if (this->glCaps().mipmapLodControlSupport()) {
2938 if (setAll || newSamplerState.fMinLOD != oldSamplerState.fMinLOD) {
2939 this->setTextureUnit(unitIdx);
2940 GL_CALL(TexParameterf(target, GR_GL_TEXTURE_MIN_LOD, newSamplerState.fMinLOD));
2941 }
2942 if (setAll || newSamplerState.fMaxLOD != oldSamplerState.fMaxLOD) {
2943 this->setTextureUnit(unitIdx);
2944 GL_CALL(TexParameterf(target, GR_GL_TEXTURE_MAX_LOD, newSamplerState.fMaxLOD));
2945 }
2946 }
2947 if (setAll || newSamplerState.fWrapS != oldSamplerState.fWrapS) {
2948 this->setTextureUnit(unitIdx);
2949 GL_CALL(TexParameteri(target, GR_GL_TEXTURE_WRAP_S, newSamplerState.fWrapS));
2950 }
2951 if (setAll || newSamplerState.fWrapT != oldSamplerState.fWrapT) {
2952 this->setTextureUnit(unitIdx);
2953 GL_CALL(TexParameteri(target, GR_GL_TEXTURE_WRAP_T, newSamplerState.fWrapT));
2954 }
2955 if (this->glCaps().clampToBorderSupport()) {
2956 // Make sure the border color is transparent black (the default)
2957 if (setAll || oldSamplerState.fBorderColorInvalid) {
2958 this->setTextureUnit(unitIdx);
2959 static const GrGLfloat kTransparentBlack[4] = {0.f, 0.f, 0.f, 0.f};
2960 GL_CALL(TexParameterfv(target, GR_GL_TEXTURE_BORDER_COLOR, kTransparentBlack));
2961 }
2962 }
2963 if (this->caps()->anisoSupport()) {
2964 if (setAll || oldSamplerState.fMaxAniso != newSamplerState.fMaxAniso) {
2965 GL_CALL(TexParameterf(target,
2966 GR_GL_TEXTURE_MAX_ANISOTROPY,
2967 newSamplerState.fMaxAniso));
2968 }
2969 }
2970 }
2971 GrGLTextureParameters::NonsamplerState newNonsamplerState;
2972 newNonsamplerState.fBaseMipMapLevel = 0;
2973 newNonsamplerState.fMaxMipmapLevel = texture->maxMipmapLevel();
2974 newNonsamplerState.fSwizzleIsRGBA = true;
2975
2976 const GrGLTextureParameters::NonsamplerState& oldNonsamplerState =
2977 texture->parameters()->nonsamplerState();
2978 if (this->glCaps().textureSwizzleSupport()) {
2979 if (setAll || !oldNonsamplerState.fSwizzleIsRGBA) {
2980 static constexpr GrGLenum kRGBA[4] {
2981 GR_GL_RED,
2982 GR_GL_GREEN,
2983 GR_GL_BLUE,
2984 GR_GL_ALPHA
2985 };
2986 this->setTextureUnit(unitIdx);
2987 if (GR_IS_GR_GL(this->glStandard())) {
2988 static_assert(sizeof(kRGBA[0]) == sizeof(GrGLint));
2989 GL_CALL(TexParameteriv(target, GR_GL_TEXTURE_SWIZZLE_RGBA,
2990 reinterpret_cast<const GrGLint*>(kRGBA)));
2991 } else if (GR_IS_GR_GL_ES(this->glStandard())) {
2992 // ES3 added swizzle support but not GL_TEXTURE_SWIZZLE_RGBA.
2993 GL_CALL(TexParameteri(target, GR_GL_TEXTURE_SWIZZLE_R, kRGBA[0]));
2994 GL_CALL(TexParameteri(target, GR_GL_TEXTURE_SWIZZLE_G, kRGBA[1]));
2995 GL_CALL(TexParameteri(target, GR_GL_TEXTURE_SWIZZLE_B, kRGBA[2]));
2996 GL_CALL(TexParameteri(target, GR_GL_TEXTURE_SWIZZLE_A, kRGBA[3]));
2997 }
2998 }
2999 }
3000 // These are not supported in ES2 contexts
3001 if (this->glCaps().mipmapLevelControlSupport() &&
3002 (texture->textureType() != GrTextureType::kExternal ||
3003 !this->glCaps().dontSetBaseOrMaxLevelForExternalTextures())) {
3004 if (newNonsamplerState.fBaseMipMapLevel != oldNonsamplerState.fBaseMipMapLevel) {
3005 this->setTextureUnit(unitIdx);
3006 GL_CALL(TexParameteri(target, GR_GL_TEXTURE_BASE_LEVEL,
3007 newNonsamplerState.fBaseMipMapLevel));
3008 }
3009 if (newNonsamplerState.fMaxMipmapLevel != oldNonsamplerState.fMaxMipmapLevel) {
3010 this->setTextureUnit(unitIdx);
3011 GL_CALL(TexParameteri(target, GR_GL_TEXTURE_MAX_LEVEL,
3012 newNonsamplerState.fMaxMipmapLevel));
3013 }
3014 }
3015 texture->parameters()->set(samplerStateToRecord, newNonsamplerState,
3016 fResetTimestampForTextureParameters);
3017 }
3018
3019 void GrGLGpu::onResetTextureBindings() {
3020 static constexpr GrGLenum kTargets[] = {GR_GL_TEXTURE_2D, GR_GL_TEXTURE_RECTANGLE,
3021 GR_GL_TEXTURE_EXTERNAL};
3022 for (int i = 0; i < this->numTextureUnits(); ++i) {
3023 this->setTextureUnit(i);
3024 for (auto target : kTargets) {
3025 if (fHWTextureUnitBindings[i].hasBeenModified(target)) {
3026 GL_CALL(BindTexture(target, 0));
3027 }
3028 }
3029 fHWTextureUnitBindings[i].invalidateAllTargets(true);
3030 }
3031 }
3032
3033 void GrGLGpu::flushColorWrite(bool writeColor) {
3034 if (!writeColor) {
3035 if (kNo_TriState != fHWWriteToColor) {
3036 GL_CALL(ColorMask(GR_GL_FALSE, GR_GL_FALSE,
3037 GR_GL_FALSE, GR_GL_FALSE));
3038 fHWWriteToColor = kNo_TriState;
3039 }
3040 } else {
3041 if (kYes_TriState != fHWWriteToColor) {
3042 GL_CALL(ColorMask(GR_GL_TRUE, GR_GL_TRUE, GR_GL_TRUE, GR_GL_TRUE));
3043 fHWWriteToColor = kYes_TriState;
3044 }
3045 }
3046 }
3047
3048 void GrGLGpu::flushClearColor(std::array<float, 4> color) {
3049 GrGLfloat r = color[0], g = color[1], b = color[2], a = color[3];
3050 if (this->glCaps().clearToBoundaryValuesIsBroken() &&
3051 (1 == r || 0 == r) && (1 == g || 0 == g) && (1 == b || 0 == b) && (1 == a || 0 == a)) {
3052 static const GrGLfloat safeAlpha1 = nextafter(1.f, 2.f);
3053 static const GrGLfloat safeAlpha0 = nextafter(0.f, -1.f);
3054 a = (1 == a) ? safeAlpha1 : safeAlpha0;
3055 }
3056 if (r != fHWClearColor[0] || g != fHWClearColor[1] ||
3057 b != fHWClearColor[2] || a != fHWClearColor[3]) {
3058 GL_CALL(ClearColor(r, g, b, a));
3059 fHWClearColor[0] = r;
3060 fHWClearColor[1] = g;
3061 fHWClearColor[2] = b;
3062 fHWClearColor[3] = a;
3063 }
3064 }
3065
3066 void GrGLGpu::setTextureUnit(int unit) {
3067 SkASSERT(unit >= 0 && unit < this->numTextureUnits());
3068 if (unit != fHWActiveTextureUnitIdx) {
3069 GL_CALL(ActiveTexture(GR_GL_TEXTURE0 + unit));
3070 fHWActiveTextureUnitIdx = unit;
3071 }
3072 }
3073
3074 void GrGLGpu::bindTextureToScratchUnit(GrGLenum target, GrGLint textureID) {
3075 // Bind the last texture unit since it is the least likely to be used by GrGLProgram.
3076 int lastUnitIdx = this->numTextureUnits() - 1;
3077 if (lastUnitIdx != fHWActiveTextureUnitIdx) {
3078 GL_CALL(ActiveTexture(GR_GL_TEXTURE0 + lastUnitIdx));
3079 fHWActiveTextureUnitIdx = lastUnitIdx;
3080 }
3081 // Clear out the this field so that if a GrGLProgram does use this unit it will rebind the
3082 // correct texture.
3083 fHWTextureUnitBindings[lastUnitIdx].invalidateForScratchUse(target);
3084 GL_CALL(BindTexture(target, textureID));
3085 }
3086
3087 // Determines whether glBlitFramebuffer could be used between src and dst by onCopySurface.
3088 static inline bool can_blit_framebuffer_for_copy_surface(const GrSurface* dst,
3089 const GrSurface* src,
3090 const SkIRect& srcRect,
3091 const SkIRect& dstRect,
3092 const GrGLCaps& caps) {
3093 int dstSampleCnt = 0;
3094 int srcSampleCnt = 0;
3095 if (const GrRenderTarget* rt = dst->asRenderTarget()) {
3096 dstSampleCnt = rt->numSamples();
3097 }
3098 if (const GrRenderTarget* rt = src->asRenderTarget()) {
3099 srcSampleCnt = rt->numSamples();
3100 }
3101 SkASSERT((dstSampleCnt > 0) == SkToBool(dst->asRenderTarget()));
3102 SkASSERT((srcSampleCnt > 0) == SkToBool(src->asRenderTarget()));
3103
3104 GrGLFormat dstFormat = GrBackendFormats::AsGLFormat(dst->backendFormat());
3105 GrGLFormat srcFormat = GrBackendFormats::AsGLFormat(src->backendFormat());
3106
3107 const GrGLTexture* dstTex = static_cast<const GrGLTexture*>(dst->asTexture());
3108 const GrGLTexture* srcTex = static_cast<const GrGLTexture*>(src->asTexture());
3109
3110 GrTextureType dstTexType;
3111 GrTextureType* dstTexTypePtr = nullptr;
3112 GrTextureType srcTexType;
3113 GrTextureType* srcTexTypePtr = nullptr;
3114 if (dstTex) {
3115 dstTexType = dstTex->textureType();
3116 dstTexTypePtr = &dstTexType;
3117 }
3118 if (srcTex) {
3119 srcTexType = srcTex->textureType();
3120 srcTexTypePtr = &srcTexType;
3121 }
3122
3123 return caps.canCopyAsBlit(dstFormat, dstSampleCnt, dstTexTypePtr,
3124 srcFormat, srcSampleCnt, srcTexTypePtr,
3125 src->getBoundsRect(), true, srcRect, dstRect);
3126 }
3127
3128 static bool rt_has_msaa_render_buffer(const GrGLRenderTarget* rt, const GrGLCaps& glCaps) {
3129 // A RT has a separate MSAA renderbuffer if:
3130 // 1) It's multisampled
3131 // 2) We're using an extension with separate MSAA renderbuffers
3132 // 3) It's not FBO 0, which is special and always auto-resolves
3133 return rt->numSamples() > 1 && glCaps.usesMSAARenderBuffers() && !rt->isFBO0(true/*msaa*/);
3134 }
3135
3136 static inline bool can_copy_texsubimage(const GrSurface* dst, const GrSurface* src,
3137 const GrGLCaps& caps) {
3138
3139 const GrGLRenderTarget* dstRT = static_cast<const GrGLRenderTarget*>(dst->asRenderTarget());
3140 const GrGLRenderTarget* srcRT = static_cast<const GrGLRenderTarget*>(src->asRenderTarget());
3141 const GrGLTexture* dstTex = static_cast<const GrGLTexture*>(dst->asTexture());
3142 const GrGLTexture* srcTex = static_cast<const GrGLTexture*>(src->asTexture());
3143
3144 bool dstHasMSAARenderBuffer = dstRT ? rt_has_msaa_render_buffer(dstRT, caps) : false;
3145 bool srcHasMSAARenderBuffer = srcRT ? rt_has_msaa_render_buffer(srcRT, caps) : false;
3146
3147 GrGLFormat dstFormat = GrBackendFormats::AsGLFormat(dst->backendFormat());
3148 GrGLFormat srcFormat = GrBackendFormats::AsGLFormat(src->backendFormat());
3149
3150 GrTextureType dstTexType;
3151 GrTextureType* dstTexTypePtr = nullptr;
3152 GrTextureType srcTexType;
3153 GrTextureType* srcTexTypePtr = nullptr;
3154 if (dstTex) {
3155 dstTexType = dstTex->textureType();
3156 dstTexTypePtr = &dstTexType;
3157 }
3158 if (srcTex) {
3159 srcTexType = srcTex->textureType();
3160 srcTexTypePtr = &srcTexType;
3161 }
3162
3163 return caps.canCopyTexSubImage(dstFormat, dstHasMSAARenderBuffer, dstTexTypePtr,
3164 srcFormat, srcHasMSAARenderBuffer, srcTexTypePtr);
3165 }
3166
3167 void GrGLGpu::bindSurfaceFBOForPixelOps(GrSurface* surface, int mipLevel, GrGLenum fboTarget,
3168 TempFBOTarget tempFBOTarget) {
3169 GrGLRenderTarget* rt = static_cast<GrGLRenderTarget*>(surface->asRenderTarget());
3170 if (!rt || mipLevel > 0) {
3171 SkASSERT(surface->asTexture());
3172 GrGLTexture* texture = static_cast<GrGLTexture*>(surface->asTexture());
3173 GrGLuint texID = texture->textureID();
3174 GrGLenum target = texture->target();
3175 GrGLuint* tempFBOID;
3176 tempFBOID = kSrc_TempFBOTarget == tempFBOTarget ? &fTempSrcFBOID : &fTempDstFBOID;
3177
3178 if (0 == *tempFBOID) {
3179 GR_GL_CALL(this->glInterface(), GenFramebuffers(1, tempFBOID));
3180 }
3181
3182 this->bindFramebuffer(fboTarget, *tempFBOID);
3183 GR_GL_CALL(
3184 this->glInterface(),
3185 FramebufferTexture2D(fboTarget, GR_GL_COLOR_ATTACHMENT0, target, texID, mipLevel));
3186 if (mipLevel == 0) {
3187 texture->baseLevelWasBoundToFBO();
3188 }
3189 } else {
3190 rt->bindForPixelOps(fboTarget);
3191 }
3192 }
3193
3194 void GrGLGpu::unbindSurfaceFBOForPixelOps(GrSurface* surface, int mipLevel, GrGLenum fboTarget) {
3195 // bindSurfaceFBOForPixelOps temporarily binds textures that are not render targets to
3196 if (mipLevel > 0 || !surface->asRenderTarget()) {
3197 SkASSERT(surface->asTexture());
3198 GrGLenum textureTarget = static_cast<GrGLTexture*>(surface->asTexture())->target();
3199 GR_GL_CALL(this->glInterface(), FramebufferTexture2D(fboTarget,
3200 GR_GL_COLOR_ATTACHMENT0,
3201 textureTarget,
3202 0,
3203 0));
3204 }
3205 }
3206
3207 void GrGLGpu::onFBOChanged() {
3208 if (this->caps()->workarounds().flush_on_framebuffer_change) {
3209 this->flush(FlushType::kForce);
3210 }
3211 #ifdef SK_DEBUG
3212 if (fIsExecutingCommandBuffer_DebugOnly) {
3213 SkDebugf("WARNING: GL FBO binding changed while executing a command buffer. "
3214 "This will severely hurt performance.\n");
3215 }
3216 #endif
3217 }
3218
3219 void GrGLGpu::bindFramebuffer(GrGLenum target, GrGLuint fboid) {
3220 GL_CALL(BindFramebuffer(target, fboid));
3221 if (target == GR_GL_FRAMEBUFFER || target == GR_GL_DRAW_FRAMEBUFFER) {
3222 fBoundDrawFramebuffer = fboid;
3223 }
3224 this->onFBOChanged();
3225 }
3226
3227 void GrGLGpu::deleteFramebuffer(GrGLuint fboid) {
3228 // We're relying on the GL state shadowing being correct in the workaround code below so we
3229 // need to handle a dirty context.
3230 this->handleDirtyContext();
3231 if (fboid == fBoundDrawFramebuffer &&
3232 this->caps()->workarounds().unbind_attachments_on_bound_render_fbo_delete) {
3233 // This workaround only applies to deleting currently bound framebuffers
3234 // on Adreno 420. Because this is a somewhat rare case, instead of
3235 // tracking all the attachments of every framebuffer instead just always
3236 // unbind all attachments.
3237 GL_CALL(FramebufferRenderbuffer(GR_GL_FRAMEBUFFER, GR_GL_COLOR_ATTACHMENT0,
3238 GR_GL_RENDERBUFFER, 0));
3239 GL_CALL(FramebufferRenderbuffer(GR_GL_FRAMEBUFFER, GR_GL_STENCIL_ATTACHMENT,
3240 GR_GL_RENDERBUFFER, 0));
3241 GL_CALL(FramebufferRenderbuffer(GR_GL_FRAMEBUFFER, GR_GL_DEPTH_ATTACHMENT,
3242 GR_GL_RENDERBUFFER, 0));
3243 }
3244
3245 GL_CALL(DeleteFramebuffers(1, &fboid));
3246
3247 // Deleting the currently bound framebuffer rebinds to 0.
3248 if (fboid == fBoundDrawFramebuffer) {
3249 this->onFBOChanged();
3250 }
3251 }
3252
3253 bool GrGLGpu::onCopySurface(GrSurface* dst, const SkIRect& dstRect,
3254 GrSurface* src, const SkIRect& srcRect,
3255 GrSamplerState::Filter filter) {
3256 // Don't prefer copying as a draw if the dst doesn't already have a FBO object.
3257 // This implicitly handles this->glCaps().useDrawInsteadOfAllRenderTargetWrites().
3258 bool preferCopy = SkToBool(dst->asRenderTarget());
3259 bool scalingCopy = dstRect.size() != srcRect.size();
3260 auto dstFormat = GrBackendFormats::AsGLFormat(dst->backendFormat());
3261 if (preferCopy &&
3262 this->glCaps().canCopyAsDraw(dstFormat, SkToBool(src->asTexture()), scalingCopy)) {
3263 GrRenderTarget* dstRT = dst->asRenderTarget();
3264 bool drawToMultisampleFBO = dstRT && dstRT->numSamples() > 1;
3265 if (this->copySurfaceAsDraw(dst, drawToMultisampleFBO, src, srcRect, dstRect, filter)) {
3266 return true;
3267 }
3268 }
3269
3270 // Prefer copying as with glCopyTexSubImage when the dimensions are the same.
3271 if (!scalingCopy && can_copy_texsubimage(dst, src, this->glCaps())) {
3272 this->copySurfaceAsCopyTexSubImage(dst, src, srcRect, dstRect.topLeft());
3273 return true;
3274 }
3275
3276 if (can_blit_framebuffer_for_copy_surface(dst, src, srcRect, dstRect, this->glCaps())) {
3277 return this->copySurfaceAsBlitFramebuffer(dst, src, srcRect, dstRect, filter);
3278 }
3279
3280 if (!preferCopy &&
3281 this->glCaps().canCopyAsDraw(dstFormat, SkToBool(src->asTexture()), scalingCopy)) {
3282 GrRenderTarget* dstRT = dst->asRenderTarget();
3283 bool drawToMultisampleFBO = dstRT && dstRT->numSamples() > 1;
3284 if (this->copySurfaceAsDraw(dst, drawToMultisampleFBO, src, srcRect, dstRect, filter)) {
3285 return true;
3286 }
3287 }
3288
3289 return false;
3290 }
3291
3292 bool GrGLGpu::createCopyProgram(GrTexture* srcTex) {
3293 TRACE_EVENT0("skia.gpu", TRACE_FUNC);
3294
3295 int progIdx = TextureToCopyProgramIdx(srcTex);
3296 const GrShaderCaps* shaderCaps = this->caps()->shaderCaps();
3297 SkSLType samplerType = SkSLCombinedSamplerTypeForTextureType(srcTex->textureType());
3298
3299 if (!fCopyProgramArrayBuffer) {
3300 static const GrGLfloat vdata[] = {
3301 0, 0,
3302 0, 1,
3303 1, 0,
3304 1, 1
3305 };
3306 fCopyProgramArrayBuffer = GrGLBuffer::Make(this,
3307 sizeof(vdata),
3308 GrGpuBufferType::kVertex,
3309 kStatic_GrAccessPattern);
3310 if (fCopyProgramArrayBuffer) {
3311 fCopyProgramArrayBuffer->updateData(
3312 vdata, /*offset=*/0, sizeof(vdata), /*preserve=*/false);
3313 }
3314 }
3315 if (!fCopyProgramArrayBuffer) {
3316 return false;
3317 }
3318
3319 SkASSERT(!fCopyPrograms[progIdx].fProgram);
3320 GL_CALL_RET(fCopyPrograms[progIdx].fProgram, CreateProgram());
3321 if (!fCopyPrograms[progIdx].fProgram) {
3322 return false;
3323 }
3324
3325 GrShaderVar aVertex("a_vertex", SkSLType::kHalf2, GrShaderVar::TypeModifier::In);
3326 GrShaderVar uTexCoordXform("u_texCoordXform", SkSLType::kHalf4,
3327 GrShaderVar::TypeModifier::Uniform);
3328 GrShaderVar uPosXform("u_posXform", SkSLType::kHalf4, GrShaderVar::TypeModifier::Uniform);
3329 GrShaderVar uTexture("u_texture", samplerType);
3330 GrShaderVar vTexCoord("v_texCoord", SkSLType::kHalf2, GrShaderVar::TypeModifier::Out);
3331 GrShaderVar oFragColor("o_FragColor", SkSLType::kHalf4, GrShaderVar::TypeModifier::Out);
3332
3333 SkString vshaderTxt;
3334 if (shaderCaps->fNoPerspectiveInterpolationSupport) {
3335 if (const char* extension = shaderCaps->noperspectiveInterpolationExtensionString()) {
3336 vshaderTxt.appendf("#extension %s : require\n", extension);
3337 }
3338 vTexCoord.addModifier("noperspective");
3339 }
3340
3341 aVertex.appendDecl(shaderCaps, &vshaderTxt);
3342 vshaderTxt.append(";");
3343 uTexCoordXform.appendDecl(shaderCaps, &vshaderTxt);
3344 vshaderTxt.append(";");
3345 uPosXform.appendDecl(shaderCaps, &vshaderTxt);
3346 vshaderTxt.append(";");
3347 vTexCoord.appendDecl(shaderCaps, &vshaderTxt);
3348 vshaderTxt.append(";");
3349
3350 vshaderTxt.append(
3351 // Copy Program VS
3352 "void main() {"
3353 "v_texCoord = half2(a_vertex.xy * u_texCoordXform.xy + u_texCoordXform.zw);"
3354 "sk_Position.xy = a_vertex * u_posXform.xy + u_posXform.zw;"
3355 "sk_Position.zw = half2(0, 1);"
3356 "}"
3357 );
3358
3359 SkString fshaderTxt;
3360 if (shaderCaps->fNoPerspectiveInterpolationSupport) {
3361 if (const char* extension = shaderCaps->noperspectiveInterpolationExtensionString()) {
3362 fshaderTxt.appendf("#extension %s : require\n", extension);
3363 }
3364 }
3365 vTexCoord.setTypeModifier(GrShaderVar::TypeModifier::In);
3366 vTexCoord.appendDecl(shaderCaps, &fshaderTxt);
3367 fshaderTxt.append(";");
3368 uTexture.appendDecl(shaderCaps, &fshaderTxt);
3369 fshaderTxt.append(";");
3370 fshaderTxt.appendf(
3371 // Copy Program FS
3372 "void main() {"
3373 "sk_FragColor = sample(u_texture, v_texCoord);"
3374 "}"
3375 );
3376 std::string vertexSkSL{vshaderTxt.c_str(), vshaderTxt.size()};
3377 std::string fragmentSkSL{fshaderTxt.c_str(), fshaderTxt.size()};
3378
3379 auto errorHandler = this->getContext()->priv().getShaderErrorHandler();
3380 SkSL::NativeShader glsl[kGrShaderTypeCount];
3381 SkSL::ProgramSettings settings;
3382 SkSL::Program::Interface interface;
3383 skgpu::SkSLToGLSL(shaderCaps, vertexSkSL, SkSL::ProgramKind::kVertex, settings,
3384 &glsl[kVertex_GrShaderType], &interface, errorHandler);
3385 GrGLuint vshader = GrGLCompileAndAttachShader(*fGLContext,
3386 fCopyPrograms[progIdx].fProgram,
3387 GR_GL_VERTEX_SHADER,
3388 glsl[kVertex_GrShaderType],
3389 /*shaderWasCached=*/false,
3390 fProgramCache->stats(),
3391 errorHandler);
3392 SkASSERT(interface == SkSL::Program::Interface());
3393 if (!vshader) {
3394 // Just delete the program, no shaders to delete
3395 cleanup_program(this, &fCopyPrograms[progIdx].fProgram, nullptr, nullptr);
3396 return false;
3397 }
3398
3399 skgpu::SkSLToGLSL(shaderCaps, fragmentSkSL, SkSL::ProgramKind::kFragment, settings,
3400 &glsl[kFragment_GrShaderType], &interface, errorHandler);
3401 GrGLuint fshader = GrGLCompileAndAttachShader(*fGLContext,
3402 fCopyPrograms[progIdx].fProgram,
3403 GR_GL_FRAGMENT_SHADER,
3404 glsl[kFragment_GrShaderType],
3405 /*shaderWasCached=*/false,
3406 fProgramCache->stats(),
3407 errorHandler);
3408 SkASSERT(interface == SkSL::Program::Interface());
3409 if (!fshader) {
3410 // Delete the program and previously compiled vertex shader
3411 cleanup_program(this, &fCopyPrograms[progIdx].fProgram, &vshader, nullptr);
3412 return false;
3413 }
3414
3415 const std::string* sksl[kGrShaderTypeCount] = {&vertexSkSL, &fragmentSkSL};
3416 GL_CALL(LinkProgram(fCopyPrograms[progIdx].fProgram));
3417 if (!GrGLCheckLinkStatus(this,
3418 fCopyPrograms[progIdx].fProgram,
3419 /*shaderWasCached=*/false,
3420 errorHandler,
3421 sksl,
3422 glsl)) {
3423 // Failed to link, delete everything
3424 cleanup_program(this, &fCopyPrograms[progIdx].fProgram, &vshader, &fshader);
3425 return false;
3426 }
3427
3428 GL_CALL_RET(fCopyPrograms[progIdx].fTextureUniform,
3429 GetUniformLocation(fCopyPrograms[progIdx].fProgram, "u_texture"));
3430 GL_CALL_RET(fCopyPrograms[progIdx].fPosXformUniform,
3431 GetUniformLocation(fCopyPrograms[progIdx].fProgram, "u_posXform"));
3432 GL_CALL_RET(fCopyPrograms[progIdx].fTexCoordXformUniform,
3433 GetUniformLocation(fCopyPrograms[progIdx].fProgram, "u_texCoordXform"));
3434
3435 GL_CALL(BindAttribLocation(fCopyPrograms[progIdx].fProgram, 0, "a_vertex"));
3436
3437 // Cleanup the shaders, but not the program
3438 cleanup_program(this, nullptr, &vshader, &fshader);
3439
3440 return true;
3441 }
3442
3443 bool GrGLGpu::createMipmapProgram(int progIdx) {
3444 const bool oddWidth = SkToBool(progIdx & 0x2);
3445 const bool oddHeight = SkToBool(progIdx & 0x1);
3446 const int numTaps = (oddWidth ? 2 : 1) * (oddHeight ? 2 : 1);
3447
3448 const GrShaderCaps* shaderCaps = this->caps()->shaderCaps();
3449
3450 SkASSERT(!fMipmapPrograms[progIdx].fProgram);
3451 GL_CALL_RET(fMipmapPrograms[progIdx].fProgram, CreateProgram());
3452 if (!fMipmapPrograms[progIdx].fProgram) {
3453 return false;
3454 }
3455
3456 GrShaderVar aVertex("a_vertex", SkSLType::kHalf2, GrShaderVar::TypeModifier::In);
3457 GrShaderVar uTexCoordXform("u_texCoordXform", SkSLType::kHalf4,
3458 GrShaderVar::TypeModifier::Uniform);
3459 GrShaderVar uTexture("u_texture", SkSLType::kTexture2DSampler);
3460 // We need 1, 2, or 4 texture coordinates (depending on parity of each dimension):
3461 GrShaderVar vTexCoords[] = {
3462 GrShaderVar("v_texCoord0", SkSLType::kHalf2, GrShaderVar::TypeModifier::Out),
3463 GrShaderVar("v_texCoord1", SkSLType::kHalf2, GrShaderVar::TypeModifier::Out),
3464 GrShaderVar("v_texCoord2", SkSLType::kHalf2, GrShaderVar::TypeModifier::Out),
3465 GrShaderVar("v_texCoord3", SkSLType::kHalf2, GrShaderVar::TypeModifier::Out),
3466 };
3467 GrShaderVar oFragColor("o_FragColor", SkSLType::kHalf4,GrShaderVar::TypeModifier::Out);
3468
3469 SkString vshaderTxt;
3470 if (shaderCaps->fNoPerspectiveInterpolationSupport) {
3471 if (const char* extension = shaderCaps->noperspectiveInterpolationExtensionString()) {
3472 vshaderTxt.appendf("#extension %s : require\n", extension);
3473 }
3474 vTexCoords[0].addModifier("noperspective");
3475 vTexCoords[1].addModifier("noperspective");
3476 vTexCoords[2].addModifier("noperspective");
3477 vTexCoords[3].addModifier("noperspective");
3478 }
3479
3480 aVertex.appendDecl(shaderCaps, &vshaderTxt);
3481 vshaderTxt.append(";");
3482 uTexCoordXform.appendDecl(shaderCaps, &vshaderTxt);
3483 vshaderTxt.append(";");
3484 for (int i = 0; i < numTaps; ++i) {
3485 vTexCoords[i].appendDecl(shaderCaps, &vshaderTxt);
3486 vshaderTxt.append(";");
3487 }
3488
3489 vshaderTxt.append(
3490 // Mipmap Program VS
3491 "void main() {"
3492 "sk_Position.xy = a_vertex * half2(2) - half2(1);"
3493 "sk_Position.zw = half2(0, 1);"
3494 );
3495
3496 // Insert texture coordinate computation:
3497 if (oddWidth && oddHeight) {
3498 vshaderTxt.append(
3499 "v_texCoord0 = a_vertex.xy * u_texCoordXform.yw;"
3500 "v_texCoord1 = a_vertex.xy * u_texCoordXform.yw + half2(u_texCoordXform.x, 0);"
3501 "v_texCoord2 = a_vertex.xy * u_texCoordXform.yw + half2(0, u_texCoordXform.z);"
3502 "v_texCoord3 = a_vertex.xy * u_texCoordXform.yw + u_texCoordXform.xz;"
3503 );
3504 } else if (oddWidth) {
3505 vshaderTxt.append(
3506 "v_texCoord0 = a_vertex.xy * half2(u_texCoordXform.y, 1);"
3507 "v_texCoord1 = a_vertex.xy * half2(u_texCoordXform.y, 1) + half2(u_texCoordXform.x, 0);"
3508 );
3509 } else if (oddHeight) {
3510 vshaderTxt.append(
3511 "v_texCoord0 = a_vertex.xy * half2(1, u_texCoordXform.w);"
3512 "v_texCoord1 = a_vertex.xy * half2(1, u_texCoordXform.w) + half2(0, u_texCoordXform.z);"
3513 );
3514 } else {
3515 vshaderTxt.append(
3516 "v_texCoord0 = a_vertex.xy;"
3517 );
3518 }
3519
3520 vshaderTxt.append("}");
3521
3522 SkString fshaderTxt;
3523 if (shaderCaps->fNoPerspectiveInterpolationSupport) {
3524 if (const char* extension = shaderCaps->noperspectiveInterpolationExtensionString()) {
3525 fshaderTxt.appendf("#extension %s : require\n", extension);
3526 }
3527 }
3528 for (int i = 0; i < numTaps; ++i) {
3529 vTexCoords[i].setTypeModifier(GrShaderVar::TypeModifier::In);
3530 vTexCoords[i].appendDecl(shaderCaps, &fshaderTxt);
3531 fshaderTxt.append(";");
3532 }
3533 uTexture.appendDecl(shaderCaps, &fshaderTxt);
3534 fshaderTxt.append(";");
3535 fshaderTxt.append(
3536 // Mipmap Program FS
3537 "void main() {"
3538 );
3539
3540 if (oddWidth && oddHeight) {
3541 fshaderTxt.append(
3542 "sk_FragColor = (sample(u_texture, v_texCoord0) + "
3543 "sample(u_texture, v_texCoord1) + "
3544 "sample(u_texture, v_texCoord2) + "
3545 "sample(u_texture, v_texCoord3)) * 0.25;"
3546 );
3547 } else if (oddWidth || oddHeight) {
3548 fshaderTxt.append(
3549 "sk_FragColor = (sample(u_texture, v_texCoord0) + "
3550 "sample(u_texture, v_texCoord1)) * 0.5;"
3551 );
3552 } else {
3553 fshaderTxt.append(
3554 "sk_FragColor = sample(u_texture, v_texCoord0);"
3555 );
3556 }
3557
3558 fshaderTxt.append("}");
3559
3560 std::string vertexSkSL{vshaderTxt.c_str(), vshaderTxt.size()};
3561 std::string fragmentSkSL{fshaderTxt.c_str(), fshaderTxt.size()};
3562
3563 auto errorHandler = this->getContext()->priv().getShaderErrorHandler();
3564 SkSL::NativeShader glsl[kGrShaderTypeCount];
3565 SkSL::ProgramSettings settings;
3566 SkSL::Program::Interface interface;
3567
3568 skgpu::SkSLToGLSL(shaderCaps, vertexSkSL, SkSL::ProgramKind::kVertex, settings,
3569 &glsl[kVertex_GrShaderType], &interface, errorHandler);
3570 GrGLuint vshader = GrGLCompileAndAttachShader(*fGLContext,
3571 fMipmapPrograms[progIdx].fProgram,
3572 GR_GL_VERTEX_SHADER,
3573 glsl[kVertex_GrShaderType],
3574 /*shaderWasCached=*/false,
3575 fProgramCache->stats(),
3576 errorHandler);
3577 SkASSERT(interface == SkSL::Program::Interface());
3578 if (!vshader) {
3579 cleanup_program(this, &fMipmapPrograms[progIdx].fProgram, nullptr, nullptr);
3580 return false;
3581 }
3582
3583 skgpu::SkSLToGLSL(shaderCaps, fragmentSkSL, SkSL::ProgramKind::kFragment, settings,
3584 &glsl[kFragment_GrShaderType], &interface, errorHandler);
3585 GrGLuint fshader = GrGLCompileAndAttachShader(*fGLContext,
3586 fMipmapPrograms[progIdx].fProgram,
3587 GR_GL_FRAGMENT_SHADER,
3588 glsl[kFragment_GrShaderType],
3589 /*shaderWasCached=*/false,
3590 fProgramCache->stats(),
3591 errorHandler);
3592 SkASSERT(interface == SkSL::Program::Interface());
3593 if (!fshader) {
3594 cleanup_program(this, &fMipmapPrograms[progIdx].fProgram, &vshader, nullptr);
3595 return false;
3596 }
3597
3598 const std::string* sksl[kGrShaderTypeCount] = {&vertexSkSL, &fragmentSkSL};
3599 GL_CALL(LinkProgram(fMipmapPrograms[progIdx].fProgram));
3600 if (!GrGLCheckLinkStatus(this,
3601 fMipmapPrograms[progIdx].fProgram,
3602 /*shaderWasCached=*/false,
3603 errorHandler,
3604 sksl,
3605 glsl)) {
3606 // Program linking failed, clean up
3607 cleanup_program(this, &fMipmapPrograms[progIdx].fProgram, &vshader, &fshader);
3608 return false;
3609 }
3610
3611 GL_CALL_RET(fMipmapPrograms[progIdx].fTextureUniform,
3612 GetUniformLocation(fMipmapPrograms[progIdx].fProgram, "u_texture"));
3613 GL_CALL_RET(fMipmapPrograms[progIdx].fTexCoordXformUniform,
3614 GetUniformLocation(fMipmapPrograms[progIdx].fProgram, "u_texCoordXform"));
3615
3616 GL_CALL(BindAttribLocation(fMipmapPrograms[progIdx].fProgram, 0, "a_vertex"));
3617
3618 // Clean up the shaders
3619 cleanup_program(this, nullptr, &vshader, &fshader);
3620
3621 return true;
3622 }
3623
3624 bool GrGLGpu::copySurfaceAsDraw(GrSurface* dst, bool drawToMultisampleFBO, GrSurface* src,
3625 const SkIRect& srcRect, const SkIRect& dstRect,
3626 GrSamplerState::Filter filter) {
3627 auto* srcTex = static_cast<GrGLTexture*>(src->asTexture());
3628 if (!srcTex) {
3629 return false;
3630 }
3631 // We don't swizzle at all in our copies.
3632 this->bindTexture(0, filter, skgpu::Swizzle::RGBA(), srcTex);
3633 if (auto* dstRT = static_cast<GrGLRenderTarget*>(dst->asRenderTarget())) {
3634 this->flushRenderTarget(dstRT, drawToMultisampleFBO);
3635 } else {
3636 auto* dstTex = static_cast<GrGLTexture*>(src->asTexture());
3637 SkASSERT(dstTex);
3638 SkASSERT(!drawToMultisampleFBO);
3639 if (!this->glCaps().isFormatRenderable(dstTex->format(), 1)) {
3640 return false;
3641 }
3642 this->bindSurfaceFBOForPixelOps(dst, 0, GR_GL_FRAMEBUFFER, kDst_TempFBOTarget);
3643 fHWBoundRenderTargetUniqueID.makeInvalid();
3644 }
3645 int progIdx = TextureToCopyProgramIdx(srcTex);
3646 if (!fCopyPrograms[progIdx].fProgram) {
3647 if (!this->createCopyProgram(srcTex)) {
3648 SkDebugf("Failed to create copy program.\n");
3649 return false;
3650 }
3651 }
3652 this->flushViewport(SkIRect::MakeSize(dst->dimensions()),
3653 dst->height(),
3654 kTopLeft_GrSurfaceOrigin); // the origin is irrelevant in this case
3655 this->flushProgram(fCopyPrograms[progIdx].fProgram);
3656 fHWVertexArrayState.setVertexArrayID(this, 0);
3657 GrGLAttribArrayState* attribs = fHWVertexArrayState.bindInternalVertexArray(this);
3658 attribs->enableVertexArrays(this, 1);
3659 attribs->set(this, 0, fCopyProgramArrayBuffer.get(), kFloat2_GrVertexAttribType,
3660 SkSLType::kFloat2, 2 * sizeof(GrGLfloat), 0);
3661 // dst rect edges in NDC (-1 to 1)
3662 int dw = dst->width();
3663 int dh = dst->height();
3664 GrGLfloat dx0 = 2.f * dstRect.fLeft / dw - 1.f;
3665 GrGLfloat dx1 = 2.f * dstRect.fRight / dw - 1.f;
3666 GrGLfloat dy0 = 2.f * dstRect.fTop / dh - 1.f;
3667 GrGLfloat dy1 = 2.f * dstRect.fBottom / dh - 1.f;
3668 GrGLfloat sx0 = (GrGLfloat)srcRect.fLeft;
3669 GrGLfloat sx1 = (GrGLfloat)(srcRect.fRight);
3670 GrGLfloat sy0 = (GrGLfloat)srcRect.fTop;
3671 GrGLfloat sy1 = (GrGLfloat)(srcRect.fBottom);
3672 int sw = src->width();
3673 int sh = src->height();
3674 if (srcTex->textureType() != GrTextureType::kRectangle) {
3675 // src rect edges in normalized texture space (0 to 1)
3676 sx0 /= sw;
3677 sx1 /= sw;
3678 sy0 /= sh;
3679 sy1 /= sh;
3680 }
3681 GL_CALL(Uniform4f(fCopyPrograms[progIdx].fPosXformUniform, dx1 - dx0, dy1 - dy0, dx0, dy0));
3682 GL_CALL(Uniform4f(fCopyPrograms[progIdx].fTexCoordXformUniform,
3683 sx1 - sx0, sy1 - sy0, sx0, sy0));
3684 GL_CALL(Uniform1i(fCopyPrograms[progIdx].fTextureUniform, 0));
3685 this->flushBlendAndColorWrite(skgpu::BlendInfo(), skgpu::Swizzle::RGBA());
3686 this->flushConservativeRasterState(false);
3687 this->flushWireframeState(false);
3688 this->flushScissorTest(GrScissorTest::kDisabled);
3689 this->disableWindowRectangles();
3690 this->disableStencil();
3691 if (this->glCaps().srgbWriteControl()) {
3692 this->flushFramebufferSRGB(true);
3693 }
3694 GL_CALL(DrawArrays(GR_GL_TRIANGLE_STRIP, 0, 4));
3695 this->unbindSurfaceFBOForPixelOps(dst, 0, GR_GL_FRAMEBUFFER);
3696 // The rect is already in device space so we pass in kTopLeft so no flip is done.
3697 this->didWriteToSurface(dst, kTopLeft_GrSurfaceOrigin, &dstRect);
3698 return true;
3699 }
3700
3701 void GrGLGpu::copySurfaceAsCopyTexSubImage(GrSurface* dst, GrSurface* src, const SkIRect& srcRect,
3702 const SkIPoint& dstPoint) {
3703 SkASSERT(can_copy_texsubimage(dst, src, this->glCaps()));
3704 this->bindSurfaceFBOForPixelOps(src, 0, GR_GL_FRAMEBUFFER, kSrc_TempFBOTarget);
3705 GrGLTexture* dstTex = static_cast<GrGLTexture *>(dst->asTexture());
3706 SkASSERT(dstTex);
3707 // We modified the bound FBO
3708 fHWBoundRenderTargetUniqueID.makeInvalid();
3709
3710 this->bindTextureToScratchUnit(dstTex->target(), dstTex->textureID());
3711 GL_CALL(CopyTexSubImage2D(dstTex->target(), 0,
3712 dstPoint.fX, dstPoint.fY,
3713 srcRect.fLeft, srcRect.fTop,
3714 srcRect.width(), srcRect.height()));
3715 this->unbindSurfaceFBOForPixelOps(src, 0, GR_GL_FRAMEBUFFER);
3716 SkIRect dstRect = SkIRect::MakeXYWH(dstPoint.fX, dstPoint.fY,
3717 srcRect.width(), srcRect.height());
3718 // The rect is already in device space so we pass in kTopLeft so no flip is done.
3719 this->didWriteToSurface(dst, kTopLeft_GrSurfaceOrigin, &dstRect);
3720 }
3721
3722 bool GrGLGpu::copySurfaceAsBlitFramebuffer(GrSurface* dst, GrSurface* src, const SkIRect& srcRect,
3723 const SkIRect& dstRect, GrSamplerState::Filter filter) {
3724 SkASSERT(can_blit_framebuffer_for_copy_surface(dst, src, srcRect, dstRect, this->glCaps()));
3725 if (dst == src) {
3726 if (SkIRect::Intersects(dstRect, srcRect)) {
3727 return false;
3728 }
3729 }
3730
3731 this->bindSurfaceFBOForPixelOps(dst, 0, GR_GL_DRAW_FRAMEBUFFER, kDst_TempFBOTarget);
3732 this->bindSurfaceFBOForPixelOps(src, 0, GR_GL_READ_FRAMEBUFFER, kSrc_TempFBOTarget);
3733 // We modified the bound FBO
3734 fHWBoundRenderTargetUniqueID.makeInvalid();
3735
3736 // BlitFrameBuffer respects the scissor, so disable it.
3737 this->flushScissorTest(GrScissorTest::kDisabled);
3738 this->disableWindowRectangles();
3739
3740 GL_CALL(BlitFramebuffer(srcRect.fLeft,
3741 srcRect.fTop,
3742 srcRect.fRight,
3743 srcRect.fBottom,
3744 dstRect.fLeft,
3745 dstRect.fTop,
3746 dstRect.fRight,
3747 dstRect.fBottom,
3748 GR_GL_COLOR_BUFFER_BIT,
3749 filter_to_gl_mag_filter(filter)));
3750 this->unbindSurfaceFBOForPixelOps(dst, 0, GR_GL_DRAW_FRAMEBUFFER);
3751 this->unbindSurfaceFBOForPixelOps(src, 0, GR_GL_READ_FRAMEBUFFER);
3752
3753 // The rect is already in device space so we pass in kTopLeft so no flip is done.
3754 this->didWriteToSurface(dst, kTopLeft_GrSurfaceOrigin, &dstRect);
3755 return true;
3756 }
3757
3758 bool GrGLGpu::onRegenerateMipMapLevels(GrTexture* texture) {
3759 using RegenerateMipmapType = GrGLCaps::RegenerateMipmapType;
3760
3761 auto glTex = static_cast<GrGLTexture*>(texture);
3762 // Mipmaps are only supported on 2D textures:
3763 if (GR_GL_TEXTURE_2D != glTex->target()) {
3764 return false;
3765 }
3766 GrGLFormat format = glTex->format();
3767 // Manual implementation of mipmap generation, to work around driver bugs w/sRGB.
3768 // Uses draw calls to do a series of downsample operations to successive mips.
3769
3770 // The manual approach requires the ability to limit which level we're sampling and that the
3771 // destination can be bound to a FBO:
3772 if (!this->glCaps().doManualMipmapping() || !this->glCaps().isFormatRenderable(format, 1)) {
3773 GrGLenum target = glTex->target();
3774 this->bindTextureToScratchUnit(target, glTex->textureID());
3775 GL_CALL(GenerateMipmap(glTex->target()));
3776 return true;
3777 }
3778
3779 int width = texture->width();
3780 int height = texture->height();
3781 int levelCount = SkMipmap::ComputeLevelCount(width, height) + 1;
3782 SkASSERT(levelCount == texture->maxMipmapLevel() + 1);
3783
3784 // Create (if necessary), then bind temporary FBO:
3785 if (0 == fTempDstFBOID) {
3786 GL_CALL(GenFramebuffers(1, &fTempDstFBOID));
3787 }
3788 this->bindFramebuffer(GR_GL_FRAMEBUFFER, fTempDstFBOID);
3789 fHWBoundRenderTargetUniqueID.makeInvalid();
3790
3791 // Bind the texture, to get things configured for filtering.
3792 // We'll be changing our base level and max level further below:
3793 this->setTextureUnit(0);
3794 // The mipmap program does not do any swizzling.
3795 this->bindTexture(0, GrSamplerState::Filter::kLinear, skgpu::Swizzle::RGBA(), glTex);
3796
3797 // Vertex data:
3798 if (!fMipmapProgramArrayBuffer) {
3799 static const GrGLfloat vdata[] = {
3800 0, 0,
3801 0, 1,
3802 1, 0,
3803 1, 1
3804 };
3805 fMipmapProgramArrayBuffer = GrGLBuffer::Make(this,
3806 sizeof(vdata),
3807 GrGpuBufferType::kVertex,
3808 kStatic_GrAccessPattern);
3809 fMipmapProgramArrayBuffer->updateData(vdata, /*offset=*/0,
3810
3811 sizeof(vdata),
3812 /*preserve=*/false);
3813 }
3814 if (!fMipmapProgramArrayBuffer) {
3815 return false;
3816 }
3817
3818 fHWVertexArrayState.setVertexArrayID(this, 0);
3819
3820 GrGLAttribArrayState* attribs = fHWVertexArrayState.bindInternalVertexArray(this);
3821 attribs->enableVertexArrays(this, 1);
3822 attribs->set(this, 0, fMipmapProgramArrayBuffer.get(), kFloat2_GrVertexAttribType,
3823 SkSLType::kFloat2, 2 * sizeof(GrGLfloat), 0);
3824
3825 // Set "simple" state once:
3826 this->flushBlendAndColorWrite(skgpu::BlendInfo(), skgpu::Swizzle::RGBA());
3827 this->flushScissorTest(GrScissorTest::kDisabled);
3828 this->disableWindowRectangles();
3829 this->disableStencil();
3830
3831 // Do all the blits:
3832 width = texture->width();
3833 height = texture->height();
3834
3835 std::unique_ptr<GrSemaphore> semaphore;
3836 for (GrGLint level = 1; level < levelCount; ++level) {
3837 // Get and bind the program for this particular downsample (filter shape can vary):
3838 int progIdx = TextureSizeToMipmapProgramIdx(width, height);
3839 if (!fMipmapPrograms[progIdx].fProgram) {
3840 if (!this->createMipmapProgram(progIdx)) {
3841 SkDebugf("Failed to create mipmap program.\n");
3842 // Invalidate all params to cover base and max level change in a previous iteration.
3843 glTex->textureParamsModified();
3844 return false;
3845 }
3846 }
3847 this->flushProgram(fMipmapPrograms[progIdx].fProgram);
3848
3849 if (this->glCaps().regenerateMipmapType() == RegenerateMipmapType::kBasePlusSync &&
3850 level > 1) {
3851 this->waitSemaphore(semaphore.get());
3852 semaphore.reset();
3853 }
3854
3855 // Texcoord uniform is expected to contain (1/w, (w-1)/w, 1/h, (h-1)/h)
3856 const float invWidth = 1.0f / width;
3857 const float invHeight = 1.0f / height;
3858 GL_CALL(Uniform4f(fMipmapPrograms[progIdx].fTexCoordXformUniform,
3859 invWidth, (width - 1) * invWidth, invHeight, (height - 1) * invHeight));
3860 GL_CALL(Uniform1i(fMipmapPrograms[progIdx].fTextureUniform, 0));
3861
3862 // Set the base level so that we only sample from the previous mip.
3863 SkASSERT(this->glCaps().mipmapLevelControlSupport());
3864 GL_CALL(TexParameteri(GR_GL_TEXTURE_2D, GR_GL_TEXTURE_BASE_LEVEL, level - 1));
3865 // Setting the max level is technically unnecessary and can affect
3866 // validation for the framebuffer. However, by making it clear that a
3867 // rendering feedback loop is not occurring, we avoid hitting a slow
3868 // path on some drivers.
3869 if (this->glCaps().regenerateMipmapType() == RegenerateMipmapType::kBasePlusMaxLevel) {
3870 GL_CALL(TexParameteri(GR_GL_TEXTURE_2D, GR_GL_TEXTURE_MAX_LEVEL, level - 1));
3871 }
3872
3873 GL_CALL(FramebufferTexture2D(GR_GL_FRAMEBUFFER, GR_GL_COLOR_ATTACHMENT0, GR_GL_TEXTURE_2D,
3874 glTex->textureID(), level));
3875
3876 width = std::max(1, width / 2);
3877 height = std::max(1, height / 2);
3878 this->flushViewport(SkIRect::MakeWH(width, height), height, kTopLeft_GrSurfaceOrigin);
3879
3880 GL_CALL(DrawArrays(GR_GL_TRIANGLE_STRIP, 0, 4));
3881
3882 if (this->glCaps().regenerateMipmapType() == RegenerateMipmapType::kBasePlusSync &&
3883 level < levelCount-1) {
3884 semaphore = this->makeSemaphore(true);
3885 this->insertSemaphore(semaphore.get());
3886 }
3887 }
3888
3889 // Unbind:
3890 GL_CALL(FramebufferTexture2D(GR_GL_FRAMEBUFFER, GR_GL_COLOR_ATTACHMENT0,
3891 GR_GL_TEXTURE_2D, 0, 0));
3892
3893 // We modified the base level and max level params.
3894 GrGLTextureParameters::NonsamplerState nonsamplerState = glTex->parameters()->nonsamplerState();
3895 // We drew the 2nd to last level into the last level.
3896 nonsamplerState.fBaseMipMapLevel = levelCount - 2;
3897 if (this->glCaps().regenerateMipmapType() == RegenerateMipmapType::kBasePlusMaxLevel) {
3898 nonsamplerState.fMaxMipmapLevel = levelCount - 2;
3899 }
3900 glTex->parameters()->set(nullptr, nonsamplerState, fResetTimestampForTextureParameters);
3901
3902 return true;
3903 }
3904
3905 void GrGLGpu::xferBarrier(GrRenderTarget* rt, GrXferBarrierType type) {
3906 SkASSERT(type);
3907 switch (type) {
3908 case kTexture_GrXferBarrierType: {
3909 GrGLRenderTarget* glrt = static_cast<GrGLRenderTarget*>(rt);
3910 SkASSERT(glrt->asTexture());
3911 SkASSERT(!glrt->isFBO0(false/*multisample*/));
3912 if (glrt->requiresManualMSAAResolve()) {
3913 // The render target uses separate storage so no need for glTextureBarrier.
3914 // FIXME: The render target will resolve automatically when its texture is bound,
3915 // but we could resolve only the bounds that will be read if we do it here instead.
3916 return;
3917 }
3918 SkASSERT(this->caps()->textureBarrierSupport());
3919 GL_CALL(TextureBarrier());
3920 return;
3921 }
3922 case kBlend_GrXferBarrierType:
3923 SkASSERT(GrCaps::kAdvanced_BlendEquationSupport ==
3924 this->caps()->blendEquationSupport());
3925 GL_CALL(BlendBarrier());
3926 return;
3927 default: break; // placate compiler warnings that kNone not handled
3928 }
3929 }
3930
3931 GrBackendTexture GrGLGpu::onCreateBackendTexture(SkISize dimensions,
3932 const GrBackendFormat& format,
3933 GrRenderable renderable,
3934 skgpu::Mipmapped mipmapped,
3935 GrProtected isProtected,
3936 std::string_view label) {
3937 this->handleDirtyContext();
3938
3939 if (isProtected == GrProtected::kYes && !this->glCaps().supportsProtectedContent()) {
3940 return {};
3941 }
3942
3943 GrGLFormat glFormat = GrBackendFormats::AsGLFormat(format);
3944 if (glFormat == GrGLFormat::kUnknown) {
3945 return {};
3946 }
3947
3948 int numMipLevels = 1;
3949 if (mipmapped == skgpu::Mipmapped::kYes) {
3950 numMipLevels = SkMipmap::ComputeLevelCount(dimensions) + 1;
3951 }
3952
3953 // Compressed formats go through onCreateCompressedBackendTexture
3954 SkASSERT(!GrGLFormatIsCompressed(glFormat));
3955
3956 GrGLTextureInfo info;
3957 GrGLTextureParameters::SamplerOverriddenState initialState;
3958
3959 if (glFormat == GrGLFormat::kUnknown) {
3960 return {};
3961 }
3962 switch (format.textureType()) {
3963 case GrTextureType::kNone:
3964 case GrTextureType::kExternal:
3965 return {};
3966 case GrTextureType::k2D:
3967 info.fTarget = GR_GL_TEXTURE_2D;
3968 break;
3969 case GrTextureType::kRectangle:
3970 if (!this->glCaps().rectangleTextureSupport() || mipmapped == skgpu::Mipmapped::kYes) {
3971 return {};
3972 }
3973 info.fTarget = GR_GL_TEXTURE_RECTANGLE;
3974 break;
3975 }
3976 info.fProtected = skgpu::Protected(isProtected == skgpu::Protected::kYes ||
3977 this->glCaps().strictProtectedness());
3978 info.fFormat = GrGLFormatToEnum(glFormat);
3979 info.fID = this->createTexture(dimensions, glFormat, info.fTarget, renderable, &initialState,
3980 numMipLevels, info.fProtected, label);
3981 if (!info.fID) {
3982 return {};
3983 }
3984
3985 // Unbind this texture from the scratch texture unit.
3986 this->bindTextureToScratchUnit(info.fTarget, 0);
3987
3988 auto parameters = sk_make_sp<GrGLTextureParameters>();
3989 // The non-sampler params are still at their default values.
3990 parameters->set(&initialState, GrGLTextureParameters::NonsamplerState(),
3991 fResetTimestampForTextureParameters);
3992
3993 return GrBackendTextures::MakeGL(
3994 dimensions.width(), dimensions.height(), mipmapped, info, std::move(parameters), label);
3995 }
3996
3997 bool GrGLGpu::onClearBackendTexture(const GrBackendTexture& backendTexture,
3998 sk_sp<skgpu::RefCntedCallback> finishedCallback,
3999 std::array<float, 4> color) {
4000 this->handleDirtyContext();
4001
4002 GrGLTextureInfo info;
4003 SkAssertResult(GrBackendTextures::GetGLTextureInfo(backendTexture, &info));
4004
4005 int numMipLevels = 1;
4006 if (backendTexture.hasMipmaps()) {
4007 numMipLevels =
4008 SkMipmap::ComputeLevelCount(backendTexture.width(), backendTexture.height()) + 1;
4009 }
4010
4011 GrGLFormat glFormat = GrGLFormatFromGLEnum(info.fFormat);
4012
4013 this->bindTextureToScratchUnit(info.fTarget, info.fID);
4014
4015 // If we have mips make sure the base level is set to 0 and the max level set to numMipLevels-1
4016 // so that the uploads go to the right levels.
4017 if (numMipLevels && this->glCaps().mipmapLevelControlSupport()) {
4018 auto params = get_gl_texture_params(backendTexture);
4019 GrGLTextureParameters::NonsamplerState nonsamplerState = params->nonsamplerState();
4020 if (params->nonsamplerState().fBaseMipMapLevel != 0) {
4021 GL_CALL(TexParameteri(info.fTarget, GR_GL_TEXTURE_BASE_LEVEL, 0));
4022 nonsamplerState.fBaseMipMapLevel = 0;
4023 }
4024 if (params->nonsamplerState().fMaxMipmapLevel != (numMipLevels - 1)) {
4025 GL_CALL(TexParameteri(info.fTarget, GR_GL_TEXTURE_MAX_LEVEL, numMipLevels - 1));
4026 nonsamplerState.fBaseMipMapLevel = numMipLevels - 1;
4027 }
4028 params->set(nullptr, nonsamplerState, fResetTimestampForTextureParameters);
4029 }
4030
4031 uint32_t levelMask = (1 << numMipLevels) - 1;
4032 bool result = this->uploadColorToTex(glFormat,
4033 backendTexture.dimensions(),
4034 info.fTarget,
4035 color,
4036 levelMask);
4037
4038 // Unbind this texture from the scratch texture unit.
4039 this->bindTextureToScratchUnit(info.fTarget, 0);
4040 return result;
4041 }
4042
4043 void GrGLGpu::deleteBackendTexture(const GrBackendTexture& tex) {
4044 SkASSERT(GrBackendApi::kOpenGL == tex.backend());
4045
4046 GrGLTextureInfo info;
4047 if (GrBackendTextures::GetGLTextureInfo(tex, &info)) {
4048 GL_CALL(DeleteTextures(1, &info.fID));
4049 }
4050 }
4051
4052 bool GrGLGpu::compile(const GrProgramDesc& desc, const GrProgramInfo& programInfo) {
4053 GrThreadSafePipelineBuilder::Stats::ProgramCacheResult stat;
4054
4055 sk_sp<GrGLProgram> tmp = fProgramCache->findOrCreateProgram(this->getContext(),
4056 desc, programInfo, &stat);
4057 if (!tmp) {
4058 return false;
4059 }
4060
4061 return stat != GrThreadSafePipelineBuilder::Stats::ProgramCacheResult::kHit;
4062 }
4063
4064 #if defined(GPU_TEST_UTILS)
4065
4066 bool GrGLGpu::isTestingOnlyBackendTexture(const GrBackendTexture& tex) const {
4067 SkASSERT(GrBackendApi::kOpenGL == tex.backend());
4068
4069 GrGLTextureInfo info;
4070 if (!GrBackendTextures::GetGLTextureInfo(tex, &info)) {
4071 return false;
4072 }
4073
4074 GrGLboolean result;
4075 GL_CALL_RET(result, IsTexture(info.fID));
4076
4077 return (GR_GL_TRUE == result);
4078 }
4079
4080 GrBackendRenderTarget GrGLGpu::createTestingOnlyBackendRenderTarget(SkISize dimensions,
4081 GrColorType colorType,
4082 int sampleCnt,
4083 GrProtected isProtected) {
4084 if (dimensions.width() > this->caps()->maxRenderTargetSize() ||
4085 dimensions.height() > this->caps()->maxRenderTargetSize()) {
4086 return {};
4087 }
4088 if (isProtected == GrProtected::kYes && !this->glCaps().supportsProtectedContent()) {
4089 return {};
4090 }
4091
4092 this->handleDirtyContext();
4093 auto format = this->glCaps().getFormatFromColorType(colorType);
4094 sampleCnt = this->glCaps().getRenderTargetSampleCount(sampleCnt, format);
4095 if (!sampleCnt) {
4096 return {};
4097 }
4098 // We make a texture instead of a render target if we're using a
4099 // "multisampled_render_to_texture" style extension or have a BGRA format that
4100 // is allowed for textures but not render buffer internal formats.
4101 bool useTexture = false;
4102 if (sampleCnt > 1 && !this->glCaps().usesMSAARenderBuffers()) {
4103 useTexture = true;
4104 } else if (format == GrGLFormat::kBGRA8 &&
4105 this->glCaps().getRenderbufferInternalFormat(GrGLFormat::kBGRA8) != GR_GL_BGRA8) {
4106 // We have a BGRA extension that doesn't support BGRA render buffers. We can use a texture
4107 // unless we've been asked for MSAA. Note we already checked above for render-to-
4108 // multisampled-texture style extensions.
4109 if (sampleCnt > 1) {
4110 return {};
4111 }
4112 useTexture = true;
4113 }
4114
4115 bool avoidStencil = this->glCaps().avoidStencilBuffers();
4116 int sFormatIdx = -1;
4117 if (!avoidStencil) {
4118 sFormatIdx = this->getCompatibleStencilIndex(format);
4119 if (sFormatIdx < 0) {
4120 return {};
4121 }
4122 }
4123 GrGLuint colorID = 0;
4124 GrGLuint stencilID = 0;
4125 GrGLFramebufferInfo info;
4126 info.fFBOID = 0;
4127 info.fFormat = GrGLFormatToEnum(format);
4128 info.fProtected = skgpu::Protected(isProtected == skgpu::Protected::kYes ||
4129 this->glCaps().strictProtectedness());
4130
4131 auto deleteIDs = [&](bool saveFBO = false) {
4132 if (colorID) {
4133 if (useTexture) {
4134 GL_CALL(DeleteTextures(1, &colorID));
4135 } else {
4136 GL_CALL(DeleteRenderbuffers(1, &colorID));
4137 }
4138 }
4139 if (stencilID) {
4140 GL_CALL(DeleteRenderbuffers(1, &stencilID));
4141 }
4142 if (!saveFBO && info.fFBOID) {
4143 this->deleteFramebuffer(info.fFBOID);
4144 }
4145 };
4146
4147 if (useTexture) {
4148 GL_CALL(GenTextures(1, &colorID));
4149 } else {
4150 GL_CALL(GenRenderbuffers(1, &colorID));
4151 }
4152 if (!colorID) {
4153 deleteIDs();
4154 return {};
4155 }
4156
4157 if (!avoidStencil) {
4158 GL_CALL(GenRenderbuffers(1, &stencilID));
4159 if (!stencilID) {
4160 deleteIDs();
4161 return {};
4162 }
4163 }
4164
4165 GL_CALL(GenFramebuffers(1, &info.fFBOID));
4166 if (!info.fFBOID) {
4167 deleteIDs();
4168 return {};
4169 }
4170
4171 this->invalidateBoundRenderTarget();
4172
4173 this->bindFramebuffer(GR_GL_FRAMEBUFFER, info.fFBOID);
4174 if (useTexture) {
4175 GrGLTextureParameters::SamplerOverriddenState initialState;
4176 colorID = this->createTexture(dimensions, format, GR_GL_TEXTURE_2D, GrRenderable::kYes,
4177 &initialState,
4178 1,
4179 info.fProtected,
4180 /*label=*/"Skia");
4181 if (!colorID) {
4182 deleteIDs();
4183 return {};
4184 }
4185 if (sampleCnt == 1) {
4186 GL_CALL(FramebufferTexture2D(GR_GL_FRAMEBUFFER, GR_GL_COLOR_ATTACHMENT0,
4187 GR_GL_TEXTURE_2D, colorID, 0));
4188 } else {
4189 GL_CALL(FramebufferTexture2DMultisample(GR_GL_FRAMEBUFFER, GR_GL_COLOR_ATTACHMENT0,
4190 GR_GL_TEXTURE_2D, colorID, 0, sampleCnt));
4191 }
4192 } else {
4193 GrGLenum renderBufferFormat = this->glCaps().getRenderbufferInternalFormat(format);
4194 GL_CALL(BindRenderbuffer(GR_GL_RENDERBUFFER, colorID));
4195 if (sampleCnt == 1) {
4196 GL_CALL(RenderbufferStorage(GR_GL_RENDERBUFFER, renderBufferFormat, dimensions.width(),
4197 dimensions.height()));
4198 } else {
4199 if (!this->renderbufferStorageMSAA(this->glContext(), sampleCnt, renderBufferFormat,
4200 dimensions.width(), dimensions.height())) {
4201 deleteIDs();
4202 return {};
4203 }
4204 }
4205 GL_CALL(FramebufferRenderbuffer(GR_GL_FRAMEBUFFER, GR_GL_COLOR_ATTACHMENT0,
4206 GR_GL_RENDERBUFFER, colorID));
4207 }
4208 if (!avoidStencil) {
4209 GL_CALL(BindRenderbuffer(GR_GL_RENDERBUFFER, stencilID));
4210 auto stencilBufferFormat = this->glCaps().stencilFormats()[sFormatIdx];
4211 if (sampleCnt == 1) {
4212 GL_CALL(RenderbufferStorage(GR_GL_RENDERBUFFER, GrGLFormatToEnum(stencilBufferFormat),
4213 dimensions.width(), dimensions.height()));
4214 } else {
4215 if (!this->renderbufferStorageMSAA(this->glContext(), sampleCnt,
4216 GrGLFormatToEnum(stencilBufferFormat),
4217 dimensions.width(), dimensions.height())) {
4218 deleteIDs();
4219 return {};
4220 }
4221 }
4222 GL_CALL(FramebufferRenderbuffer(GR_GL_FRAMEBUFFER,
4223 GR_GL_STENCIL_ATTACHMENT,
4224 GR_GL_RENDERBUFFER,
4225 stencilID));
4226 if (GrGLFormatIsPackedDepthStencil(this->glCaps().stencilFormats()[sFormatIdx])) {
4227 GL_CALL(FramebufferRenderbuffer(GR_GL_FRAMEBUFFER, GR_GL_DEPTH_ATTACHMENT,
4228 GR_GL_RENDERBUFFER, stencilID));
4229 }
4230 }
4231
4232 // We don't want to have to recover the renderbuffer/texture IDs later to delete them. OpenGL
4233 // has this rule that if a renderbuffer/texture is deleted and a FBO other than the current FBO
4234 // has the RB attached then deletion is delayed. So we unbind the FBO here and delete the
4235 // renderbuffers/texture.
4236 this->bindFramebuffer(GR_GL_FRAMEBUFFER, 0);
4237 deleteIDs(/* saveFBO = */ true);
4238
4239 this->bindFramebuffer(GR_GL_FRAMEBUFFER, info.fFBOID);
4240 GrGLenum status;
4241 GL_CALL_RET(status, CheckFramebufferStatus(GR_GL_FRAMEBUFFER));
4242 if (GR_GL_FRAMEBUFFER_COMPLETE != status) {
4243 this->deleteFramebuffer(info.fFBOID);
4244 return {};
4245 }
4246
4247 int stencilBits = 0;
4248 if (!avoidStencil) {
4249 stencilBits = SkToInt(GrGLFormatStencilBits(this->glCaps().stencilFormats()[sFormatIdx]));
4250 }
4251
4252 GrBackendRenderTarget beRT = GrBackendRenderTargets::MakeGL(
4253 dimensions.width(), dimensions.height(), sampleCnt, stencilBits, info);
4254 SkASSERT(this->caps()->areColorTypeAndFormatCompatible(colorType, beRT.getBackendFormat()));
4255 return beRT;
4256 }
4257
4258 void GrGLGpu::deleteTestingOnlyBackendRenderTarget(const GrBackendRenderTarget& backendRT) {
4259 SkASSERT(GrBackendApi::kOpenGL == backendRT.backend());
4260 GrGLFramebufferInfo info;
4261 if (GrBackendRenderTargets::GetGLFramebufferInfo(backendRT, &info)) {
4262 if (info.fFBOID) {
4263 this->deleteFramebuffer(info.fFBOID);
4264 }
4265 }
4266 }
4267 #endif
4268
4269 ///////////////////////////////////////////////////////////////////////////////
4270
4271 GrGLAttribArrayState* GrGLGpu::HWVertexArrayState::bindInternalVertexArray(GrGLGpu* gpu,
4272 const GrBuffer* ibuf) {
4273 SkASSERT(!ibuf || ibuf->isCpuBuffer() || !static_cast<const GrGpuBuffer*>(ibuf)->isMapped());
4274 GrGLAttribArrayState* attribState;
4275
4276 if (gpu->glCaps().isCoreProfile()) {
4277 if (!fCoreProfileVertexArray) {
4278 GrGLuint arrayID;
4279 GR_GL_CALL(gpu->glInterface(), GenVertexArrays(1, &arrayID));
4280 int attrCount = gpu->glCaps().maxVertexAttributes();
4281 fCoreProfileVertexArray = new GrGLVertexArray(arrayID, attrCount);
4282 }
4283 if (ibuf) {
4284 attribState = fCoreProfileVertexArray->bindWithIndexBuffer(gpu, ibuf);
4285 } else {
4286 attribState = fCoreProfileVertexArray->bind(gpu);
4287 }
4288 } else {
4289 if (ibuf) {
4290 // bindBuffer implicitly binds VAO 0 when binding an index buffer.
4291 gpu->bindBuffer(GrGpuBufferType::kIndex, ibuf);
4292 } else {
4293 this->setVertexArrayID(gpu, 0);
4294 }
4295 int attrCount = gpu->glCaps().maxVertexAttributes();
4296 if (fDefaultVertexArrayAttribState.count() != attrCount) {
4297 fDefaultVertexArrayAttribState.resize(attrCount);
4298 }
4299 attribState = &fDefaultVertexArrayAttribState;
4300 }
4301 return attribState;
4302 }
4303
4304 void GrGLGpu::addFinishedCallback(skgpu::AutoCallback callback,
4305 std::optional<GrTimerQuery> timerQuery) {
4306 GrGLint glQuery = timerQuery ? static_cast<GrGLint>(timerQuery->query) : 0;
4307 fFinishCallbacks.add(std::move(callback), glQuery);
4308 }
4309
4310 void GrGLGpu::flush(FlushType flushType) {
4311 if (fNeedsGLFlush || flushType == FlushType::kForce) {
4312 GL_CALL(Flush());
4313 fNeedsGLFlush = false;
4314 }
4315 }
4316
4317 void GrGLGpu::prepareSurfacesForBackendAccessAndStateUpdates(
4318 SkSpan<GrSurfaceProxy*> proxies,
4319 SkSurfaces::BackendSurfaceAccess access,
4320 const skgpu::MutableTextureState* newState) {
4321 // For reasons not fully understood, some platforms require binding to framebuffer 0 when
4322 // presenting to a display; see skbug.com/398631003.
4323 SkASSERT(!newState);
4324 if (proxies.size() == 1 && proxies[0]->asRenderTargetProxy() &&
4325 proxies[0]->asRenderTargetProxy()->glRTFBOIDIs0() &&
4326 access == SkSurfaces::BackendSurfaceAccess::kPresent &&
4327 this->glCaps().bindDefaultFramebufferOnPresent()) {
4328 this->bindFramebuffer(GR_GL_DRAW_FRAMEBUFFER, 0);
4329 }
4330 }
4331
4332 bool GrGLGpu::onSubmitToGpu(const GrSubmitInfo& info) {
4333 if (info.fSync == GrSyncCpu::kYes ||
4334 (!fFinishCallbacks.empty() && !this->glCaps().fenceSyncSupport())) {
4335 this->finishOutstandingGpuWork();
4336 fFinishCallbacks.callAll(true);
4337 } else {
4338 this->flush();
4339 // See if any previously inserted finish procs are good to go.
4340 fFinishCallbacks.check();
4341 }
4342 if (!this->glCaps().skipErrorChecks()) {
4343 this->clearErrorsAndCheckForOOM();
4344 }
4345 return true;
4346 }
4347
4348 void GrGLGpu::willExecute() {
4349 // Because our transfers will be submitted to GL to perfom immediately (no command buffer to
4350 // submit), we must unmap any staging buffers.
4351 if (fStagingBufferManager) {
4352 fStagingBufferManager->detachBuffers();
4353 }
4354 }
4355
4356 void GrGLGpu::submit(GrOpsRenderPass* renderPass) {
4357 // The GrGLOpsRenderPass doesn't buffer ops so there is nothing to do here
4358 SkASSERT(fCachedOpsRenderPass.get() == renderPass);
4359 fCachedOpsRenderPass->reset();
4360 }
4361
4362 [[nodiscard]] GrGLsync GrGLGpu::insertSync() {
4363 GrGLsync sync = nullptr;
4364 switch (this->glCaps().fenceType()) {
4365 case GrGLCaps::FenceType::kNone:
4366 return nullptr;
4367 case GrGLCaps::FenceType::kNVFence: {
4368 static_assert(sizeof(GrGLsync) >= sizeof(GrGLuint));
4369 GrGLuint fence = 0;
4370 GL_CALL(GenFences(1, &fence));
4371 GL_CALL(SetFence(fence, GR_GL_ALL_COMPLETED));
4372 sync = reinterpret_cast<GrGLsync>(static_cast<intptr_t>(fence));
4373 break;
4374 }
4375 case GrGLCaps::FenceType::kSyncObject: {
4376 GL_CALL_RET(sync, FenceSync(GR_GL_SYNC_GPU_COMMANDS_COMPLETE, 0));
4377 break;
4378 }
4379 }
4380 this->setNeedsFlush();
4381 return sync;
4382 }
4383
4384 bool GrGLGpu::testSync(GrGLsync sync) {
4385 switch (this->glCaps().fenceType()) {
4386 case GrGLCaps::FenceType::kNone:
4387 SK_ABORT("Testing sync without sync support.");
4388 return false;
4389 case GrGLCaps::FenceType::kNVFence: {
4390 GrGLuint nvFence = static_cast<GrGLuint>(reinterpret_cast<intptr_t>(sync));
4391 GrGLboolean result;
4392 GL_CALL_RET(result, TestFence(nvFence));
4393 return result == GR_GL_TRUE;
4394 }
4395 case GrGLCaps::FenceType::kSyncObject: {
4396 constexpr GrGLbitfield kFlags = 0;
4397 GrGLenum result;
4398 #if defined(__EMSCRIPTEN__) && __EMSCRIPTEN_major__ < 5
4399 GL_CALL_RET(result, ClientWaitSync(sync, kFlags, 0, 0));
4400 #else
4401 GL_CALL_RET(result, ClientWaitSync(sync, kFlags, 0));
4402 #endif
4403 return (GR_GL_CONDITION_SATISFIED == result || GR_GL_ALREADY_SIGNALED == result);
4404 }
4405 }
4406 SkUNREACHABLE;
4407 }
4408
4409 void GrGLGpu::deleteSync(GrGLsync sync) {
4410 switch (this->glCaps().fenceType()) {
4411 case GrGLCaps::FenceType::kNone:
4412 SK_ABORT("Deleting sync without sync support.");
4413 break;
4414 case GrGLCaps::FenceType::kNVFence: {
4415 GrGLuint nvFence = SkToUInt(reinterpret_cast<intptr_t>(sync));
4416 GL_CALL(DeleteFences(1, &nvFence));
4417 break;
4418 }
4419 case GrGLCaps::FenceType::kSyncObject:
4420 GL_CALL(DeleteSync(sync));
4421 break;
4422 }
4423 }
4424
4425 [[nodiscard]] std::unique_ptr<GrSemaphore> GrGLGpu::makeSemaphore(bool isOwned) {
4426 SkASSERT(this->caps()->semaphoreSupport());
4427 return GrGLSemaphore::Make(this, isOwned);
4428 }
4429
4430 std::unique_ptr<GrSemaphore> GrGLGpu::wrapBackendSemaphore(const GrBackendSemaphore&,
4431 GrSemaphoreWrapType,
4432 GrWrapOwnership) {
4433 SK_ABORT("Unsupported");
4434 }
4435
4436 void GrGLGpu::insertSemaphore(GrSemaphore* semaphore) {
4437 SkASSERT(semaphore);
4438 GrGLSemaphore* glSem = static_cast<GrGLSemaphore*>(semaphore);
4439
4440 GrGLsync sync;
4441 GL_CALL_RET(sync, FenceSync(GR_GL_SYNC_GPU_COMMANDS_COMPLETE, 0));
4442 glSem->setSync(sync);
4443 this->setNeedsFlush();
4444 }
4445
4446 void GrGLGpu::waitSemaphore(GrSemaphore* semaphore) {
4447 SkASSERT(semaphore);
4448 GrGLSemaphore* glSem = static_cast<GrGLSemaphore*>(semaphore);
4449
4450 #if defined(__EMSCRIPTEN__) && __EMSCRIPTEN_major__ < 5
4451 constexpr auto kLo = SkTo<GrGLuint>(GR_GL_TIMEOUT_IGNORED & 0xFFFFFFFFull);
4452 constexpr auto kHi = SkTo<GrGLuint>(GR_GL_TIMEOUT_IGNORED >> 32);
4453 GL_CALL(WaitSync(glSem->sync(), 0, kLo, kHi));
4454 #else
4455 GL_CALL(WaitSync(glSem->sync(), 0, GR_GL_TIMEOUT_IGNORED));
4456 #endif
4457 }
4458
4459 std::optional<GrTimerQuery> GrGLGpu::startTimerQuery() {
4460 if (glCaps().timerQueryType() == GrGLCaps::TimerQueryType::kNone) {
4461 return {};
4462 }
4463 GrGLuint glQuery;
4464 GL_CALL(GenQueries(1, &glQuery));
4465 if (!glQuery) {
4466 return {};
4467 }
4468 if (glCaps().timerQueryType() == GrGLCaps::TimerQueryType::kDisjoint) {
4469 // Clear the disjoint state
4470 GrGLint _;
4471 GR_GL_GetIntegerv(this->glInterface(), GR_GL_GPU_DISJOINT, &_);
4472 }
4473 GL_CALL(BeginQuery(GR_GL_TIME_ELAPSED, glQuery));
4474 return GrTimerQuery{glQuery};
4475 }
4476
4477 void GrGLGpu::endTimerQuery(const GrTimerQuery& timerQuery) {
4478 SkASSERT(glCaps().timerQueryType() != GrGLCaps::TimerQueryType::kNone);
4479 SkASSERT(SkToUInt(timerQuery.query));
4480 // Since only one query of a particular type can be active at once, glEndQuery doesn't take a
4481 // query parameter.
4482 GL_CALL(EndQuery(GR_GL_TIME_ELAPSED));
4483 }
4484
4485 uint64_t GrGLGpu::getTimerQueryResult(GrGLuint query) {
4486 SkASSERT(glCaps().timerQueryType() != GrGLCaps::TimerQueryType::kNone);
4487 SkASSERT(query);
4488
4489 // Because we only call this after a sync completes the query *should* be available.
4490 GrGLuint available;
4491 GL_CALL(GetQueryObjectuiv(query, GR_GL_QUERY_RESULT_AVAILABLE, &available));
4492 bool getResult = true;
4493 if (!available) {
4494 SkDebugf("GL timer query is not available.\n");
4495 getResult = false;
4496 }
4497
4498 if (glCaps().timerQueryType() == GrGLCaps::TimerQueryType::kDisjoint) {
4499 // Clear the disjoint state
4500 GrGLint disjoint;
4501 GR_GL_GetIntegerv(this->glInterface(), GR_GL_GPU_DISJOINT, &disjoint);
4502 if (disjoint) {
4503 SkDebugf("GL timer query ignored because of disjoint event.\n");
4504 getResult = false;
4505 }
4506 }
4507
4508 uint64_t result = 0;
4509 if (getResult) {
4510 GR_GL_GetQueryObjectui64v(this->glInterface(), query, GR_GL_QUERY_RESULT, &result);
4511 }
4512 GL_CALL(DeleteQueries(1, &query));
4513 return result;
4514 }
4515
4516 void GrGLGpu::checkFinishedCallbacks() {
4517 fFinishCallbacks.check();
4518 }
4519
4520 void GrGLGpu::finishOutstandingGpuWork() {
4521 GL_CALL(Finish());
4522 }
4523
4524 void GrGLGpu::clearErrorsAndCheckForOOM() {
4525 while (this->getErrorAndCheckForOOM() != GR_GL_NO_ERROR) {}
4526 }
4527
4528 GrGLenum GrGLGpu::getErrorAndCheckForOOM() {
4529 #if GR_GL_CHECK_ERROR
4530 if (this->glInterface()->checkAndResetOOMed()) {
4531 this->setOOMed();
4532 }
4533 #endif
4534 GrGLenum error = this->fGLContext->glInterface()->fFunctions.fGetError();
4535 if (error == GR_GL_OUT_OF_MEMORY) {
4536 this->setOOMed();
4537 }
4538 return error;
4539 }
4540
4541 std::unique_ptr<GrSemaphore> GrGLGpu::prepareTextureForCrossContextUsage(GrTexture* texture) {
4542 // Set up a semaphore to be signaled once the data is ready, and flush GL
4543 std::unique_ptr<GrSemaphore> semaphore = this->makeSemaphore(true);
4544 SkASSERT(semaphore);
4545 this->insertSemaphore(semaphore.get());
4546 // We must call flush here to make sure the GrGLsync object gets created and sent to the gpu.
4547 this->flush(FlushType::kForce);
4548
4549 return semaphore;
4550 }
4551
4552 int GrGLGpu::TextureToCopyProgramIdx(GrTexture* texture) {
4553 switch (SkSLCombinedSamplerTypeForTextureType(texture->textureType())) {
4554 case SkSLType::kTexture2DSampler:
4555 return 0;
4556 case SkSLType::kTexture2DRectSampler:
4557 return 1;
4558 case SkSLType::kTextureExternalSampler:
4559 return 2;
4560 default:
4561 SK_ABORT("Unexpected samper type");
4562 }
4563 }
4564
4565 #ifdef SK_ENABLE_DUMP_GPU
4566 #include "src/utils/SkJSONWriter.h"
4567 void GrGLGpu::onDumpJSON(SkJSONWriter* writer) const {
4568 // We are called by the base class, which has already called beginObject(). We choose to nest
4569 // all of our caps information in a named sub-object.
4570 writer->beginObject("GL GPU");
4571
4572 const GrGLubyte* str;
4573 GL_CALL_RET(str, GetString(GR_GL_VERSION));
4574 writer->appendCString("GL_VERSION", (const char*)(str));
4575 GL_CALL_RET(str, GetString(GR_GL_RENDERER));
4576 writer->appendCString("GL_RENDERER", (const char*)(str));
4577 GL_CALL_RET(str, GetString(GR_GL_VENDOR));
4578 writer->appendCString("GL_VENDOR", (const char*)(str));
4579 GL_CALL_RET(str, GetString(GR_GL_SHADING_LANGUAGE_VERSION));
4580 writer->appendCString("GL_SHADING_LANGUAGE_VERSION", (const char*)(str));
4581
4582 writer->appendName("extensions");
4583 glInterface()->fExtensions.dumpJSON(writer);
4584
4585 writer->endObject();
4586 }
4587 #endif