• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2010 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 "GrRenderTargetOpList.h"
9 #include "GrAuditTrail.h"
10 #include "GrCaps.h"
11 #include "GrGpu.h"
12 #include "GrGpuCommandBuffer.h"
13 #include "GrMemoryPool.h"
14 #include "GrRect.h"
15 #include "GrRenderTargetContext.h"
16 #include "GrResourceAllocator.h"
17 #include "SkExchange.h"
18 #include "SkRectPriv.h"
19 #include "SkTraceEvent.h"
20 #include "ops/GrClearOp.h"
21 #include "ops/GrCopySurfaceOp.h"
22 
23 ////////////////////////////////////////////////////////////////////////////////
24 
25 // Experimentally we have found that most combining occurs within the first 10 comparisons.
26 static const int kMaxOpMergeDistance = 10;
27 static const int kMaxOpChainDistance = 10;
28 
29 ////////////////////////////////////////////////////////////////////////////////
30 
31 using DstProxy = GrXferProcessor::DstProxy;
32 
33 ////////////////////////////////////////////////////////////////////////////////
34 
can_reorder(const SkRect & a,const SkRect & b)35 static inline bool can_reorder(const SkRect& a, const SkRect& b) { return !GrRectsOverlap(a, b); }
36 
37 ////////////////////////////////////////////////////////////////////////////////
38 
List(std::unique_ptr<GrOp> op)39 inline GrRenderTargetOpList::OpChain::List::List(std::unique_ptr<GrOp> op)
40         : fHead(std::move(op)), fTail(fHead.get()) {
41     this->validate();
42 }
43 
List(List && that)44 inline GrRenderTargetOpList::OpChain::List::List(List&& that) { *this = std::move(that); }
45 
operator =(List && that)46 inline GrRenderTargetOpList::OpChain::List& GrRenderTargetOpList::OpChain::List::operator=(
47         List&& that) {
48     fHead = std::move(that.fHead);
49     fTail = that.fTail;
50     that.fTail = nullptr;
51     this->validate();
52     return *this;
53 }
54 
popHead()55 inline std::unique_ptr<GrOp> GrRenderTargetOpList::OpChain::List::popHead() {
56     SkASSERT(fHead);
57     auto temp = fHead->cutChain();
58     std::swap(temp, fHead);
59     if (!fHead) {
60         SkASSERT(fTail == temp.get());
61         fTail = nullptr;
62     }
63     return temp;
64 }
65 
removeOp(GrOp * op)66 inline std::unique_ptr<GrOp> GrRenderTargetOpList::OpChain::List::removeOp(GrOp* op) {
67 #ifdef SK_DEBUG
68     auto head = op;
69     while (head->prevInChain()) { head = head->prevInChain(); }
70     SkASSERT(head == fHead.get());
71 #endif
72     auto prev = op->prevInChain();
73     if (!prev) {
74         SkASSERT(op == fHead.get());
75         return this->popHead();
76     }
77     auto temp = prev->cutChain();
78     if (auto next = temp->cutChain()) {
79         prev->chainConcat(std::move(next));
80     } else {
81         SkASSERT(fTail == op);
82         fTail = prev;
83     }
84     this->validate();
85     return temp;
86 }
87 
pushHead(std::unique_ptr<GrOp> op)88 inline void GrRenderTargetOpList::OpChain::List::pushHead(std::unique_ptr<GrOp> op) {
89     SkASSERT(op);
90     SkASSERT(op->isChainHead());
91     SkASSERT(op->isChainTail());
92     if (fHead) {
93         op->chainConcat(std::move(fHead));
94         fHead = std::move(op);
95     } else {
96         fHead = std::move(op);
97         fTail = fHead.get();
98     }
99 }
100 
pushTail(std::unique_ptr<GrOp> op)101 inline void GrRenderTargetOpList::OpChain::List::pushTail(std::unique_ptr<GrOp> op) {
102     SkASSERT(op->isChainTail());
103     fTail->chainConcat(std::move(op));
104     fTail = fTail->nextInChain();
105 }
106 
validate() const107 inline void GrRenderTargetOpList::OpChain::List::validate() const {
108 #ifdef SK_DEBUG
109     if (fHead) {
110         SkASSERT(fTail);
111         fHead->validateChain(fTail);
112     }
113 #endif
114 }
115 
116 ////////////////////////////////////////////////////////////////////////////////
117 
OpChain(std::unique_ptr<GrOp> op,GrProcessorSet::Analysis processorAnalysis,GrAppliedClip * appliedClip,const DstProxy * dstProxy)118 GrRenderTargetOpList::OpChain::OpChain(std::unique_ptr<GrOp> op,
119                                        GrProcessorSet::Analysis processorAnalysis,
120                                        GrAppliedClip* appliedClip, const DstProxy* dstProxy)
121         : fList{std::move(op)}
122         , fProcessorAnalysis(processorAnalysis)
123         , fAppliedClip(appliedClip) {
124     if (fProcessorAnalysis.requiresDstTexture()) {
125         SkASSERT(dstProxy && dstProxy->proxy());
126         fDstProxy = *dstProxy;
127     }
128     fBounds = fList.head()->bounds();
129 }
130 
visitProxies(const GrOp::VisitProxyFunc & func,GrOp::VisitorType visitor) const131 void GrRenderTargetOpList::OpChain::visitProxies(const GrOp::VisitProxyFunc& func,
132                                                  GrOp::VisitorType visitor) const {
133     if (fList.empty()) {
134         return;
135     }
136     for (const auto& op : GrOp::ChainRange<>(fList.head())) {
137         op.visitProxies(func, visitor);
138     }
139     if (fDstProxy.proxy()) {
140         func(fDstProxy.proxy());
141     }
142     if (fAppliedClip) {
143         fAppliedClip->visitProxies(func);
144     }
145 }
146 
deleteOps(GrOpMemoryPool * pool)147 void GrRenderTargetOpList::OpChain::deleteOps(GrOpMemoryPool* pool) {
148     while (!fList.empty()) {
149         pool->release(fList.popHead());
150     }
151 }
152 
153 // Concatenates two op chains and attempts to merge ops across the chains. Assumes that we know that
154 // the two chains are chainable. Returns the new chain.
DoConcat(List chainA,List chainB,const GrCaps & caps,GrOpMemoryPool * pool,GrAuditTrail * auditTrail)155 GrRenderTargetOpList::OpChain::List GrRenderTargetOpList::OpChain::DoConcat(
156         List chainA, List chainB, const GrCaps& caps, GrOpMemoryPool* pool,
157         GrAuditTrail* auditTrail) {
158     // We process ops in chain b from head to tail. We attempt to merge with nodes in a, starting
159     // at chain a's tail and working toward the head. We produce one of the following outcomes:
160     // 1) b's head is merged into an op in a.
161     // 2) An op from chain a is merged into b's head. (In this case b's head gets processed again.)
162     // 3) b's head is popped from chain a and added at the tail of a.
163     // After result 3 we don't want to attempt to merge the next head of b with the new tail of a,
164     // as we assume merges were already attempted when chain b was created. So we keep track of the
165     // original tail of a and start our iteration of a there. We also track the bounds of the nodes
166     // appended to chain a that will be skipped for bounds testing. If the original tail of a is
167     // merged into an op in b (case 2) then we advance the "original tail" towards the head of a.
168     GrOp* origATail = chainA.tail();
169     SkRect skipBounds = SkRectPriv::MakeLargestInverted();
170     do {
171         int numMergeChecks = 0;
172         bool merged = false;
173         bool noSkip = (origATail == chainA.tail());
174         SkASSERT(noSkip == (skipBounds == SkRectPriv::MakeLargestInverted()));
175         bool canBackwardMerge = noSkip || can_reorder(chainB.head()->bounds(), skipBounds);
176         SkRect forwardMergeBounds = skipBounds;
177         GrOp* a = origATail;
178         while (a) {
179             bool canForwardMerge =
180                     (a == chainA.tail()) || can_reorder(a->bounds(), forwardMergeBounds);
181             if (canForwardMerge || canBackwardMerge) {
182                 auto result = a->combineIfPossible(chainB.head(), caps);
183                 SkASSERT(result != GrOp::CombineResult::kCannotCombine);
184                 merged = (result == GrOp::CombineResult::kMerged);
185                 GrOP_INFO("\t\t: (%s opID: %u) -> Combining with (%s, opID: %u)\n",
186                           chainB.head()->name(), chainB.head()->uniqueID(), a->name(),
187                           a->uniqueID());
188             }
189             if (merged) {
190                 GR_AUDIT_TRAIL_OPS_RESULT_COMBINED(auditTrail, a, chainB.head());
191                 if (canBackwardMerge) {
192                     pool->release(chainB.popHead());
193                 } else {
194                     // We merged the contents of b's head into a. We will replace b's head with a in
195                     // chain b.
196                     SkASSERT(canForwardMerge);
197                     if (a == origATail) {
198                         origATail = a->prevInChain();
199                     }
200                     std::unique_ptr<GrOp> detachedA = chainA.removeOp(a);
201                     pool->release(chainB.popHead());
202                     chainB.pushHead(std::move(detachedA));
203                     if (chainA.empty()) {
204                         // We merged all the nodes in chain a to chain b.
205                         return chainB;
206                     }
207                 }
208                 break;
209             } else {
210                 if (++numMergeChecks == kMaxOpMergeDistance) {
211                     break;
212                 }
213                 forwardMergeBounds.joinNonEmptyArg(a->bounds());
214                 canBackwardMerge =
215                         canBackwardMerge && can_reorder(chainB.head()->bounds(), a->bounds());
216                 a = a->prevInChain();
217             }
218         }
219         // If we weren't able to merge b's head then pop b's head from chain b and make it the new
220         // tail of a.
221         if (!merged) {
222             chainA.pushTail(chainB.popHead());
223             skipBounds.joinNonEmptyArg(chainA.tail()->bounds());
224         }
225     } while (!chainB.empty());
226     return chainA;
227 }
228 
229 // Attempts to concatenate the given chain onto our own and merge ops across the chains. Returns
230 // whether the operation succeeded. On success, the provided list will be returned empty.
tryConcat(List * list,GrProcessorSet::Analysis processorAnalysis,const DstProxy & dstProxy,const GrAppliedClip * appliedClip,const SkRect & bounds,const GrCaps & caps,GrOpMemoryPool * pool,GrAuditTrail * auditTrail)231 bool GrRenderTargetOpList::OpChain::tryConcat(
232         List* list, GrProcessorSet::Analysis processorAnalysis, const DstProxy& dstProxy,
233         const GrAppliedClip* appliedClip, const SkRect& bounds, const GrCaps& caps,
234         GrOpMemoryPool* pool, GrAuditTrail* auditTrail) {
235     SkASSERT(!fList.empty());
236     SkASSERT(!list->empty());
237     SkASSERT(fProcessorAnalysis.requiresDstTexture() == SkToBool(fDstProxy.proxy()));
238     SkASSERT(processorAnalysis.requiresDstTexture() == SkToBool(dstProxy.proxy()));
239     // All returns use explicit tuple constructor rather than {a, b} to work around old GCC bug.
240     if (fList.head()->classID() != list->head()->classID() ||
241         SkToBool(fAppliedClip) != SkToBool(appliedClip) ||
242         (fAppliedClip && *fAppliedClip != *appliedClip) ||
243         (fProcessorAnalysis.requiresNonOverlappingDraws() !=
244                 processorAnalysis.requiresNonOverlappingDraws()) ||
245         (fProcessorAnalysis.requiresNonOverlappingDraws() &&
246                 // Non-overlaping draws are only required when Ganesh will either insert a barrier,
247                 // or read back a new dst texture between draws. In either case, we can neither
248                 // chain nor combine overlapping Ops.
249                 GrRectsTouchOrOverlap(fBounds, bounds)) ||
250         (fProcessorAnalysis.requiresDstTexture() != processorAnalysis.requiresDstTexture()) ||
251         (fProcessorAnalysis.requiresDstTexture() && fDstProxy != dstProxy)) {
252         return false;
253     }
254 
255     SkDEBUGCODE(bool first = true;)
256     do {
257         switch (fList.tail()->combineIfPossible(list->head(), caps)) {
258             case GrOp::CombineResult::kCannotCombine:
259                 // If an op supports chaining then it is required that chaining is transitive and
260                 // that if any two ops in two different chains can merge then the two chains
261                 // may also be chained together. Thus, we should only hit this on the first
262                 // iteration.
263                 SkASSERT(first);
264                 return false;
265             case GrOp::CombineResult::kMayChain:
266                 fList = DoConcat(std::move(fList), skstd::exchange(*list, List()), caps, pool,
267                                  auditTrail);
268                 // The above exchange cleared out 'list'. The list needs to be empty now for the
269                 // loop to terminate.
270                 SkASSERT(list->empty());
271                 break;
272             case GrOp::CombineResult::kMerged: {
273                 GrOP_INFO("\t\t: (%s opID: %u) -> Combining with (%s, opID: %u)\n",
274                           list->tail()->name(), list->tail()->uniqueID(), list->head()->name(),
275                           list->head()->uniqueID());
276                 GR_AUDIT_TRAIL_OPS_RESULT_COMBINED(auditTrail, fList.tail(), list->head());
277                 pool->release(list->popHead());
278                 break;
279             }
280         }
281         SkDEBUGCODE(first = false);
282     } while (!list->empty());
283 
284     // The new ops were successfully merged and/or chained onto our own.
285     fBounds.joinPossiblyEmptyRect(bounds);
286     return true;
287 }
288 
prependChain(OpChain * that,const GrCaps & caps,GrOpMemoryPool * pool,GrAuditTrail * auditTrail)289 bool GrRenderTargetOpList::OpChain::prependChain(OpChain* that, const GrCaps& caps,
290                                                  GrOpMemoryPool* pool, GrAuditTrail* auditTrail) {
291     if (!that->tryConcat(
292             &fList, fProcessorAnalysis, fDstProxy, fAppliedClip, fBounds, caps, pool, auditTrail)) {
293         this->validate();
294         // append failed
295         return false;
296     }
297 
298     // 'that' owns the combined chain. Move it into 'this'.
299     SkASSERT(fList.empty());
300     fList = std::move(that->fList);
301     fBounds = that->fBounds;
302 
303     that->fDstProxy.setProxy(nullptr);
304     if (that->fAppliedClip) {
305         for (int i = 0; i < that->fAppliedClip->numClipCoverageFragmentProcessors(); ++i) {
306             that->fAppliedClip->detachClipCoverageFragmentProcessor(i);
307         }
308     }
309     this->validate();
310     return true;
311 }
312 
appendOp(std::unique_ptr<GrOp> op,GrProcessorSet::Analysis processorAnalysis,const DstProxy * dstProxy,const GrAppliedClip * appliedClip,const GrCaps & caps,GrOpMemoryPool * pool,GrAuditTrail * auditTrail)313 std::unique_ptr<GrOp> GrRenderTargetOpList::OpChain::appendOp(
314         std::unique_ptr<GrOp> op, GrProcessorSet::Analysis processorAnalysis,
315         const DstProxy* dstProxy, const GrAppliedClip* appliedClip, const GrCaps& caps,
316         GrOpMemoryPool* pool, GrAuditTrail* auditTrail) {
317     const GrXferProcessor::DstProxy noDstProxy;
318     if (!dstProxy) {
319         dstProxy = &noDstProxy;
320     }
321     SkASSERT(op->isChainHead() && op->isChainTail());
322     SkRect opBounds = op->bounds();
323     List chain(std::move(op));
324     if (!this->tryConcat(
325             &chain, processorAnalysis, *dstProxy, appliedClip, opBounds, caps, pool, auditTrail)) {
326         // append failed, give the op back to the caller.
327         this->validate();
328         return chain.popHead();
329     }
330 
331     SkASSERT(chain.empty());
332     this->validate();
333     return nullptr;
334 }
335 
validate() const336 inline void GrRenderTargetOpList::OpChain::validate() const {
337 #ifdef SK_DEBUG
338     fList.validate();
339     for (const auto& op : GrOp::ChainRange<>(fList.head())) {
340         // Not using SkRect::contains because we allow empty rects.
341         SkASSERT(fBounds.fLeft <= op.bounds().fLeft && fBounds.fTop <= op.bounds().fTop &&
342                  fBounds.fRight >= op.bounds().fRight && fBounds.fBottom >= op.bounds().fBottom);
343     }
344 #endif
345 }
346 
347 ////////////////////////////////////////////////////////////////////////////////
348 
GrRenderTargetOpList(GrResourceProvider * resourceProvider,sk_sp<GrOpMemoryPool> opMemoryPool,GrRenderTargetProxy * proxy,GrAuditTrail * auditTrail)349 GrRenderTargetOpList::GrRenderTargetOpList(GrResourceProvider* resourceProvider,
350                                            sk_sp<GrOpMemoryPool> opMemoryPool,
351                                            GrRenderTargetProxy* proxy,
352                                            GrAuditTrail* auditTrail)
353         : INHERITED(resourceProvider, std::move(opMemoryPool), proxy, auditTrail)
354         , fLastClipStackGenID(SK_InvalidUniqueID)
355         SkDEBUGCODE(, fNumClips(0)) {
356 }
357 
deleteOps()358 void GrRenderTargetOpList::deleteOps() {
359     for (auto& chain : fOpChains) {
360         chain.deleteOps(fOpMemoryPool.get());
361     }
362     fOpChains.reset();
363 }
364 
~GrRenderTargetOpList()365 GrRenderTargetOpList::~GrRenderTargetOpList() {
366     this->deleteOps();
367 }
368 
369 ////////////////////////////////////////////////////////////////////////////////
370 
371 #ifdef SK_DEBUG
dump(bool printDependencies) const372 void GrRenderTargetOpList::dump(bool printDependencies) const {
373     INHERITED::dump(printDependencies);
374 
375     SkDebugf("ops (%d):\n", fOpChains.count());
376     for (int i = 0; i < fOpChains.count(); ++i) {
377         SkDebugf("*******************************\n");
378         if (!fOpChains[i].head()) {
379             SkDebugf("%d: <combined forward or failed instantiation>\n", i);
380         } else {
381             SkDebugf("%d: %s\n", i, fOpChains[i].head()->name());
382             SkRect bounds = fOpChains[i].bounds();
383             SkDebugf("ClippedBounds: [L: %.2f, T: %.2f, R: %.2f, B: %.2f]\n", bounds.fLeft,
384                      bounds.fTop, bounds.fRight, bounds.fBottom);
385             for (const auto& op : GrOp::ChainRange<>(fOpChains[i].head())) {
386                 SkString info = SkTabString(op.dumpInfo(), 1);
387                 SkDebugf("%s\n", info.c_str());
388                 bounds = op.bounds();
389                 SkDebugf("\tClippedBounds: [L: %.2f, T: %.2f, R: %.2f, B: %.2f]\n", bounds.fLeft,
390                          bounds.fTop, bounds.fRight, bounds.fBottom);
391             }
392         }
393     }
394 }
395 
visitProxies_debugOnly(const GrOp::VisitProxyFunc & func) const396 void GrRenderTargetOpList::visitProxies_debugOnly(const GrOp::VisitProxyFunc& func) const {
397     for (const OpChain& chain : fOpChains) {
398         chain.visitProxies(func, GrOp::VisitorType::kOther);
399     }
400 }
401 
402 #endif
403 
onPrepare(GrOpFlushState * flushState)404 void GrRenderTargetOpList::onPrepare(GrOpFlushState* flushState) {
405     SkASSERT(fTarget.get()->peekRenderTarget());
406     SkASSERT(this->isClosed());
407 #ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
408     TRACE_EVENT0("skia", TRACE_FUNC);
409 #endif
410 
411     // Loop over the ops that haven't yet been prepared.
412     for (const auto& chain : fOpChains) {
413         if (chain.head()) {
414 #ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
415             TRACE_EVENT0("skia", chain.head()->name());
416 #endif
417             GrOpFlushState::OpArgs opArgs = {
418                 chain.head(),
419                 fTarget.get()->asRenderTargetProxy(),
420                 chain.appliedClip(),
421                 chain.dstProxy()
422             };
423             flushState->setOpArgs(&opArgs);
424             chain.head()->prepare(flushState);
425             flushState->setOpArgs(nullptr);
426         }
427     }
428 }
429 
create_command_buffer(GrGpu * gpu,GrRenderTarget * rt,GrSurfaceOrigin origin,const SkRect & bounds,GrLoadOp colorLoadOp,const SkPMColor4f & loadClearColor,GrLoadOp stencilLoadOp)430 static GrGpuRTCommandBuffer* create_command_buffer(GrGpu* gpu,
431                                                    GrRenderTarget* rt,
432                                                    GrSurfaceOrigin origin,
433                                                    const SkRect& bounds,
434                                                    GrLoadOp colorLoadOp,
435                                                    const SkPMColor4f& loadClearColor,
436                                                    GrLoadOp stencilLoadOp) {
437     const GrGpuRTCommandBuffer::LoadAndStoreInfo kColorLoadStoreInfo {
438         colorLoadOp,
439         GrStoreOp::kStore,
440         loadClearColor
441     };
442 
443     // TODO:
444     // We would like to (at this level) only ever clear & discard. We would need
445     // to stop splitting up higher level opLists for copyOps to achieve that.
446     // Note: we would still need SB loads and stores but they would happen at a
447     // lower level (inside the VK command buffer).
448     const GrGpuRTCommandBuffer::StencilLoadAndStoreInfo stencilLoadAndStoreInfo {
449         stencilLoadOp,
450         GrStoreOp::kStore,
451     };
452 
453     return gpu->getCommandBuffer(rt, origin, bounds, kColorLoadStoreInfo, stencilLoadAndStoreInfo);
454 }
455 
456 // TODO: this is where GrOp::renderTarget is used (which is fine since it
457 // is at flush time). However, we need to store the RenderTargetProxy in the
458 // Ops and instantiate them here.
onExecute(GrOpFlushState * flushState)459 bool GrRenderTargetOpList::onExecute(GrOpFlushState* flushState) {
460     // TODO: Forcing the execution of the discard here isn't ideal since it will cause us to do a
461     // discard and then store the data back in memory so that the load op on future draws doesn't
462     // think the memory is unitialized. Ideally we would want a system where we are tracking whether
463     // the proxy itself has valid data or not, and then use that as a signal on whether we should be
464     // loading or discarding. In that world we wouldni;t need to worry about executing oplists with
465     // no ops just to do a discard.
466     if (fOpChains.empty() && GrLoadOp::kClear != fColorLoadOp &&
467         GrLoadOp::kDiscard != fColorLoadOp) {
468         return false;
469     }
470 
471     SkASSERT(fTarget.get()->peekRenderTarget());
472     TRACE_EVENT0("skia", TRACE_FUNC);
473 
474     // TODO: at the very least, we want the stencil store op to always be discard (at this
475     // level). In Vulkan, sub-command buffers would still need to load & store the stencil buffer.
476 
477     // Make sure load ops are not kClear if the GPU needs to use draws for clears
478     SkASSERT(fColorLoadOp != GrLoadOp::kClear ||
479              !flushState->gpu()->caps()->performColorClearsAsDraws());
480     SkASSERT(fStencilLoadOp != GrLoadOp::kClear ||
481              !flushState->gpu()->caps()->performStencilClearsAsDraws());
482     GrGpuRTCommandBuffer* commandBuffer = create_command_buffer(
483                                                     flushState->gpu(),
484                                                     fTarget.get()->peekRenderTarget(),
485                                                     fTarget.get()->origin(),
486                                                     fTarget.get()->getBoundsRect(),
487                                                     fColorLoadOp,
488                                                     fLoadClearColor,
489                                                     fStencilLoadOp);
490     flushState->setCommandBuffer(commandBuffer);
491     commandBuffer->begin();
492 
493     // Draw all the generated geometry.
494     for (const auto& chain : fOpChains) {
495         if (!chain.head()) {
496             continue;
497         }
498 #ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
499         TRACE_EVENT0("skia", chain.head()->name());
500 #endif
501 
502         GrOpFlushState::OpArgs opArgs {
503             chain.head(),
504             fTarget.get()->asRenderTargetProxy(),
505             chain.appliedClip(),
506             chain.dstProxy()
507         };
508 
509         flushState->setOpArgs(&opArgs);
510         chain.head()->execute(flushState, chain.bounds());
511         flushState->setOpArgs(nullptr);
512     }
513 
514     commandBuffer->end();
515     flushState->gpu()->submit(commandBuffer);
516     flushState->setCommandBuffer(nullptr);
517 
518     return true;
519 }
520 
endFlush()521 void GrRenderTargetOpList::endFlush() {
522     fLastClipStackGenID = SK_InvalidUniqueID;
523     this->deleteOps();
524     fClipAllocator.reset();
525     INHERITED::endFlush();
526 }
527 
discard()528 void GrRenderTargetOpList::discard() {
529     // Discard calls to in-progress opLists are ignored. Calls at the start update the
530     // opLists' color & stencil load ops.
531     if (this->isEmpty()) {
532         fColorLoadOp = GrLoadOp::kDiscard;
533         fStencilLoadOp = GrLoadOp::kDiscard;
534     }
535 }
536 
setStencilLoadOp(GrLoadOp op)537 void GrRenderTargetOpList::setStencilLoadOp(GrLoadOp op) {
538     fStencilLoadOp = op;
539 }
540 
setColorLoadOp(GrLoadOp op,const SkPMColor4f & color)541 void GrRenderTargetOpList::setColorLoadOp(GrLoadOp op, const SkPMColor4f& color) {
542     fColorLoadOp = op;
543     fLoadClearColor = color;
544 }
545 
resetForFullscreenClear()546 bool GrRenderTargetOpList::resetForFullscreenClear() {
547     // Mark the color load op as discard (this may be followed by a clearColorOnLoad call to make
548     // the load op kClear, or it may be followed by an explicit op). In the event of an absClear()
549     // after a regular clear(), we could end up with a clear load op and a real clear op in the list
550     // if the load op were not reset here.
551     fColorLoadOp = GrLoadOp::kDiscard;
552 
553     // Regardless of how the clear is implemented (native clear or a fullscreen quad), all prior ops
554     // would be overwritten, so discard them entirely. The one exception is if the opList is marked
555     // as needing a stencil buffer then there may be a prior op that writes to the stencil buffer.
556     // Although the clear will ignore the stencil buffer, following draw ops may not so we can't get
557     // rid of all the preceding ops. Beware! If we ever add any ops that have a side effect beyond
558     // modifying the stencil buffer we will need a more elaborate tracking system (skbug.com/7002).
559     if (this->isEmpty() || !fTarget.get()->asRenderTargetProxy()->needsStencil()) {
560         this->deleteOps();
561         fDeferredProxies.reset();
562 
563         // If the opList is using a render target which wraps a vulkan command buffer, we can't do a
564         // clear load since we cannot change the render pass that we are using. Thus we fall back to
565         // making a clear op in this case.
566         return !fTarget.get()->asRenderTargetProxy()->wrapsVkSecondaryCB();
567     }
568 
569     // Could not empty the list, so an op must be added to handle the clear
570     return false;
571 }
572 
573 ////////////////////////////////////////////////////////////////////////////////
574 
575 // This closely parallels GrTextureOpList::copySurface but renderTargetOpLists
576 // also store the applied clip and dest proxy with the op
copySurface(GrContext * context,GrSurfaceProxy * dst,GrSurfaceProxy * src,const SkIRect & srcRect,const SkIPoint & dstPoint)577 bool GrRenderTargetOpList::copySurface(GrContext* context,
578                                        GrSurfaceProxy* dst,
579                                        GrSurfaceProxy* src,
580                                        const SkIRect& srcRect,
581                                        const SkIPoint& dstPoint) {
582     SkASSERT(dst->asRenderTargetProxy() == fTarget.get());
583     std::unique_ptr<GrOp> op = GrCopySurfaceOp::Make(context, dst, src, srcRect, dstPoint);
584     if (!op) {
585         return false;
586     }
587 
588     this->addOp(std::move(op), *context->contextPriv().caps());
589     return true;
590 }
591 
purgeOpsWithUninstantiatedProxies()592 void GrRenderTargetOpList::purgeOpsWithUninstantiatedProxies() {
593     bool hasUninstantiatedProxy = false;
594     auto checkInstantiation = [&hasUninstantiatedProxy](GrSurfaceProxy* p) {
595         if (!p->isInstantiated()) {
596             hasUninstantiatedProxy = true;
597         }
598     };
599     for (OpChain& recordedOp : fOpChains) {
600         hasUninstantiatedProxy = false;
601         recordedOp.visitProxies(checkInstantiation, GrOp::VisitorType::kOther);
602         if (hasUninstantiatedProxy) {
603             // When instantiation of the proxy fails we drop the Op
604             recordedOp.deleteOps(fOpMemoryPool.get());
605         }
606     }
607 }
608 
gatherProxyIntervals(GrResourceAllocator * alloc) const609 void GrRenderTargetOpList::gatherProxyIntervals(GrResourceAllocator* alloc) const {
610     unsigned int cur = alloc->numOps();
611 
612     for (int i = 0; i < fDeferredProxies.count(); ++i) {
613         SkASSERT(!fDeferredProxies[i]->isInstantiated());
614         // We give all the deferred proxies a write usage at the very start of flushing. This
615         // locks them out of being reused for the entire flush until they are read - and then
616         // they can be recycled. This is a bit unfortunate because a flush can proceed in waves
617         // with sub-flushes. The deferred proxies only need to be pinned from the start of
618         // the sub-flush in which they appear.
619         alloc->addInterval(fDeferredProxies[i], 0, 0);
620     }
621 
622     // Add the interval for all the writes to this opList's target
623     if (fOpChains.count()) {
624         alloc->addInterval(fTarget.get(), cur, cur + fOpChains.count() - 1);
625     } else {
626         // This can happen if there is a loadOp (e.g., a clear) but no other draws. In this case we
627         // still need to add an interval for the destination so we create a fake op# for
628         // the missing clear op.
629         alloc->addInterval(fTarget.get());
630         alloc->incOps();
631     }
632 
633     auto gather = [ alloc SkDEBUGCODE(, this) ] (GrSurfaceProxy* p) {
634         alloc->addInterval(p SkDEBUGCODE(, fTarget.get() == p));
635     };
636     for (const OpChain& recordedOp : fOpChains) {
637         // only diff from the GrTextureOpList version
638         recordedOp.visitProxies(gather, GrOp::VisitorType::kAllocatorGather);
639 
640         // Even though the op may have been moved we still need to increment the op count to
641         // keep all the math consistent.
642         alloc->incOps();
643     }
644 }
645 
recordOp(std::unique_ptr<GrOp> op,GrProcessorSet::Analysis processorAnalysis,GrAppliedClip * clip,const DstProxy * dstProxy,const GrCaps & caps)646 void GrRenderTargetOpList::recordOp(
647         std::unique_ptr<GrOp> op, GrProcessorSet::Analysis processorAnalysis, GrAppliedClip* clip,
648         const DstProxy* dstProxy, const GrCaps& caps) {
649     SkDEBUGCODE(op->validate();)
650     SkASSERT(processorAnalysis.requiresDstTexture() == (dstProxy && dstProxy->proxy()));
651     SkASSERT(fTarget.get());
652 
653     // A closed GrOpList should never receive new/more ops
654     SkASSERT(!this->isClosed());
655     if (!op->bounds().isFinite()) {
656         fOpMemoryPool->release(std::move(op));
657         return;
658     }
659 
660     // Check if there is an op we can combine with by linearly searching back until we either
661     // 1) check every op
662     // 2) intersect with something
663     // 3) find a 'blocker'
664     GR_AUDIT_TRAIL_ADD_OP(fAuditTrail, op.get(), fTarget.get()->uniqueID());
665     GrOP_INFO("opList: %d Recording (%s, opID: %u)\n"
666               "\tBounds [L: %.2f, T: %.2f R: %.2f B: %.2f]\n",
667                this->uniqueID(),
668                op->name(),
669                op->uniqueID(),
670                op->bounds().fLeft, op->bounds().fTop,
671                op->bounds().fRight, op->bounds().fBottom);
672     GrOP_INFO(SkTabString(op->dumpInfo(), 1).c_str());
673     GrOP_INFO("\tOutcome:\n");
674     int maxCandidates = SkTMin(kMaxOpChainDistance, fOpChains.count());
675     if (maxCandidates) {
676         int i = 0;
677         while (true) {
678             OpChain& candidate = fOpChains.fromBack(i);
679             op = candidate.appendOp(std::move(op), processorAnalysis, dstProxy, clip, caps,
680                                     fOpMemoryPool.get(), fAuditTrail);
681             if (!op) {
682                 return;
683             }
684             // Stop going backwards if we would cause a painter's order violation.
685             if (!can_reorder(candidate.bounds(), op->bounds())) {
686                 GrOP_INFO("\t\tBackward: Intersects with chain (%s, head opID: %u)\n",
687                           candidate.head()->name(), candidate.head()->uniqueID());
688                 break;
689             }
690             if (++i == maxCandidates) {
691                 GrOP_INFO("\t\tBackward: Reached max lookback or beginning of op array %d\n", i);
692                 break;
693             }
694         }
695     } else {
696         GrOP_INFO("\t\tBackward: FirstOp\n");
697     }
698     if (clip) {
699         clip = fClipAllocator.make<GrAppliedClip>(std::move(*clip));
700         SkDEBUGCODE(fNumClips++;)
701     }
702     fOpChains.emplace_back(std::move(op), processorAnalysis, clip, dstProxy);
703 }
704 
forwardCombine(const GrCaps & caps)705 void GrRenderTargetOpList::forwardCombine(const GrCaps& caps) {
706     SkASSERT(!this->isClosed());
707     GrOP_INFO("opList: %d ForwardCombine %d ops:\n", this->uniqueID(), fOpChains.count());
708 
709     for (int i = 0; i < fOpChains.count() - 1; ++i) {
710         OpChain& chain = fOpChains[i];
711         int maxCandidateIdx = SkTMin(i + kMaxOpChainDistance, fOpChains.count() - 1);
712         int j = i + 1;
713         while (true) {
714             OpChain& candidate = fOpChains[j];
715             if (candidate.prependChain(&chain, caps, fOpMemoryPool.get(), fAuditTrail)) {
716                 break;
717             }
718             // Stop traversing if we would cause a painter's order violation.
719             if (!can_reorder(chain.bounds(), candidate.bounds())) {
720                 GrOP_INFO(
721                         "\t\t%d: chain (%s head opID: %u) -> "
722                         "Intersects with chain (%s, head opID: %u)\n",
723                         i, chain.head()->name(), chain.head()->uniqueID(), candidate.head()->name(),
724                         candidate.head()->uniqueID());
725                 break;
726             }
727             if (++j > maxCandidateIdx) {
728                 GrOP_INFO("\t\t%d: chain (%s opID: %u) -> Reached max lookahead or end of array\n",
729                           i, chain.head()->name(), chain.head()->uniqueID());
730                 break;
731             }
732         }
733     }
734 }
735 
736