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