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