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 "include/core/SkPixmap.h"
9 #include "include/core/SkStrokeRec.h"
10 #include "include/core/SkTypes.h"
11 #include "include/gpu/GrBackendSemaphore.h"
12 #include "include/gpu/GrBackendSurface.h"
13 #include "include/gpu/GrTypes.h"
14 #include "include/private/SkHalf.h"
15 #include "include/private/SkTemplates.h"
16 #include "include/private/SkTo.h"
17 #include "src/core/SkAutoMalloc.h"
18 #include "src/core/SkConvertPixels.h"
19 #include "src/core/SkMakeUnique.h"
20 #include "src/core/SkMipMap.h"
21 #include "src/core/SkTraceEvent.h"
22 #include "src/gpu/GrContextPriv.h"
23 #include "src/gpu/GrCpuBuffer.h"
24 #include "src/gpu/GrDataUtils.h"
25 #include "src/gpu/GrFixedClip.h"
26 #include "src/gpu/GrGpuResourcePriv.h"
27 #include "src/gpu/GrMesh.h"
28 #include "src/gpu/GrPipeline.h"
29 #include "src/gpu/GrProgramInfo.h"
30 #include "src/gpu/GrRenderTargetPriv.h"
31 #include "src/gpu/GrShaderCaps.h"
32 #include "src/gpu/GrSurfaceProxyPriv.h"
33 #include "src/gpu/GrTexturePriv.h"
34 #include "src/gpu/gl/GrGLBuffer.h"
35 #include "src/gpu/gl/GrGLGpu.h"
36 #include "src/gpu/gl/GrGLOpsRenderPass.h"
37 #include "src/gpu/gl/GrGLSemaphore.h"
38 #include "src/gpu/gl/GrGLStencilAttachment.h"
39 #include "src/gpu/gl/GrGLTextureRenderTarget.h"
40 #include "src/gpu/gl/builders/GrGLShaderStringBuilder.h"
41 #include "src/sksl/SkSLCompiler.h"
42
43 #include <cmath>
44
45 #define GL_CALL(X) GR_GL_CALL(this->glInterface(), X)
46 #define GL_CALL_RET(RET, X) GR_GL_CALL_RET(this->glInterface(), RET, X)
47
48 #if GR_GL_CHECK_ALLOC_WITH_GET_ERROR
49 #define CLEAR_ERROR_BEFORE_ALLOC(iface) GrGLClearErr(iface)
50 #define GL_ALLOC_CALL(iface, call) GR_GL_CALL_NOERRCHECK(iface, call)
51 #define CHECK_ALLOC_ERROR(iface) GR_GL_GET_ERROR(iface)
52 #else
53 #define CLEAR_ERROR_BEFORE_ALLOC(iface)
54 #define GL_ALLOC_CALL(iface, call) GR_GL_CALL(iface, call)
55 #define CHECK_ALLOC_ERROR(iface) GR_GL_NO_ERROR
56 #endif
57
58 //#define USE_NSIGHT
59
60 ///////////////////////////////////////////////////////////////////////////////
61
62 static const GrGLenum gXfermodeEquation2Blend[] = {
63 // Basic OpenGL blend equations.
64 GR_GL_FUNC_ADD,
65 GR_GL_FUNC_SUBTRACT,
66 GR_GL_FUNC_REVERSE_SUBTRACT,
67
68 // GL_KHR_blend_equation_advanced.
69 GR_GL_SCREEN,
70 GR_GL_OVERLAY,
71 GR_GL_DARKEN,
72 GR_GL_LIGHTEN,
73 GR_GL_COLORDODGE,
74 GR_GL_COLORBURN,
75 GR_GL_HARDLIGHT,
76 GR_GL_SOFTLIGHT,
77 GR_GL_DIFFERENCE,
78 GR_GL_EXCLUSION,
79 GR_GL_MULTIPLY,
80 GR_GL_HSL_HUE,
81 GR_GL_HSL_SATURATION,
82 GR_GL_HSL_COLOR,
83 GR_GL_HSL_LUMINOSITY,
84
85 // Illegal... needs to map to something.
86 GR_GL_FUNC_ADD,
87 };
88 GR_STATIC_ASSERT(0 == kAdd_GrBlendEquation);
89 GR_STATIC_ASSERT(1 == kSubtract_GrBlendEquation);
90 GR_STATIC_ASSERT(2 == kReverseSubtract_GrBlendEquation);
91 GR_STATIC_ASSERT(3 == kScreen_GrBlendEquation);
92 GR_STATIC_ASSERT(4 == kOverlay_GrBlendEquation);
93 GR_STATIC_ASSERT(5 == kDarken_GrBlendEquation);
94 GR_STATIC_ASSERT(6 == kLighten_GrBlendEquation);
95 GR_STATIC_ASSERT(7 == kColorDodge_GrBlendEquation);
96 GR_STATIC_ASSERT(8 == kColorBurn_GrBlendEquation);
97 GR_STATIC_ASSERT(9 == kHardLight_GrBlendEquation);
98 GR_STATIC_ASSERT(10 == kSoftLight_GrBlendEquation);
99 GR_STATIC_ASSERT(11 == kDifference_GrBlendEquation);
100 GR_STATIC_ASSERT(12 == kExclusion_GrBlendEquation);
101 GR_STATIC_ASSERT(13 == kMultiply_GrBlendEquation);
102 GR_STATIC_ASSERT(14 == kHSLHue_GrBlendEquation);
103 GR_STATIC_ASSERT(15 == kHSLSaturation_GrBlendEquation);
104 GR_STATIC_ASSERT(16 == kHSLColor_GrBlendEquation);
105 GR_STATIC_ASSERT(17 == kHSLLuminosity_GrBlendEquation);
106 GR_STATIC_ASSERT(SK_ARRAY_COUNT(gXfermodeEquation2Blend) == kGrBlendEquationCnt);
107
108 static const GrGLenum gXfermodeCoeff2Blend[] = {
109 GR_GL_ZERO,
110 GR_GL_ONE,
111 GR_GL_SRC_COLOR,
112 GR_GL_ONE_MINUS_SRC_COLOR,
113 GR_GL_DST_COLOR,
114 GR_GL_ONE_MINUS_DST_COLOR,
115 GR_GL_SRC_ALPHA,
116 GR_GL_ONE_MINUS_SRC_ALPHA,
117 GR_GL_DST_ALPHA,
118 GR_GL_ONE_MINUS_DST_ALPHA,
119 GR_GL_CONSTANT_COLOR,
120 GR_GL_ONE_MINUS_CONSTANT_COLOR,
121 GR_GL_CONSTANT_ALPHA,
122 GR_GL_ONE_MINUS_CONSTANT_ALPHA,
123
124 // extended blend coeffs
125 GR_GL_SRC1_COLOR,
126 GR_GL_ONE_MINUS_SRC1_COLOR,
127 GR_GL_SRC1_ALPHA,
128 GR_GL_ONE_MINUS_SRC1_ALPHA,
129
130 // Illegal... needs to map to something.
131 GR_GL_ZERO,
132 };
133
BlendCoeffReferencesConstant(GrBlendCoeff coeff)134 bool GrGLGpu::BlendCoeffReferencesConstant(GrBlendCoeff coeff) {
135 static const bool gCoeffReferencesBlendConst[] = {
136 false,
137 false,
138 false,
139 false,
140 false,
141 false,
142 false,
143 false,
144 false,
145 false,
146 true,
147 true,
148 true,
149 true,
150
151 // extended blend coeffs
152 false,
153 false,
154 false,
155 false,
156
157 // Illegal.
158 false,
159 };
160 return gCoeffReferencesBlendConst[coeff];
161 GR_STATIC_ASSERT(kGrBlendCoeffCnt == SK_ARRAY_COUNT(gCoeffReferencesBlendConst));
162
163 GR_STATIC_ASSERT(0 == kZero_GrBlendCoeff);
164 GR_STATIC_ASSERT(1 == kOne_GrBlendCoeff);
165 GR_STATIC_ASSERT(2 == kSC_GrBlendCoeff);
166 GR_STATIC_ASSERT(3 == kISC_GrBlendCoeff);
167 GR_STATIC_ASSERT(4 == kDC_GrBlendCoeff);
168 GR_STATIC_ASSERT(5 == kIDC_GrBlendCoeff);
169 GR_STATIC_ASSERT(6 == kSA_GrBlendCoeff);
170 GR_STATIC_ASSERT(7 == kISA_GrBlendCoeff);
171 GR_STATIC_ASSERT(8 == kDA_GrBlendCoeff);
172 GR_STATIC_ASSERT(9 == kIDA_GrBlendCoeff);
173 GR_STATIC_ASSERT(10 == kConstC_GrBlendCoeff);
174 GR_STATIC_ASSERT(11 == kIConstC_GrBlendCoeff);
175 GR_STATIC_ASSERT(12 == kConstA_GrBlendCoeff);
176 GR_STATIC_ASSERT(13 == kIConstA_GrBlendCoeff);
177
178 GR_STATIC_ASSERT(14 == kS2C_GrBlendCoeff);
179 GR_STATIC_ASSERT(15 == kIS2C_GrBlendCoeff);
180 GR_STATIC_ASSERT(16 == kS2A_GrBlendCoeff);
181 GR_STATIC_ASSERT(17 == kIS2A_GrBlendCoeff);
182
183 // assertion for gXfermodeCoeff2Blend have to be in GrGpu scope
184 GR_STATIC_ASSERT(kGrBlendCoeffCnt == SK_ARRAY_COUNT(gXfermodeCoeff2Blend));
185 }
186
187 //////////////////////////////////////////////////////////////////////////////
188
gl_target_to_binding_index(GrGLenum target)189 static int gl_target_to_binding_index(GrGLenum target) {
190 switch (target) {
191 case GR_GL_TEXTURE_2D:
192 return 0;
193 case GR_GL_TEXTURE_RECTANGLE:
194 return 1;
195 case GR_GL_TEXTURE_EXTERNAL:
196 return 2;
197 }
198 SK_ABORT("Unexpected GL texture target.");
199 }
200
boundID(GrGLenum target) const201 GrGpuResource::UniqueID GrGLGpu::TextureUnitBindings::boundID(GrGLenum target) const {
202 return fTargetBindings[gl_target_to_binding_index(target)].fBoundResourceID;
203 }
204
hasBeenModified(GrGLenum target) const205 bool GrGLGpu::TextureUnitBindings::hasBeenModified(GrGLenum target) const {
206 return fTargetBindings[gl_target_to_binding_index(target)].fHasBeenModified;
207 }
208
setBoundID(GrGLenum target,GrGpuResource::UniqueID resourceID)209 void GrGLGpu::TextureUnitBindings::setBoundID(GrGLenum target, GrGpuResource::UniqueID resourceID) {
210 int targetIndex = gl_target_to_binding_index(target);
211 fTargetBindings[targetIndex].fBoundResourceID = resourceID;
212 fTargetBindings[targetIndex].fHasBeenModified = true;
213 }
214
invalidateForScratchUse(GrGLenum target)215 void GrGLGpu::TextureUnitBindings::invalidateForScratchUse(GrGLenum target) {
216 this->setBoundID(target, GrGpuResource::UniqueID());
217 }
218
invalidateAllTargets(bool markUnmodified)219 void GrGLGpu::TextureUnitBindings::invalidateAllTargets(bool markUnmodified) {
220 for (auto& targetBinding : fTargetBindings) {
221 targetBinding.fBoundResourceID.makeInvalid();
222 if (markUnmodified) {
223 targetBinding.fHasBeenModified = false;
224 }
225 }
226 }
227
228 //////////////////////////////////////////////////////////////////////////////
229
filter_to_gl_mag_filter(GrSamplerState::Filter filter)230 static GrGLenum filter_to_gl_mag_filter(GrSamplerState::Filter filter) {
231 switch (filter) {
232 case GrSamplerState::Filter::kNearest: return GR_GL_NEAREST;
233 case GrSamplerState::Filter::kBilerp: return GR_GL_LINEAR;
234 case GrSamplerState::Filter::kMipMap: return GR_GL_LINEAR;
235 }
236 SK_ABORT("Unknown filter");
237 }
238
filter_to_gl_min_filter(GrSamplerState::Filter filter)239 static GrGLenum filter_to_gl_min_filter(GrSamplerState::Filter filter) {
240 switch (filter) {
241 case GrSamplerState::Filter::kNearest: return GR_GL_NEAREST;
242 case GrSamplerState::Filter::kBilerp: return GR_GL_LINEAR;
243 case GrSamplerState::Filter::kMipMap: return GR_GL_LINEAR_MIPMAP_LINEAR;
244 }
245 SK_ABORT("Unknown filter");
246 }
247
wrap_mode_to_gl_wrap(GrSamplerState::WrapMode wrapMode,const GrCaps & caps)248 static inline GrGLenum wrap_mode_to_gl_wrap(GrSamplerState::WrapMode wrapMode,
249 const GrCaps& caps) {
250 switch (wrapMode) {
251 case GrSamplerState::WrapMode::kClamp: return GR_GL_CLAMP_TO_EDGE;
252 case GrSamplerState::WrapMode::kRepeat: return GR_GL_REPEAT;
253 case GrSamplerState::WrapMode::kMirrorRepeat: return GR_GL_MIRRORED_REPEAT;
254 case GrSamplerState::WrapMode::kClampToBorder:
255 // May not be supported but should have been caught earlier
256 SkASSERT(caps.clampToBorderSupport());
257 return GR_GL_CLAMP_TO_BORDER;
258 }
259 SK_ABORT("Unknown wrap mode");
260 }
261
262 ///////////////////////////////////////////////////////////////////////////////
263
264 class GrGLGpu::SamplerObjectCache {
265 public:
SamplerObjectCache(GrGLGpu * gpu)266 SamplerObjectCache(GrGLGpu* gpu) : fGpu(gpu) {
267 fNumTextureUnits = fGpu->glCaps().shaderCaps()->maxFragmentSamplers();
268 fHWBoundSamplers.reset(new GrGLuint[fNumTextureUnits]);
269 std::fill_n(fHWBoundSamplers.get(), fNumTextureUnits, 0);
270 std::fill_n(fSamplers, kNumSamplers, 0);
271 }
272
~SamplerObjectCache()273 ~SamplerObjectCache() {
274 if (!fNumTextureUnits) {
275 // We've already been abandoned.
276 return;
277 }
278 for (GrGLuint sampler : fSamplers) {
279 // The spec states that "zero" values should be silently ignored, however they still
280 // trigger GL errors on some NVIDIA platforms.
281 if (sampler) {
282 GR_GL_CALL(fGpu->glInterface(), DeleteSamplers(1, &sampler));
283 }
284 }
285 }
286
bindSampler(int unitIdx,const GrSamplerState & state)287 void bindSampler(int unitIdx, const GrSamplerState& state) {
288 int index = StateToIndex(state);
289 if (!fSamplers[index]) {
290 GrGLuint s;
291 GR_GL_CALL(fGpu->glInterface(), GenSamplers(1, &s));
292 if (!s) {
293 return;
294 }
295 fSamplers[index] = s;
296 auto minFilter = filter_to_gl_min_filter(state.filter());
297 auto magFilter = filter_to_gl_mag_filter(state.filter());
298 auto wrapX = wrap_mode_to_gl_wrap(state.wrapModeX(), fGpu->glCaps());
299 auto wrapY = wrap_mode_to_gl_wrap(state.wrapModeY(), fGpu->glCaps());
300 GR_GL_CALL(fGpu->glInterface(),
301 SamplerParameteri(s, GR_GL_TEXTURE_MIN_FILTER, minFilter));
302 GR_GL_CALL(fGpu->glInterface(),
303 SamplerParameteri(s, GR_GL_TEXTURE_MAG_FILTER, magFilter));
304 GR_GL_CALL(fGpu->glInterface(), SamplerParameteri(s, GR_GL_TEXTURE_WRAP_S, wrapX));
305 GR_GL_CALL(fGpu->glInterface(), SamplerParameteri(s, GR_GL_TEXTURE_WRAP_T, wrapY));
306 }
307 if (fHWBoundSamplers[unitIdx] != fSamplers[index]) {
308 GR_GL_CALL(fGpu->glInterface(), BindSampler(unitIdx, fSamplers[index]));
309 fHWBoundSamplers[unitIdx] = fSamplers[index];
310 }
311 }
312
invalidateBindings()313 void invalidateBindings() {
314 // When we have sampler support we always use samplers. So setting these to zero will cause
315 // a rebind on next usage.
316 std::fill_n(fHWBoundSamplers.get(), fNumTextureUnits, 0);
317 }
318
abandon()319 void abandon() {
320 fHWBoundSamplers.reset();
321 fNumTextureUnits = 0;
322 }
323
release()324 void release() {
325 if (!fNumTextureUnits) {
326 // We've already been abandoned.
327 return;
328 }
329 GR_GL_CALL(fGpu->glInterface(), DeleteSamplers(kNumSamplers, fSamplers));
330 std::fill_n(fSamplers, kNumSamplers, 0);
331 // Deleting a bound sampler implicitly binds sampler 0.
332 std::fill_n(fHWBoundSamplers.get(), fNumTextureUnits, 0);
333 }
334
335 private:
StateToIndex(const GrSamplerState & state)336 static int StateToIndex(const GrSamplerState& state) {
337 int filter = static_cast<int>(state.filter());
338 SkASSERT(filter >= 0 && filter < 3);
339 int wrapX = static_cast<int>(state.wrapModeX());
340 SkASSERT(wrapX >= 0 && wrapX < 4);
341 int wrapY = static_cast<int>(state.wrapModeY());
342 SkASSERT(wrapY >= 0 && wrapY < 4);
343 int idx = 16 * filter + 4 * wrapX + wrapY;
344 SkASSERT(idx < kNumSamplers);
345 return idx;
346 }
347
348 GrGLGpu* fGpu;
349 static constexpr int kNumSamplers = 48;
350 std::unique_ptr<GrGLuint[]> fHWBoundSamplers;
351 GrGLuint fSamplers[kNumSamplers];
352 int fNumTextureUnits;
353 };
354
355 ///////////////////////////////////////////////////////////////////////////////
356
Make(sk_sp<const GrGLInterface> interface,const GrContextOptions & options,GrContext * context)357 sk_sp<GrGpu> GrGLGpu::Make(sk_sp<const GrGLInterface> interface, const GrContextOptions& options,
358 GrContext* context) {
359 if (!interface) {
360 interface = GrGLMakeNativeInterface();
361 // For clients that have written their own GrGLCreateNativeInterface and haven't yet updated
362 // to GrGLMakeNativeInterface.
363 if (!interface) {
364 interface = sk_ref_sp(GrGLCreateNativeInterface());
365 }
366 if (!interface) {
367 return nullptr;
368 }
369 }
370 #ifdef USE_NSIGHT
371 const_cast<GrContextOptions&>(options).fSuppressPathRendering = true;
372 #endif
373 auto glContext = GrGLContext::Make(std::move(interface), options);
374 if (!glContext) {
375 return nullptr;
376 }
377 return sk_sp<GrGpu>(new GrGLGpu(std::move(glContext), context));
378 }
379
GrGLGpu(std::unique_ptr<GrGLContext> ctx,GrContext * context)380 GrGLGpu::GrGLGpu(std::unique_ptr<GrGLContext> ctx, GrContext* context)
381 : GrGpu(context)
382 , fGLContext(std::move(ctx))
383 , fProgramCache(new ProgramCache(this))
384 , fHWProgramID(0)
385 , fTempSrcFBOID(0)
386 , fTempDstFBOID(0)
387 , fStencilClearFBOID(0) {
388 SkASSERT(fGLContext);
389 GrGLClearErr(this->glInterface());
390 fCaps = sk_ref_sp(fGLContext->caps());
391
392 fHWTextureUnitBindings.reset(this->numTextureUnits());
393
394 this->hwBufferState(GrGpuBufferType::kVertex)->fGLTarget = GR_GL_ARRAY_BUFFER;
395 this->hwBufferState(GrGpuBufferType::kIndex)->fGLTarget = GR_GL_ELEMENT_ARRAY_BUFFER;
396 if (GrGLCaps::kChromium_TransferBufferType == this->glCaps().transferBufferType()) {
397 this->hwBufferState(GrGpuBufferType::kXferCpuToGpu)->fGLTarget =
398 GR_GL_PIXEL_UNPACK_TRANSFER_BUFFER_CHROMIUM;
399 this->hwBufferState(GrGpuBufferType::kXferGpuToCpu)->fGLTarget =
400 GR_GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM;
401 } else {
402 this->hwBufferState(GrGpuBufferType::kXferCpuToGpu)->fGLTarget = GR_GL_PIXEL_UNPACK_BUFFER;
403 this->hwBufferState(GrGpuBufferType::kXferGpuToCpu)->fGLTarget = GR_GL_PIXEL_PACK_BUFFER;
404 }
405 for (int i = 0; i < kGrGpuBufferTypeCount; ++i) {
406 fHWBufferState[i].invalidate();
407 }
408 GR_STATIC_ASSERT(4 == SK_ARRAY_COUNT(fHWBufferState));
409
410 if (this->glCaps().shaderCaps()->pathRenderingSupport()) {
411 fPathRendering.reset(new GrGLPathRendering(this));
412 }
413
414 if (this->glCaps().samplerObjectSupport()) {
415 fSamplerObjectCache.reset(new SamplerObjectCache(this));
416 }
417 }
418
~GrGLGpu()419 GrGLGpu::~GrGLGpu() {
420 // Ensure any GrGpuResource objects get deleted first, since they may require a working GrGLGpu
421 // to release the resources held by the objects themselves.
422 fPathRendering.reset();
423 fCopyProgramArrayBuffer.reset();
424 fMipmapProgramArrayBuffer.reset();
425
426 fHWProgram.reset();
427 if (fHWProgramID) {
428 // detach the current program so there is no confusion on OpenGL's part
429 // that we want it to be deleted
430 GL_CALL(UseProgram(0));
431 }
432
433 if (fTempSrcFBOID) {
434 this->deleteFramebuffer(fTempSrcFBOID);
435 }
436 if (fTempDstFBOID) {
437 this->deleteFramebuffer(fTempDstFBOID);
438 }
439 if (fStencilClearFBOID) {
440 this->deleteFramebuffer(fStencilClearFBOID);
441 }
442
443 for (size_t i = 0; i < SK_ARRAY_COUNT(fCopyPrograms); ++i) {
444 if (0 != fCopyPrograms[i].fProgram) {
445 GL_CALL(DeleteProgram(fCopyPrograms[i].fProgram));
446 }
447 }
448
449 for (size_t i = 0; i < SK_ARRAY_COUNT(fMipmapPrograms); ++i) {
450 if (0 != fMipmapPrograms[i].fProgram) {
451 GL_CALL(DeleteProgram(fMipmapPrograms[i].fProgram));
452 }
453 }
454
455 delete fProgramCache;
456 fSamplerObjectCache.reset();
457 }
458
disconnect(DisconnectType type)459 void GrGLGpu::disconnect(DisconnectType type) {
460 INHERITED::disconnect(type);
461 if (DisconnectType::kCleanup == type) {
462 if (fHWProgramID) {
463 GL_CALL(UseProgram(0));
464 }
465 if (fTempSrcFBOID) {
466 this->deleteFramebuffer(fTempSrcFBOID);
467 }
468 if (fTempDstFBOID) {
469 this->deleteFramebuffer(fTempDstFBOID);
470 }
471 if (fStencilClearFBOID) {
472 this->deleteFramebuffer(fStencilClearFBOID);
473 }
474 for (size_t i = 0; i < SK_ARRAY_COUNT(fCopyPrograms); ++i) {
475 if (fCopyPrograms[i].fProgram) {
476 GL_CALL(DeleteProgram(fCopyPrograms[i].fProgram));
477 }
478 }
479 for (size_t i = 0; i < SK_ARRAY_COUNT(fMipmapPrograms); ++i) {
480 if (fMipmapPrograms[i].fProgram) {
481 GL_CALL(DeleteProgram(fMipmapPrograms[i].fProgram));
482 }
483 }
484
485 if (fSamplerObjectCache) {
486 fSamplerObjectCache->release();
487 }
488 } else {
489 if (fProgramCache) {
490 fProgramCache->abandon();
491 }
492 if (fSamplerObjectCache) {
493 fSamplerObjectCache->abandon();
494 }
495 }
496
497 fHWProgram.reset();
498 delete fProgramCache;
499 fProgramCache = nullptr;
500
501 fHWProgramID = 0;
502 fTempSrcFBOID = 0;
503 fTempDstFBOID = 0;
504 fStencilClearFBOID = 0;
505 fCopyProgramArrayBuffer.reset();
506 for (size_t i = 0; i < SK_ARRAY_COUNT(fCopyPrograms); ++i) {
507 fCopyPrograms[i].fProgram = 0;
508 }
509 fMipmapProgramArrayBuffer.reset();
510 for (size_t i = 0; i < SK_ARRAY_COUNT(fMipmapPrograms); ++i) {
511 fMipmapPrograms[i].fProgram = 0;
512 }
513
514 if (this->glCaps().shaderCaps()->pathRenderingSupport()) {
515 this->glPathRendering()->disconnect(type);
516 }
517 }
518
519 ///////////////////////////////////////////////////////////////////////////////
520
onResetContext(uint32_t resetBits)521 void GrGLGpu::onResetContext(uint32_t resetBits) {
522 if (resetBits & kMisc_GrGLBackendState) {
523 // we don't use the zb at all
524 GL_CALL(Disable(GR_GL_DEPTH_TEST));
525 GL_CALL(DepthMask(GR_GL_FALSE));
526
527 // We don't use face culling.
528 GL_CALL(Disable(GR_GL_CULL_FACE));
529 // We do use separate stencil. Our algorithms don't care which face is front vs. back so
530 // just set this to the default for self-consistency.
531 GL_CALL(FrontFace(GR_GL_CCW));
532
533 this->hwBufferState(GrGpuBufferType::kXferCpuToGpu)->invalidate();
534 this->hwBufferState(GrGpuBufferType::kXferGpuToCpu)->invalidate();
535
536 if (GR_IS_GR_GL(this->glStandard())) {
537 #ifndef USE_NSIGHT
538 // Desktop-only state that we never change
539 if (!this->glCaps().isCoreProfile()) {
540 GL_CALL(Disable(GR_GL_POINT_SMOOTH));
541 GL_CALL(Disable(GR_GL_LINE_SMOOTH));
542 GL_CALL(Disable(GR_GL_POLYGON_SMOOTH));
543 GL_CALL(Disable(GR_GL_POLYGON_STIPPLE));
544 GL_CALL(Disable(GR_GL_COLOR_LOGIC_OP));
545 GL_CALL(Disable(GR_GL_INDEX_LOGIC_OP));
546 }
547 // The windows NVIDIA driver has GL_ARB_imaging in the extension string when using a
548 // core profile. This seems like a bug since the core spec removes any mention of
549 // GL_ARB_imaging.
550 if (this->glCaps().imagingSupport() && !this->glCaps().isCoreProfile()) {
551 GL_CALL(Disable(GR_GL_COLOR_TABLE));
552 }
553 GL_CALL(Disable(GR_GL_POLYGON_OFFSET_FILL));
554
555 if (this->caps()->wireframeMode()) {
556 GL_CALL(PolygonMode(GR_GL_FRONT_AND_BACK, GR_GL_LINE));
557 } else {
558 GL_CALL(PolygonMode(GR_GL_FRONT_AND_BACK, GR_GL_FILL));
559 }
560 #endif
561 // Since ES doesn't support glPointSize at all we always use the VS to
562 // set the point size
563 GL_CALL(Enable(GR_GL_VERTEX_PROGRAM_POINT_SIZE));
564
565 }
566
567 if (GR_IS_GR_GL_ES(this->glStandard()) &&
568 this->glCaps().fbFetchRequiresEnablePerSample()) {
569 // The arm extension requires specifically enabling MSAA fetching per sample.
570 // On some devices this may have a perf hit. Also multiple render targets are disabled
571 GL_CALL(Enable(GR_GL_FETCH_PER_SAMPLE));
572 }
573 fHWWriteToColor = kUnknown_TriState;
574 // we only ever use lines in hairline mode
575 GL_CALL(LineWidth(1));
576 GL_CALL(Disable(GR_GL_DITHER));
577
578 fHWClearColor[0] = fHWClearColor[1] = fHWClearColor[2] = fHWClearColor[3] = SK_FloatNaN;
579 }
580
581 if (resetBits & kMSAAEnable_GrGLBackendState) {
582 fMSAAEnabled = kUnknown_TriState;
583
584 if (this->caps()->mixedSamplesSupport()) {
585 // The skia blend modes all use premultiplied alpha and therefore expect RGBA coverage
586 // modulation. This state has no effect when not rendering to a mixed sampled target.
587 GL_CALL(CoverageModulation(GR_GL_RGBA));
588 }
589 }
590
591 fHWActiveTextureUnitIdx = -1; // invalid
592 fLastPrimitiveType = static_cast<GrPrimitiveType>(-1);
593
594 if (resetBits & kTextureBinding_GrGLBackendState) {
595 for (int s = 0; s < this->numTextureUnits(); ++s) {
596 fHWTextureUnitBindings[s].invalidateAllTargets(false);
597 }
598 if (fSamplerObjectCache) {
599 fSamplerObjectCache->invalidateBindings();
600 }
601 }
602
603 if (resetBits & kBlend_GrGLBackendState) {
604 fHWBlendState.invalidate();
605 }
606
607 if (resetBits & kView_GrGLBackendState) {
608 fHWScissorSettings.invalidate();
609 fHWWindowRectsState.invalidate();
610 fHWViewport.invalidate();
611 }
612
613 if (resetBits & kStencil_GrGLBackendState) {
614 fHWStencilSettings.invalidate();
615 fHWStencilTestEnabled = kUnknown_TriState;
616 }
617
618 // Vertex
619 if (resetBits & kVertex_GrGLBackendState) {
620 fHWVertexArrayState.invalidate();
621 this->hwBufferState(GrGpuBufferType::kVertex)->invalidate();
622 this->hwBufferState(GrGpuBufferType::kIndex)->invalidate();
623 }
624
625 if (resetBits & kRenderTarget_GrGLBackendState) {
626 fHWBoundRenderTargetUniqueID.makeInvalid();
627 fHWSRGBFramebuffer = kUnknown_TriState;
628 }
629
630 if (resetBits & kPathRendering_GrGLBackendState) {
631 if (this->caps()->shaderCaps()->pathRenderingSupport()) {
632 this->glPathRendering()->resetContext();
633 }
634 }
635
636 // we assume these values
637 if (resetBits & kPixelStore_GrGLBackendState) {
638 if (this->caps()->writePixelsRowBytesSupport()) {
639 GL_CALL(PixelStorei(GR_GL_UNPACK_ROW_LENGTH, 0));
640 }
641 if (this->glCaps().readPixelsRowBytesSupport()) {
642 GL_CALL(PixelStorei(GR_GL_PACK_ROW_LENGTH, 0));
643 }
644 if (this->glCaps().packFlipYSupport()) {
645 GL_CALL(PixelStorei(GR_GL_PACK_REVERSE_ROW_ORDER, GR_GL_FALSE));
646 }
647 }
648
649 if (resetBits & kProgram_GrGLBackendState) {
650 fHWProgramID = 0;
651 fHWProgram.reset();
652 }
653 ++fResetTimestampForTextureParameters;
654 }
655
check_backend_texture(const GrBackendTexture & backendTex,const GrColorType colorType,const GrGLCaps & caps,GrGLTexture::Desc * desc,bool skipRectTexSupportCheck=false)656 static bool check_backend_texture(const GrBackendTexture& backendTex, const GrColorType colorType,
657 const GrGLCaps& caps, GrGLTexture::Desc* desc,
658 bool skipRectTexSupportCheck = false) {
659 GrGLTextureInfo info;
660 if (!backendTex.getGLTextureInfo(&info) || !info.fID || !info.fFormat) {
661 return false;
662 }
663
664 desc->fSize = {backendTex.width(), backendTex.height()};
665 desc->fTarget = info.fTarget;
666 desc->fID = info.fID;
667 desc->fFormat = GrGLFormatFromGLEnum(info.fFormat);
668
669 if (desc->fFormat == GrGLFormat::kUnknown) {
670 return false;
671 }
672 if (GR_GL_TEXTURE_EXTERNAL == desc->fTarget) {
673 if (!caps.shaderCaps()->externalTextureSupport()) {
674 return false;
675 }
676 } else if (GR_GL_TEXTURE_RECTANGLE == desc->fTarget) {
677 if (!caps.rectangleTextureSupport() && !skipRectTexSupportCheck) {
678 return false;
679 }
680 } else if (GR_GL_TEXTURE_2D != desc->fTarget) {
681 return false;
682 }
683 if (backendTex.isProtected()) {
684 // Not supported in GL backend at this time.
685 return false;
686 }
687
688 desc->fConfig = caps.getConfigFromBackendFormat(backendTex.getBackendFormat(), colorType);
689 SkASSERT(desc->fConfig != kUnknown_GrPixelConfig);
690
691 return true;
692 }
693
onWrapBackendTexture(const GrBackendTexture & backendTex,GrColorType colorType,GrWrapOwnership ownership,GrWrapCacheable cacheable,GrIOType ioType)694 sk_sp<GrTexture> GrGLGpu::onWrapBackendTexture(const GrBackendTexture& backendTex,
695 GrColorType colorType, GrWrapOwnership ownership,
696 GrWrapCacheable cacheable, GrIOType ioType) {
697 GrGLTexture::Desc desc;
698 if (!check_backend_texture(backendTex, colorType, this->glCaps(), &desc)) {
699 return nullptr;
700 }
701
702 if (kBorrow_GrWrapOwnership == ownership) {
703 desc.fOwnership = GrBackendObjectOwnership::kBorrowed;
704 } else {
705 desc.fOwnership = GrBackendObjectOwnership::kOwned;
706 }
707
708 GrMipMapsStatus mipMapsStatus = backendTex.hasMipMaps() ? GrMipMapsStatus::kValid
709 : GrMipMapsStatus::kNotAllocated;
710
711 auto texture = GrGLTexture::MakeWrapped(this, mipMapsStatus, desc,
712 backendTex.getGLTextureParams(), cacheable, ioType);
713 // We don't know what parameters are already set on wrapped textures.
714 texture->textureParamsModified();
715 return texture;
716 }
717
onWrapRenderableBackendTexture(const GrBackendTexture & backendTex,int sampleCnt,GrColorType colorType,GrWrapOwnership ownership,GrWrapCacheable cacheable)718 sk_sp<GrTexture> GrGLGpu::onWrapRenderableBackendTexture(const GrBackendTexture& backendTex,
719 int sampleCnt,
720 GrColorType colorType,
721 GrWrapOwnership ownership,
722 GrWrapCacheable cacheable) {
723 const GrGLCaps& caps = this->glCaps();
724
725 GrGLTexture::Desc desc;
726 if (!check_backend_texture(backendTex, colorType, this->glCaps(), &desc)) {
727 return nullptr;
728 }
729 SkASSERT(caps.isFormatRenderable(desc.fFormat, sampleCnt));
730 SkASSERT(caps.isFormatTexturable(desc.fFormat));
731
732 // We don't support rendering to a EXTERNAL texture.
733 if (GR_GL_TEXTURE_EXTERNAL == desc.fTarget) {
734 return nullptr;
735 }
736
737 if (kBorrow_GrWrapOwnership == ownership) {
738 desc.fOwnership = GrBackendObjectOwnership::kBorrowed;
739 } else {
740 desc.fOwnership = GrBackendObjectOwnership::kOwned;
741 }
742
743
744 sampleCnt = caps.getRenderTargetSampleCount(sampleCnt, desc.fFormat);
745 SkASSERT(sampleCnt);
746
747 GrGLRenderTarget::IDs rtIDs;
748 if (!this->createRenderTargetObjects(desc, sampleCnt, &rtIDs)) {
749 return nullptr;
750 }
751
752 GrMipMapsStatus mipMapsStatus = backendTex.hasMipMaps() ? GrMipMapsStatus::kDirty
753 : GrMipMapsStatus::kNotAllocated;
754
755 sk_sp<GrGLTextureRenderTarget> texRT(GrGLTextureRenderTarget::MakeWrapped(
756 this, sampleCnt, desc, backendTex.getGLTextureParams(), rtIDs, cacheable,
757 mipMapsStatus));
758 texRT->baseLevelWasBoundToFBO();
759 // We don't know what parameters are already set on wrapped textures.
760 texRT->textureParamsModified();
761 return texRT;
762 }
763
onWrapBackendRenderTarget(const GrBackendRenderTarget & backendRT,GrColorType grColorType)764 sk_sp<GrRenderTarget> GrGLGpu::onWrapBackendRenderTarget(const GrBackendRenderTarget& backendRT,
765 GrColorType grColorType) {
766 GrGLFramebufferInfo info;
767 if (!backendRT.getGLFramebufferInfo(&info)) {
768 return nullptr;
769 }
770
771 if (backendRT.isProtected()) {
772 // Not supported in GL at this time.
773 return nullptr;
774 }
775
776 const auto format = backendRT.getBackendFormat().asGLFormat();
777 if (!this->glCaps().isFormatRenderable(format, backendRT.sampleCnt())) {
778 return nullptr;
779 }
780
781 GrGLRenderTarget::IDs rtIDs;
782 rtIDs.fRTFBOID = info.fFBOID;
783 rtIDs.fMSColorRenderbufferID = 0;
784 rtIDs.fTexFBOID = GrGLRenderTarget::kUnresolvableFBOID;
785 rtIDs.fRTFBOOwnership = GrBackendObjectOwnership::kBorrowed;
786
787 GrPixelConfig config = this->caps()->getConfigFromBackendFormat(backendRT.getBackendFormat(),
788 grColorType);
789 SkASSERT(kUnknown_GrPixelConfig != config);
790
791 const auto size = SkISize::Make(backendRT.width(), backendRT.height());
792 int sampleCount = this->glCaps().getRenderTargetSampleCount(backendRT.sampleCnt(), format);
793
794 return GrGLRenderTarget::MakeWrapped(this, size, format, config, sampleCount, rtIDs,
795 backendRT.stencilBits());
796 }
797
onWrapBackendTextureAsRenderTarget(const GrBackendTexture & tex,int sampleCnt,GrColorType colorType)798 sk_sp<GrRenderTarget> GrGLGpu::onWrapBackendTextureAsRenderTarget(const GrBackendTexture& tex,
799 int sampleCnt,
800 GrColorType colorType) {
801 GrGLTexture::Desc desc;
802 // We do not check whether texture rectangle is supported by Skia - if the caller provided us
803 // with a texture rectangle,we assume the necessary support exists.
804 if (!check_backend_texture(tex, colorType, this->glCaps(), &desc, true)) {
805 return nullptr;
806 }
807
808 if (!this->glCaps().isFormatRenderable(desc.fFormat, sampleCnt)) {
809 return nullptr;
810 }
811
812 const int sampleCount = this->glCaps().getRenderTargetSampleCount(sampleCnt, desc.fFormat);
813 GrGLRenderTarget::IDs rtIDs;
814 if (!this->createRenderTargetObjects(desc, sampleCount, &rtIDs)) {
815 return nullptr;
816 }
817 return GrGLRenderTarget::MakeWrapped(this, desc.fSize, desc.fFormat, desc.fConfig, sampleCount,
818 rtIDs, 0);
819 }
820
check_write_and_transfer_input(GrGLTexture * glTex)821 static bool check_write_and_transfer_input(GrGLTexture* glTex) {
822 if (!glTex) {
823 return false;
824 }
825
826 // Write or transfer of pixels is not implemented for TEXTURE_EXTERNAL textures
827 if (GR_GL_TEXTURE_EXTERNAL == glTex->target()) {
828 return false;
829 }
830
831 return true;
832 }
833
onWritePixels(GrSurface * surface,int left,int top,int width,int height,GrColorType surfaceColorType,GrColorType srcColorType,const GrMipLevel texels[],int mipLevelCount,bool prepForTexSampling)834 bool GrGLGpu::onWritePixels(GrSurface* surface, int left, int top, int width, int height,
835 GrColorType surfaceColorType, GrColorType srcColorType,
836 const GrMipLevel texels[], int mipLevelCount,
837 bool prepForTexSampling) {
838 auto glTex = static_cast<GrGLTexture*>(surface->asTexture());
839
840 if (!check_write_and_transfer_input(glTex)) {
841 return false;
842 }
843
844 this->bindTextureToScratchUnit(glTex->target(), glTex->textureID());
845
846 SkASSERT(!GrGLFormatIsCompressed(glTex->format()));
847 return this->uploadTexData(glTex->format(), surfaceColorType, glTex->width(), glTex->height(),
848 glTex->target(), left, top, width, height, srcColorType, texels,
849 mipLevelCount);
850 }
851
onTransferPixelsTo(GrTexture * texture,int left,int top,int width,int height,GrColorType textureColorType,GrColorType bufferColorType,GrGpuBuffer * transferBuffer,size_t offset,size_t rowBytes)852 bool GrGLGpu::onTransferPixelsTo(GrTexture* texture, int left, int top, int width, int height,
853 GrColorType textureColorType, GrColorType bufferColorType,
854 GrGpuBuffer* transferBuffer, size_t offset, size_t rowBytes) {
855 GrGLTexture* glTex = static_cast<GrGLTexture*>(texture);
856
857 // Can't transfer compressed data
858 SkASSERT(!GrGLFormatIsCompressed(glTex->format()));
859
860 if (!check_write_and_transfer_input(glTex)) {
861 return false;
862 }
863
864 static_assert(sizeof(int) == sizeof(int32_t), "");
865 if (width <= 0 || height <= 0) {
866 return false;
867 }
868
869 this->bindTextureToScratchUnit(glTex->target(), glTex->textureID());
870
871 SkASSERT(!transferBuffer->isMapped());
872 SkASSERT(!transferBuffer->isCpuBuffer());
873 const GrGLBuffer* glBuffer = static_cast<const GrGLBuffer*>(transferBuffer);
874 this->bindBuffer(GrGpuBufferType::kXferCpuToGpu, glBuffer);
875
876 SkDEBUGCODE(
877 SkIRect subRect = SkIRect::MakeXYWH(left, top, width, height);
878 SkIRect bounds = SkIRect::MakeWH(texture->width(), texture->height());
879 SkASSERT(bounds.contains(subRect));
880 )
881
882 size_t bpp = GrColorTypeBytesPerPixel(bufferColorType);
883 const size_t trimRowBytes = width * bpp;
884 const void* pixels = (void*)offset;
885 if (width < 0 || height < 0) {
886 return false;
887 }
888
889 bool restoreGLRowLength = false;
890 if (trimRowBytes != rowBytes) {
891 // we should have checked for this support already
892 SkASSERT(this->glCaps().writePixelsRowBytesSupport());
893 GL_CALL(PixelStorei(GR_GL_UNPACK_ROW_LENGTH, rowBytes / bpp));
894 restoreGLRowLength = true;
895 }
896
897 GrGLFormat textureFormat = glTex->format();
898 // External format and type come from the upload data.
899 GrGLenum externalFormat = 0;
900 GrGLenum externalType = 0;
901 this->glCaps().getTexSubImageExternalFormatAndType(
902 textureFormat, textureColorType, bufferColorType, &externalFormat, &externalType);
903 if (!externalFormat || !externalType) {
904 return false;
905 }
906
907 GL_CALL(PixelStorei(GR_GL_UNPACK_ALIGNMENT, 1));
908 GL_CALL(TexSubImage2D(glTex->target(),
909 0,
910 left, top,
911 width,
912 height,
913 externalFormat, externalType,
914 pixels));
915
916 if (restoreGLRowLength) {
917 GL_CALL(PixelStorei(GR_GL_UNPACK_ROW_LENGTH, 0));
918 }
919
920 return true;
921 }
922
onTransferPixelsFrom(GrSurface * surface,int left,int top,int width,int height,GrColorType surfaceColorType,GrColorType dstColorType,GrGpuBuffer * transferBuffer,size_t offset)923 bool GrGLGpu::onTransferPixelsFrom(GrSurface* surface, int left, int top, int width, int height,
924 GrColorType surfaceColorType, GrColorType dstColorType,
925 GrGpuBuffer* transferBuffer, size_t offset) {
926 auto* glBuffer = static_cast<GrGLBuffer*>(transferBuffer);
927 this->bindBuffer(GrGpuBufferType::kXferGpuToCpu, glBuffer);
928 auto offsetAsPtr = reinterpret_cast<void*>(offset);
929 return this->readOrTransferPixelsFrom(surface, left, top, width, height, surfaceColorType,
930 dstColorType, offsetAsPtr, width);
931 }
932
unbindCpuToGpuXferBuffer()933 void GrGLGpu::unbindCpuToGpuXferBuffer() {
934 auto* xferBufferState = this->hwBufferState(GrGpuBufferType::kXferCpuToGpu);
935 if (!xferBufferState->fBoundBufferUniqueID.isInvalid()) {
936 GL_CALL(BindBuffer(xferBufferState->fGLTarget, 0));
937 xferBufferState->invalidate();
938 }
939 }
940
uploadTexData(GrGLFormat textureFormat,GrColorType textureColorType,int texWidth,int texHeight,GrGLenum target,int left,int top,int width,int height,GrColorType srcColorType,const GrMipLevel texels[],int mipLevelCount,GrMipMapsStatus * mipMapsStatus)941 bool GrGLGpu::uploadTexData(GrGLFormat textureFormat, GrColorType textureColorType, int texWidth,
942 int texHeight, GrGLenum target, int left, int top, int width,
943 int height, GrColorType srcColorType, const GrMipLevel texels[],
944 int mipLevelCount, GrMipMapsStatus* mipMapsStatus) {
945 // If we're uploading compressed data then we should be using uploadCompressedTexData
946 SkASSERT(!GrGLFormatIsCompressed(textureFormat));
947
948 SkASSERT(this->glCaps().isFormatTexturable(textureFormat));
949 SkDEBUGCODE(
950 SkIRect subRect = SkIRect::MakeXYWH(left, top, width, height);
951 SkIRect bounds = SkIRect::MakeWH(texWidth, texHeight);
952 SkASSERT(bounds.contains(subRect));
953 )
954 SkASSERT(1 == mipLevelCount ||
955 (0 == left && 0 == top && width == texWidth && height == texHeight));
956
957 this->unbindCpuToGpuXferBuffer();
958
959 const GrGLInterface* interface = this->glInterface();
960 const GrGLCaps& caps = this->glCaps();
961
962 size_t bpp = GrColorTypeBytesPerPixel(srcColorType);
963
964 if (width == 0 || height == 0) {
965 return false;
966 }
967
968 // External format and type come from the upload data.
969 GrGLenum externalFormat;
970 GrGLenum externalType;
971 this->glCaps().getTexSubImageExternalFormatAndType(
972 textureFormat, textureColorType, srcColorType, &externalFormat, &externalType);
973 if (!externalFormat || !externalType) {
974 return false;
975 }
976
977 /*
978 * Check whether to allocate a temporary buffer for flipping y or
979 * because our srcData has extra bytes past each row. If so, we need
980 * to trim those off here, since GL ES may not let us specify
981 * GL_UNPACK_ROW_LENGTH.
982 */
983 bool restoreGLRowLength = false;
984
985 if (mipMapsStatus) {
986 *mipMapsStatus = (mipLevelCount > 1) ?
987 GrMipMapsStatus::kValid : GrMipMapsStatus::kNotAllocated;
988 }
989
990 GR_GL_CALL(interface, PixelStorei(GR_GL_UNPACK_ALIGNMENT, 1));
991
992 for (int currentMipLevel = 0; currentMipLevel < mipLevelCount; currentMipLevel++) {
993 if (!texels[currentMipLevel].fPixels) {
994 if (mipMapsStatus) {
995 *mipMapsStatus = GrMipMapsStatus::kDirty;
996 }
997 continue;
998 }
999 int twoToTheMipLevel = 1 << currentMipLevel;
1000 const int currentWidth = SkTMax(1, width / twoToTheMipLevel);
1001 const int currentHeight = SkTMax(1, height / twoToTheMipLevel);
1002 const size_t trimRowBytes = currentWidth * bpp;
1003 const size_t rowBytes = texels[currentMipLevel].fRowBytes;
1004
1005 if (caps.writePixelsRowBytesSupport() && (rowBytes != trimRowBytes || restoreGLRowLength)) {
1006 GrGLint rowLength = static_cast<GrGLint>(rowBytes / bpp);
1007 GR_GL_CALL(interface, PixelStorei(GR_GL_UNPACK_ROW_LENGTH, rowLength));
1008 restoreGLRowLength = true;
1009 }
1010
1011 GL_CALL(TexSubImage2D(target, currentMipLevel, left, top, currentWidth, currentHeight,
1012 externalFormat, externalType, texels[currentMipLevel].fPixels));
1013 }
1014 if (restoreGLRowLength) {
1015 SkASSERT(caps.writePixelsRowBytesSupport());
1016 GL_CALL(PixelStorei(GR_GL_UNPACK_ROW_LENGTH, 0));
1017 }
1018 return true;
1019 }
1020
uploadCompressedTexData(GrGLFormat format,SkImage::CompressionType compressionType,const SkISize & size,GrGLenum target,const void * data)1021 bool GrGLGpu::uploadCompressedTexData(GrGLFormat format,
1022 SkImage::CompressionType compressionType,
1023 const SkISize& size,
1024 GrGLenum target,
1025 const void* data) {
1026 SkASSERT(format != GrGLFormat::kUnknown);
1027 const GrGLCaps& caps = this->glCaps();
1028
1029 // We only need the internal format for compressed 2D textures.
1030 GrGLenum internalFormat = caps.getTexImageOrStorageInternalFormat(format);
1031 if (!internalFormat) {
1032 return 0;
1033 }
1034
1035 bool useTexStorage = caps.formatSupportsTexStorage(format);
1036
1037 static constexpr int kMipLevelCount = 1;
1038
1039 // Make sure that the width and height that we pass to OpenGL
1040 // is a multiple of the block size.
1041 size_t dataSize = GrCompressedDataSize(compressionType, size.width(), size.height());
1042
1043 if (useTexStorage) {
1044 // We never resize or change formats of textures.
1045 GL_ALLOC_CALL(
1046 this->glInterface(),
1047 TexStorage2D(target, kMipLevelCount, internalFormat, size.width(), size.height()));
1048 GrGLenum error = CHECK_ALLOC_ERROR(this->glInterface());
1049 if (error != GR_GL_NO_ERROR) {
1050 return false;
1051 }
1052 GL_CALL(CompressedTexSubImage2D(target,
1053 0, // level
1054 0, // left
1055 0, // top
1056 size.width(),
1057 size.height(),
1058 internalFormat,
1059 SkToInt(dataSize),
1060 data));
1061 } else {
1062 GL_ALLOC_CALL(this->glInterface(), CompressedTexImage2D(target,
1063 0, // level
1064 internalFormat,
1065 size.width(),
1066 size.height(),
1067 0, // border
1068 SkToInt(dataSize),
1069 data));
1070
1071 GrGLenum error = CHECK_ALLOC_ERROR(this->glInterface());
1072 if (error != GR_GL_NO_ERROR) {
1073 return false;
1074 }
1075 }
1076 return true;
1077 }
1078
renderbuffer_storage_msaa(const GrGLContext & ctx,int sampleCount,GrGLenum format,int width,int height)1079 static bool renderbuffer_storage_msaa(const GrGLContext& ctx,
1080 int sampleCount,
1081 GrGLenum format,
1082 int width, int height) {
1083 CLEAR_ERROR_BEFORE_ALLOC(ctx.interface());
1084 SkASSERT(GrGLCaps::kNone_MSFBOType != ctx.caps()->msFBOType());
1085 switch (ctx.caps()->msFBOType()) {
1086 case GrGLCaps::kStandard_MSFBOType:
1087 GL_ALLOC_CALL(ctx.interface(),
1088 RenderbufferStorageMultisample(GR_GL_RENDERBUFFER,
1089 sampleCount,
1090 format,
1091 width, height));
1092 break;
1093 case GrGLCaps::kES_Apple_MSFBOType:
1094 GL_ALLOC_CALL(ctx.interface(),
1095 RenderbufferStorageMultisampleES2APPLE(GR_GL_RENDERBUFFER,
1096 sampleCount,
1097 format,
1098 width, height));
1099 break;
1100 case GrGLCaps::kES_EXT_MsToTexture_MSFBOType:
1101 case GrGLCaps::kES_IMG_MsToTexture_MSFBOType:
1102 GL_ALLOC_CALL(ctx.interface(),
1103 RenderbufferStorageMultisampleES2EXT(GR_GL_RENDERBUFFER,
1104 sampleCount,
1105 format,
1106 width, height));
1107 break;
1108 case GrGLCaps::kNone_MSFBOType:
1109 SK_ABORT("Shouldn't be here if we don't support multisampled renderbuffers.");
1110 break;
1111 }
1112 return (GR_GL_NO_ERROR == CHECK_ALLOC_ERROR(ctx.interface()));
1113 }
1114
createRenderTargetObjects(const GrGLTexture::Desc & desc,int sampleCount,GrGLRenderTarget::IDs * rtIDs)1115 bool GrGLGpu::createRenderTargetObjects(const GrGLTexture::Desc& desc,
1116 int sampleCount,
1117 GrGLRenderTarget::IDs* rtIDs) {
1118 rtIDs->fMSColorRenderbufferID = 0;
1119 rtIDs->fRTFBOID = 0;
1120 rtIDs->fRTFBOOwnership = GrBackendObjectOwnership::kOwned;
1121 rtIDs->fTexFBOID = 0;
1122
1123 GrGLenum colorRenderbufferFormat = 0; // suppress warning
1124
1125 if (desc.fFormat == GrGLFormat::kUnknown) {
1126 goto FAILED;
1127 }
1128
1129 if (sampleCount > 1 && GrGLCaps::kNone_MSFBOType == this->glCaps().msFBOType()) {
1130 goto FAILED;
1131 }
1132
1133 GL_CALL(GenFramebuffers(1, &rtIDs->fTexFBOID));
1134 if (!rtIDs->fTexFBOID) {
1135 goto FAILED;
1136 }
1137
1138 // If we are using multisampling we will create two FBOS. We render to one and then resolve to
1139 // the texture bound to the other. The exception is the IMG multisample extension. With this
1140 // extension the texture is multisampled when rendered to and then auto-resolves it when it is
1141 // rendered from.
1142 if (sampleCount > 1 && this->glCaps().usesMSAARenderBuffers()) {
1143 GL_CALL(GenFramebuffers(1, &rtIDs->fRTFBOID));
1144 GL_CALL(GenRenderbuffers(1, &rtIDs->fMSColorRenderbufferID));
1145 if (!rtIDs->fRTFBOID || !rtIDs->fMSColorRenderbufferID) {
1146 goto FAILED;
1147 }
1148 colorRenderbufferFormat = this->glCaps().getRenderbufferInternalFormat(desc.fFormat);
1149 } else {
1150 rtIDs->fRTFBOID = rtIDs->fTexFBOID;
1151 }
1152
1153 // below here we may bind the FBO
1154 fHWBoundRenderTargetUniqueID.makeInvalid();
1155 if (rtIDs->fRTFBOID != rtIDs->fTexFBOID) {
1156 SkASSERT(sampleCount > 1);
1157 GL_CALL(BindRenderbuffer(GR_GL_RENDERBUFFER, rtIDs->fMSColorRenderbufferID));
1158 if (!renderbuffer_storage_msaa(*fGLContext, sampleCount, colorRenderbufferFormat,
1159 desc.fSize.width(), desc.fSize.height())) {
1160 goto FAILED;
1161 }
1162 this->bindFramebuffer(GR_GL_FRAMEBUFFER, rtIDs->fRTFBOID);
1163 GL_CALL(FramebufferRenderbuffer(GR_GL_FRAMEBUFFER,
1164 GR_GL_COLOR_ATTACHMENT0,
1165 GR_GL_RENDERBUFFER,
1166 rtIDs->fMSColorRenderbufferID));
1167 }
1168 this->bindFramebuffer(GR_GL_FRAMEBUFFER, rtIDs->fTexFBOID);
1169
1170 if (this->glCaps().usesImplicitMSAAResolve() && sampleCount > 1) {
1171 GL_CALL(FramebufferTexture2DMultisample(GR_GL_FRAMEBUFFER,
1172 GR_GL_COLOR_ATTACHMENT0,
1173 desc.fTarget,
1174 desc.fID,
1175 0,
1176 sampleCount));
1177 } else {
1178 GL_CALL(FramebufferTexture2D(GR_GL_FRAMEBUFFER,
1179 GR_GL_COLOR_ATTACHMENT0,
1180 desc.fTarget,
1181 desc.fID,
1182 0));
1183 }
1184
1185 return true;
1186
1187 FAILED:
1188 if (rtIDs->fMSColorRenderbufferID) {
1189 GL_CALL(DeleteRenderbuffers(1, &rtIDs->fMSColorRenderbufferID));
1190 }
1191 if (rtIDs->fRTFBOID != rtIDs->fTexFBOID) {
1192 this->deleteFramebuffer(rtIDs->fRTFBOID);
1193 }
1194 if (rtIDs->fTexFBOID) {
1195 this->deleteFramebuffer(rtIDs->fTexFBOID);
1196 }
1197 return false;
1198 }
1199
1200 // good to set a break-point here to know when createTexture fails
return_null_texture()1201 static sk_sp<GrTexture> return_null_texture() {
1202 // SkDEBUGFAIL("null texture");
1203 return nullptr;
1204 }
1205
set_initial_texture_params(const GrGLInterface * interface,GrGLenum target)1206 static GrGLTextureParameters::SamplerOverriddenState set_initial_texture_params(
1207 const GrGLInterface* interface, GrGLenum target) {
1208 // Some drivers like to know filter/wrap before seeing glTexImage2D. Some
1209 // drivers have a bug where an FBO won't be complete if it includes a
1210 // texture that is not mipmap complete (considering the filter in use).
1211 GrGLTextureParameters::SamplerOverriddenState state;
1212 state.fMinFilter = GR_GL_NEAREST;
1213 state.fMagFilter = GR_GL_NEAREST;
1214 state.fWrapS = GR_GL_CLAMP_TO_EDGE;
1215 state.fWrapT = GR_GL_CLAMP_TO_EDGE;
1216 GR_GL_CALL(interface, TexParameteri(target, GR_GL_TEXTURE_MAG_FILTER, state.fMagFilter));
1217 GR_GL_CALL(interface, TexParameteri(target, GR_GL_TEXTURE_MIN_FILTER, state.fMinFilter));
1218 GR_GL_CALL(interface, TexParameteri(target, GR_GL_TEXTURE_WRAP_S, state.fWrapS));
1219 GR_GL_CALL(interface, TexParameteri(target, GR_GL_TEXTURE_WRAP_T, state.fWrapT));
1220 return state;
1221 }
1222
onCreateTexture(const GrSurfaceDesc & desc,const GrBackendFormat & format,GrRenderable renderable,int renderTargetSampleCnt,SkBudgeted budgeted,GrProtected isProtected,int mipLevelCount,uint32_t levelClearMask)1223 sk_sp<GrTexture> GrGLGpu::onCreateTexture(const GrSurfaceDesc& desc,
1224 const GrBackendFormat& format,
1225 GrRenderable renderable,
1226 int renderTargetSampleCnt,
1227 SkBudgeted budgeted,
1228 GrProtected isProtected,
1229 int mipLevelCount,
1230 uint32_t levelClearMask) {
1231 // We don't support protected textures in GL.
1232 if (isProtected == GrProtected::kYes) {
1233 return nullptr;
1234 }
1235 SkASSERT(GrGLCaps::kNone_MSFBOType != this->glCaps().msFBOType() || renderTargetSampleCnt == 1);
1236
1237 SkASSERT(mipLevelCount > 0);
1238 GrMipMapsStatus mipMapsStatus =
1239 mipLevelCount > 1 ? GrMipMapsStatus::kDirty : GrMipMapsStatus::kNotAllocated;
1240 GrGLTextureParameters::SamplerOverriddenState initialState;
1241 GrGLTexture::Desc texDesc;
1242 texDesc.fSize = {desc.fWidth, desc.fHeight};
1243 texDesc.fTarget = GR_GL_TEXTURE_2D;
1244 texDesc.fFormat = format.asGLFormat();
1245 texDesc.fConfig = desc.fConfig;
1246 texDesc.fOwnership = GrBackendObjectOwnership::kOwned;
1247 SkASSERT(texDesc.fFormat != GrGLFormat::kUnknown);
1248 SkASSERT(!GrGLFormatIsCompressed(texDesc.fFormat));
1249
1250 texDesc.fID = this->createTexture2D({desc.fWidth, desc.fHeight}, texDesc.fFormat, renderable,
1251 &initialState, mipLevelCount);
1252
1253 if (!texDesc.fID) {
1254 return return_null_texture();
1255 }
1256
1257 sk_sp<GrGLTexture> tex;
1258 if (renderable == GrRenderable::kYes) {
1259 // unbind the texture from the texture unit before binding it to the frame buffer
1260 GL_CALL(BindTexture(texDesc.fTarget, 0));
1261 GrGLRenderTarget::IDs rtIDDesc;
1262
1263 if (!this->createRenderTargetObjects(texDesc, renderTargetSampleCnt, &rtIDDesc)) {
1264 GL_CALL(DeleteTextures(1, &texDesc.fID));
1265 return return_null_texture();
1266 }
1267 tex = sk_make_sp<GrGLTextureRenderTarget>(
1268 this, budgeted, renderTargetSampleCnt, texDesc, rtIDDesc, mipMapsStatus);
1269 tex->baseLevelWasBoundToFBO();
1270 } else {
1271 tex = sk_make_sp<GrGLTexture>(this, budgeted, texDesc, mipMapsStatus);
1272 }
1273 // The non-sampler params are still at their default values.
1274 tex->parameters()->set(&initialState, GrGLTextureParameters::NonsamplerState(),
1275 fResetTimestampForTextureParameters);
1276 if (levelClearMask) {
1277 GrGLenum externalFormat, externalType;
1278 size_t bpp;
1279 this->glCaps().getTexSubImageZeroFormatTypeAndBpp(texDesc.fFormat, &externalFormat,
1280 &externalType, &bpp);
1281 if (this->glCaps().clearTextureSupport()) {
1282 for (int i = 0; i < mipLevelCount; ++i) {
1283 if (levelClearMask & (1U << i)) {
1284 GL_CALL(ClearTexImage(tex->textureID(), i, externalFormat, externalType,
1285 nullptr));
1286 }
1287 }
1288 } else if (this->glCaps().canFormatBeFBOColorAttachment(format.asGLFormat()) &&
1289 !this->glCaps().performColorClearsAsDraws()) {
1290 this->disableScissor();
1291 this->disableWindowRectangles();
1292 this->flushColorWrite(true);
1293 this->flushClearColor(SK_PMColor4fTRANSPARENT);
1294 for (int i = 0; i < mipLevelCount; ++i) {
1295 if (levelClearMask & (1U << i)) {
1296 this->bindSurfaceFBOForPixelOps(tex.get(), i, GR_GL_FRAMEBUFFER,
1297 kDst_TempFBOTarget);
1298 GL_CALL(Clear(GR_GL_COLOR_BUFFER_BIT));
1299 this->unbindSurfaceFBOForPixelOps(tex.get(), i, GR_GL_FRAMEBUFFER);
1300 }
1301 }
1302 fHWBoundRenderTargetUniqueID.makeInvalid();
1303 } else {
1304 std::unique_ptr<char[]> zeros;
1305 GL_CALL(PixelStorei(GR_GL_UNPACK_ALIGNMENT, 1));
1306 for (int i = 0; i < mipLevelCount; ++i) {
1307 if (levelClearMask & (1U << i)) {
1308 int levelWidth = SkTMax(1, texDesc.fSize.width() >> i);
1309 int levelHeight = SkTMax(1, texDesc.fSize.height() >> i);
1310 // Levels only get smaller as we proceed. Once we create a zeros use it for all
1311 // smaller levels that need clearing.
1312 if (!zeros) {
1313 size_t size = levelWidth * levelHeight * bpp;
1314 zeros.reset(new char[size]());
1315 }
1316 this->bindTextureToScratchUnit(GR_GL_TEXTURE_2D, tex->textureID());
1317 GL_CALL(TexSubImage2D(GR_GL_TEXTURE_2D, i, 0, 0, levelWidth, levelHeight,
1318 externalFormat, externalType, zeros.get()));
1319 }
1320 }
1321 }
1322 }
1323 return tex;
1324 }
1325
onCreateCompressedTexture(int width,int height,const GrBackendFormat & format,SkImage::CompressionType compression,SkBudgeted budgeted,const void * data)1326 sk_sp<GrTexture> GrGLGpu::onCreateCompressedTexture(int width, int height,
1327 const GrBackendFormat& format,
1328 SkImage::CompressionType compression,
1329 SkBudgeted budgeted, const void* data) {
1330 GrGLTextureParameters::SamplerOverriddenState initialState;
1331 GrGLTexture::Desc desc;
1332 desc.fSize = {width, height};
1333 desc.fTarget = GR_GL_TEXTURE_2D;
1334 desc.fConfig = GrCompressionTypePixelConfig(compression);
1335 desc.fOwnership = GrBackendObjectOwnership::kOwned;
1336 desc.fFormat = format.asGLFormat();
1337 desc.fID = this->createCompressedTexture2D(desc.fSize, desc.fFormat, compression, &initialState,
1338 data);
1339 if (!desc.fID) {
1340 return nullptr;
1341 }
1342 auto tex = sk_make_sp<GrGLTexture>(this, budgeted, desc, GrMipMapsStatus::kNotAllocated);
1343 // The non-sampler params are still at their default values.
1344 tex->parameters()->set(&initialState, GrGLTextureParameters::NonsamplerState(),
1345 fResetTimestampForTextureParameters);
1346 return tex;
1347 }
1348
1349 namespace {
1350
1351 const GrGLuint kUnknownBitCount = GrGLStencilAttachment::kUnknownBitCount;
1352
get_stencil_rb_sizes(const GrGLInterface * gl,GrGLStencilAttachment::Format * format)1353 void inline get_stencil_rb_sizes(const GrGLInterface* gl,
1354 GrGLStencilAttachment::Format* format) {
1355
1356 // we shouldn't ever know one size and not the other
1357 SkASSERT((kUnknownBitCount == format->fStencilBits) ==
1358 (kUnknownBitCount == format->fTotalBits));
1359 if (kUnknownBitCount == format->fStencilBits) {
1360 GR_GL_GetRenderbufferParameteriv(gl, GR_GL_RENDERBUFFER,
1361 GR_GL_RENDERBUFFER_STENCIL_SIZE,
1362 (GrGLint*)&format->fStencilBits);
1363 if (format->fPacked) {
1364 GR_GL_GetRenderbufferParameteriv(gl, GR_GL_RENDERBUFFER,
1365 GR_GL_RENDERBUFFER_DEPTH_SIZE,
1366 (GrGLint*)&format->fTotalBits);
1367 format->fTotalBits += format->fStencilBits;
1368 } else {
1369 format->fTotalBits = format->fStencilBits;
1370 }
1371 }
1372 }
1373 }
1374
getCompatibleStencilIndex(GrGLFormat format)1375 int GrGLGpu::getCompatibleStencilIndex(GrGLFormat format) {
1376 static const int kSize = 16;
1377 SkASSERT(this->glCaps().canFormatBeFBOColorAttachment(format));
1378
1379 if (!this->glCaps().hasStencilFormatBeenDeterminedForFormat(format)) {
1380 // Default to unsupported, set this if we find a stencil format that works.
1381 int firstWorkingStencilFormatIndex = -1;
1382
1383 GrGLuint colorID =
1384 this->createTexture2D({kSize, kSize}, format, GrRenderable::kYes, nullptr, 1);
1385 if (!colorID) {
1386 return -1;
1387 }
1388 // unbind the texture from the texture unit before binding it to the frame buffer
1389 GL_CALL(BindTexture(GR_GL_TEXTURE_2D, 0));
1390
1391 // Create Framebuffer
1392 GrGLuint fb = 0;
1393 GL_CALL(GenFramebuffers(1, &fb));
1394 this->bindFramebuffer(GR_GL_FRAMEBUFFER, fb);
1395 fHWBoundRenderTargetUniqueID.makeInvalid();
1396 GL_CALL(FramebufferTexture2D(GR_GL_FRAMEBUFFER,
1397 GR_GL_COLOR_ATTACHMENT0,
1398 GR_GL_TEXTURE_2D,
1399 colorID,
1400 0));
1401 GrGLuint sbRBID = 0;
1402 GL_CALL(GenRenderbuffers(1, &sbRBID));
1403
1404 // look over formats till I find a compatible one
1405 int stencilFmtCnt = this->glCaps().stencilFormats().count();
1406 if (sbRBID) {
1407 GL_CALL(BindRenderbuffer(GR_GL_RENDERBUFFER, sbRBID));
1408 for (int i = 0; i < stencilFmtCnt && sbRBID; ++i) {
1409 const GrGLCaps::StencilFormat& sFmt = this->glCaps().stencilFormats()[i];
1410 CLEAR_ERROR_BEFORE_ALLOC(this->glInterface());
1411 GL_ALLOC_CALL(this->glInterface(), RenderbufferStorage(GR_GL_RENDERBUFFER,
1412 sFmt.fInternalFormat,
1413 kSize, kSize));
1414 if (GR_GL_NO_ERROR == CHECK_ALLOC_ERROR(this->glInterface())) {
1415 GL_CALL(FramebufferRenderbuffer(GR_GL_FRAMEBUFFER,
1416 GR_GL_STENCIL_ATTACHMENT,
1417 GR_GL_RENDERBUFFER, sbRBID));
1418 if (sFmt.fPacked) {
1419 GL_CALL(FramebufferRenderbuffer(GR_GL_FRAMEBUFFER,
1420 GR_GL_DEPTH_ATTACHMENT,
1421 GR_GL_RENDERBUFFER, sbRBID));
1422 } else {
1423 GL_CALL(FramebufferRenderbuffer(GR_GL_FRAMEBUFFER,
1424 GR_GL_DEPTH_ATTACHMENT,
1425 GR_GL_RENDERBUFFER, 0));
1426 }
1427 GrGLenum status;
1428 GL_CALL_RET(status, CheckFramebufferStatus(GR_GL_FRAMEBUFFER));
1429 if (status == GR_GL_FRAMEBUFFER_COMPLETE) {
1430 firstWorkingStencilFormatIndex = i;
1431 break;
1432 }
1433 GL_CALL(FramebufferRenderbuffer(GR_GL_FRAMEBUFFER,
1434 GR_GL_STENCIL_ATTACHMENT,
1435 GR_GL_RENDERBUFFER, 0));
1436 if (sFmt.fPacked) {
1437 GL_CALL(FramebufferRenderbuffer(GR_GL_FRAMEBUFFER,
1438 GR_GL_DEPTH_ATTACHMENT,
1439 GR_GL_RENDERBUFFER, 0));
1440 }
1441 }
1442 }
1443 GL_CALL(DeleteRenderbuffers(1, &sbRBID));
1444 }
1445 GL_CALL(DeleteTextures(1, &colorID));
1446 this->bindFramebuffer(GR_GL_FRAMEBUFFER, 0);
1447 this->deleteFramebuffer(fb);
1448 fGLContext->caps()->setStencilFormatIndexForFormat(format, firstWorkingStencilFormatIndex);
1449 }
1450 return this->glCaps().getStencilFormatIndexForFormat(format);
1451 }
1452
createCompressedTexture2D(const SkISize & size,GrGLFormat format,SkImage::CompressionType compression,GrGLTextureParameters::SamplerOverriddenState * initialState,const void * data)1453 GrGLuint GrGLGpu::createCompressedTexture2D(
1454 const SkISize& size,
1455 GrGLFormat format,
1456 SkImage::CompressionType compression,
1457 GrGLTextureParameters::SamplerOverriddenState* initialState,
1458 const void* data) {
1459 if (format == GrGLFormat::kUnknown) {
1460 return 0;
1461 }
1462 GrGLuint id = 0;
1463 GL_CALL(GenTextures(1, &id));
1464 if (!id) {
1465 return 0;
1466 }
1467
1468 this->bindTextureToScratchUnit(GR_GL_TEXTURE_2D, id);
1469
1470 *initialState = set_initial_texture_params(this->glInterface(), GR_GL_TEXTURE_2D);
1471
1472 if (!this->uploadCompressedTexData(format, compression, size, GR_GL_TEXTURE_2D, data)) {
1473 GL_CALL(DeleteTextures(1, &id));
1474 return 0;
1475 }
1476 return id;
1477 }
1478
createTexture2D(const SkISize & size,GrGLFormat format,GrRenderable renderable,GrGLTextureParameters::SamplerOverriddenState * initialState,int mipLevelCount)1479 GrGLuint GrGLGpu::createTexture2D(const SkISize& size,
1480 GrGLFormat format,
1481 GrRenderable renderable,
1482 GrGLTextureParameters::SamplerOverriddenState* initialState,
1483 int mipLevelCount) {
1484 SkASSERT(format != GrGLFormat::kUnknown);
1485 SkASSERT(!GrGLFormatIsCompressed(format));
1486
1487 GrGLuint id = 0;
1488 GL_CALL(GenTextures(1, &id));
1489
1490 if (!id) {
1491 return 0;
1492 }
1493
1494 this->bindTextureToScratchUnit(GR_GL_TEXTURE_2D, id);
1495
1496 if (GrRenderable::kYes == renderable && this->glCaps().textureUsageSupport()) {
1497 // provides a hint about how this texture will be used
1498 GL_CALL(TexParameteri(GR_GL_TEXTURE_2D, GR_GL_TEXTURE_USAGE, GR_GL_FRAMEBUFFER_ATTACHMENT));
1499 }
1500
1501 if (initialState) {
1502 *initialState = set_initial_texture_params(this->glInterface(), GR_GL_TEXTURE_2D);
1503 } else {
1504 set_initial_texture_params(this->glInterface(), GR_GL_TEXTURE_2D);
1505 }
1506
1507 GrGLenum internalFormat = this->glCaps().getTexImageOrStorageInternalFormat(format);
1508
1509 bool success = false;
1510 if (internalFormat) {
1511 CLEAR_ERROR_BEFORE_ALLOC(this->glInterface());
1512 if (this->glCaps().formatSupportsTexStorage(format)) {
1513 GL_ALLOC_CALL(this->glInterface(),
1514 TexStorage2D(GR_GL_TEXTURE_2D, SkTMax(mipLevelCount, 1), internalFormat,
1515 size.width(), size.height()));
1516 success = (GR_GL_NO_ERROR == CHECK_ALLOC_ERROR(this->glInterface()));
1517 } else {
1518 GrGLenum externalFormat, externalType;
1519 this->glCaps().getTexImageExternalFormatAndType(format, &externalFormat, &externalType);
1520 GrGLenum error = GR_GL_NO_ERROR;
1521 if (externalFormat && externalType) {
1522 for (int level = 0; level < mipLevelCount && error == GR_GL_NO_ERROR; level++) {
1523 const int twoToTheMipLevel = 1 << level;
1524 const int currentWidth = SkTMax(1, size.width() / twoToTheMipLevel);
1525 const int currentHeight = SkTMax(1, size.height() / twoToTheMipLevel);
1526 GL_ALLOC_CALL(
1527 this->glInterface(),
1528 TexImage2D(GR_GL_TEXTURE_2D, level, internalFormat, currentWidth,
1529 currentHeight, 0, externalFormat, externalType, nullptr));
1530 error = CHECK_ALLOC_ERROR(this->glInterface());
1531 }
1532 success = (GR_GL_NO_ERROR == error);
1533 }
1534 }
1535 }
1536 if (success) {
1537 return id;
1538 }
1539 GL_CALL(DeleteTextures(1, &id));
1540 return 0;
1541 }
1542
createStencilAttachmentForRenderTarget(const GrRenderTarget * rt,int width,int height,int numStencilSamples)1543 GrStencilAttachment* GrGLGpu::createStencilAttachmentForRenderTarget(
1544 const GrRenderTarget* rt, int width, int height, int numStencilSamples) {
1545 SkASSERT(width >= rt->width());
1546 SkASSERT(height >= rt->height());
1547
1548 GrGLStencilAttachment::IDDesc sbDesc;
1549
1550 int sIdx = this->getCompatibleStencilIndex(rt->backendFormat().asGLFormat());
1551 if (sIdx < 0) {
1552 return nullptr;
1553 }
1554
1555 if (!sbDesc.fRenderbufferID) {
1556 GL_CALL(GenRenderbuffers(1, &sbDesc.fRenderbufferID));
1557 }
1558 if (!sbDesc.fRenderbufferID) {
1559 return nullptr;
1560 }
1561 GL_CALL(BindRenderbuffer(GR_GL_RENDERBUFFER, sbDesc.fRenderbufferID));
1562 const GrGLCaps::StencilFormat& sFmt = this->glCaps().stencilFormats()[sIdx];
1563 CLEAR_ERROR_BEFORE_ALLOC(this->glInterface());
1564 // we do this "if" so that we don't call the multisample
1565 // version on a GL that doesn't have an MSAA extension.
1566 if (numStencilSamples > 1) {
1567 SkAssertResult(renderbuffer_storage_msaa(*fGLContext,
1568 numStencilSamples,
1569 sFmt.fInternalFormat,
1570 width, height));
1571 } else {
1572 GL_ALLOC_CALL(this->glInterface(), RenderbufferStorage(GR_GL_RENDERBUFFER,
1573 sFmt.fInternalFormat,
1574 width, height));
1575 SkASSERT(GR_GL_NO_ERROR == CHECK_ALLOC_ERROR(this->glInterface()));
1576 }
1577 fStats.incStencilAttachmentCreates();
1578 // After sized formats we attempt an unsized format and take
1579 // whatever sizes GL gives us. In that case we query for the size.
1580 GrGLStencilAttachment::Format format = sFmt;
1581 get_stencil_rb_sizes(this->glInterface(), &format);
1582 GrGLStencilAttachment* stencil = new GrGLStencilAttachment(this,
1583 sbDesc,
1584 width,
1585 height,
1586 numStencilSamples,
1587 format);
1588 return stencil;
1589 }
1590
1591 ////////////////////////////////////////////////////////////////////////////////
1592
onCreateBuffer(size_t size,GrGpuBufferType intendedType,GrAccessPattern accessPattern,const void * data)1593 sk_sp<GrGpuBuffer> GrGLGpu::onCreateBuffer(size_t size, GrGpuBufferType intendedType,
1594 GrAccessPattern accessPattern, const void* data) {
1595 return GrGLBuffer::Make(this, size, intendedType, accessPattern, data);
1596 }
1597
flushScissor(const GrScissorState & scissorState,int rtWidth,int rtHeight,GrSurfaceOrigin rtOrigin)1598 void GrGLGpu::flushScissor(const GrScissorState& scissorState, int rtWidth, int rtHeight,
1599 GrSurfaceOrigin rtOrigin) {
1600 if (scissorState.enabled()) {
1601 auto scissor = GrNativeRect::MakeRelativeTo(rtOrigin, rtHeight, scissorState.rect());
1602 // if the scissor fully contains the viewport then we fall through and
1603 // disable the scissor test.
1604 if (!scissor.contains(rtWidth, rtHeight)) {
1605 if (fHWScissorSettings.fRect != scissor) {
1606 GL_CALL(Scissor(scissor.fX, scissor.fY, scissor.fWidth, scissor.fHeight));
1607 fHWScissorSettings.fRect = scissor;
1608 }
1609 if (kYes_TriState != fHWScissorSettings.fEnabled) {
1610 GL_CALL(Enable(GR_GL_SCISSOR_TEST));
1611 fHWScissorSettings.fEnabled = kYes_TriState;
1612 }
1613 return;
1614 }
1615 }
1616
1617 // See fall through note above
1618 this->disableScissor();
1619 }
1620
flushWindowRectangles(const GrWindowRectsState & windowState,const GrGLRenderTarget * rt,GrSurfaceOrigin origin)1621 void GrGLGpu::flushWindowRectangles(const GrWindowRectsState& windowState,
1622 const GrGLRenderTarget* rt, GrSurfaceOrigin origin) {
1623 #ifndef USE_NSIGHT
1624 typedef GrWindowRectsState::Mode Mode;
1625 SkASSERT(!windowState.enabled() || rt->renderFBOID()); // Window rects can't be used on-screen.
1626 SkASSERT(windowState.numWindows() <= this->caps()->maxWindowRectangles());
1627
1628 if (!this->caps()->maxWindowRectangles() ||
1629 fHWWindowRectsState.knownEqualTo(origin, rt->width(), rt->height(), windowState)) {
1630 return;
1631 }
1632
1633 // This is purely a workaround for a spurious warning generated by gcc. Otherwise the above
1634 // assert would be sufficient. https://gcc.gnu.org/bugzilla/show_bug.cgi?id=5912
1635 int numWindows = SkTMin(windowState.numWindows(), int(GrWindowRectangles::kMaxWindows));
1636 SkASSERT(windowState.numWindows() == numWindows);
1637
1638 GrNativeRect glwindows[GrWindowRectangles::kMaxWindows];
1639 const SkIRect* skwindows = windowState.windows().data();
1640 for (int i = 0; i < numWindows; ++i) {
1641 glwindows[i].setRelativeTo(origin, rt->height(), skwindows[i]);
1642 }
1643
1644 GrGLenum glmode = (Mode::kExclusive == windowState.mode()) ? GR_GL_EXCLUSIVE : GR_GL_INCLUSIVE;
1645 GL_CALL(WindowRectangles(glmode, numWindows, glwindows->asInts()));
1646
1647 fHWWindowRectsState.set(origin, rt->width(), rt->height(), windowState);
1648 #endif
1649 }
1650
disableWindowRectangles()1651 void GrGLGpu::disableWindowRectangles() {
1652 #ifndef USE_NSIGHT
1653 if (!this->caps()->maxWindowRectangles() || fHWWindowRectsState.knownDisabled()) {
1654 return;
1655 }
1656 GL_CALL(WindowRectangles(GR_GL_EXCLUSIVE, 0, nullptr));
1657 fHWWindowRectsState.setDisabled();
1658 #endif
1659 }
1660
flushGLState(GrRenderTarget * renderTarget,const GrProgramInfo & programInfo,GrPrimitiveType primitiveType)1661 bool GrGLGpu::flushGLState(GrRenderTarget* renderTarget,
1662 const GrProgramInfo& programInfo,
1663 GrPrimitiveType primitiveType) {
1664
1665 sk_sp<GrGLProgram> program(fProgramCache->refProgram(this, renderTarget, programInfo,
1666 primitiveType));
1667 if (!program) {
1668 GrCapsDebugf(this->caps(), "Failed to create program!\n");
1669 return false;
1670 }
1671
1672 this->flushProgram(std::move(program));
1673
1674 // Swizzle the blend to match what the shader will output.
1675 this->flushBlendAndColorWrite(programInfo.pipeline().getXferProcessor().getBlendInfo(),
1676 programInfo.pipeline().outputSwizzle());
1677
1678 fHWProgram->updateUniformsAndTextureBindings(renderTarget, programInfo);
1679
1680 GrGLRenderTarget* glRT = static_cast<GrGLRenderTarget*>(renderTarget);
1681 GrStencilSettings stencil;
1682 if (programInfo.pipeline().isStencilEnabled()) {
1683 // TODO: attach stencil and create settings during render target flush.
1684 SkASSERT(glRT->renderTargetPriv().getStencilAttachment());
1685 stencil.reset(*programInfo.pipeline().getUserStencil(),
1686 programInfo.pipeline().hasStencilClip(),
1687 glRT->renderTargetPriv().numStencilBits());
1688 }
1689 this->flushStencil(stencil, programInfo.origin());
1690 if (programInfo.pipeline().isScissorEnabled()) {
1691 static constexpr SkIRect kBogusScissor{0, 0, 1, 1};
1692 GrScissorState state(programInfo.fixedDynamicState() ? programInfo.fixedScissor()
1693 : kBogusScissor);
1694 this->flushScissor(state, glRT->width(), glRT->height(), programInfo.origin());
1695 } else {
1696 this->disableScissor();
1697 }
1698 this->flushWindowRectangles(programInfo.pipeline().getWindowRectsState(),
1699 glRT, programInfo.origin());
1700 this->flushHWAAState(glRT, programInfo.pipeline().isHWAntialiasState());
1701
1702 // This must come after textures are flushed because a texture may need
1703 // to be msaa-resolved (which will modify bound FBO state).
1704 this->flushRenderTarget(glRT);
1705
1706 return true;
1707 }
1708
flushProgram(sk_sp<GrGLProgram> program)1709 void GrGLGpu::flushProgram(sk_sp<GrGLProgram> program) {
1710 if (!program) {
1711 fHWProgram.reset();
1712 fHWProgramID = 0;
1713 return;
1714 }
1715 SkASSERT((program == fHWProgram) == (fHWProgramID == program->programID()));
1716 if (program == fHWProgram) {
1717 return;
1718 }
1719 auto id = program->programID();
1720 SkASSERT(id);
1721 GL_CALL(UseProgram(id));
1722 fHWProgram = std::move(program);
1723 fHWProgramID = id;
1724 }
1725
flushProgram(GrGLuint id)1726 void GrGLGpu::flushProgram(GrGLuint id) {
1727 SkASSERT(id);
1728 if (fHWProgramID == id) {
1729 SkASSERT(!fHWProgram);
1730 return;
1731 }
1732 fHWProgram.reset();
1733 GL_CALL(UseProgram(id));
1734 fHWProgramID = id;
1735 }
1736
setupGeometry(const GrBuffer * indexBuffer,const GrBuffer * vertexBuffer,int baseVertex,const GrBuffer * instanceBuffer,int baseInstance,GrPrimitiveRestart enablePrimitiveRestart)1737 void GrGLGpu::setupGeometry(const GrBuffer* indexBuffer,
1738 const GrBuffer* vertexBuffer,
1739 int baseVertex,
1740 const GrBuffer* instanceBuffer,
1741 int baseInstance,
1742 GrPrimitiveRestart enablePrimitiveRestart) {
1743 SkASSERT((enablePrimitiveRestart == GrPrimitiveRestart::kNo) || indexBuffer);
1744
1745 GrGLAttribArrayState* attribState;
1746 if (indexBuffer) {
1747 SkASSERT(indexBuffer->isCpuBuffer() ||
1748 !static_cast<const GrGpuBuffer*>(indexBuffer)->isMapped());
1749 attribState = fHWVertexArrayState.bindInternalVertexArray(this, indexBuffer);
1750 } else {
1751 attribState = fHWVertexArrayState.bindInternalVertexArray(this);
1752 }
1753
1754 int numAttribs = fHWProgram->numVertexAttributes() + fHWProgram->numInstanceAttributes();
1755 attribState->enableVertexArrays(this, numAttribs, enablePrimitiveRestart);
1756
1757 if (int vertexStride = fHWProgram->vertexStride()) {
1758 SkASSERT(vertexBuffer);
1759 SkASSERT(vertexBuffer->isCpuBuffer() ||
1760 !static_cast<const GrGpuBuffer*>(vertexBuffer)->isMapped());
1761 size_t bufferOffset = baseVertex * static_cast<size_t>(vertexStride);
1762 for (int i = 0; i < fHWProgram->numVertexAttributes(); ++i) {
1763 const auto& attrib = fHWProgram->vertexAttribute(i);
1764 static constexpr int kDivisor = 0;
1765 attribState->set(this, attrib.fLocation, vertexBuffer, attrib.fCPUType, attrib.fGPUType,
1766 vertexStride, bufferOffset + attrib.fOffset, kDivisor);
1767 }
1768 }
1769 if (int instanceStride = fHWProgram->instanceStride()) {
1770 SkASSERT(instanceBuffer);
1771 SkASSERT(instanceBuffer->isCpuBuffer() ||
1772 !static_cast<const GrGpuBuffer*>(instanceBuffer)->isMapped());
1773 size_t bufferOffset = baseInstance * static_cast<size_t>(instanceStride);
1774 int attribIdx = fHWProgram->numVertexAttributes();
1775 for (int i = 0; i < fHWProgram->numInstanceAttributes(); ++i, ++attribIdx) {
1776 const auto& attrib = fHWProgram->instanceAttribute(i);
1777 static constexpr int kDivisor = 1;
1778 attribState->set(this, attrib.fLocation, instanceBuffer, attrib.fCPUType,
1779 attrib.fGPUType, instanceStride, bufferOffset + attrib.fOffset,
1780 kDivisor);
1781 }
1782 }
1783 }
1784
bindBuffer(GrGpuBufferType type,const GrBuffer * buffer)1785 GrGLenum GrGLGpu::bindBuffer(GrGpuBufferType type, const GrBuffer* buffer) {
1786 this->handleDirtyContext();
1787
1788 // Index buffer state is tied to the vertex array.
1789 if (GrGpuBufferType::kIndex == type) {
1790 this->bindVertexArray(0);
1791 }
1792
1793 auto* bufferState = this->hwBufferState(type);
1794 if (buffer->isCpuBuffer()) {
1795 if (!bufferState->fBufferZeroKnownBound) {
1796 GL_CALL(BindBuffer(bufferState->fGLTarget, 0));
1797 bufferState->fBufferZeroKnownBound = true;
1798 bufferState->fBoundBufferUniqueID.makeInvalid();
1799 }
1800 } else if (static_cast<const GrGpuBuffer*>(buffer)->uniqueID() !=
1801 bufferState->fBoundBufferUniqueID) {
1802 const GrGLBuffer* glBuffer = static_cast<const GrGLBuffer*>(buffer);
1803 GL_CALL(BindBuffer(bufferState->fGLTarget, glBuffer->bufferID()));
1804 bufferState->fBufferZeroKnownBound = false;
1805 bufferState->fBoundBufferUniqueID = glBuffer->uniqueID();
1806 }
1807
1808 return bufferState->fGLTarget;
1809 }
disableScissor()1810 void GrGLGpu::disableScissor() {
1811 if (kNo_TriState != fHWScissorSettings.fEnabled) {
1812 GL_CALL(Disable(GR_GL_SCISSOR_TEST));
1813 fHWScissorSettings.fEnabled = kNo_TriState;
1814 return;
1815 }
1816 }
1817
clear(const GrFixedClip & clip,const SkPMColor4f & color,GrRenderTarget * target,GrSurfaceOrigin origin)1818 void GrGLGpu::clear(const GrFixedClip& clip, const SkPMColor4f& color,
1819 GrRenderTarget* target, GrSurfaceOrigin origin) {
1820 // parent class should never let us get here with no RT
1821 SkASSERT(target);
1822 SkASSERT(!this->caps()->performColorClearsAsDraws());
1823 SkASSERT(!clip.scissorEnabled() || !this->caps()->performPartialClearsAsDraws());
1824
1825 this->handleDirtyContext();
1826
1827 GrGLRenderTarget* glRT = static_cast<GrGLRenderTarget*>(target);
1828
1829 if (clip.scissorEnabled()) {
1830 this->flushRenderTarget(glRT, origin, clip.scissorRect());
1831 } else {
1832 this->flushRenderTarget(glRT);
1833 }
1834 this->flushScissor(clip.scissorState(), glRT->width(), glRT->height(), origin);
1835 this->flushWindowRectangles(clip.windowRectsState(), glRT, origin);
1836 this->flushColorWrite(true);
1837 this->flushClearColor(color);
1838 GL_CALL(Clear(GR_GL_COLOR_BUFFER_BIT));
1839 }
1840
clearStencil(GrRenderTarget * target,int clearValue)1841 void GrGLGpu::clearStencil(GrRenderTarget* target, int clearValue) {
1842 SkASSERT(!this->caps()->performStencilClearsAsDraws());
1843
1844 if (!target) {
1845 return;
1846 }
1847
1848 // This should only be called internally when we know we have a stencil buffer.
1849 SkASSERT(target->renderTargetPriv().getStencilAttachment());
1850
1851 GrGLRenderTarget* glRT = static_cast<GrGLRenderTarget*>(target);
1852 this->flushRenderTargetNoColorWrites(glRT);
1853
1854 this->disableScissor();
1855 this->disableWindowRectangles();
1856
1857 GL_CALL(StencilMask(0xffffffff));
1858 GL_CALL(ClearStencil(clearValue));
1859 GL_CALL(Clear(GR_GL_STENCIL_BUFFER_BIT));
1860 fHWStencilSettings.invalidate();
1861 }
1862
use_tiled_rendering(const GrGLCaps & glCaps,const GrOpsRenderPass::StencilLoadAndStoreInfo & stencilLoadStore)1863 static bool use_tiled_rendering(const GrGLCaps& glCaps,
1864 const GrOpsRenderPass::StencilLoadAndStoreInfo& stencilLoadStore) {
1865 // Only use the tiled rendering extension if we can explicitly clear and discard the stencil.
1866 // Otherwise it's faster to just not use it.
1867 return glCaps.tiledRenderingSupport() && GrLoadOp::kClear == stencilLoadStore.fLoadOp &&
1868 GrStoreOp::kDiscard == stencilLoadStore.fStoreOp;
1869 }
1870
beginCommandBuffer(GrRenderTarget * rt,const SkIRect & bounds,GrSurfaceOrigin origin,const GrOpsRenderPass::LoadAndStoreInfo & colorLoadStore,const GrOpsRenderPass::StencilLoadAndStoreInfo & stencilLoadStore)1871 void GrGLGpu::beginCommandBuffer(GrRenderTarget* rt, const SkIRect& bounds, GrSurfaceOrigin origin,
1872 const GrOpsRenderPass::LoadAndStoreInfo& colorLoadStore,
1873 const GrOpsRenderPass::StencilLoadAndStoreInfo& stencilLoadStore) {
1874 SkASSERT(!fIsExecutingCommandBuffer_DebugOnly);
1875
1876 this->handleDirtyContext();
1877
1878 auto glRT = static_cast<GrGLRenderTarget*>(rt);
1879 this->flushRenderTarget(glRT);
1880 SkDEBUGCODE(fIsExecutingCommandBuffer_DebugOnly = true);
1881
1882 if (use_tiled_rendering(this->glCaps(), stencilLoadStore)) {
1883 auto nativeBounds = GrNativeRect::MakeRelativeTo(origin, glRT->height(), bounds);
1884 GrGLbitfield preserveMask = (GrLoadOp::kLoad == colorLoadStore.fLoadOp)
1885 ? GR_GL_COLOR_BUFFER_BIT0 : GR_GL_NONE;
1886 SkASSERT(GrLoadOp::kLoad != stencilLoadStore.fLoadOp); // Handled by use_tiled_rendering().
1887 GL_CALL(StartTiling(nativeBounds.fX, nativeBounds.fY, nativeBounds.fWidth,
1888 nativeBounds.fHeight, preserveMask));
1889 }
1890
1891 GrGLbitfield clearMask = 0;
1892 if (GrLoadOp::kClear == colorLoadStore.fLoadOp) {
1893 SkASSERT(!this->caps()->performColorClearsAsDraws());
1894 this->flushClearColor(colorLoadStore.fClearColor);
1895 this->flushColorWrite(true);
1896 clearMask |= GR_GL_COLOR_BUFFER_BIT;
1897 }
1898 if (GrLoadOp::kClear == stencilLoadStore.fLoadOp) {
1899 SkASSERT(!this->caps()->performStencilClearsAsDraws());
1900 GL_CALL(StencilMask(0xffffffff));
1901 GL_CALL(ClearStencil(0));
1902 clearMask |= GR_GL_STENCIL_BUFFER_BIT;
1903 }
1904 if (clearMask) {
1905 this->disableScissor();
1906 this->disableWindowRectangles();
1907 GL_CALL(Clear(clearMask));
1908 }
1909 }
1910
endCommandBuffer(GrRenderTarget * rt,const GrOpsRenderPass::LoadAndStoreInfo & colorLoadStore,const GrOpsRenderPass::StencilLoadAndStoreInfo & stencilLoadStore)1911 void GrGLGpu::endCommandBuffer(GrRenderTarget* rt,
1912 const GrOpsRenderPass::LoadAndStoreInfo& colorLoadStore,
1913 const GrOpsRenderPass::StencilLoadAndStoreInfo& stencilLoadStore) {
1914 SkASSERT(fIsExecutingCommandBuffer_DebugOnly);
1915
1916 this->handleDirtyContext();
1917
1918 if (rt->uniqueID() != fHWBoundRenderTargetUniqueID) {
1919 // The framebuffer binding changed in the middle of a command buffer. We should have already
1920 // printed a warning during onFBOChanged.
1921 return;
1922 }
1923
1924 if (GrGLCaps::kNone_InvalidateFBType != this->glCaps().invalidateFBType()) {
1925 auto glRT = static_cast<GrGLRenderTarget*>(rt);
1926
1927 SkSTArray<2, GrGLenum> discardAttachments;
1928 if (GrStoreOp::kDiscard == colorLoadStore.fStoreOp) {
1929 discardAttachments.push_back(
1930 (0 == glRT->renderFBOID()) ? GR_GL_COLOR : GR_GL_COLOR_ATTACHMENT0);
1931 }
1932 if (GrStoreOp::kDiscard == stencilLoadStore.fStoreOp) {
1933 discardAttachments.push_back(
1934 (0 == glRT->renderFBOID()) ? GR_GL_STENCIL : GR_GL_STENCIL_ATTACHMENT);
1935 }
1936
1937 if (!discardAttachments.empty()) {
1938 if (GrGLCaps::kInvalidate_InvalidateFBType == this->glCaps().invalidateFBType()) {
1939 GL_CALL(InvalidateFramebuffer(GR_GL_FRAMEBUFFER, discardAttachments.count(),
1940 discardAttachments.begin()));
1941 } else {
1942 SkASSERT(GrGLCaps::kDiscard_InvalidateFBType == this->glCaps().invalidateFBType());
1943 GL_CALL(DiscardFramebuffer(GR_GL_FRAMEBUFFER, discardAttachments.count(),
1944 discardAttachments.begin()));
1945 }
1946 }
1947 }
1948
1949 if (use_tiled_rendering(this->glCaps(), stencilLoadStore)) {
1950 GrGLbitfield preserveMask = (GrStoreOp::kStore == colorLoadStore.fStoreOp)
1951 ? GR_GL_COLOR_BUFFER_BIT0 : GR_GL_NONE;
1952 // Handled by use_tiled_rendering().
1953 SkASSERT(GrStoreOp::kStore != stencilLoadStore.fStoreOp);
1954 GL_CALL(EndTiling(preserveMask));
1955 }
1956
1957 SkDEBUGCODE(fIsExecutingCommandBuffer_DebugOnly = false);
1958 }
1959
clearStencilClip(const GrFixedClip & clip,bool insideStencilMask,GrRenderTarget * target,GrSurfaceOrigin origin)1960 void GrGLGpu::clearStencilClip(const GrFixedClip& clip,
1961 bool insideStencilMask,
1962 GrRenderTarget* target, GrSurfaceOrigin origin) {
1963 SkASSERT(target);
1964 SkASSERT(!this->caps()->performStencilClearsAsDraws());
1965 this->handleDirtyContext();
1966
1967 GrStencilAttachment* sb = target->renderTargetPriv().getStencilAttachment();
1968 // this should only be called internally when we know we have a
1969 // stencil buffer.
1970 SkASSERT(sb);
1971 GrGLint stencilBitCount = sb->bits();
1972 #if 0
1973 SkASSERT(stencilBitCount > 0);
1974 GrGLint clipStencilMask = (1 << (stencilBitCount - 1));
1975 #else
1976 // we could just clear the clip bit but when we go through
1977 // ANGLE a partial stencil mask will cause clears to be
1978 // turned into draws. Our contract on GrOpsTask says that
1979 // changing the clip between stencil passes may or may not
1980 // zero the client's clip bits. So we just clear the whole thing.
1981 static const GrGLint clipStencilMask = ~0;
1982 #endif
1983 GrGLint value;
1984 if (insideStencilMask) {
1985 value = (1 << (stencilBitCount - 1));
1986 } else {
1987 value = 0;
1988 }
1989 GrGLRenderTarget* glRT = static_cast<GrGLRenderTarget*>(target);
1990 this->flushRenderTargetNoColorWrites(glRT);
1991
1992 this->flushScissor(clip.scissorState(), glRT->width(), glRT->height(), origin);
1993 this->flushWindowRectangles(clip.windowRectsState(), glRT, origin);
1994
1995 GL_CALL(StencilMask((uint32_t) clipStencilMask));
1996 GL_CALL(ClearStencil(value));
1997 GL_CALL(Clear(GR_GL_STENCIL_BUFFER_BIT));
1998 fHWStencilSettings.invalidate();
1999 }
2000
readOrTransferPixelsFrom(GrSurface * surface,int left,int top,int width,int height,GrColorType surfaceColorType,GrColorType dstColorType,void * offsetOrPtr,int rowWidthInPixels)2001 bool GrGLGpu::readOrTransferPixelsFrom(GrSurface* surface, int left, int top, int width, int height,
2002 GrColorType surfaceColorType, GrColorType dstColorType,
2003 void* offsetOrPtr, int rowWidthInPixels) {
2004 SkASSERT(surface);
2005
2006 auto format = surface->backendFormat().asGLFormat();
2007 GrGLRenderTarget* renderTarget = static_cast<GrGLRenderTarget*>(surface->asRenderTarget());
2008 if (!renderTarget && !this->glCaps().isFormatRenderable(format, 1)) {
2009 return false;
2010 }
2011 GrGLenum externalFormat = 0;
2012 GrGLenum externalType = 0;
2013 this->glCaps().getReadPixelsFormat(surface->backendFormat().asGLFormat(),
2014 surfaceColorType,
2015 dstColorType,
2016 &externalFormat,
2017 &externalType);
2018 if (!externalFormat || !externalType) {
2019 return false;
2020 }
2021
2022 if (renderTarget) {
2023 if (renderTarget->numSamples() <= 1 ||
2024 renderTarget->renderFBOID() == renderTarget->textureFBOID()) { // Also catches FBO 0.
2025 SkASSERT(!renderTarget->requiresManualMSAAResolve());
2026 this->flushRenderTargetNoColorWrites(renderTarget);
2027 } else if (GrGLRenderTarget::kUnresolvableFBOID == renderTarget->textureFBOID()) {
2028 SkASSERT(!renderTarget->requiresManualMSAAResolve());
2029 return false;
2030 } else {
2031 SkASSERT(renderTarget->requiresManualMSAAResolve());
2032 // we don't track the state of the READ FBO ID.
2033 this->bindFramebuffer(GR_GL_READ_FRAMEBUFFER, renderTarget->textureFBOID());
2034 }
2035 } else {
2036 // Use a temporary FBO.
2037 this->bindSurfaceFBOForPixelOps(surface, 0, GR_GL_FRAMEBUFFER, kSrc_TempFBOTarget);
2038 fHWBoundRenderTargetUniqueID.makeInvalid();
2039 }
2040
2041 // the read rect is viewport-relative
2042 GrNativeRect readRect = {left, top, width, height};
2043
2044 // determine if GL can read using the passed rowBytes or if we need a scratch buffer.
2045 if (rowWidthInPixels != width) {
2046 SkASSERT(this->glCaps().readPixelsRowBytesSupport());
2047 GL_CALL(PixelStorei(GR_GL_PACK_ROW_LENGTH, rowWidthInPixels));
2048 }
2049 GL_CALL(PixelStorei(GR_GL_PACK_ALIGNMENT, 1));
2050
2051 bool reattachStencil = false;
2052 if (this->glCaps().detachStencilFromMSAABuffersBeforeReadPixels() &&
2053 renderTarget &&
2054 renderTarget->renderTargetPriv().getStencilAttachment() &&
2055 renderTarget->numSamples() > 1) {
2056 // Fix Adreno devices that won't read from MSAA framebuffers with stencil attached
2057 reattachStencil = true;
2058 GL_CALL(FramebufferRenderbuffer(GR_GL_FRAMEBUFFER, GR_GL_STENCIL_ATTACHMENT,
2059 GR_GL_RENDERBUFFER, 0));
2060 }
2061
2062 GL_CALL(ReadPixels(readRect.fX, readRect.fY, readRect.fWidth, readRect.fHeight,
2063 externalFormat, externalType, offsetOrPtr));
2064
2065 if (reattachStencil) {
2066 GrGLStencilAttachment* stencilAttachment = static_cast<GrGLStencilAttachment*>(
2067 renderTarget->renderTargetPriv().getStencilAttachment());
2068 GL_CALL(FramebufferRenderbuffer(GR_GL_FRAMEBUFFER, GR_GL_STENCIL_ATTACHMENT,
2069 GR_GL_RENDERBUFFER, stencilAttachment->renderbufferID()));
2070 }
2071
2072 if (rowWidthInPixels != width) {
2073 SkASSERT(this->glCaps().readPixelsRowBytesSupport());
2074 GL_CALL(PixelStorei(GR_GL_PACK_ROW_LENGTH, 0));
2075 }
2076
2077 if (!renderTarget) {
2078 this->unbindSurfaceFBOForPixelOps(surface, 0, GR_GL_FRAMEBUFFER);
2079 }
2080 return true;
2081 }
2082
onReadPixels(GrSurface * surface,int left,int top,int width,int height,GrColorType surfaceColorType,GrColorType dstColorType,void * buffer,size_t rowBytes)2083 bool GrGLGpu::onReadPixels(GrSurface* surface, int left, int top, int width, int height,
2084 GrColorType surfaceColorType, GrColorType dstColorType, void* buffer,
2085 size_t rowBytes) {
2086 SkASSERT(surface);
2087
2088 size_t bytesPerPixel = GrColorTypeBytesPerPixel(dstColorType);
2089
2090 // GL_PACK_ROW_LENGTH is in terms of pixels not bytes.
2091 int rowPixelWidth;
2092
2093 if (rowBytes == SkToSizeT(width * bytesPerPixel)) {
2094 rowPixelWidth = width;
2095 } else {
2096 SkASSERT(!(rowBytes % bytesPerPixel));
2097 rowPixelWidth = rowBytes / bytesPerPixel;
2098 }
2099 return this->readOrTransferPixelsFrom(surface, left, top, width, height, surfaceColorType,
2100 dstColorType, buffer, rowPixelWidth);
2101 }
2102
getOpsRenderPass(GrRenderTarget * rt,GrSurfaceOrigin origin,const SkIRect & bounds,const GrOpsRenderPass::LoadAndStoreInfo & colorInfo,const GrOpsRenderPass::StencilLoadAndStoreInfo & stencilInfo,const SkTArray<GrTextureProxy *,true> & sampledProxies)2103 GrOpsRenderPass* GrGLGpu::getOpsRenderPass(
2104 GrRenderTarget* rt, GrSurfaceOrigin origin, const SkIRect& bounds,
2105 const GrOpsRenderPass::LoadAndStoreInfo& colorInfo,
2106 const GrOpsRenderPass::StencilLoadAndStoreInfo& stencilInfo,
2107 const SkTArray<GrTextureProxy*, true>& sampledProxies) {
2108 if (!fCachedOpsRenderPass) {
2109 fCachedOpsRenderPass.reset(new GrGLOpsRenderPass(this));
2110 }
2111
2112 fCachedOpsRenderPass->set(rt, bounds, origin, colorInfo, stencilInfo);
2113 return fCachedOpsRenderPass.get();
2114 }
2115
flushRenderTarget(GrGLRenderTarget * target,GrSurfaceOrigin origin,const SkIRect & bounds)2116 void GrGLGpu::flushRenderTarget(GrGLRenderTarget* target, GrSurfaceOrigin origin,
2117 const SkIRect& bounds) {
2118 this->flushRenderTargetNoColorWrites(target);
2119 this->didWriteToSurface(target, origin, &bounds);
2120 }
2121
flushRenderTarget(GrGLRenderTarget * target)2122 void GrGLGpu::flushRenderTarget(GrGLRenderTarget* target) {
2123 this->flushRenderTargetNoColorWrites(target);
2124 this->didWriteToSurface(target, kTopLeft_GrSurfaceOrigin, nullptr);
2125 }
2126
flushRenderTargetNoColorWrites(GrGLRenderTarget * target)2127 void GrGLGpu::flushRenderTargetNoColorWrites(GrGLRenderTarget* target) {
2128 SkASSERT(target);
2129 GrGpuResource::UniqueID rtID = target->uniqueID();
2130 if (fHWBoundRenderTargetUniqueID != rtID) {
2131 this->bindFramebuffer(GR_GL_FRAMEBUFFER, target->renderFBOID());
2132 #ifdef SK_DEBUG
2133 // don't do this check in Chromium -- this is causing
2134 // lots of repeated command buffer flushes when the compositor is
2135 // rendering with Ganesh, which is really slow; even too slow for
2136 // Debug mode.
2137 if (kChromium_GrGLDriver != this->glContext().driver()) {
2138 GrGLenum status;
2139 GL_CALL_RET(status, CheckFramebufferStatus(GR_GL_FRAMEBUFFER));
2140 if (status != GR_GL_FRAMEBUFFER_COMPLETE) {
2141 SkDebugf("GrGLGpu::flushRenderTarget glCheckFramebufferStatus %x\n", status);
2142 }
2143 }
2144 #endif
2145 fHWBoundRenderTargetUniqueID = rtID;
2146 this->flushViewport(target->width(), target->height());
2147 }
2148
2149 if (this->glCaps().srgbWriteControl()) {
2150 this->flushFramebufferSRGB(this->caps()->isFormatSRGB(target->backendFormat()));
2151 }
2152 }
2153
flushFramebufferSRGB(bool enable)2154 void GrGLGpu::flushFramebufferSRGB(bool enable) {
2155 if (enable && kYes_TriState != fHWSRGBFramebuffer) {
2156 GL_CALL(Enable(GR_GL_FRAMEBUFFER_SRGB));
2157 fHWSRGBFramebuffer = kYes_TriState;
2158 } else if (!enable && kNo_TriState != fHWSRGBFramebuffer) {
2159 GL_CALL(Disable(GR_GL_FRAMEBUFFER_SRGB));
2160 fHWSRGBFramebuffer = kNo_TriState;
2161 }
2162 }
2163
flushViewport(int width,int height)2164 void GrGLGpu::flushViewport(int width, int height) {
2165 GrNativeRect viewport = {0, 0, width, height};
2166 if (fHWViewport != viewport) {
2167 GL_CALL(Viewport(viewport.fX, viewport.fY, viewport.fWidth, viewport.fHeight));
2168 fHWViewport = viewport;
2169 }
2170 }
2171
2172 #define SWAP_PER_DRAW 0
2173
2174 #if SWAP_PER_DRAW
2175 #if defined(SK_BUILD_FOR_MAC)
2176 #include <AGL/agl.h>
2177 #elif defined(SK_BUILD_FOR_WIN)
2178 #include <gl/GL.h>
SwapBuf()2179 void SwapBuf() {
2180 DWORD procID = GetCurrentProcessId();
2181 HWND hwnd = GetTopWindow(GetDesktopWindow());
2182 while(hwnd) {
2183 DWORD wndProcID = 0;
2184 GetWindowThreadProcessId(hwnd, &wndProcID);
2185 if(wndProcID == procID) {
2186 SwapBuffers(GetDC(hwnd));
2187 }
2188 hwnd = GetNextWindow(hwnd, GW_HWNDNEXT);
2189 }
2190 }
2191 #endif
2192 #endif
2193
draw(GrRenderTarget * renderTarget,const GrProgramInfo & programInfo,const GrMesh meshes[],int meshCount)2194 void GrGLGpu::draw(GrRenderTarget* renderTarget,
2195 const GrProgramInfo& programInfo,
2196 const GrMesh meshes[],
2197 int meshCount) {
2198 this->handleDirtyContext();
2199
2200 SkASSERT(meshCount); // guaranteed by GrOpsRenderPass::draw
2201
2202 GrPrimitiveType primitiveType = meshes[0].primitiveType();
2203
2204 #ifdef SK_DEBUG
2205 // kPoints should never be intermingled in with the other primitive types
2206 for (int i = 1; i < meshCount; ++i) {
2207 if (primitiveType == GrPrimitiveType::kPoints) {
2208 SkASSERT(meshes[i].primitiveType() == GrPrimitiveType::kPoints);
2209 } else {
2210 SkASSERT(meshes[i].primitiveType() != GrPrimitiveType::kPoints);
2211 }
2212 }
2213 #endif
2214
2215 // Passing 'primitiveType' here is a bit misleading. In GL's case it works out, since
2216 // GL only cares if it is kPoints or not.
2217 if (!this->flushGLState(renderTarget, programInfo, primitiveType)) {
2218 return;
2219 }
2220
2221 bool hasDynamicScissors = programInfo.hasDynamicScissors();
2222 bool hasDynamicPrimProcTextures = programInfo.hasDynamicPrimProcTextures();
2223
2224 for (int m = 0; m < meshCount; ++m) {
2225 if (auto barrierType = programInfo.pipeline().xferBarrierType(renderTarget->asTexture(),
2226 *this->caps())) {
2227 this->xferBarrier(renderTarget, barrierType);
2228 }
2229
2230 if (hasDynamicScissors) {
2231 GrGLRenderTarget* glRT = static_cast<GrGLRenderTarget*>(renderTarget);
2232 this->flushScissor(GrScissorState(programInfo.dynamicScissor(m)),
2233 glRT->width(), glRT->height(), programInfo.origin());
2234 }
2235 if (hasDynamicPrimProcTextures) {
2236 auto texProxyArray = programInfo.dynamicPrimProcTextures(m);
2237 fHWProgram->updatePrimitiveProcessorTextureBindings(programInfo.primProc(),
2238 texProxyArray);
2239 }
2240 if (this->glCaps().requiresCullFaceEnableDisableWhenDrawingLinesAfterNonLines() &&
2241 GrIsPrimTypeLines(meshes[m].primitiveType()) &&
2242 !GrIsPrimTypeLines(fLastPrimitiveType)) {
2243 GL_CALL(Enable(GR_GL_CULL_FACE));
2244 GL_CALL(Disable(GR_GL_CULL_FACE));
2245 }
2246 meshes[m].sendToGpu(this);
2247 fLastPrimitiveType = meshes[m].primitiveType();
2248 }
2249
2250 #if SWAP_PER_DRAW
2251 glFlush();
2252 #if defined(SK_BUILD_FOR_MAC)
2253 aglSwapBuffers(aglGetCurrentContext());
2254 int set_a_break_pt_here = 9;
2255 aglSwapBuffers(aglGetCurrentContext());
2256 #elif defined(SK_BUILD_FOR_WIN)
2257 SwapBuf();
2258 int set_a_break_pt_here = 9;
2259 SwapBuf();
2260 #endif
2261 #endif
2262 }
2263
gr_primitive_type_to_gl_mode(GrPrimitiveType primitiveType)2264 static GrGLenum gr_primitive_type_to_gl_mode(GrPrimitiveType primitiveType) {
2265 switch (primitiveType) {
2266 case GrPrimitiveType::kTriangles:
2267 return GR_GL_TRIANGLES;
2268 case GrPrimitiveType::kTriangleStrip:
2269 return GR_GL_TRIANGLE_STRIP;
2270 case GrPrimitiveType::kPoints:
2271 return GR_GL_POINTS;
2272 case GrPrimitiveType::kLines:
2273 return GR_GL_LINES;
2274 case GrPrimitiveType::kLineStrip:
2275 return GR_GL_LINE_STRIP;
2276 case GrPrimitiveType::kPath:
2277 SK_ABORT("non-mesh-based GrPrimitiveType");
2278 return 0;
2279 }
2280 SK_ABORT("invalid GrPrimitiveType");
2281 }
2282
sendMeshToGpu(GrPrimitiveType primitiveType,const GrBuffer * vertexBuffer,int vertexCount,int baseVertex)2283 void GrGLGpu::sendMeshToGpu(GrPrimitiveType primitiveType, const GrBuffer* vertexBuffer,
2284 int vertexCount, int baseVertex) {
2285 const GrGLenum glPrimType = gr_primitive_type_to_gl_mode(primitiveType);
2286 if (this->glCaps().drawArraysBaseVertexIsBroken()) {
2287 this->setupGeometry(nullptr, vertexBuffer, baseVertex, nullptr, 0, GrPrimitiveRestart::kNo);
2288 GL_CALL(DrawArrays(glPrimType, 0, vertexCount));
2289 } else {
2290 this->setupGeometry(nullptr, vertexBuffer, 0, nullptr, 0, GrPrimitiveRestart::kNo);
2291 GL_CALL(DrawArrays(glPrimType, baseVertex, vertexCount));
2292 }
2293 fStats.incNumDraws();
2294 }
2295
element_ptr(const GrBuffer * indexBuffer,int baseIndex)2296 static const GrGLvoid* element_ptr(const GrBuffer* indexBuffer, int baseIndex) {
2297 size_t baseOffset = baseIndex * sizeof(uint16_t);
2298 if (indexBuffer->isCpuBuffer()) {
2299 return static_cast<const GrCpuBuffer*>(indexBuffer)->data() + baseOffset;
2300 } else {
2301 return reinterpret_cast<const GrGLvoid*>(baseOffset);
2302 }
2303 }
2304
sendIndexedMeshToGpu(GrPrimitiveType primitiveType,const GrBuffer * indexBuffer,int indexCount,int baseIndex,uint16_t minIndexValue,uint16_t maxIndexValue,const GrBuffer * vertexBuffer,int baseVertex,GrPrimitiveRestart enablePrimitiveRestart)2305 void GrGLGpu::sendIndexedMeshToGpu(GrPrimitiveType primitiveType, const GrBuffer* indexBuffer,
2306 int indexCount, int baseIndex, uint16_t minIndexValue,
2307 uint16_t maxIndexValue, const GrBuffer* vertexBuffer,
2308 int baseVertex, GrPrimitiveRestart enablePrimitiveRestart) {
2309 const GrGLenum glPrimType = gr_primitive_type_to_gl_mode(primitiveType);
2310 const GrGLvoid* elementPtr = element_ptr(indexBuffer, baseIndex);
2311
2312 this->setupGeometry(indexBuffer, vertexBuffer, baseVertex, nullptr, 0, enablePrimitiveRestart);
2313
2314 if (this->glCaps().drawRangeElementsSupport()) {
2315 GL_CALL(DrawRangeElements(glPrimType, minIndexValue, maxIndexValue, indexCount,
2316 GR_GL_UNSIGNED_SHORT, elementPtr));
2317 } else {
2318 GL_CALL(DrawElements(glPrimType, indexCount, GR_GL_UNSIGNED_SHORT, elementPtr));
2319 }
2320 fStats.incNumDraws();
2321 }
2322
sendInstancedMeshToGpu(GrPrimitiveType primitiveType,const GrBuffer * vertexBuffer,int vertexCount,int baseVertex,const GrBuffer * instanceBuffer,int instanceCount,int baseInstance)2323 void GrGLGpu::sendInstancedMeshToGpu(GrPrimitiveType primitiveType, const GrBuffer* vertexBuffer,
2324 int vertexCount, int baseVertex,
2325 const GrBuffer* instanceBuffer, int instanceCount,
2326 int baseInstance) {
2327 GrGLenum glPrimType = gr_primitive_type_to_gl_mode(primitiveType);
2328 int maxInstances = this->glCaps().maxInstancesPerDrawWithoutCrashing(instanceCount);
2329 for (int i = 0; i < instanceCount; i += maxInstances) {
2330 this->setupGeometry(nullptr, vertexBuffer, 0, instanceBuffer, baseInstance + i,
2331 GrPrimitiveRestart::kNo);
2332 GL_CALL(DrawArraysInstanced(glPrimType, baseVertex, vertexCount,
2333 SkTMin(instanceCount - i, maxInstances)));
2334 fStats.incNumDraws();
2335 }
2336 }
2337
sendIndexedInstancedMeshToGpu(GrPrimitiveType primitiveType,const GrBuffer * indexBuffer,int indexCount,int baseIndex,const GrBuffer * vertexBuffer,int baseVertex,const GrBuffer * instanceBuffer,int instanceCount,int baseInstance,GrPrimitiveRestart enablePrimitiveRestart)2338 void GrGLGpu::sendIndexedInstancedMeshToGpu(GrPrimitiveType primitiveType,
2339 const GrBuffer* indexBuffer, int indexCount,
2340 int baseIndex, const GrBuffer* vertexBuffer,
2341 int baseVertex, const GrBuffer* instanceBuffer,
2342 int instanceCount, int baseInstance,
2343 GrPrimitiveRestart enablePrimitiveRestart) {
2344 const GrGLenum glPrimType = gr_primitive_type_to_gl_mode(primitiveType);
2345 const GrGLvoid* elementPtr = element_ptr(indexBuffer, baseIndex);
2346 int maxInstances = this->glCaps().maxInstancesPerDrawWithoutCrashing(instanceCount);
2347 for (int i = 0; i < instanceCount; i += maxInstances) {
2348 this->setupGeometry(indexBuffer, vertexBuffer, baseVertex, instanceBuffer, baseInstance + i,
2349 enablePrimitiveRestart);
2350 GL_CALL(DrawElementsInstanced(glPrimType, indexCount, GR_GL_UNSIGNED_SHORT, elementPtr,
2351 SkTMin(instanceCount - i, maxInstances)));
2352 fStats.incNumDraws();
2353 }
2354 }
2355
onResolveRenderTarget(GrRenderTarget * target,const SkIRect & resolveRect,GrSurfaceOrigin resolveOrigin,ForExternalIO)2356 void GrGLGpu::onResolveRenderTarget(GrRenderTarget* target, const SkIRect& resolveRect,
2357 GrSurfaceOrigin resolveOrigin, ForExternalIO) {
2358 // Some extensions automatically resolves the texture when it is read.
2359 SkASSERT(this->glCaps().usesMSAARenderBuffers());
2360
2361 GrGLRenderTarget* rt = static_cast<GrGLRenderTarget*>(target);
2362 SkASSERT(rt->textureFBOID() != rt->renderFBOID());
2363 SkASSERT(rt->textureFBOID() != 0 && rt->renderFBOID() != 0);
2364 this->bindFramebuffer(GR_GL_READ_FRAMEBUFFER, rt->renderFBOID());
2365 this->bindFramebuffer(GR_GL_DRAW_FRAMEBUFFER, rt->textureFBOID());
2366
2367 // make sure we go through flushRenderTarget() since we've modified
2368 // the bound DRAW FBO ID.
2369 fHWBoundRenderTargetUniqueID.makeInvalid();
2370 if (GrGLCaps::kES_Apple_MSFBOType == this->glCaps().msFBOType()) {
2371 // Apple's extension uses the scissor as the blit bounds.
2372 GrScissorState scissorState;
2373 scissorState.set(resolveRect);
2374 this->flushScissor(scissorState, rt->width(), rt->height(), resolveOrigin);
2375 this->disableWindowRectangles();
2376 GL_CALL(ResolveMultisampleFramebuffer());
2377 } else {
2378 int l, b, r, t;
2379 if (GrGLCaps::kResolveMustBeFull_BlitFrambufferFlag &
2380 this->glCaps().blitFramebufferSupportFlags()) {
2381 l = 0;
2382 b = 0;
2383 r = target->width();
2384 t = target->height();
2385 } else {
2386 auto rect = GrNativeRect::MakeRelativeTo(
2387 resolveOrigin, rt->height(), resolveRect);
2388 l = rect.fX;
2389 b = rect.fY;
2390 r = rect.fX + rect.fWidth;
2391 t = rect.fY + rect.fHeight;
2392 }
2393
2394 // BlitFrameBuffer respects the scissor, so disable it.
2395 this->disableScissor();
2396 this->disableWindowRectangles();
2397 GL_CALL(BlitFramebuffer(l, b, r, t, l, b, r, t, GR_GL_COLOR_BUFFER_BIT, GR_GL_NEAREST));
2398 }
2399 }
2400
2401 namespace {
2402
2403
gr_to_gl_stencil_op(GrStencilOp op)2404 GrGLenum gr_to_gl_stencil_op(GrStencilOp op) {
2405 static const GrGLenum gTable[kGrStencilOpCount] = {
2406 GR_GL_KEEP, // kKeep
2407 GR_GL_ZERO, // kZero
2408 GR_GL_REPLACE, // kReplace
2409 GR_GL_INVERT, // kInvert
2410 GR_GL_INCR_WRAP, // kIncWrap
2411 GR_GL_DECR_WRAP, // kDecWrap
2412 GR_GL_INCR, // kIncClamp
2413 GR_GL_DECR, // kDecClamp
2414 };
2415 GR_STATIC_ASSERT(0 == (int)GrStencilOp::kKeep);
2416 GR_STATIC_ASSERT(1 == (int)GrStencilOp::kZero);
2417 GR_STATIC_ASSERT(2 == (int)GrStencilOp::kReplace);
2418 GR_STATIC_ASSERT(3 == (int)GrStencilOp::kInvert);
2419 GR_STATIC_ASSERT(4 == (int)GrStencilOp::kIncWrap);
2420 GR_STATIC_ASSERT(5 == (int)GrStencilOp::kDecWrap);
2421 GR_STATIC_ASSERT(6 == (int)GrStencilOp::kIncClamp);
2422 GR_STATIC_ASSERT(7 == (int)GrStencilOp::kDecClamp);
2423 SkASSERT(op < (GrStencilOp)kGrStencilOpCount);
2424 return gTable[(int)op];
2425 }
2426
set_gl_stencil(const GrGLInterface * gl,const GrStencilSettings::Face & face,GrGLenum glFace)2427 void set_gl_stencil(const GrGLInterface* gl,
2428 const GrStencilSettings::Face& face,
2429 GrGLenum glFace) {
2430 GrGLenum glFunc = GrToGLStencilFunc(face.fTest);
2431 GrGLenum glFailOp = gr_to_gl_stencil_op(face.fFailOp);
2432 GrGLenum glPassOp = gr_to_gl_stencil_op(face.fPassOp);
2433
2434 GrGLint ref = face.fRef;
2435 GrGLint mask = face.fTestMask;
2436 GrGLint writeMask = face.fWriteMask;
2437
2438 if (GR_GL_FRONT_AND_BACK == glFace) {
2439 // we call the combined func just in case separate stencil is not
2440 // supported.
2441 GR_GL_CALL(gl, StencilFunc(glFunc, ref, mask));
2442 GR_GL_CALL(gl, StencilMask(writeMask));
2443 GR_GL_CALL(gl, StencilOp(glFailOp, GR_GL_KEEP, glPassOp));
2444 } else {
2445 GR_GL_CALL(gl, StencilFuncSeparate(glFace, glFunc, ref, mask));
2446 GR_GL_CALL(gl, StencilMaskSeparate(glFace, writeMask));
2447 GR_GL_CALL(gl, StencilOpSeparate(glFace, glFailOp, GR_GL_KEEP, glPassOp));
2448 }
2449 }
2450 }
2451
flushStencil(const GrStencilSettings & stencilSettings,GrSurfaceOrigin origin)2452 void GrGLGpu::flushStencil(const GrStencilSettings& stencilSettings, GrSurfaceOrigin origin) {
2453 if (stencilSettings.isDisabled()) {
2454 this->disableStencil();
2455 } else if (fHWStencilSettings != stencilSettings ||
2456 (stencilSettings.isTwoSided() && fHWStencilOrigin != origin)) {
2457 if (kYes_TriState != fHWStencilTestEnabled) {
2458 GL_CALL(Enable(GR_GL_STENCIL_TEST));
2459
2460 fHWStencilTestEnabled = kYes_TriState;
2461 }
2462 if (stencilSettings.isTwoSided()) {
2463 set_gl_stencil(this->glInterface(), stencilSettings.front(origin), GR_GL_FRONT);
2464 set_gl_stencil(this->glInterface(), stencilSettings.back(origin), GR_GL_BACK);
2465 } else {
2466 set_gl_stencil(
2467 this->glInterface(), stencilSettings.frontAndBack(), GR_GL_FRONT_AND_BACK);
2468 }
2469 fHWStencilSettings = stencilSettings;
2470 fHWStencilOrigin = origin;
2471 }
2472 }
2473
disableStencil()2474 void GrGLGpu::disableStencil() {
2475 if (kNo_TriState != fHWStencilTestEnabled) {
2476 GL_CALL(Disable(GR_GL_STENCIL_TEST));
2477
2478 fHWStencilTestEnabled = kNo_TriState;
2479 fHWStencilSettings.invalidate();
2480 }
2481 }
2482
flushHWAAState(GrRenderTarget * rt,bool useHWAA)2483 void GrGLGpu::flushHWAAState(GrRenderTarget* rt, bool useHWAA) {
2484 // rt is only optional if useHWAA is false.
2485 SkASSERT(rt || !useHWAA);
2486 #ifdef SK_DEBUG
2487 if (useHWAA && rt->numSamples() <= 1) {
2488 SkASSERT(this->caps()->mixedSamplesSupport());
2489 SkASSERT(0 != static_cast<GrGLRenderTarget*>(rt)->renderFBOID());
2490 SkASSERT(rt->renderTargetPriv().getStencilAttachment());
2491 }
2492 #endif
2493
2494 if (this->caps()->multisampleDisableSupport()) {
2495 if (useHWAA) {
2496 if (kYes_TriState != fMSAAEnabled) {
2497 GL_CALL(Enable(GR_GL_MULTISAMPLE));
2498 fMSAAEnabled = kYes_TriState;
2499 }
2500 } else {
2501 if (kNo_TriState != fMSAAEnabled) {
2502 GL_CALL(Disable(GR_GL_MULTISAMPLE));
2503 fMSAAEnabled = kNo_TriState;
2504 }
2505 }
2506 }
2507 }
2508
flushBlendAndColorWrite(const GrXferProcessor::BlendInfo & blendInfo,const GrSwizzle & swizzle)2509 void GrGLGpu::flushBlendAndColorWrite(
2510 const GrXferProcessor::BlendInfo& blendInfo, const GrSwizzle& swizzle) {
2511 if (this->glCaps().neverDisableColorWrites() && !blendInfo.fWriteColor) {
2512 // We need to work around a driver bug by using a blend state that preserves the dst color,
2513 // rather than disabling color writes.
2514 GrXferProcessor::BlendInfo preserveDstBlend;
2515 preserveDstBlend.fSrcBlend = kZero_GrBlendCoeff;
2516 preserveDstBlend.fDstBlend = kOne_GrBlendCoeff;
2517 this->flushBlendAndColorWrite(preserveDstBlend, swizzle);
2518 return;
2519 }
2520
2521 GrBlendEquation equation = blendInfo.fEquation;
2522 GrBlendCoeff srcCoeff = blendInfo.fSrcBlend;
2523 GrBlendCoeff dstCoeff = blendInfo.fDstBlend;
2524
2525 // Any optimization to disable blending should have already been applied and
2526 // tweaked the equation to "add" or "subtract", and the coeffs to (1, 0).
2527 bool blendOff =
2528 ((kAdd_GrBlendEquation == equation || kSubtract_GrBlendEquation == equation) &&
2529 kOne_GrBlendCoeff == srcCoeff && kZero_GrBlendCoeff == dstCoeff) ||
2530 !blendInfo.fWriteColor;
2531
2532 if (blendOff) {
2533 if (kNo_TriState != fHWBlendState.fEnabled) {
2534 GL_CALL(Disable(GR_GL_BLEND));
2535
2536 // Workaround for the ARM KHR_blend_equation_advanced blacklist issue
2537 // https://code.google.com/p/skia/issues/detail?id=3943
2538 if (kARM_GrGLVendor == this->ctxInfo().vendor() &&
2539 GrBlendEquationIsAdvanced(fHWBlendState.fEquation)) {
2540 SkASSERT(this->caps()->advancedBlendEquationSupport());
2541 // Set to any basic blending equation.
2542 GrBlendEquation blend_equation = kAdd_GrBlendEquation;
2543 GL_CALL(BlendEquation(gXfermodeEquation2Blend[blend_equation]));
2544 fHWBlendState.fEquation = blend_equation;
2545 }
2546
2547 fHWBlendState.fEnabled = kNo_TriState;
2548 }
2549 } else {
2550 if (kYes_TriState != fHWBlendState.fEnabled) {
2551 GL_CALL(Enable(GR_GL_BLEND));
2552
2553 fHWBlendState.fEnabled = kYes_TriState;
2554 }
2555
2556 if (fHWBlendState.fEquation != equation) {
2557 GL_CALL(BlendEquation(gXfermodeEquation2Blend[equation]));
2558 fHWBlendState.fEquation = equation;
2559 }
2560
2561 if (GrBlendEquationIsAdvanced(equation)) {
2562 SkASSERT(this->caps()->advancedBlendEquationSupport());
2563 // Advanced equations have no other blend state.
2564 return;
2565 }
2566
2567 if (fHWBlendState.fSrcCoeff != srcCoeff || fHWBlendState.fDstCoeff != dstCoeff) {
2568 GL_CALL(BlendFunc(gXfermodeCoeff2Blend[srcCoeff],
2569 gXfermodeCoeff2Blend[dstCoeff]));
2570 fHWBlendState.fSrcCoeff = srcCoeff;
2571 fHWBlendState.fDstCoeff = dstCoeff;
2572 }
2573
2574 if ((BlendCoeffReferencesConstant(srcCoeff) || BlendCoeffReferencesConstant(dstCoeff))) {
2575 SkPMColor4f blendConst = swizzle.applyTo(blendInfo.fBlendConstant);
2576 if (!fHWBlendState.fConstColorValid || fHWBlendState.fConstColor != blendConst) {
2577 GL_CALL(BlendColor(blendConst.fR, blendConst.fG, blendConst.fB, blendConst.fA));
2578 fHWBlendState.fConstColor = blendConst;
2579 fHWBlendState.fConstColorValid = true;
2580 }
2581 }
2582 }
2583
2584 this->flushColorWrite(blendInfo.fWriteColor);
2585 }
2586
get_gl_swizzle_values(const GrSwizzle & swizzle,GrGLenum glValues[4])2587 static void get_gl_swizzle_values(const GrSwizzle& swizzle, GrGLenum glValues[4]) {
2588 for (int i = 0; i < 4; ++i) {
2589 switch (swizzle[i]) {
2590 case 'r': glValues[i] = GR_GL_RED; break;
2591 case 'g': glValues[i] = GR_GL_GREEN; break;
2592 case 'b': glValues[i] = GR_GL_BLUE; break;
2593 case 'a': glValues[i] = GR_GL_ALPHA; break;
2594 case '0': glValues[i] = GR_GL_ZERO; break;
2595 case '1': glValues[i] = GR_GL_ONE; break;
2596 default: SK_ABORT("Unsupported component");
2597 }
2598 }
2599 }
2600
bindTexture(int unitIdx,GrSamplerState samplerState,const GrSwizzle & swizzle,GrGLTexture * texture)2601 void GrGLGpu::bindTexture(int unitIdx, GrSamplerState samplerState, const GrSwizzle& swizzle,
2602 GrGLTexture* texture) {
2603 SkASSERT(texture);
2604
2605 #ifdef SK_DEBUG
2606 if (!this->caps()->npotTextureTileSupport()) {
2607 if (samplerState.isRepeated()) {
2608 const int w = texture->width();
2609 const int h = texture->height();
2610 SkASSERT(SkIsPow2(w) && SkIsPow2(h));
2611 }
2612 }
2613 #endif
2614
2615 GrGpuResource::UniqueID textureID = texture->uniqueID();
2616 GrGLenum target = texture->target();
2617 if (fHWTextureUnitBindings[unitIdx].boundID(target) != textureID) {
2618 this->setTextureUnit(unitIdx);
2619 GL_CALL(BindTexture(target, texture->textureID()));
2620 fHWTextureUnitBindings[unitIdx].setBoundID(target, textureID);
2621 }
2622
2623 if (samplerState.filter() == GrSamplerState::Filter::kMipMap) {
2624 if (!this->caps()->mipMapSupport() ||
2625 texture->texturePriv().mipMapped() == GrMipMapped::kNo) {
2626 samplerState.setFilterMode(GrSamplerState::Filter::kBilerp);
2627 }
2628 }
2629
2630 #ifdef SK_DEBUG
2631 // We were supposed to ensure MipMaps were up-to-date before getting here.
2632 if (samplerState.filter() == GrSamplerState::Filter::kMipMap) {
2633 SkASSERT(!texture->texturePriv().mipMapsAreDirty());
2634 }
2635 #endif
2636
2637 auto timestamp = texture->parameters()->resetTimestamp();
2638 bool setAll = timestamp < fResetTimestampForTextureParameters;
2639
2640 const GrGLTextureParameters::SamplerOverriddenState* samplerStateToRecord = nullptr;
2641 GrGLTextureParameters::SamplerOverriddenState newSamplerState;
2642 if (fSamplerObjectCache) {
2643 fSamplerObjectCache->bindSampler(unitIdx, samplerState);
2644 } else {
2645 const GrGLTextureParameters::SamplerOverriddenState& oldSamplerState =
2646 texture->parameters()->samplerOverriddenState();
2647 samplerStateToRecord = &newSamplerState;
2648
2649 newSamplerState.fMinFilter = filter_to_gl_min_filter(samplerState.filter());
2650 newSamplerState.fMagFilter = filter_to_gl_mag_filter(samplerState.filter());
2651
2652 newSamplerState.fWrapS = wrap_mode_to_gl_wrap(samplerState.wrapModeX(), this->glCaps());
2653 newSamplerState.fWrapT = wrap_mode_to_gl_wrap(samplerState.wrapModeY(), this->glCaps());
2654
2655 // These are the OpenGL default values.
2656 newSamplerState.fMinLOD = -1000.f;
2657 newSamplerState.fMaxLOD = 1000.f;
2658
2659 if (setAll || newSamplerState.fMagFilter != oldSamplerState.fMagFilter) {
2660 this->setTextureUnit(unitIdx);
2661 GL_CALL(TexParameteri(target, GR_GL_TEXTURE_MAG_FILTER, newSamplerState.fMagFilter));
2662 }
2663 if (setAll || newSamplerState.fMinFilter != oldSamplerState.fMinFilter) {
2664 this->setTextureUnit(unitIdx);
2665 GL_CALL(TexParameteri(target, GR_GL_TEXTURE_MIN_FILTER, newSamplerState.fMinFilter));
2666 }
2667 if (this->glCaps().mipMapLevelAndLodControlSupport()) {
2668 if (setAll || newSamplerState.fMinLOD != oldSamplerState.fMinLOD) {
2669 this->setTextureUnit(unitIdx);
2670 GL_CALL(TexParameterf(target, GR_GL_TEXTURE_MIN_LOD, newSamplerState.fMinLOD));
2671 }
2672 if (setAll || newSamplerState.fMaxLOD != oldSamplerState.fMaxLOD) {
2673 this->setTextureUnit(unitIdx);
2674 GL_CALL(TexParameterf(target, GR_GL_TEXTURE_MAX_LOD, newSamplerState.fMaxLOD));
2675 }
2676 }
2677 if (setAll || newSamplerState.fWrapS != oldSamplerState.fWrapS) {
2678 this->setTextureUnit(unitIdx);
2679 GL_CALL(TexParameteri(target, GR_GL_TEXTURE_WRAP_S, newSamplerState.fWrapS));
2680 }
2681 if (setAll || newSamplerState.fWrapT != oldSamplerState.fWrapT) {
2682 this->setTextureUnit(unitIdx);
2683 GL_CALL(TexParameteri(target, GR_GL_TEXTURE_WRAP_T, newSamplerState.fWrapT));
2684 }
2685 if (this->glCaps().clampToBorderSupport()) {
2686 // Make sure the border color is transparent black (the default)
2687 if (setAll || oldSamplerState.fBorderColorInvalid) {
2688 this->setTextureUnit(unitIdx);
2689 static const GrGLfloat kTransparentBlack[4] = {0.f, 0.f, 0.f, 0.f};
2690 GL_CALL(TexParameterfv(target, GR_GL_TEXTURE_BORDER_COLOR, kTransparentBlack));
2691 }
2692 }
2693 }
2694 GrGLTextureParameters::NonsamplerState newNonsamplerState;
2695 newNonsamplerState.fBaseMipMapLevel = 0;
2696 newNonsamplerState.fMaxMipMapLevel = texture->texturePriv().maxMipMapLevel();
2697
2698 const GrGLTextureParameters::NonsamplerState& oldNonsamplerState =
2699 texture->parameters()->nonsamplerState();
2700 if (!this->caps()->shaderCaps()->textureSwizzleAppliedInShader()) {
2701 newNonsamplerState.fSwizzleKey = swizzle.asKey();
2702 if (setAll || swizzle.asKey() != oldNonsamplerState.fSwizzleKey) {
2703 GrGLenum glValues[4];
2704 get_gl_swizzle_values(swizzle, glValues);
2705 this->setTextureUnit(unitIdx);
2706 if (GR_IS_GR_GL(this->glStandard())) {
2707 GR_STATIC_ASSERT(sizeof(glValues[0]) == sizeof(GrGLint));
2708 GL_CALL(TexParameteriv(target, GR_GL_TEXTURE_SWIZZLE_RGBA,
2709 reinterpret_cast<const GrGLint*>(glValues)));
2710 } else if (GR_IS_GR_GL_ES(this->glStandard())) {
2711 // ES3 added swizzle support but not GL_TEXTURE_SWIZZLE_RGBA.
2712 GL_CALL(TexParameteri(target, GR_GL_TEXTURE_SWIZZLE_R, glValues[0]));
2713 GL_CALL(TexParameteri(target, GR_GL_TEXTURE_SWIZZLE_G, glValues[1]));
2714 GL_CALL(TexParameteri(target, GR_GL_TEXTURE_SWIZZLE_B, glValues[2]));
2715 GL_CALL(TexParameteri(target, GR_GL_TEXTURE_SWIZZLE_A, glValues[3]));
2716 }
2717 }
2718 }
2719 // These are not supported in ES2 contexts
2720 if (this->glCaps().mipMapLevelAndLodControlSupport() &&
2721 (texture->texturePriv().textureType() != GrTextureType::kExternal ||
2722 !this->glCaps().dontSetBaseOrMaxLevelForExternalTextures())) {
2723 if (newNonsamplerState.fBaseMipMapLevel != oldNonsamplerState.fBaseMipMapLevel) {
2724 this->setTextureUnit(unitIdx);
2725 GL_CALL(TexParameteri(target, GR_GL_TEXTURE_BASE_LEVEL,
2726 newNonsamplerState.fBaseMipMapLevel));
2727 }
2728 if (newNonsamplerState.fMaxMipMapLevel != oldNonsamplerState.fMaxMipMapLevel) {
2729 this->setTextureUnit(unitIdx);
2730 GL_CALL(TexParameteri(target, GR_GL_TEXTURE_MAX_LEVEL,
2731 newNonsamplerState.fMaxMipMapLevel));
2732 }
2733 }
2734 texture->parameters()->set(samplerStateToRecord, newNonsamplerState,
2735 fResetTimestampForTextureParameters);
2736 }
2737
onResetTextureBindings()2738 void GrGLGpu::onResetTextureBindings() {
2739 static constexpr GrGLenum kTargets[] = {GR_GL_TEXTURE_2D, GR_GL_TEXTURE_RECTANGLE,
2740 GR_GL_TEXTURE_EXTERNAL};
2741 for (int i = 0; i < this->numTextureUnits(); ++i) {
2742 this->setTextureUnit(i);
2743 for (auto target : kTargets) {
2744 if (fHWTextureUnitBindings[i].hasBeenModified(target)) {
2745 GL_CALL(BindTexture(target, 0));
2746 }
2747 }
2748 fHWTextureUnitBindings[i].invalidateAllTargets(true);
2749 }
2750 }
2751
flushColorWrite(bool writeColor)2752 void GrGLGpu::flushColorWrite(bool writeColor) {
2753 if (!writeColor) {
2754 if (kNo_TriState != fHWWriteToColor) {
2755 GL_CALL(ColorMask(GR_GL_FALSE, GR_GL_FALSE,
2756 GR_GL_FALSE, GR_GL_FALSE));
2757 fHWWriteToColor = kNo_TriState;
2758 }
2759 } else {
2760 if (kYes_TriState != fHWWriteToColor) {
2761 GL_CALL(ColorMask(GR_GL_TRUE, GR_GL_TRUE, GR_GL_TRUE, GR_GL_TRUE));
2762 fHWWriteToColor = kYes_TriState;
2763 }
2764 }
2765 }
2766
flushClearColor(const SkPMColor4f & color)2767 void GrGLGpu::flushClearColor(const SkPMColor4f& color) {
2768 GrGLfloat r = color.fR, g = color.fG, b = color.fB, a = color.fA;
2769 if (this->glCaps().clearToBoundaryValuesIsBroken() &&
2770 (1 == r || 0 == r) && (1 == g || 0 == g) && (1 == b || 0 == b) && (1 == a || 0 == a)) {
2771 static const GrGLfloat safeAlpha1 = nextafter(1.f, 2.f);
2772 static const GrGLfloat safeAlpha0 = nextafter(0.f, -1.f);
2773 a = (1 == a) ? safeAlpha1 : safeAlpha0;
2774 }
2775 if (r != fHWClearColor[0] || g != fHWClearColor[1] ||
2776 b != fHWClearColor[2] || a != fHWClearColor[3]) {
2777 GL_CALL(ClearColor(r, g, b, a));
2778 fHWClearColor[0] = r;
2779 fHWClearColor[1] = g;
2780 fHWClearColor[2] = b;
2781 fHWClearColor[3] = a;
2782 }
2783 }
2784
setTextureUnit(int unit)2785 void GrGLGpu::setTextureUnit(int unit) {
2786 SkASSERT(unit >= 0 && unit < this->numTextureUnits());
2787 if (unit != fHWActiveTextureUnitIdx) {
2788 GL_CALL(ActiveTexture(GR_GL_TEXTURE0 + unit));
2789 fHWActiveTextureUnitIdx = unit;
2790 }
2791 }
2792
bindTextureToScratchUnit(GrGLenum target,GrGLint textureID)2793 void GrGLGpu::bindTextureToScratchUnit(GrGLenum target, GrGLint textureID) {
2794 // Bind the last texture unit since it is the least likely to be used by GrGLProgram.
2795 int lastUnitIdx = this->numTextureUnits() - 1;
2796 if (lastUnitIdx != fHWActiveTextureUnitIdx) {
2797 GL_CALL(ActiveTexture(GR_GL_TEXTURE0 + lastUnitIdx));
2798 fHWActiveTextureUnitIdx = lastUnitIdx;
2799 }
2800 // Clear out the this field so that if a GrGLProgram does use this unit it will rebind the
2801 // correct texture.
2802 fHWTextureUnitBindings[lastUnitIdx].invalidateForScratchUse(target);
2803 GL_CALL(BindTexture(target, textureID));
2804 }
2805
2806 // Determines whether glBlitFramebuffer could be used between src and dst by onCopySurface.
can_blit_framebuffer_for_copy_surface(const GrSurface * dst,const GrSurface * src,const SkIRect & srcRect,const SkIPoint & dstPoint,const GrGLCaps & caps)2807 static inline bool can_blit_framebuffer_for_copy_surface(const GrSurface* dst,
2808 const GrSurface* src,
2809 const SkIRect& srcRect,
2810 const SkIPoint& dstPoint,
2811 const GrGLCaps& caps) {
2812 int dstSampleCnt = 0;
2813 int srcSampleCnt = 0;
2814 if (const GrRenderTarget* rt = dst->asRenderTarget()) {
2815 dstSampleCnt = rt->numSamples();
2816 }
2817 if (const GrRenderTarget* rt = src->asRenderTarget()) {
2818 srcSampleCnt = rt->numSamples();
2819 }
2820 SkASSERT((dstSampleCnt > 0) == SkToBool(dst->asRenderTarget()));
2821 SkASSERT((srcSampleCnt > 0) == SkToBool(src->asRenderTarget()));
2822
2823 GrGLFormat dstFormat = dst->backendFormat().asGLFormat();
2824 GrGLFormat srcFormat = src->backendFormat().asGLFormat();
2825
2826 const GrGLTexture* dstTex = static_cast<const GrGLTexture*>(dst->asTexture());
2827 const GrGLTexture* srcTex = static_cast<const GrGLTexture*>(src->asTexture());
2828
2829 GrTextureType dstTexType;
2830 GrTextureType* dstTexTypePtr = nullptr;
2831 GrTextureType srcTexType;
2832 GrTextureType* srcTexTypePtr = nullptr;
2833 if (dstTex) {
2834 dstTexType = dstTex->texturePriv().textureType();
2835 dstTexTypePtr = &dstTexType;
2836 }
2837 if (srcTex) {
2838 srcTexType = srcTex->texturePriv().textureType();
2839 srcTexTypePtr = &srcTexType;
2840 }
2841
2842 return caps.canCopyAsBlit(dstFormat, dstSampleCnt, dstTexTypePtr,
2843 srcFormat, srcSampleCnt, srcTexTypePtr,
2844 src->getBoundsRect(), true, srcRect, dstPoint);
2845 }
2846
rt_has_msaa_render_buffer(const GrGLRenderTarget * rt,const GrGLCaps & glCaps)2847 static bool rt_has_msaa_render_buffer(const GrGLRenderTarget* rt, const GrGLCaps& glCaps) {
2848 // A RT has a separate MSAA renderbuffer if:
2849 // 1) It's multisampled
2850 // 2) We're using an extension with separate MSAA renderbuffers
2851 // 3) It's not FBO 0, which is special and always auto-resolves
2852 return rt->numSamples() > 1 && glCaps.usesMSAARenderBuffers() && rt->renderFBOID() != 0;
2853 }
2854
can_copy_texsubimage(const GrSurface * dst,const GrSurface * src,const GrGLCaps & caps)2855 static inline bool can_copy_texsubimage(const GrSurface* dst, const GrSurface* src,
2856 const GrGLCaps& caps) {
2857
2858 const GrGLRenderTarget* dstRT = static_cast<const GrGLRenderTarget*>(dst->asRenderTarget());
2859 const GrGLRenderTarget* srcRT = static_cast<const GrGLRenderTarget*>(src->asRenderTarget());
2860 const GrGLTexture* dstTex = static_cast<const GrGLTexture*>(dst->asTexture());
2861 const GrGLTexture* srcTex = static_cast<const GrGLTexture*>(src->asTexture());
2862
2863 bool dstHasMSAARenderBuffer = dstRT ? rt_has_msaa_render_buffer(dstRT, caps) : false;
2864 bool srcHasMSAARenderBuffer = srcRT ? rt_has_msaa_render_buffer(srcRT, caps) : false;
2865
2866 GrGLFormat dstFormat = dst->backendFormat().asGLFormat();
2867 GrGLFormat srcFormat = src->backendFormat().asGLFormat();
2868
2869 GrTextureType dstTexType;
2870 GrTextureType* dstTexTypePtr = nullptr;
2871 GrTextureType srcTexType;
2872 GrTextureType* srcTexTypePtr = nullptr;
2873 if (dstTex) {
2874 dstTexType = dstTex->texturePriv().textureType();
2875 dstTexTypePtr = &dstTexType;
2876 }
2877 if (srcTex) {
2878 srcTexType = srcTex->texturePriv().textureType();
2879 srcTexTypePtr = &srcTexType;
2880 }
2881
2882 return caps.canCopyTexSubImage(dstFormat, dstHasMSAARenderBuffer, dstTexTypePtr,
2883 srcFormat, srcHasMSAARenderBuffer, srcTexTypePtr);
2884 }
2885
2886 // If a temporary FBO was created, its non-zero ID is returned.
bindSurfaceFBOForPixelOps(GrSurface * surface,int mipLevel,GrGLenum fboTarget,TempFBOTarget tempFBOTarget)2887 void GrGLGpu::bindSurfaceFBOForPixelOps(GrSurface* surface, int mipLevel, GrGLenum fboTarget,
2888 TempFBOTarget tempFBOTarget) {
2889 GrGLRenderTarget* rt = static_cast<GrGLRenderTarget*>(surface->asRenderTarget());
2890 if (!rt || mipLevel > 0) {
2891 SkASSERT(surface->asTexture());
2892 GrGLTexture* texture = static_cast<GrGLTexture*>(surface->asTexture());
2893 GrGLuint texID = texture->textureID();
2894 GrGLenum target = texture->target();
2895 GrGLuint* tempFBOID;
2896 tempFBOID = kSrc_TempFBOTarget == tempFBOTarget ? &fTempSrcFBOID : &fTempDstFBOID;
2897
2898 if (0 == *tempFBOID) {
2899 GR_GL_CALL(this->glInterface(), GenFramebuffers(1, tempFBOID));
2900 }
2901
2902 this->bindFramebuffer(fboTarget, *tempFBOID);
2903 GR_GL_CALL(
2904 this->glInterface(),
2905 FramebufferTexture2D(fboTarget, GR_GL_COLOR_ATTACHMENT0, target, texID, mipLevel));
2906 if (mipLevel == 0) {
2907 texture->baseLevelWasBoundToFBO();
2908 }
2909 } else {
2910 this->bindFramebuffer(fboTarget, rt->renderFBOID());
2911 }
2912 }
2913
unbindSurfaceFBOForPixelOps(GrSurface * surface,int mipLevel,GrGLenum fboTarget)2914 void GrGLGpu::unbindSurfaceFBOForPixelOps(GrSurface* surface, int mipLevel, GrGLenum fboTarget) {
2915 // bindSurfaceFBOForPixelOps temporarily binds textures that are not render targets to
2916 if (mipLevel > 0 || !surface->asRenderTarget()) {
2917 SkASSERT(surface->asTexture());
2918 GrGLenum textureTarget = static_cast<GrGLTexture*>(surface->asTexture())->target();
2919 GR_GL_CALL(this->glInterface(), FramebufferTexture2D(fboTarget,
2920 GR_GL_COLOR_ATTACHMENT0,
2921 textureTarget,
2922 0,
2923 0));
2924 }
2925 }
2926
onFBOChanged()2927 void GrGLGpu::onFBOChanged() {
2928 if (this->caps()->workarounds().flush_on_framebuffer_change ||
2929 this->caps()->workarounds().restore_scissor_on_fbo_change) {
2930 GL_CALL(Flush());
2931 }
2932 #ifdef SK_DEBUG
2933 if (fIsExecutingCommandBuffer_DebugOnly) {
2934 SkDebugf("WARNING: GL FBO binding changed while executing a command buffer. "
2935 "This will severely hurt performance.\n");
2936 }
2937 #endif
2938 }
2939
bindFramebuffer(GrGLenum target,GrGLuint fboid)2940 void GrGLGpu::bindFramebuffer(GrGLenum target, GrGLuint fboid) {
2941 fStats.incRenderTargetBinds();
2942 GL_CALL(BindFramebuffer(target, fboid));
2943 if (target == GR_GL_FRAMEBUFFER || target == GR_GL_DRAW_FRAMEBUFFER) {
2944 fBoundDrawFramebuffer = fboid;
2945 }
2946
2947 if (this->caps()->workarounds().restore_scissor_on_fbo_change) {
2948 // The driver forgets the correct scissor when modifying the FBO binding.
2949 if (!fHWScissorSettings.fRect.isInvalid()) {
2950 const GrNativeRect& r = fHWScissorSettings.fRect;
2951 GL_CALL(Scissor(r.fX, r.fY, r.fWidth, r.fHeight));
2952 }
2953 }
2954
2955 this->onFBOChanged();
2956 }
2957
deleteFramebuffer(GrGLuint fboid)2958 void GrGLGpu::deleteFramebuffer(GrGLuint fboid) {
2959 if (fboid == fBoundDrawFramebuffer &&
2960 this->caps()->workarounds().unbind_attachments_on_bound_render_fbo_delete) {
2961 // This workaround only applies to deleting currently bound framebuffers
2962 // on Adreno 420. Because this is a somewhat rare case, instead of
2963 // tracking all the attachments of every framebuffer instead just always
2964 // unbind all attachments.
2965 GL_CALL(FramebufferRenderbuffer(GR_GL_FRAMEBUFFER, GR_GL_COLOR_ATTACHMENT0,
2966 GR_GL_RENDERBUFFER, 0));
2967 GL_CALL(FramebufferRenderbuffer(GR_GL_FRAMEBUFFER, GR_GL_STENCIL_ATTACHMENT,
2968 GR_GL_RENDERBUFFER, 0));
2969 GL_CALL(FramebufferRenderbuffer(GR_GL_FRAMEBUFFER, GR_GL_DEPTH_ATTACHMENT,
2970 GR_GL_RENDERBUFFER, 0));
2971 }
2972
2973 GL_CALL(DeleteFramebuffers(1, &fboid));
2974
2975 // Deleting the currently bound framebuffer rebinds to 0.
2976 if (fboid == fBoundDrawFramebuffer) {
2977 this->onFBOChanged();
2978 }
2979 }
2980
onCopySurface(GrSurface * dst,GrSurface * src,const SkIRect & srcRect,const SkIPoint & dstPoint)2981 bool GrGLGpu::onCopySurface(GrSurface* dst, GrSurface* src, const SkIRect& srcRect,
2982 const SkIPoint& dstPoint) {
2983 // Don't prefer copying as a draw if the dst doesn't already have a FBO object.
2984 // This implicitly handles this->glCaps().useDrawInsteadOfAllRenderTargetWrites().
2985 bool preferCopy = SkToBool(dst->asRenderTarget());
2986 auto dstFormat = dst->backendFormat().asGLFormat();
2987 if (preferCopy && this->glCaps().canCopyAsDraw(dstFormat, SkToBool(src->asTexture()))) {
2988 if (this->copySurfaceAsDraw(dst, src, srcRect, dstPoint)) {
2989 return true;
2990 }
2991 }
2992
2993 if (can_copy_texsubimage(dst, src, this->glCaps())) {
2994 this->copySurfaceAsCopyTexSubImage(dst, src, srcRect, dstPoint);
2995 return true;
2996 }
2997
2998 if (can_blit_framebuffer_for_copy_surface(dst, src, srcRect, dstPoint, this->glCaps())) {
2999 return this->copySurfaceAsBlitFramebuffer(dst, src, srcRect, dstPoint);
3000 }
3001
3002 if (!preferCopy && this->glCaps().canCopyAsDraw(dstFormat, SkToBool(src->asTexture()))) {
3003 if (this->copySurfaceAsDraw(dst, src, srcRect, dstPoint)) {
3004 return true;
3005 }
3006 }
3007
3008 return false;
3009 }
3010
createCopyProgram(GrTexture * srcTex)3011 bool GrGLGpu::createCopyProgram(GrTexture* srcTex) {
3012 TRACE_EVENT0("skia.gpu", TRACE_FUNC);
3013
3014 int progIdx = TextureToCopyProgramIdx(srcTex);
3015 const GrShaderCaps* shaderCaps = this->caps()->shaderCaps();
3016 GrSLType samplerType =
3017 GrSLCombinedSamplerTypeForTextureType(srcTex->texturePriv().textureType());
3018
3019 if (!fCopyProgramArrayBuffer) {
3020 static const GrGLfloat vdata[] = {
3021 0, 0,
3022 0, 1,
3023 1, 0,
3024 1, 1
3025 };
3026 fCopyProgramArrayBuffer = GrGLBuffer::Make(this, sizeof(vdata), GrGpuBufferType::kVertex,
3027 kStatic_GrAccessPattern, vdata);
3028 }
3029 if (!fCopyProgramArrayBuffer) {
3030 return false;
3031 }
3032
3033 SkASSERT(!fCopyPrograms[progIdx].fProgram);
3034 GL_CALL_RET(fCopyPrograms[progIdx].fProgram, CreateProgram());
3035 if (!fCopyPrograms[progIdx].fProgram) {
3036 return false;
3037 }
3038
3039 GrShaderVar aVertex("a_vertex", kHalf2_GrSLType, GrShaderVar::kIn_TypeModifier);
3040 GrShaderVar uTexCoordXform("u_texCoordXform", kHalf4_GrSLType,
3041 GrShaderVar::kUniform_TypeModifier);
3042 GrShaderVar uPosXform("u_posXform", kHalf4_GrSLType, GrShaderVar::kUniform_TypeModifier);
3043 GrShaderVar uTexture("u_texture", samplerType, GrShaderVar::kUniform_TypeModifier);
3044 GrShaderVar vTexCoord("v_texCoord", kHalf2_GrSLType, GrShaderVar::kOut_TypeModifier);
3045 GrShaderVar oFragColor("o_FragColor", kHalf4_GrSLType, GrShaderVar::kOut_TypeModifier);
3046
3047 SkString vshaderTxt;
3048 if (shaderCaps->noperspectiveInterpolationSupport()) {
3049 if (const char* extension = shaderCaps->noperspectiveInterpolationExtensionString()) {
3050 vshaderTxt.appendf("#extension %s : require\n", extension);
3051 }
3052 vTexCoord.addModifier("noperspective");
3053 }
3054
3055 aVertex.appendDecl(shaderCaps, &vshaderTxt);
3056 vshaderTxt.append(";");
3057 uTexCoordXform.appendDecl(shaderCaps, &vshaderTxt);
3058 vshaderTxt.append(";");
3059 uPosXform.appendDecl(shaderCaps, &vshaderTxt);
3060 vshaderTxt.append(";");
3061 vTexCoord.appendDecl(shaderCaps, &vshaderTxt);
3062 vshaderTxt.append(";");
3063
3064 vshaderTxt.append(
3065 "// Copy Program VS\n"
3066 "void main() {"
3067 " v_texCoord = half2(a_vertex.xy * u_texCoordXform.xy + u_texCoordXform.zw);"
3068 " sk_Position.xy = a_vertex * u_posXform.xy + u_posXform.zw;"
3069 " sk_Position.zw = half2(0, 1);"
3070 "}"
3071 );
3072
3073 SkString fshaderTxt;
3074 if (shaderCaps->noperspectiveInterpolationSupport()) {
3075 if (const char* extension = shaderCaps->noperspectiveInterpolationExtensionString()) {
3076 fshaderTxt.appendf("#extension %s : require\n", extension);
3077 }
3078 }
3079 vTexCoord.setTypeModifier(GrShaderVar::kIn_TypeModifier);
3080 vTexCoord.appendDecl(shaderCaps, &fshaderTxt);
3081 fshaderTxt.append(";");
3082 uTexture.appendDecl(shaderCaps, &fshaderTxt);
3083 fshaderTxt.append(";");
3084 fshaderTxt.appendf(
3085 "// Copy Program FS\n"
3086 "void main() {"
3087 " sk_FragColor = sample(u_texture, v_texCoord);"
3088 "}"
3089 );
3090
3091 auto errorHandler = this->getContext()->priv().getShaderErrorHandler();
3092 SkSL::String sksl(vshaderTxt.c_str(), vshaderTxt.size());
3093 SkSL::Program::Settings settings;
3094 settings.fCaps = shaderCaps;
3095 SkSL::String glsl;
3096 std::unique_ptr<SkSL::Program> program = GrSkSLtoGLSL(*fGLContext, SkSL::Program::kVertex_Kind,
3097 sksl, settings, &glsl, errorHandler);
3098 GrGLuint vshader = GrGLCompileAndAttachShader(*fGLContext, fCopyPrograms[progIdx].fProgram,
3099 GR_GL_VERTEX_SHADER, glsl, &fStats, errorHandler);
3100 SkASSERT(program->fInputs.isEmpty());
3101
3102 sksl.assign(fshaderTxt.c_str(), fshaderTxt.size());
3103 program = GrSkSLtoGLSL(*fGLContext, SkSL::Program::kFragment_Kind, sksl, settings, &glsl,
3104 errorHandler);
3105 GrGLuint fshader = GrGLCompileAndAttachShader(*fGLContext, fCopyPrograms[progIdx].fProgram,
3106 GR_GL_FRAGMENT_SHADER, glsl, &fStats,
3107 errorHandler);
3108 SkASSERT(program->fInputs.isEmpty());
3109
3110 GL_CALL(LinkProgram(fCopyPrograms[progIdx].fProgram));
3111
3112 GL_CALL_RET(fCopyPrograms[progIdx].fTextureUniform,
3113 GetUniformLocation(fCopyPrograms[progIdx].fProgram, "u_texture"));
3114 GL_CALL_RET(fCopyPrograms[progIdx].fPosXformUniform,
3115 GetUniformLocation(fCopyPrograms[progIdx].fProgram, "u_posXform"));
3116 GL_CALL_RET(fCopyPrograms[progIdx].fTexCoordXformUniform,
3117 GetUniformLocation(fCopyPrograms[progIdx].fProgram, "u_texCoordXform"));
3118
3119 GL_CALL(BindAttribLocation(fCopyPrograms[progIdx].fProgram, 0, "a_vertex"));
3120
3121 GL_CALL(DeleteShader(vshader));
3122 GL_CALL(DeleteShader(fshader));
3123
3124 return true;
3125 }
3126
createMipmapProgram(int progIdx)3127 bool GrGLGpu::createMipmapProgram(int progIdx) {
3128 const bool oddWidth = SkToBool(progIdx & 0x2);
3129 const bool oddHeight = SkToBool(progIdx & 0x1);
3130 const int numTaps = (oddWidth ? 2 : 1) * (oddHeight ? 2 : 1);
3131
3132 const GrShaderCaps* shaderCaps = this->caps()->shaderCaps();
3133
3134 SkASSERT(!fMipmapPrograms[progIdx].fProgram);
3135 GL_CALL_RET(fMipmapPrograms[progIdx].fProgram, CreateProgram());
3136 if (!fMipmapPrograms[progIdx].fProgram) {
3137 return false;
3138 }
3139
3140 GrShaderVar aVertex("a_vertex", kHalf2_GrSLType, GrShaderVar::kIn_TypeModifier);
3141 GrShaderVar uTexCoordXform("u_texCoordXform", kHalf4_GrSLType,
3142 GrShaderVar::kUniform_TypeModifier);
3143 GrShaderVar uTexture("u_texture", kTexture2DSampler_GrSLType,
3144 GrShaderVar::kUniform_TypeModifier);
3145 // We need 1, 2, or 4 texture coordinates (depending on parity of each dimension):
3146 GrShaderVar vTexCoords[] = {
3147 GrShaderVar("v_texCoord0", kHalf2_GrSLType, GrShaderVar::kOut_TypeModifier),
3148 GrShaderVar("v_texCoord1", kHalf2_GrSLType, GrShaderVar::kOut_TypeModifier),
3149 GrShaderVar("v_texCoord2", kHalf2_GrSLType, GrShaderVar::kOut_TypeModifier),
3150 GrShaderVar("v_texCoord3", kHalf2_GrSLType, GrShaderVar::kOut_TypeModifier),
3151 };
3152 GrShaderVar oFragColor("o_FragColor", kHalf4_GrSLType,GrShaderVar::kOut_TypeModifier);
3153
3154 SkString vshaderTxt;
3155 if (shaderCaps->noperspectiveInterpolationSupport()) {
3156 if (const char* extension = shaderCaps->noperspectiveInterpolationExtensionString()) {
3157 vshaderTxt.appendf("#extension %s : require\n", extension);
3158 }
3159 vTexCoords[0].addModifier("noperspective");
3160 vTexCoords[1].addModifier("noperspective");
3161 vTexCoords[2].addModifier("noperspective");
3162 vTexCoords[3].addModifier("noperspective");
3163 }
3164
3165 aVertex.appendDecl(shaderCaps, &vshaderTxt);
3166 vshaderTxt.append(";");
3167 uTexCoordXform.appendDecl(shaderCaps, &vshaderTxt);
3168 vshaderTxt.append(";");
3169 for (int i = 0; i < numTaps; ++i) {
3170 vTexCoords[i].appendDecl(shaderCaps, &vshaderTxt);
3171 vshaderTxt.append(";");
3172 }
3173
3174 vshaderTxt.append(
3175 "// Mipmap Program VS\n"
3176 "void main() {"
3177 " sk_Position.xy = a_vertex * half2(2, 2) - half2(1, 1);"
3178 " sk_Position.zw = half2(0, 1);"
3179 );
3180
3181 // Insert texture coordinate computation:
3182 if (oddWidth && oddHeight) {
3183 vshaderTxt.append(
3184 " v_texCoord0 = a_vertex.xy * u_texCoordXform.yw;"
3185 " v_texCoord1 = a_vertex.xy * u_texCoordXform.yw + half2(u_texCoordXform.x, 0);"
3186 " v_texCoord2 = a_vertex.xy * u_texCoordXform.yw + half2(0, u_texCoordXform.z);"
3187 " v_texCoord3 = a_vertex.xy * u_texCoordXform.yw + u_texCoordXform.xz;"
3188 );
3189 } else if (oddWidth) {
3190 vshaderTxt.append(
3191 " v_texCoord0 = a_vertex.xy * half2(u_texCoordXform.y, 1);"
3192 " v_texCoord1 = a_vertex.xy * half2(u_texCoordXform.y, 1) + half2(u_texCoordXform.x, 0);"
3193 );
3194 } else if (oddHeight) {
3195 vshaderTxt.append(
3196 " v_texCoord0 = a_vertex.xy * half2(1, u_texCoordXform.w);"
3197 " v_texCoord1 = a_vertex.xy * half2(1, u_texCoordXform.w) + half2(0, u_texCoordXform.z);"
3198 );
3199 } else {
3200 vshaderTxt.append(
3201 " v_texCoord0 = a_vertex.xy;"
3202 );
3203 }
3204
3205 vshaderTxt.append("}");
3206
3207 SkString fshaderTxt;
3208 if (shaderCaps->noperspectiveInterpolationSupport()) {
3209 if (const char* extension = shaderCaps->noperspectiveInterpolationExtensionString()) {
3210 fshaderTxt.appendf("#extension %s : require\n", extension);
3211 }
3212 }
3213 for (int i = 0; i < numTaps; ++i) {
3214 vTexCoords[i].setTypeModifier(GrShaderVar::kIn_TypeModifier);
3215 vTexCoords[i].appendDecl(shaderCaps, &fshaderTxt);
3216 fshaderTxt.append(";");
3217 }
3218 uTexture.appendDecl(shaderCaps, &fshaderTxt);
3219 fshaderTxt.append(";");
3220 fshaderTxt.append(
3221 "// Mipmap Program FS\n"
3222 "void main() {"
3223 );
3224
3225 if (oddWidth && oddHeight) {
3226 fshaderTxt.append(
3227 " sk_FragColor = (sample(u_texture, v_texCoord0) + "
3228 " sample(u_texture, v_texCoord1) + "
3229 " sample(u_texture, v_texCoord2) + "
3230 " sample(u_texture, v_texCoord3)) * 0.25;"
3231 );
3232 } else if (oddWidth || oddHeight) {
3233 fshaderTxt.append(
3234 " sk_FragColor = (sample(u_texture, v_texCoord0) + "
3235 " sample(u_texture, v_texCoord1)) * 0.5;"
3236 );
3237 } else {
3238 fshaderTxt.append(
3239 " sk_FragColor = sample(u_texture, v_texCoord0);"
3240 );
3241 }
3242
3243 fshaderTxt.append("}");
3244
3245 auto errorHandler = this->getContext()->priv().getShaderErrorHandler();
3246 SkSL::String sksl(vshaderTxt.c_str(), vshaderTxt.size());
3247 SkSL::Program::Settings settings;
3248 settings.fCaps = shaderCaps;
3249 SkSL::String glsl;
3250 std::unique_ptr<SkSL::Program> program = GrSkSLtoGLSL(*fGLContext, SkSL::Program::kVertex_Kind,
3251 sksl, settings, &glsl, errorHandler);
3252 GrGLuint vshader = GrGLCompileAndAttachShader(*fGLContext, fMipmapPrograms[progIdx].fProgram,
3253 GR_GL_VERTEX_SHADER, glsl, &fStats, errorHandler);
3254 SkASSERT(program->fInputs.isEmpty());
3255
3256 sksl.assign(fshaderTxt.c_str(), fshaderTxt.size());
3257 program = GrSkSLtoGLSL(*fGLContext, SkSL::Program::kFragment_Kind, sksl, settings, &glsl,
3258 errorHandler);
3259 GrGLuint fshader = GrGLCompileAndAttachShader(*fGLContext, fMipmapPrograms[progIdx].fProgram,
3260 GR_GL_FRAGMENT_SHADER, glsl, &fStats,
3261 errorHandler);
3262 SkASSERT(program->fInputs.isEmpty());
3263
3264 GL_CALL(LinkProgram(fMipmapPrograms[progIdx].fProgram));
3265
3266 GL_CALL_RET(fMipmapPrograms[progIdx].fTextureUniform,
3267 GetUniformLocation(fMipmapPrograms[progIdx].fProgram, "u_texture"));
3268 GL_CALL_RET(fMipmapPrograms[progIdx].fTexCoordXformUniform,
3269 GetUniformLocation(fMipmapPrograms[progIdx].fProgram, "u_texCoordXform"));
3270
3271 GL_CALL(BindAttribLocation(fMipmapPrograms[progIdx].fProgram, 0, "a_vertex"));
3272
3273 GL_CALL(DeleteShader(vshader));
3274 GL_CALL(DeleteShader(fshader));
3275
3276 return true;
3277 }
3278
copySurfaceAsDraw(GrSurface * dst,GrSurface * src,const SkIRect & srcRect,const SkIPoint & dstPoint)3279 bool GrGLGpu::copySurfaceAsDraw(GrSurface* dst, GrSurface* src, const SkIRect& srcRect,
3280 const SkIPoint& dstPoint) {
3281 auto* srcTex = static_cast<GrGLTexture*>(src->asTexture());
3282 auto* dstTex = static_cast<GrGLTexture*>(src->asTexture());
3283 auto* dstRT = static_cast<GrGLRenderTarget*>(src->asRenderTarget());
3284 if (!srcTex) {
3285 return false;
3286 }
3287 int progIdx = TextureToCopyProgramIdx(srcTex);
3288 if (!dstRT) {
3289 SkASSERT(dstTex);
3290 if (!this->glCaps().isFormatRenderable(dstTex->format(), 1)) {
3291 return false;
3292 }
3293 }
3294 if (!fCopyPrograms[progIdx].fProgram) {
3295 if (!this->createCopyProgram(srcTex)) {
3296 SkDebugf("Failed to create copy program.\n");
3297 return false;
3298 }
3299 }
3300 int w = srcRect.width();
3301 int h = srcRect.height();
3302 // We don't swizzle at all in our copies.
3303 this->bindTexture(0, GrSamplerState::ClampNearest(), GrSwizzle::RGBA(), srcTex);
3304 this->bindSurfaceFBOForPixelOps(dst, 0, GR_GL_FRAMEBUFFER, kDst_TempFBOTarget);
3305 this->flushViewport(dst->width(), dst->height());
3306 fHWBoundRenderTargetUniqueID.makeInvalid();
3307 SkIRect dstRect = SkIRect::MakeXYWH(dstPoint.fX, dstPoint.fY, w, h);
3308 this->flushProgram(fCopyPrograms[progIdx].fProgram);
3309 fHWVertexArrayState.setVertexArrayID(this, 0);
3310 GrGLAttribArrayState* attribs = fHWVertexArrayState.bindInternalVertexArray(this);
3311 attribs->enableVertexArrays(this, 1);
3312 attribs->set(this, 0, fCopyProgramArrayBuffer.get(), kFloat2_GrVertexAttribType,
3313 kFloat2_GrSLType, 2 * sizeof(GrGLfloat), 0);
3314 // dst rect edges in NDC (-1 to 1)
3315 int dw = dst->width();
3316 int dh = dst->height();
3317 GrGLfloat dx0 = 2.f * dstPoint.fX / dw - 1.f;
3318 GrGLfloat dx1 = 2.f * (dstPoint.fX + w) / dw - 1.f;
3319 GrGLfloat dy0 = 2.f * dstPoint.fY / dh - 1.f;
3320 GrGLfloat dy1 = 2.f * (dstPoint.fY + h) / dh - 1.f;
3321 GrGLfloat sx0 = (GrGLfloat)srcRect.fLeft;
3322 GrGLfloat sx1 = (GrGLfloat)(srcRect.fLeft + w);
3323 GrGLfloat sy0 = (GrGLfloat)srcRect.fTop;
3324 GrGLfloat sy1 = (GrGLfloat)(srcRect.fTop + h);
3325 int sw = src->width();
3326 int sh = src->height();
3327 if (srcTex->texturePriv().textureType() != GrTextureType::kRectangle) {
3328 // src rect edges in normalized texture space (0 to 1)
3329 sx0 /= sw;
3330 sx1 /= sw;
3331 sy0 /= sh;
3332 sy1 /= sh;
3333 }
3334 GL_CALL(Uniform4f(fCopyPrograms[progIdx].fPosXformUniform, dx1 - dx0, dy1 - dy0, dx0, dy0));
3335 GL_CALL(Uniform4f(fCopyPrograms[progIdx].fTexCoordXformUniform,
3336 sx1 - sx0, sy1 - sy0, sx0, sy0));
3337 GL_CALL(Uniform1i(fCopyPrograms[progIdx].fTextureUniform, 0));
3338 this->flushBlendAndColorWrite(GrXferProcessor::BlendInfo(), GrSwizzle::RGBA());
3339 this->flushHWAAState(nullptr, false);
3340 this->disableScissor();
3341 this->disableWindowRectangles();
3342 this->disableStencil();
3343 if (this->glCaps().srgbWriteControl()) {
3344 this->flushFramebufferSRGB(true);
3345 }
3346 GL_CALL(DrawArrays(GR_GL_TRIANGLE_STRIP, 0, 4));
3347 this->unbindSurfaceFBOForPixelOps(dst, 0, GR_GL_FRAMEBUFFER);
3348 // The rect is already in device space so we pass in kTopLeft so no flip is done.
3349 this->didWriteToSurface(dst, kTopLeft_GrSurfaceOrigin, &dstRect);
3350 return true;
3351 }
3352
copySurfaceAsCopyTexSubImage(GrSurface * dst,GrSurface * src,const SkIRect & srcRect,const SkIPoint & dstPoint)3353 void GrGLGpu::copySurfaceAsCopyTexSubImage(GrSurface* dst, GrSurface* src, const SkIRect& srcRect,
3354 const SkIPoint& dstPoint) {
3355 SkASSERT(can_copy_texsubimage(dst, src, this->glCaps()));
3356 this->bindSurfaceFBOForPixelOps(src, 0, GR_GL_FRAMEBUFFER, kSrc_TempFBOTarget);
3357 GrGLTexture* dstTex = static_cast<GrGLTexture *>(dst->asTexture());
3358 SkASSERT(dstTex);
3359 // We modified the bound FBO
3360 fHWBoundRenderTargetUniqueID.makeInvalid();
3361
3362 this->bindTextureToScratchUnit(dstTex->target(), dstTex->textureID());
3363 GL_CALL(CopyTexSubImage2D(dstTex->target(), 0,
3364 dstPoint.fX, dstPoint.fY,
3365 srcRect.fLeft, srcRect.fTop,
3366 srcRect.width(), srcRect.height()));
3367 this->unbindSurfaceFBOForPixelOps(src, 0, GR_GL_FRAMEBUFFER);
3368 SkIRect dstRect = SkIRect::MakeXYWH(dstPoint.fX, dstPoint.fY,
3369 srcRect.width(), srcRect.height());
3370 // The rect is already in device space so we pass in kTopLeft so no flip is done.
3371 this->didWriteToSurface(dst, kTopLeft_GrSurfaceOrigin, &dstRect);
3372 }
3373
copySurfaceAsBlitFramebuffer(GrSurface * dst,GrSurface * src,const SkIRect & srcRect,const SkIPoint & dstPoint)3374 bool GrGLGpu::copySurfaceAsBlitFramebuffer(GrSurface* dst, GrSurface* src, const SkIRect& srcRect,
3375 const SkIPoint& dstPoint) {
3376 SkASSERT(can_blit_framebuffer_for_copy_surface(dst, src, srcRect, dstPoint, this->glCaps()));
3377 SkIRect dstRect = SkIRect::MakeXYWH(dstPoint.fX, dstPoint.fY,
3378 srcRect.width(), srcRect.height());
3379 if (dst == src) {
3380 if (SkIRect::Intersects(dstRect, srcRect)) {
3381 return false;
3382 }
3383 }
3384
3385 this->bindSurfaceFBOForPixelOps(dst, 0, GR_GL_DRAW_FRAMEBUFFER, kDst_TempFBOTarget);
3386 this->bindSurfaceFBOForPixelOps(src, 0, GR_GL_READ_FRAMEBUFFER, kSrc_TempFBOTarget);
3387 // We modified the bound FBO
3388 fHWBoundRenderTargetUniqueID.makeInvalid();
3389
3390 // BlitFrameBuffer respects the scissor, so disable it.
3391 this->disableScissor();
3392 this->disableWindowRectangles();
3393
3394 GL_CALL(BlitFramebuffer(srcRect.fLeft,
3395 srcRect.fTop,
3396 srcRect.fRight,
3397 srcRect.fBottom,
3398 dstRect.fLeft,
3399 dstRect.fTop,
3400 dstRect.fRight,
3401 dstRect.fBottom,
3402 GR_GL_COLOR_BUFFER_BIT, GR_GL_NEAREST));
3403 this->unbindSurfaceFBOForPixelOps(dst, 0, GR_GL_DRAW_FRAMEBUFFER);
3404 this->unbindSurfaceFBOForPixelOps(src, 0, GR_GL_READ_FRAMEBUFFER);
3405
3406 // The rect is already in device space so we pass in kTopLeft so no flip is done.
3407 this->didWriteToSurface(dst, kTopLeft_GrSurfaceOrigin, &dstRect);
3408 return true;
3409 }
3410
onRegenerateMipMapLevels(GrTexture * texture)3411 bool GrGLGpu::onRegenerateMipMapLevels(GrTexture* texture) {
3412 auto glTex = static_cast<GrGLTexture*>(texture);
3413 // Mipmaps are only supported on 2D textures:
3414 if (GR_GL_TEXTURE_2D != glTex->target()) {
3415 return false;
3416 }
3417 GrGLFormat format = glTex->format();
3418 // Manual implementation of mipmap generation, to work around driver bugs w/sRGB.
3419 // Uses draw calls to do a series of downsample operations to successive mips.
3420
3421 // The manual approach requires the ability to limit which level we're sampling and that the
3422 // destination can be bound to a FBO:
3423 if (!this->glCaps().doManualMipmapping() || !this->glCaps().isFormatRenderable(format, 1)) {
3424 GrGLenum target = glTex->target();
3425 this->bindTextureToScratchUnit(target, glTex->textureID());
3426 GL_CALL(GenerateMipmap(glTex->target()));
3427 return true;
3428 }
3429
3430 int width = texture->width();
3431 int height = texture->height();
3432 int levelCount = SkMipMap::ComputeLevelCount(width, height) + 1;
3433 SkASSERT(levelCount == texture->texturePriv().maxMipMapLevel() + 1);
3434
3435 // Create (if necessary), then bind temporary FBO:
3436 if (0 == fTempDstFBOID) {
3437 GL_CALL(GenFramebuffers(1, &fTempDstFBOID));
3438 }
3439 this->bindFramebuffer(GR_GL_FRAMEBUFFER, fTempDstFBOID);
3440 fHWBoundRenderTargetUniqueID.makeInvalid();
3441
3442 // Bind the texture, to get things configured for filtering.
3443 // We'll be changing our base level further below:
3444 this->setTextureUnit(0);
3445 // The mipmap program does not do any swizzling.
3446 this->bindTexture(0, GrSamplerState::ClampBilerp(), GrSwizzle::RGBA(), glTex);
3447
3448 // Vertex data:
3449 if (!fMipmapProgramArrayBuffer) {
3450 static const GrGLfloat vdata[] = {
3451 0, 0,
3452 0, 1,
3453 1, 0,
3454 1, 1
3455 };
3456 fMipmapProgramArrayBuffer = GrGLBuffer::Make(this, sizeof(vdata), GrGpuBufferType::kVertex,
3457 kStatic_GrAccessPattern, vdata);
3458 }
3459 if (!fMipmapProgramArrayBuffer) {
3460 return false;
3461 }
3462
3463 fHWVertexArrayState.setVertexArrayID(this, 0);
3464
3465 GrGLAttribArrayState* attribs = fHWVertexArrayState.bindInternalVertexArray(this);
3466 attribs->enableVertexArrays(this, 1);
3467 attribs->set(this, 0, fMipmapProgramArrayBuffer.get(), kFloat2_GrVertexAttribType,
3468 kFloat2_GrSLType, 2 * sizeof(GrGLfloat), 0);
3469
3470 // Set "simple" state once:
3471 this->flushBlendAndColorWrite(GrXferProcessor::BlendInfo(), GrSwizzle::RGBA());
3472 this->flushHWAAState(nullptr, false);
3473 this->disableScissor();
3474 this->disableWindowRectangles();
3475 this->disableStencil();
3476
3477 // Do all the blits:
3478 width = texture->width();
3479 height = texture->height();
3480
3481 for (GrGLint level = 1; level < levelCount; ++level) {
3482 // Get and bind the program for this particular downsample (filter shape can vary):
3483 int progIdx = TextureSizeToMipmapProgramIdx(width, height);
3484 if (!fMipmapPrograms[progIdx].fProgram) {
3485 if (!this->createMipmapProgram(progIdx)) {
3486 SkDebugf("Failed to create mipmap program.\n");
3487 // Invalidate all params to cover base level change in a previous iteration.
3488 glTex->textureParamsModified();
3489 return false;
3490 }
3491 }
3492 this->flushProgram(fMipmapPrograms[progIdx].fProgram);
3493
3494 // Texcoord uniform is expected to contain (1/w, (w-1)/w, 1/h, (h-1)/h)
3495 const float invWidth = 1.0f / width;
3496 const float invHeight = 1.0f / height;
3497 GL_CALL(Uniform4f(fMipmapPrograms[progIdx].fTexCoordXformUniform,
3498 invWidth, (width - 1) * invWidth, invHeight, (height - 1) * invHeight));
3499 GL_CALL(Uniform1i(fMipmapPrograms[progIdx].fTextureUniform, 0));
3500
3501 // Only sample from previous mip
3502 GL_CALL(TexParameteri(GR_GL_TEXTURE_2D, GR_GL_TEXTURE_BASE_LEVEL, level - 1));
3503
3504 GL_CALL(FramebufferTexture2D(GR_GL_FRAMEBUFFER, GR_GL_COLOR_ATTACHMENT0, GR_GL_TEXTURE_2D,
3505 glTex->textureID(), level));
3506
3507 width = SkTMax(1, width / 2);
3508 height = SkTMax(1, height / 2);
3509 this->flushViewport(width, height);
3510
3511 GL_CALL(DrawArrays(GR_GL_TRIANGLE_STRIP, 0, 4));
3512 }
3513
3514 // Unbind:
3515 GL_CALL(FramebufferTexture2D(GR_GL_FRAMEBUFFER, GR_GL_COLOR_ATTACHMENT0,
3516 GR_GL_TEXTURE_2D, 0, 0));
3517
3518 // We modified the base level param.
3519 GrGLTextureParameters::NonsamplerState nonsamplerState = glTex->parameters()->nonsamplerState();
3520 // We drew the 2nd to last level into the last level.
3521 nonsamplerState.fBaseMipMapLevel = levelCount - 2;
3522 glTex->parameters()->set(nullptr, nonsamplerState, fResetTimestampForTextureParameters);
3523
3524 return true;
3525 }
3526
querySampleLocations(GrRenderTarget * renderTarget,SkTArray<SkPoint> * sampleLocations)3527 void GrGLGpu::querySampleLocations(
3528 GrRenderTarget* renderTarget, SkTArray<SkPoint>* sampleLocations) {
3529 this->flushRenderTargetNoColorWrites(static_cast<GrGLRenderTarget*>(renderTarget));
3530
3531 int effectiveSampleCnt;
3532 GR_GL_GetIntegerv(this->glInterface(), GR_GL_SAMPLES, &effectiveSampleCnt);
3533 SkASSERT(effectiveSampleCnt >= renderTarget->numSamples());
3534
3535 sampleLocations->reset(effectiveSampleCnt);
3536 for (int i = 0; i < effectiveSampleCnt; ++i) {
3537 GL_CALL(GetMultisamplefv(GR_GL_SAMPLE_POSITION, i, &(*sampleLocations)[i].fX));
3538 }
3539 }
3540
xferBarrier(GrRenderTarget * rt,GrXferBarrierType type)3541 void GrGLGpu::xferBarrier(GrRenderTarget* rt, GrXferBarrierType type) {
3542 SkASSERT(type);
3543 switch (type) {
3544 case kTexture_GrXferBarrierType: {
3545 GrGLRenderTarget* glrt = static_cast<GrGLRenderTarget*>(rt);
3546 SkASSERT(glrt->textureFBOID() != 0 && glrt->renderFBOID() != 0);
3547 if (glrt->textureFBOID() != glrt->renderFBOID()) {
3548 // The render target uses separate storage so no need for glTextureBarrier.
3549 // FIXME: The render target will resolve automatically when its texture is bound,
3550 // but we could resolve only the bounds that will be read if we do it here instead.
3551 return;
3552 }
3553 SkASSERT(this->caps()->textureBarrierSupport());
3554 GL_CALL(TextureBarrier());
3555 return;
3556 }
3557 case kBlend_GrXferBarrierType:
3558 SkASSERT(GrCaps::kAdvanced_BlendEquationSupport ==
3559 this->caps()->blendEquationSupport());
3560 GL_CALL(BlendBarrier());
3561 return;
3562 default: break; // placate compiler warnings that kNone not handled
3563 }
3564 }
3565
gl_format_to_pixel_config(GrGLFormat format)3566 static GrPixelConfig gl_format_to_pixel_config(GrGLFormat format) {
3567 switch (format) {
3568 case GrGLFormat::kRGBA8: return kRGBA_8888_GrPixelConfig;
3569 case GrGLFormat::kRGB8: return kRGB_888_GrPixelConfig;
3570 case GrGLFormat::kRG8: return kRG_88_GrPixelConfig;
3571 case GrGLFormat::kBGRA8: return kBGRA_8888_GrPixelConfig;
3572 case GrGLFormat::kLUMINANCE8: return kGray_8_GrPixelConfig;
3573 case GrGLFormat::kSRGB8_ALPHA8: return kSRGBA_8888_GrPixelConfig;
3574 case GrGLFormat::kRGB10_A2: return kRGBA_1010102_GrPixelConfig;
3575 case GrGLFormat::kRGB565: return kRGB_565_GrPixelConfig;
3576 case GrGLFormat::kRGBA4: return kRGBA_4444_GrPixelConfig;
3577 case GrGLFormat::kRGBA16F: return kRGBA_half_GrPixelConfig;
3578 case GrGLFormat::kR16: return kAlpha_16_GrPixelConfig;
3579 case GrGLFormat::kRG16: return kRG_1616_GrPixelConfig;
3580 case GrGLFormat::kRGBA16: return kRGBA_16161616_GrPixelConfig;
3581 case GrGLFormat::kRG16F: return kRG_half_GrPixelConfig;
3582 case GrGLFormat::kUnknown: return kUnknown_GrPixelConfig;
3583
3584 // Configs with multiple equivalent formats.
3585
3586 case GrGLFormat::kR16F: return kAlpha_half_GrPixelConfig;
3587 case GrGLFormat::kLUMINANCE16F: return kAlpha_half_GrPixelConfig;
3588
3589 case GrGLFormat::kALPHA8: return kAlpha_8_GrPixelConfig;
3590 case GrGLFormat::kR8: return kAlpha_8_GrPixelConfig;
3591
3592 case GrGLFormat::kCOMPRESSED_RGB8_ETC2: return kRGB_ETC1_GrPixelConfig;
3593 case GrGLFormat::kCOMPRESSED_ETC1_RGB8: return kRGB_ETC1_GrPixelConfig;
3594 }
3595 SkUNREACHABLE;
3596 }
3597
onCreateBackendTexture(int w,int h,const GrBackendFormat & format,GrMipMapped mipMapped,GrRenderable renderable,const SkPixmap srcData[],int numMipLevels,const SkColor4f * color,GrProtected isProtected)3598 GrBackendTexture GrGLGpu::onCreateBackendTexture(int w, int h,
3599 const GrBackendFormat& format,
3600 GrMipMapped mipMapped,
3601 GrRenderable renderable,
3602 const SkPixmap srcData[], int numMipLevels,
3603 const SkColor4f* color,
3604 GrProtected isProtected) {
3605 this->handleDirtyContext();
3606
3607 SkDEBUGCODE(const GrCaps* caps = this->caps();)
3608
3609 // GrGpu::createBackendTexture should've ensured these conditions
3610 SkASSERT(w >= 1 && w <= caps->maxTextureSize() && h >= 1 && h <= caps->maxTextureSize());
3611 SkASSERT(GrGpu::MipMapsAreCorrect(w, h, mipMapped, srcData, numMipLevels));
3612 SkASSERT(mipMapped == GrMipMapped::kNo || caps->mipMapSupport());
3613
3614 GrGLFormat glFormat = format.asGLFormat();
3615 if (glFormat == GrGLFormat::kUnknown) {
3616 return GrBackendTexture(); // invalid
3617 }
3618
3619 // Compressed formats go through onCreateCompressedBackendTexture
3620 SkASSERT(!GrGLFormatIsCompressed(glFormat));
3621
3622 GrPixelConfig config = gl_format_to_pixel_config(glFormat);
3623
3624 if (config == kUnknown_GrPixelConfig) {
3625 return GrBackendTexture(); // invalid
3626 }
3627
3628 auto textureColorType = GrPixelConfigToColorType(config);
3629
3630 // TODO: move the texturability check up to GrGpu::createBackendTexture and just assert here
3631 if (!this->caps()->isFormatTexturableAndUploadable(textureColorType, format)) {
3632 return GrBackendTexture(); // invalid
3633 }
3634
3635 GrGLTextureInfo info;
3636 GrGLTextureParameters::SamplerOverriddenState initialState;
3637
3638 SkTDArray<GrMipLevel> texels;
3639 SkAutoMalloc pixelStorage;
3640
3641 int mipLevelCount = 1;
3642 if (srcData) {
3643 mipLevelCount = numMipLevels;
3644 texels.append(mipLevelCount);
3645 for (int i = 0; i < mipLevelCount; ++i) {
3646 texels[i] = { srcData[i].addr(), srcData[i].rowBytes() };
3647 }
3648 } else if (color) {
3649 if (GrMipMapped::kYes == mipMapped) {
3650 mipLevelCount = SkMipMap::ComputeLevelCount(w, h) + 1;
3651 }
3652
3653 texels.append(mipLevelCount);
3654 SkTArray<size_t> individualMipOffsets(mipLevelCount);
3655
3656 size_t bytesPerPixel = this->glCaps().bytesPerPixel(glFormat);
3657
3658 size_t totalSize = GrComputeTightCombinedBufferSize(
3659 bytesPerPixel, w, h, &individualMipOffsets, mipLevelCount);
3660
3661 char* tmpPixels = (char*)pixelStorage.reset(totalSize);
3662
3663 GrFillInData(textureColorType, w, h, individualMipOffsets, tmpPixels, *color);
3664 for (int i = 0; i < mipLevelCount; ++i) {
3665 size_t offset = individualMipOffsets[i];
3666
3667 int twoToTheMipLevel = 1 << i;
3668 int currentWidth = SkTMax(1, w / twoToTheMipLevel);
3669
3670 texels[i] = {&(tmpPixels[offset]), currentWidth * bytesPerPixel};
3671 }
3672 }
3673
3674 GrSurfaceDesc desc;
3675 desc.fWidth = w;
3676 desc.fHeight = h;
3677 desc.fConfig = config;
3678
3679 info.fTarget = GR_GL_TEXTURE_2D;
3680 info.fFormat = GrGLFormatToEnum(glFormat);
3681 info.fID = this->createTexture2D({desc.fWidth, desc.fHeight}, glFormat, renderable,
3682 &initialState, SkTMax(1, texels.count()));
3683 if (!info.fID) {
3684 return GrBackendTexture(); // invalid
3685 }
3686 auto srcColorType = GrPixelConfigToColorType(desc.fConfig);
3687 if (!texels.empty() &&
3688 !this->uploadTexData(glFormat, textureColorType, desc.fWidth, desc.fHeight,
3689 GR_GL_TEXTURE_2D, 0, 0, desc.fWidth, desc.fHeight, srcColorType,
3690 texels.begin(), texels.count())) {
3691 GL_CALL(DeleteTextures(1, &info.fID));
3692 return GrBackendTexture();
3693 }
3694
3695 // unbind the texture from the texture unit to avoid asserts
3696 GL_CALL(BindTexture(info.fTarget, 0));
3697
3698 auto parameters = sk_make_sp<GrGLTextureParameters>();
3699 parameters->set(&initialState, GrGLTextureParameters::NonsamplerState(),
3700 fResetTimestampForTextureParameters);
3701
3702 return GrBackendTexture(w, h, mipMapped, info, std::move(parameters));
3703 }
3704
deleteBackendTexture(const GrBackendTexture & tex)3705 void GrGLGpu::deleteBackendTexture(const GrBackendTexture& tex) {
3706 SkASSERT(GrBackendApi::kOpenGL == tex.backend());
3707
3708 GrGLTextureInfo info;
3709 if (tex.getGLTextureInfo(&info)) {
3710 GL_CALL(DeleteTextures(1, &info.fID));
3711 }
3712 }
3713
3714 #if GR_TEST_UTILS
3715
isTestingOnlyBackendTexture(const GrBackendTexture & tex) const3716 bool GrGLGpu::isTestingOnlyBackendTexture(const GrBackendTexture& tex) const {
3717 SkASSERT(GrBackendApi::kOpenGL == tex.backend());
3718
3719 GrGLTextureInfo info;
3720 if (!tex.getGLTextureInfo(&info)) {
3721 return false;
3722 }
3723
3724 GrGLboolean result;
3725 GL_CALL_RET(result, IsTexture(info.fID));
3726
3727 return (GR_GL_TRUE == result);
3728 }
3729
createTestingOnlyBackendRenderTarget(int w,int h,GrColorType colorType)3730 GrBackendRenderTarget GrGLGpu::createTestingOnlyBackendRenderTarget(int w, int h,
3731 GrColorType colorType) {
3732 if (w > this->caps()->maxRenderTargetSize() || h > this->caps()->maxRenderTargetSize()) {
3733 return GrBackendRenderTarget(); // invalid
3734 }
3735 this->handleDirtyContext();
3736 auto format = this->glCaps().getFormatFromColorType(colorType);
3737 if (!this->glCaps().isFormatRenderable(format, 1)) {
3738 return {};
3739 }
3740 bool useTexture = format == GrGLFormat::kBGRA8;
3741 int sFormatIdx = this->getCompatibleStencilIndex(format);
3742 if (sFormatIdx < 0) {
3743 return {};
3744 }
3745 GrGLuint colorID = 0;
3746 GrGLuint stencilID = 0;
3747 auto deleteIDs = [&] {
3748 if (colorID) {
3749 if (useTexture) {
3750 GL_CALL(DeleteTextures(1, &colorID));
3751 } else {
3752 GL_CALL(DeleteRenderbuffers(1, &colorID));
3753 }
3754 }
3755 if (stencilID) {
3756 GL_CALL(DeleteRenderbuffers(1, &stencilID));
3757 }
3758 };
3759
3760 if (useTexture) {
3761 GL_CALL(GenTextures(1, &colorID));
3762 } else {
3763 GL_CALL(GenRenderbuffers(1, &colorID));
3764 }
3765 GL_CALL(GenRenderbuffers(1, &stencilID));
3766 if (!stencilID || !colorID) {
3767 deleteIDs();
3768 return {};
3769 }
3770
3771 GrGLFramebufferInfo info;
3772 info.fFBOID = 0;
3773 info.fFormat = GrGLFormatToEnum(format);
3774 GL_CALL(GenFramebuffers(1, &info.fFBOID));
3775 if (!info.fFBOID) {
3776 deleteIDs();
3777 return {};
3778 }
3779
3780 this->invalidateBoundRenderTarget();
3781
3782 this->bindFramebuffer(GR_GL_FRAMEBUFFER, info.fFBOID);
3783 if (useTexture) {
3784 GrGLTextureParameters::SamplerOverriddenState initialState;
3785 colorID = this->createTexture2D({w, h}, format, GrRenderable::kYes, &initialState, 1);
3786 if (!colorID) {
3787 deleteIDs();
3788 return {};
3789 }
3790 GL_CALL(FramebufferTexture2D(GR_GL_FRAMEBUFFER, GR_GL_COLOR_ATTACHMENT0, GR_GL_TEXTURE_2D,
3791 colorID, 0));
3792 } else {
3793 GrGLenum renderBufferFormat = this->glCaps().getRenderbufferInternalFormat(format);
3794 GL_CALL(BindRenderbuffer(GR_GL_RENDERBUFFER, colorID));
3795 GL_ALLOC_CALL(this->glInterface(),
3796 RenderbufferStorage(GR_GL_RENDERBUFFER, renderBufferFormat, w, h));
3797 GL_CALL(FramebufferRenderbuffer(GR_GL_FRAMEBUFFER, GR_GL_COLOR_ATTACHMENT0,
3798 GR_GL_RENDERBUFFER, colorID));
3799 }
3800 GL_CALL(BindRenderbuffer(GR_GL_RENDERBUFFER, stencilID));
3801 auto stencilBufferFormat = this->glCaps().stencilFormats()[sFormatIdx].fInternalFormat;
3802 GL_ALLOC_CALL(this->glInterface(),
3803 RenderbufferStorage(GR_GL_RENDERBUFFER, stencilBufferFormat, w, h));
3804 GL_CALL(FramebufferRenderbuffer(GR_GL_FRAMEBUFFER, GR_GL_STENCIL_ATTACHMENT, GR_GL_RENDERBUFFER,
3805 stencilID));
3806 if (this->glCaps().stencilFormats()[sFormatIdx].fPacked) {
3807 GL_CALL(FramebufferRenderbuffer(GR_GL_FRAMEBUFFER, GR_GL_DEPTH_ATTACHMENT,
3808 GR_GL_RENDERBUFFER, stencilID));
3809 }
3810
3811 // We don't want to have to recover the renderbuffer/texture IDs later to delete them. OpenGL
3812 // has this rule that if a renderbuffer/texture is deleted and a FBO other than the current FBO
3813 // has the RB attached then deletion is delayed. So we unbind the FBO here and delete the
3814 // renderbuffers/texture.
3815 this->bindFramebuffer(GR_GL_FRAMEBUFFER, 0);
3816 deleteIDs();
3817
3818 this->bindFramebuffer(GR_GL_FRAMEBUFFER, info.fFBOID);
3819 GrGLenum status;
3820 GL_CALL_RET(status, CheckFramebufferStatus(GR_GL_FRAMEBUFFER));
3821 if (GR_GL_FRAMEBUFFER_COMPLETE != status) {
3822 this->deleteFramebuffer(info.fFBOID);
3823 return {};
3824 }
3825 auto stencilBits = SkToInt(this->glCaps().stencilFormats()[sFormatIdx].fStencilBits);
3826
3827 GrBackendRenderTarget beRT = GrBackendRenderTarget(w, h, 1, stencilBits, info);
3828 SkASSERT(this->caps()->areColorTypeAndFormatCompatible(colorType, beRT.getBackendFormat()));
3829 return beRT;
3830 }
3831
deleteTestingOnlyBackendRenderTarget(const GrBackendRenderTarget & backendRT)3832 void GrGLGpu::deleteTestingOnlyBackendRenderTarget(const GrBackendRenderTarget& backendRT) {
3833 SkASSERT(GrBackendApi::kOpenGL == backendRT.backend());
3834 GrGLFramebufferInfo info;
3835 if (backendRT.getGLFramebufferInfo(&info)) {
3836 if (info.fFBOID) {
3837 this->deleteFramebuffer(info.fFBOID);
3838 }
3839 }
3840 }
3841
testingOnly_flushGpuAndSync()3842 void GrGLGpu::testingOnly_flushGpuAndSync() {
3843 GL_CALL(Finish());
3844 }
3845 #endif
3846
3847 ///////////////////////////////////////////////////////////////////////////////
3848
bindInternalVertexArray(GrGLGpu * gpu,const GrBuffer * ibuf)3849 GrGLAttribArrayState* GrGLGpu::HWVertexArrayState::bindInternalVertexArray(GrGLGpu* gpu,
3850 const GrBuffer* ibuf) {
3851 GrGLAttribArrayState* attribState;
3852
3853 if (gpu->glCaps().isCoreProfile()) {
3854 if (!fCoreProfileVertexArray) {
3855 GrGLuint arrayID;
3856 GR_GL_CALL(gpu->glInterface(), GenVertexArrays(1, &arrayID));
3857 int attrCount = gpu->glCaps().maxVertexAttributes();
3858 fCoreProfileVertexArray = new GrGLVertexArray(arrayID, attrCount);
3859 }
3860 if (ibuf) {
3861 attribState = fCoreProfileVertexArray->bindWithIndexBuffer(gpu, ibuf);
3862 } else {
3863 attribState = fCoreProfileVertexArray->bind(gpu);
3864 }
3865 } else {
3866 if (ibuf) {
3867 // bindBuffer implicitly binds VAO 0 when binding an index buffer.
3868 gpu->bindBuffer(GrGpuBufferType::kIndex, ibuf);
3869 } else {
3870 this->setVertexArrayID(gpu, 0);
3871 }
3872 int attrCount = gpu->glCaps().maxVertexAttributes();
3873 if (fDefaultVertexArrayAttribState.count() != attrCount) {
3874 fDefaultVertexArrayAttribState.resize(attrCount);
3875 }
3876 attribState = &fDefaultVertexArrayAttribState;
3877 }
3878 return attribState;
3879 }
3880
onFinishFlush(GrSurfaceProxy * [],int,SkSurface::BackendSurfaceAccess access,const GrFlushInfo & info,const GrPrepareForExternalIORequests &)3881 void GrGLGpu::onFinishFlush(GrSurfaceProxy*[], int, SkSurface::BackendSurfaceAccess access,
3882 const GrFlushInfo& info, const GrPrepareForExternalIORequests&) {
3883 // If we inserted semaphores during the flush, we need to call GLFlush.
3884 bool insertedSemaphore = info.fNumSemaphores > 0 && this->caps()->semaphoreSupport();
3885 // We call finish if the client told us to sync or if we have a finished proc but don't support
3886 // GLsync objects.
3887 bool finish = (info.fFlags & kSyncCpu_GrFlushFlag) ||
3888 (info.fFinishedProc && !this->caps()->fenceSyncSupport());
3889 if (finish) {
3890 GL_CALL(Finish());
3891 // After a finish everything previously sent to GL is done.
3892 for (const auto& cb : fFinishCallbacks) {
3893 cb.fCallback(cb.fContext);
3894 this->deleteSync(cb.fSync);
3895 }
3896 fFinishCallbacks.clear();
3897 if (info.fFinishedProc) {
3898 info.fFinishedProc(info.fFinishedContext);
3899 }
3900 } else {
3901 if (info.fFinishedProc) {
3902 FinishCallback callback;
3903 callback.fCallback = info.fFinishedProc;
3904 callback.fContext = info.fFinishedContext;
3905 callback.fSync = (GrGLsync)this->insertFence();
3906 fFinishCallbacks.push_back(callback);
3907 GL_CALL(Flush());
3908 } else if (insertedSemaphore) {
3909 // Must call flush after semaphores in case they are waited on another GL context.
3910 GL_CALL(Flush());
3911 }
3912 // See if any previously inserted finish procs are good to go.
3913 this->checkFinishProcs();
3914 }
3915 }
3916
submit(GrOpsRenderPass * renderPass)3917 void GrGLGpu::submit(GrOpsRenderPass* renderPass) {
3918 // The GrGLOpsRenderPass doesn't buffer ops so there is nothing to do here
3919 SkASSERT(fCachedOpsRenderPass.get() == renderPass);
3920 fCachedOpsRenderPass->reset();
3921 }
3922
insertFence()3923 GrFence SK_WARN_UNUSED_RESULT GrGLGpu::insertFence() {
3924 SkASSERT(this->caps()->fenceSyncSupport());
3925 GrGLsync sync;
3926 GL_CALL_RET(sync, FenceSync(GR_GL_SYNC_GPU_COMMANDS_COMPLETE, 0));
3927 GR_STATIC_ASSERT(sizeof(GrFence) >= sizeof(GrGLsync));
3928 return (GrFence)sync;
3929 }
3930
waitSync(GrGLsync sync,uint64_t timeout,bool flush)3931 bool GrGLGpu::waitSync(GrGLsync sync, uint64_t timeout, bool flush) {
3932 GrGLbitfield flags = flush ? GR_GL_SYNC_FLUSH_COMMANDS_BIT : 0;
3933 GrGLenum result;
3934 GL_CALL_RET(result, ClientWaitSync(sync, flags, timeout));
3935 return (GR_GL_CONDITION_SATISFIED == result || GR_GL_ALREADY_SIGNALED == result);
3936 }
3937
waitFence(GrFence fence,uint64_t timeout)3938 bool GrGLGpu::waitFence(GrFence fence, uint64_t timeout) {
3939 return this->waitSync((GrGLsync)fence, timeout, /* flush = */ true);
3940 }
3941
deleteFence(GrFence fence) const3942 void GrGLGpu::deleteFence(GrFence fence) const {
3943 this->deleteSync((GrGLsync)fence);
3944 }
3945
makeSemaphore(bool isOwned)3946 sk_sp<GrSemaphore> SK_WARN_UNUSED_RESULT GrGLGpu::makeSemaphore(bool isOwned) {
3947 SkASSERT(this->caps()->semaphoreSupport());
3948 return GrGLSemaphore::Make(this, isOwned);
3949 }
3950
wrapBackendSemaphore(const GrBackendSemaphore & semaphore,GrResourceProvider::SemaphoreWrapType wrapType,GrWrapOwnership ownership)3951 sk_sp<GrSemaphore> GrGLGpu::wrapBackendSemaphore(const GrBackendSemaphore& semaphore,
3952 GrResourceProvider::SemaphoreWrapType wrapType,
3953 GrWrapOwnership ownership) {
3954 SkASSERT(this->caps()->semaphoreSupport());
3955 return GrGLSemaphore::MakeWrapped(this, semaphore.glSync(), ownership);
3956 }
3957
insertSemaphore(sk_sp<GrSemaphore> semaphore)3958 void GrGLGpu::insertSemaphore(sk_sp<GrSemaphore> semaphore) {
3959 GrGLSemaphore* glSem = static_cast<GrGLSemaphore*>(semaphore.get());
3960
3961 GrGLsync sync;
3962 GL_CALL_RET(sync, FenceSync(GR_GL_SYNC_GPU_COMMANDS_COMPLETE, 0));
3963 glSem->setSync(sync);
3964 }
3965
waitSemaphore(sk_sp<GrSemaphore> semaphore)3966 void GrGLGpu::waitSemaphore(sk_sp<GrSemaphore> semaphore) {
3967 GrGLSemaphore* glSem = static_cast<GrGLSemaphore*>(semaphore.get());
3968
3969 GL_CALL(WaitSync(glSem->sync(), 0, GR_GL_TIMEOUT_IGNORED));
3970 }
3971
checkFinishProcs()3972 void GrGLGpu::checkFinishProcs() {
3973 // Bail after the first unfinished sync since we expect they signal in the order inserted.
3974 while (!fFinishCallbacks.empty() && this->waitSync(fFinishCallbacks.front().fSync,
3975 /* timeout = */ 0, /* flush = */ false)) {
3976 fFinishCallbacks.front().fCallback(fFinishCallbacks.front().fContext);
3977 this->deleteSync(fFinishCallbacks.front().fSync);
3978 fFinishCallbacks.pop_front();
3979 }
3980 }
3981
deleteSync(GrGLsync sync) const3982 void GrGLGpu::deleteSync(GrGLsync sync) const {
3983 GL_CALL(DeleteSync(sync));
3984 }
3985
insertEventMarker(const char * msg)3986 void GrGLGpu::insertEventMarker(const char* msg) {
3987 GL_CALL(InsertEventMarker(strlen(msg), msg));
3988 }
3989
prepareTextureForCrossContextUsage(GrTexture * texture)3990 sk_sp<GrSemaphore> GrGLGpu::prepareTextureForCrossContextUsage(GrTexture* texture) {
3991 // Set up a semaphore to be signaled once the data is ready, and flush GL
3992 sk_sp<GrSemaphore> semaphore = this->makeSemaphore(true);
3993 this->insertSemaphore(semaphore);
3994 // We must call flush here to make sure the GrGLSync object gets created and sent to the gpu.
3995 GL_CALL(Flush());
3996
3997 return semaphore;
3998 }
3999
TextureToCopyProgramIdx(GrTexture * texture)4000 int GrGLGpu::TextureToCopyProgramIdx(GrTexture* texture) {
4001 switch (GrSLCombinedSamplerTypeForTextureType(texture->texturePriv().textureType())) {
4002 case kTexture2DSampler_GrSLType:
4003 return 0;
4004 case kTexture2DRectSampler_GrSLType:
4005 return 1;
4006 case kTextureExternalSampler_GrSLType:
4007 return 2;
4008 default:
4009 SK_ABORT("Unexpected samper type");
4010 }
4011 }
4012
4013 #ifdef SK_ENABLE_DUMP_GPU
4014 #include "src/utils/SkJSONWriter.h"
onDumpJSON(SkJSONWriter * writer) const4015 void GrGLGpu::onDumpJSON(SkJSONWriter* writer) const {
4016 // We are called by the base class, which has already called beginObject(). We choose to nest
4017 // all of our caps information in a named sub-object.
4018 writer->beginObject("GL GPU");
4019
4020 const GrGLubyte* str;
4021 GL_CALL_RET(str, GetString(GR_GL_VERSION));
4022 writer->appendString("GL_VERSION", (const char*)(str));
4023 GL_CALL_RET(str, GetString(GR_GL_RENDERER));
4024 writer->appendString("GL_RENDERER", (const char*)(str));
4025 GL_CALL_RET(str, GetString(GR_GL_VENDOR));
4026 writer->appendString("GL_VENDOR", (const char*)(str));
4027 GL_CALL_RET(str, GetString(GR_GL_SHADING_LANGUAGE_VERSION));
4028 writer->appendString("GL_SHADING_LANGUAGE_VERSION", (const char*)(str));
4029
4030 writer->appendName("extensions");
4031 glInterface()->fExtensions.dumpJSON(writer);
4032
4033 writer->endObject();
4034 }
4035 #endif
4036