• 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 "src/gpu/v1/SurfaceDrawContext_v1.h"
9 
10 #include "include/core/SkDrawable.h"
11 #include "include/core/SkVertices.h"
12 #include "include/gpu/GrBackendSemaphore.h"
13 #include "include/gpu/GrDirectContext.h"
14 #include "include/gpu/GrRecordingContext.h"
15 #include "include/private/GrImageContext.h"
16 #include "include/private/SkShadowFlags.h"
17 #include "include/private/SkVx.h"
18 #include "include/utils/SkShadowUtils.h"
19 #include "src/core/SkAutoPixmapStorage.h"
20 #include "src/core/SkConvertPixels.h"
21 #include "src/core/SkDrawProcs.h"
22 #include "src/core/SkDrawShadowInfo.h"
23 #include "src/core/SkGlyphRunPainter.h"
24 #include "src/core/SkLatticeIter.h"
25 #include "src/core/SkMatrixPriv.h"
26 #include "src/core/SkMatrixProvider.h"
27 #include "src/core/SkRRectPriv.h"
28 #include "src/gpu/GrAppliedClip.h"
29 #include "src/gpu/GrAttachment.h"
30 #include "src/gpu/GrCaps.h"
31 #include "src/gpu/GrClip.h"
32 #include "src/gpu/GrColor.h"
33 #include "src/gpu/GrDataUtils.h"
34 #include "src/gpu/GrDirectContextPriv.h"
35 #include "src/gpu/GrDrawingManager.h"
36 #include "src/gpu/GrGpuResourcePriv.h"
37 #include "src/gpu/GrImageContextPriv.h"
38 #include "src/gpu/GrImageInfo.h"
39 #include "src/gpu/GrMemoryPool.h"
40 #include "src/gpu/GrProxyProvider.h"
41 #include "src/gpu/GrRenderTarget.h"
42 #include "src/gpu/GrResourceProvider.h"
43 #include "src/gpu/GrSemaphore.h"
44 #include "src/gpu/GrStencilSettings.h"
45 #include "src/gpu/GrStyle.h"
46 #include "src/gpu/GrTracing.h"
47 #include "src/gpu/SkGr.h"
48 #include "src/gpu/effects/GrBicubicEffect.h"
49 #include "src/gpu/effects/GrBlendFragmentProcessor.h"
50 #include "src/gpu/effects/GrDisableColorXP.h"
51 #include "src/gpu/effects/GrRRectEffect.h"
52 #include "src/gpu/effects/GrTextureEffect.h"
53 #include "src/gpu/geometry/GrQuad.h"
54 #include "src/gpu/geometry/GrQuadUtils.h"
55 #include "src/gpu/geometry/GrStyledShape.h"
56 #include "src/gpu/ops/ClearOp.h"
57 #include "src/gpu/ops/DrawAtlasOp.h"
58 #include "src/gpu/ops/DrawVerticesOp.h"
59 #include "src/gpu/ops/DrawableOp.h"
60 #include "src/gpu/ops/FillRRectOp.h"
61 #include "src/gpu/ops/FillRectOp.h"
62 #include "src/gpu/ops/GrDrawOp.h"
63 #include "src/gpu/ops/GrOp.h"
64 #include "src/gpu/ops/GrOvalOpFactory.h"
65 #include "src/gpu/ops/LatticeOp.h"
66 #include "src/gpu/ops/RegionOp.h"
67 #include "src/gpu/ops/ShadowRRectOp.h"
68 #include "src/gpu/ops/StrokeRectOp.h"
69 #include "src/gpu/ops/TextureOp.h"
70 #include "src/gpu/text/GrSDFTControl.h"
71 #include "src/gpu/text/GrTextBlobCache.h"
72 #include "src/gpu/v1/PathRenderer.h"
73 
74 #define ASSERT_OWNED_RESOURCE(R) SkASSERT(!(R) || (R)->getContext() == this->drawingManager()->getContext())
75 #define ASSERT_SINGLE_OWNER        GR_ASSERT_SINGLE_OWNER(this->singleOwner())
76 #define RETURN_IF_ABANDONED        if (fContext->abandoned()) { return; }
77 #define RETURN_FALSE_IF_ABANDONED  if (fContext->abandoned()) { return false; }
78 
79 //////////////////////////////////////////////////////////////////////////////
80 
81 namespace {
82 
op_bounds(SkRect * bounds,const GrOp * op)83 void op_bounds(SkRect* bounds, const GrOp* op) {
84     *bounds = op->bounds();
85     if (op->hasZeroArea()) {
86         if (op->hasAABloat()) {
87             bounds->outset(0.5f, 0.5f);
88         } else {
89             // We don't know which way the particular GPU will snap lines or points at integer
90             // coords. So we ensure that the bounds is large enough for either snap.
91             SkRect before = *bounds;
92             bounds->roundOut(bounds);
93             if (bounds->fLeft == before.fLeft) {
94                 bounds->fLeft -= 1;
95             }
96             if (bounds->fTop == before.fTop) {
97                 bounds->fTop -= 1;
98             }
99             if (bounds->fRight == before.fRight) {
100                 bounds->fRight += 1;
101             }
102             if (bounds->fBottom == before.fBottom) {
103                 bounds->fBottom += 1;
104             }
105         }
106     }
107 }
108 
109 } // anonymous namespace
110 
111 namespace skgpu::v1 {
112 
113 using DoSimplify = GrStyledShape::DoSimplify;
114 
115 class AutoCheckFlush {
116 public:
AutoCheckFlush(GrDrawingManager * drawingManager)117     AutoCheckFlush(GrDrawingManager* drawingManager) : fDrawingManager(drawingManager) {
118         SkASSERT(fDrawingManager);
119     }
~AutoCheckFlush()120     ~AutoCheckFlush() { fDrawingManager->flushIfNecessary(); }
121 
122 private:
123     GrDrawingManager* fDrawingManager;
124 };
125 
Make(GrRecordingContext * rContext,GrColorType colorType,sk_sp<GrSurfaceProxy> proxy,sk_sp<SkColorSpace> colorSpace,GrSurfaceOrigin origin,const SkSurfaceProps & surfaceProps,bool flushTimeOpsTask)126 std::unique_ptr<SurfaceDrawContext> SurfaceDrawContext::Make(GrRecordingContext* rContext,
127                                                              GrColorType colorType,
128                                                              sk_sp<GrSurfaceProxy> proxy,
129                                                              sk_sp<SkColorSpace> colorSpace,
130                                                              GrSurfaceOrigin origin,
131                                                              const SkSurfaceProps& surfaceProps,
132                                                              bool flushTimeOpsTask) {
133     if (!rContext || !proxy || colorType == GrColorType::kUnknown) {
134         return nullptr;
135     }
136 
137     const GrBackendFormat& format = proxy->backendFormat();
138     GrSwizzle readSwizzle = rContext->priv().caps()->getReadSwizzle(format, colorType);
139     GrSwizzle writeSwizzle = rContext->priv().caps()->getWriteSwizzle(format, colorType);
140 
141     GrSurfaceProxyView readView (          proxy,  origin, readSwizzle);
142     GrSurfaceProxyView writeView(std::move(proxy), origin, writeSwizzle);
143 
144     return std::make_unique<SurfaceDrawContext>(rContext,
145                                                 std::move(readView),
146                                                 std::move(writeView),
147                                                 colorType,
148                                                 std::move(colorSpace),
149                                                 surfaceProps,
150                                                 flushTimeOpsTask);
151 }
152 
Make(GrRecordingContext * rContext,sk_sp<SkColorSpace> colorSpace,SkBackingFit fit,SkISize dimensions,const GrBackendFormat & format,int sampleCnt,GrMipmapped mipMapped,GrProtected isProtected,GrSwizzle readSwizzle,GrSwizzle writeSwizzle,GrSurfaceOrigin origin,SkBudgeted budgeted,const SkSurfaceProps & surfaceProps)153 std::unique_ptr<SurfaceDrawContext> SurfaceDrawContext::Make(
154         GrRecordingContext* rContext,
155         sk_sp<SkColorSpace> colorSpace,
156         SkBackingFit fit,
157         SkISize dimensions,
158         const GrBackendFormat& format,
159         int sampleCnt,
160         GrMipmapped mipMapped,
161         GrProtected isProtected,
162         GrSwizzle readSwizzle,
163         GrSwizzle writeSwizzle,
164         GrSurfaceOrigin origin,
165         SkBudgeted budgeted,
166         const SkSurfaceProps& surfaceProps) {
167     // It is probably not necessary to check if the context is abandoned here since uses of the
168     // SurfaceDrawContext which need the context will mostly likely fail later on without an
169     // issue. However having this hear adds some reassurance in case there is a path doesn't handle
170     // an abandoned context correctly. It also lets us early out of some extra work.
171     if (rContext->abandoned()) {
172         return nullptr;
173     }
174 
175     sk_sp<GrTextureProxy> proxy = rContext->priv().proxyProvider()->createProxy(
176             format,
177             dimensions,
178             GrRenderable::kYes,
179             sampleCnt,
180             mipMapped,
181             fit,
182             budgeted,
183             isProtected);
184     if (!proxy) {
185         return nullptr;
186     }
187 
188     GrSurfaceProxyView readView (           proxy, origin,  readSwizzle);
189     GrSurfaceProxyView writeView(std::move(proxy), origin, writeSwizzle);
190 
191     auto sdc = std::make_unique<SurfaceDrawContext>(rContext,
192                                                     std::move(readView),
193                                                     std::move(writeView),
194                                                     GrColorType::kUnknown,
195                                                     std::move(colorSpace),
196                                                     surfaceProps);
197     sdc->discard();
198     return sdc;
199 }
200 
Make(GrRecordingContext * rContext,GrColorType colorType,sk_sp<SkColorSpace> colorSpace,SkBackingFit fit,SkISize dimensions,const SkSurfaceProps & surfaceProps,int sampleCnt,GrMipmapped mipMapped,GrProtected isProtected,GrSurfaceOrigin origin,SkBudgeted budgeted)201 std::unique_ptr<SurfaceDrawContext> SurfaceDrawContext::Make(
202         GrRecordingContext* rContext,
203         GrColorType colorType,
204         sk_sp<SkColorSpace> colorSpace,
205         SkBackingFit fit,
206         SkISize dimensions,
207         const SkSurfaceProps& surfaceProps,
208         int sampleCnt,
209         GrMipmapped mipMapped,
210         GrProtected isProtected,
211         GrSurfaceOrigin origin,
212         SkBudgeted budgeted) {
213     if (!rContext) {
214         return nullptr;
215     }
216 
217     auto format = rContext->priv().caps()->getDefaultBackendFormat(colorType, GrRenderable::kYes);
218     if (!format.isValid()) {
219         return nullptr;
220     }
221     sk_sp<GrTextureProxy> proxy = rContext->priv().proxyProvider()->createProxy(format,
222                                                                                 dimensions,
223                                                                                 GrRenderable::kYes,
224                                                                                 sampleCnt,
225                                                                                 mipMapped,
226                                                                                 fit,
227                                                                                 budgeted,
228                                                                                 isProtected);
229     if (!proxy) {
230         return nullptr;
231     }
232 
233     return SurfaceDrawContext::Make(rContext,
234                                     colorType,
235                                     std::move(proxy),
236                                     std::move(colorSpace),
237                                     origin,
238                                     surfaceProps);
239 }
240 
MakeWithFallback(GrRecordingContext * rContext,GrColorType colorType,sk_sp<SkColorSpace> colorSpace,SkBackingFit fit,SkISize dimensions,const SkSurfaceProps & surfaceProps,int sampleCnt,GrMipmapped mipMapped,GrProtected isProtected,GrSurfaceOrigin origin,SkBudgeted budgeted)241 std::unique_ptr<SurfaceDrawContext> SurfaceDrawContext::MakeWithFallback(
242         GrRecordingContext* rContext,
243         GrColorType colorType,
244         sk_sp<SkColorSpace> colorSpace,
245         SkBackingFit fit,
246         SkISize dimensions,
247         const SkSurfaceProps& surfaceProps,
248         int sampleCnt,
249         GrMipmapped mipMapped,
250         GrProtected isProtected,
251         GrSurfaceOrigin origin,
252         SkBudgeted budgeted) {
253     const GrCaps* caps = rContext->priv().caps();
254     auto [ct, _] = caps->getFallbackColorTypeAndFormat(colorType, sampleCnt);
255     if (ct == GrColorType::kUnknown) {
256         return nullptr;
257     }
258     return SurfaceDrawContext::Make(rContext, ct, colorSpace, fit, dimensions, surfaceProps,
259                                     sampleCnt, mipMapped, isProtected, origin, budgeted);
260 }
261 
MakeFromBackendTexture(GrRecordingContext * rContext,GrColorType colorType,sk_sp<SkColorSpace> colorSpace,const GrBackendTexture & tex,int sampleCnt,GrSurfaceOrigin origin,const SkSurfaceProps & surfaceProps,sk_sp<GrRefCntedCallback> releaseHelper)262 std::unique_ptr<SurfaceDrawContext> SurfaceDrawContext::MakeFromBackendTexture(
263         GrRecordingContext* rContext,
264         GrColorType colorType,
265         sk_sp<SkColorSpace> colorSpace,
266         const GrBackendTexture& tex,
267         int sampleCnt,
268         GrSurfaceOrigin origin,
269         const SkSurfaceProps& surfaceProps,
270         sk_sp<GrRefCntedCallback> releaseHelper) {
271     SkASSERT(sampleCnt > 0);
272     sk_sp<GrTextureProxy> proxy(rContext->priv().proxyProvider()->wrapRenderableBackendTexture(
273             tex, sampleCnt, kBorrow_GrWrapOwnership, GrWrapCacheable::kNo,
274             std::move(releaseHelper)));
275     if (!proxy) {
276         return nullptr;
277     }
278 
279     return SurfaceDrawContext::Make(rContext, colorType, std::move(proxy), std::move(colorSpace),
280                                     origin, surfaceProps);
281 }
282 
283 // In MDB mode the reffing of the 'getLastOpsTask' call's result allows in-progress
284 // OpsTask to be picked up and added to by SurfaceDrawContexts lower in the call
285 // stack. When this occurs with a closed OpsTask, a new one will be allocated
286 // when the surfaceDrawContext attempts to use it (via getOpsTask).
SurfaceDrawContext(GrRecordingContext * rContext,GrSurfaceProxyView readView,GrSurfaceProxyView writeView,GrColorType colorType,sk_sp<SkColorSpace> colorSpace,const SkSurfaceProps & surfaceProps,bool flushTimeOpsTask)287 SurfaceDrawContext::SurfaceDrawContext(GrRecordingContext* rContext,
288                                        GrSurfaceProxyView readView,
289                                        GrSurfaceProxyView writeView,
290                                        GrColorType colorType,
291                                        sk_sp<SkColorSpace> colorSpace,
292                                        const SkSurfaceProps& surfaceProps,
293                                        bool flushTimeOpsTask)
294         : SurfaceFillContext(rContext,
295                              std::move(readView),
296                              std::move(writeView),
297                              {colorType, kPremul_SkAlphaType, std::move(colorSpace)},
298                              flushTimeOpsTask)
299         , fSurfaceProps(surfaceProps)
300         , fCanUseDynamicMSAA(
301                 (fSurfaceProps.flags() & SkSurfaceProps::kDynamicMSAA_Flag) &&
302                 rContext->priv().caps()->supportsDynamicMSAA(this->asRenderTargetProxy()))
303         , fGlyphPainter(*this) {
304     SkDEBUGCODE(this->validate();)
305 }
306 
~SurfaceDrawContext()307 SurfaceDrawContext::~SurfaceDrawContext() {
308     ASSERT_SINGLE_OWNER
309 }
310 
willReplaceOpsTask(OpsTask * prevTask,OpsTask * nextTask)311 void SurfaceDrawContext::willReplaceOpsTask(OpsTask* prevTask, OpsTask* nextTask) {
312     if (prevTask && fNeedsStencil) {
313         // Store the stencil values in memory upon completion of fOpsTask.
314         prevTask->setMustPreserveStencil();
315         // Reload the stencil buffer content at the beginning of newOpsTask.
316         // FIXME: Could the topo sort insert a task between these two that modifies the stencil
317         // values?
318         nextTask->setInitialStencilContent(OpsTask::StencilContent::kPreserved);
319     }
320 #if GR_GPU_STATS && GR_TEST_UTILS
321     if (fCanUseDynamicMSAA) {
322         fContext->priv().dmsaaStats().fNumRenderPasses++;
323     }
324 #endif
325 }
326 
drawGlyphRunListNoCache(const GrClip * clip,const SkMatrixProvider & viewMatrix,const SkGlyphRunList & glyphRunList,const SkPaint & paint)327 void SurfaceDrawContext::drawGlyphRunListNoCache(const GrClip* clip,
328                                                  const SkMatrixProvider& viewMatrix,
329                                                  const SkGlyphRunList& glyphRunList,
330                                                  const SkPaint& paint) {
331     GrSDFTControl control =
332             fContext->priv().getSDFTControl(fSurfaceProps.isUseDeviceIndependentFonts());
333     const SkPoint drawOrigin = glyphRunList.origin();
334     SkMatrix drawMatrix = viewMatrix.localToDevice();
335     drawMatrix.preTranslate(drawOrigin.x(), drawOrigin.y());
336     GrSubRunAllocator* const alloc = this->subRunAlloc();
337 
338     GrSubRunNoCachePainter painter{this, alloc, clip, viewMatrix, glyphRunList, paint};
339     for (auto& glyphRun : glyphRunList) {
340         // Make and add the text ops.
341         fGlyphPainter.processGlyphRun(glyphRun,
342                                       drawMatrix,
343                                       paint,
344                                       control,
345                                       &painter);
346     }
347 }
348 
drawGlyphRunListWithCache(const GrClip * clip,const SkMatrixProvider & viewMatrix,const SkGlyphRunList & glyphRunList,const SkPaint & paint)349 void SurfaceDrawContext::drawGlyphRunListWithCache(const GrClip* clip,
350                                                    const SkMatrixProvider& viewMatrix,
351                                                    const SkGlyphRunList& glyphRunList,
352                                                    const SkPaint& paint) {
353     SkMatrix drawMatrix(viewMatrix.localToDevice());
354     drawMatrix.preTranslate(glyphRunList.origin().x(), glyphRunList.origin().y());
355 
356     GrSDFTControl control =
357             this->recordingContext()->priv().getSDFTControl(
358                     this->surfaceProps().isUseDeviceIndependentFonts());
359 
360     auto [canCache, key] = GrTextBlob::Key::Make(glyphRunList,
361                                                  paint,
362                                                  fSurfaceProps,
363                                                  this->colorInfo(),
364                                                  drawMatrix,
365                                                  control);
366 
367     sk_sp<GrTextBlob> blob;
368     GrTextBlobCache* textBlobCache = fContext->priv().getTextBlobCache();
369     if (canCache) {
370         blob = textBlobCache->find(key);
371     }
372 
373     if (blob == nullptr || !blob->canReuse(paint, drawMatrix)) {
374         if (blob != nullptr) {
375             // We have to remake the blob because changes may invalidate our masks.
376             // TODO we could probably get away with reuse most of the time if the pointer is unique,
377             //      but we'd have to clear the SubRun information
378             textBlobCache->remove(blob.get());
379         }
380 
381         blob = GrTextBlob::Make(glyphRunList, paint, drawMatrix, control, &fGlyphPainter);
382 
383         if (canCache) {
384             blob->addKey(key);
385             // The blob may already have been created on a different thread. Use the first one
386             // that was there.
387             blob = textBlobCache->addOrReturnExisting(glyphRunList, blob);
388         }
389     }
390 
391     for (const GrSubRun& subRun : blob->subRunList()) {
392         subRun.draw(clip, viewMatrix, glyphRunList, paint, this);
393     }
394 }
395 
396 // choose to use the GrTextBlob cache or not.
397 bool gGrDrawTextNoCache = false;
drawGlyphRunList(const GrClip * clip,const SkMatrixProvider & viewMatrix,const SkGlyphRunList & glyphRunList,const SkPaint & paint)398 void SurfaceDrawContext::drawGlyphRunList(const GrClip* clip,
399                                           const SkMatrixProvider& viewMatrix,
400                                           const SkGlyphRunList& glyphRunList,
401                                           const SkPaint& paint) {
402     ASSERT_SINGLE_OWNER
403     RETURN_IF_ABANDONED
404     SkDEBUGCODE(this->validate();)
405     GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "drawGlyphRunList", fContext);
406 
407     // Drawing text can cause us to do inline uploads. This is not supported for wrapped vulkan
408     // secondary command buffers because it would require stopping and starting a render pass which
409     // we don't have access to.
410     if (this->wrapsVkSecondaryCB()) {
411         return;
412     }
413 
414     if (gGrDrawTextNoCache || glyphRunList.blob() == nullptr) {
415         // If the glyphRunList does not have an associated text blob, then it was created by one of
416         // the direct draw APIs (drawGlyphs, etc.). There is no need to create a GrTextBlob just
417         // build the sub run directly and place it in the op.
418         this->drawGlyphRunListNoCache(clip, viewMatrix, glyphRunList, paint);
419     } else {
420         this->drawGlyphRunListWithCache(clip, viewMatrix, glyphRunList, paint);
421     }
422 }
423 
drawPaint(const GrClip * clip,GrPaint && paint,const SkMatrix & viewMatrix)424 void SurfaceDrawContext::drawPaint(const GrClip* clip,
425                                    GrPaint&& paint,
426                                    const SkMatrix& viewMatrix) {
427     // Start with the render target, since that is the maximum content we could possibly fill.
428     // drawFilledQuad() will automatically restrict it to clip bounds for us if possible.
429     if (!paint.numTotalFragmentProcessors()) {
430         // The paint is trivial so we won't need to use local coordinates, so skip calculating the
431         // inverse view matrix.
432         SkRect r = this->asSurfaceProxy()->getBoundsRect();
433         this->fillRectToRect(clip, std::move(paint), GrAA::kNo, SkMatrix::I(), r, r);
434     } else {
435         // Use the inverse view matrix to arrive at appropriate local coordinates for the paint.
436         SkMatrix localMatrix;
437         if (!viewMatrix.invert(&localMatrix)) {
438             return;
439         }
440         SkIRect bounds = SkIRect::MakeSize(this->asSurfaceProxy()->dimensions());
441         this->fillPixelsWithLocalMatrix(clip, std::move(paint), bounds, localMatrix);
442     }
443 }
444 
445 enum class SurfaceDrawContext::QuadOptimization {
446     // The rect to draw doesn't intersect clip or render target, so no draw op should be added
447     kDiscarded,
448     // The rect to draw was converted to some other op and appended to the oplist, so no additional
449     // op is necessary. Currently this can convert it to a clear op or a rrect op. Only valid if
450     // a constColor is provided.
451     kSubmitted,
452     // The clip was folded into the device quad, with updated edge flags and local coords, and
453     // caller is responsible for adding an appropriate op.
454     kClipApplied,
455     // No change to clip, but quad updated to better fit clip/render target, and caller is
456     // responsible for adding an appropriate op.
457     kCropped
458 };
459 
attemptQuadOptimization(const GrClip * clip,const GrUserStencilSettings * stencilSettings,GrAA * aa,DrawQuad * quad,GrPaint * paint)460 SurfaceDrawContext::QuadOptimization SurfaceDrawContext::attemptQuadOptimization(
461         const GrClip* clip, const GrUserStencilSettings* stencilSettings, GrAA* aa, DrawQuad* quad,
462         GrPaint* paint) {
463     // Optimization requirements:
464     // 1. kDiscard applies when clip bounds and quad bounds do not intersect
465     // 2a. kSubmitted applies when constColor and final geom is pixel aligned rect;
466     //       pixel aligned rect requires rect clip and (rect quad or quad covers clip) OR
467     // 2b. kSubmitted applies when constColor and rrect clip and quad covers clip
468     // 4. kClipApplied applies when rect clip and (rect quad or quad covers clip)
469     // 5. kCropped in all other scenarios (although a crop may be a no-op)
470     const SkPMColor4f* constColor = nullptr;
471     SkPMColor4f paintColor;
472     if (!stencilSettings && paint && !paint->hasCoverageFragmentProcessor() &&
473         paint->isConstantBlendedColor(&paintColor)) {
474         // Only consider clears/rrects when it's easy to guarantee 100% fill with single color
475         constColor = &paintColor;
476     }
477 
478     // Save the old AA flags since CropToRect will modify 'quad' and if kCropped is returned, it's
479     // better to just keep the old flags instead of introducing mixed edge flags.
480     GrQuadAAFlags oldFlags = quad->fEdgeFlags;
481 
482     // Use the logical size of the render target, which allows for "fullscreen" clears even if
483     // the render target has an approximate backing fit
484     SkRect rtRect = this->asSurfaceProxy()->getBoundsRect();
485 
486     // For historical reasons, we assume AA for exact bounds checking in IsOutsideClip.
487     // TODO(michaelludwig) - Hopefully that can be revisited when the clipping optimizations are
488     // refactored to work better with round rects and dmsaa.
489     SkRect drawBounds = quad->fDevice.bounds();
490     if (!quad->fDevice.isFinite() || drawBounds.isEmpty() ||
491         GrClip::IsOutsideClip(SkIRect::MakeSize(this->dimensions()), drawBounds, GrAA::kYes)) {
492         return QuadOptimization::kDiscarded;
493     } else if (GrQuadUtils::WillUseHairline(quad->fDevice, GrAAType::kCoverage, quad->fEdgeFlags)) {
494         // Don't try to apply the clip early if we know rendering will use hairline methods, as this
495         // has an effect on the op bounds not otherwise taken into account in this function.
496         return QuadOptimization::kCropped;
497     }
498 
499     auto conservativeCrop = [&]() {
500         static constexpr int kLargeDrawLimit = 15000;
501         // Crop the quad to the render target. This doesn't change the visual results of drawing but
502         // is meant to help numerical stability for excessively large draws.
503         if (drawBounds.width() > kLargeDrawLimit || drawBounds.height() > kLargeDrawLimit) {
504             GrQuadUtils::CropToRect(rtRect, *aa, quad, /* compute local */ !constColor);
505         }
506     };
507 
508     bool simpleColor = !stencilSettings && constColor;
509     GrClip::PreClipResult result = clip ? clip->preApply(drawBounds, *aa)
510                                         : GrClip::PreClipResult(GrClip::Effect::kUnclipped);
511     switch(result.fEffect) {
512         case GrClip::Effect::kClippedOut:
513             return QuadOptimization::kDiscarded;
514         case GrClip::Effect::kUnclipped:
515             if (!simpleColor) {
516                 conservativeCrop();
517                 return QuadOptimization::kClipApplied;
518             } else {
519                 // Update result to store the render target bounds in order and then fall
520                 // through to attempt the draw->native clear optimization
521                 result = GrClip::PreClipResult(SkRRect::MakeRect(rtRect), *aa);
522             }
523             break;
524         case GrClip::Effect::kClipped:
525             if (!result.fIsRRect || (stencilSettings && result.fAA != *aa) ||
526                 (!result.fRRect.isRect() && !simpleColor)) {
527                 // The clip and draw state are too complicated to try and reduce
528                 conservativeCrop();
529                 return QuadOptimization::kCropped;
530             } // Else fall through to attempt to combine the draw and clip geometry together
531             break;
532         default:
533             SkUNREACHABLE;
534     }
535 
536     // If we reached here, we know we're an axis-aligned clip that is either a rect or a round rect,
537     // so we can potentially combine it with the draw geometry so that no clipping is needed.
538     SkASSERT(result.fEffect == GrClip::Effect::kClipped && result.fIsRRect);
539     SkRect clippedBounds = result.fRRect.getBounds();
540     clippedBounds.intersect(rtRect);
541     if (!drawBounds.intersect(clippedBounds)) {
542         // Our fractional bounds aren't actually inside the clip. GrClip::preApply() can sometimes
543         // think in terms of rounded-out bounds. Discard the draw.
544         return QuadOptimization::kDiscarded;
545     }
546     // Guard against the clipped draw turning into a hairline draw after intersection
547     if (drawBounds.width() < 1.f || drawBounds.height() < 1.f) {
548         return QuadOptimization::kCropped;
549     }
550 
551     if (result.fRRect.isRect()) {
552         // No rounded corners, so we might be able to become a native clear or we might be able to
553         // modify geometry and edge flags to represent intersected shape of clip and draw.
554         if (GrQuadUtils::CropToRect(clippedBounds, result.fAA, quad,
555                                     /*compute local*/ !constColor)) {
556             if (simpleColor && quad->fDevice.quadType() == GrQuad::Type::kAxisAligned) {
557                 // Clear optimization is possible
558                 drawBounds = quad->fDevice.bounds();
559                 if (drawBounds.contains(rtRect)) {
560                     // Fullscreen clear
561                     this->clear(*constColor);
562                     return QuadOptimization::kSubmitted;
563                 } else if (GrClip::IsPixelAligned(drawBounds) &&
564                            drawBounds.width() > 256 && drawBounds.height() > 256) {
565                     // Scissor + clear (round shouldn't do anything since we are pixel aligned)
566                     SkIRect scissorRect;
567                     drawBounds.round(&scissorRect);
568                     this->clear(scissorRect, *constColor);
569                     return QuadOptimization::kSubmitted;
570                 }
571             }
572 
573             // else the draw and clip were combined so just update the AA to reflect combination
574             if (*aa == GrAA::kNo && result.fAA == GrAA::kYes &&
575                 quad->fEdgeFlags != GrQuadAAFlags::kNone) {
576                 // The clip was anti-aliased and now the draw needs to be upgraded to AA to
577                 // properly reflect the smooth edge of the clip.
578                 *aa = GrAA::kYes;
579             }
580             // We intentionally do not downgrade AA here because we don't know if we need to
581             // preserve MSAA (see GrQuadAAFlags docs). But later in the pipeline, the ops can
582             // use GrResolveAATypeForQuad() to turn off coverage AA when all flags are off.
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         }
587     } else {
588         // Rounded corners and constant filled color (limit ourselves to solid colors because
589         // there is no way to use custom local coordinates with drawRRect).
590         SkASSERT(simpleColor);
591         if (GrQuadUtils::CropToRect(clippedBounds, result.fAA, quad,
592                                     /* compute local */ false) &&
593             quad->fDevice.quadType() == GrQuad::Type::kAxisAligned &&
594             quad->fDevice.bounds().contains(clippedBounds)) {
595             // Since the cropped quad became a rectangle which covered the bounds of the rrect,
596             // we can draw the rrect directly and ignore the edge flags
597             this->drawRRect(nullptr, std::move(*paint), result.fAA, SkMatrix::I(), result.fRRect,
598                             GrStyle::SimpleFill());
599             return QuadOptimization::kSubmitted;
600         }
601     }
602 
603     // The quads have been updated to better fit the clip bounds, but can't get rid of
604     // the clip entirely
605     quad->fEdgeFlags = oldFlags;
606     return QuadOptimization::kCropped;
607 }
608 
drawFilledQuad(const GrClip * clip,GrPaint && paint,GrAA aa,DrawQuad * quad,const GrUserStencilSettings * ss)609 void SurfaceDrawContext::drawFilledQuad(const GrClip* clip,
610                                         GrPaint&& paint,
611                                         GrAA aa,
612                                         DrawQuad* quad,
613                                         const GrUserStencilSettings* ss) {
614     ASSERT_SINGLE_OWNER
615     RETURN_IF_ABANDONED
616     SkDEBUGCODE(this->validate();)
617     GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "drawFilledQuad", fContext);
618 
619     AutoCheckFlush acf(this->drawingManager());
620 
621     QuadOptimization opt = this->attemptQuadOptimization(clip, ss, &aa, quad, &paint);
622     if (opt >= QuadOptimization::kClipApplied) {
623         // These optimizations require caller to add an op themselves
624         const GrClip* finalClip = opt == QuadOptimization::kClipApplied ? nullptr : clip;
625         GrAAType aaType;
626         if (ss) {
627             aaType = (aa == GrAA::kYes) ? GrAAType::kMSAA : GrAAType::kNone;
628         } else if (fCanUseDynamicMSAA && aa == GrAA::kNo) {
629             // The SkGpuDevice ensures GrAA is always kYes when using dmsaa. If the caller calls
630             // into here with GrAA::kNo, trust that they know what they're doing and that the
631             // rendering will be equal with or without msaa.
632             aaType = GrAAType::kNone;
633         } else {
634             aaType = this->chooseAAType(aa);
635         }
636         this->addDrawOp(finalClip, FillRectOp::Make(fContext, std::move(paint), aaType,
637                                                     quad, ss));
638     }
639     // All other optimization levels were completely handled inside attempt(), so no extra op needed
640 }
641 
drawTexture(const GrClip * clip,GrSurfaceProxyView view,SkAlphaType srcAlphaType,GrSamplerState::Filter filter,GrSamplerState::MipmapMode mm,SkBlendMode blendMode,const SkPMColor4f & color,const SkRect & srcRect,const SkRect & dstRect,GrAA aa,GrQuadAAFlags edgeAA,SkCanvas::SrcRectConstraint constraint,const SkMatrix & viewMatrix,sk_sp<GrColorSpaceXform> colorSpaceXform)642 void SurfaceDrawContext::drawTexture(const GrClip* clip,
643                                      GrSurfaceProxyView view,
644                                      SkAlphaType srcAlphaType,
645                                      GrSamplerState::Filter filter,
646                                      GrSamplerState::MipmapMode mm,
647                                      SkBlendMode blendMode,
648                                      const SkPMColor4f& color,
649                                      const SkRect& srcRect,
650                                      const SkRect& dstRect,
651                                      GrAA aa,
652                                      GrQuadAAFlags edgeAA,
653                                      SkCanvas::SrcRectConstraint constraint,
654                                      const SkMatrix& viewMatrix,
655                                      sk_sp<GrColorSpaceXform> colorSpaceXform) {
656     // If we are using dmsaa then go through FillRRectOp (via fillRectToRect).
657     if ((this->alwaysAntialias() || this->caps()->reducedShaderMode()) && aa == GrAA::kYes) {
658         GrPaint paint;
659         paint.setColor4f(color);
660         std::unique_ptr<GrFragmentProcessor> fp;
661         if (constraint == SkCanvas::kStrict_SrcRectConstraint) {
662             fp = GrTextureEffect::MakeSubset(view, srcAlphaType, SkMatrix::I(),
663                                              GrSamplerState(filter, mm), srcRect,
664                                              *this->caps());
665         } else {
666             fp = GrTextureEffect::Make(view, srcAlphaType, SkMatrix::I(), filter, mm);
667         }
668         if (colorSpaceXform) {
669             fp = GrColorSpaceXformEffect::Make(std::move(fp), std::move(colorSpaceXform));
670         }
671         fp = GrBlendFragmentProcessor::Make(std::move(fp), nullptr, SkBlendMode::kModulate);
672         paint.setColorFragmentProcessor(std::move(fp));
673         if (blendMode != SkBlendMode::kSrcOver) {
674             paint.setXPFactory(SkBlendMode_AsXPFactory(blendMode));
675         }
676         this->fillRectToRect(clip, std::move(paint), GrAA::kYes, viewMatrix, dstRect, srcRect);
677         return;
678     }
679 
680     const SkRect* subset = constraint == SkCanvas::kStrict_SrcRectConstraint ?
681             &srcRect : nullptr;
682     DrawQuad quad{GrQuad::MakeFromRect(dstRect, viewMatrix), GrQuad(srcRect), edgeAA};
683 
684     this->drawTexturedQuad(clip, std::move(view), srcAlphaType, std::move(colorSpaceXform), filter,
685                            mm, color, blendMode, aa, &quad, subset);
686 }
687 
drawTexturedQuad(const GrClip * clip,GrSurfaceProxyView proxyView,SkAlphaType srcAlphaType,sk_sp<GrColorSpaceXform> textureXform,GrSamplerState::Filter filter,GrSamplerState::MipmapMode mm,const SkPMColor4f & color,SkBlendMode blendMode,GrAA aa,DrawQuad * quad,const SkRect * subset)688 void SurfaceDrawContext::drawTexturedQuad(const GrClip* clip,
689                                           GrSurfaceProxyView proxyView,
690                                           SkAlphaType srcAlphaType,
691                                           sk_sp<GrColorSpaceXform> textureXform,
692                                           GrSamplerState::Filter filter,
693                                           GrSamplerState::MipmapMode mm,
694                                           const SkPMColor4f& color,
695                                           SkBlendMode blendMode,
696                                           GrAA aa,
697                                           DrawQuad* quad,
698                                           const SkRect* subset) {
699     ASSERT_SINGLE_OWNER
700     RETURN_IF_ABANDONED
701     SkDEBUGCODE(this->validate();)
702     SkASSERT(proxyView.asTextureProxy());
703     GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "drawTexturedQuad", fContext);
704 
705     AutoCheckFlush acf(this->drawingManager());
706 
707     // Functionally this is very similar to drawFilledQuad except that there's no constColor to
708     // enable the kSubmitted optimizations, no stencil settings support, and its a TextureOp.
709     QuadOptimization opt = this->attemptQuadOptimization(clip, nullptr/*stencil*/, &aa, quad,
710                                                          nullptr/*paint*/);
711 
712     SkASSERT(opt != QuadOptimization::kSubmitted);
713     if (opt != QuadOptimization::kDiscarded) {
714         // And the texture op if not discarded
715         const GrClip* finalClip = opt == QuadOptimization::kClipApplied ? nullptr : clip;
716         GrAAType aaType = this->chooseAAType(aa);
717         auto clampType = GrColorTypeClampType(this->colorInfo().colorType());
718         auto saturate = clampType == GrClampType::kManual ? TextureOp::Saturate::kYes
719                                                           : TextureOp::Saturate::kNo;
720         // Use the provided subset, although hypothetically we could detect that the cropped local
721         // quad is sufficiently inside the subset and the constraint could be dropped.
722         this->addDrawOp(finalClip,
723                         TextureOp::Make(fContext, std::move(proxyView), srcAlphaType,
724                                         std::move(textureXform), filter, mm, color, saturate,
725                                         blendMode, aaType, quad, subset));
726     }
727 }
728 
drawRect(const GrClip * clip,GrPaint && paint,GrAA aa,const SkMatrix & viewMatrix,const SkRect & rect,const GrStyle * style)729 void SurfaceDrawContext::drawRect(const GrClip* clip,
730                                   GrPaint&& paint,
731                                   GrAA aa,
732                                   const SkMatrix& viewMatrix,
733                                   const SkRect& rect,
734                                   const GrStyle* style) {
735     if (!style) {
736         style = &GrStyle::SimpleFill();
737     }
738     ASSERT_SINGLE_OWNER
739     RETURN_IF_ABANDONED
740     SkDEBUGCODE(this->validate();)
741     GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "drawRect", fContext);
742 
743     // Path effects should've been devolved to a path in SkGpuDevice
744     SkASSERT(!style->pathEffect());
745 
746     AutoCheckFlush acf(this->drawingManager());
747 
748     const SkStrokeRec& stroke = style->strokeRec();
749     if (stroke.getStyle() == SkStrokeRec::kFill_Style) {
750         // Fills the rect, using rect as its own local coordinates
751         this->fillRectToRect(clip, std::move(paint), aa, viewMatrix, rect, rect);
752         return;
753     } else if ((stroke.getStyle() == SkStrokeRec::kStroke_Style ||
754                 stroke.getStyle() == SkStrokeRec::kHairline_Style) &&
755                rect.width()                                        &&
756                rect.height()                                       &&
757                !this->caps()->reducedShaderMode()) {
758         // Only use the StrokeRectOp for non-empty rectangles. Empty rectangles will be processed by
759         // GrStyledShape to handle stroke caps and dashing properly.
760         //
761         // http://skbug.com/12206 -- there is a double-blend issue with the bevel version of
762         // AAStrokeRectOp, and if we increase the AA bloat for MSAA it becomes more pronounced.
763         // Don't use the bevel version with DMSAA.
764         GrAAType aaType = (fCanUseDynamicMSAA &&
765                            stroke.getJoin() == SkPaint::kMiter_Join &&
766                            stroke.getMiter() >= SK_ScalarSqrt2) ? GrAAType::kCoverage
767                                                                 : this->chooseAAType(aa);
768         GrOp::Owner op = StrokeRectOp::Make(fContext, std::move(paint), aaType, viewMatrix,
769                                             rect, stroke);
770         // op may be null if the stroke is not supported or if using coverage aa and the view matrix
771         // does not preserve rectangles.
772         if (op) {
773             this->addDrawOp(clip, std::move(op));
774             return;
775         }
776     }
777     assert_alive(paint);
778     this->drawShapeUsingPathRenderer(clip, std::move(paint), aa, viewMatrix,
779                                      GrStyledShape(rect, *style, DoSimplify::kNo));
780 }
781 
fillRectToRect(const GrClip * clip,GrPaint && paint,GrAA aa,const SkMatrix & viewMatrix,const SkRect & rectToDraw,const SkRect & localRect)782 void SurfaceDrawContext::fillRectToRect(const GrClip* clip,
783                                         GrPaint&& paint,
784                                         GrAA aa,
785                                         const SkMatrix& viewMatrix,
786                                         const SkRect& rectToDraw,
787                                         const SkRect& localRect) {
788     DrawQuad quad{GrQuad::MakeFromRect(rectToDraw, viewMatrix), GrQuad(localRect),
789                   aa == GrAA::kYes ? GrQuadAAFlags::kAll : GrQuadAAFlags::kNone};
790 
791     // If we are using dmsaa then attempt to draw the rect with FillRRectOp.
792     if ((fContext->priv().caps()->reducedShaderMode() || this->alwaysAntialias()) &&
793         this->caps()->drawInstancedSupport()                                      &&
794         aa == GrAA::kYes) {  // If aa is kNo when using dmsaa, the rect is axis aligned. Don't use
795                              // FillRRectOp because it might require dual source blending.
796                              // http://skbug.com/11756
797         QuadOptimization opt = this->attemptQuadOptimization(clip, nullptr/*stencil*/, &aa, &quad,
798                                                              &paint);
799         if (opt < QuadOptimization::kClipApplied) {
800             // The optimization was completely handled inside attempt().
801             return;
802         }
803 
804         SkRect croppedRect, croppedLocal{};
805         const GrClip* optimizedClip = clip;
806         if (clip && viewMatrix.isScaleTranslate() && quad.fDevice.asRect(&croppedRect) &&
807             (!paint.usesLocalCoords() || quad.fLocal.asRect(&croppedLocal))) {
808             // The cropped quad is still a rect, and our view matrix preserves rects. Map it back
809             // to pre-matrix space.
810             SkMatrix inverse;
811             if (!viewMatrix.invert(&inverse)) {
812                 return;
813             }
814             SkASSERT(inverse.rectStaysRect());
815             inverse.mapRect(&croppedRect);
816             if (opt == QuadOptimization::kClipApplied) {
817                 optimizedClip = nullptr;
818             }
819         } else {
820             // Even if attemptQuadOptimization gave us an optimized quad, FillRRectOp needs a rect
821             // in pre-matrix space, so use the original rect. Also preserve the original clip.
822             croppedRect = rectToDraw;
823             croppedLocal = localRect;
824         }
825 
826         if (auto op = FillRRectOp::Make(fContext, this->arenaAlloc(), std::move(paint),
827                                         viewMatrix, SkRRect::MakeRect(croppedRect), croppedLocal,
828                                         GrAA::kYes)) {
829             this->addDrawOp(optimizedClip, std::move(op));
830             return;
831         }
832     }
833 
834     assert_alive(paint);
835     this->drawFilledQuad(clip, std::move(paint), aa, &quad);
836 }
837 
drawQuadSet(const GrClip * clip,GrPaint && paint,GrAA aa,const SkMatrix & viewMatrix,const GrQuadSetEntry quads[],int cnt)838 void SurfaceDrawContext::drawQuadSet(const GrClip* clip,
839                                      GrPaint&& paint,
840                                      GrAA aa,
841                                      const SkMatrix& viewMatrix,
842                                      const GrQuadSetEntry quads[],
843                                      int cnt) {
844     GrAAType aaType = this->chooseAAType(aa);
845 
846     FillRectOp::AddFillRectOps(this, clip, fContext, std::move(paint), aaType, viewMatrix,
847                                quads, cnt);
848 }
849 
maxWindowRectangles() const850 int SurfaceDrawContext::maxWindowRectangles() const {
851     return this->asRenderTargetProxy()->maxWindowRectangles(*this->caps());
852 }
853 
canDiscardPreviousOpsOnFullClear() const854 OpsTask::CanDiscardPreviousOps SurfaceDrawContext::canDiscardPreviousOpsOnFullClear() const {
855 #if GR_TEST_UTILS
856     if (fPreserveOpsOnFullClear_TestingOnly) {
857         return OpsTask::CanDiscardPreviousOps::kNo;
858     }
859 #endif
860     // Regardless of how the clear is implemented (native clear or a fullscreen quad), all prior ops
861     // would normally be overwritten. The one exception is if the render target context is marked as
862     // needing a stencil buffer then there may be a prior op that writes to the stencil buffer.
863     // Although the clear will ignore the stencil buffer, following draw ops may not so we can't get
864     // rid of all the preceding ops. Beware! If we ever add any ops that have a side effect beyond
865     // modifying the stencil buffer we will need a more elaborate tracking system (skbug.com/7002).
866     return OpsTask::CanDiscardPreviousOps(!fNeedsStencil);
867 }
868 
setNeedsStencil()869 void SurfaceDrawContext::setNeedsStencil() {
870     // Don't clear stencil until after we've set fNeedsStencil. This ensures we don't loop forever
871     // in the event that there are driver bugs and we need to clear as a draw.
872     bool hasInitializedStencil = fNeedsStencil;
873     fNeedsStencil = true;
874     if (!hasInitializedStencil) {
875         this->asRenderTargetProxy()->setNeedsStencil();
876         if (this->caps()->performStencilClearsAsDraws()) {
877             // There is a driver bug with clearing stencil. We must use an op to manually clear the
878             // stencil buffer before the op that required 'setNeedsStencil'.
879             this->internalStencilClear(nullptr, /* inside mask */ false);
880         } else {
881             this->getOpsTask()->setInitialStencilContent(
882                     OpsTask::StencilContent::kUserBitsCleared);
883         }
884     }
885 }
886 
internalStencilClear(const SkIRect * scissor,bool insideStencilMask)887 void SurfaceDrawContext::internalStencilClear(const SkIRect* scissor, bool insideStencilMask) {
888     this->setNeedsStencil();
889 
890     GrScissorState scissorState(this->asSurfaceProxy()->backingStoreDimensions());
891     if (scissor && !scissorState.set(*scissor)) {
892         // The requested clear region is off screen, so nothing to do.
893         return;
894     }
895 
896     bool clearWithDraw = this->caps()->performStencilClearsAsDraws() ||
897                          (scissorState.enabled() && this->caps()->performPartialClearsAsDraws());
898     if (clearWithDraw) {
899         const GrUserStencilSettings* ss = GrStencilSettings::SetClipBitSettings(insideStencilMask);
900 
901         // Configure the paint to have no impact on the color buffer
902         GrPaint paint;
903         paint.setXPFactory(GrDisableColorXPFactory::Get());
904         this->addDrawOp(nullptr,
905                         FillRectOp::MakeNonAARect(fContext, std::move(paint), SkMatrix::I(),
906                                                   SkRect::Make(scissorState.rect()), ss));
907     } else {
908         this->addOp(ClearOp::MakeStencilClip(fContext, scissorState, insideStencilMask));
909     }
910 }
911 
stencilPath(const GrHardClip * clip,GrAA doStencilMSAA,const SkMatrix & viewMatrix,const SkPath & path)912 bool SurfaceDrawContext::stencilPath(const GrHardClip* clip,
913                                      GrAA doStencilMSAA,
914                                      const SkMatrix& viewMatrix,
915                                      const SkPath& path) {
916     SkIRect clipBounds = clip ? clip->getConservativeBounds()
917                               : SkIRect::MakeSize(this->dimensions());
918     GrStyledShape shape(path, GrStyledShape::DoSimplify::kNo);
919 
920     PathRenderer::CanDrawPathArgs canDrawArgs;
921     canDrawArgs.fCaps = fContext->priv().caps();
922     canDrawArgs.fProxy = this->asRenderTargetProxy();
923     canDrawArgs.fClipConservativeBounds = &clipBounds;
924     canDrawArgs.fViewMatrix = &viewMatrix;
925     canDrawArgs.fShape = &shape;
926     canDrawArgs.fPaint = nullptr;
927     canDrawArgs.fSurfaceProps = &fSurfaceProps;
928     canDrawArgs.fAAType = (doStencilMSAA == GrAA::kYes) ? GrAAType::kMSAA : GrAAType::kNone;
929     canDrawArgs.fHasUserStencilSettings = false;
930     auto pr = this->drawingManager()->getPathRenderer(canDrawArgs,
931                                                       false,
932                                                       PathRendererChain::DrawType::kStencil);
933     if (!pr) {
934         SkDebugf("WARNING: No path renderer to stencil path.\n");
935         return false;
936     }
937 
938     PathRenderer::StencilPathArgs args;
939     args.fContext = fContext;
940     args.fSurfaceDrawContext = this;
941     args.fClip = clip;
942     args.fClipConservativeBounds = &clipBounds;
943     args.fViewMatrix = &viewMatrix;
944     args.fShape = &shape;
945     args.fDoStencilMSAA = doStencilMSAA;
946     pr->stencilPath(args);
947     return true;
948 }
949 
drawTextureSet(const GrClip * clip,GrTextureSetEntry set[],int cnt,int proxyRunCnt,GrSamplerState::Filter filter,GrSamplerState::MipmapMode mm,SkBlendMode mode,GrAA aa,SkCanvas::SrcRectConstraint constraint,const SkMatrix & viewMatrix,sk_sp<GrColorSpaceXform> texXform)950 void SurfaceDrawContext::drawTextureSet(const GrClip* clip,
951                                         GrTextureSetEntry set[],
952                                         int cnt,
953                                         int proxyRunCnt,
954                                         GrSamplerState::Filter filter,
955                                         GrSamplerState::MipmapMode mm,
956                                         SkBlendMode mode,
957                                         GrAA aa,
958                                         SkCanvas::SrcRectConstraint constraint,
959                                         const SkMatrix& viewMatrix,
960                                         sk_sp<GrColorSpaceXform> texXform) {
961     ASSERT_SINGLE_OWNER
962     RETURN_IF_ABANDONED
963     SkDEBUGCODE(this->validate();)
964     GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "drawTextureSet", fContext);
965 
966     // Create the minimum number of GrTextureOps needed to draw this set. Individual
967     // GrTextureOps can rebind the texture between draws thus avoiding GrPaint (re)creation.
968     AutoCheckFlush acf(this->drawingManager());
969     GrAAType aaType = this->chooseAAType(aa);
970     auto clampType = GrColorTypeClampType(this->colorInfo().colorType());
971     auto saturate = clampType == GrClampType::kManual ? TextureOp::Saturate::kYes
972                                                       : TextureOp::Saturate::kNo;
973     TextureOp::AddTextureSetOps(this, clip, fContext, set, cnt, proxyRunCnt, filter, mm, saturate,
974                                 mode, aaType, constraint, viewMatrix, std::move(texXform));
975 }
976 
drawVertices(const GrClip * clip,GrPaint && paint,const SkMatrixProvider & matrixProvider,sk_sp<SkVertices> vertices,GrPrimitiveType * overridePrimType)977 void SurfaceDrawContext::drawVertices(const GrClip* clip,
978                                       GrPaint&& paint,
979                                       const SkMatrixProvider& matrixProvider,
980                                       sk_sp<SkVertices> vertices,
981                                       GrPrimitiveType* overridePrimType) {
982     ASSERT_SINGLE_OWNER
983     RETURN_IF_ABANDONED
984     SkDEBUGCODE(this->validate();)
985     GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "drawVertices", fContext);
986 
987     AutoCheckFlush acf(this->drawingManager());
988 
989     SkASSERT(vertices);
990     GrAAType aaType = fCanUseDynamicMSAA ? GrAAType::kMSAA : this->chooseAAType(GrAA::kNo);
991     GrOp::Owner op = DrawVerticesOp::Make(fContext,
992                                           std::move(paint),
993                                           std::move(vertices),
994                                           matrixProvider,
995                                           aaType,
996                                           this->colorInfo().refColorSpaceXformFromSRGB(),
997                                           overridePrimType);
998     this->addDrawOp(clip, std::move(op));
999 }
1000 
1001 ///////////////////////////////////////////////////////////////////////////////
1002 
drawAtlas(const GrClip * clip,GrPaint && paint,const SkMatrix & viewMatrix,int spriteCount,const SkRSXform xform[],const SkRect texRect[],const SkColor colors[])1003 void SurfaceDrawContext::drawAtlas(const GrClip* clip,
1004                                    GrPaint&& paint,
1005                                    const SkMatrix& viewMatrix,
1006                                    int spriteCount,
1007                                    const SkRSXform xform[],
1008                                    const SkRect texRect[],
1009                                    const SkColor colors[]) {
1010     ASSERT_SINGLE_OWNER
1011     RETURN_IF_ABANDONED
1012     SkDEBUGCODE(this->validate();)
1013     GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "drawAtlas", fContext);
1014 
1015     AutoCheckFlush acf(this->drawingManager());
1016 
1017     GrAAType aaType = this->chooseAAType(GrAA::kNo);
1018     GrOp::Owner op = DrawAtlasOp::Make(fContext, std::move(paint), viewMatrix,
1019                                        aaType, spriteCount, xform, texRect, colors);
1020     this->addDrawOp(clip, std::move(op));
1021 }
1022 
1023 ///////////////////////////////////////////////////////////////////////////////
1024 
drawRRect(const GrClip * origClip,GrPaint && paint,GrAA aa,const SkMatrix & viewMatrix,const SkRRect & rrect,const GrStyle & style)1025 void SurfaceDrawContext::drawRRect(const GrClip* origClip,
1026                                    GrPaint&& paint,
1027                                    GrAA aa,
1028                                    const SkMatrix& viewMatrix,
1029                                    const SkRRect& rrect,
1030                                    const GrStyle& style) {
1031     ASSERT_SINGLE_OWNER
1032     RETURN_IF_ABANDONED
1033     SkDEBUGCODE(this->validate();)
1034     GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "drawRRect", fContext);
1035 
1036     SkASSERT(!style.pathEffect()); // this should've been devolved to a path in SkGpuDevice
1037 
1038     const SkStrokeRec& stroke = style.strokeRec();
1039     if (stroke.getStyle() == SkStrokeRec::kFill_Style && rrect.isEmpty()) {
1040        return;
1041     }
1042 
1043     const GrClip* clip = origClip;
1044     // It is not uncommon to clip to a round rect and then draw that same round rect. Since our
1045     // lower level clip code works from op bounds, which are SkRects, it doesn't detect that the
1046     // clip can be ignored. The following test attempts to mitigate the stencil clip cost but only
1047     // works for axis-aligned round rects. This also only works for filled rrects since the stroke
1048     // width outsets beyond the rrect itself.
1049     // TODO: skbug.com/10462 - There was mixed performance wins and regressions when this
1050     // optimization was turned on outside of Android Framework. I (michaelludwig) believe this is
1051     // do to the overhead in determining if an SkClipStack is just a rrect. Once that is improved,
1052     // re-enable this and see if we avoid the regressions.
1053 #ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
1054     SkRRect devRRect;
1055     if (clip && stroke.getStyle() == SkStrokeRec::kFill_Style &&
1056         rrect.transform(viewMatrix, &devRRect)) {
1057         GrClip::PreClipResult result = clip->preApply(devRRect.getBounds(), aa);
1058         switch(result.fEffect) {
1059             case GrClip::Effect::kClippedOut:
1060                 return;
1061             case GrClip::Effect::kUnclipped:
1062                 clip = nullptr;
1063                 break;
1064             case GrClip::Effect::kClipped:
1065                 // Currently there's no general-purpose rrect-to-rrect contains function, and if we
1066                 // got here, we know the devRRect's bounds aren't fully contained by the clip.
1067                 // Testing for equality between the two is a reasonable stop-gap for now.
1068                 if (result.fIsRRect && result.fRRect == devRRect) {
1069                     // NOTE: On the android framework, we allow this optimization even when the clip
1070                     // is non-AA and the draw is AA.
1071                     if (result.fAA == aa || (result.fAA == GrAA::kNo && aa == GrAA::kYes)) {
1072                         clip = nullptr;
1073                     }
1074                 }
1075                 break;
1076             default:
1077                 SkUNREACHABLE;
1078         }
1079     }
1080 #endif
1081 
1082     AutoCheckFlush acf(this->drawingManager());
1083 
1084     GrAAType aaType = this->chooseAAType(aa);
1085 
1086     GrOp::Owner op;
1087     if (aaType == GrAAType::kCoverage                          &&
1088         !fCanUseDynamicMSAA                                    &&
1089         !this->caps()->reducedShaderMode()                     &&
1090         rrect.isSimple()                                       &&
1091         rrect.getSimpleRadii().fX == rrect.getSimpleRadii().fY &&
1092         viewMatrix.rectStaysRect() && viewMatrix.isSimilarity()) {
1093         // In specific cases we use a dedicated circular round rect op to try and get better perf.
1094         assert_alive(paint);
1095         op = GrOvalOpFactory::MakeCircularRRectOp(fContext, std::move(paint), viewMatrix, rrect,
1096                                                   stroke, this->caps()->shaderCaps());
1097     }
1098     if (!op && style.isSimpleFill()) {
1099         assert_alive(paint);
1100         op = FillRRectOp::Make(fContext, this->arenaAlloc(), std::move(paint), viewMatrix, rrect,
1101                                rrect.rect(), GrAA(aaType != GrAAType::kNone));
1102     }
1103     if (!op && (aaType == GrAAType::kCoverage || fCanUseDynamicMSAA)) {
1104         assert_alive(paint);
1105         op = GrOvalOpFactory::MakeRRectOp(
1106                 fContext, std::move(paint), viewMatrix, rrect, stroke, this->caps()->shaderCaps());
1107     }
1108     if (op) {
1109         this->addDrawOp(clip, std::move(op));
1110         return;
1111     }
1112 
1113     assert_alive(paint);
1114     this->drawShapeUsingPathRenderer(clip, std::move(paint), aa, viewMatrix,
1115                                      GrStyledShape(rrect, style, DoSimplify::kNo));
1116 }
1117 
1118 ///////////////////////////////////////////////////////////////////////////////
1119 
drawFastShadow(const GrClip * clip,const SkMatrix & viewMatrix,const SkPath & path,const SkDrawShadowRec & rec)1120 bool SurfaceDrawContext::drawFastShadow(const GrClip* clip,
1121                                         const SkMatrix& viewMatrix,
1122                                         const SkPath& path,
1123                                         const SkDrawShadowRec& rec) {
1124     ASSERT_SINGLE_OWNER
1125     if (fContext->abandoned()) {
1126         return true;
1127     }
1128     SkDEBUGCODE(this->validate();)
1129     GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "drawFastShadow", fContext);
1130 
1131     // check z plane
1132     bool tiltZPlane = SkToBool(!SkScalarNearlyZero(rec.fZPlaneParams.fX) ||
1133                                !SkScalarNearlyZero(rec.fZPlaneParams.fY));
1134     bool skipAnalytic = SkToBool(rec.fFlags & SkShadowFlags::kGeometricOnly_ShadowFlag);
1135     if (tiltZPlane || skipAnalytic || !viewMatrix.rectStaysRect() || !viewMatrix.isSimilarity()) {
1136         return false;
1137     }
1138 
1139     SkRRect rrect;
1140     SkRect rect;
1141     // we can only handle rects, circles, and simple rrects with circular corners
1142     bool isRRect = path.isRRect(&rrect) && SkRRectPriv::IsNearlySimpleCircular(rrect) &&
1143                    rrect.getSimpleRadii().fX > SK_ScalarNearlyZero;
1144     if (!isRRect &&
1145         path.isOval(&rect) && SkScalarNearlyEqual(rect.width(), rect.height()) &&
1146         rect.width() > SK_ScalarNearlyZero) {
1147         rrect.setOval(rect);
1148         isRRect = true;
1149     }
1150     if (!isRRect && path.isRect(&rect)) {
1151         rrect.setRect(rect);
1152         isRRect = true;
1153     }
1154 
1155     if (!isRRect) {
1156         return false;
1157     }
1158 
1159     if (rrect.isEmpty()) {
1160         return true;
1161     }
1162 
1163     AutoCheckFlush acf(this->drawingManager());
1164 
1165     SkPoint3 devLightPos = rec.fLightPos;
1166     bool directional = SkToBool(rec.fFlags & kDirectionalLight_ShadowFlag);
1167     if (!directional) {
1168         // transform light
1169         viewMatrix.mapPoints((SkPoint*)&devLightPos.fX, 1);
1170     }
1171 
1172     // 1/scale
1173     SkScalar devToSrcScale = viewMatrix.isScaleTranslate() ?
1174         SkScalarInvert(SkScalarAbs(viewMatrix[SkMatrix::kMScaleX])) :
1175         sk_float_rsqrt(viewMatrix[SkMatrix::kMScaleX] * viewMatrix[SkMatrix::kMScaleX] +
1176                        viewMatrix[SkMatrix::kMSkewX] * viewMatrix[SkMatrix::kMSkewX]);
1177 
1178     SkScalar occluderHeight = rec.fZPlaneParams.fZ;
1179     bool transparent = SkToBool(rec.fFlags & SkShadowFlags::kTransparentOccluder_ShadowFlag);
1180 
1181     if (SkColorGetA(rec.fAmbientColor) > 0) {
1182         SkScalar devSpaceInsetWidth = SkDrawShadowMetrics::AmbientBlurRadius(occluderHeight);
1183         const SkScalar umbraRecipAlpha = SkDrawShadowMetrics::AmbientRecipAlpha(occluderHeight);
1184         const SkScalar devSpaceAmbientBlur = devSpaceInsetWidth * umbraRecipAlpha;
1185 
1186         // Outset the shadow rrect to the border of the penumbra
1187         SkScalar ambientPathOutset = devSpaceInsetWidth * devToSrcScale;
1188         SkRRect ambientRRect;
1189         SkRect outsetRect = rrect.rect().makeOutset(ambientPathOutset, ambientPathOutset);
1190         // If the rrect was an oval then its outset will also be one.
1191         // We set it explicitly to avoid errors.
1192         if (rrect.isOval()) {
1193             ambientRRect = SkRRect::MakeOval(outsetRect);
1194         } else {
1195             SkScalar outsetRad = SkRRectPriv::GetSimpleRadii(rrect).fX + ambientPathOutset;
1196             ambientRRect = SkRRect::MakeRectXY(outsetRect, outsetRad, outsetRad);
1197         }
1198 
1199         GrColor ambientColor = SkColorToPremulGrColor(rec.fAmbientColor);
1200         if (transparent) {
1201             // set a large inset to force a fill
1202             devSpaceInsetWidth = ambientRRect.width();
1203         }
1204 
1205         GrOp::Owner op = ShadowRRectOp::Make(fContext,
1206                                              ambientColor,
1207                                              viewMatrix,
1208                                              ambientRRect,
1209                                              devSpaceAmbientBlur,
1210                                              devSpaceInsetWidth);
1211         if (op) {
1212             this->addDrawOp(clip, std::move(op));
1213         }
1214     }
1215 
1216     if (SkColorGetA(rec.fSpotColor) > 0) {
1217         SkScalar devSpaceSpotBlur;
1218         SkScalar spotScale;
1219         SkVector spotOffset;
1220         if (directional) {
1221             SkDrawShadowMetrics::GetDirectionalParams(occluderHeight, devLightPos.fX,
1222                                                       devLightPos.fY, devLightPos.fZ,
1223                                                       rec.fLightRadius, &devSpaceSpotBlur,
1224                                                       &spotScale, &spotOffset);
1225         } else {
1226             SkDrawShadowMetrics::GetSpotParams(occluderHeight, devLightPos.fX, devLightPos.fY,
1227                                                devLightPos.fZ, rec.fLightRadius,
1228                                                &devSpaceSpotBlur, &spotScale, &spotOffset);
1229         }
1230         // handle scale of radius due to CTM
1231         const SkScalar srcSpaceSpotBlur = devSpaceSpotBlur * devToSrcScale;
1232 
1233         // Adjust translate for the effect of the scale.
1234         spotOffset.fX += spotScale*viewMatrix[SkMatrix::kMTransX];
1235         spotOffset.fY += spotScale*viewMatrix[SkMatrix::kMTransY];
1236         // This offset is in dev space, need to transform it into source space.
1237         SkMatrix ctmInverse;
1238         if (viewMatrix.invert(&ctmInverse)) {
1239             ctmInverse.mapPoints(&spotOffset, 1);
1240         } else {
1241             // Since the matrix is a similarity, this should never happen, but just in case...
1242             SkDebugf("Matrix is degenerate. Will not render spot shadow correctly!\n");
1243             SkASSERT(false);
1244         }
1245 
1246         // Compute the transformed shadow rrect
1247         SkRRect spotShadowRRect;
1248         SkMatrix shadowTransform;
1249         shadowTransform.setScaleTranslate(spotScale, spotScale, spotOffset.fX, spotOffset.fY);
1250         rrect.transform(shadowTransform, &spotShadowRRect);
1251         SkScalar spotRadius = spotShadowRRect.getSimpleRadii().fX;
1252 
1253         // Compute the insetWidth
1254         SkScalar blurOutset = srcSpaceSpotBlur;
1255         SkScalar insetWidth = blurOutset;
1256         if (transparent) {
1257             // If transparent, just do a fill
1258             insetWidth += spotShadowRRect.width();
1259         } else {
1260             // For shadows, instead of using a stroke we specify an inset from the penumbra
1261             // border. We want to extend this inset area so that it meets up with the caster
1262             // geometry. The inset geometry will by default already be inset by the blur width.
1263             //
1264             // We compare the min and max corners inset by the radius between the original
1265             // rrect and the shadow rrect. The distance between the two plus the difference
1266             // between the scaled radius and the original radius gives the distance from the
1267             // transformed shadow shape to the original shape in that corner. The max
1268             // of these gives the maximum distance we need to cover.
1269             //
1270             // Since we are outsetting by 1/2 the blur distance, we just add the maxOffset to
1271             // that to get the full insetWidth.
1272             SkScalar maxOffset;
1273             if (rrect.isRect()) {
1274                 // Manhattan distance works better for rects
1275                 maxOffset = std::max(std::max(SkTAbs(spotShadowRRect.rect().fLeft -
1276                                                  rrect.rect().fLeft),
1277                                           SkTAbs(spotShadowRRect.rect().fTop -
1278                                                  rrect.rect().fTop)),
1279                                    std::max(SkTAbs(spotShadowRRect.rect().fRight -
1280                                                  rrect.rect().fRight),
1281                                           SkTAbs(spotShadowRRect.rect().fBottom -
1282                                                  rrect.rect().fBottom)));
1283             } else {
1284                 SkScalar dr = spotRadius - SkRRectPriv::GetSimpleRadii(rrect).fX;
1285                 SkPoint upperLeftOffset = SkPoint::Make(spotShadowRRect.rect().fLeft -
1286                                                         rrect.rect().fLeft + dr,
1287                                                         spotShadowRRect.rect().fTop -
1288                                                         rrect.rect().fTop + dr);
1289                 SkPoint lowerRightOffset = SkPoint::Make(spotShadowRRect.rect().fRight -
1290                                                          rrect.rect().fRight - dr,
1291                                                          spotShadowRRect.rect().fBottom -
1292                                                          rrect.rect().fBottom - dr);
1293                 maxOffset = SkScalarSqrt(std::max(SkPointPriv::LengthSqd(upperLeftOffset),
1294                                                   SkPointPriv::LengthSqd(lowerRightOffset))) + dr;
1295             }
1296             insetWidth += std::max(blurOutset, maxOffset);
1297         }
1298 
1299         // Outset the shadow rrect to the border of the penumbra
1300         SkRect outsetRect = spotShadowRRect.rect().makeOutset(blurOutset, blurOutset);
1301         if (spotShadowRRect.isOval()) {
1302             spotShadowRRect = SkRRect::MakeOval(outsetRect);
1303         } else {
1304             SkScalar outsetRad = spotRadius + blurOutset;
1305             spotShadowRRect = SkRRect::MakeRectXY(outsetRect, outsetRad, outsetRad);
1306         }
1307 
1308         GrColor spotColor = SkColorToPremulGrColor(rec.fSpotColor);
1309 
1310         GrOp::Owner op = ShadowRRectOp::Make(fContext,
1311                                              spotColor,
1312                                              viewMatrix,
1313                                              spotShadowRRect,
1314                                              2.0f * devSpaceSpotBlur,
1315                                              insetWidth);
1316         if (op) {
1317             this->addDrawOp(clip, std::move(op));
1318         }
1319     }
1320 
1321     return true;
1322 }
1323 
1324 ///////////////////////////////////////////////////////////////////////////////
1325 
drawRegion(const GrClip * clip,GrPaint && paint,GrAA aa,const SkMatrix & viewMatrix,const SkRegion & region,const GrStyle & style,const GrUserStencilSettings * ss)1326 void SurfaceDrawContext::drawRegion(const GrClip* clip,
1327                                     GrPaint&& paint,
1328                                     GrAA aa,
1329                                     const SkMatrix& viewMatrix,
1330                                     const SkRegion& region,
1331                                     const GrStyle& style,
1332                                     const GrUserStencilSettings* ss) {
1333     ASSERT_SINGLE_OWNER
1334     RETURN_IF_ABANDONED
1335     SkDEBUGCODE(this->validate();)
1336     GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "drawRegion", fContext);
1337 
1338     if (GrAA::kYes == aa) {
1339         // GrRegionOp performs no antialiasing but is much faster, so here we check the matrix
1340         // to see whether aa is really required.
1341         if (!SkToBool(viewMatrix.getType() & ~(SkMatrix::kTranslate_Mask)) &&
1342             SkScalarIsInt(viewMatrix.getTranslateX()) &&
1343             SkScalarIsInt(viewMatrix.getTranslateY())) {
1344             aa = GrAA::kNo;
1345         }
1346     }
1347     bool complexStyle = !style.isSimpleFill();
1348     if (complexStyle || GrAA::kYes == aa) {
1349         SkPath path;
1350         region.getBoundaryPath(&path);
1351         path.setIsVolatile(true);
1352 
1353         return this->drawPath(clip, std::move(paint), aa, viewMatrix, path, style);
1354     }
1355 
1356     GrAAType aaType = (this->numSamples() > 1) ? GrAAType::kMSAA : GrAAType::kNone;
1357     GrOp::Owner op = RegionOp::Make(fContext, std::move(paint), viewMatrix, region, aaType, ss);
1358     this->addDrawOp(clip, std::move(op));
1359 }
1360 
drawOval(const GrClip * clip,GrPaint && paint,GrAA aa,const SkMatrix & viewMatrix,const SkRect & oval,const GrStyle & style)1361 void SurfaceDrawContext::drawOval(const GrClip* clip,
1362                                   GrPaint&& paint,
1363                                   GrAA aa,
1364                                   const SkMatrix& viewMatrix,
1365                                   const SkRect& oval,
1366                                   const GrStyle& style) {
1367     ASSERT_SINGLE_OWNER
1368     RETURN_IF_ABANDONED
1369     SkDEBUGCODE(this->validate();)
1370     GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "drawOval", fContext);
1371 
1372     const SkStrokeRec& stroke = style.strokeRec();
1373 
1374     if (oval.isEmpty() && !style.pathEffect()) {
1375         if (stroke.getStyle() == SkStrokeRec::kFill_Style) {
1376             return;
1377         }
1378 
1379         this->drawRect(clip, std::move(paint), aa, viewMatrix, oval, &style);
1380         return;
1381     }
1382 
1383     AutoCheckFlush acf(this->drawingManager());
1384 
1385     GrAAType aaType = this->chooseAAType(aa);
1386 
1387     GrOp::Owner op;
1388     if (aaType == GrAAType::kCoverage      &&
1389         !fCanUseDynamicMSAA                &&
1390         !this->caps()->reducedShaderMode() &&
1391         oval.width() > SK_ScalarNearlyZero &&
1392         oval.width() == oval.height()      &&
1393         viewMatrix.isSimilarity()) {
1394         // In specific cases we use a dedicated circle op to try and get better perf.
1395         assert_alive(paint);
1396         op = GrOvalOpFactory::MakeCircleOp(fContext, std::move(paint), viewMatrix, oval, style,
1397                                            this->caps()->shaderCaps());
1398     }
1399     if (!op && style.isSimpleFill()) {
1400         // FillRRectOp has special geometry and a fragment-shader branch to conditionally evaluate
1401         // the arc equation. This same special geometry and fragment branch also turn out to be a
1402         // substantial optimization for drawing ovals (namely, by not evaluating the arc equation
1403         // inside the oval's inner diamond). Given these optimizations, it's a clear win to draw
1404         // ovals the exact same way we do round rects.
1405         assert_alive(paint);
1406         op = FillRRectOp::Make(fContext, this->arenaAlloc(), std::move(paint), viewMatrix,
1407                                SkRRect::MakeOval(oval), oval, GrAA(aaType != GrAAType::kNone));
1408     }
1409     if (!op && (aaType == GrAAType::kCoverage || fCanUseDynamicMSAA)) {
1410         assert_alive(paint);
1411         op = GrOvalOpFactory::MakeOvalOp(fContext, std::move(paint), viewMatrix, oval, style,
1412                                          this->caps()->shaderCaps());
1413     }
1414     if (op) {
1415         this->addDrawOp(clip, std::move(op));
1416         return;
1417     }
1418 
1419     assert_alive(paint);
1420     this->drawShapeUsingPathRenderer(clip, std::move(paint), aa, viewMatrix,
1421                                      GrStyledShape(SkRRect::MakeOval(oval), SkPathDirection::kCW, 2,
1422                                                    false, style, DoSimplify::kNo));
1423 }
1424 
drawArc(const GrClip * clip,GrPaint && paint,GrAA aa,const SkMatrix & viewMatrix,const SkRect & oval,SkScalar startAngle,SkScalar sweepAngle,bool useCenter,const GrStyle & style)1425 void SurfaceDrawContext::drawArc(const GrClip* clip,
1426                                  GrPaint&& paint,
1427                                  GrAA aa,
1428                                  const SkMatrix& viewMatrix,
1429                                  const SkRect& oval,
1430                                  SkScalar startAngle,
1431                                  SkScalar sweepAngle,
1432                                  bool useCenter,
1433                                  const GrStyle& style) {
1434     ASSERT_SINGLE_OWNER
1435     RETURN_IF_ABANDONED
1436     SkDEBUGCODE(this->validate();)
1437             GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "drawArc", fContext);
1438 
1439     AutoCheckFlush acf(this->drawingManager());
1440 
1441     GrAAType aaType = this->chooseAAType(aa);
1442     if (aaType == GrAAType::kCoverage) {
1443         const GrShaderCaps* shaderCaps = this->caps()->shaderCaps();
1444         GrOp::Owner op = GrOvalOpFactory::MakeArcOp(fContext,
1445                                                     std::move(paint),
1446                                                     viewMatrix,
1447                                                     oval,
1448                                                     startAngle,
1449                                                     sweepAngle,
1450                                                     useCenter,
1451                                                     style,
1452                                                     shaderCaps);
1453         if (op) {
1454             this->addDrawOp(clip, std::move(op));
1455             return;
1456         }
1457         assert_alive(paint);
1458     }
1459     this->drawShapeUsingPathRenderer(clip, std::move(paint), aa, viewMatrix,
1460                                      GrStyledShape::MakeArc(oval, startAngle, sweepAngle, useCenter,
1461                                                             style, DoSimplify::kNo));
1462 }
1463 
drawImageLattice(const GrClip * clip,GrPaint && paint,const SkMatrix & viewMatrix,GrSurfaceProxyView view,SkAlphaType alphaType,sk_sp<GrColorSpaceXform> csxf,GrSamplerState::Filter filter,std::unique_ptr<SkLatticeIter> iter,const SkRect & dst)1464 void SurfaceDrawContext::drawImageLattice(const GrClip* clip,
1465                                           GrPaint&& paint,
1466                                           const SkMatrix& viewMatrix,
1467                                           GrSurfaceProxyView view,
1468                                           SkAlphaType alphaType,
1469                                           sk_sp<GrColorSpaceXform> csxf,
1470                                           GrSamplerState::Filter filter,
1471                                           std::unique_ptr<SkLatticeIter> iter,
1472                                           const SkRect& dst) {
1473     ASSERT_SINGLE_OWNER
1474     RETURN_IF_ABANDONED
1475     SkDEBUGCODE(this->validate();)
1476     GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "drawImageLattice", fContext);
1477 
1478     AutoCheckFlush acf(this->drawingManager());
1479 
1480     GrOp::Owner op =
1481               LatticeOp::MakeNonAA(fContext, std::move(paint), viewMatrix, std::move(view),
1482                                    alphaType, std::move(csxf), filter, std::move(iter), dst);
1483     this->addDrawOp(clip, std::move(op));
1484 }
1485 
drawDrawable(std::unique_ptr<SkDrawable::GpuDrawHandler> drawable,const SkRect & bounds)1486 void SurfaceDrawContext::drawDrawable(std::unique_ptr<SkDrawable::GpuDrawHandler> drawable,
1487                                       const SkRect& bounds) {
1488     GrOp::Owner op(DrawableOp::Make(fContext, std::move(drawable), bounds));
1489     SkASSERT(op);
1490     this->addOp(std::move(op));
1491 }
1492 
setLastClip(uint32_t clipStackGenID,const SkIRect & devClipBounds,int numClipAnalyticElements)1493 void SurfaceDrawContext::setLastClip(uint32_t clipStackGenID,
1494                                      const SkIRect& devClipBounds,
1495                                      int numClipAnalyticElements) {
1496     auto opsTask = this->getOpsTask();
1497     opsTask->fLastClipStackGenID = clipStackGenID;
1498     opsTask->fLastDevClipBounds = devClipBounds;
1499     opsTask->fLastClipNumAnalyticElements = numClipAnalyticElements;
1500 }
1501 
mustRenderClip(uint32_t clipStackGenID,const SkIRect & devClipBounds,int numClipAnalyticElements)1502 bool SurfaceDrawContext::mustRenderClip(uint32_t clipStackGenID,
1503                                         const SkIRect& devClipBounds,
1504                                         int numClipAnalyticElements) {
1505     auto opsTask = this->getOpsTask();
1506     return opsTask->fLastClipStackGenID != clipStackGenID ||
1507            !opsTask->fLastDevClipBounds.contains(devClipBounds) ||
1508            opsTask->fLastClipNumAnalyticElements != numClipAnalyticElements;
1509 }
1510 
waitOnSemaphores(int numSemaphores,const GrBackendSemaphore waitSemaphores[],bool deleteSemaphoresAfterWait)1511 bool SurfaceDrawContext::waitOnSemaphores(int numSemaphores,
1512                                           const GrBackendSemaphore waitSemaphores[],
1513                                           bool deleteSemaphoresAfterWait) {
1514     ASSERT_SINGLE_OWNER
1515     RETURN_FALSE_IF_ABANDONED
1516     SkDEBUGCODE(this->validate();)
1517     GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "waitOnSemaphores", fContext);
1518 
1519     AutoCheckFlush acf(this->drawingManager());
1520 
1521     if (numSemaphores && !this->caps()->semaphoreSupport()) {
1522         return false;
1523     }
1524 
1525     auto direct = fContext->asDirectContext();
1526     if (!direct) {
1527         return false;
1528     }
1529 
1530     auto resourceProvider = direct->priv().resourceProvider();
1531 
1532     GrWrapOwnership ownership =
1533             deleteSemaphoresAfterWait ? kAdopt_GrWrapOwnership : kBorrow_GrWrapOwnership;
1534 
1535     std::unique_ptr<std::unique_ptr<GrSemaphore>[]> grSemaphores(
1536             new std::unique_ptr<GrSemaphore>[numSemaphores]);
1537     for (int i = 0; i < numSemaphores; ++i) {
1538         grSemaphores[i] = resourceProvider->wrapBackendSemaphore(waitSemaphores[i],
1539                                                                  GrSemaphoreWrapType::kWillWait,
1540                                                                  ownership);
1541     }
1542     this->drawingManager()->newWaitRenderTask(this->asSurfaceProxyRef(), std::move(grSemaphores),
1543                                               numSemaphores);
1544     return true;
1545 }
1546 
drawPath(const GrClip * clip,GrPaint && paint,GrAA aa,const SkMatrix & viewMatrix,const SkPath & path,const GrStyle & style)1547 void SurfaceDrawContext::drawPath(const GrClip* clip,
1548                                   GrPaint&& paint,
1549                                   GrAA aa,
1550                                   const SkMatrix& viewMatrix,
1551                                   const SkPath& path,
1552                                   const GrStyle& style) {
1553     ASSERT_SINGLE_OWNER
1554     RETURN_IF_ABANDONED
1555     SkDEBUGCODE(this->validate();)
1556     GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "drawPath", fContext);
1557 
1558     GrStyledShape shape(path, style, DoSimplify::kNo);
1559     this->drawShape(clip, std::move(paint), aa, viewMatrix, std::move(shape));
1560 }
1561 
drawShape(const GrClip * clip,GrPaint && paint,GrAA aa,const SkMatrix & viewMatrix,GrStyledShape && shape)1562 void SurfaceDrawContext::drawShape(const GrClip* clip,
1563                                    GrPaint&& paint,
1564                                    GrAA aa,
1565                                    const SkMatrix& viewMatrix,
1566                                    GrStyledShape&& shape) {
1567     ASSERT_SINGLE_OWNER
1568     RETURN_IF_ABANDONED
1569     SkDEBUGCODE(this->validate();)
1570     GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "drawShape", fContext);
1571 
1572     if (shape.isEmpty()) {
1573         if (shape.inverseFilled()) {
1574             this->drawPaint(clip, std::move(paint), viewMatrix);
1575         }
1576         return;
1577     }
1578 
1579     AutoCheckFlush acf(this->drawingManager());
1580 
1581     // If we get here in drawShape(), we definitely need to use path rendering
1582     this->drawShapeUsingPathRenderer(clip, std::move(paint), aa, viewMatrix, std::move(shape),
1583                                      /* attemptDrawSimple */ true);
1584 }
1585 
get_clip_bounds(const SurfaceDrawContext * sdc,const GrClip * clip)1586 static SkIRect get_clip_bounds(const SurfaceDrawContext* sdc, const GrClip* clip) {
1587     return clip ? clip->getConservativeBounds() : SkIRect::MakeWH(sdc->width(), sdc->height());
1588 }
1589 
drawAndStencilPath(const GrHardClip * clip,const GrUserStencilSettings * ss,SkRegion::Op op,bool invert,GrAA aa,const SkMatrix & viewMatrix,const SkPath & path)1590 bool SurfaceDrawContext::drawAndStencilPath(const GrHardClip* clip,
1591                                             const GrUserStencilSettings* ss,
1592                                             SkRegion::Op op,
1593                                             bool invert,
1594                                             GrAA aa,
1595                                             const SkMatrix& viewMatrix,
1596                                             const SkPath& path) {
1597     ASSERT_SINGLE_OWNER
1598     RETURN_FALSE_IF_ABANDONED
1599     SkDEBUGCODE(this->validate();)
1600     GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "drawAndStencilPath", fContext);
1601 
1602     if (path.isEmpty() && path.isInverseFillType()) {
1603         GrPaint paint;
1604         paint.setCoverageSetOpXPFactory(op, invert);
1605         this->stencilRect(clip, ss, std::move(paint), GrAA::kNo, SkMatrix::I(),
1606                           SkRect::Make(this->dimensions()));
1607         return true;
1608     }
1609 
1610     AutoCheckFlush acf(this->drawingManager());
1611 
1612     // An Assumption here is that path renderer would use some form of tweaking
1613     // the src color (either the input alpha or in the frag shader) to implement
1614     // aa. If we have some future driver-mojo path AA that can do the right
1615     // thing WRT to the blend then we'll need some query on the PR.
1616     GrAAType aaType = this->chooseAAType(aa);
1617     bool hasUserStencilSettings = !ss->isUnused();
1618 
1619     SkIRect clipConservativeBounds = get_clip_bounds(this, clip);
1620 
1621     GrPaint paint;
1622     paint.setCoverageSetOpXPFactory(op, invert);
1623 
1624     GrStyledShape shape(path, GrStyle::SimpleFill());
1625     PathRenderer::CanDrawPathArgs canDrawArgs;
1626     canDrawArgs.fCaps = this->caps();
1627     canDrawArgs.fProxy = this->asRenderTargetProxy();
1628     canDrawArgs.fViewMatrix = &viewMatrix;
1629     canDrawArgs.fShape = &shape;
1630     canDrawArgs.fPaint = &paint;
1631     canDrawArgs.fSurfaceProps = &fSurfaceProps;
1632     canDrawArgs.fClipConservativeBounds = &clipConservativeBounds;
1633     canDrawArgs.fAAType = aaType;
1634     canDrawArgs.fHasUserStencilSettings = hasUserStencilSettings;
1635 
1636     using DrawType = PathRendererChain::DrawType;
1637 
1638     // Don't allow the SW renderer
1639     auto pr = this->drawingManager()->getPathRenderer(canDrawArgs,
1640                                                       false,
1641                                                       DrawType::kStencilAndColor);
1642     if (!pr) {
1643         return false;
1644     }
1645 
1646     PathRenderer::DrawPathArgs args{this->drawingManager()->getContext(),
1647                                     std::move(paint),
1648                                     ss,
1649                                     this,
1650                                     clip,
1651                                     &clipConservativeBounds,
1652                                     &viewMatrix,
1653                                     &shape,
1654                                     aaType,
1655                                     this->colorInfo().isLinearlyBlended()};
1656     pr->drawPath(args);
1657     return true;
1658 }
1659 
isBudgeted() const1660 SkBudgeted SurfaceDrawContext::isBudgeted() const {
1661     ASSERT_SINGLE_OWNER
1662 
1663     if (fContext->abandoned()) {
1664         return SkBudgeted::kNo;
1665     }
1666 
1667     SkDEBUGCODE(this->validate();)
1668 
1669     return this->asSurfaceProxy()->isBudgeted();
1670 }
1671 
drawStrokedLine(const GrClip * clip,GrPaint && paint,GrAA aa,const SkMatrix & viewMatrix,const SkPoint points[2],const SkStrokeRec & stroke)1672 void SurfaceDrawContext::drawStrokedLine(const GrClip* clip,
1673                                          GrPaint&& paint,
1674                                          GrAA aa,
1675                                          const SkMatrix& viewMatrix,
1676                                          const SkPoint points[2],
1677                                          const SkStrokeRec& stroke) {
1678     ASSERT_SINGLE_OWNER
1679 
1680     SkASSERT(stroke.getStyle() == SkStrokeRec::kStroke_Style);
1681     SkASSERT(stroke.getWidth() > 0);
1682     // Adding support for round capping would require a
1683     // SurfaceDrawContext::fillRRectWithLocalMatrix entry point
1684     SkASSERT(SkPaint::kRound_Cap != stroke.getCap());
1685 
1686     const SkScalar halfWidth = 0.5f * stroke.getWidth();
1687     if (halfWidth <= 0.f) {
1688         // Prevents underflow when stroke width is epsilon > 0 (so technically not a hairline).
1689         // The CTM would need to have a scale near 1/epsilon in order for this to have meaningful
1690         // coverage (although that would likely overflow elsewhere and cause the draw to drop due
1691         // to non-finite bounds). At any other scale, this line is so thin, it's coverage is
1692         // negligible, so discarding the draw is visually equivalent.
1693         return;
1694     }
1695 
1696     SkVector parallel = points[1] - points[0];
1697 
1698     if (!SkPoint::Normalize(&parallel)) {
1699         parallel.fX = 1.0f;
1700         parallel.fY = 0.0f;
1701     }
1702     parallel *= halfWidth;
1703 
1704     SkVector ortho = { parallel.fY, -parallel.fX };
1705     if (SkPaint::kButt_Cap == stroke.getCap()) {
1706         // No extra extension for butt caps
1707         parallel = {0.f, 0.f};
1708     }
1709     // Order is TL, TR, BR, BL where arbitrarily "down" is p0 to p1 and "right" is positive
1710     SkPoint corners[4] = { points[0] - ortho - parallel,
1711                            points[0] + ortho - parallel,
1712                            points[1] + ortho + parallel,
1713                            points[1] - ortho + parallel };
1714 
1715     GrQuadAAFlags edgeAA = (aa == GrAA::kYes) ? GrQuadAAFlags::kAll : GrQuadAAFlags::kNone;
1716     this->fillQuadWithEdgeAA(clip, std::move(paint), aa, edgeAA, viewMatrix, corners, nullptr);
1717 }
1718 
drawSimpleShape(const GrClip * clip,GrPaint * paint,GrAA aa,const SkMatrix & viewMatrix,const GrStyledShape & shape)1719 bool SurfaceDrawContext::drawSimpleShape(const GrClip* clip,
1720                                          GrPaint* paint,
1721                                          GrAA aa,
1722                                          const SkMatrix& viewMatrix,
1723                                          const GrStyledShape& shape) {
1724     if (!shape.style().hasPathEffect()) {
1725         GrAAType aaType = this->chooseAAType(aa);
1726         SkPoint linePts[2];
1727         SkRRect rrect;
1728         // We can ignore the starting point and direction since there is no path effect.
1729         bool inverted;
1730         if (shape.asLine(linePts, &inverted) && !inverted &&
1731             shape.style().strokeRec().getStyle() == SkStrokeRec::kStroke_Style &&
1732             shape.style().strokeRec().getCap() != SkPaint::kRound_Cap) {
1733             // The stroked line is an oriented rectangle, which looks the same or better (if
1734             // perspective) compared to path rendering. The exception is subpixel/hairline lines
1735             // that are non-AA or MSAA, in which case the default path renderer achieves higher
1736             // quality.
1737             // FIXME(michaelludwig): If the fill rect op could take an external coverage, or checks
1738             // for and outsets thin non-aa rects to 1px, the path renderer could be skipped.
1739             SkScalar coverage;
1740             if (aaType == GrAAType::kCoverage ||
1741                 !SkDrawTreatAAStrokeAsHairline(shape.style().strokeRec().getWidth(), viewMatrix,
1742                                                &coverage)) {
1743                 this->drawStrokedLine(clip, std::move(*paint), aa, viewMatrix, linePts,
1744                                       shape.style().strokeRec());
1745                 return true;
1746             }
1747         } else if (shape.asRRect(&rrect, nullptr, nullptr, &inverted) && !inverted) {
1748             if (rrect.isRect()) {
1749                 this->drawRect(clip, std::move(*paint), aa, viewMatrix, rrect.rect(),
1750                                &shape.style());
1751                 return true;
1752             } else if (rrect.isOval()) {
1753                 this->drawOval(clip, std::move(*paint), aa, viewMatrix, rrect.rect(),
1754                                shape.style());
1755                 return true;
1756             }
1757             this->drawRRect(clip, std::move(*paint), aa, viewMatrix, rrect, shape.style());
1758             return true;
1759         } else if (GrAAType::kCoverage == aaType &&
1760                    shape.style().isSimpleFill()  &&
1761                    viewMatrix.rectStaysRect()    &&
1762                    !this->caps()->reducedShaderMode()) {
1763             // TODO: the rectStaysRect restriction could be lifted if we were willing to apply the
1764             // matrix to all the points individually rather than just to the rect
1765             SkRect rects[2];
1766             if (shape.asNestedRects(rects)) {
1767                 // Concave AA paths are expensive - try to avoid them for special cases
1768                 GrOp::Owner op = StrokeRectOp::MakeNested(fContext, std::move(*paint),
1769                                                           viewMatrix, rects);
1770                 if (op) {
1771                     this->addDrawOp(clip, std::move(op));
1772                     return true;
1773                 }
1774                 // Fall through to let path renderer handle subpixel nested rects with unequal
1775                 // stroke widths along X/Y.
1776             }
1777         }
1778     }
1779     return false;
1780 }
1781 
drawShapeUsingPathRenderer(const GrClip * clip,GrPaint && paint,GrAA aa,const SkMatrix & viewMatrix,GrStyledShape && shape,bool attemptDrawSimple)1782 void SurfaceDrawContext::drawShapeUsingPathRenderer(const GrClip* clip,
1783                                                     GrPaint&& paint,
1784                                                     GrAA aa,
1785                                                     const SkMatrix& viewMatrix,
1786                                                     GrStyledShape&& shape,
1787                                                     bool attemptDrawSimple) {
1788     ASSERT_SINGLE_OWNER
1789     RETURN_IF_ABANDONED
1790     GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "internalDrawPath", fContext);
1791 
1792     if (!viewMatrix.isFinite() || !shape.bounds().isFinite()) {
1793         return;
1794     }
1795 
1796     SkIRect clipConservativeBounds = get_clip_bounds(this, clip);
1797 
1798     // Always allow paths to trigger DMSAA.
1799     GrAAType aaType = fCanUseDynamicMSAA ? GrAAType::kMSAA : this->chooseAAType(aa);
1800 
1801     PathRenderer::CanDrawPathArgs canDrawArgs;
1802     canDrawArgs.fCaps = this->caps();
1803     canDrawArgs.fProxy = this->asRenderTargetProxy();
1804     canDrawArgs.fViewMatrix = &viewMatrix;
1805     canDrawArgs.fShape = &shape;
1806     canDrawArgs.fPaint = &paint;
1807     canDrawArgs.fSurfaceProps = &fSurfaceProps;
1808     canDrawArgs.fClipConservativeBounds = &clipConservativeBounds;
1809     canDrawArgs.fHasUserStencilSettings = false;
1810     canDrawArgs.fAAType = aaType;
1811 
1812     constexpr static bool kDisallowSWPathRenderer = false;
1813     constexpr static bool kAllowSWPathRenderer = true;
1814     using DrawType = PathRendererChain::DrawType;
1815 
1816     PathRenderer* pr = nullptr;
1817 
1818     if (!shape.style().strokeRec().isFillStyle() && !shape.isEmpty()) {
1819         // Give the tessellation path renderer a chance to claim this stroke before we simplify it.
1820         PathRenderer* tess = this->drawingManager()->getTessellationPathRenderer();
1821         if (tess && tess->canDrawPath(canDrawArgs) == PathRenderer::CanDrawPath::kYes) {
1822             pr = tess;
1823         }
1824     }
1825 
1826     if (!pr) {
1827         // The shape isn't a stroke that can be drawn directly. Simplify if possible.
1828         shape.simplify();
1829 
1830         if (shape.isEmpty() && !shape.inverseFilled()) {
1831             return;
1832         }
1833 
1834         if (attemptDrawSimple || shape.simplified()) {
1835             // Usually we enter drawShapeUsingPathRenderer() because the shape+style was too complex
1836             // for dedicated draw ops. However, if GrStyledShape was able to reduce something we
1837             // ought to try again instead of going right to path rendering.
1838             if (this->drawSimpleShape(clip, &paint, aa, viewMatrix, shape)) {
1839                 return;
1840             }
1841         }
1842 
1843         // Try a 1st time without applying any of the style to the geometry (and barring sw)
1844         pr = this->drawingManager()->getPathRenderer(canDrawArgs, kDisallowSWPathRenderer,
1845                                                      DrawType::kColor);
1846     }
1847 
1848     SkScalar styleScale =  GrStyle::MatrixToScaleFactor(viewMatrix);
1849     if (styleScale == 0.0f) {
1850         return;
1851     }
1852 
1853     if (!pr && shape.style().pathEffect()) {
1854         // It didn't work above, so try again with the path effect applied.
1855         shape = shape.applyStyle(GrStyle::Apply::kPathEffectOnly, styleScale);
1856         if (shape.isEmpty()) {
1857             return;
1858         }
1859         pr = this->drawingManager()->getPathRenderer(canDrawArgs, kDisallowSWPathRenderer,
1860                                                      DrawType::kColor);
1861     }
1862     if (!pr) {
1863         if (shape.style().applies()) {
1864             shape = shape.applyStyle(GrStyle::Apply::kPathEffectAndStrokeRec, styleScale);
1865             if (shape.isEmpty()) {
1866                 return;
1867             }
1868             // This time, allow SW renderer
1869             pr = this->drawingManager()->getPathRenderer(canDrawArgs, kAllowSWPathRenderer,
1870                                                          DrawType::kColor);
1871         } else {
1872             pr = this->drawingManager()->getSoftwarePathRenderer();
1873 #if GR_PATH_RENDERER_SPEW
1874             SkDebugf("falling back to: %s\n", pr->name());
1875 #endif
1876         }
1877     }
1878 
1879     if (!pr) {
1880 #ifdef SK_DEBUG
1881         SkDebugf("Unable to find path renderer compatible with path.\n");
1882 #endif
1883         return;
1884     }
1885 
1886     PathRenderer::DrawPathArgs args{this->drawingManager()->getContext(),
1887                                     std::move(paint),
1888                                     &GrUserStencilSettings::kUnused,
1889                                     this,
1890                                     clip,
1891                                     &clipConservativeBounds,
1892                                     &viewMatrix,
1893                                     canDrawArgs.fShape,
1894                                     aaType,
1895                                     this->colorInfo().isLinearlyBlended()};
1896     pr->drawPath(args);
1897 }
1898 
addDrawOp(const GrClip * clip,GrOp::Owner op,const std::function<WillAddOpFn> & willAddFn)1899 void SurfaceDrawContext::addDrawOp(const GrClip* clip,
1900                                    GrOp::Owner op,
1901                                    const std::function<WillAddOpFn>& willAddFn) {
1902     ASSERT_SINGLE_OWNER
1903     if (fContext->abandoned()) {
1904         return;
1905     }
1906     GrDrawOp* drawOp = (GrDrawOp*)op.get();
1907     SkDEBUGCODE(this->validate();)
1908     SkDEBUGCODE(drawOp->fAddDrawOpCalled = true;)
1909     GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceDrawContext", "addDrawOp", fContext);
1910 
1911     // Setup clip
1912     SkRect bounds;
1913     op_bounds(&bounds, op.get());
1914     GrAppliedClip appliedClip(this->dimensions(), this->asSurfaceProxy()->backingStoreDimensions());
1915     const bool opUsesMSAA = drawOp->usesMSAA();
1916     bool skipDraw = false;
1917     if (clip) {
1918         // Have a complex clip, so defer to its early clip culling
1919         GrAAType aaType;
1920         if (opUsesMSAA) {
1921             aaType = GrAAType::kMSAA;
1922         } else {
1923             aaType = op->hasAABloat() ? GrAAType::kCoverage : GrAAType::kNone;
1924         }
1925         skipDraw = clip->apply(fContext, this, drawOp, aaType,
1926                                &appliedClip, &bounds) == GrClip::Effect::kClippedOut;
1927     } else {
1928         // No clipping, so just clip the bounds against the logical render target dimensions
1929         skipDraw = !bounds.intersect(this->asSurfaceProxy()->getBoundsRect());
1930     }
1931 
1932     if (skipDraw) {
1933         return;
1934     }
1935 
1936     GrClampType clampType = GrColorTypeClampType(this->colorInfo().colorType());
1937     GrProcessorSet::Analysis analysis = drawOp->finalize(*this->caps(), &appliedClip, clampType);
1938 
1939     const bool opUsesStencil = drawOp->usesStencil();
1940 
1941     // Always trigger DMSAA when there is stencil. This ensures stencil contents get properly
1942     // preserved between render passes, if needed.
1943     const bool drawNeedsMSAA = opUsesMSAA || (fCanUseDynamicMSAA && opUsesStencil);
1944 
1945     // Must be called before setDstProxyView so that it sees the final bounds of the op.
1946     op->setClippedBounds(bounds);
1947 
1948     // Determine if the Op will trigger the use of a separate DMSAA attachment that requires manual
1949     // resolves.
1950     // TODO: Currently usesAttachmentIfDMSAA checks if this is a textureProxy or not. This check is
1951     // really only for GL which uses a normal texture sampling when using barriers. For Vulkan it
1952     // is possible to use the msaa buffer as an input attachment even if this is not a texture.
1953     // However, support for that is not fully implemented yet in Vulkan. Once it is, this check
1954     // should change to a virtual caps check that returns whether we need to break up an OpsTask
1955     // if it has barriers and we are about to promote to MSAA.
1956     bool usesAttachmentIfDMSAA =
1957             fCanUseDynamicMSAA &&
1958             (!this->caps()->msaaResolvesAutomatically() || !this->asTextureProxy());
1959     bool opRequiresDMSAAAttachment = usesAttachmentIfDMSAA && drawNeedsMSAA;
1960     bool opTriggersDMSAAAttachment =
1961             opRequiresDMSAAAttachment && !this->getOpsTask()->usesMSAASurface();
1962     if (opTriggersDMSAAAttachment) {
1963         // This will be the op that actually triggers use of a DMSAA attachment. Texture barriers
1964         // can't be moved to a DMSAA attachment, so if there already are any on the current opsTask
1965         // then we need to split.
1966         if (this->getOpsTask()->renderPassXferBarriers() & GrXferBarrierFlags::kTexture) {
1967             SkASSERT(!this->getOpsTask()->isColorNoOp());
1968             this->replaceOpsTask()->setCannotMergeBackward();
1969         }
1970     }
1971 
1972     GrDstProxyView dstProxyView;
1973     if (analysis.requiresDstTexture()) {
1974         if (!this->setupDstProxyView(drawOp->bounds(), drawNeedsMSAA, &dstProxyView)) {
1975             return;
1976         }
1977 #ifdef SK_DEBUG
1978         if (fCanUseDynamicMSAA && drawNeedsMSAA && !this->caps()->msaaResolvesAutomatically()) {
1979             // Since we aren't literally writing to the render target texture while using a DMSAA
1980             // attachment, we need to resolve that texture before sampling it. Ensure the current
1981             // opsTask got closed off in order to initiate an implicit resolve.
1982             SkASSERT(this->getOpsTask()->isEmpty());
1983         }
1984 #endif
1985     }
1986 
1987     auto opsTask = this->getOpsTask();
1988     if (willAddFn) {
1989         willAddFn(op.get(), opsTask->uniqueID());
1990     }
1991 
1992     // Note if the op needs stencil. Stencil clipping already called setNeedsStencil for itself, if
1993     // needed.
1994     if (opUsesStencil) {
1995         this->setNeedsStencil();
1996     }
1997 
1998 #if GR_GPU_STATS && GR_TEST_UTILS
1999     if (fCanUseDynamicMSAA && drawNeedsMSAA) {
2000         if (!opsTask->usesMSAASurface()) {
2001             fContext->priv().dmsaaStats().fNumMultisampleRenderPasses++;
2002         }
2003         fContext->priv().dmsaaStats().fTriggerCounts[op->name()]++;
2004     }
2005 #endif
2006 
2007     opsTask->addDrawOp(this->drawingManager(), std::move(op), drawNeedsMSAA, analysis,
2008                        std::move(appliedClip), dstProxyView,
2009                        GrTextureResolveManager(this->drawingManager()), *this->caps());
2010 
2011 #ifdef SK_DEBUG
2012     if (fCanUseDynamicMSAA && drawNeedsMSAA) {
2013         SkASSERT(opsTask->usesMSAASurface());
2014     }
2015 #endif
2016 }
2017 
setupDstProxyView(const SkRect & opBounds,bool opRequiresMSAA,GrDstProxyView * dstProxyView)2018 bool SurfaceDrawContext::setupDstProxyView(const SkRect& opBounds,
2019                                            bool opRequiresMSAA,
2020                                            GrDstProxyView* dstProxyView) {
2021     // If we are wrapping a vulkan secondary command buffer, we can't make a dst copy because we
2022     // don't actually have a VkImage to make a copy of. Additionally we don't have the power to
2023     // start and stop the render pass in order to make the copy.
2024     if (this->asRenderTargetProxy()->wrapsVkSecondaryCB()) {
2025         return false;
2026     }
2027 
2028     // First get the dstSampleFlags as if we will put the draw into the current OpsTask
2029     auto dstSampleFlags = this->caps()->getDstSampleFlagsForProxy(
2030             this->asRenderTargetProxy(), this->getOpsTask()->usesMSAASurface() || opRequiresMSAA);
2031 
2032     // If we don't have barriers for this draw then we will definitely be breaking up the OpsTask.
2033     // However, if using dynamic MSAA, the new OpsTask will not have MSAA already enabled on it
2034     // and that may allow us to use texture barriers. So we check if we can use barriers on the new
2035     // ops task and then break it up if so.
2036     if (!(dstSampleFlags & GrDstSampleFlags::kRequiresTextureBarrier) &&
2037         fCanUseDynamicMSAA && this->getOpsTask()->usesMSAASurface() && !opRequiresMSAA) {
2038         auto newFlags =
2039                 this->caps()->getDstSampleFlagsForProxy(this->asRenderTargetProxy(),
2040                                                         false/*=opRequiresMSAA*/);
2041         if (newFlags & GrDstSampleFlags::kRequiresTextureBarrier) {
2042             // We can't have an empty ops task if we are in DMSAA and the ops task already returns
2043             // true for usesMSAASurface.
2044             SkASSERT(!this->getOpsTask()->isColorNoOp());
2045             this->replaceOpsTask()->setCannotMergeBackward();
2046             dstSampleFlags = newFlags;
2047         }
2048     }
2049 
2050     if (dstSampleFlags & GrDstSampleFlags::kRequiresTextureBarrier) {
2051         // If we require a barrier to sample the dst it means we are sampling the RT itself
2052         // either as a texture or input attachment. In this case we don't need to break up the
2053         // OpsTask.
2054         dstProxyView->setProxyView(this->readSurfaceView());
2055         dstProxyView->setOffset(0, 0);
2056         dstProxyView->setDstSampleFlags(dstSampleFlags);
2057         return true;
2058     }
2059     SkASSERT(dstSampleFlags == GrDstSampleFlags::kNone);
2060 
2061     // We are using a different surface from the main color attachment to sample the dst from. If we
2062     // are in DMSAA we can just use the single sampled RT texture itself. Otherwise, we must do a
2063     // copy.
2064     // We do have to check if we ended up here becasue we don't have texture barriers but do have
2065     // msaaResolvesAutomatically (i.e. render-to-msaa-texture). In that case there will be no op or
2066     // barrier between draws to flush the render target before being used as a texture in the next
2067     // draw. So in that case we just fall through to doing a copy.
2068     if (fCanUseDynamicMSAA && opRequiresMSAA && this->asTextureProxy() &&
2069         !this->caps()->msaaResolvesAutomatically() &&
2070         this->caps()->dmsaaResolveCanBeUsedAsTextureInSameRenderPass()) {
2071         this->replaceOpsTaskIfModifiesColor()->setCannotMergeBackward();
2072         dstProxyView->setProxyView(this->readSurfaceView());
2073         dstProxyView->setOffset(0, 0);
2074         dstProxyView->setDstSampleFlags(dstSampleFlags);
2075         return true;
2076     }
2077 
2078     // Now we fallback to doing a copy.
2079 
2080     GrColorType colorType = this->colorInfo().colorType();
2081     // MSAA consideration: When there is support for reading MSAA samples in the shader we could
2082     // have per-sample dst values by making the copy multisampled.
2083     GrCaps::DstCopyRestrictions restrictions = this->caps()->getDstCopyRestrictions(
2084             this->asRenderTargetProxy(), colorType);
2085 
2086     SkIRect copyRect = SkIRect::MakeSize(this->asSurfaceProxy()->backingStoreDimensions());
2087     if (!restrictions.fMustCopyWholeSrc) {
2088         // If we don't need the whole source, restrict to the op's bounds. We add an extra pixel
2089         // of padding to account for AA bloat and the unpredictable rounding of coords near pixel
2090         // centers during rasterization.
2091         SkIRect conservativeDrawBounds = opBounds.roundOut();
2092         conservativeDrawBounds.outset(1, 1);
2093         SkAssertResult(copyRect.intersect(conservativeDrawBounds));
2094     }
2095 
2096     SkIPoint dstOffset;
2097     SkBackingFit fit;
2098     if (restrictions.fRectsMustMatch == GrSurfaceProxy::RectsMustMatch::kYes) {
2099         dstOffset = {0, 0};
2100         fit = SkBackingFit::kExact;
2101     } else {
2102         dstOffset = {copyRect.fLeft, copyRect.fTop};
2103         fit = SkBackingFit::kApprox;
2104     }
2105     auto copy = GrSurfaceProxy::Copy(fContext,
2106                                      this->asSurfaceProxyRef(),
2107                                      this->origin(),
2108                                      GrMipmapped::kNo,
2109                                      copyRect,
2110                                      fit,
2111                                      SkBudgeted::kYes,
2112                                      restrictions.fRectsMustMatch);
2113     SkASSERT(copy);
2114 
2115     dstProxyView->setProxyView({std::move(copy), this->origin(), this->readSwizzle()});
2116     dstProxyView->setOffset(dstOffset);
2117     dstProxyView->setDstSampleFlags(dstSampleFlags);
2118     return true;
2119 }
2120 
replaceOpsTaskIfModifiesColor()2121 OpsTask* SurfaceDrawContext::replaceOpsTaskIfModifiesColor() {
2122     if (!this->getOpsTask()->isColorNoOp()) {
2123         this->replaceOpsTask();
2124     }
2125     return this->getOpsTask();
2126 }
2127 
2128 } // namespace skgpu::v1
2129