Debian Codegraph @

src/gpu/ganesh/SurfaceDrawContext.cpp

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