• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2019 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/ops/OpsTask.h"
9 
10 #include "include/gpu/GrRecordingContext.h"
11 #include "src/core/SkRectPriv.h"
12 #include "src/core/SkScopeExit.h"
13 #include "src/core/SkTraceEvent.h"
14 #include "src/gpu/GrAttachment.h"
15 #include "src/gpu/GrAuditTrail.h"
16 #include "src/gpu/GrCaps.h"
17 #include "src/gpu/GrGpu.h"
18 #include "src/gpu/GrMemoryPool.h"
19 #include "src/gpu/GrOpFlushState.h"
20 #include "src/gpu/GrOpsRenderPass.h"
21 #include "src/gpu/GrRecordingContextPriv.h"
22 #include "src/gpu/GrRenderTarget.h"
23 #include "src/gpu/GrResourceAllocator.h"
24 #include "src/gpu/GrResourceProvider.h"
25 #include "src/gpu/GrTexture.h"
26 #include "src/gpu/geometry/GrRect.h"
27 
28 ////////////////////////////////////////////////////////////////////////////////
29 
30 namespace {
31 
32 // Experimentally we have found that most combining occurs within the first 10 comparisons.
33 static const int kMaxOpMergeDistance = 10;
34 static const int kMaxOpChainDistance = 10;
35 
36 ////////////////////////////////////////////////////////////////////////////////
37 
can_reorder(const SkRect & a,const SkRect & b)38 inline bool can_reorder(const SkRect& a, const SkRect& b) { return !GrRectsOverlap(a, b); }
39 
create_render_pass(GrGpu * gpu,GrRenderTarget * rt,bool useMSAASurface,GrAttachment * stencil,GrSurfaceOrigin origin,const SkIRect & bounds,GrLoadOp colorLoadOp,const std::array<float,4> & loadClearColor,GrLoadOp stencilLoadOp,GrStoreOp stencilStoreOp,const SkTArray<GrSurfaceProxy *,true> & sampledProxies,GrXferBarrierFlags renderPassXferBarriers)40 GrOpsRenderPass* create_render_pass(GrGpu* gpu,
41                                     GrRenderTarget* rt,
42                                     bool useMSAASurface,
43                                     GrAttachment* stencil,
44                                     GrSurfaceOrigin origin,
45                                     const SkIRect& bounds,
46                                     GrLoadOp colorLoadOp,
47                                     const std::array<float, 4>& loadClearColor,
48                                     GrLoadOp stencilLoadOp,
49                                     GrStoreOp stencilStoreOp,
50                                     const SkTArray<GrSurfaceProxy*, true>& sampledProxies,
51                                     GrXferBarrierFlags renderPassXferBarriers) {
52     const GrOpsRenderPass::LoadAndStoreInfo kColorLoadStoreInfo {
53         colorLoadOp,
54         GrStoreOp::kStore,
55         loadClearColor
56     };
57 
58     // TODO:
59     // We would like to (at this level) only ever clear & discard. We would need
60     // to stop splitting up higher level OpsTasks for copyOps to achieve that.
61     // Note: we would still need SB loads and stores but they would happen at a
62     // lower level (inside the VK command buffer).
63     const GrOpsRenderPass::StencilLoadAndStoreInfo stencilLoadAndStoreInfo {
64         stencilLoadOp,
65         stencilStoreOp,
66     };
67 
68     return gpu->getOpsRenderPass(rt, useMSAASurface, stencil, origin, bounds, kColorLoadStoreInfo,
69                                  stencilLoadAndStoreInfo, sampledProxies, renderPassXferBarriers);
70 }
71 
72 } // anonymous namespace
73 
74 ////////////////////////////////////////////////////////////////////////////////
75 
76 namespace skgpu::v1 {
77 
List(GrOp::Owner op)78 inline OpsTask::OpChain::List::List(GrOp::Owner op)
79         : fHead(std::move(op)), fTail(fHead.get()) {
80     this->validate();
81 }
82 
List(List && that)83 inline OpsTask::OpChain::List::List(List&& that) { *this = std::move(that); }
84 
operator =(List && that)85 inline OpsTask::OpChain::List& OpsTask::OpChain::List::operator=(List&& that) {
86     fHead = std::move(that.fHead);
87     fTail = that.fTail;
88     that.fTail = nullptr;
89     this->validate();
90     return *this;
91 }
92 
popHead()93 inline GrOp::Owner OpsTask::OpChain::List::popHead() {
94     SkASSERT(fHead);
95     auto temp = fHead->cutChain();
96     std::swap(temp, fHead);
97     if (!fHead) {
98         SkASSERT(fTail == temp.get());
99         fTail = nullptr;
100     }
101     return temp;
102 }
103 
removeOp(GrOp * op)104 inline GrOp::Owner OpsTask::OpChain::List::removeOp(GrOp* op) {
105 #ifdef SK_DEBUG
106     auto head = op;
107     while (head->prevInChain()) { head = head->prevInChain(); }
108     SkASSERT(head == fHead.get());
109 #endif
110     auto prev = op->prevInChain();
111     if (!prev) {
112         SkASSERT(op == fHead.get());
113         return this->popHead();
114     }
115     auto temp = prev->cutChain();
116     if (auto next = temp->cutChain()) {
117         prev->chainConcat(std::move(next));
118     } else {
119         SkASSERT(fTail == op);
120         fTail = prev;
121     }
122     this->validate();
123     return temp;
124 }
125 
pushHead(GrOp::Owner op)126 inline void OpsTask::OpChain::List::pushHead(GrOp::Owner op) {
127     SkASSERT(op);
128     SkASSERT(op->isChainHead());
129     SkASSERT(op->isChainTail());
130     if (fHead) {
131         op->chainConcat(std::move(fHead));
132         fHead = std::move(op);
133     } else {
134         fHead = std::move(op);
135         fTail = fHead.get();
136     }
137 }
138 
pushTail(GrOp::Owner op)139 inline void OpsTask::OpChain::List::pushTail(GrOp::Owner op) {
140     SkASSERT(op->isChainTail());
141     fTail->chainConcat(std::move(op));
142     fTail = fTail->nextInChain();
143 }
144 
validate() const145 inline void OpsTask::OpChain::List::validate() const {
146 #ifdef SK_DEBUG
147     if (fHead) {
148         SkASSERT(fTail);
149         fHead->validateChain(fTail);
150     }
151 #endif
152 }
153 
154 ////////////////////////////////////////////////////////////////////////////////
155 
OpChain(GrOp::Owner op,GrProcessorSet::Analysis processorAnalysis,GrAppliedClip * appliedClip,const GrDstProxyView * dstProxyView)156 OpsTask::OpChain::OpChain(GrOp::Owner op, GrProcessorSet::Analysis processorAnalysis,
157                           GrAppliedClip* appliedClip, const GrDstProxyView* dstProxyView)
158         : fList{std::move(op)}
159         , fProcessorAnalysis(processorAnalysis)
160         , fAppliedClip(appliedClip) {
161     if (fProcessorAnalysis.requiresDstTexture()) {
162         SkASSERT(dstProxyView && dstProxyView->proxy());
163         fDstProxyView = *dstProxyView;
164     }
165     fBounds = fList.head()->bounds();
166 }
167 
visitProxies(const GrVisitProxyFunc & func) const168 void OpsTask::OpChain::visitProxies(const GrVisitProxyFunc& func) const {
169     if (fList.empty()) {
170         return;
171     }
172     for (const auto& op : GrOp::ChainRange<>(fList.head())) {
173         op.visitProxies(func);
174     }
175     if (fDstProxyView.proxy()) {
176         func(fDstProxyView.proxy(), GrMipmapped::kNo);
177     }
178     if (fAppliedClip) {
179         fAppliedClip->visitProxies(func);
180     }
181 }
182 
deleteOps()183 void OpsTask::OpChain::deleteOps() {
184     while (!fList.empty()) {
185         // Since the value goes out of scope immediately, the GrOp::Owner deletes the op.
186         fList.popHead();
187     }
188 }
189 
190 // Concatenates two op chains and attempts to merge ops across the chains. Assumes that we know that
191 // the two chains are chainable. Returns the new chain.
DoConcat(List chainA,List chainB,const GrCaps & caps,SkArenaAlloc * opsTaskArena,GrAuditTrail * auditTrail)192 OpsTask::OpChain::List OpsTask::OpChain::DoConcat(List chainA, List chainB, const GrCaps& caps,
193                                                   SkArenaAlloc* opsTaskArena,
194                                                   GrAuditTrail* auditTrail) {
195     // We process ops in chain b from head to tail. We attempt to merge with nodes in a, starting
196     // at chain a's tail and working toward the head. We produce one of the following outcomes:
197     // 1) b's head is merged into an op in a.
198     // 2) An op from chain a is merged into b's head. (In this case b's head gets processed again.)
199     // 3) b's head is popped from chain a and added at the tail of a.
200     // After result 3 we don't want to attempt to merge the next head of b with the new tail of a,
201     // as we assume merges were already attempted when chain b was created. So we keep track of the
202     // original tail of a and start our iteration of a there. We also track the bounds of the nodes
203     // appended to chain a that will be skipped for bounds testing. If the original tail of a is
204     // merged into an op in b (case 2) then we advance the "original tail" towards the head of a.
205     GrOp* origATail = chainA.tail();
206     SkRect skipBounds = SkRectPriv::MakeLargestInverted();
207     do {
208         int numMergeChecks = 0;
209         bool merged = false;
210         bool noSkip = (origATail == chainA.tail());
211         SkASSERT(noSkip == (skipBounds == SkRectPriv::MakeLargestInverted()));
212         bool canBackwardMerge = noSkip || can_reorder(chainB.head()->bounds(), skipBounds);
213         SkRect forwardMergeBounds = skipBounds;
214         GrOp* a = origATail;
215         while (a) {
216             bool canForwardMerge =
217                     (a == chainA.tail()) || can_reorder(a->bounds(), forwardMergeBounds);
218             if (canForwardMerge || canBackwardMerge) {
219                 auto result = a->combineIfPossible(chainB.head(), opsTaskArena, caps);
220                 SkASSERT(result != GrOp::CombineResult::kCannotCombine);
221                 merged = (result == GrOp::CombineResult::kMerged);
222                 GrOP_INFO("\t\t: (%s opID: %u) -> Combining with (%s, opID: %u)\n",
223                           chainB.head()->name(), chainB.head()->uniqueID(), a->name(),
224                           a->uniqueID());
225             }
226             if (merged) {
227                 GR_AUDIT_TRAIL_OPS_RESULT_COMBINED(auditTrail, a, chainB.head());
228                 if (canBackwardMerge) {
229                     // The GrOp::Owner releases the op.
230                     chainB.popHead();
231                 } else {
232                     // We merged the contents of b's head into a. We will replace b's head with a in
233                     // chain b.
234                     SkASSERT(canForwardMerge);
235                     if (a == origATail) {
236                         origATail = a->prevInChain();
237                     }
238                     GrOp::Owner detachedA = chainA.removeOp(a);
239                     // The GrOp::Owner releases the op.
240                     chainB.popHead();
241                     chainB.pushHead(std::move(detachedA));
242                     if (chainA.empty()) {
243                         // We merged all the nodes in chain a to chain b.
244                         return chainB;
245                     }
246                 }
247                 break;
248             } else {
249                 if (++numMergeChecks == kMaxOpMergeDistance) {
250                     break;
251                 }
252                 forwardMergeBounds.joinNonEmptyArg(a->bounds());
253                 canBackwardMerge =
254                         canBackwardMerge && can_reorder(chainB.head()->bounds(), a->bounds());
255                 a = a->prevInChain();
256             }
257         }
258         // If we weren't able to merge b's head then pop b's head from chain b and make it the new
259         // tail of a.
260         if (!merged) {
261             chainA.pushTail(chainB.popHead());
262             skipBounds.joinNonEmptyArg(chainA.tail()->bounds());
263         }
264     } while (!chainB.empty());
265     return chainA;
266 }
267 
268 // Attempts to concatenate the given chain onto our own and merge ops across the chains. Returns
269 // whether the operation succeeded. On success, the provided list will be returned empty.
tryConcat(List * list,GrProcessorSet::Analysis processorAnalysis,const GrDstProxyView & dstProxyView,const GrAppliedClip * appliedClip,const SkRect & bounds,const GrCaps & caps,SkArenaAlloc * opsTaskArena,GrAuditTrail * auditTrail)270 bool OpsTask::OpChain::tryConcat(
271         List* list, GrProcessorSet::Analysis processorAnalysis, const GrDstProxyView& dstProxyView,
272         const GrAppliedClip* appliedClip, const SkRect& bounds, const GrCaps& caps,
273         SkArenaAlloc* opsTaskArena, GrAuditTrail* auditTrail) {
274     SkASSERT(!fList.empty());
275     SkASSERT(!list->empty());
276     SkASSERT(fProcessorAnalysis.requiresDstTexture() == SkToBool(fDstProxyView.proxy()));
277     SkASSERT(processorAnalysis.requiresDstTexture() == SkToBool(dstProxyView.proxy()));
278     // All returns use explicit tuple constructor rather than {a, b} to work around old GCC bug.
279     if (fList.head()->classID() != list->head()->classID() ||
280         SkToBool(fAppliedClip) != SkToBool(appliedClip) ||
281         (fAppliedClip && *fAppliedClip != *appliedClip) ||
282         (fProcessorAnalysis.requiresNonOverlappingDraws() !=
283                 processorAnalysis.requiresNonOverlappingDraws()) ||
284         (fProcessorAnalysis.requiresNonOverlappingDraws() &&
285                 // Non-overlaping draws are only required when Ganesh will either insert a barrier,
286                 // or read back a new dst texture between draws. In either case, we can neither
287                 // chain nor combine overlapping Ops.
288                 GrRectsTouchOrOverlap(fBounds, bounds)) ||
289         (fProcessorAnalysis.requiresDstTexture() != processorAnalysis.requiresDstTexture()) ||
290         (fProcessorAnalysis.requiresDstTexture() && fDstProxyView != dstProxyView)) {
291         return false;
292     }
293 
294     SkDEBUGCODE(bool first = true;)
295     do {
296         switch (fList.tail()->combineIfPossible(list->head(), opsTaskArena, caps))
297         {
298             case GrOp::CombineResult::kCannotCombine:
299                 // If an op supports chaining then it is required that chaining is transitive and
300                 // that if any two ops in two different chains can merge then the two chains
301                 // may also be chained together. Thus, we should only hit this on the first
302                 // iteration.
303                 SkASSERT(first);
304                 return false;
305             case GrOp::CombineResult::kMayChain:
306                 fList = DoConcat(std::move(fList), std::exchange(*list, List()), caps, opsTaskArena,
307                                  auditTrail);
308                 // The above exchange cleared out 'list'. The list needs to be empty now for the
309                 // loop to terminate.
310                 SkASSERT(list->empty());
311                 break;
312             case GrOp::CombineResult::kMerged: {
313                 GrOP_INFO("\t\t: (%s opID: %u) -> Combining with (%s, opID: %u)\n",
314                           list->tail()->name(), list->tail()->uniqueID(), list->head()->name(),
315                           list->head()->uniqueID());
316                 GR_AUDIT_TRAIL_OPS_RESULT_COMBINED(auditTrail, fList.tail(), list->head());
317                 // The GrOp::Owner releases the op.
318                 list->popHead();
319                 break;
320             }
321         }
322         SkDEBUGCODE(first = false);
323     } while (!list->empty());
324 
325     // The new ops were successfully merged and/or chained onto our own.
326     fBounds.joinPossiblyEmptyRect(bounds);
327     return true;
328 }
329 
prependChain(OpChain * that,const GrCaps & caps,SkArenaAlloc * opsTaskArena,GrAuditTrail * auditTrail)330 bool OpsTask::OpChain::prependChain(OpChain* that, const GrCaps& caps, SkArenaAlloc* opsTaskArena,
331                                     GrAuditTrail* auditTrail) {
332     if (!that->tryConcat(&fList, fProcessorAnalysis, fDstProxyView, fAppliedClip, fBounds, caps,
333                          opsTaskArena, auditTrail)) {
334         this->validate();
335         // append failed
336         return false;
337     }
338 
339     // 'that' owns the combined chain. Move it into 'this'.
340     SkASSERT(fList.empty());
341     fList = std::move(that->fList);
342     fBounds = that->fBounds;
343 
344     that->fDstProxyView.setProxyView({});
345     if (that->fAppliedClip && that->fAppliedClip->hasCoverageFragmentProcessor()) {
346         // Obliterates the processor.
347         that->fAppliedClip->detachCoverageFragmentProcessor();
348     }
349     this->validate();
350     return true;
351 }
352 
appendOp(GrOp::Owner op,GrProcessorSet::Analysis processorAnalysis,const GrDstProxyView * dstProxyView,const GrAppliedClip * appliedClip,const GrCaps & caps,SkArenaAlloc * opsTaskArena,GrAuditTrail * auditTrail)353 GrOp::Owner OpsTask::OpChain::appendOp(
354         GrOp::Owner op, GrProcessorSet::Analysis processorAnalysis,
355         const GrDstProxyView* dstProxyView, const GrAppliedClip* appliedClip, const GrCaps& caps,
356         SkArenaAlloc* opsTaskArena, GrAuditTrail* auditTrail) {
357     const GrDstProxyView noDstProxyView;
358     if (!dstProxyView) {
359         dstProxyView = &noDstProxyView;
360     }
361     SkASSERT(op->isChainHead() && op->isChainTail());
362     SkRect opBounds = op->bounds();
363     List chain(std::move(op));
364     if (!this->tryConcat(&chain, processorAnalysis, *dstProxyView, appliedClip, opBounds, caps,
365                          opsTaskArena, auditTrail)) {
366         // append failed, give the op back to the caller.
367         this->validate();
368         return chain.popHead();
369     }
370 
371     SkASSERT(chain.empty());
372     this->validate();
373     return nullptr;
374 }
375 
validate() const376 inline void OpsTask::OpChain::validate() const {
377 #ifdef SK_DEBUG
378     fList.validate();
379     for (const auto& op : GrOp::ChainRange<>(fList.head())) {
380         // Not using SkRect::contains because we allow empty rects.
381         SkASSERT(fBounds.fLeft <= op.bounds().fLeft && fBounds.fTop <= op.bounds().fTop &&
382                  fBounds.fRight >= op.bounds().fRight && fBounds.fBottom >= op.bounds().fBottom);
383     }
384 #endif
385 }
386 
387 ////////////////////////////////////////////////////////////////////////////////
388 
OpsTask(GrDrawingManager * drawingMgr,GrSurfaceProxyView view,GrAuditTrail * auditTrail,sk_sp<GrArenas> arenas)389 OpsTask::OpsTask(GrDrawingManager* drawingMgr,
390                  GrSurfaceProxyView view,
391                  GrAuditTrail* auditTrail,
392                  sk_sp<GrArenas> arenas)
393         : GrRenderTask()
394         , fAuditTrail(auditTrail)
395         , fUsesMSAASurface(view.asRenderTargetProxy()->numSamples() > 1)
396         , fTargetSwizzle(view.swizzle())
397         , fTargetOrigin(view.origin())
398         , fArenas{std::move(arenas)}
399           SkDEBUGCODE(, fNumClips(0)) {
400     this->addTarget(drawingMgr, view.detachProxy());
401 }
402 
deleteOps()403 void OpsTask::deleteOps() {
404     for (auto& chain : fOpChains) {
405         chain.deleteOps();
406     }
407     fOpChains.reset();
408 }
409 
~OpsTask()410 OpsTask::~OpsTask() {
411     this->deleteOps();
412 }
413 
addOp(GrDrawingManager * drawingMgr,GrOp::Owner op,GrTextureResolveManager textureResolveManager,const GrCaps & caps)414 void OpsTask::addOp(GrDrawingManager* drawingMgr, GrOp::Owner op,
415                     GrTextureResolveManager textureResolveManager, const GrCaps& caps) {
416     auto addDependency = [&](GrSurfaceProxy* p, GrMipmapped mipmapped) {
417         this->addDependency(drawingMgr, p, mipmapped, textureResolveManager, caps);
418     };
419 
420     op->visitProxies(addDependency);
421 
422     this->recordOp(std::move(op), false/*usesMSAA*/, GrProcessorSet::EmptySetAnalysis(), nullptr,
423                    nullptr, caps);
424 }
425 
addDrawOp(GrDrawingManager * drawingMgr,GrOp::Owner op,bool usesMSAA,const GrProcessorSet::Analysis & processorAnalysis,GrAppliedClip && clip,const GrDstProxyView & dstProxyView,GrTextureResolveManager textureResolveManager,const GrCaps & caps)426 void OpsTask::addDrawOp(GrDrawingManager* drawingMgr, GrOp::Owner op, bool usesMSAA,
427                         const GrProcessorSet::Analysis& processorAnalysis, GrAppliedClip&& clip,
428                         const GrDstProxyView& dstProxyView,
429                         GrTextureResolveManager textureResolveManager, const GrCaps& caps) {
430 #ifdef SKIA_OHOS
431     if (UNLIKELY(SkOHOSDebugLevelTraceUtil::getEnableDebugTrace()) && drawingMgr) {
432         drawingMgr->increaseDrawOpNum();
433     }
434 #endif
435     auto addDependency = [&](GrSurfaceProxy* p, GrMipmapped mipmapped) {
436         this->addSampledTexture(p);
437         this->addDependency(drawingMgr, p, mipmapped, textureResolveManager, caps);
438     };
439 
440     op->visitProxies(addDependency);
441     clip.visitProxies(addDependency);
442     if (dstProxyView.proxy()) {
443         if (!(dstProxyView.dstSampleFlags() & GrDstSampleFlags::kAsInputAttachment)) {
444             this->addSampledTexture(dstProxyView.proxy());
445         }
446         if (dstProxyView.dstSampleFlags() & GrDstSampleFlags::kRequiresTextureBarrier) {
447             fRenderPassXferBarriers |= GrXferBarrierFlags::kTexture;
448         }
449         addDependency(dstProxyView.proxy(), GrMipmapped::kNo);
450         SkASSERT(!(dstProxyView.dstSampleFlags() & GrDstSampleFlags::kAsInputAttachment) ||
451                  dstProxyView.offset().isZero());
452     }
453 
454     if (processorAnalysis.usesNonCoherentHWBlending()) {
455         fRenderPassXferBarriers |= GrXferBarrierFlags::kBlend;
456     }
457 
458     this->recordOp(std::move(op), usesMSAA, processorAnalysis, clip.doesClip() ? &clip : nullptr,
459                    &dstProxyView, caps);
460 }
461 
endFlush(GrDrawingManager * drawingMgr)462 void OpsTask::endFlush(GrDrawingManager* drawingMgr) {
463     fLastClipStackGenID = SK_InvalidUniqueID;
464     this->deleteOps();
465 
466     fDeferredProxies.reset();
467     fSampledProxies.reset();
468     fAuditTrail = nullptr;
469 #ifdef SKIA_OHOS
470     fNumOpChainsExecuted = 0;
471 #endif
472 
473     GrRenderTask::endFlush(drawingMgr);
474 }
475 
onPrePrepare(GrRecordingContext * context)476 void OpsTask::onPrePrepare(GrRecordingContext* context) {
477     SkASSERT(this->isClosed());
478     // TODO: remove the check for discard here once reduced op splitting is turned on. Currently we
479     // can end up with OpsTasks that only have a discard load op and no ops. For vulkan validation
480     // we need to keep that discard and not drop it. Once we have reduce op list splitting enabled
481     // we shouldn't end up with OpsTasks with only discard.
482     if (this->isColorNoOp() ||
483         (fClippedContentBounds.isEmpty() && fColorLoadOp != GrLoadOp::kDiscard)) {
484         return;
485     }
486     TRACE_EVENT0("skia.gpu", TRACE_FUNC);
487 
488     GrSurfaceProxyView dstView(sk_ref_sp(this->target(0)), fTargetOrigin, fTargetSwizzle);
489     for (const auto& chain : fOpChains) {
490         if (chain.shouldExecute()) {
491             chain.head()->prePrepare(context,
492                                      dstView,
493                                      chain.appliedClip(),
494                                      chain.dstProxyView(),
495                                      fRenderPassXferBarriers,
496                                      fColorLoadOp);
497         }
498     }
499 }
500 
onPrepare(GrOpFlushState * flushState)501 void OpsTask::onPrepare(GrOpFlushState* flushState) {
502     SkASSERT(this->target(0)->peekRenderTarget());
503     SkASSERT(this->isClosed());
504     // TODO: remove the check for discard here once reduced op splitting is turned on. Currently we
505     // can end up with OpsTasks that only have a discard load op and no ops. For vulkan validation
506     // we need to keep that discard and not drop it. Once we have reduce op list splitting enabled
507     // we shouldn't end up with OpsTasks with only discard.
508     if (this->isColorNoOp() ||
509         (fClippedContentBounds.isEmpty() && fColorLoadOp != GrLoadOp::kDiscard)) {
510         return;
511     }
512     TRACE_EVENT0("skia.gpu", TRACE_FUNC);
513 #ifdef SK_ENABLE_STENCIL_CULLING_OHOS
514     fDisableStencilCulling = flushState->fDisableStencilCulling;
515     fHasStencilCullingOp = flushState->fHasStencilCullingOp;
516 #endif
517     flushState->setSampledProxyArray(&fSampledProxies);
518     GrSurfaceProxyView dstView(sk_ref_sp(this->target(0)), fTargetOrigin, fTargetSwizzle);
519     auto grGpu = flushState->gpu();
520     // Loop over the ops that haven't yet been prepared.
521     GrGpuResourceTag tag;
522     for (const auto& chain : fOpChains) {
523         if (chain.shouldExecute()) {
524 #ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
525             TRACE_EVENT0("skia.gpu", chain.head()->name());
526 #endif
527             tag = chain.head()->getGrOpTag();
528             if (grGpu && tag.isGrTagValid()) {
529                 grGpu->setCurrentGrResourceTag(tag);
530             }
531             GrOpFlushState::OpArgs opArgs(chain.head(),
532                                           dstView,
533                                           fUsesMSAASurface,
534                                           chain.appliedClip(),
535                                           chain.dstProxyView(),
536                                           fRenderPassXferBarriers,
537                                           fColorLoadOp);
538 
539             flushState->setOpArgs(&opArgs);
540 
541             // Temporary debugging helper: for debugging prePrepare w/o going through DDLs
542             // Delete once most of the GrOps have an onPrePrepare.
543             // chain.head()->prePrepare(flushState->gpu()->getContext(), &this->target(0),
544             //                          chain.appliedClip());
545 
546             // GrOp::prePrepare may or may not have been called at this point
547             chain.head()->prepare(flushState);
548             flushState->setOpArgs(nullptr);
549             if (grGpu && tag.isGrTagValid()) {
550                 grGpu->popGrResourceTag();
551             }
552         }
553     }
554     flushState->setSampledProxyArray(nullptr);
555 }
556 
557 // TODO: this is where GrOp::renderTarget is used (which is fine since it
558 // is at flush time). However, we need to store the RenderTargetProxy in the
559 // Ops and instantiate them here.
onExecute(GrOpFlushState * flushState)560 bool OpsTask::onExecute(GrOpFlushState* flushState) {
561     SkASSERT(this->numTargets() == 1);
562     GrRenderTargetProxy* proxy = this->target(0)->asRenderTargetProxy();
563     SkASSERT(proxy);
564     SK_AT_SCOPE_EXIT(proxy->clearArenas());
565 
566     // TODO: remove the check for discard here once reduced op splitting is turned on. Currently we
567     // can end up with OpsTasks that only have a discard load op and no ops. For vulkan validation
568     // we need to keep that discard and not drop it. Once we have reduce op list splitting enabled
569     // we shouldn't end up with OpsTasks with only discard.
570     if (this->isColorNoOp() ||
571         (fClippedContentBounds.isEmpty() && fColorLoadOp != GrLoadOp::kDiscard)) {
572         return false;
573     }
574 
575     TRACE_EVENT0("skia.gpu", TRACE_FUNC);
576 
577     // Make sure load ops are not kClear if the GPU needs to use draws for clears
578     SkASSERT(fColorLoadOp != GrLoadOp::kClear ||
579              !flushState->gpu()->caps()->performColorClearsAsDraws());
580 
581     const GrCaps& caps = *flushState->gpu()->caps();
582     GrRenderTarget* renderTarget = proxy->peekRenderTarget();
583     SkASSERT(renderTarget);
584 
585     GrAttachment* stencil = nullptr;
586     if (proxy->needsStencil()) {
587         SkASSERT(proxy->canUseStencil(caps));
588         if (!flushState->resourceProvider()->attachStencilAttachment(renderTarget,
589                                                                      fUsesMSAASurface)) {
590             SkDebugf("WARNING: failed to attach a stencil buffer. Rendering will be skipped.\n");
591             return false;
592         }
593         stencil = renderTarget->getStencilAttachment(fUsesMSAASurface);
594     }
595 
596     GrLoadOp stencilLoadOp;
597     switch (fInitialStencilContent) {
598         case StencilContent::kDontCare:
599             stencilLoadOp = GrLoadOp::kDiscard;
600             break;
601         case StencilContent::kUserBitsCleared:
602             SkASSERT(!caps.performStencilClearsAsDraws());
603             SkASSERT(stencil);
604             if (caps.discardStencilValuesAfterRenderPass()) {
605                 // Always clear the stencil if it is being discarded after render passes. This is
606                 // also an optimization because we are on a tiler and it avoids loading the values
607                 // from memory.
608                 stencilLoadOp = GrLoadOp::kClear;
609                 break;
610             }
611             if (!stencil->hasPerformedInitialClear()) {
612                 stencilLoadOp = GrLoadOp::kClear;
613                 stencil->markHasPerformedInitialClear();
614                 break;
615             }
616             // SurfaceDrawContexts are required to leave the user stencil bits in a cleared state
617             // once finished, meaning the stencil values will always remain cleared after the
618             // initial clear. Just fall through to reloading the existing (cleared) stencil values
619             // from memory.
620             [[fallthrough]];
621         case StencilContent::kPreserved:
622             SkASSERT(stencil);
623             stencilLoadOp = GrLoadOp::kLoad;
624             break;
625     }
626 
627     // NOTE: If fMustPreserveStencil is set, then we are executing a surfaceDrawContext that split
628     // its opsTask.
629     //
630     // FIXME: We don't currently flag render passes that don't use stencil at all. In that case
631     // their store op might be "discard", and we currently make the assumption that a discard will
632     // not invalidate what's already in main memory. This is probably ok for now, but certainly
633     // something we want to address soon.
634     GrStoreOp stencilStoreOp = (caps.discardStencilValuesAfterRenderPass() && !fMustPreserveStencil)
635             ? GrStoreOp::kDiscard
636             : GrStoreOp::kStore;
637 #ifdef SK_ENABLE_STENCIL_CULLING_OHOS
638     if (!fDisableStencilCulling && fHasStencilCullingOp) {
639         TRACE_EVENT0("skia.gpu", "StencilCullingOpt Load/Store opt");
640         stencilLoadOp = GrLoadOp::kDiscard;
641         stencilStoreOp = GrStoreOp::kDiscard;
642     }
643 #endif
644     GrOpsRenderPass* renderPass = create_render_pass(flushState->gpu(),
645                                                      proxy->peekRenderTarget(),
646                                                      fUsesMSAASurface,
647                                                      stencil,
648                                                      fTargetOrigin,
649                                                      fClippedContentBounds,
650                                                      fColorLoadOp,
651                                                      fLoadClearColor,
652                                                      stencilLoadOp,
653                                                      stencilStoreOp,
654                                                      fSampledProxies,
655                                                      fRenderPassXferBarriers);
656 
657     if (!renderPass) {
658         return false;
659     }
660     flushState->setOpsRenderPass(renderPass);
661     renderPass->begin();
662 
663     GrSurfaceProxyView dstView(sk_ref_sp(this->target(0)), fTargetOrigin, fTargetSwizzle);
664 
665     auto grGpu = flushState->gpu();
666     // Draw all the generated geometry.
667     GrGpuResourceTag tag;
668     for (const auto& chain : fOpChains) {
669         if (!chain.shouldExecute()) {
670             continue;
671         }
672 #ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
673         TRACE_EVENT0("skia.gpu", chain.head()->name());
674 #endif
675 #ifdef SKIA_OHOS
676         fNumOpChainsExecuted++;
677 #endif
678         tag = chain.head()->getGrOpTag();
679             if (grGpu && tag.isGrTagValid()) {
680                 grGpu->setCurrentGrResourceTag(tag);
681             }
682 
683         GrOpFlushState::OpArgs opArgs(chain.head(),
684                                       dstView,
685                                       fUsesMSAASurface,
686                                       chain.appliedClip(),
687                                       chain.dstProxyView(),
688                                       fRenderPassXferBarriers,
689                                       fColorLoadOp);
690 
691         flushState->setOpArgs(&opArgs);
692         chain.head()->execute(flushState, chain.bounds());
693         flushState->setOpArgs(nullptr);
694         if (grGpu && tag.isGrTagValid()) {
695                 grGpu->popGrResourceTag();
696             }
697     }
698 
699     renderPass->end();
700     flushState->gpu()->submit(renderPass);
701     flushState->setOpsRenderPass(nullptr);
702 
703     return true;
704 }
705 
setColorLoadOp(GrLoadOp op,std::array<float,4> color)706 void OpsTask::setColorLoadOp(GrLoadOp op, std::array<float, 4> color) {
707     fColorLoadOp = op;
708     fLoadClearColor = color;
709     if (GrLoadOp::kClear == fColorLoadOp) {
710         GrSurfaceProxy* proxy = this->target(0);
711         SkASSERT(proxy);
712         fTotalBounds = proxy->backingStoreBoundsRect();
713     }
714 }
715 
reset()716 void OpsTask::reset() {
717     fDeferredProxies.reset();
718     fSampledProxies.reset();
719     fClippedContentBounds = SkIRect::MakeEmpty();
720     fTotalBounds = SkRect::MakeEmpty();
721     this->deleteOps();
722     fRenderPassXferBarriers = GrXferBarrierFlags::kNone;
723 }
724 
canMerge(const OpsTask * opsTask) const725 bool OpsTask::canMerge(const OpsTask* opsTask) const {
726     return this->target(0) == opsTask->target(0) &&
727            fArenas == opsTask->fArenas &&
728            !opsTask->fCannotMergeBackward;
729 }
730 
mergeFrom(SkSpan<const sk_sp<GrRenderTask>> tasks)731 int OpsTask::mergeFrom(SkSpan<const sk_sp<GrRenderTask>> tasks) {
732     int mergedCount = 0;
733     for (const sk_sp<GrRenderTask>& task : tasks) {
734         auto opsTask = task->asOpsTask();
735         if (!opsTask || !this->canMerge(opsTask)) {
736             break;
737         }
738         SkASSERT(fTargetSwizzle == opsTask->fTargetSwizzle);
739         SkASSERT(fTargetOrigin == opsTask->fTargetOrigin);
740         if (GrLoadOp::kClear == opsTask->fColorLoadOp) {
741             // TODO(11903): Go back to actually dropping ops tasks when we are merged with
742             // color clear.
743             return 0;
744         }
745         mergedCount += 1;
746     }
747     if (0 == mergedCount) {
748         return 0;
749     }
750 
751     SkSpan<const sk_sp<OpsTask>> mergingNodes(
752             reinterpret_cast<const sk_sp<OpsTask>*>(tasks.data()), SkToSizeT(mergedCount));
753     int addlDeferredProxyCount = 0;
754     int addlProxyCount = 0;
755     int addlOpChainCount = 0;
756     for (const auto& toMerge : mergingNodes) {
757         addlDeferredProxyCount += toMerge->fDeferredProxies.count();
758         addlProxyCount += toMerge->fSampledProxies.count();
759         addlOpChainCount += toMerge->fOpChains.count();
760         fClippedContentBounds.join(toMerge->fClippedContentBounds);
761         fTotalBounds.join(toMerge->fTotalBounds);
762         fRenderPassXferBarriers |= toMerge->fRenderPassXferBarriers;
763         if (fInitialStencilContent == StencilContent::kDontCare) {
764             // Propogate the first stencil content that isn't kDontCare.
765             //
766             // Once the stencil has any kind of initial content that isn't kDontCare, then the
767             // inital contents of subsequent opsTasks that get merged in don't matter.
768             //
769             // (This works because the opsTask all target the same render target and are in
770             // painter's order. kPreserved obviously happens automatically with a merge, and kClear
771             // is also automatic because the contract is for ops to leave the stencil buffer in a
772             // cleared state when finished.)
773             fInitialStencilContent = toMerge->fInitialStencilContent;
774         }
775         fUsesMSAASurface |= toMerge->fUsesMSAASurface;
776         SkDEBUGCODE(fNumClips += toMerge->fNumClips);
777     }
778 
779     fLastClipStackGenID = SK_InvalidUniqueID;
780     fDeferredProxies.reserve_back(addlDeferredProxyCount);
781     fSampledProxies.reserve_back(addlProxyCount);
782     fOpChains.reserve_back(addlOpChainCount);
783     for (const auto& toMerge : mergingNodes) {
784         for (GrRenderTask* renderTask : toMerge->dependents()) {
785             renderTask->replaceDependency(toMerge.get(), this);
786         }
787         for (GrRenderTask* renderTask : toMerge->dependencies()) {
788             renderTask->replaceDependent(toMerge.get(), this);
789         }
790         fDeferredProxies.move_back_n(toMerge->fDeferredProxies.count(),
791                                      toMerge->fDeferredProxies.data());
792         fSampledProxies.move_back_n(toMerge->fSampledProxies.count(),
793                                     toMerge->fSampledProxies.data());
794         fOpChains.move_back_n(toMerge->fOpChains.count(),
795                               toMerge->fOpChains.data());
796         toMerge->fDeferredProxies.reset();
797         toMerge->fSampledProxies.reset();
798         toMerge->fOpChains.reset();
799     }
800     fMustPreserveStencil = mergingNodes.back()->fMustPreserveStencil;
801     return mergedCount;
802 }
803 
resetForFullscreenClear(CanDiscardPreviousOps canDiscardPreviousOps)804 bool OpsTask::resetForFullscreenClear(CanDiscardPreviousOps canDiscardPreviousOps) {
805     if (CanDiscardPreviousOps::kYes == canDiscardPreviousOps || this->isEmpty()) {
806         this->deleteOps();
807         fDeferredProxies.reset();
808         fSampledProxies.reset();
809 
810         // If the opsTask is using a render target which wraps a vulkan command buffer, we can't do
811         // a clear load since we cannot change the render pass that we are using. Thus we fall back
812         // to making a clear op in this case.
813         return !this->target(0)->asRenderTargetProxy()->wrapsVkSecondaryCB();
814     }
815 
816     // Could not empty the task, so an op must be added to handle the clear
817     return false;
818 }
819 
discard()820 void OpsTask::discard() {
821     // Discard calls to in-progress opsTasks are ignored. Calls at the start update the
822     // opsTasks' color & stencil load ops.
823     if (this->isEmpty()) {
824         fColorLoadOp = GrLoadOp::kDiscard;
825         fInitialStencilContent = StencilContent::kDontCare;
826         fTotalBounds.setEmpty();
827     }
828 }
829 
830 ////////////////////////////////////////////////////////////////////////////////
831 
832 #if GR_TEST_UTILS
dump(const SkString & label,SkString indent,bool printDependencies,bool close) const833 void OpsTask::dump(const SkString& label,
834                    SkString indent,
835                    bool printDependencies,
836                    bool close) const {
837     GrRenderTask::dump(label, indent, printDependencies, false);
838 
839     SkDebugf("%sfColorLoadOp: ", indent.c_str());
840     switch (fColorLoadOp) {
841         case GrLoadOp::kLoad:
842             SkDebugf("kLoad\n");
843             break;
844         case GrLoadOp::kClear:
845             SkDebugf("kClear {%g, %g, %g, %g}\n",
846                      fLoadClearColor[0],
847                      fLoadClearColor[1],
848                      fLoadClearColor[2],
849                      fLoadClearColor[3]);
850             break;
851         case GrLoadOp::kDiscard:
852             SkDebugf("kDiscard\n");
853             break;
854     }
855 
856     SkDebugf("%sfInitialStencilContent: ", indent.c_str());
857     switch (fInitialStencilContent) {
858         case StencilContent::kDontCare:
859             SkDebugf("kDontCare\n");
860             break;
861         case StencilContent::kUserBitsCleared:
862             SkDebugf("kUserBitsCleared\n");
863             break;
864         case StencilContent::kPreserved:
865             SkDebugf("kPreserved\n");
866             break;
867     }
868 
869     SkDebugf("%s%d ops:\n", indent.c_str(), fOpChains.count());
870     for (int i = 0; i < fOpChains.count(); ++i) {
871         SkDebugf("%s*******************************\n", indent.c_str());
872         if (!fOpChains[i].head()) {
873             SkDebugf("%s%d: <combined forward or failed instantiation>\n", indent.c_str(), i);
874         } else {
875             SkDebugf("%s%d: %s\n", indent.c_str(), i, fOpChains[i].head()->name());
876             SkRect bounds = fOpChains[i].bounds();
877             SkDebugf("%sClippedBounds: [L: %.2f, T: %.2f, R: %.2f, B: %.2f]\n",
878                      indent.c_str(),
879                      bounds.fLeft, bounds.fTop, bounds.fRight, bounds.fBottom);
880             for (const auto& op : GrOp::ChainRange<>(fOpChains[i].head())) {
881                 SkString info = SkTabString(op.dumpInfo(), 1);
882                 SkDebugf("%s%s\n", indent.c_str(), info.c_str());
883                 bounds = op.bounds();
884                 SkDebugf("%s\tClippedBounds: [L: %.2f, T: %.2f, R: %.2f, B: %.2f]\n",
885                          indent.c_str(),
886                          bounds.fLeft, bounds.fTop, bounds.fRight, bounds.fBottom);
887             }
888         }
889     }
890 
891     if (close) {
892         SkDebugf("%s--------------------------------------------------------------\n\n",
893                  indent.c_str());
894     }
895 }
896 #endif
897 
898 #ifdef SK_DEBUG
visitProxies_debugOnly(const GrVisitProxyFunc & func) const899 void OpsTask::visitProxies_debugOnly(const GrVisitProxyFunc& func) const {
900     auto textureFunc = [ func ] (GrSurfaceProxy* tex, GrMipmapped mipmapped) {
901         func(tex, mipmapped);
902     };
903 
904     for (const OpChain& chain : fOpChains) {
905         chain.visitProxies(textureFunc);
906     }
907 }
908 
909 #endif
910 
911 ////////////////////////////////////////////////////////////////////////////////
912 
onMakeSkippable()913 void OpsTask::onMakeSkippable() {
914     this->deleteOps();
915     fDeferredProxies.reset();
916     fColorLoadOp = GrLoadOp::kLoad;
917     SkASSERT(this->isColorNoOp());
918 }
919 
onIsUsed(GrSurfaceProxy * proxyToCheck) const920 bool OpsTask::onIsUsed(GrSurfaceProxy* proxyToCheck) const {
921     bool used = false;
922     for (GrSurfaceProxy* proxy : fSampledProxies) {
923         if (proxy == proxyToCheck) {
924             used = true;
925             break;
926         }
927     }
928 #ifdef SK_DEBUG
929     bool usedSlow = false;
930     auto visit = [ proxyToCheck, &usedSlow ] (GrSurfaceProxy* p, GrMipmapped) {
931         if (p == proxyToCheck) {
932             usedSlow = true;
933         }
934     };
935     this->visitProxies_debugOnly(visit);
936     SkASSERT(used == usedSlow);
937 #endif
938 
939     return used;
940 }
941 
gatherProxyIntervals(GrResourceAllocator * alloc) const942 void OpsTask::gatherProxyIntervals(GrResourceAllocator* alloc) const {
943     SkASSERT(this->isClosed());
944     if (this->isColorNoOp()) {
945         return;
946     }
947 
948     for (int i = 0; i < fDeferredProxies.count(); ++i) {
949         SkASSERT(!fDeferredProxies[i]->isInstantiated());
950         // We give all the deferred proxies a write usage at the very start of flushing. This
951         // locks them out of being reused for the entire flush until they are read - and then
952         // they can be recycled. This is a bit unfortunate because a flush can proceed in waves
953         // with sub-flushes. The deferred proxies only need to be pinned from the start of
954         // the sub-flush in which they appear.
955         alloc->addInterval(fDeferredProxies[i], 0, 0, GrResourceAllocator::ActualUse::kNo);
956     }
957 
958     GrSurfaceProxy* targetProxy = this->target(0);
959 
960     // Add the interval for all the writes to this OpsTasks's target
961     if (fOpChains.count()) {
962         unsigned int cur = alloc->curOp();
963 
964         alloc->addInterval(targetProxy, cur, cur + fOpChains.count() - 1,
965                            GrResourceAllocator::ActualUse::kYes);
966     } else {
967         // This can happen if there is a loadOp (e.g., a clear) but no other draws. In this case we
968         // still need to add an interval for the destination so we create a fake op# for
969         // the missing clear op.
970         alloc->addInterval(targetProxy, alloc->curOp(), alloc->curOp(),
971                            GrResourceAllocator::ActualUse::kYes);
972         alloc->incOps();
973     }
974 
975     auto gather = [ alloc SkDEBUGCODE(, this) ] (GrSurfaceProxy* p, GrMipmapped) {
976         alloc->addInterval(p,
977                            alloc->curOp(),
978                            alloc->curOp(),
979                            GrResourceAllocator::ActualUse::kYes
980                            SkDEBUGCODE(, this->target(0) == p));
981     };
982     // TODO: visitProxies is expensive. Can we do this with fSampledProxies instead?
983     for (const OpChain& recordedOp : fOpChains) {
984         recordedOp.visitProxies(gather);
985 
986         // Even though the op may have been (re)moved we still need to increment the op count to
987         // keep all the math consistent.
988         alloc->incOps();
989     }
990 }
991 
recordOp(GrOp::Owner op,bool usesMSAA,GrProcessorSet::Analysis processorAnalysis,GrAppliedClip * clip,const GrDstProxyView * dstProxyView,const GrCaps & caps)992 void OpsTask::recordOp(
993         GrOp::Owner op, bool usesMSAA, GrProcessorSet::Analysis processorAnalysis,
994         GrAppliedClip* clip, const GrDstProxyView* dstProxyView, const GrCaps& caps) {
995     GrSurfaceProxy* proxy = this->target(0);
996 #ifdef SK_DEBUG
997     op->validate();
998     SkASSERT(processorAnalysis.requiresDstTexture() == (dstProxyView && dstProxyView->proxy()));
999     SkASSERT(proxy);
1000     // A closed OpsTask should never receive new/more ops
1001     SkASSERT(!this->isClosed());
1002     // Ensure we can support dynamic msaa if the caller is trying to trigger it.
1003     if (proxy->asRenderTargetProxy()->numSamples() == 1 && usesMSAA) {
1004         SkASSERT(caps.supportsDynamicMSAA(proxy->asRenderTargetProxy()));
1005     }
1006 #endif
1007 
1008     if (!op->bounds().isFinite()) {
1009         return;
1010     }
1011 
1012     fUsesMSAASurface |= usesMSAA;
1013 
1014     // Account for this op's bounds before we attempt to combine.
1015     // NOTE: The caller should have already called "op->setClippedBounds()" by now, if applicable.
1016     fTotalBounds.join(op->bounds());
1017 
1018     // Check if there is an op we can combine with by linearly searching back until we either
1019     // 1) check every op
1020     // 2) intersect with something
1021     // 3) find a 'blocker'
1022     GR_AUDIT_TRAIL_ADD_OP(fAuditTrail, op.get(), proxy->uniqueID());
1023     GrOP_INFO("opsTask: %d Recording (%s, opID: %u)\n"
1024               "\tBounds [L: %.2f, T: %.2f R: %.2f B: %.2f]\n",
1025                this->uniqueID(),
1026                op->name(),
1027                op->uniqueID(),
1028                op->bounds().fLeft, op->bounds().fTop,
1029                op->bounds().fRight, op->bounds().fBottom);
1030     GrOP_INFO(SkTabString(op->dumpInfo(), 1).c_str());
1031     GrOP_INFO("\tOutcome:\n");
1032     int maxCandidates = std::min(kMaxOpChainDistance, fOpChains.count());
1033     if (maxCandidates) {
1034         int i = 0;
1035         while (true) {
1036             OpChain& candidate = fOpChains.fromBack(i);
1037             op = candidate.appendOp(std::move(op), processorAnalysis, dstProxyView, clip, caps,
1038                                     fArenas->arenaAlloc(), fAuditTrail);
1039             if (!op) {
1040                 return;
1041             }
1042             // Stop going backwards if we would cause a painter's order violation.
1043             if (!can_reorder(candidate.bounds(), op->bounds())) {
1044                 GrOP_INFO("\t\tBackward: Intersects with chain (%s, head opID: %u)\n",
1045                           candidate.head()->name(), candidate.head()->uniqueID());
1046                 break;
1047             }
1048             if (++i == maxCandidates) {
1049                 GrOP_INFO("\t\tBackward: Reached max lookback or beginning of op array %d\n", i);
1050                 break;
1051             }
1052         }
1053     } else {
1054         GrOP_INFO("\t\tBackward: FirstOp\n");
1055     }
1056     if (clip) {
1057         clip = fArenas->arenaAlloc()->make<GrAppliedClip>(std::move(*clip));
1058         SkDEBUGCODE(fNumClips++;)
1059     }
1060     fOpChains.emplace_back(std::move(op), processorAnalysis, clip, dstProxyView);
1061 }
1062 
forwardCombine(const GrCaps & caps)1063 void OpsTask::forwardCombine(const GrCaps& caps) {
1064     SkASSERT(!this->isClosed());
1065     GrOP_INFO("opsTask: %d ForwardCombine %d ops:\n", this->uniqueID(), fOpChains.count());
1066 
1067     for (int i = 0; i < fOpChains.count() - 1; ++i) {
1068         OpChain& chain = fOpChains[i];
1069         int maxCandidateIdx = std::min(i + kMaxOpChainDistance, fOpChains.count() - 1);
1070         int j = i + 1;
1071         while (true) {
1072             OpChain& candidate = fOpChains[j];
1073             if (candidate.prependChain(&chain, caps, fArenas->arenaAlloc(), fAuditTrail)) {
1074                 break;
1075             }
1076             // Stop traversing if we would cause a painter's order violation.
1077             if (!can_reorder(chain.bounds(), candidate.bounds())) {
1078                 GrOP_INFO(
1079                         "\t\t%d: chain (%s head opID: %u) -> "
1080                         "Intersects with chain (%s, head opID: %u)\n",
1081                         i, chain.head()->name(), chain.head()->uniqueID(), candidate.head()->name(),
1082                         candidate.head()->uniqueID());
1083                 break;
1084             }
1085             if (++j > maxCandidateIdx) {
1086                 GrOP_INFO("\t\t%d: chain (%s opID: %u) -> Reached max lookahead or end of array\n",
1087                           i, chain.head()->name(), chain.head()->uniqueID());
1088                 break;
1089             }
1090         }
1091     }
1092 }
1093 
onMakeClosed(GrRecordingContext * rContext,SkIRect * targetUpdateBounds)1094 GrRenderTask::ExpectedOutcome OpsTask::onMakeClosed(GrRecordingContext* rContext,
1095                                                     SkIRect* targetUpdateBounds) {
1096     this->forwardCombine(*rContext->priv().caps());
1097     if (!this->isColorNoOp()) {
1098         GrSurfaceProxy* proxy = this->target(0);
1099         // Use the entire backing store bounds since the GPU doesn't clip automatically to the
1100         // logical dimensions.
1101         SkRect clippedContentBounds = proxy->backingStoreBoundsRect();
1102         // TODO: If we can fix up GLPrograms test to always intersect the target proxy bounds
1103         // then we can simply assert here that the bounds intersect.
1104         if (clippedContentBounds.intersect(fTotalBounds)) {
1105             clippedContentBounds.roundOut(&fClippedContentBounds);
1106             *targetUpdateBounds = GrNativeRect::MakeIRectRelativeTo(
1107                     fTargetOrigin,
1108                     this->target(0)->backingStoreDimensions().height(),
1109                     fClippedContentBounds);
1110             return ExpectedOutcome::kTargetDirty;
1111         }
1112     }
1113     return ExpectedOutcome::kTargetUnchanged;
1114 }
1115 
1116 } // namespace skgpu::v1
1117