• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2015 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/SkDrawable.h"
9 #include "include/gpu/GrBackendSemaphore.h"
10 #include "include/private/GrRecordingContext.h"
11 #include "include/private/SkShadowFlags.h"
12 #include "include/utils/SkShadowUtils.h"
13 #include "src/core/SkAutoPixmapStorage.h"
14 #include "src/core/SkConvertPixels.h"
15 #include "src/core/SkDrawShadowInfo.h"
16 #include "src/core/SkGlyphRunPainter.h"
17 #include "src/core/SkLatticeIter.h"
18 #include "src/core/SkMatrixPriv.h"
19 #include "src/core/SkRRectPriv.h"
20 #include "src/core/SkSurfacePriv.h"
21 #include "src/gpu/GrAppliedClip.h"
22 #include "src/gpu/GrAuditTrail.h"
23 #include "src/gpu/GrBlurUtils.h"
24 #include "src/gpu/GrCaps.h"
25 #include "src/gpu/GrColor.h"
26 #include "src/gpu/GrContextPriv.h"
27 #include "src/gpu/GrDataUtils.h"
28 #include "src/gpu/GrDrawingManager.h"
29 #include "src/gpu/GrFixedClip.h"
30 #include "src/gpu/GrGpuResourcePriv.h"
31 #include "src/gpu/GrMemoryPool.h"
32 #include "src/gpu/GrOpList.h"
33 #include "src/gpu/GrPathRenderer.h"
34 #include "src/gpu/GrRecordingContextPriv.h"
35 #include "src/gpu/GrRenderTarget.h"
36 #include "src/gpu/GrRenderTargetContext.h"
37 #include "src/gpu/GrRenderTargetContextPriv.h"
38 #include "src/gpu/GrResourceProvider.h"
39 #include "src/gpu/GrStencilAttachment.h"
40 #include "src/gpu/GrStyle.h"
41 #include "src/gpu/GrTracing.h"
42 #include "src/gpu/SkGr.h"
43 #include "src/gpu/effects/GrBicubicEffect.h"
44 #include "src/gpu/effects/GrRRectEffect.h"
45 #include "src/gpu/effects/GrTextureDomain.h"
46 #include "src/gpu/effects/generated/GrColorMatrixFragmentProcessor.h"
47 #include "src/gpu/geometry/GrQuad.h"
48 #include "src/gpu/geometry/GrQuadUtils.h"
49 #include "src/gpu/geometry/GrShape.h"
50 #include "src/gpu/ops/GrAtlasTextOp.h"
51 #include "src/gpu/ops/GrClearOp.h"
52 #include "src/gpu/ops/GrClearStencilClipOp.h"
53 #include "src/gpu/ops/GrDebugMarkerOp.h"
54 #include "src/gpu/ops/GrDrawAtlasOp.h"
55 #include "src/gpu/ops/GrDrawOp.h"
56 #include "src/gpu/ops/GrDrawVerticesOp.h"
57 #include "src/gpu/ops/GrDrawableOp.h"
58 #include "src/gpu/ops/GrFillRRectOp.h"
59 #include "src/gpu/ops/GrFillRectOp.h"
60 #include "src/gpu/ops/GrLatticeOp.h"
61 #include "src/gpu/ops/GrOp.h"
62 #include "src/gpu/ops/GrOvalOpFactory.h"
63 #include "src/gpu/ops/GrRegionOp.h"
64 #include "src/gpu/ops/GrSemaphoreOp.h"
65 #include "src/gpu/ops/GrShadowRRectOp.h"
66 #include "src/gpu/ops/GrStencilPathOp.h"
67 #include "src/gpu/ops/GrStrokeRectOp.h"
68 #include "src/gpu/ops/GrTextureOp.h"
69 #include "src/gpu/ops/GrTransferFromOp.h"
70 #include "src/gpu/text/GrTextContext.h"
71 #include "src/gpu/text/GrTextTarget.h"
72 
73 class GrRenderTargetContext::TextTarget : public GrTextTarget {
74 public:
TextTarget(GrRenderTargetContext * renderTargetContext)75     TextTarget(GrRenderTargetContext* renderTargetContext)
76             : GrTextTarget(renderTargetContext->width(), renderTargetContext->height(),
77                            renderTargetContext->colorSpaceInfo())
78             , fRenderTargetContext(renderTargetContext)
79             , fGlyphPainter{*renderTargetContext}{}
80 
addDrawOp(const GrClip & clip,std::unique_ptr<GrAtlasTextOp> op)81     void addDrawOp(const GrClip& clip, std::unique_ptr<GrAtlasTextOp> op) override {
82         fRenderTargetContext->addDrawOp(clip, std::move(op));
83     }
84 
drawShape(const GrClip & clip,const SkPaint & paint,const SkMatrix & viewMatrix,const GrShape & shape)85     void drawShape(const GrClip& clip, const SkPaint& paint,
86                   const SkMatrix& viewMatrix, const GrShape& shape) override {
87         GrBlurUtils::drawShapeWithMaskFilter(fRenderTargetContext->fContext, fRenderTargetContext,
88                                              clip, paint, viewMatrix, shape);
89     }
90 
makeGrPaint(GrMaskFormat maskFormat,const SkPaint & skPaint,const SkMatrix & viewMatrix,GrPaint * grPaint)91     void makeGrPaint(GrMaskFormat maskFormat, const SkPaint& skPaint, const SkMatrix& viewMatrix,
92                      GrPaint* grPaint) override {
93         auto context = fRenderTargetContext->fContext;
94         const GrColorSpaceInfo& colorSpaceInfo = fRenderTargetContext->colorSpaceInfo();
95         if (kARGB_GrMaskFormat == maskFormat) {
96             SkPaintToGrPaintWithPrimitiveColor(context, colorSpaceInfo, skPaint, grPaint);
97         } else {
98             SkPaintToGrPaint(context, colorSpaceInfo, skPaint, viewMatrix, grPaint);
99         }
100     }
101 
getContext()102     GrRecordingContext* getContext() override {
103         return fRenderTargetContext->fContext;
104     }
105 
glyphPainter()106     SkGlyphRunListPainter* glyphPainter() override {
107         return &fGlyphPainter;
108     }
109 
110 private:
111     GrRenderTargetContext* fRenderTargetContext;
112     SkGlyphRunListPainter fGlyphPainter;
113 
114 };
115 
116 #define ASSERT_OWNED_RESOURCE(R) SkASSERT(!(R) || (R)->getContext() == this->drawingManager()->getContext())
117 #define ASSERT_SINGLE_OWNER \
118     SkDEBUGCODE(GrSingleOwner::AutoEnforce debug_SingleOwner(this->singleOwner());)
119 #define ASSERT_SINGLE_OWNER_PRIV \
120     SkDEBUGCODE(GrSingleOwner::AutoEnforce debug_SingleOwner(fRenderTargetContext->singleOwner());)
121 #define RETURN_IF_ABANDONED        if (fContext->priv().abandoned()) { return; }
122 #define RETURN_IF_ABANDONED_PRIV   if (fRenderTargetContext->fContext->priv().abandoned()) { return; }
123 #define RETURN_FALSE_IF_ABANDONED  if (fContext->priv().abandoned()) { return false; }
124 #define RETURN_FALSE_IF_ABANDONED_PRIV  if (fRenderTargetContext->fContext->priv().abandoned()) { return false; }
125 #define RETURN_NULL_IF_ABANDONED   if (fContext->priv().abandoned()) { return nullptr; }
126 
127 //////////////////////////////////////////////////////////////////////////////
128 
129 class AutoCheckFlush {
130 public:
AutoCheckFlush(GrDrawingManager * drawingManager)131     AutoCheckFlush(GrDrawingManager* drawingManager) : fDrawingManager(drawingManager) {
132         SkASSERT(fDrawingManager);
133     }
~AutoCheckFlush()134     ~AutoCheckFlush() { fDrawingManager->flushIfNecessary(); }
135 
136 private:
137     GrDrawingManager* fDrawingManager;
138 };
139 
140 // In MDB mode the reffing of the 'getLastOpList' call's result allows in-progress
141 // GrOpLists to be picked up and added to by renderTargetContexts lower in the call
142 // stack. When this occurs with a closed GrOpList, a new one will be allocated
143 // when the renderTargetContext attempts to use it (via getOpList).
GrRenderTargetContext(GrRecordingContext * context,sk_sp<GrRenderTargetProxy> rtp,GrColorType colorType,sk_sp<SkColorSpace> colorSpace,const SkSurfaceProps * surfaceProps,bool managedOpList)144 GrRenderTargetContext::GrRenderTargetContext(GrRecordingContext* context,
145                                              sk_sp<GrRenderTargetProxy> rtp,
146                                              GrColorType colorType,
147                                              sk_sp<SkColorSpace> colorSpace,
148                                              const SkSurfaceProps* surfaceProps,
149                                              bool managedOpList)
150         : GrSurfaceContext(context, colorType, kPremul_SkAlphaType, std::move(colorSpace))
151         , fRenderTargetProxy(std::move(rtp))
152         , fOpList(sk_ref_sp(fRenderTargetProxy->getLastRenderTargetOpList()))
153         , fSurfaceProps(SkSurfacePropsCopyOrDefault(surfaceProps))
154         , fManagedOpList(managedOpList) {
155     fTextTarget.reset(new TextTarget(this));
156     SkDEBUGCODE(this->validate();)
157 }
158 
159 #ifdef SK_DEBUG
validate() const160 void GrRenderTargetContext::validate() const {
161     SkASSERT(fRenderTargetProxy);
162     fRenderTargetProxy->validate(fContext);
163 
164     if (fOpList && !fOpList->isClosed()) {
165         SkASSERT(fRenderTargetProxy->getLastRenderTask() == fOpList.get());
166     }
167 }
168 #endif
169 
~GrRenderTargetContext()170 GrRenderTargetContext::~GrRenderTargetContext() {
171     ASSERT_SINGLE_OWNER
172 }
173 
chooseAAType(GrAA aa)174 inline GrAAType GrRenderTargetContext::chooseAAType(GrAA aa) {
175     if (GrAA::kNo == aa) {
176         // On some devices we cannot disable MSAA if it is enabled so we make the AA type reflect
177         // that.
178         if (this->numSamples() > 1 && !this->caps()->multisampleDisableSupport()) {
179             return GrAAType::kMSAA;
180         }
181         return GrAAType::kNone;
182     }
183     return (this->numSamples() > 1) ? GrAAType::kMSAA : GrAAType::kCoverage;
184 }
185 
asTextureProxy()186 GrTextureProxy* GrRenderTargetContext::asTextureProxy() {
187     return fRenderTargetProxy->asTextureProxy();
188 }
189 
asTextureProxy() const190 const GrTextureProxy* GrRenderTargetContext::asTextureProxy() const {
191     return fRenderTargetProxy->asTextureProxy();
192 }
193 
asTextureProxyRef()194 sk_sp<GrTextureProxy> GrRenderTargetContext::asTextureProxyRef() {
195     return sk_ref_sp(fRenderTargetProxy->asTextureProxy());
196 }
197 
mipMapped() const198 GrMipMapped GrRenderTargetContext::mipMapped() const {
199     if (const GrTextureProxy* proxy = this->asTextureProxy()) {
200         return proxy->mipMapped();
201     }
202     return GrMipMapped::kNo;
203 }
204 
getRTOpList()205 GrRenderTargetOpList* GrRenderTargetContext::getRTOpList() {
206     ASSERT_SINGLE_OWNER
207     SkDEBUGCODE(this->validate();)
208 
209     if (!fOpList || fOpList->isClosed()) {
210         fOpList = this->drawingManager()->newRTOpList(fRenderTargetProxy, fManagedOpList);
211     }
212 
213     return fOpList.get();
214 }
215 
getOpList()216 GrOpList* GrRenderTargetContext::getOpList() {
217     return this->getRTOpList();
218 }
219 
drawGlyphRunList(const GrClip & clip,const SkMatrix & viewMatrix,const SkGlyphRunList & blob)220 void GrRenderTargetContext::drawGlyphRunList(
221         const GrClip& clip, const SkMatrix& viewMatrix,
222         const SkGlyphRunList& blob) {
223     ASSERT_SINGLE_OWNER
224     RETURN_IF_ABANDONED
225     SkDEBUGCODE(this->validate();)
226     GR_CREATE_TRACE_MARKER_CONTEXT("GrRenderTargetContext", "drawGlyphRunList", fContext);
227 
228     // Drawing text can cause us to do inline uploads. This is not supported for wrapped vulkan
229     // secondary command buffers because it would require stopping and starting a render pass which
230     // we don't have access to.
231     if (this->wrapsVkSecondaryCB()) {
232         return;
233     }
234 
235     GrTextContext* atlasTextContext = this->drawingManager()->getTextContext();
236     atlasTextContext->drawGlyphRunList(fContext, fTextTarget.get(), clip, viewMatrix,
237                                        fSurfaceProps, blob);
238 }
239 
discard()240 void GrRenderTargetContext::discard() {
241     ASSERT_SINGLE_OWNER
242     RETURN_IF_ABANDONED
243     SkDEBUGCODE(this->validate();)
244     GR_CREATE_TRACE_MARKER_CONTEXT("GrRenderTargetContext", "discard", fContext);
245 
246     AutoCheckFlush acf(this->drawingManager());
247 
248     this->getRTOpList()->discard();
249 }
250 
clear(const SkIRect * rect,const SkPMColor4f & color,CanClearFullscreen canClearFullscreen)251 void GrRenderTargetContext::clear(const SkIRect* rect,
252                                   const SkPMColor4f& color,
253                                   CanClearFullscreen canClearFullscreen) {
254     ASSERT_SINGLE_OWNER
255     RETURN_IF_ABANDONED
256     SkDEBUGCODE(this->validate();)
257     GR_CREATE_TRACE_MARKER_CONTEXT("GrRenderTargetContext", "clear", fContext);
258 
259     AutoCheckFlush acf(this->drawingManager());
260     this->internalClear(rect ? GrFixedClip(*rect) : GrFixedClip::Disabled(), color,
261                         canClearFullscreen);
262 }
263 
clear(const GrFixedClip & clip,const SkPMColor4f & color,CanClearFullscreen canClearFullscreen)264 void GrRenderTargetContextPriv::clear(const GrFixedClip& clip,
265                                       const SkPMColor4f& color,
266                                       CanClearFullscreen canClearFullscreen) {
267     ASSERT_SINGLE_OWNER_PRIV
268     RETURN_IF_ABANDONED_PRIV
269     SkDEBUGCODE(fRenderTargetContext->validate();)
270     GR_CREATE_TRACE_MARKER_CONTEXT("GrRenderTargetContextPriv", "clear",
271                                    fRenderTargetContext->fContext);
272 
273     AutoCheckFlush acf(fRenderTargetContext->drawingManager());
274     fRenderTargetContext->internalClear(clip, color, canClearFullscreen);
275 }
276 
clear_to_grpaint(const SkPMColor4f & color,GrPaint * paint)277 static void clear_to_grpaint(const SkPMColor4f& color, GrPaint* paint) {
278     paint->setColor4f(color);
279     if (color.isOpaque()) {
280         // Can just rely on the src-over blend mode to do the right thing
281         paint->setPorterDuffXPFactory(SkBlendMode::kSrcOver);
282     } else {
283         // A clear overwrites the prior color, so even if it's transparent, it behaves as if it
284         // were src blended
285         paint->setPorterDuffXPFactory(SkBlendMode::kSrc);
286     }
287 }
288 
internalClear(const GrFixedClip & clip,const SkPMColor4f & color,CanClearFullscreen canClearFullscreen)289 void GrRenderTargetContext::internalClear(const GrFixedClip& clip,
290                                           const SkPMColor4f& color,
291                                           CanClearFullscreen canClearFullscreen) {
292     bool isFull = false;
293     if (!clip.hasWindowRectangles()) {
294         // TODO: wrt the shouldInitializeTextures path, it would be more performant to
295         // only clear the entire target if we knew it had not been cleared before. As
296         // is this could end up doing a lot of redundant clears.
297         isFull = !clip.scissorEnabled() ||
298                  (CanClearFullscreen::kYes == canClearFullscreen &&
299                   (this->caps()->preferFullscreenClears() || this->caps()->shouldInitializeTextures())) ||
300                  clip.scissorRect().contains(SkIRect::MakeWH(this->width(), this->height()));
301     }
302 
303     if (isFull) {
304         GrRenderTargetOpList* opList = this->getRTOpList();
305         if (opList->resetForFullscreenClear(this->canDiscardPreviousOpsOnFullClear()) &&
306             !this->caps()->performColorClearsAsDraws()) {
307             // The op list was emptied and native clears are allowed, so just use the load op
308             opList->setColorLoadOp(GrLoadOp::kClear, color);
309             return;
310         } else {
311             // Will use an op for the clear, reset the load op to discard since the op will
312             // blow away the color buffer contents
313             opList->setColorLoadOp(GrLoadOp::kDiscard);
314         }
315 
316         // Must add an op to the list (either because we couldn't use a load op, or because the
317         // clear load op isn't supported)
318         if (this->caps()->performColorClearsAsDraws()) {
319             SkRect rtRect = SkRect::MakeWH(this->width(), this->height());
320             GrPaint paint;
321             clear_to_grpaint(color, &paint);
322             this->addDrawOp(GrFixedClip::Disabled(),
323                             GrFillRectOp::MakeNonAARect(fContext, std::move(paint), SkMatrix::I(),
324                                                         rtRect));
325         } else {
326             this->addOp(GrClearOp::Make(
327                     fContext, SkIRect::MakeEmpty(), color, /* fullscreen */ true));
328         }
329     } else {
330         if (this->caps()->performPartialClearsAsDraws()) {
331             // performPartialClearsAsDraws() also returns true if any clear has to be a draw.
332             GrPaint paint;
333             clear_to_grpaint(color, &paint);
334 
335             this->addDrawOp(clip,
336                             GrFillRectOp::MakeNonAARect(fContext, std::move(paint), SkMatrix::I(),
337                                                         SkRect::Make(clip.scissorRect())));
338         } else {
339             std::unique_ptr<GrOp> op(GrClearOp::Make(fContext, clip, color,
340                                                      this->asSurfaceProxy()));
341             // This version of the clear op factory can return null if the clip doesn't intersect
342             // with the surface proxy's boundary
343             if (!op) {
344                 return;
345             }
346             this->addOp(std::move(op));
347         }
348     }
349 }
350 
absClear(const SkIRect * clearRect,const SkPMColor4f & color)351 void GrRenderTargetContextPriv::absClear(const SkIRect* clearRect, const SkPMColor4f& color) {
352     ASSERT_SINGLE_OWNER_PRIV
353     RETURN_IF_ABANDONED_PRIV
354     SkDEBUGCODE(fRenderTargetContext->validate();)
355     GR_CREATE_TRACE_MARKER_CONTEXT("GrRenderTargetContextPriv", "absClear",
356                                    fRenderTargetContext->fContext);
357 
358     AutoCheckFlush acf(fRenderTargetContext->drawingManager());
359 
360     SkIRect rtRect = SkIRect::MakeWH(fRenderTargetContext->fRenderTargetProxy->worstCaseWidth(),
361                                      fRenderTargetContext->fRenderTargetProxy->worstCaseHeight());
362 
363     if (clearRect) {
364         if (clearRect->contains(rtRect)) {
365             clearRect = nullptr; // full screen
366         } else {
367             if (!rtRect.intersect(*clearRect)) {
368                 return;
369             }
370         }
371     }
372 
373     // TODO: in a post-MDB world this should be handled at the OpList level.
374     // This makes sure to always add an op to the list, instead of marking the clear as a load op.
375     // This code follows very similar logic to internalClear() below, but critical differences are
376     // highlighted in line related to absClear()'s unique behavior.
377     if (clearRect) {
378         if (fRenderTargetContext->caps()->performPartialClearsAsDraws()) {
379             GrPaint paint;
380             clear_to_grpaint(color, &paint);
381 
382             // Use the disabled clip; the rect geometry already matches the clear rectangle and
383             // if it were added to a scissor, that would be intersected with the logical surface
384             // bounds and not the worst case dimensions required here.
385             fRenderTargetContext->addDrawOp(
386                     GrFixedClip::Disabled(),
387                     GrFillRectOp::MakeNonAARect(fRenderTargetContext->fContext, std::move(paint),
388                                                 SkMatrix::I(), SkRect::Make(rtRect)));
389         } else {
390             // Must use the ClearOp factory that takes a boolean (false) instead of a surface
391             // proxy. The surface proxy variant would intersect the clip rect with its logical
392             // bounds, which is not desired in this special case.
393             fRenderTargetContext->addOp(GrClearOp::Make(
394                     fRenderTargetContext->fContext, rtRect, color, /* fullscreen */ false));
395         }
396     } else {
397         // Reset the oplist like in internalClear(), but do not rely on a load op for the clear
398         fRenderTargetContext->getRTOpList()->resetForFullscreenClear(
399                 fRenderTargetContext->canDiscardPreviousOpsOnFullClear());
400         fRenderTargetContext->getRTOpList()->setColorLoadOp(GrLoadOp::kDiscard);
401 
402         if (fRenderTargetContext->caps()->performColorClearsAsDraws()) {
403             // This draws a quad covering the worst case dimensions instead of just the logical
404             // width and height like in internalClear().
405             GrPaint paint;
406             clear_to_grpaint(color, &paint);
407             fRenderTargetContext->addDrawOp(
408                     GrFixedClip::Disabled(),
409                     GrFillRectOp::MakeNonAARect(fRenderTargetContext->fContext, std::move(paint),
410                                                 SkMatrix::I(), SkRect::Make(rtRect)));
411         } else {
412             // Nothing special about this path in absClear compared to internalClear()
413             fRenderTargetContext->addOp(GrClearOp::Make(
414                     fRenderTargetContext->fContext, SkIRect::MakeEmpty(), color,
415                     /* fullscreen */ true));
416         }
417     }
418 }
419 
drawPaint(const GrClip & clip,GrPaint && paint,const SkMatrix & viewMatrix)420 void GrRenderTargetContext::drawPaint(const GrClip& clip,
421                                       GrPaint&& paint,
422                                       const SkMatrix& viewMatrix) {
423     // Start with the render target, since that is the maximum content we could possibly fill.
424     // drawFilledQuad() will automatically restrict it to clip bounds for us if possible.
425     SkRect r = fRenderTargetProxy->getBoundsRect();
426     if (!paint.numTotalFragmentProcessors()) {
427         // The paint is trivial so we won't need to use local coordinates, so skip calculating the
428         // inverse view matrix.
429         this->fillRectToRect(clip, std::move(paint), GrAA::kNo, SkMatrix::I(), r, r);
430     } else {
431         // Use the inverse view matrix to arrive at appropriate local coordinates for the paint.
432         SkMatrix localMatrix;
433         if (!viewMatrix.invert(&localMatrix)) {
434             return;
435         }
436         this->fillRectWithLocalMatrix(clip, std::move(paint), GrAA::kNo, SkMatrix::I(), r,
437                                       localMatrix);
438     }
439 }
440 
441 enum class GrRenderTargetContext::QuadOptimization {
442     // The rect to draw doesn't intersect clip or render target, so no draw op should be added
443     kDiscarded,
444     // The rect to draw was converted to some other op and appended to the oplist, so no additional
445     // op is necessary. Currently this can convert it to a clear op or a rrect op. Only valid if
446     // a constColor is provided.
447     kSubmitted,
448     // The clip was folded into the device quad, with updated edge flags and local coords, and
449     // caller is responsible for adding an appropriate op.
450     kClipApplied,
451     // No change to clip, but quad updated to better fit clip/render target, and caller is
452     // responsible for adding an appropriate op.
453     kCropped
454 };
455 
make_vertex_finite(float * value)456 static bool make_vertex_finite(float* value) {
457     if (SkScalarIsNaN(*value)) {
458         return false;
459     }
460 
461     if (!SkScalarIsFinite(*value)) {
462         // +/- infinity at this point. Don't use exactly SK_ScalarMax so that we have some precision
463         // left when calculating crops.
464         static constexpr float kNearInfinity = SK_ScalarMax / 4.f;
465         *value = *value < 0.f ? -kNearInfinity : kNearInfinity;
466     }
467 
468     return true;
469 }
470 
attemptQuadOptimization(const GrClip & clip,const SkPMColor4f * constColor,const GrUserStencilSettings * stencilSettings,GrAA * aa,GrQuadAAFlags * edgeFlags,GrQuad * deviceQuad,GrQuad * localQuad)471 GrRenderTargetContext::QuadOptimization GrRenderTargetContext::attemptQuadOptimization(
472         const GrClip& clip, const SkPMColor4f* constColor,
473         const GrUserStencilSettings* stencilSettings, GrAA* aa, GrQuadAAFlags* edgeFlags,
474         GrQuad* deviceQuad, GrQuad* localQuad) {
475     // Optimization requirements:
476     // 1. kDiscard applies when clip bounds and quad bounds do not intersect
477     // 2. kClear applies when constColor and final geom is pixel aligned rect;
478     //       pixel aligned rect requires rect clip and (rect quad or quad covers clip)
479     // 3. kRRect applies when constColor and rrect clip and quad covers clip
480     // 4. kExplicitClip applies when rect clip and (rect quad or quad covers clip)
481     // 5. kCropped applies when rect quad (currently)
482     // 6. kNone always applies
483     GrQuadAAFlags newFlags = *edgeFlags;
484 
485     SkRect rtRect;
486     if (stencilSettings) {
487         // Must use worst case bounds so that stencil buffer updates on approximately sized render
488         // targets don't get corrupted.
489         rtRect = SkRect::MakeWH(fRenderTargetProxy->worstCaseWidth(),
490                                 fRenderTargetProxy->worstCaseHeight());
491     } else {
492         // Use the logical size of the render target, which allows for "fullscreen" clears even if
493         // the render target has an approximate backing fit
494         rtRect = SkRect::MakeWH(this->width(), this->height());
495     }
496 
497     SkRect drawBounds = deviceQuad->bounds();
498     if (constColor) {
499         // Don't bother updating local coordinates when the paint will ignore them anyways
500         localQuad = nullptr;
501         // If the device quad is not finite, coerce into a finite quad. This is acceptable since it
502         // will be cropped to the finite 'clip' or render target and there is no local space mapping
503         if (!deviceQuad->isFinite()) {
504             for (int i = 0; i < 4; ++i) {
505                 if (!make_vertex_finite(deviceQuad->xs() + i) ||
506                     !make_vertex_finite(deviceQuad->ys() + i) ||
507                     !make_vertex_finite(deviceQuad->ws() + i)) {
508                     // Discard if we see a nan
509                     return QuadOptimization::kDiscarded;
510                 }
511             }
512             SkASSERT(deviceQuad->isFinite());
513         }
514     } else {
515         // CropToRect requires the quads to be finite. If they are not finite and we have local
516         // coordinates, the mapping from local space to device space is poorly defined so drop it
517         if (!deviceQuad->isFinite()) {
518             return QuadOptimization::kDiscarded;
519         }
520     }
521 
522     // If the quad is entirely off screen, it doesn't matter what the clip does
523     if (!rtRect.intersects(drawBounds)) {
524         return QuadOptimization::kDiscarded;
525     }
526 
527     // Check if clip can be represented as a rounded rect (initialize as if clip fully contained
528     // the render target).
529     SkRRect clipRRect = SkRRect::MakeRect(rtRect);
530     // We initialize clipAA to *aa when there are stencil settings so that we don't artificially
531     // encounter mixed-aa edges (not allowed for stencil), but we want to start as non-AA for
532     // regular draws so that if we fully cover the render target, that can stop being anti-aliased.
533     GrAA clipAA = stencilSettings ? *aa : GrAA::kNo;
534     bool axisAlignedClip = true;
535     if (!clip.quickContains(rtRect)) {
536         if (!clip.isRRect(rtRect, &clipRRect, &clipAA)) {
537             axisAlignedClip = false;
538         }
539     }
540 
541     // If the clip rrect is valid (i.e. axis-aligned), we can potentially combine it with the
542     // draw geometry so that no clip is needed when drawing.
543     if (axisAlignedClip && (!stencilSettings || clipAA == *aa)) {
544         // Tighten clip bounds (if clipRRect.isRect() is true, clipBounds now holds the intersection
545         // of the render target and the clip rect)
546         SkRect clipBounds = rtRect;
547         if (!clipBounds.intersect(clipRRect.rect()) || !clipBounds.intersects(drawBounds)) {
548             return QuadOptimization::kDiscarded;
549         }
550 
551         if (clipRRect.isRect()) {
552             // No rounded corners, so the kClear and kExplicitClip optimizations are possible
553             if (GrQuadUtils::CropToRect(clipBounds, clipAA, &newFlags, deviceQuad, localQuad)) {
554                 if (constColor && deviceQuad->quadType() == GrQuad::Type::kAxisAligned) {
555                     // Clear optimization is possible
556                     drawBounds = deviceQuad->bounds();
557                     if (drawBounds.contains(rtRect)) {
558                         // Fullscreen clear
559                         this->clear(nullptr, *constColor, CanClearFullscreen::kYes);
560                         return QuadOptimization::kSubmitted;
561                     } else if (GrClip::IsPixelAligned(drawBounds) &&
562                                drawBounds.width() > 256 && drawBounds.height() > 256) {
563                         // Scissor + clear (round shouldn't do anything since we are pixel aligned)
564                         SkIRect scissorRect;
565                         drawBounds.round(&scissorRect);
566                         this->clear(&scissorRect, *constColor, CanClearFullscreen::kNo);
567                         return QuadOptimization::kSubmitted;
568                     }
569                 }
570 
571                 // Update overall AA setting.
572                 *edgeFlags = newFlags;
573                 if (*aa == GrAA::kNo && clipAA == GrAA::kYes &&
574                     newFlags != GrQuadAAFlags::kNone) {
575                     // The clip was anti-aliased and now the draw needs to be upgraded to AA to
576                     // properly reflect the smooth edge of the clip.
577                     *aa = GrAA::kYes;
578                 }
579                 // We intentionally do not downgrade AA here because we don't know if we need to
580                 // preserve MSAA (see GrQuadAAFlags docs). But later in the pipeline, the ops can
581                 // use GrResolveAATypeForQuad() to turn off coverage AA when all flags are off.
582 
583                 // deviceQuad is exactly the intersection of original quad and clip, so it can be
584                 // drawn with no clip (submitted by caller)
585                 return QuadOptimization::kClipApplied;
586             } else {
587                 // The quads have been updated to better fit the clip bounds, but can't get rid of
588                 // the clip entirely
589                 return QuadOptimization::kCropped;
590             }
591         } else if (constColor) {
592             // Rounded corners and constant filled color (limit ourselves to solid colors because
593             // there is no way to use custom local coordinates with drawRRect).
594             if (GrQuadUtils::CropToRect(clipBounds, clipAA, &newFlags, deviceQuad, localQuad) &&
595                 deviceQuad->quadType() == GrQuad::Type::kAxisAligned &&
596                 deviceQuad->bounds().contains(clipBounds)) {
597                 // Since the cropped quad became a rectangle which covered the bounds of the rrect,
598                 // we can draw the rrect directly and ignore the edge flags
599                 GrPaint paint;
600                 clear_to_grpaint(*constColor, &paint);
601                 this->drawRRect(GrFixedClip::Disabled(), std::move(paint), clipAA, SkMatrix::I(),
602                                 clipRRect, GrStyle::SimpleFill());
603                 return QuadOptimization::kSubmitted;
604             } else {
605                 // The quad has been updated to better fit clip bounds, but can't remove the clip
606                 return QuadOptimization::kCropped;
607             }
608         }
609     }
610 
611     // Crop the quad to the conservative bounds of the clip.
612     SkIRect clipDevBounds;
613     clip.getConservativeBounds(rtRect.width(), rtRect.height(), &clipDevBounds);
614     SkRect clipBounds = SkRect::Make(clipDevBounds);
615 
616     // One final check for discarding, since we may have gone here directly due to a complex clip
617     if (!clipBounds.intersects(drawBounds)) {
618         return QuadOptimization::kDiscarded;
619     }
620 
621     // Even if this were to return true, the crop rect does not exactly match the clip, so can not
622     // report explicit-clip. Since these edges aren't visible, don't update the final edge flags.
623     GrQuadUtils::CropToRect(clipBounds, clipAA, &newFlags, deviceQuad, localQuad);
624 
625     return QuadOptimization::kCropped;
626 }
627 
drawFilledQuad(const GrClip & clip,GrPaint && paint,GrAA aa,GrQuadAAFlags edgeFlags,const GrQuad & deviceQuad,const GrQuad & localQuad,const GrUserStencilSettings * ss)628 void GrRenderTargetContext::drawFilledQuad(const GrClip& clip,
629                                            GrPaint&& paint,
630                                            GrAA aa,
631                                            GrQuadAAFlags edgeFlags,
632                                            const GrQuad& deviceQuad,
633                                            const GrQuad& localQuad,
634                                            const GrUserStencilSettings* ss) {
635     ASSERT_SINGLE_OWNER
636     RETURN_IF_ABANDONED
637     SkDEBUGCODE(this->validate();)
638     GR_CREATE_TRACE_MARKER_CONTEXT("GrRenderTargetContext", "drawFilledQuad", fContext);
639 
640     AutoCheckFlush acf(this->drawingManager());
641 
642     SkPMColor4f* constColor = nullptr;
643     SkPMColor4f paintColor;
644     if (!ss && !paint.numCoverageFragmentProcessors() &&
645         paint.isConstantBlendedColor(&paintColor)) {
646         // Only consider clears/rrects when it's easy to guarantee 100% fill with single color
647         constColor = &paintColor;
648     }
649 
650     GrQuad croppedDeviceQuad = deviceQuad;
651     GrQuad croppedLocalQuad = localQuad;
652     QuadOptimization opt = this->attemptQuadOptimization(clip, constColor, ss, &aa, &edgeFlags,
653                                                          &croppedDeviceQuad, &croppedLocalQuad);
654     if (opt >= QuadOptimization::kClipApplied) {
655         // These optimizations require caller to add an op themselves
656         const GrClip& finalClip = opt == QuadOptimization::kClipApplied ? GrFixedClip::Disabled()
657                                                                         : clip;
658         GrAAType aaType = ss ? (aa == GrAA::kYes ? GrAAType::kMSAA : GrAAType::kNone)
659                              : this->chooseAAType(aa);
660         this->addDrawOp(finalClip, GrFillRectOp::Make(fContext, std::move(paint), aaType, edgeFlags,
661                                                       croppedDeviceQuad, croppedLocalQuad, ss));
662     }
663     // All other optimization levels were completely handled inside attempt(), so no extra op needed
664 }
665 
drawTexturedQuad(const GrClip & clip,sk_sp<GrTextureProxy> proxy,sk_sp<GrColorSpaceXform> textureXform,GrSamplerState::Filter filter,const SkPMColor4f & color,SkBlendMode blendMode,GrAA aa,GrQuadAAFlags edgeFlags,const GrQuad & deviceQuad,const GrQuad & localQuad,const SkRect * domain)666 void GrRenderTargetContext::drawTexturedQuad(const GrClip& clip,
667                                              sk_sp<GrTextureProxy> proxy,
668                                              sk_sp<GrColorSpaceXform> textureXform,
669                                              GrSamplerState::Filter filter,
670                                              const SkPMColor4f& color,
671                                              SkBlendMode blendMode,
672                                              GrAA aa,
673                                              GrQuadAAFlags edgeFlags,
674                                              const GrQuad& deviceQuad,
675                                              const GrQuad& localQuad,
676                                              const SkRect* domain) {
677     ASSERT_SINGLE_OWNER
678     RETURN_IF_ABANDONED
679     SkDEBUGCODE(this->validate();)
680     GR_CREATE_TRACE_MARKER_CONTEXT("GrRenderTargetContext", "drawTexturedQuad", fContext);
681 
682     AutoCheckFlush acf(this->drawingManager());
683 
684     // Functionally this is very similar to drawFilledQuad except that there's no constColor to
685     // enable the kSubmitted optimizations, no stencil settings support, and its a GrTextureOp.
686     GrQuad croppedDeviceQuad = deviceQuad;
687     GrQuad croppedLocalQuad = localQuad;
688     QuadOptimization opt = this->attemptQuadOptimization(clip, nullptr, nullptr, &aa, &edgeFlags,
689                                                          &croppedDeviceQuad, &croppedLocalQuad);
690 
691     SkASSERT(opt != QuadOptimization::kSubmitted);
692     if (opt != QuadOptimization::kDiscarded) {
693         // And the texture op if not discarded
694         const GrClip& finalClip = opt == QuadOptimization::kClipApplied ? GrFixedClip::Disabled()
695                                                                         : clip;
696         GrAAType aaType = this->chooseAAType(aa);
697         // Use the provided domain, although hypothetically we could detect that the cropped local
698         // quad is sufficiently inside the domain and the constraint could be dropped.
699         this->addDrawOp(finalClip, GrTextureOp::Make(fContext, std::move(proxy),
700                                                      std::move(textureXform), filter, color,
701                                                      blendMode, aaType, edgeFlags,
702                                                      croppedDeviceQuad, croppedLocalQuad, domain));
703     }
704 }
705 
drawRect(const GrClip & clip,GrPaint && paint,GrAA aa,const SkMatrix & viewMatrix,const SkRect & rect,const GrStyle * style)706 void GrRenderTargetContext::drawRect(const GrClip& clip,
707                                      GrPaint&& paint,
708                                      GrAA aa,
709                                      const SkMatrix& viewMatrix,
710                                      const SkRect& rect,
711                                      const GrStyle* style) {
712     if (!style) {
713         style = &GrStyle::SimpleFill();
714     }
715     ASSERT_SINGLE_OWNER
716     RETURN_IF_ABANDONED
717     SkDEBUGCODE(this->validate();)
718     GR_CREATE_TRACE_MARKER_CONTEXT("GrRenderTargetContext", "drawRect", fContext);
719 
720     // Path effects should've been devolved to a path in SkGpuDevice
721     SkASSERT(!style->pathEffect());
722 
723     AutoCheckFlush acf(this->drawingManager());
724 
725     const SkStrokeRec& stroke = style->strokeRec();
726     if (stroke.getStyle() == SkStrokeRec::kFill_Style) {
727         // Fills the rect, using rect as its own local coordinates
728         this->fillRectToRect(clip, std::move(paint), aa, viewMatrix, rect, rect);
729         return;
730     } else if (stroke.getStyle() == SkStrokeRec::kStroke_Style ||
731                stroke.getStyle() == SkStrokeRec::kHairline_Style) {
732         if ((!rect.width() || !rect.height()) &&
733             SkStrokeRec::kHairline_Style != stroke.getStyle()) {
734             SkScalar r = stroke.getWidth() / 2;
735             // TODO: Move these stroke->fill fallbacks to GrShape?
736             switch (stroke.getJoin()) {
737                 case SkPaint::kMiter_Join:
738                     this->drawRect(
739                             clip, std::move(paint), aa, viewMatrix,
740                             {rect.fLeft - r, rect.fTop - r, rect.fRight + r, rect.fBottom + r},
741                             &GrStyle::SimpleFill());
742                     return;
743                 case SkPaint::kRound_Join:
744                     // Raster draws nothing when both dimensions are empty.
745                     if (rect.width() || rect.height()){
746                         SkRRect rrect = SkRRect::MakeRectXY(rect.makeOutset(r, r), r, r);
747                         this->drawRRect(clip, std::move(paint), aa, viewMatrix, rrect,
748                                         GrStyle::SimpleFill());
749                         return;
750                     }
751                 case SkPaint::kBevel_Join:
752                     if (!rect.width()) {
753                         this->drawRect(clip, std::move(paint), aa, viewMatrix,
754                                        {rect.fLeft - r, rect.fTop, rect.fRight + r, rect.fBottom},
755                                        &GrStyle::SimpleFill());
756                     } else {
757                         this->drawRect(clip, std::move(paint), aa, viewMatrix,
758                                        {rect.fLeft, rect.fTop - r, rect.fRight, rect.fBottom + r},
759                                        &GrStyle::SimpleFill());
760                     }
761                     return;
762                 }
763         }
764 
765         std::unique_ptr<GrDrawOp> op;
766 
767         GrAAType aaType = this->chooseAAType(aa);
768         op = GrStrokeRectOp::Make(fContext, std::move(paint), aaType, viewMatrix, rect, stroke);
769         // op may be null if the stroke is not supported or if using coverage aa and the view matrix
770         // does not preserve rectangles.
771         if (op) {
772             this->addDrawOp(clip, std::move(op));
773             return;
774         }
775     }
776     assert_alive(paint);
777     this->drawShapeUsingPathRenderer(clip, std::move(paint), aa, viewMatrix, GrShape(rect, *style));
778 }
779 
drawQuadSet(const GrClip & clip,GrPaint && paint,GrAA aa,const SkMatrix & viewMatrix,const QuadSetEntry quads[],int cnt)780 void GrRenderTargetContext::drawQuadSet(const GrClip& clip, GrPaint&& paint, GrAA aa,
781                                         const SkMatrix& viewMatrix, const QuadSetEntry quads[],
782                                         int cnt) {
783     GrAAType aaType = this->chooseAAType(aa);
784     this->addDrawOp(clip, GrFillRectOp::MakeSet(fContext, std::move(paint), aaType, viewMatrix,
785                                                 quads, cnt));
786 }
787 
maxWindowRectangles() const788 int GrRenderTargetContextPriv::maxWindowRectangles() const {
789     return fRenderTargetContext->fRenderTargetProxy->maxWindowRectangles(
790             *fRenderTargetContext->caps());
791 }
792 
canDiscardPreviousOpsOnFullClear() const793 GrRenderTargetOpList::CanDiscardPreviousOps GrRenderTargetContext::canDiscardPreviousOpsOnFullClear(
794         ) const {
795 #if GR_TEST_UTILS
796     if (fPreserveOpsOnFullClear_TestingOnly) {
797         return GrRenderTargetOpList::CanDiscardPreviousOps::kNo;
798     }
799 #endif
800     // Regardless of how the clear is implemented (native clear or a fullscreen quad), all prior ops
801     // would normally be overwritten. The one exception is if the render target context is marked as
802     // needing a stencil buffer then there may be a prior op that writes to the stencil buffer.
803     // Although the clear will ignore the stencil buffer, following draw ops may not so we can't get
804     // rid of all the preceding ops. Beware! If we ever add any ops that have a side effect beyond
805     // modifying the stencil buffer we will need a more elaborate tracking system (skbug.com/7002).
806     return GrRenderTargetOpList::CanDiscardPreviousOps(!fNumStencilSamples);
807 }
808 
setNeedsStencil(bool multisampled)809 void GrRenderTargetContext::setNeedsStencil(bool multisampled) {
810     // Don't clear stencil until after we've changed fNumStencilSamples. This ensures we don't loop
811     // forever in the event that there are driver bugs and we need to clear as a draw.
812     bool needsStencilClear = !fNumStencilSamples;
813 
814     int numRequiredSamples = this->numSamples();
815     if (multisampled && 1 == numRequiredSamples) {
816         // The caller has requested a multisampled stencil buffer on a non-MSAA render target. Use
817         // mixed samples.
818         SkASSERT(fRenderTargetProxy->canUseMixedSamples(*this->caps()));
819         numRequiredSamples = this->caps()->internalMultisampleCount(
820                 this->asSurfaceProxy()->backendFormat());
821     }
822     SkASSERT(numRequiredSamples > 0);
823 
824     if (numRequiredSamples > fNumStencilSamples) {
825         fNumStencilSamples = numRequiredSamples;
826         fRenderTargetProxy->setNeedsStencil(fNumStencilSamples);
827     }
828 
829     if (needsStencilClear) {
830         if (this->caps()->performStencilClearsAsDraws()) {
831             // There is a driver bug with clearing stencil. We must use an op to manually clear the
832             // stencil buffer before the op that required 'setNeedsStencil'.
833             this->internalStencilClear(GrFixedClip::Disabled(), /* inside mask */ false);
834         } else {
835             // Setting the clear stencil load op is preferable. On non-tilers, this lets the flush
836             // code note when the instantiated stencil buffer is already clear and skip the clear
837             // altogether. And on tilers, loading the stencil buffer cleared is even faster than
838             // preserving the previous contents.
839             this->getRTOpList()->setStencilLoadOp(GrLoadOp::kClear);
840         }
841     }
842 }
843 
clearStencilClip(const GrFixedClip & clip,bool insideStencilMask)844 void GrRenderTargetContextPriv::clearStencilClip(const GrFixedClip& clip, bool insideStencilMask) {
845     ASSERT_SINGLE_OWNER_PRIV
846     RETURN_IF_ABANDONED_PRIV
847     SkDEBUGCODE(fRenderTargetContext->validate();)
848     GR_CREATE_TRACE_MARKER_CONTEXT("GrRenderTargetContextPriv", "clearStencilClip",
849                                    fRenderTargetContext->fContext);
850 
851     AutoCheckFlush acf(fRenderTargetContext->drawingManager());
852 
853     fRenderTargetContext->internalStencilClear(clip, insideStencilMask);
854 }
855 
internalStencilClear(const GrFixedClip & clip,bool insideStencilMask)856 void GrRenderTargetContext::internalStencilClear(const GrFixedClip& clip, bool insideStencilMask) {
857     if (this->caps()->performStencilClearsAsDraws()) {
858         const GrUserStencilSettings* ss = GrStencilSettings::SetClipBitSettings(insideStencilMask);
859         SkRect rtRect = SkRect::MakeWH(this->width(), this->height());
860 
861         // Configure the paint to have no impact on the color buffer
862         GrPaint paint;
863         paint.setXPFactory(GrDisableColorXPFactory::Get());
864         this->addDrawOp(clip, GrFillRectOp::MakeNonAARect(fContext, std::move(paint), SkMatrix::I(),
865                                                           rtRect, ss));
866     } else {
867         std::unique_ptr<GrOp> op(GrClearStencilClipOp::Make(fContext, clip, insideStencilMask,
868                                                             fRenderTargetProxy.get()));
869         if (!op) {
870             return;
871         }
872         this->addOp(std::move(op));
873     }
874 }
875 
stencilPath(const GrHardClip & clip,GrAA doStencilMSAA,const SkMatrix & viewMatrix,const GrPath * path)876 void GrRenderTargetContextPriv::stencilPath(const GrHardClip& clip,
877                                             GrAA doStencilMSAA,
878                                             const SkMatrix& viewMatrix,
879                                             const GrPath* path) {
880     ASSERT_SINGLE_OWNER_PRIV
881     RETURN_IF_ABANDONED_PRIV
882     SkDEBUGCODE(fRenderTargetContext->validate();)
883     GR_CREATE_TRACE_MARKER_CONTEXT("GrRenderTargetContextPriv", "stencilPath",
884                                    fRenderTargetContext->fContext);
885 
886     // TODO: extract portions of checkDraw that are relevant to path stenciling.
887     SkASSERT(path);
888     SkASSERT(fRenderTargetContext->caps()->shaderCaps()->pathRenderingSupport());
889 
890     // FIXME: Use path bounds instead of this WAR once
891     // https://bugs.chromium.org/p/skia/issues/detail?id=5640 is resolved.
892     SkRect bounds = SkRect::MakeIWH(fRenderTargetContext->width(), fRenderTargetContext->height());
893 
894     // Setup clip
895     GrAppliedHardClip appliedClip;
896     if (!clip.apply(fRenderTargetContext->width(), fRenderTargetContext->height(), &appliedClip,
897                     &bounds)) {
898         return;
899     }
900 
901     std::unique_ptr<GrOp> op = GrStencilPathOp::Make(fRenderTargetContext->fContext,
902                                                      viewMatrix,
903                                                      GrAA::kYes == doStencilMSAA,
904                                                      path->getFillType(),
905                                                      appliedClip.hasStencilClip(),
906                                                      appliedClip.scissorState(),
907                                                      path);
908     if (!op) {
909         return;
910     }
911     op->setClippedBounds(bounds);
912 
913     fRenderTargetContext->setNeedsStencil(GrAA::kYes == doStencilMSAA);
914     fRenderTargetContext->addOp(std::move(op));
915 }
916 
drawTextureSet(const GrClip & clip,const TextureSetEntry set[],int cnt,GrSamplerState::Filter filter,SkBlendMode mode,GrAA aa,SkCanvas::SrcRectConstraint constraint,const SkMatrix & viewMatrix,sk_sp<GrColorSpaceXform> texXform)917 void GrRenderTargetContext::drawTextureSet(const GrClip& clip, const TextureSetEntry set[], int cnt,
918                                            GrSamplerState::Filter filter, SkBlendMode mode,
919                                            GrAA aa, SkCanvas::SrcRectConstraint constraint,
920                                            const SkMatrix& viewMatrix,
921                                            sk_sp<GrColorSpaceXform> texXform) {
922     ASSERT_SINGLE_OWNER
923     RETURN_IF_ABANDONED
924     SkDEBUGCODE(this->validate();)
925     GR_CREATE_TRACE_MARKER_CONTEXT("GrRenderTargetContext", "drawTextureSet", fContext);
926 
927     if (mode != SkBlendMode::kSrcOver ||
928         !fContext->priv().caps()->dynamicStateArrayGeometryProcessorTextureSupport()) {
929         // Draw one at a time since the bulk API doesn't support non src-over blending, or the
930         // backend can't support the bulk geometry processor yet.
931         SkMatrix ctm;
932         for (int i = 0; i < cnt; ++i) {
933             float alpha = set[i].fAlpha;
934             ctm = viewMatrix;
935             if (set[i].fPreViewMatrix) {
936                 ctm.preConcat(*set[i].fPreViewMatrix);
937             }
938 
939             GrQuad quad, srcQuad;
940             if (set[i].fDstClipQuad) {
941                 quad = GrQuad::MakeFromSkQuad(set[i].fDstClipQuad, ctm);
942 
943                 SkPoint srcPts[4];
944                 GrMapRectPoints(set[i].fDstRect, set[i].fSrcRect, set[i].fDstClipQuad, srcPts, 4);
945                 srcQuad = GrQuad::MakeFromSkQuad(srcPts, SkMatrix::I());
946             } else {
947                 quad = GrQuad::MakeFromRect(set[i].fDstRect, ctm);
948                 srcQuad = GrQuad(set[i].fSrcRect);
949             }
950 
951             const SkRect* domain = constraint == SkCanvas::kStrict_SrcRectConstraint
952                     ? &set[i].fSrcRect : nullptr;
953             this->drawTexturedQuad(clip, set[i].fProxy, texXform, filter,
954                                    {alpha, alpha, alpha, alpha}, mode, aa, set[i].fAAFlags,
955                                    quad, srcQuad, domain);
956         }
957     } else {
958         // Can use a single op, avoiding GrPaint creation, and can batch across proxies
959         AutoCheckFlush acf(this->drawingManager());
960         GrAAType aaType = this->chooseAAType(aa);
961         auto op = GrTextureOp::MakeSet(fContext, set, cnt, filter, aaType, constraint, viewMatrix,
962                                        std::move(texXform));
963         this->addDrawOp(clip, std::move(op));
964     }
965 }
966 
drawVertices(const GrClip & clip,GrPaint && paint,const SkMatrix & viewMatrix,sk_sp<SkVertices> vertices,const SkVertices::Bone bones[],int boneCount,GrPrimitiveType * overridePrimType)967 void GrRenderTargetContext::drawVertices(const GrClip& clip,
968                                          GrPaint&& paint,
969                                          const SkMatrix& viewMatrix,
970                                          sk_sp<SkVertices> vertices,
971                                          const SkVertices::Bone bones[],
972                                          int boneCount,
973                                          GrPrimitiveType* overridePrimType) {
974     ASSERT_SINGLE_OWNER
975     RETURN_IF_ABANDONED
976     SkDEBUGCODE(this->validate();)
977     GR_CREATE_TRACE_MARKER_CONTEXT("GrRenderTargetContext", "drawVertices", fContext);
978 
979     AutoCheckFlush acf(this->drawingManager());
980 
981     SkASSERT(vertices);
982     GrAAType aaType = this->chooseAAType(GrAA::kNo);
983     std::unique_ptr<GrDrawOp> op = GrDrawVerticesOp::Make(
984             fContext, std::move(paint), std::move(vertices), bones, boneCount, viewMatrix, aaType,
985             this->colorSpaceInfo().refColorSpaceXformFromSRGB(), overridePrimType);
986     this->addDrawOp(clip, std::move(op));
987 }
988 
989 ///////////////////////////////////////////////////////////////////////////////
990 
drawAtlas(const GrClip & clip,GrPaint && paint,const SkMatrix & viewMatrix,int spriteCount,const SkRSXform xform[],const SkRect texRect[],const SkColor colors[])991 void GrRenderTargetContext::drawAtlas(const GrClip& clip,
992                                       GrPaint&& paint,
993                                       const SkMatrix& viewMatrix,
994                                       int spriteCount,
995                                       const SkRSXform xform[],
996                                       const SkRect texRect[],
997                                       const SkColor colors[]) {
998     ASSERT_SINGLE_OWNER
999     RETURN_IF_ABANDONED
1000     SkDEBUGCODE(this->validate();)
1001     GR_CREATE_TRACE_MARKER_CONTEXT("GrRenderTargetContext", "drawAtlas", fContext);
1002 
1003     AutoCheckFlush acf(this->drawingManager());
1004 
1005     GrAAType aaType = this->chooseAAType(GrAA::kNo);
1006     std::unique_ptr<GrDrawOp> op = GrDrawAtlasOp::Make(fContext, std::move(paint), viewMatrix,
1007                                                        aaType, spriteCount, xform, texRect, colors);
1008     this->addDrawOp(clip, std::move(op));
1009 }
1010 
1011 ///////////////////////////////////////////////////////////////////////////////
1012 
drawRRect(const GrClip & origClip,GrPaint && paint,GrAA aa,const SkMatrix & viewMatrix,const SkRRect & rrect,const GrStyle & style)1013 void GrRenderTargetContext::drawRRect(const GrClip& origClip,
1014                                       GrPaint&& paint,
1015                                       GrAA aa,
1016                                       const SkMatrix& viewMatrix,
1017                                       const SkRRect& rrect,
1018                                       const GrStyle& style) {
1019     ASSERT_SINGLE_OWNER
1020     RETURN_IF_ABANDONED
1021     SkDEBUGCODE(this->validate();)
1022     GR_CREATE_TRACE_MARKER_CONTEXT("GrRenderTargetContext", "drawRRect", fContext);
1023 
1024     const SkStrokeRec& stroke = style.strokeRec();
1025     if (stroke.getStyle() == SkStrokeRec::kFill_Style && rrect.isEmpty()) {
1026        return;
1027     }
1028 
1029     GrNoClip noclip;
1030     const GrClip* clip = &origClip;
1031 #ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
1032     // The Android framework frequently clips rrects to themselves where the clip is non-aa and the
1033     // draw is aa. Since our lower level clip code works from op bounds, which are SkRects, it
1034     // doesn't detect that the clip can be ignored (modulo antialiasing). The following test
1035     // attempts to mitigate the stencil clip cost but will only help when the entire clip stack
1036     // can be ignored. We'd prefer to fix this in the framework by removing the clips calls. This
1037     // only works for filled rrects since the stroke width outsets beyond the rrect itself.
1038     SkRRect devRRect;
1039     if (stroke.getStyle() == SkStrokeRec::kFill_Style && rrect.transform(viewMatrix, &devRRect) &&
1040         clip->quickContains(devRRect)) {
1041         clip = &noclip;
1042     }
1043 #endif
1044     SkASSERT(!style.pathEffect()); // this should've been devolved to a path in SkGpuDevice
1045 
1046     AutoCheckFlush acf(this->drawingManager());
1047 
1048     GrAAType aaType = this->chooseAAType(aa);
1049 
1050     std::unique_ptr<GrDrawOp> op;
1051     if (GrAAType::kCoverage == aaType && rrect.isSimple() &&
1052         rrect.getSimpleRadii().fX == rrect.getSimpleRadii().fY &&
1053         viewMatrix.rectStaysRect() && viewMatrix.isSimilarity()) {
1054         // In coverage mode, we draw axis-aligned circular roundrects with the GrOvalOpFactory
1055         // to avoid perf regressions on some platforms.
1056         assert_alive(paint);
1057         op = GrOvalOpFactory::MakeCircularRRectOp(
1058                 fContext, std::move(paint), viewMatrix, rrect, stroke, this->caps()->shaderCaps());
1059     }
1060     if (!op && style.isSimpleFill()) {
1061         assert_alive(paint);
1062         op = GrFillRRectOp::Make(
1063                 fContext, aaType, viewMatrix, rrect, *this->caps(), std::move(paint));
1064     }
1065     if (!op && GrAAType::kCoverage == aaType) {
1066         assert_alive(paint);
1067         op = GrOvalOpFactory::MakeRRectOp(
1068                 fContext, std::move(paint), viewMatrix, rrect, stroke, this->caps()->shaderCaps());
1069     }
1070     if (op) {
1071         this->addDrawOp(*clip, std::move(op));
1072         return;
1073     }
1074 
1075     assert_alive(paint);
1076     this->drawShapeUsingPathRenderer(*clip, std::move(paint), aa, viewMatrix,
1077                                      GrShape(rrect, style));
1078 }
1079 
1080 ///////////////////////////////////////////////////////////////////////////////
1081 
map(const SkMatrix & m,const SkPoint3 & pt)1082 static SkPoint3 map(const SkMatrix& m, const SkPoint3& pt) {
1083     SkPoint3 result;
1084     m.mapXY(pt.fX, pt.fY, (SkPoint*)&result.fX);
1085     result.fZ = pt.fZ;
1086     return result;
1087 }
1088 
drawFastShadow(const GrClip & clip,const SkMatrix & viewMatrix,const SkPath & path,const SkDrawShadowRec & rec)1089 bool GrRenderTargetContext::drawFastShadow(const GrClip& clip,
1090                                            const SkMatrix& viewMatrix,
1091                                            const SkPath& path,
1092                                            const SkDrawShadowRec& rec) {
1093     ASSERT_SINGLE_OWNER
1094     if (fContext->priv().abandoned()) {
1095         return true;
1096     }
1097     SkDEBUGCODE(this->validate();)
1098     GR_CREATE_TRACE_MARKER_CONTEXT("GrRenderTargetContext", "drawFastShadow", fContext);
1099 
1100     // check z plane
1101     bool tiltZPlane = SkToBool(!SkScalarNearlyZero(rec.fZPlaneParams.fX) ||
1102                                !SkScalarNearlyZero(rec.fZPlaneParams.fY));
1103     bool skipAnalytic = SkToBool(rec.fFlags & SkShadowFlags::kGeometricOnly_ShadowFlag);
1104     if (tiltZPlane || skipAnalytic || !viewMatrix.rectStaysRect() || !viewMatrix.isSimilarity()) {
1105         return false;
1106     }
1107 
1108     SkRRect rrect;
1109     SkRect rect;
1110     // we can only handle rects, circles, and rrects with circular corners
1111     bool isRRect = path.isRRect(&rrect) && SkRRectPriv::IsSimpleCircular(rrect) &&
1112         rrect.radii(SkRRect::kUpperLeft_Corner).fX > SK_ScalarNearlyZero;
1113     if (!isRRect &&
1114         path.isOval(&rect) && SkScalarNearlyEqual(rect.width(), rect.height()) &&
1115         rect.width() > SK_ScalarNearlyZero) {
1116         rrect.setOval(rect);
1117         isRRect = true;
1118     }
1119     if (!isRRect && path.isRect(&rect)) {
1120         rrect.setRect(rect);
1121         isRRect = true;
1122     }
1123 
1124     if (!isRRect) {
1125         return false;
1126     }
1127 
1128     if (rrect.isEmpty()) {
1129         return true;
1130     }
1131 
1132     AutoCheckFlush acf(this->drawingManager());
1133 
1134     // transform light
1135     SkPoint3 devLightPos = map(viewMatrix, rec.fLightPos);
1136 
1137     // 1/scale
1138     SkScalar devToSrcScale = viewMatrix.isScaleTranslate() ?
1139         SkScalarInvert(SkScalarAbs(viewMatrix[SkMatrix::kMScaleX])) :
1140         sk_float_rsqrt(viewMatrix[SkMatrix::kMScaleX] * viewMatrix[SkMatrix::kMScaleX] +
1141                        viewMatrix[SkMatrix::kMSkewX] * viewMatrix[SkMatrix::kMSkewX]);
1142 
1143     SkScalar occluderHeight = rec.fZPlaneParams.fZ;
1144     bool transparent = SkToBool(rec.fFlags & SkShadowFlags::kTransparentOccluder_ShadowFlag);
1145 
1146     if (SkColorGetA(rec.fAmbientColor) > 0) {
1147         SkScalar devSpaceInsetWidth = SkDrawShadowMetrics::AmbientBlurRadius(occluderHeight);
1148         const SkScalar umbraRecipAlpha = SkDrawShadowMetrics::AmbientRecipAlpha(occluderHeight);
1149         const SkScalar devSpaceAmbientBlur = devSpaceInsetWidth * umbraRecipAlpha;
1150 
1151         // Outset the shadow rrect to the border of the penumbra
1152         SkScalar ambientPathOutset = devSpaceInsetWidth * devToSrcScale;
1153         SkRRect ambientRRect;
1154         SkRect outsetRect = rrect.rect().makeOutset(ambientPathOutset, ambientPathOutset);
1155         // If the rrect was an oval then its outset will also be one.
1156         // We set it explicitly to avoid errors.
1157         if (rrect.isOval()) {
1158             ambientRRect = SkRRect::MakeOval(outsetRect);
1159         } else {
1160             SkScalar outsetRad = SkRRectPriv::GetSimpleRadii(rrect).fX + ambientPathOutset;
1161             ambientRRect = SkRRect::MakeRectXY(outsetRect, outsetRad, outsetRad);
1162         }
1163 
1164         GrColor ambientColor = SkColorToPremulGrColor(rec.fAmbientColor);
1165         if (transparent) {
1166             // set a large inset to force a fill
1167             devSpaceInsetWidth = ambientRRect.width();
1168         }
1169 
1170         std::unique_ptr<GrDrawOp> op = GrShadowRRectOp::Make(fContext,
1171                                                              ambientColor,
1172                                                              viewMatrix,
1173                                                              ambientRRect,
1174                                                              devSpaceAmbientBlur,
1175                                                              devSpaceInsetWidth);
1176         if (op) {
1177             this->addDrawOp(clip, std::move(op));
1178         }
1179     }
1180 
1181     if (SkColorGetA(rec.fSpotColor) > 0) {
1182         SkScalar devSpaceSpotBlur;
1183         SkScalar spotScale;
1184         SkVector spotOffset;
1185         SkDrawShadowMetrics::GetSpotParams(occluderHeight, devLightPos.fX, devLightPos.fY,
1186                                            devLightPos.fZ, rec.fLightRadius,
1187                                            &devSpaceSpotBlur, &spotScale, &spotOffset);
1188         // handle scale of radius due to CTM
1189         const SkScalar srcSpaceSpotBlur = devSpaceSpotBlur * devToSrcScale;
1190 
1191         // Adjust translate for the effect of the scale.
1192         spotOffset.fX += spotScale*viewMatrix[SkMatrix::kMTransX];
1193         spotOffset.fY += spotScale*viewMatrix[SkMatrix::kMTransY];
1194         // This offset is in dev space, need to transform it into source space.
1195         SkMatrix ctmInverse;
1196         if (viewMatrix.invert(&ctmInverse)) {
1197             ctmInverse.mapPoints(&spotOffset, 1);
1198         } else {
1199             // Since the matrix is a similarity, this should never happen, but just in case...
1200             SkDebugf("Matrix is degenerate. Will not render spot shadow correctly!\n");
1201             SkASSERT(false);
1202         }
1203 
1204         // Compute the transformed shadow rrect
1205         SkRRect spotShadowRRect;
1206         SkMatrix shadowTransform;
1207         shadowTransform.setScaleTranslate(spotScale, spotScale, spotOffset.fX, spotOffset.fY);
1208         rrect.transform(shadowTransform, &spotShadowRRect);
1209         SkScalar spotRadius = SkRRectPriv::GetSimpleRadii(spotShadowRRect).fX;
1210 
1211         // Compute the insetWidth
1212         SkScalar blurOutset = srcSpaceSpotBlur;
1213         SkScalar insetWidth = blurOutset;
1214         if (transparent) {
1215             // If transparent, just do a fill
1216             insetWidth += spotShadowRRect.width();
1217         } else {
1218             // For shadows, instead of using a stroke we specify an inset from the penumbra
1219             // border. We want to extend this inset area so that it meets up with the caster
1220             // geometry. The inset geometry will by default already be inset by the blur width.
1221             //
1222             // We compare the min and max corners inset by the radius between the original
1223             // rrect and the shadow rrect. The distance between the two plus the difference
1224             // between the scaled radius and the original radius gives the distance from the
1225             // transformed shadow shape to the original shape in that corner. The max
1226             // of these gives the maximum distance we need to cover.
1227             //
1228             // Since we are outsetting by 1/2 the blur distance, we just add the maxOffset to
1229             // that to get the full insetWidth.
1230             SkScalar maxOffset;
1231             if (rrect.isRect()) {
1232                 // Manhattan distance works better for rects
1233                 maxOffset = SkTMax(SkTMax(SkTAbs(spotShadowRRect.rect().fLeft -
1234                                                  rrect.rect().fLeft),
1235                                           SkTAbs(spotShadowRRect.rect().fTop -
1236                                                  rrect.rect().fTop)),
1237                                    SkTMax(SkTAbs(spotShadowRRect.rect().fRight -
1238                                                  rrect.rect().fRight),
1239                                           SkTAbs(spotShadowRRect.rect().fBottom -
1240                                                  rrect.rect().fBottom)));
1241             } else {
1242                 SkScalar dr = spotRadius - SkRRectPriv::GetSimpleRadii(rrect).fX;
1243                 SkPoint upperLeftOffset = SkPoint::Make(spotShadowRRect.rect().fLeft -
1244                                                         rrect.rect().fLeft + dr,
1245                                                         spotShadowRRect.rect().fTop -
1246                                                         rrect.rect().fTop + dr);
1247                 SkPoint lowerRightOffset = SkPoint::Make(spotShadowRRect.rect().fRight -
1248                                                          rrect.rect().fRight - dr,
1249                                                          spotShadowRRect.rect().fBottom -
1250                                                          rrect.rect().fBottom - dr);
1251                 maxOffset = SkScalarSqrt(SkTMax(SkPointPriv::LengthSqd(upperLeftOffset),
1252                                                 SkPointPriv::LengthSqd(lowerRightOffset))) + dr;
1253             }
1254             insetWidth += SkTMax(blurOutset, maxOffset);
1255         }
1256 
1257         // Outset the shadow rrect to the border of the penumbra
1258         SkRect outsetRect = spotShadowRRect.rect().makeOutset(blurOutset, blurOutset);
1259         if (spotShadowRRect.isOval()) {
1260             spotShadowRRect = SkRRect::MakeOval(outsetRect);
1261         } else {
1262             SkScalar outsetRad = spotRadius + blurOutset;
1263             spotShadowRRect = SkRRect::MakeRectXY(outsetRect, outsetRad, outsetRad);
1264         }
1265 
1266         GrColor spotColor = SkColorToPremulGrColor(rec.fSpotColor);
1267 
1268         std::unique_ptr<GrDrawOp> op = GrShadowRRectOp::Make(fContext,
1269                                                              spotColor,
1270                                                              viewMatrix,
1271                                                              spotShadowRRect,
1272                                                              2.0f * devSpaceSpotBlur,
1273                                                              insetWidth);
1274         if (op) {
1275             this->addDrawOp(clip, std::move(op));
1276         }
1277     }
1278 
1279     return true;
1280 }
1281 
1282 ///////////////////////////////////////////////////////////////////////////////
1283 
drawFilledDRRect(const GrClip & clip,GrPaint && paint,GrAA aa,const SkMatrix & viewMatrix,const SkRRect & origOuter,const SkRRect & origInner)1284 bool GrRenderTargetContext::drawFilledDRRect(const GrClip& clip,
1285                                              GrPaint&& paint,
1286                                              GrAA aa,
1287                                              const SkMatrix& viewMatrix,
1288                                              const SkRRect& origOuter,
1289                                              const SkRRect& origInner) {
1290     SkASSERT(!origInner.isEmpty());
1291     SkASSERT(!origOuter.isEmpty());
1292 
1293     SkTCopyOnFirstWrite<SkRRect> inner(origInner), outer(origOuter);
1294 
1295     GrAAType aaType = this->chooseAAType(aa);
1296 
1297     if (GrAAType::kMSAA == aaType) {
1298         return false;
1299     }
1300 
1301     if (GrAAType::kCoverage == aaType && SkRRectPriv::IsCircle(*inner)
1302                                       && SkRRectPriv::IsCircle(*outer)) {
1303         auto outerR = outer->width() / 2.f;
1304         auto innerR = inner->width() / 2.f;
1305         auto cx = outer->getBounds().fLeft + outerR;
1306         auto cy = outer->getBounds().fTop + outerR;
1307         if (SkScalarNearlyEqual(cx, inner->getBounds().fLeft + innerR) &&
1308             SkScalarNearlyEqual(cy, inner->getBounds().fTop + innerR)) {
1309             auto avgR = (innerR + outerR) / 2.f;
1310             auto circleBounds = SkRect::MakeLTRB(cx - avgR, cy - avgR, cx + avgR, cy + avgR);
1311             SkStrokeRec stroke(SkStrokeRec::kFill_InitStyle);
1312             stroke.setStrokeStyle(outerR - innerR);
1313             auto op = GrOvalOpFactory::MakeOvalOp(fContext, std::move(paint), viewMatrix,
1314                                                   circleBounds, GrStyle(stroke, nullptr),
1315                                                   this->caps()->shaderCaps());
1316             if (op) {
1317                 this->addDrawOp(clip, std::move(op));
1318                 return true;
1319             }
1320             assert_alive(paint);
1321         }
1322     }
1323 
1324     GrClipEdgeType innerEdgeType, outerEdgeType;
1325     if (GrAAType::kCoverage == aaType) {
1326         innerEdgeType = GrClipEdgeType::kInverseFillAA;
1327         outerEdgeType = GrClipEdgeType::kFillAA;
1328     } else {
1329         innerEdgeType = GrClipEdgeType::kInverseFillBW;
1330         outerEdgeType = GrClipEdgeType::kFillBW;
1331     }
1332 
1333     SkMatrix inverseVM;
1334     if (!viewMatrix.isIdentity()) {
1335         if (!origInner.transform(viewMatrix, inner.writable())) {
1336             return false;
1337         }
1338         if (!origOuter.transform(viewMatrix, outer.writable())) {
1339             return false;
1340         }
1341         if (!viewMatrix.invert(&inverseVM)) {
1342             return false;
1343         }
1344     } else {
1345         inverseVM.reset();
1346     }
1347 
1348     const auto& caps = *this->caps()->shaderCaps();
1349     // TODO these need to be a geometry processors
1350     auto innerEffect = GrRRectEffect::Make(innerEdgeType, *inner, caps);
1351     if (!innerEffect) {
1352         return false;
1353     }
1354 
1355     auto outerEffect = GrRRectEffect::Make(outerEdgeType, *outer, caps);
1356     if (!outerEffect) {
1357         return false;
1358     }
1359 
1360     paint.addCoverageFragmentProcessor(std::move(innerEffect));
1361     paint.addCoverageFragmentProcessor(std::move(outerEffect));
1362 
1363     SkRect bounds = outer->getBounds();
1364     if (GrAAType::kCoverage == aaType) {
1365         bounds.outset(SK_ScalarHalf, SK_ScalarHalf);
1366     }
1367 
1368     this->fillRectWithLocalMatrix(clip, std::move(paint), GrAA::kNo, SkMatrix::I(), bounds,
1369                                   inverseVM);
1370     return true;
1371 }
1372 
drawDRRect(const GrClip & clip,GrPaint && paint,GrAA aa,const SkMatrix & viewMatrix,const SkRRect & outer,const SkRRect & inner)1373 void GrRenderTargetContext::drawDRRect(const GrClip& clip,
1374                                        GrPaint&& paint,
1375                                        GrAA aa,
1376                                        const SkMatrix& viewMatrix,
1377                                        const SkRRect& outer,
1378                                        const SkRRect& inner) {
1379     ASSERT_SINGLE_OWNER
1380     RETURN_IF_ABANDONED
1381     SkDEBUGCODE(this->validate();)
1382     GR_CREATE_TRACE_MARKER_CONTEXT("GrRenderTargetContext", "drawDRRect", fContext);
1383 
1384     SkASSERT(!outer.isEmpty());
1385     SkASSERT(!inner.isEmpty());
1386 
1387     AutoCheckFlush acf(this->drawingManager());
1388 
1389     if (this->drawFilledDRRect(clip, std::move(paint), aa, viewMatrix, outer, inner)) {
1390         return;
1391     }
1392     assert_alive(paint);
1393 
1394     SkPath path;
1395     path.setIsVolatile(true);
1396     path.addRRect(inner);
1397     path.addRRect(outer);
1398     path.setFillType(SkPath::kEvenOdd_FillType);
1399     this->drawShapeUsingPathRenderer(clip, std::move(paint), aa, viewMatrix, GrShape(path));
1400 }
1401 
1402 ///////////////////////////////////////////////////////////////////////////////
1403 
drawRegion(const GrClip & clip,GrPaint && paint,GrAA aa,const SkMatrix & viewMatrix,const SkRegion & region,const GrStyle & style,const GrUserStencilSettings * ss)1404 void GrRenderTargetContext::drawRegion(const GrClip& clip,
1405                                        GrPaint&& paint,
1406                                        GrAA aa,
1407                                        const SkMatrix& viewMatrix,
1408                                        const SkRegion& region,
1409                                        const GrStyle& style,
1410                                        const GrUserStencilSettings* ss) {
1411     ASSERT_SINGLE_OWNER
1412     RETURN_IF_ABANDONED
1413     SkDEBUGCODE(this->validate();)
1414     GR_CREATE_TRACE_MARKER_CONTEXT("GrRenderTargetContext", "drawRegion", fContext);
1415 
1416     if (GrAA::kYes == aa) {
1417         // GrRegionOp performs no antialiasing but is much faster, so here we check the matrix
1418         // to see whether aa is really required.
1419         if (!SkToBool(viewMatrix.getType() & ~(SkMatrix::kTranslate_Mask)) &&
1420             SkScalarIsInt(viewMatrix.getTranslateX()) &&
1421             SkScalarIsInt(viewMatrix.getTranslateY())) {
1422             aa = GrAA::kNo;
1423         }
1424     }
1425     bool complexStyle = !style.isSimpleFill();
1426     if (complexStyle || GrAA::kYes == aa) {
1427         SkPath path;
1428         region.getBoundaryPath(&path);
1429         path.setIsVolatile(true);
1430 
1431         return this->drawPath(clip, std::move(paint), aa, viewMatrix, path, style);
1432     }
1433 
1434     GrAAType aaType = this->chooseAAType(GrAA::kNo);
1435     std::unique_ptr<GrDrawOp> op = GrRegionOp::Make(fContext, std::move(paint), viewMatrix, region,
1436                                                     aaType, ss);
1437     this->addDrawOp(clip, std::move(op));
1438 }
1439 
drawOval(const GrClip & clip,GrPaint && paint,GrAA aa,const SkMatrix & viewMatrix,const SkRect & oval,const GrStyle & style)1440 void GrRenderTargetContext::drawOval(const GrClip& clip,
1441                                      GrPaint&& paint,
1442                                      GrAA aa,
1443                                      const SkMatrix& viewMatrix,
1444                                      const SkRect& oval,
1445                                      const GrStyle& style) {
1446     ASSERT_SINGLE_OWNER
1447     RETURN_IF_ABANDONED
1448     SkDEBUGCODE(this->validate();)
1449     GR_CREATE_TRACE_MARKER_CONTEXT("GrRenderTargetContext", "drawOval", fContext);
1450 
1451     const SkStrokeRec& stroke = style.strokeRec();
1452 
1453     if (oval.isEmpty() && !style.pathEffect()) {
1454         if (stroke.getStyle() == SkStrokeRec::kFill_Style) {
1455             return;
1456         }
1457 
1458         this->drawRect(clip, std::move(paint), aa, viewMatrix, oval, &style);
1459         return;
1460     }
1461 
1462     AutoCheckFlush acf(this->drawingManager());
1463 
1464     GrAAType aaType = this->chooseAAType(aa);
1465 
1466     std::unique_ptr<GrDrawOp> op;
1467     if (GrAAType::kCoverage == aaType && oval.width() > SK_ScalarNearlyZero &&
1468         oval.width() == oval.height() && viewMatrix.isSimilarity()) {
1469         // We don't draw true circles as round rects in coverage mode, because it can
1470         // cause perf regressions on some platforms as compared to the dedicated circle Op.
1471         assert_alive(paint);
1472         op = GrOvalOpFactory::MakeCircleOp(fContext, std::move(paint), viewMatrix, oval, style,
1473                                            this->caps()->shaderCaps());
1474     }
1475     if (!op && style.isSimpleFill()) {
1476         // GrFillRRectOp has special geometry and a fragment-shader branch to conditionally evaluate
1477         // the arc equation. This same special geometry and fragment branch also turn out to be a
1478         // substantial optimization for drawing ovals (namely, by not evaluating the arc equation
1479         // inside the oval's inner diamond). Given these optimizations, it's a clear win to draw
1480         // ovals the exact same way we do round rects.
1481         assert_alive(paint);
1482         op = GrFillRRectOp::Make(fContext, aaType, viewMatrix, SkRRect::MakeOval(oval),
1483                                  *this->caps(), std::move(paint));
1484     }
1485     if (!op && GrAAType::kCoverage == aaType) {
1486         assert_alive(paint);
1487         op = GrOvalOpFactory::MakeOvalOp(fContext, std::move(paint), viewMatrix, oval, style,
1488                                          this->caps()->shaderCaps());
1489     }
1490     if (op) {
1491         this->addDrawOp(clip, std::move(op));
1492         return;
1493     }
1494 
1495     assert_alive(paint);
1496     this->drawShapeUsingPathRenderer(
1497             clip, std::move(paint), aa, viewMatrix,
1498             GrShape(SkRRect::MakeOval(oval), SkPath::kCW_Direction, 2, false, style));
1499 }
1500 
drawArc(const GrClip & clip,GrPaint && paint,GrAA aa,const SkMatrix & viewMatrix,const SkRect & oval,SkScalar startAngle,SkScalar sweepAngle,bool useCenter,const GrStyle & style)1501 void GrRenderTargetContext::drawArc(const GrClip& clip,
1502                                     GrPaint&& paint,
1503                                     GrAA aa,
1504                                     const SkMatrix& viewMatrix,
1505                                     const SkRect& oval,
1506                                     SkScalar startAngle,
1507                                     SkScalar sweepAngle,
1508                                     bool useCenter,
1509                                     const GrStyle& style) {
1510     ASSERT_SINGLE_OWNER
1511     RETURN_IF_ABANDONED
1512     SkDEBUGCODE(this->validate();)
1513             GR_CREATE_TRACE_MARKER_CONTEXT("GrRenderTargetContext", "drawArc", fContext);
1514 
1515     AutoCheckFlush acf(this->drawingManager());
1516 
1517     GrAAType aaType = this->chooseAAType(aa);
1518     if (GrAAType::kCoverage == aaType) {
1519         const GrShaderCaps* shaderCaps = this->caps()->shaderCaps();
1520         std::unique_ptr<GrDrawOp> op = GrOvalOpFactory::MakeArcOp(fContext,
1521                                                                   std::move(paint),
1522                                                                   viewMatrix,
1523                                                                   oval,
1524                                                                   startAngle,
1525                                                                   sweepAngle,
1526                                                                   useCenter,
1527                                                                   style,
1528                                                                   shaderCaps);
1529         if (op) {
1530             this->addDrawOp(clip, std::move(op));
1531             return;
1532         }
1533         assert_alive(paint);
1534     }
1535     this->drawShapeUsingPathRenderer(
1536             clip, std::move(paint), aa, viewMatrix,
1537             GrShape::MakeArc(oval, startAngle, sweepAngle, useCenter, style));
1538 }
1539 
drawImageLattice(const GrClip & clip,GrPaint && paint,const SkMatrix & viewMatrix,sk_sp<GrTextureProxy> image,sk_sp<GrColorSpaceXform> csxf,GrSamplerState::Filter filter,std::unique_ptr<SkLatticeIter> iter,const SkRect & dst)1540 void GrRenderTargetContext::drawImageLattice(const GrClip& clip,
1541                                              GrPaint&& paint,
1542                                              const SkMatrix& viewMatrix,
1543                                              sk_sp<GrTextureProxy> image,
1544                                              sk_sp<GrColorSpaceXform> csxf,
1545                                              GrSamplerState::Filter filter,
1546                                              std::unique_ptr<SkLatticeIter> iter,
1547                                              const SkRect& dst) {
1548     ASSERT_SINGLE_OWNER
1549     RETURN_IF_ABANDONED
1550     SkDEBUGCODE(this->validate();)
1551     GR_CREATE_TRACE_MARKER_CONTEXT("GrRenderTargetContext", "drawImageLattice", fContext);
1552 
1553     AutoCheckFlush acf(this->drawingManager());
1554 
1555     std::unique_ptr<GrDrawOp> op =
1556             GrLatticeOp::MakeNonAA(fContext, std::move(paint), viewMatrix, std::move(image),
1557                                    std::move(csxf), filter, std::move(iter), dst);
1558     this->addDrawOp(clip, std::move(op));
1559 }
1560 
drawDrawable(std::unique_ptr<SkDrawable::GpuDrawHandler> drawable,const SkRect & bounds)1561 void GrRenderTargetContext::drawDrawable(std::unique_ptr<SkDrawable::GpuDrawHandler> drawable,
1562                                          const SkRect& bounds) {
1563     std::unique_ptr<GrOp> op(GrDrawableOp::Make(fContext, std::move(drawable), bounds));
1564     SkASSERT(op);
1565     this->addOp(std::move(op));
1566 }
1567 
asyncRescaleAndReadPixels(const SkImageInfo & info,const SkIRect & srcRect,SkSurface::RescaleGamma rescaleGamma,SkFilterQuality rescaleQuality,ReadPixelsCallback callback,ReadPixelsContext context)1568 void GrRenderTargetContext::asyncRescaleAndReadPixels(
1569         const SkImageInfo& info, const SkIRect& srcRect, SkSurface::RescaleGamma rescaleGamma,
1570         SkFilterQuality rescaleQuality, ReadPixelsCallback callback, ReadPixelsContext context) {
1571     auto direct = fContext->priv().asDirectContext();
1572     if (!direct) {
1573         callback(context, nullptr, 0);
1574         return;
1575     }
1576     if (fRenderTargetProxy->wrapsVkSecondaryCB()) {
1577         callback(context, nullptr, 0);
1578         return;
1579     }
1580     auto dstCT = SkColorTypeToGrColorType(info.colorType());
1581     bool needsRescale = srcRect.width() != info.width() || srcRect.height() != info.height();
1582     auto colorTypeOfFinalContext = this->colorSpaceInfo().colorType();
1583     auto backendFormatOfFinalContext = fRenderTargetProxy->backendFormat();
1584     if (needsRescale) {
1585         colorTypeOfFinalContext = dstCT;
1586         backendFormatOfFinalContext = this->caps()->getDefaultBackendFormat(dstCT,
1587                                                                             GrRenderable::kYes);
1588     }
1589     auto readInfo = this->caps()->supportedReadPixelsColorType(colorTypeOfFinalContext,
1590                                                                backendFormatOfFinalContext, dstCT);
1591     // Fail if we can't read from the source surface's color type.
1592     if (readInfo.fColorType == GrColorType::kUnknown) {
1593         callback(context, nullptr, 0);
1594         return;
1595     }
1596     // Fail if read color type does not have all of dstCT's color channels and those missing color
1597     // channels are in the src.
1598     uint32_t dstComponents = GrColorTypeComponentFlags(dstCT);
1599     uint32_t legalReadComponents = GrColorTypeComponentFlags(readInfo.fColorType);
1600     uint32_t srcComponents = GrColorTypeComponentFlags(this->colorSpaceInfo().colorType());
1601     if ((~legalReadComponents & dstComponents) & srcComponents) {
1602         callback(context, nullptr, 0);
1603         return;
1604     }
1605 
1606     sk_sp<GrRenderTargetContext> rtc;
1607     int x = srcRect.fLeft;
1608     int y = srcRect.fTop;
1609     if (needsRescale) {
1610         rtc = this->rescale(info, srcRect, rescaleGamma, rescaleQuality);
1611         if (!rtc) {
1612             callback(context, nullptr, 0);
1613             return;
1614         }
1615         SkASSERT(SkColorSpace::Equals(rtc->colorSpaceInfo().colorSpace(), info.colorSpace()));
1616         SkASSERT(rtc->origin() == kTopLeft_GrSurfaceOrigin);
1617         x = y = 0;
1618     } else {
1619         sk_sp<GrColorSpaceXform> xform =
1620                 GrColorSpaceXform::Make(this->colorSpaceInfo().colorSpace(),
1621                                         this->colorSpaceInfo().alphaType(),
1622                                         info.colorSpace(), info.alphaType());
1623         // Insert a draw to a temporary surface if we need to do a y-flip or color space conversion.
1624         if (this->origin() == kBottomLeft_GrSurfaceOrigin || xform) {
1625             // We flip or color convert by drawing and we don't currently support drawing to
1626             // kPremul.
1627             if (info.alphaType() == kUnpremul_SkAlphaType) {
1628                 callback(context, nullptr, 0);
1629                 return;
1630             }
1631             sk_sp<GrTextureProxy> texProxy = sk_ref_sp(fRenderTargetProxy->asTextureProxy());
1632             SkRect srcRectToDraw = SkRect::Make(srcRect);
1633             // If the src is not texturable first try to make a copy to a texture.
1634             if (!texProxy) {
1635                 texProxy = GrSurfaceProxy::Copy(fContext, fRenderTargetProxy.get(),
1636                                                 GrMipMapped::kNo, srcRect, SkBackingFit::kApprox,
1637                                                 SkBudgeted::kNo);
1638                 if (!texProxy) {
1639                     callback(context, nullptr, 0);
1640                     return;
1641                 }
1642                 srcRectToDraw = SkRect::MakeWH(srcRect.width(), srcRect.height());
1643             }
1644             rtc = direct->priv().makeDeferredRenderTargetContext(
1645                     SkBackingFit::kApprox, srcRect.width(), srcRect.height(),
1646                     this->colorSpaceInfo().colorType(), info.refColorSpace(), 1, GrMipMapped::kNo,
1647                     kTopLeft_GrSurfaceOrigin);
1648             if (!rtc) {
1649                 callback(context, nullptr, 0);
1650                 return;
1651             }
1652             rtc->drawTexture(GrNoClip(), std::move(texProxy), GrSamplerState::Filter::kNearest,
1653                              SkBlendMode::kSrc, SK_PMColor4fWHITE, srcRectToDraw,
1654                              SkRect::MakeWH(srcRect.width(), srcRect.height()), GrAA::kNo,
1655                              GrQuadAAFlags::kNone, SkCanvas::kFast_SrcRectConstraint, SkMatrix::I(),
1656                              std::move(xform));
1657             x = y = 0;
1658         } else {
1659             rtc = sk_ref_sp(this);
1660         }
1661     }
1662     return rtc->asyncReadPixels(SkIRect::MakeXYWH(x, y, info.width(), info.height()),
1663                                 info.colorType(), callback, context);
1664 }
1665 
asyncReadPixels(const SkIRect & rect,SkColorType colorType,ReadPixelsCallback callback,ReadPixelsContext context)1666 void GrRenderTargetContext::asyncReadPixels(const SkIRect& rect, SkColorType colorType,
1667                                             ReadPixelsCallback callback,
1668                                             ReadPixelsContext context) {
1669     SkASSERT(rect.fLeft >= 0 && rect.fRight <= this->width());
1670     SkASSERT(rect.fTop >= 0 && rect.fBottom <= this->height());
1671 
1672     auto transferResult = this->transferPixels(SkColorTypeToGrColorType(colorType), rect);
1673 
1674     if (!transferResult.fTransferBuffer) {
1675         SkAutoPixmapStorage pm;
1676         auto ii = SkImageInfo::Make(rect.width(), rect.height(), colorType,
1677                                     this->colorSpaceInfo().alphaType(),
1678                                     this->colorSpaceInfo().refColorSpace());
1679         pm.alloc(ii);
1680         if (!this->readPixels(ii, pm.writable_addr(), pm.rowBytes(), {rect.fLeft, rect.fTop})) {
1681             callback(context, nullptr, 0);
1682         }
1683         callback(context, pm.addr(), pm.rowBytes());
1684         return;
1685     }
1686 
1687     struct FinishContext {
1688         ReadPixelsCallback* fClientCallback;
1689         ReadPixelsContext fClientContext;
1690         int fW, fH;
1691         SkColorType fColorType;
1692         PixelTransferResult fTransferResult;
1693     };
1694     // Assumption is that the caller would like to flush. We could take a parameter or require an
1695     // explicit flush from the caller. We'd have to have a way to defer attaching the finish
1696     // callback to GrGpu until after the next flush that flushes our op list, though.
1697     auto* finishContext = new FinishContext{callback, context, rect.width(),
1698                                             rect.height(), colorType, std::move(transferResult)};
1699     auto finishCallback = [](GrGpuFinishedContext c) {
1700         const auto* context = reinterpret_cast<const FinishContext*>(c);
1701         const void* data = context->fTransferResult.fTransferBuffer->map();
1702         if (!data) {
1703             (*context->fClientCallback)(context->fClientContext, nullptr, 0);
1704             delete context;
1705             return;
1706         }
1707         std::unique_ptr<char[]> tmp;
1708         size_t rowBytes = context->fW * SkColorTypeBytesPerPixel(context->fColorType);
1709         if (context->fTransferResult.fPixelConverter) {
1710             tmp.reset(new char[rowBytes * context->fH]);
1711             context->fTransferResult.fPixelConverter(tmp.get(), data);
1712             data = tmp.get();
1713         }
1714         (*context->fClientCallback)(context->fClientContext, data, rowBytes);
1715         delete context;
1716     };
1717     GrFlushInfo flushInfo;
1718     flushInfo.fFinishedContext = finishContext;
1719     flushInfo.fFinishedProc = finishCallback;
1720     this->flush(SkSurface::BackendSurfaceAccess::kNoAccess, flushInfo);
1721 }
1722 
asyncRescaleAndReadPixelsYUV420(SkYUVColorSpace yuvColorSpace,sk_sp<SkColorSpace> dstColorSpace,const SkIRect & srcRect,int dstW,int dstH,RescaleGamma rescaleGamma,SkFilterQuality rescaleQuality,ReadPixelsCallbackYUV420 callback,ReadPixelsContext context)1723 void GrRenderTargetContext::asyncRescaleAndReadPixelsYUV420(
1724         SkYUVColorSpace yuvColorSpace, sk_sp<SkColorSpace> dstColorSpace, const SkIRect& srcRect,
1725         int dstW, int dstH, RescaleGamma rescaleGamma, SkFilterQuality rescaleQuality,
1726         ReadPixelsCallbackYUV420 callback, ReadPixelsContext context) {
1727     SkASSERT(srcRect.fLeft >= 0 && srcRect.fRight <= this->width());
1728     SkASSERT(srcRect.fTop >= 0 && srcRect.fBottom <= this->height());
1729     SkASSERT((dstW % 2 == 0) && (dstH % 2 == 0));
1730     auto direct = fContext->priv().asDirectContext();
1731     if (!direct) {
1732         callback(context, nullptr, nullptr);
1733         return;
1734     }
1735     if (fRenderTargetProxy->wrapsVkSecondaryCB()) {
1736         callback(context, nullptr, nullptr);
1737         return;
1738     }
1739     if (dstW & 0x1) {
1740         return;
1741     }
1742     int x = srcRect.fLeft;
1743     int y = srcRect.fTop;
1744     auto rtc = sk_ref_sp(this);
1745     bool needsRescale = srcRect.width() != dstW || srcRect.height() != dstH;
1746     if (needsRescale) {
1747         // We assume the caller wants kPremul. There is no way to indicate a preference.
1748         auto info = SkImageInfo::Make(dstW, dstH, kRGBA_8888_SkColorType, kPremul_SkAlphaType,
1749                                       dstColorSpace);
1750         // TODO: Incorporate the YUV conversion into last pass of rescaling.
1751         rtc = this->rescale(info, srcRect, rescaleGamma, rescaleQuality);
1752         if (!rtc) {
1753             callback(context, nullptr, nullptr);
1754             return;
1755         }
1756         SkASSERT(SkColorSpace::Equals(rtc->colorSpaceInfo().colorSpace(), info.colorSpace()));
1757         SkASSERT(rtc->origin() == kTopLeft_GrSurfaceOrigin);
1758         x = y = 0;
1759     } else {
1760         // We assume the caller wants kPremul. There is no way to indicate a preference.
1761         sk_sp<GrColorSpaceXform> xform = GrColorSpaceXform::Make(
1762                 this->colorSpaceInfo().colorSpace(), this->colorSpaceInfo().alphaType(),
1763                 dstColorSpace.get(), kPremul_SkAlphaType);
1764         if (xform) {
1765             sk_sp<GrTextureProxy> texProxy = this->asTextureProxyRef();
1766             // TODO: Do something if the input is not a texture already.
1767             if (!texProxy) {
1768                 callback(context, nullptr, nullptr);
1769                 return;
1770             }
1771             SkRect srcRectToDraw = SkRect::Make(srcRect);
1772             rtc = direct->priv().makeDeferredRenderTargetContext(
1773                     SkBackingFit::kApprox, dstW, dstH, this->colorSpaceInfo().colorType(),
1774                     dstColorSpace, 1, GrMipMapped::kNo, kTopLeft_GrSurfaceOrigin);
1775             if (!rtc) {
1776                 callback(context, nullptr, nullptr);
1777                 return;
1778             }
1779             rtc->drawTexture(GrNoClip(), std::move(texProxy), GrSamplerState::Filter::kNearest,
1780                              SkBlendMode::kSrc, SK_PMColor4fWHITE, srcRectToDraw,
1781                              SkRect::MakeWH(srcRect.width(), srcRect.height()), GrAA::kNo,
1782                              GrQuadAAFlags::kNone, SkCanvas::kFast_SrcRectConstraint, SkMatrix::I(),
1783                              std::move(xform));
1784             x = y = 0;
1785         }
1786     }
1787     auto srcProxy = rtc->asTextureProxyRef();
1788     // TODO: Do something if the input is not a texture already.
1789     if (!srcProxy) {
1790         callback(context, nullptr, nullptr);
1791         return;
1792     }
1793     auto yRTC = direct->priv().makeDeferredRenderTargetContextWithFallback(
1794             SkBackingFit::kApprox, dstW, dstH, GrColorType::kAlpha_8, dstColorSpace, 1,
1795             GrMipMapped::kNo, kTopLeft_GrSurfaceOrigin);
1796     auto uRTC = direct->priv().makeDeferredRenderTargetContextWithFallback(
1797             SkBackingFit::kApprox, dstW / 2, dstH / 2, GrColorType::kAlpha_8, dstColorSpace, 1,
1798             GrMipMapped::kNo, kTopLeft_GrSurfaceOrigin);
1799     auto vRTC = direct->priv().makeDeferredRenderTargetContextWithFallback(
1800             SkBackingFit::kApprox, dstW / 2, dstH / 2, GrColorType::kAlpha_8, dstColorSpace, 1,
1801             GrMipMapped::kNo, kTopLeft_GrSurfaceOrigin);
1802     if (!yRTC || !uRTC || !vRTC) {
1803         callback(context, nullptr, nullptr);
1804         return;
1805     }
1806 
1807     static constexpr float kRec601M[] {
1808              65.481f / 255, 128.553f / 255,  24.966f / 255,  16.f / 255,   // y
1809             -37.797f / 255, -74.203f / 255, 112.0f   / 255, 128.f / 255,  // u
1810             112.f    / 255, -93.786f / 255, -18.214f / 255, 128.f / 255,  // v
1811     };
1812     static constexpr float kRec709M[] {
1813              45.5594f / 255,  156.6288f / 255,  15.8118f / 255,  16.f / 255, // y
1814             -25.6642f / 255,  -86.3358f / 255, 112.f     / 255, 128.f / 255,  // u
1815             112.f     / 255, -101.7303f / 255, -10.2697f / 255, 128.f / 255,  // v
1816     };
1817     static constexpr float kJpegM[] {
1818              0.299f   ,  0.587f   ,  0.114f   ,   0.f / 255,  // y
1819             -0.168736f, -0.331264f,  0.5f     , 128.f / 255,  // u
1820              0.5f     , -0.418688f, -0.081312f, 128.f / 255,  // v
1821     };
1822     static constexpr float kIM[] {
1823             1.f, 0.f, 0.f, 0.f,
1824             0.f, 1.f, 0.f, 0.f,
1825             0.f, 0.f, 1.f, 0.f,
1826     };
1827     const float* baseM = kIM;
1828     switch (yuvColorSpace) {
1829         case kRec601_SkYUVColorSpace:
1830             baseM = kRec601M;
1831             break;
1832         case kRec709_SkYUVColorSpace:
1833             baseM = kRec709M;
1834             break;
1835         case kJPEG_SkYUVColorSpace:
1836             baseM = kJpegM;
1837             break;
1838         case kIdentity_SkYUVColorSpace:
1839             baseM = kIM;
1840             break;
1841     }
1842     // TODO: Use one transfer buffer for all three planes to reduce map/unmap cost?
1843 
1844     auto texMatrix = SkMatrix::MakeTrans(x, y);
1845 
1846     SkRect dstRectY = SkRect::MakeWH(dstW, dstH);
1847     SkRect dstRectUV = SkRect::MakeWH(dstW / 2, dstH / 2);
1848 
1849     // This matrix generates (r,g,b,a) = (0, 0, 0, y)
1850     float yM[20];
1851     std::fill_n(yM, 15, 0.f);
1852     yM[15] = baseM[0]; yM[16] = baseM[1]; yM[17] = baseM[2]; yM[18] = 0; yM[19] = baseM[3];
1853     GrPaint yPaint;
1854     yPaint.addColorTextureProcessor(srcProxy, texMatrix);
1855     auto yFP = GrColorMatrixFragmentProcessor::Make(yM, false, true, false);
1856     yPaint.addColorFragmentProcessor(std::move(yFP));
1857     yPaint.setPorterDuffXPFactory(SkBlendMode::kSrc);
1858     yRTC->fillRectToRect(GrNoClip(), std::move(yPaint), GrAA::kNo, SkMatrix::I(),
1859                          dstRectY, dstRectY);
1860     auto yTransfer = yRTC->transferPixels(GrColorType::kAlpha_8,
1861                                           SkIRect::MakeWH(yRTC->width(), yRTC->height()));
1862     if (!yTransfer.fTransferBuffer) {
1863         callback(context, nullptr, nullptr);
1864         return;
1865     }
1866 
1867     texMatrix.preScale(2.f, 2.f);
1868     // This matrix generates (r,g,b,a) = (0, 0, 0, u)
1869     float uM[20];
1870     std::fill_n(uM, 15, 0.f);
1871     uM[15] = baseM[4]; uM[16] = baseM[5]; uM[17] = baseM[6]; uM[18] = 0; uM[19] = baseM[7];
1872     GrPaint uPaint;
1873     uPaint.addColorTextureProcessor(srcProxy, texMatrix, GrSamplerState::ClampBilerp());
1874     auto uFP = GrColorMatrixFragmentProcessor::Make(uM, false, true, false);
1875     uPaint.addColorFragmentProcessor(std::move(uFP));
1876     uPaint.setPorterDuffXPFactory(SkBlendMode::kSrc);
1877     uRTC->fillRectToRect(GrNoClip(), std::move(uPaint), GrAA::kNo, SkMatrix::I(),
1878                          dstRectUV, dstRectUV);
1879     auto uTransfer = uRTC->transferPixels(GrColorType::kAlpha_8,
1880                                           SkIRect::MakeWH(uRTC->width(), uRTC->height()));
1881     if (!uTransfer.fTransferBuffer) {
1882         callback(context, nullptr, nullptr);
1883         return;
1884     }
1885 
1886     // This matrix generates (r,g,b,a) = (0, 0, 0, v)
1887     float vM[20];
1888     std::fill_n(vM, 15, 0.f);
1889     vM[15] = baseM[8]; vM[16] = baseM[9]; vM[17] = baseM[10]; vM[18] = 0; vM[19] = baseM[11];
1890     GrPaint vPaint;
1891     vPaint.addColorTextureProcessor(srcProxy, texMatrix, GrSamplerState::ClampBilerp());
1892     auto vFP = GrColorMatrixFragmentProcessor::Make(vM, false, true, false);
1893     vPaint.addColorFragmentProcessor(std::move(vFP));
1894     vPaint.setPorterDuffXPFactory(SkBlendMode::kSrc);
1895     vRTC->fillRectToRect(GrNoClip(), std::move(vPaint), GrAA::kNo, SkMatrix::I(),
1896                          dstRectUV, dstRectUV);
1897     auto vTransfer = vRTC->transferPixels(GrColorType::kAlpha_8,
1898                                           SkIRect::MakeWH(vRTC->width(), vRTC->height()));
1899     if (!vTransfer.fTransferBuffer) {
1900         callback(context, nullptr, nullptr);
1901         return;
1902     }
1903 
1904     struct FinishContext {
1905         ReadPixelsCallbackYUV420* fClientCallback;
1906         ReadPixelsContext fClientContext;
1907         int fW, fH;
1908         PixelTransferResult fYTransfer;
1909         PixelTransferResult fUTransfer;
1910         PixelTransferResult fVTransfer;
1911     };
1912     // Assumption is that the caller would like to flush. We could take a parameter or require an
1913     // explicit flush from the caller. We'd have to have a way to defer attaching the finish
1914     // callback to GrGpu until after the next flush that flushes our op list, though.
1915     auto* finishContext = new FinishContext{callback,
1916                                             context,
1917                                             dstW,
1918                                             dstH,
1919                                             std::move(yTransfer),
1920                                             std::move(uTransfer),
1921                                             std::move(vTransfer)};
1922     auto finishCallback = [](GrGpuFinishedContext c) {
1923         const auto* context = reinterpret_cast<const FinishContext*>(c);
1924         const void* y = context->fYTransfer.fTransferBuffer->map();
1925         const void* u = context->fUTransfer.fTransferBuffer->map();
1926         const void* v = context->fVTransfer.fTransferBuffer->map();
1927         if (!y || !u || !v) {
1928             if (y) {
1929                 context->fYTransfer.fTransferBuffer->unmap();
1930             }
1931             if (u) {
1932                 context->fUTransfer.fTransferBuffer->unmap();
1933             }
1934             if (v) {
1935                 context->fVTransfer.fTransferBuffer->unmap();
1936             }
1937             (*context->fClientCallback)(context->fClientContext, nullptr, 0);
1938             delete context;
1939             return;
1940         }
1941         size_t w = SkToSizeT(context->fW);
1942         size_t h = SkToSizeT(context->fH);
1943         std::unique_ptr<uint8_t[]> yTemp;
1944         if (context->fYTransfer.fPixelConverter) {
1945             yTemp.reset(new uint8_t[w * h]);
1946             context->fYTransfer.fPixelConverter(yTemp.get(), y);
1947             y = yTemp.get();
1948         }
1949         std::unique_ptr<uint8_t[]> uTemp;
1950         if (context->fUTransfer.fPixelConverter) {
1951             uTemp.reset(new uint8_t[w / 2 * h / 2]);
1952             context->fUTransfer.fPixelConverter(uTemp.get(), u);
1953             u = uTemp.get();
1954         }
1955         std::unique_ptr<uint8_t[]> vTemp;
1956         if (context->fVTransfer.fPixelConverter) {
1957             vTemp.reset(new uint8_t[w / 2 * h / 2]);
1958             context->fVTransfer.fPixelConverter(vTemp.get(), v);
1959             v = vTemp.get();
1960         }
1961         const void* data[] = {y, u, v};
1962         size_t rowBytes[] = {w, w / 2, w / 2};
1963         (*context->fClientCallback)(context->fClientContext, data, rowBytes);
1964         context->fYTransfer.fTransferBuffer->unmap();
1965         context->fUTransfer.fTransferBuffer->unmap();
1966         context->fVTransfer.fTransferBuffer->unmap();
1967         delete context;
1968     };
1969     GrFlushInfo flushInfo;
1970     flushInfo.fFinishedContext = finishContext;
1971     flushInfo.fFinishedProc = finishCallback;
1972     this->flush(SkSurface::BackendSurfaceAccess::kNoAccess, flushInfo);
1973 }
1974 
flush(SkSurface::BackendSurfaceAccess access,const GrFlushInfo & info)1975 GrSemaphoresSubmitted GrRenderTargetContext::flush(SkSurface::BackendSurfaceAccess access,
1976                                                    const GrFlushInfo& info) {
1977     ASSERT_SINGLE_OWNER
1978     if (fContext->priv().abandoned()) {
1979         return GrSemaphoresSubmitted::kNo;
1980     }
1981     SkDEBUGCODE(this->validate();)
1982     GR_CREATE_TRACE_MARKER_CONTEXT("GrRenderTargetContext", "flush", fContext);
1983 
1984     return this->drawingManager()->flushSurface(fRenderTargetProxy.get(), access, info);
1985 }
1986 
waitOnSemaphores(int numSemaphores,const GrBackendSemaphore waitSemaphores[])1987 bool GrRenderTargetContext::waitOnSemaphores(int numSemaphores,
1988                                              const GrBackendSemaphore waitSemaphores[]) {
1989     ASSERT_SINGLE_OWNER
1990     RETURN_FALSE_IF_ABANDONED
1991     SkDEBUGCODE(this->validate();)
1992     GR_CREATE_TRACE_MARKER_CONTEXT("GrRenderTargetContext", "waitOnSemaphores", fContext);
1993 
1994     AutoCheckFlush acf(this->drawingManager());
1995 
1996     if (numSemaphores && !this->caps()->semaphoreSupport()) {
1997         return false;
1998     }
1999 
2000     auto direct = fContext->priv().asDirectContext();
2001     if (!direct) {
2002         return false;
2003     }
2004 
2005     auto resourceProvider = direct->priv().resourceProvider();
2006 
2007     for (int i = 0; i < numSemaphores; ++i) {
2008         sk_sp<GrSemaphore> sema = resourceProvider->wrapBackendSemaphore(
2009                 waitSemaphores[i], GrResourceProvider::SemaphoreWrapType::kWillWait,
2010                 kAdopt_GrWrapOwnership);
2011         std::unique_ptr<GrOp> waitOp(GrSemaphoreOp::MakeWait(fContext, std::move(sema),
2012                                                              fRenderTargetProxy.get()));
2013         this->getRTOpList()->addWaitOp(
2014                 std::move(waitOp), GrTextureResolveManager(this->drawingManager()), *this->caps());
2015     }
2016     return true;
2017 }
2018 
insertEventMarker(const SkString & str)2019 void GrRenderTargetContext::insertEventMarker(const SkString& str) {
2020     std::unique_ptr<GrOp> op(GrDebugMarkerOp::Make(fContext, fRenderTargetProxy.get(), str));
2021     this->addOp(std::move(op));
2022 }
2023 
drawPath(const GrClip & clip,GrPaint && paint,GrAA aa,const SkMatrix & viewMatrix,const SkPath & path,const GrStyle & style)2024 void GrRenderTargetContext::drawPath(const GrClip& clip,
2025                                      GrPaint&& paint,
2026                                      GrAA aa,
2027                                      const SkMatrix& viewMatrix,
2028                                      const SkPath& path,
2029                                      const GrStyle& style) {
2030     ASSERT_SINGLE_OWNER
2031     RETURN_IF_ABANDONED
2032     SkDEBUGCODE(this->validate();)
2033     GR_CREATE_TRACE_MARKER_CONTEXT("GrRenderTargetContext", "drawPath", fContext);
2034 
2035     GrShape shape(path, style);
2036 
2037     this->drawShape(clip, std::move(paint), aa, viewMatrix, shape);
2038 }
2039 
drawShape(const GrClip & clip,GrPaint && paint,GrAA aa,const SkMatrix & viewMatrix,const GrShape & shape)2040 void GrRenderTargetContext::drawShape(const GrClip& clip,
2041                                       GrPaint&& paint,
2042                                       GrAA aa,
2043                                       const SkMatrix& viewMatrix,
2044                                       const GrShape& shape) {
2045     ASSERT_SINGLE_OWNER
2046     RETURN_IF_ABANDONED
2047     SkDEBUGCODE(this->validate();)
2048     GR_CREATE_TRACE_MARKER_CONTEXT("GrRenderTargetContext", "drawShape", fContext);
2049 
2050     if (shape.isEmpty()) {
2051         if (shape.inverseFilled()) {
2052             this->drawPaint(clip, std::move(paint), viewMatrix);
2053         }
2054         return;
2055     }
2056 
2057     AutoCheckFlush acf(this->drawingManager());
2058 
2059     if (!shape.style().hasPathEffect()) {
2060         GrAAType aaType = this->chooseAAType(aa);
2061         SkRRect rrect;
2062         // We can ignore the starting point and direction since there is no path effect.
2063         bool inverted;
2064         if (shape.asRRect(&rrect, nullptr, nullptr, &inverted) && !inverted) {
2065             if (rrect.isRect()) {
2066                 this->drawRect(clip, std::move(paint), aa, viewMatrix, rrect.rect(),
2067                                &shape.style());
2068                 return;
2069             } else if (rrect.isOval()) {
2070                 this->drawOval(clip, std::move(paint), aa, viewMatrix, rrect.rect(), shape.style());
2071                 return;
2072             }
2073             this->drawRRect(clip, std::move(paint), aa, viewMatrix, rrect, shape.style());
2074             return;
2075         } else if (GrAAType::kCoverage == aaType && shape.style().isSimpleFill() &&
2076                    viewMatrix.rectStaysRect()) {
2077             // TODO: the rectStaysRect restriction could be lifted if we were willing to apply
2078             // the matrix to all the points individually rather than just to the rect
2079             SkRect rects[2];
2080             if (shape.asNestedRects(rects)) {
2081                 // Concave AA paths are expensive - try to avoid them for special cases
2082                 std::unique_ptr<GrDrawOp> op = GrStrokeRectOp::MakeNested(
2083                                 fContext, std::move(paint), viewMatrix, rects);
2084                 if (op) {
2085                     this->addDrawOp(clip, std::move(op));
2086                 }
2087                 // Returning here indicates that there is nothing to draw in this case.
2088                 return;
2089             }
2090         }
2091     }
2092 
2093     this->drawShapeUsingPathRenderer(clip, std::move(paint), aa, viewMatrix, shape);
2094 }
2095 
drawAndStencilPath(const GrHardClip & clip,const GrUserStencilSettings * ss,SkRegion::Op op,bool invert,GrAA aa,const SkMatrix & viewMatrix,const SkPath & path)2096 bool GrRenderTargetContextPriv::drawAndStencilPath(const GrHardClip& clip,
2097                                                    const GrUserStencilSettings* ss,
2098                                                    SkRegion::Op op,
2099                                                    bool invert,
2100                                                    GrAA aa,
2101                                                    const SkMatrix& viewMatrix,
2102                                                    const SkPath& path) {
2103     ASSERT_SINGLE_OWNER_PRIV
2104     RETURN_FALSE_IF_ABANDONED_PRIV
2105     SkDEBUGCODE(fRenderTargetContext->validate();)
2106     GR_CREATE_TRACE_MARKER_CONTEXT("GrRenderTargetContextPriv", "drawAndStencilPath",
2107                                    fRenderTargetContext->fContext);
2108 
2109     if (path.isEmpty() && path.isInverseFillType()) {
2110         GrPaint paint;
2111         paint.setCoverageSetOpXPFactory(op, invert);
2112         this->stencilRect(clip, ss, std::move(paint), GrAA::kNo, SkMatrix::I(),
2113                           SkRect::MakeIWH(fRenderTargetContext->width(),
2114                                           fRenderTargetContext->height()));
2115         return true;
2116     }
2117 
2118     AutoCheckFlush acf(fRenderTargetContext->drawingManager());
2119 
2120     // An Assumption here is that path renderer would use some form of tweaking
2121     // the src color (either the input alpha or in the frag shader) to implement
2122     // aa. If we have some future driver-mojo path AA that can do the right
2123     // thing WRT to the blend then we'll need some query on the PR.
2124     GrAAType aaType = fRenderTargetContext->chooseAAType(aa);
2125     bool hasUserStencilSettings = !ss->isUnused();
2126 
2127     SkIRect clipConservativeBounds;
2128     clip.getConservativeBounds(fRenderTargetContext->width(), fRenderTargetContext->height(),
2129                                &clipConservativeBounds, nullptr);
2130 
2131     GrShape shape(path, GrStyle::SimpleFill());
2132     GrPathRenderer::CanDrawPathArgs canDrawArgs;
2133     canDrawArgs.fCaps = fRenderTargetContext->caps();
2134     canDrawArgs.fProxy = fRenderTargetContext->proxy();
2135     canDrawArgs.fViewMatrix = &viewMatrix;
2136     canDrawArgs.fShape = &shape;
2137     canDrawArgs.fClipConservativeBounds = &clipConservativeBounds;
2138     canDrawArgs.fAAType = aaType;
2139     SkASSERT(!fRenderTargetContext->wrapsVkSecondaryCB());
2140     canDrawArgs.fTargetIsWrappedVkSecondaryCB = false;
2141     canDrawArgs.fHasUserStencilSettings = hasUserStencilSettings;
2142 
2143     // Don't allow the SW renderer
2144     GrPathRenderer* pr = fRenderTargetContext->drawingManager()->getPathRenderer(
2145             canDrawArgs, false, GrPathRendererChain::DrawType::kStencilAndColor);
2146     if (!pr) {
2147         return false;
2148     }
2149 
2150     GrPaint paint;
2151     paint.setCoverageSetOpXPFactory(op, invert);
2152 
2153     GrPathRenderer::DrawPathArgs args{fRenderTargetContext->drawingManager()->getContext(),
2154                                       std::move(paint),
2155                                       ss,
2156                                       fRenderTargetContext,
2157                                       &clip,
2158                                       &clipConservativeBounds,
2159                                       &viewMatrix,
2160                                       &shape,
2161                                       aaType,
2162                                       fRenderTargetContext->colorSpaceInfo().isLinearlyBlended()};
2163     pr->drawPath(args);
2164     return true;
2165 }
2166 
isBudgeted() const2167 SkBudgeted GrRenderTargetContextPriv::isBudgeted() const {
2168     ASSERT_SINGLE_OWNER_PRIV
2169 
2170     if (fRenderTargetContext->fContext->priv().abandoned()) {
2171         return SkBudgeted::kNo;
2172     }
2173 
2174     SkDEBUGCODE(fRenderTargetContext->validate();)
2175 
2176     return fRenderTargetContext->fRenderTargetProxy->isBudgeted();
2177 }
2178 
drawShapeUsingPathRenderer(const GrClip & clip,GrPaint && paint,GrAA aa,const SkMatrix & viewMatrix,const GrShape & originalShape)2179 void GrRenderTargetContext::drawShapeUsingPathRenderer(const GrClip& clip,
2180                                                        GrPaint&& paint,
2181                                                        GrAA aa,
2182                                                        const SkMatrix& viewMatrix,
2183                                                        const GrShape& originalShape) {
2184     ASSERT_SINGLE_OWNER
2185     RETURN_IF_ABANDONED
2186     GR_CREATE_TRACE_MARKER_CONTEXT("GrRenderTargetContext", "internalDrawPath", fContext);
2187 
2188     if (!viewMatrix.isFinite() || !originalShape.bounds().isFinite()) {
2189         return;
2190     }
2191 
2192     SkIRect clipConservativeBounds;
2193     clip.getConservativeBounds(this->width(), this->height(), &clipConservativeBounds, nullptr);
2194 
2195     GrShape tempShape;
2196     GrAAType aaType = this->chooseAAType(aa);
2197 
2198     GrPathRenderer::CanDrawPathArgs canDrawArgs;
2199     canDrawArgs.fCaps = this->caps();
2200     canDrawArgs.fProxy = this->proxy();
2201     canDrawArgs.fViewMatrix = &viewMatrix;
2202     canDrawArgs.fShape = &originalShape;
2203     canDrawArgs.fClipConservativeBounds = &clipConservativeBounds;
2204     canDrawArgs.fTargetIsWrappedVkSecondaryCB = this->wrapsVkSecondaryCB();
2205     canDrawArgs.fHasUserStencilSettings = false;
2206 
2207     GrPathRenderer* pr;
2208     static constexpr GrPathRendererChain::DrawType kType = GrPathRendererChain::DrawType::kColor;
2209     if (originalShape.isEmpty() && !originalShape.inverseFilled()) {
2210         return;
2211     }
2212 
2213     canDrawArgs.fAAType = aaType;
2214 
2215     // Try a 1st time without applying any of the style to the geometry (and barring sw)
2216     pr = this->drawingManager()->getPathRenderer(canDrawArgs, false, kType);
2217     SkScalar styleScale =  GrStyle::MatrixToScaleFactor(viewMatrix);
2218 
2219     if (!pr && originalShape.style().pathEffect()) {
2220         // It didn't work above, so try again with the path effect applied.
2221         tempShape = originalShape.applyStyle(GrStyle::Apply::kPathEffectOnly, styleScale);
2222         if (tempShape.isEmpty()) {
2223             return;
2224         }
2225         canDrawArgs.fShape = &tempShape;
2226         pr = this->drawingManager()->getPathRenderer(canDrawArgs, false, kType);
2227     }
2228     if (!pr) {
2229         if (canDrawArgs.fShape->style().applies()) {
2230             tempShape = canDrawArgs.fShape->applyStyle(GrStyle::Apply::kPathEffectAndStrokeRec,
2231                                                        styleScale);
2232             if (tempShape.isEmpty()) {
2233                 return;
2234             }
2235             canDrawArgs.fShape = &tempShape;
2236             // This time, allow SW renderer
2237             pr = this->drawingManager()->getPathRenderer(canDrawArgs, true, kType);
2238         } else {
2239             pr = this->drawingManager()->getSoftwarePathRenderer();
2240         }
2241     }
2242 
2243     if (!pr) {
2244 #ifdef SK_DEBUG
2245         SkDebugf("Unable to find path renderer compatible with path.\n");
2246 #endif
2247         return;
2248     }
2249 
2250     GrPathRenderer::DrawPathArgs args{this->drawingManager()->getContext(),
2251                                       std::move(paint),
2252                                       &GrUserStencilSettings::kUnused,
2253                                       this,
2254                                       &clip,
2255                                       &clipConservativeBounds,
2256                                       &viewMatrix,
2257                                       canDrawArgs.fShape,
2258                                       aaType,
2259                                       this->colorSpaceInfo().isLinearlyBlended()};
2260     pr->drawPath(args);
2261 }
2262 
op_bounds(SkRect * bounds,const GrOp * op)2263 static void op_bounds(SkRect* bounds, const GrOp* op) {
2264     *bounds = op->bounds();
2265     if (op->hasZeroArea()) {
2266         if (op->hasAABloat()) {
2267             bounds->outset(0.5f, 0.5f);
2268         } else {
2269             // We don't know which way the particular GPU will snap lines or points at integer
2270             // coords. So we ensure that the bounds is large enough for either snap.
2271             SkRect before = *bounds;
2272             bounds->roundOut(bounds);
2273             if (bounds->fLeft == before.fLeft) {
2274                 bounds->fLeft -= 1;
2275             }
2276             if (bounds->fTop == before.fTop) {
2277                 bounds->fTop -= 1;
2278             }
2279             if (bounds->fRight == before.fRight) {
2280                 bounds->fRight += 1;
2281             }
2282             if (bounds->fBottom == before.fBottom) {
2283                 bounds->fBottom += 1;
2284             }
2285         }
2286     }
2287 }
2288 
addOp(std::unique_ptr<GrOp> op)2289 void GrRenderTargetContext::addOp(std::unique_ptr<GrOp> op) {
2290     auto direct = fContext->priv().asDirectContext();
2291     if (direct && op) {
2292         op->setGrOpTag(direct->getCurrentGrResourceTag());
2293     }
2294     this->getRTOpList()->addOp(
2295             std::move(op), GrTextureResolveManager(this->drawingManager()), *this->caps());
2296 }
2297 
addDrawOp(const GrClip & clip,std::unique_ptr<GrDrawOp> op,const std::function<WillAddOpFn> & willAddFn)2298 void GrRenderTargetContext::addDrawOp(const GrClip& clip, std::unique_ptr<GrDrawOp> op,
2299                                       const std::function<WillAddOpFn>& willAddFn) {
2300     ASSERT_SINGLE_OWNER
2301     if (fContext->priv().abandoned()) {
2302         fContext->priv().opMemoryPool()->release(std::move(op));
2303         return;
2304     }
2305     SkDEBUGCODE(this->validate();)
2306     SkDEBUGCODE(op->fAddDrawOpCalled = true;)
2307     GR_CREATE_TRACE_MARKER_CONTEXT("GrRenderTargetContext", "addDrawOp", fContext);
2308 
2309     // Setup clip
2310     SkRect bounds;
2311     op_bounds(&bounds, op.get());
2312     GrAppliedClip appliedClip;
2313     GrDrawOp::FixedFunctionFlags fixedFunctionFlags = op->fixedFunctionFlags();
2314     bool usesHWAA = fixedFunctionFlags & GrDrawOp::FixedFunctionFlags::kUsesHWAA;
2315     bool usesStencil = fixedFunctionFlags & GrDrawOp::FixedFunctionFlags::kUsesStencil;
2316 
2317     if (usesStencil) {
2318         this->setNeedsStencil(usesHWAA);
2319     }
2320 
2321     if (!clip.apply(fContext, this, usesHWAA, usesStencil, &appliedClip, &bounds)) {
2322         fContext->priv().opMemoryPool()->release(std::move(op));
2323         return;
2324     }
2325 
2326     SkASSERT((!usesStencil && !appliedClip.hasStencilClip()) || (fNumStencilSamples > 0));
2327 
2328     GrClampType clampType = GrColorTypeClampType(this->colorSpaceInfo().colorType());
2329     // MIXED SAMPLES TODO: If we start using mixed samples for clips we will need to check the clip
2330     // here as well.
2331     bool hasMixedSampledCoverage = (usesHWAA && this->numSamples() <= 1);
2332 #ifdef SK_DEBUG
2333     if (hasMixedSampledCoverage) {
2334         SkASSERT(usesStencil);
2335         SkASSERT(fRenderTargetProxy->canUseMixedSamples(*this->caps()));
2336     }
2337 #endif
2338     GrProcessorSet::Analysis analysis = op->finalize(
2339             *this->caps(), &appliedClip, hasMixedSampledCoverage, clampType);
2340 
2341     GrXferProcessor::DstProxy dstProxy;
2342     if (analysis.requiresDstTexture()) {
2343         if (!this->setupDstProxy(this->asRenderTargetProxy(), clip, *op, &dstProxy)) {
2344             fContext->priv().opMemoryPool()->release(std::move(op));
2345             return;
2346         }
2347     }
2348 
2349     op->setClippedBounds(bounds);
2350     auto opList = this->getRTOpList();
2351     if (willAddFn) {
2352         willAddFn(op.get(), opList->uniqueID());
2353     }
2354     auto direct = fContext->priv().asDirectContext();
2355     if (direct && op) {
2356         op->setGrOpTag(direct->getCurrentGrResourceTag());
2357     }
2358     opList->addDrawOp(std::move(op), analysis, std::move(appliedClip), dstProxy,
2359                       GrTextureResolveManager(this->drawingManager()), *this->caps());
2360 }
2361 
setupDstProxy(GrRenderTargetProxy * rtProxy,const GrClip & clip,const GrOp & op,GrXferProcessor::DstProxy * dstProxy)2362 bool GrRenderTargetContext::setupDstProxy(GrRenderTargetProxy* rtProxy, const GrClip& clip,
2363                                           const GrOp& op, GrXferProcessor::DstProxy* dstProxy) {
2364     // If we are wrapping a vulkan secondary command buffer, we can't make a dst copy because we
2365     // don't actually have a VkImage to make a copy of. Additionally we don't have the power to
2366     // start and stop the render pass in order to make the copy.
2367     if (rtProxy->wrapsVkSecondaryCB()) {
2368         return false;
2369     }
2370 
2371     if (this->caps()->textureBarrierSupport()) {
2372         if (GrTextureProxy* texProxy = rtProxy->asTextureProxy()) {
2373             // The render target is a texture, so we can read from it directly in the shader. The XP
2374             // will be responsible to detect this situation and request a texture barrier.
2375             dstProxy->setProxy(sk_ref_sp(texProxy));
2376             dstProxy->setOffset(0, 0);
2377             return true;
2378         }
2379     }
2380 
2381     SkIRect copyRect = SkIRect::MakeWH(rtProxy->width(), rtProxy->height());
2382 
2383     SkIRect clippedRect;
2384     clip.getConservativeBounds(rtProxy->width(), rtProxy->height(), &clippedRect);
2385     SkRect opBounds = op.bounds();
2386     // If the op has aa bloating or is a infinitely thin geometry (hairline) outset the bounds by
2387     // 0.5 pixels.
2388     if (op.hasAABloat() || op.hasZeroArea()) {
2389         opBounds.outset(0.5f, 0.5f);
2390         // An antialiased/hairline draw can sometimes bleed outside of the clips bounds. For
2391         // performance we may ignore the clip when the draw is entirely inside the clip is float
2392         // space but will hit pixels just outside the clip when actually rasterizing.
2393         clippedRect.outset(1, 1);
2394         clippedRect.intersect(SkIRect::MakeWH(rtProxy->width(), rtProxy->height()));
2395     }
2396     SkIRect opIBounds;
2397     opBounds.roundOut(&opIBounds);
2398     if (!clippedRect.intersect(opIBounds)) {
2399 #ifdef SK_DEBUG
2400         GrCapsDebugf(this->caps(), "setupDstTexture: Missed an early reject bailing on draw.");
2401 #endif
2402         return false;
2403     }
2404 
2405     // MSAA consideration: When there is support for reading MSAA samples in the shader we could
2406     // have per-sample dst values by making the copy multisampled.
2407     GrCaps::DstCopyRestrictions restrictions = this->caps()->getDstCopyRestrictions(
2408             rtProxy, this->colorSpaceInfo().colorType());
2409 
2410     if (!restrictions.fMustCopyWholeSrc) {
2411         copyRect = clippedRect;
2412     }
2413 
2414     SkIPoint dstOffset;
2415     SkBackingFit fit;
2416     if (restrictions.fRectsMustMatch == GrSurfaceProxy::RectsMustMatch::kYes) {
2417         dstOffset = {0, 0};
2418         fit = SkBackingFit::kExact;
2419     } else {
2420         dstOffset = {copyRect.fLeft, copyRect.fTop};
2421         fit = SkBackingFit::kApprox;
2422     }
2423     sk_sp<GrTextureProxy> newProxy =
2424             GrSurfaceProxy::Copy(fContext, rtProxy, GrMipMapped::kNo, copyRect, fit,
2425                                  SkBudgeted::kYes, restrictions.fRectsMustMatch);
2426     SkASSERT(newProxy);
2427 
2428     dstProxy->setProxy(std::move(newProxy));
2429     dstProxy->setOffset(dstOffset);
2430     return true;
2431 }
2432 
blitTexture(GrTextureProxy * src,const SkIRect & srcRect,const SkIPoint & dstPoint)2433 bool GrRenderTargetContext::blitTexture(GrTextureProxy* src, const SkIRect& srcRect,
2434                                         const SkIPoint& dstPoint) {
2435     SkIRect clippedSrcRect;
2436     SkIPoint clippedDstPoint;
2437     if (!GrClipSrcRectAndDstPoint(this->asSurfaceProxy()->isize(), src->isize(), srcRect, dstPoint,
2438                                   &clippedSrcRect, &clippedDstPoint)) {
2439         return false;
2440     }
2441 
2442     GrPaint paint;
2443     paint.setPorterDuffXPFactory(SkBlendMode::kSrc);
2444     auto fp = GrSimpleTextureEffect::Make(sk_ref_sp(src->asTextureProxy()),
2445                                           SkMatrix::I());
2446     if (!fp) {
2447         return false;
2448     }
2449     paint.addColorFragmentProcessor(std::move(fp));
2450 
2451     this->fillRectToRect(
2452             GrNoClip(), std::move(paint), GrAA::kNo, SkMatrix::I(),
2453             SkRect::MakeXYWH(clippedDstPoint.fX, clippedDstPoint.fY, clippedSrcRect.width(),
2454                              clippedSrcRect.height()),
2455             SkRect::Make(clippedSrcRect));
2456     return true;
2457 }
2458 
2459