Debian Codegraph @

src/gpu/ganesh/ops/OpsTask.cpp

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