• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2017 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 <new>
9 
10 #include "include/core/SkPoint.h"
11 #include "include/core/SkPoint3.h"
12 #include "include/gpu/GrRecordingContext.h"
13 #include "include/private/SkFloatingPoint.h"
14 #include "include/private/SkTo.h"
15 #include "src/core/SkMathPriv.h"
16 #include "src/core/SkMatrixPriv.h"
17 #include "src/core/SkRectPriv.h"
18 #include "src/gpu/GrAppliedClip.h"
19 #include "src/gpu/GrCaps.h"
20 #include "src/gpu/GrDrawOpTest.h"
21 #include "src/gpu/GrGeometryProcessor.h"
22 #include "src/gpu/GrGpu.h"
23 #include "src/gpu/GrMemoryPool.h"
24 #include "src/gpu/GrOpFlushState.h"
25 #include "src/gpu/GrOpsTypes.h"
26 #include "src/gpu/GrRecordingContextPriv.h"
27 #include "src/gpu/GrResourceProvider.h"
28 #include "src/gpu/GrResourceProviderPriv.h"
29 #include "src/gpu/GrShaderCaps.h"
30 #include "src/gpu/GrTexture.h"
31 #include "src/gpu/GrTextureProxy.h"
32 #include "src/gpu/SkGr.h"
33 #include "src/gpu/effects/GrBlendFragmentProcessor.h"
34 #include "src/gpu/effects/GrTextureEffect.h"
35 #include "src/gpu/geometry/GrQuad.h"
36 #include "src/gpu/geometry/GrQuadBuffer.h"
37 #include "src/gpu/geometry/GrQuadUtils.h"
38 #include "src/gpu/geometry/GrRect.h"
39 #include "src/gpu/glsl/GrGLSLVarying.h"
40 #include "src/gpu/ops/FillRectOp.h"
41 #include "src/gpu/ops/GrMeshDrawOp.h"
42 #include "src/gpu/ops/GrSimpleMeshDrawOpHelper.h"
43 #include "src/gpu/ops/QuadPerEdgeAA.h"
44 #include "src/gpu/ops/TextureOp.h"
45 #include "src/gpu/v1/SurfaceDrawContext_v1.h"
46 
47 namespace {
48 
49 using Subset = skgpu::v1::QuadPerEdgeAA::Subset;
50 using VertexSpec = skgpu::v1::QuadPerEdgeAA::VertexSpec;
51 using ColorType = skgpu::v1::QuadPerEdgeAA::ColorType;
52 
53 // Extracts lengths of vertical and horizontal edges of axis-aligned quad. "width" is the edge
54 // between v0 and v2 (or v1 and v3), "height" is the edge between v0 and v1 (or v2 and v3).
axis_aligned_quad_size(const GrQuad & quad)55 SkSize axis_aligned_quad_size(const GrQuad& quad) {
56     SkASSERT(quad.quadType() == GrQuad::Type::kAxisAligned);
57     // Simplification of regular edge length equation, since it's axis aligned and can avoid sqrt
58     float dw = sk_float_abs(quad.x(2) - quad.x(0)) + sk_float_abs(quad.y(2) - quad.y(0));
59     float dh = sk_float_abs(quad.x(1) - quad.x(0)) + sk_float_abs(quad.y(1) - quad.y(0));
60     return {dw, dh};
61 }
62 
63 std::tuple<bool /* filter */,
64            bool /* mipmap */>
filter_and_mm_have_effect(const GrQuad & srcQuad,const GrQuad & dstQuad)65 filter_and_mm_have_effect(const GrQuad& srcQuad, const GrQuad& dstQuad) {
66     // If not axis-aligned in src or dst, then always say it has an effect
67     if (srcQuad.quadType() != GrQuad::Type::kAxisAligned ||
68         dstQuad.quadType() != GrQuad::Type::kAxisAligned) {
69         return {true, true};
70     }
71 
72     SkRect srcRect;
73     SkRect dstRect;
74     if (srcQuad.asRect(&srcRect) && dstQuad.asRect(&dstRect)) {
75         // Disable filtering when there is no scaling (width and height are the same), and the
76         // top-left corners have the same fraction (so src and dst snap to the pixel grid
77         // identically).
78         SkASSERT(srcRect.isSorted());
79         bool filter = srcRect.width() != dstRect.width() || srcRect.height() != dstRect.height() ||
80                       SkScalarFraction(srcRect.fLeft) != SkScalarFraction(dstRect.fLeft) ||
81                       SkScalarFraction(srcRect.fTop)  != SkScalarFraction(dstRect.fTop);
82         bool mm = srcRect.width() > dstRect.width() || srcRect.height() > dstRect.height();
83         return {filter, mm};
84     }
85     // Extract edge lengths
86     SkSize srcSize = axis_aligned_quad_size(srcQuad);
87     SkSize dstSize = axis_aligned_quad_size(dstQuad);
88     // Although the quads are axis-aligned, the local coordinate system is transformed such
89     // that fractionally-aligned sample centers will not align with the device coordinate system
90     // So disable filtering when edges are the same length and both srcQuad and dstQuad
91     // 0th vertex is integer aligned.
92     bool filter = srcSize != dstSize ||
93                   !SkScalarIsInt(srcQuad.x(0)) ||
94                   !SkScalarIsInt(srcQuad.y(0)) ||
95                   !SkScalarIsInt(dstQuad.x(0)) ||
96                   !SkScalarIsInt(dstQuad.y(0));
97     bool mm = srcSize.fWidth > dstSize.fWidth || srcSize.fHeight > dstSize.fHeight;
98     return {filter, mm};
99 }
100 
101 // Describes function for normalizing src coords: [x * iw, y * ih + yOffset] can represent
102 // regular and rectangular textures, w/ or w/o origin correction.
103 struct NormalizationParams {
104     float fIW; // 1 / width of texture, or 1.0 for texture rectangles
105     float fInvH; // 1 / height of texture, or 1.0 for tex rects, X -1 if bottom-left origin
106     float fYOffset; // 0 for top-left origin, height of [normalized] tex if bottom-left
107 };
proxy_normalization_params(const GrSurfaceProxy * proxy,GrSurfaceOrigin origin)108 NormalizationParams proxy_normalization_params(const GrSurfaceProxy* proxy,
109                                                GrSurfaceOrigin origin) {
110     // Whether or not the proxy is instantiated, this is the size its texture will be, so we can
111     // normalize the src coordinates up front.
112     SkISize dimensions = proxy->backingStoreDimensions();
113     float iw, ih, h;
114     if (proxy->backendFormat().textureType() == GrTextureType::kRectangle) {
115         iw = ih = 1.f;
116         h = dimensions.height();
117     } else {
118         iw = 1.f / dimensions.width();
119         ih = 1.f / dimensions.height();
120         h = 1.f;
121     }
122 
123     if (origin == kBottomLeft_GrSurfaceOrigin) {
124         return {iw, -ih, h};
125     } else {
126         return {iw, ih, 0.0f};
127     }
128 }
129 
130 // Normalize the subset. If 'subsetRect' is null, it is assumed no subset constraint is desired,
131 // so a sufficiently large rect is returned even if the quad ends up batched with an op that uses
132 // subsets overall. When there is a subset it will be inset based on the filter mode. Normalization
133 // and y-flipping are applied as indicated by NormalizationParams.
normalize_and_inset_subset(GrSamplerState::Filter filter,const NormalizationParams & params,const SkRect * subsetRect)134 SkRect normalize_and_inset_subset(GrSamplerState::Filter filter,
135                                   const NormalizationParams& params,
136                                   const SkRect* subsetRect) {
137     static constexpr SkRect kLargeRect = {-100000, -100000, 1000000, 1000000};
138     if (!subsetRect) {
139         // Either the quad has no subset constraint and is batched with a subset constrained op
140         // (in which case we want a subset that doesn't restrict normalized tex coords), or the
141         // entire op doesn't use the subset, in which case the returned value is ignored.
142         return kLargeRect;
143     }
144 
145     auto ltrb = skvx::Vec<4, float>::Load(subsetRect);
146     auto flipHi = skvx::Vec<4, float>({1.f, 1.f, -1.f, -1.f});
147     if (filter == GrSamplerState::Filter::kNearest) {
148         // Make sure our insetting puts us at pixel centers.
149         ltrb = skvx::floor(ltrb*flipHi)*flipHi;
150     }
151     // Inset with pin to the rect center.
152     ltrb += skvx::Vec<4, float>({.5f, .5f, -.5f, -.5f});
153     auto mid = (skvx::shuffle<2, 3, 0, 1>(ltrb) + ltrb)*0.5f;
154     ltrb = skvx::min(ltrb*flipHi, mid*flipHi)*flipHi;
155 
156     // Normalize and offset
157     ltrb = ltrb * skvx::Vec<4, float>{params.fIW, params.fInvH, params.fIW, params.fInvH} +
158                skvx::Vec<4, float>{0.f, params.fYOffset, 0.f, params.fYOffset};
159     if (params.fInvH < 0.f) {
160         // Flip top and bottom to keep the rect sorted when loaded back to SkRect.
161         ltrb = skvx::shuffle<0, 3, 2, 1>(ltrb);
162     }
163 
164     SkRect out;
165     ltrb.store(&out);
166     return out;
167 }
168 
169 // Normalizes logical src coords and corrects for origin
normalize_src_quad(const NormalizationParams & params,GrQuad * srcQuad)170 void normalize_src_quad(const NormalizationParams& params,
171                         GrQuad* srcQuad) {
172     // The src quad should not have any perspective
173     SkASSERT(!srcQuad->hasPerspective());
174     skvx::Vec<4, float> xs = srcQuad->x4f() * params.fIW;
175     skvx::Vec<4, float> ys = srcQuad->y4f() * params.fInvH + params.fYOffset;
176     xs.store(srcQuad->xs());
177     ys.store(srcQuad->ys());
178 }
179 
180 // Count the number of proxy runs in the entry set. This usually is already computed by
181 // SkGpuDevice, but when the BatchLengthLimiter chops the set up it must determine a new proxy count
182 // for each split.
proxy_run_count(const GrTextureSetEntry set[],int count)183 int proxy_run_count(const GrTextureSetEntry set[], int count) {
184     int actualProxyRunCount = 0;
185     const GrSurfaceProxy* lastProxy = nullptr;
186     for (int i = 0; i < count; ++i) {
187         if (set[i].fProxyView.proxy() != lastProxy) {
188             actualProxyRunCount++;
189             lastProxy = set[i].fProxyView.proxy();
190         }
191     }
192     return actualProxyRunCount;
193 }
194 
safe_to_ignore_subset_rect(GrAAType aaType,GrSamplerState::Filter filter,const DrawQuad & quad,const SkRect & subsetRect)195 bool safe_to_ignore_subset_rect(GrAAType aaType, GrSamplerState::Filter filter,
196                                 const DrawQuad& quad, const SkRect& subsetRect) {
197     // If both the device and local quad are both axis-aligned, and filtering is off, the local quad
198     // can push all the way up to the edges of the the subset rect and the sampler shouldn't
199     // overshoot. Unfortunately, antialiasing adds enough jitter that we can only rely on this in
200     // the non-antialiased case.
201     SkRect localBounds = quad.fLocal.bounds();
202     if (aaType == GrAAType::kNone &&
203         filter == GrSamplerState::Filter::kNearest &&
204         quad.fDevice.quadType() == GrQuad::Type::kAxisAligned &&
205         quad.fLocal.quadType() == GrQuad::Type::kAxisAligned &&
206         subsetRect.contains(localBounds)) {
207 
208         return true;
209     }
210 
211     // If the local quad is inset by at least 0.5 pixels into the subset rect's bounds, the
212     // sampler shouldn't overshoot, even when antialiasing and filtering is taken into account.
213     if (subsetRect.makeInset(0.5f, 0.5f).contains(localBounds)) {
214         return true;
215     }
216 
217     // The subset rect cannot be ignored safely.
218     return false;
219 }
220 
221 /**
222  * Op that implements TextureOp::Make. It draws textured quads. Each quad can modulate against a
223  * the texture by color. The blend with the destination is always src-over. The edges are non-AA.
224  */
225 class TextureOpImpl final : public GrMeshDrawOp {
226 public:
227     using Saturate = skgpu::v1::TextureOp::Saturate;
228 
Make(GrRecordingContext * context,GrSurfaceProxyView proxyView,sk_sp<GrColorSpaceXform> textureXform,GrSamplerState::Filter filter,GrSamplerState::MipmapMode mm,const SkPMColor4f & color,Saturate saturate,GrAAType aaType,DrawQuad * quad,const SkRect * subset)229     static GrOp::Owner Make(GrRecordingContext* context,
230                             GrSurfaceProxyView proxyView,
231                             sk_sp<GrColorSpaceXform> textureXform,
232                             GrSamplerState::Filter filter,
233                             GrSamplerState::MipmapMode mm,
234                             const SkPMColor4f& color,
235                             Saturate saturate,
236                             GrAAType aaType,
237                             DrawQuad* quad,
238                             const SkRect* subset) {
239 
240         return GrOp::Make<TextureOpImpl>(context, std::move(proxyView), std::move(textureXform),
241                                          filter, mm, color, saturate, aaType, quad, subset);
242     }
243 
Make(GrRecordingContext * context,GrTextureSetEntry set[],int cnt,int proxyRunCnt,GrSamplerState::Filter filter,GrSamplerState::MipmapMode mm,Saturate saturate,GrAAType aaType,SkCanvas::SrcRectConstraint constraint,const SkMatrix & viewMatrix,sk_sp<GrColorSpaceXform> textureColorSpaceXform)244     static GrOp::Owner Make(GrRecordingContext* context,
245                             GrTextureSetEntry set[],
246                             int cnt,
247                             int proxyRunCnt,
248                             GrSamplerState::Filter filter,
249                             GrSamplerState::MipmapMode mm,
250                             Saturate saturate,
251                             GrAAType aaType,
252                             SkCanvas::SrcRectConstraint constraint,
253                             const SkMatrix& viewMatrix,
254                             sk_sp<GrColorSpaceXform> textureColorSpaceXform) {
255         // Allocate size based on proxyRunCnt, since that determines number of ViewCountPairs.
256         SkASSERT(proxyRunCnt <= cnt);
257         return GrOp::MakeWithExtraMemory<TextureOpImpl>(
258                 context, sizeof(ViewCountPair) * (proxyRunCnt - 1),
259                 set, cnt, proxyRunCnt, filter, mm, saturate, aaType, constraint,
260                 viewMatrix, std::move(textureColorSpaceXform));
261     }
262 
~TextureOpImpl()263     ~TextureOpImpl() override {
264         for (unsigned p = 1; p < fMetadata.fProxyCount; ++p) {
265             fViewCountPairs[p].~ViewCountPair();
266         }
267     }
268 
name() const269     const char* name() const override { return "TextureOp"; }
270 
visitProxies(const GrVisitProxyFunc & func) const271     void visitProxies(const GrVisitProxyFunc& func) const override {
272         bool mipped = (fMetadata.mipmapMode() != GrSamplerState::MipmapMode::kNone);
273         for (unsigned p = 0; p <  fMetadata.fProxyCount; ++p) {
274             func(fViewCountPairs[p].fProxy.get(), GrMipmapped(mipped));
275         }
276         if (fDesc && fDesc->fProgramInfo) {
277             fDesc->fProgramInfo->visitFPProxies(func);
278         }
279     }
280 
281 #ifdef SK_DEBUG
ValidateResourceLimits()282     static void ValidateResourceLimits() {
283         // The op implementation has an upper bound on the number of quads that it can represent.
284         // However, the resource manager imposes its own limit on the number of quads, which should
285         // always be lower than the numerical limit this op can hold.
286         using CountStorage = decltype(Metadata::fTotalQuadCount);
287         CountStorage maxQuadCount = std::numeric_limits<CountStorage>::max();
288         // GrResourceProvider::Max...() is typed as int, so don't compare across signed/unsigned.
289         int resourceLimit = SkTo<int>(maxQuadCount);
290         SkASSERT(GrResourceProvider::MaxNumAAQuads() <= resourceLimit &&
291                  GrResourceProvider::MaxNumNonAAQuads() <= resourceLimit);
292     }
293 #endif
294 
finalize(const GrCaps & caps,const GrAppliedClip *,GrClampType clampType)295     GrProcessorSet::Analysis finalize(const GrCaps& caps, const GrAppliedClip*,
296                                       GrClampType clampType) override {
297         SkASSERT(fMetadata.colorType() == ColorType::kNone);
298         auto iter = fQuads.metadata();
299         while(iter.next()) {
300             auto colorType = skgpu::v1::QuadPerEdgeAA::MinColorType(iter->fColor);
301             colorType = std::max(static_cast<ColorType>(fMetadata.fColorType),
302                                  colorType);
303             if (caps.reducedShaderMode()) {
304                 colorType = std::max(colorType, ColorType::kByte);
305             }
306             fMetadata.fColorType = static_cast<uint16_t>(colorType);
307         }
308         return GrProcessorSet::EmptySetAnalysis();
309     }
310 
fixedFunctionFlags() const311     FixedFunctionFlags fixedFunctionFlags() const override {
312         return fMetadata.aaType() == GrAAType::kMSAA ? FixedFunctionFlags::kUsesHWAA
313                                                      : FixedFunctionFlags::kNone;
314     }
315 
316     DEFINE_OP_CLASS_ID
317 
318 private:
319     friend class ::GrOp;
320 
321     struct ColorSubsetAndAA {
ColorSubsetAndAA__anon150413ae0111::TextureOpImpl::ColorSubsetAndAA322         ColorSubsetAndAA(const SkPMColor4f& color, const SkRect& subsetRect, GrQuadAAFlags aaFlags)
323                 : fColor(color)
324                 , fSubsetRect(subsetRect)
325                 , fAAFlags(static_cast<uint16_t>(aaFlags)) {
326             SkASSERT(fAAFlags == static_cast<uint16_t>(aaFlags));
327         }
328 
329         SkPMColor4f fColor;
330         // If the op doesn't use subsets, this is ignored. If the op uses subsets and the specific
331         // entry does not, this rect will equal kLargeRect, so it automatically has no effect.
332         SkRect fSubsetRect;
333         unsigned fAAFlags : 4;
334 
aaFlags__anon150413ae0111::TextureOpImpl::ColorSubsetAndAA335         GrQuadAAFlags aaFlags() const { return static_cast<GrQuadAAFlags>(fAAFlags); }
336     };
337 
338     struct ViewCountPair {
339         // Normally this would be a GrSurfaceProxyView, but TextureOp applies the GrOrigin right
340         // away so it doesn't need to be stored, and all ViewCountPairs in an op have the same
341         // swizzle so that is stored in the op metadata.
342         sk_sp<GrSurfaceProxy> fProxy;
343         int fQuadCnt;
344     };
345 
346     // TextureOp and ViewCountPair are 8 byte aligned. This is packed into 8 bytes to minimally
347     // increase the size of the op; increasing the op size can have a surprising impact on
348     // performance (since texture ops are one of the most commonly used in an app).
349     struct Metadata {
350         // AAType must be filled after initialization; ColorType is determined in finalize()
Metadata__anon150413ae0111::TextureOpImpl::Metadata351         Metadata(const GrSwizzle& swizzle,
352                  GrSamplerState::Filter filter,
353                  GrSamplerState::MipmapMode mm,
354                  Subset subset,
355                  Saturate saturate)
356             : fSwizzle(swizzle)
357             , fProxyCount(1)
358             , fTotalQuadCount(1)
359             , fFilter(static_cast<uint16_t>(filter))
360             , fMipmapMode(static_cast<uint16_t>(mm))
361             , fAAType(static_cast<uint16_t>(GrAAType::kNone))
362             , fColorType(static_cast<uint16_t>(ColorType::kNone))
363             , fSubset(static_cast<uint16_t>(subset))
364             , fSaturate(static_cast<uint16_t>(saturate)) {}
365 
366         GrSwizzle fSwizzle; // sizeof(GrSwizzle) == uint16_t
367         uint16_t  fProxyCount;
368         // This will be >= fProxyCount, since a proxy may be drawn multiple times
369         uint16_t  fTotalQuadCount;
370 
371         // These must be based on uint16_t to help MSVC's pack bitfields optimally
372         uint16_t  fFilter     : 2; // GrSamplerState::Filter
373         uint16_t  fMipmapMode : 2; // GrSamplerState::MipmapMode
374         uint16_t  fAAType     : 2; // GrAAType
375         uint16_t  fColorType  : 2; // GrQuadPerEdgeAA::ColorType
376         uint16_t  fSubset     : 1; // bool
377         uint16_t  fSaturate   : 1; // bool
378         uint16_t  fUnused     : 6; // # of bits left before Metadata exceeds 8 bytes
379 
filter__anon150413ae0111::TextureOpImpl::Metadata380         GrSamplerState::Filter filter() const {
381             return static_cast<GrSamplerState::Filter>(fFilter);
382         }
mipmapMode__anon150413ae0111::TextureOpImpl::Metadata383         GrSamplerState::MipmapMode mipmapMode() const {
384             return static_cast<GrSamplerState::MipmapMode>(fMipmapMode);
385         }
aaType__anon150413ae0111::TextureOpImpl::Metadata386         GrAAType aaType() const { return static_cast<GrAAType>(fAAType); }
colorType__anon150413ae0111::TextureOpImpl::Metadata387         ColorType colorType() const { return static_cast<ColorType>(fColorType); }
subset__anon150413ae0111::TextureOpImpl::Metadata388         Subset subset() const { return static_cast<Subset>(fSubset); }
saturate__anon150413ae0111::TextureOpImpl::Metadata389         Saturate saturate() const { return static_cast<Saturate>(fSaturate); }
390 
391         static_assert(GrSamplerState::kFilterCount <= 4);
392         static_assert(kGrAATypeCount <= 4);
393         static_assert(skgpu::v1::QuadPerEdgeAA::kColorTypeCount <= 4);
394     };
395     static_assert(sizeof(Metadata) == 8);
396 
397     // This descriptor is used to store the draw info we decide on during on(Pre)PrepareDraws. We
398     // store the data in a separate struct in order to minimize the size of the TextureOp.
399     // Historically, increasing the TextureOp's size has caused surprising perf regressions, but we
400     // may want to re-evaluate whether this is still necessary.
401     //
402     // In the onPrePrepareDraws case it is allocated in the creation-time opData arena, and
403     // allocatePrePreparedVertices is also called.
404     //
405     // In the onPrepareDraws case this descriptor is allocated in the flush-time arena (i.e., as
406     // part of the flushState).
407     struct Desc {
408         VertexSpec fVertexSpec;
409         int fNumProxies = 0;
410         int fNumTotalQuads = 0;
411 
412         // This member variable is only used by 'onPrePrepareDraws'.
413         char* fPrePreparedVertices = nullptr;
414 
415         GrProgramInfo* fProgramInfo = nullptr;
416 
417         sk_sp<const GrBuffer> fIndexBuffer;
418         sk_sp<const GrBuffer> fVertexBuffer;
419         int fBaseVertex;
420 
421         // How big should 'fVertices' be to hold all the vertex data?
totalSizeInBytes__anon150413ae0111::TextureOpImpl::Desc422         size_t totalSizeInBytes() const {
423             return this->totalNumVertices() * fVertexSpec.vertexSize();
424         }
425 
totalNumVertices__anon150413ae0111::TextureOpImpl::Desc426         int totalNumVertices() const {
427             return fNumTotalQuads * fVertexSpec.verticesPerQuad();
428         }
429 
allocatePrePreparedVertices__anon150413ae0111::TextureOpImpl::Desc430         void allocatePrePreparedVertices(SkArenaAlloc* arena) {
431             fPrePreparedVertices = arena->makeArrayDefault<char>(this->totalSizeInBytes());
432         }
433     };
434     // If subsetRect is not null it will be used to apply a strict src rect-style constraint.
TextureOpImpl(GrSurfaceProxyView proxyView,sk_sp<GrColorSpaceXform> textureColorSpaceXform,GrSamplerState::Filter filter,GrSamplerState::MipmapMode mm,const SkPMColor4f & color,Saturate saturate,GrAAType aaType,DrawQuad * quad,const SkRect * subsetRect)435     TextureOpImpl(GrSurfaceProxyView proxyView,
436                   sk_sp<GrColorSpaceXform> textureColorSpaceXform,
437                   GrSamplerState::Filter filter,
438                   GrSamplerState::MipmapMode mm,
439                   const SkPMColor4f& color,
440                   Saturate saturate,
441                   GrAAType aaType,
442                   DrawQuad* quad,
443                   const SkRect* subsetRect)
444             : INHERITED(ClassID())
445             , fQuads(1, true /* includes locals */)
446             , fTextureColorSpaceXform(std::move(textureColorSpaceXform))
447             , fDesc(nullptr)
448             , fMetadata(proxyView.swizzle(), filter, mm, Subset(!!subsetRect), saturate) {
449         // Clean up disparities between the overall aa type and edge configuration and apply
450         // optimizations based on the rect and matrix when appropriate
451         GrQuadUtils::ResolveAAType(aaType, quad->fEdgeFlags, quad->fDevice,
452                                    &aaType, &quad->fEdgeFlags);
453         fMetadata.fAAType = static_cast<uint16_t>(aaType);
454 
455         // We expect our caller to have already caught this optimization.
456         SkASSERT(!subsetRect ||
457                  !subsetRect->contains(proxyView.proxy()->backingStoreBoundsRect()));
458 
459         // We may have had a strict constraint with nearest filter solely due to possible AA bloat.
460         // Try to identify cases where the subsetting isn't actually necessary, and skip it.
461         if (subsetRect) {
462             if (safe_to_ignore_subset_rect(aaType, filter, *quad, *subsetRect)) {
463                 subsetRect = nullptr;
464                 fMetadata.fSubset = static_cast<uint16_t>(Subset::kNo);
465             }
466         }
467 
468         // Normalize src coordinates and the subset (if set)
469         NormalizationParams params = proxy_normalization_params(proxyView.proxy(),
470                                                                 proxyView.origin());
471         normalize_src_quad(params, &quad->fLocal);
472         SkRect subset = normalize_and_inset_subset(filter, params, subsetRect);
473 
474         // Set bounds before clipping so we don't have to worry about unioning the bounds of
475         // the two potential quads (GrQuad::bounds() is perspective-safe).
476         bool hairline = GrQuadUtils::WillUseHairline(quad->fDevice, aaType, quad->fEdgeFlags);
477         this->setBounds(quad->fDevice.bounds(), HasAABloat(aaType == GrAAType::kCoverage),
478                         hairline ? IsHairline::kYes : IsHairline::kNo);
479         int quadCount = this->appendQuad(quad, color, subset);
480         fViewCountPairs[0] = {proxyView.detachProxy(), quadCount};
481     }
482 
TextureOpImpl(GrTextureSetEntry set[],int cnt,int proxyRunCnt,const GrSamplerState::Filter filter,const GrSamplerState::MipmapMode mm,const Saturate saturate,const GrAAType aaType,const SkCanvas::SrcRectConstraint constraint,const SkMatrix & viewMatrix,sk_sp<GrColorSpaceXform> textureColorSpaceXform)483     TextureOpImpl(GrTextureSetEntry set[],
484                   int cnt,
485                   int proxyRunCnt,
486                   const GrSamplerState::Filter filter,
487                   const GrSamplerState::MipmapMode mm,
488                   const Saturate saturate,
489                   const GrAAType aaType,
490                   const SkCanvas::SrcRectConstraint constraint,
491                   const SkMatrix& viewMatrix,
492                   sk_sp<GrColorSpaceXform> textureColorSpaceXform)
493             : INHERITED(ClassID())
494             , fQuads(cnt, true /* includes locals */)
495             , fTextureColorSpaceXform(std::move(textureColorSpaceXform))
496             , fDesc(nullptr)
497             , fMetadata(set[0].fProxyView.swizzle(),
498                         GrSamplerState::Filter::kNearest,
499                         GrSamplerState::MipmapMode::kNone,
500                         Subset::kNo,
501                         saturate) {
502         // Update counts to reflect the batch op
503         fMetadata.fProxyCount = SkToUInt(proxyRunCnt);
504         fMetadata.fTotalQuadCount = SkToUInt(cnt);
505 
506         SkRect bounds = SkRectPriv::MakeLargestInverted();
507 
508         GrAAType netAAType = GrAAType::kNone; // aa type maximally compatible with all dst rects
509         Subset netSubset = Subset::kNo;
510         GrSamplerState::Filter netFilter = GrSamplerState::Filter::kNearest;
511         GrSamplerState::MipmapMode netMM = GrSamplerState::MipmapMode::kNone;
512         bool hasSubpixel = false;
513 
514         const GrSurfaceProxy* curProxy = nullptr;
515 
516         // 'q' is the index in 'set' and fQuadBuffer; 'p' is the index in fViewCountPairs and only
517         // increases when set[q]'s proxy changes.
518         int p = 0;
519         for (int q = 0; q < cnt; ++q) {
520             SkASSERT(mm == GrSamplerState::MipmapMode::kNone ||
521                      (set[0].fProxyView.proxy()->asTextureProxy()->mipmapped() ==
522                       GrMipmapped::kYes));
523             if (q == 0) {
524                 // We do not placement new the first ViewCountPair since that one is allocated and
525                 // initialized as part of the TextureOp creation.
526                 fViewCountPairs[0].fProxy = set[0].fProxyView.detachProxy();
527                 fViewCountPairs[0].fQuadCnt = 0;
528                 curProxy = fViewCountPairs[0].fProxy.get();
529             } else if (set[q].fProxyView.proxy() != curProxy) {
530                 // We must placement new the ViewCountPairs here so that the sk_sps in the
531                 // GrSurfaceProxyView get initialized properly.
532                 new(&fViewCountPairs[++p])ViewCountPair({set[q].fProxyView.detachProxy(), 0});
533 
534                 curProxy = fViewCountPairs[p].fProxy.get();
535                 SkASSERT(GrTextureProxy::ProxiesAreCompatibleAsDynamicState(
536                         curProxy, fViewCountPairs[0].fProxy.get()));
537                 SkASSERT(fMetadata.fSwizzle == set[q].fProxyView.swizzle());
538             } // else another quad referencing the same proxy
539 
540             SkMatrix ctm = viewMatrix;
541             if (set[q].fPreViewMatrix) {
542                 ctm.preConcat(*set[q].fPreViewMatrix);
543             }
544 
545             // Use dstRect/srcRect unless dstClip is provided, in which case derive new source
546             // coordinates by mapping dstClipQuad by the dstRect to srcRect transform.
547             DrawQuad quad;
548             if (set[q].fDstClipQuad) {
549                 quad.fDevice = GrQuad::MakeFromSkQuad(set[q].fDstClipQuad, ctm);
550 
551                 SkPoint srcPts[4];
552                 GrMapRectPoints(set[q].fDstRect, set[q].fSrcRect, set[q].fDstClipQuad, srcPts, 4);
553                 quad.fLocal = GrQuad::MakeFromSkQuad(srcPts, SkMatrix::I());
554             } else {
555                 quad.fDevice = GrQuad::MakeFromRect(set[q].fDstRect, ctm);
556                 quad.fLocal = GrQuad(set[q].fSrcRect);
557             }
558 
559             // This may be reduced per-quad from the requested aggregate filtering level, and used
560             // to determine if the subset is needed for the entry as well.
561             GrSamplerState::Filter filterForQuad = filter;
562             if (netFilter != filter || netMM != mm) {
563                 // The only way netFilter != filter is if linear is requested and we haven't yet
564                 // found a quad that requires linear (so net is still nearest). Similar for mip
565                 // mapping.
566                 SkASSERT(filter == netFilter ||
567                          (netFilter == GrSamplerState::Filter::kNearest && filter > netFilter));
568                 SkASSERT(mm == netMM ||
569                          (netMM == GrSamplerState::MipmapMode::kNone && mm > netMM));
570                 auto [mustFilter, mustMM] = filter_and_mm_have_effect(quad.fLocal, quad.fDevice);
571                 if (filter != GrSamplerState::Filter::kNearest) {
572                     if (mustFilter) {
573                         netFilter = filter; // upgrade batch to higher filter level
574                     } else {
575                         filterForQuad = GrSamplerState::Filter::kNearest; // downgrade entry
576                     }
577                 }
578                 if (mustMM && mm != GrSamplerState::MipmapMode::kNone) {
579                     netMM = mm;
580                 }
581             }
582 
583             // Determine the AA type for the quad, then merge with net AA type
584             GrAAType aaForQuad;
585             GrQuadUtils::ResolveAAType(aaType, set[q].fAAFlags, quad.fDevice,
586                                        &aaForQuad, &quad.fEdgeFlags);
587             // Update overall bounds of the op as the union of all quads
588             bounds.joinPossiblyEmptyRect(quad.fDevice.bounds());
589             hasSubpixel |= GrQuadUtils::WillUseHairline(quad.fDevice, aaForQuad, quad.fEdgeFlags);
590 
591             // Resolve sets aaForQuad to aaType or None, there is never a change between aa methods
592             SkASSERT(aaForQuad == GrAAType::kNone || aaForQuad == aaType);
593             if (netAAType == GrAAType::kNone && aaForQuad != GrAAType::kNone) {
594                 netAAType = aaType;
595             }
596 
597             // Calculate metadata for the entry
598             const SkRect* subsetForQuad = nullptr;
599             if (constraint == SkCanvas::kStrict_SrcRectConstraint) {
600                 // Check (briefly) if the subset rect is actually needed for this set entry.
601                 SkRect* subsetRect = &set[q].fSrcRect;
602                 if (!subsetRect->contains(curProxy->backingStoreBoundsRect())) {
603                     if (!safe_to_ignore_subset_rect(aaForQuad, filterForQuad, quad, *subsetRect)) {
604                         netSubset = Subset::kYes;
605                         subsetForQuad = subsetRect;
606                     }
607                 }
608             }
609 
610             // Normalize the src quads and apply origin
611             NormalizationParams proxyParams = proxy_normalization_params(
612                     curProxy, set[q].fProxyView.origin());
613             normalize_src_quad(proxyParams, &quad.fLocal);
614 
615             // This subset may represent a no-op, otherwise it will have the origin and dimensions
616             // of the texture applied to it.
617             SkRect subset = normalize_and_inset_subset(filter, proxyParams, subsetForQuad);
618 
619             // Always append a quad (or 2 if perspective clipped), it just may refer back to a prior
620             // ViewCountPair (this frequently happens when Chrome draws 9-patches).
621             fViewCountPairs[p].fQuadCnt += this->appendQuad(&quad, set[q].fColor, subset);
622         }
623         // The # of proxy switches should match what was provided (+1 because we incremented p
624         // when a new proxy was encountered).
625         SkASSERT((p + 1) == fMetadata.fProxyCount);
626         SkASSERT(fQuads.count() == fMetadata.fTotalQuadCount);
627 
628         fMetadata.fAAType = static_cast<uint16_t>(netAAType);
629         fMetadata.fFilter = static_cast<uint16_t>(netFilter);
630         fMetadata.fSubset = static_cast<uint16_t>(netSubset);
631 
632         this->setBounds(bounds, HasAABloat(netAAType == GrAAType::kCoverage),
633                         hasSubpixel ? IsHairline::kYes : IsHairline::kNo);
634     }
635 
appendQuad(DrawQuad * quad,const SkPMColor4f & color,const SkRect & subset)636     int appendQuad(DrawQuad* quad, const SkPMColor4f& color, const SkRect& subset) {
637         DrawQuad extra;
638         // Always clip to W0 to stay consistent with GrQuad::bounds
639         int quadCount = GrQuadUtils::ClipToW0(quad, &extra);
640         if (quadCount == 0) {
641             // We can't discard the op at this point, but disable AA flags so it won't go through
642             // inset/outset processing
643             quad->fEdgeFlags = GrQuadAAFlags::kNone;
644             quadCount = 1;
645         }
646         fQuads.append(quad->fDevice, {color, subset, quad->fEdgeFlags},  &quad->fLocal);
647         if (quadCount > 1) {
648             fQuads.append(extra.fDevice, {color, subset, extra.fEdgeFlags}, &extra.fLocal);
649             fMetadata.fTotalQuadCount++;
650         }
651         return quadCount;
652     }
653 
programInfo()654     GrProgramInfo* programInfo() override {
655         // Although this Op implements its own onPrePrepareDraws it calls GrMeshDrawOps' version so
656         // this entry point will be called.
657         return (fDesc) ? fDesc->fProgramInfo : nullptr;
658     }
659 
onCreateProgramInfo(const GrCaps * caps,SkArenaAlloc * arena,const GrSurfaceProxyView & writeView,bool usesMSAASurface,GrAppliedClip && appliedClip,const GrDstProxyView & dstProxyView,GrXferBarrierFlags renderPassXferBarriers,GrLoadOp colorLoadOp)660     void onCreateProgramInfo(const GrCaps* caps,
661                              SkArenaAlloc* arena,
662                              const GrSurfaceProxyView& writeView,
663                              bool usesMSAASurface,
664                              GrAppliedClip&& appliedClip,
665                              const GrDstProxyView& dstProxyView,
666                              GrXferBarrierFlags renderPassXferBarriers,
667                              GrLoadOp colorLoadOp) override {
668         SkASSERT(fDesc);
669 
670         GrGeometryProcessor* gp;
671 
672         {
673             const GrBackendFormat& backendFormat =
674                     fViewCountPairs[0].fProxy->backendFormat();
675 
676             GrSamplerState samplerState = GrSamplerState(GrSamplerState::WrapMode::kClamp,
677                                                          fMetadata.filter());
678 
679             gp = skgpu::v1::QuadPerEdgeAA::MakeTexturedProcessor(
680                     arena, fDesc->fVertexSpec, *caps->shaderCaps(), backendFormat, samplerState,
681                     fMetadata.fSwizzle, std::move(fTextureColorSpaceXform), fMetadata.saturate());
682 
683             SkASSERT(fDesc->fVertexSpec.vertexSize() == gp->vertexStride());
684         }
685 
686         fDesc->fProgramInfo = GrSimpleMeshDrawOpHelper::CreateProgramInfo(
687                 caps, arena, writeView, usesMSAASurface, std::move(appliedClip), dstProxyView, gp,
688                 GrProcessorSet::MakeEmptySet(), fDesc->fVertexSpec.primitiveType(),
689                 renderPassXferBarriers, colorLoadOp, GrPipeline::InputFlags::kNone);
690     }
691 
onPrePrepareDraws(GrRecordingContext * context,const GrSurfaceProxyView & writeView,GrAppliedClip * clip,const GrDstProxyView & dstProxyView,GrXferBarrierFlags renderPassXferBarriers,GrLoadOp colorLoadOp)692     void onPrePrepareDraws(GrRecordingContext* context,
693                            const GrSurfaceProxyView& writeView,
694                            GrAppliedClip* clip,
695                            const GrDstProxyView& dstProxyView,
696                            GrXferBarrierFlags renderPassXferBarriers,
697                            GrLoadOp colorLoadOp) override {
698         TRACE_EVENT0("skia.gpu", TRACE_FUNC);
699 
700         SkDEBUGCODE(this->validate();)
701         SkASSERT(!fDesc);
702 
703         SkArenaAlloc* arena = context->priv().recordTimeAllocator();
704 
705         fDesc = arena->make<Desc>();
706         this->characterize(fDesc);
707         fDesc->allocatePrePreparedVertices(arena);
708         FillInVertices(*context->priv().caps(), this, fDesc, fDesc->fPrePreparedVertices);
709 
710         // This will call onCreateProgramInfo and register the created program with the DDL.
711         this->INHERITED::onPrePrepareDraws(context, writeView, clip, dstProxyView,
712                                            renderPassXferBarriers, colorLoadOp);
713     }
714 
FillInVertices(const GrCaps & caps,TextureOpImpl * texOp,Desc * desc,char * vertexData)715     static void FillInVertices(const GrCaps& caps,
716                                TextureOpImpl* texOp,
717                                Desc* desc,
718                                char* vertexData) {
719         SkASSERT(vertexData);
720 
721         SkDEBUGCODE(int totQuadsSeen = 0;)
722         SkDEBUGCODE(int totVerticesSeen = 0;)
723         SkDEBUGCODE(const size_t vertexSize = desc->fVertexSpec.vertexSize());
724 
725         skgpu::v1::QuadPerEdgeAA::Tessellator tessellator(desc->fVertexSpec, vertexData);
726         for (const auto& op : ChainRange<TextureOpImpl>(texOp)) {
727             auto iter = op.fQuads.iterator();
728             for (unsigned p = 0; p < op.fMetadata.fProxyCount; ++p) {
729                 const int quadCnt = op.fViewCountPairs[p].fQuadCnt;
730                 SkDEBUGCODE(int meshVertexCnt = quadCnt * desc->fVertexSpec.verticesPerQuad());
731 
732                 for (int i = 0; i < quadCnt && iter.next(); ++i) {
733                     SkASSERT(iter.isLocalValid());
734                     const ColorSubsetAndAA& info = iter.metadata();
735 
736                     tessellator.append(iter.deviceQuad(), iter.localQuad(), info.fColor,
737                                        info.fSubsetRect, info.aaFlags());
738                 }
739 
740                 SkASSERT((totVerticesSeen + meshVertexCnt) * vertexSize
741                          == (size_t)(tessellator.vertices() - vertexData));
742 
743                 SkDEBUGCODE(totQuadsSeen += quadCnt;)
744                 SkDEBUGCODE(totVerticesSeen += meshVertexCnt);
745                 SkASSERT(totQuadsSeen * desc->fVertexSpec.verticesPerQuad() == totVerticesSeen);
746             }
747 
748             // If quad counts per proxy were calculated correctly, the entire iterator
749             // should have been consumed.
750             SkASSERT(!iter.next());
751         }
752 
753         SkASSERT(desc->totalSizeInBytes() == (size_t)(tessellator.vertices() - vertexData));
754         SkASSERT(totQuadsSeen == desc->fNumTotalQuads);
755         SkASSERT(totVerticesSeen == desc->totalNumVertices());
756     }
757 
758 #ifdef SK_DEBUG
validate_op(GrTextureType textureType,GrAAType aaType,GrSwizzle swizzle,const TextureOpImpl * op)759     static int validate_op(GrTextureType textureType,
760                            GrAAType aaType,
761                            GrSwizzle swizzle,
762                            const TextureOpImpl* op) {
763         SkASSERT(op->fMetadata.fSwizzle == swizzle);
764 
765         int quadCount = 0;
766         for (unsigned p = 0; p < op->fMetadata.fProxyCount; ++p) {
767             auto* proxy = op->fViewCountPairs[p].fProxy->asTextureProxy();
768             quadCount += op->fViewCountPairs[p].fQuadCnt;
769             SkASSERT(proxy);
770             SkASSERT(proxy->textureType() == textureType);
771         }
772 
773         SkASSERT(aaType == op->fMetadata.aaType());
774         return quadCount;
775     }
776 
validate() const777     void validate() const override {
778         // NOTE: Since this is debug-only code, we use the virtual asTextureProxy()
779         auto textureType = fViewCountPairs[0].fProxy->asTextureProxy()->textureType();
780         GrAAType aaType = fMetadata.aaType();
781         GrSwizzle swizzle = fMetadata.fSwizzle;
782 
783         int quadCount = validate_op(textureType, aaType, swizzle, this);
784 
785         for (const GrOp* tmp = this->prevInChain(); tmp; tmp = tmp->prevInChain()) {
786             quadCount += validate_op(textureType, aaType, swizzle,
787                                      static_cast<const TextureOpImpl*>(tmp));
788         }
789 
790         for (const GrOp* tmp = this->nextInChain(); tmp; tmp = tmp->nextInChain()) {
791             quadCount += validate_op(textureType, aaType, swizzle,
792                                      static_cast<const TextureOpImpl*>(tmp));
793         }
794 
795         SkASSERT(quadCount == this->numChainedQuads());
796     }
797 
798 #endif
799 
800 #if GR_TEST_UTILS
numQuads() const801     int numQuads() const final { return this->totNumQuads(); }
802 #endif
803 
characterize(Desc * desc) const804     void characterize(Desc* desc) const {
805         SkDEBUGCODE(this->validate();)
806 
807         GrQuad::Type quadType = GrQuad::Type::kAxisAligned;
808         ColorType colorType = ColorType::kNone;
809         GrQuad::Type srcQuadType = GrQuad::Type::kAxisAligned;
810         Subset subset = Subset::kNo;
811         GrAAType overallAAType = fMetadata.aaType();
812 
813         desc->fNumProxies = 0;
814         desc->fNumTotalQuads = 0;
815         int maxQuadsPerMesh = 0;
816 
817         for (const auto& op : ChainRange<TextureOpImpl>(this)) {
818             if (op.fQuads.deviceQuadType() > quadType) {
819                 quadType = op.fQuads.deviceQuadType();
820             }
821             if (op.fQuads.localQuadType() > srcQuadType) {
822                 srcQuadType = op.fQuads.localQuadType();
823             }
824             if (op.fMetadata.subset() == Subset::kYes) {
825                 subset = Subset::kYes;
826             }
827             colorType = std::max(colorType, op.fMetadata.colorType());
828             desc->fNumProxies += op.fMetadata.fProxyCount;
829 
830             for (unsigned p = 0; p < op.fMetadata.fProxyCount; ++p) {
831                 maxQuadsPerMesh = std::max(op.fViewCountPairs[p].fQuadCnt, maxQuadsPerMesh);
832             }
833             desc->fNumTotalQuads += op.totNumQuads();
834 
835             if (op.fMetadata.aaType() == GrAAType::kCoverage) {
836                 overallAAType = GrAAType::kCoverage;
837             }
838         }
839 
840         SkASSERT(desc->fNumTotalQuads == this->numChainedQuads());
841 
842         SkASSERT(!CombinedQuadCountWillOverflow(overallAAType, false, desc->fNumTotalQuads));
843 
844         auto indexBufferOption = skgpu::v1::QuadPerEdgeAA::CalcIndexBufferOption(overallAAType,
845                                                                                  maxQuadsPerMesh);
846 
847         desc->fVertexSpec = VertexSpec(quadType, colorType, srcQuadType, /* hasLocal */ true,
848                                        subset, overallAAType, /* alpha as coverage */ true,
849                                        indexBufferOption);
850 
851         SkASSERT(desc->fNumTotalQuads <= skgpu::v1::QuadPerEdgeAA::QuadLimit(indexBufferOption));
852     }
853 
totNumQuads() const854     int totNumQuads() const {
855 #ifdef SK_DEBUG
856         int tmp = 0;
857         for (unsigned p = 0; p < fMetadata.fProxyCount; ++p) {
858             tmp += fViewCountPairs[p].fQuadCnt;
859         }
860         SkASSERT(tmp == fMetadata.fTotalQuadCount);
861 #endif
862 
863         return fMetadata.fTotalQuadCount;
864     }
865 
numChainedQuads() const866     int numChainedQuads() const {
867         int numChainedQuads = this->totNumQuads();
868 
869         for (const GrOp* tmp = this->prevInChain(); tmp; tmp = tmp->prevInChain()) {
870             numChainedQuads += ((const TextureOpImpl*)tmp)->totNumQuads();
871         }
872 
873         for (const GrOp* tmp = this->nextInChain(); tmp; tmp = tmp->nextInChain()) {
874             numChainedQuads += ((const TextureOpImpl*)tmp)->totNumQuads();
875         }
876 
877         return numChainedQuads;
878     }
879 
880     // onPrePrepareDraws may or may not have been called at this point
onPrepareDraws(GrMeshDrawTarget * target)881     void onPrepareDraws(GrMeshDrawTarget* target) override {
882         TRACE_EVENT0("skia.gpu", TRACE_FUNC);
883 
884         SkDEBUGCODE(this->validate();)
885 
886         SkASSERT(!fDesc || fDesc->fPrePreparedVertices);
887 
888         if (!fDesc) {
889             SkArenaAlloc* arena = target->allocator();
890             fDesc = arena->make<Desc>();
891             this->characterize(fDesc);
892             SkASSERT(!fDesc->fPrePreparedVertices);
893         }
894 
895         size_t vertexSize = fDesc->fVertexSpec.vertexSize();
896 
897         void* vdata = target->makeVertexSpace(vertexSize, fDesc->totalNumVertices(),
898                                               &fDesc->fVertexBuffer, &fDesc->fBaseVertex);
899         if (!vdata) {
900             SkDebugf("Could not allocate vertices\n");
901             return;
902         }
903 
904         if (fDesc->fVertexSpec.needsIndexBuffer()) {
905             fDesc->fIndexBuffer = skgpu::v1::QuadPerEdgeAA::GetIndexBuffer(
906                     target, fDesc->fVertexSpec.indexBufferOption());
907             if (!fDesc->fIndexBuffer) {
908                 SkDebugf("Could not allocate indices\n");
909                 return;
910             }
911         }
912 
913         if (fDesc->fPrePreparedVertices) {
914             memcpy(vdata, fDesc->fPrePreparedVertices, fDesc->totalSizeInBytes());
915         } else {
916             FillInVertices(target->caps(), this, fDesc, (char*) vdata);
917         }
918     }
919 
onExecute(GrOpFlushState * flushState,const SkRect & chainBounds)920     void onExecute(GrOpFlushState* flushState, const SkRect& chainBounds) override {
921         if (!fDesc->fVertexBuffer) {
922             return;
923         }
924 
925         if (fDesc->fVertexSpec.needsIndexBuffer() && !fDesc->fIndexBuffer) {
926             return;
927         }
928 
929         if (!fDesc->fProgramInfo) {
930             this->createProgramInfo(flushState);
931             SkASSERT(fDesc->fProgramInfo);
932         }
933 
934         flushState->bindPipelineAndScissorClip(*fDesc->fProgramInfo, chainBounds);
935         flushState->bindBuffers(std::move(fDesc->fIndexBuffer), nullptr,
936                                 std::move(fDesc->fVertexBuffer));
937 
938         int totQuadsSeen = 0;
939         SkDEBUGCODE(int numDraws = 0;)
940         for (const auto& op : ChainRange<TextureOpImpl>(this)) {
941             for (unsigned p = 0; p < op.fMetadata.fProxyCount; ++p) {
942                 const int quadCnt = op.fViewCountPairs[p].fQuadCnt;
943                 SkASSERT(numDraws < fDesc->fNumProxies);
944                 flushState->bindTextures(fDesc->fProgramInfo->geomProc(),
945                                          *op.fViewCountPairs[p].fProxy,
946                                          fDesc->fProgramInfo->pipeline());
947                 skgpu::v1::QuadPerEdgeAA::IssueDraw(flushState->caps(), flushState->opsRenderPass(),
948                                                     fDesc->fVertexSpec, totQuadsSeen, quadCnt,
949                                                     fDesc->totalNumVertices(), fDesc->fBaseVertex);
950                 totQuadsSeen += quadCnt;
951                 SkDEBUGCODE(++numDraws;)
952             }
953         }
954 
955         SkASSERT(totQuadsSeen == fDesc->fNumTotalQuads);
956         SkASSERT(numDraws == fDesc->fNumProxies);
957     }
958 
propagateCoverageAAThroughoutChain()959     void propagateCoverageAAThroughoutChain() {
960         fMetadata.fAAType = static_cast<uint16_t>(GrAAType::kCoverage);
961 
962         for (GrOp* tmp = this->prevInChain(); tmp; tmp = tmp->prevInChain()) {
963             auto tex = static_cast<TextureOpImpl*>(tmp);
964             SkASSERT(tex->fMetadata.aaType() == GrAAType::kCoverage ||
965                      tex->fMetadata.aaType() == GrAAType::kNone);
966             tex->fMetadata.fAAType = static_cast<uint16_t>(GrAAType::kCoverage);
967         }
968 
969         for (GrOp* tmp = this->nextInChain(); tmp; tmp = tmp->nextInChain()) {
970             auto tex = static_cast<TextureOpImpl*>(tmp);
971             SkASSERT(tex->fMetadata.aaType() == GrAAType::kCoverage ||
972                      tex->fMetadata.aaType() == GrAAType::kNone);
973             tex->fMetadata.fAAType = static_cast<uint16_t>(GrAAType::kCoverage);
974         }
975     }
976 
onCombineIfPossible(GrOp * t,SkArenaAlloc *,const GrCaps & caps)977     CombineResult onCombineIfPossible(GrOp* t, SkArenaAlloc*, const GrCaps& caps) override {
978         TRACE_EVENT0("skia.gpu", TRACE_FUNC);
979         auto that = t->cast<TextureOpImpl>();
980 
981         SkDEBUGCODE(this->validate();)
982         SkDEBUGCODE(that->validate();)
983 
984         if (fDesc || that->fDesc) {
985             // This should never happen (since only DDL recorded ops should be prePrepared)
986             // but, in any case, we should never combine ops that that been prePrepared
987             return CombineResult::kCannotCombine;
988         }
989 
990         if (fMetadata.subset() != that->fMetadata.subset()) {
991             // It is technically possible to combine operations across subset modes, but performance
992             // testing suggests it's better to make more draw calls where some take advantage of
993             // the more optimal shader path without coordinate clamping.
994             return CombineResult::kCannotCombine;
995         }
996         if (!GrColorSpaceXform::Equals(fTextureColorSpaceXform.get(),
997                                        that->fTextureColorSpaceXform.get())) {
998             return CombineResult::kCannotCombine;
999         }
1000 
1001         bool upgradeToCoverageAAOnMerge = false;
1002         if (fMetadata.aaType() != that->fMetadata.aaType()) {
1003             if (!CanUpgradeAAOnMerge(fMetadata.aaType(), that->fMetadata.aaType())) {
1004                 return CombineResult::kCannotCombine;
1005             }
1006             upgradeToCoverageAAOnMerge = true;
1007         }
1008 
1009         if (CombinedQuadCountWillOverflow(fMetadata.aaType(), upgradeToCoverageAAOnMerge,
1010                                           this->numChainedQuads() + that->numChainedQuads())) {
1011             return CombineResult::kCannotCombine;
1012         }
1013 
1014         if (fMetadata.saturate() != that->fMetadata.saturate()) {
1015             return CombineResult::kCannotCombine;
1016         }
1017         if (fMetadata.filter() != that->fMetadata.filter()) {
1018             return CombineResult::kCannotCombine;
1019         }
1020         if (fMetadata.mipmapMode() != that->fMetadata.mipmapMode()) {
1021             return CombineResult::kCannotCombine;
1022         }
1023         if (fMetadata.fSwizzle != that->fMetadata.fSwizzle) {
1024             return CombineResult::kCannotCombine;
1025         }
1026         const auto* thisProxy = fViewCountPairs[0].fProxy.get();
1027         const auto* thatProxy = that->fViewCountPairs[0].fProxy.get();
1028         if (fMetadata.fProxyCount > 1 || that->fMetadata.fProxyCount > 1 ||
1029             thisProxy != thatProxy) {
1030             // We can't merge across different proxies. Check if 'this' can be chained with 'that'.
1031             if (GrTextureProxy::ProxiesAreCompatibleAsDynamicState(thisProxy, thatProxy) &&
1032                 caps.dynamicStateArrayGeometryProcessorTextureSupport() &&
1033                 fMetadata.aaType() == that->fMetadata.aaType()) {
1034                 // We only allow chaining when the aaTypes match bc otherwise the AA type
1035                 // reported by the chain can be inconsistent. That is, since chaining doesn't
1036                 // propagate revised AA information throughout the chain, the head of the chain
1037                 // could have an AA setting of kNone while the chain as a whole could have a
1038                 // setting of kCoverage. This inconsistency would then interfere with the validity
1039                 // of the CombinedQuadCountWillOverflow calls.
1040                 // This problem doesn't occur w/ merging bc we do propagate the AA information
1041                 // (in propagateCoverageAAThroughoutChain) below.
1042                 return CombineResult::kMayChain;
1043             }
1044             return CombineResult::kCannotCombine;
1045         }
1046 
1047         fMetadata.fSubset |= that->fMetadata.fSubset;
1048         fMetadata.fColorType = std::max(fMetadata.fColorType, that->fMetadata.fColorType);
1049 
1050         // Concatenate quad lists together
1051         fQuads.concat(that->fQuads);
1052         fViewCountPairs[0].fQuadCnt += that->fQuads.count();
1053         fMetadata.fTotalQuadCount += that->fQuads.count();
1054 
1055         if (upgradeToCoverageAAOnMerge) {
1056             // This merger may be the start of a concatenation of two chains. When one
1057             // of the chains mutates its AA the other must follow suit or else the above AA
1058             // check may prevent later ops from chaining together. A specific example of this is
1059             // when chain2 is prepended onto chain1:
1060             //  chain1 (that): opA (non-AA/mergeable) opB (non-AA/non-mergeable)
1061             //  chain2 (this): opC (cov-AA/non-mergeable) opD (cov-AA/mergeable)
1062             // W/o this propagation, after opD & opA merge, opB and opC would say they couldn't
1063             // chain - which would stop the concatenation process.
1064             this->propagateCoverageAAThroughoutChain();
1065             that->propagateCoverageAAThroughoutChain();
1066         }
1067 
1068         SkDEBUGCODE(this->validate();)
1069 
1070         return CombineResult::kMerged;
1071     }
1072 
1073 #if GR_TEST_UTILS
onDumpInfo() const1074     SkString onDumpInfo() const override {
1075         SkString str = SkStringPrintf("# draws: %d\n", fQuads.count());
1076         auto iter = fQuads.iterator();
1077         for (unsigned p = 0; p < fMetadata.fProxyCount; ++p) {
1078             SkString proxyStr = fViewCountPairs[p].fProxy->dump();
1079             str.append(proxyStr);
1080             str.appendf(", Filter: %d, MM: %d\n",
1081                         static_cast<int>(fMetadata.fFilter),
1082                         static_cast<int>(fMetadata.fMipmapMode));
1083             for (int i = 0; i < fViewCountPairs[p].fQuadCnt && iter.next(); ++i) {
1084                 const GrQuad* quad = iter.deviceQuad();
1085                 GrQuad uv = iter.isLocalValid() ? *(iter.localQuad()) : GrQuad();
1086                 const ColorSubsetAndAA& info = iter.metadata();
1087                 str.appendf(
1088                         "%d: Color: 0x%08x, Subset(%d): [L: %.2f, T: %.2f, R: %.2f, B: %.2f]\n"
1089                         "  UVs  [(%.2f, %.2f), (%.2f, %.2f), (%.2f, %.2f), (%.2f, %.2f)]\n"
1090                         "  Quad [(%.2f, %.2f), (%.2f, %.2f), (%.2f, %.2f), (%.2f, %.2f)]\n",
1091                         i, info.fColor.toBytes_RGBA(), fMetadata.fSubset, info.fSubsetRect.fLeft,
1092                         info.fSubsetRect.fTop, info.fSubsetRect.fRight, info.fSubsetRect.fBottom,
1093                         quad->point(0).fX, quad->point(0).fY, quad->point(1).fX, quad->point(1).fY,
1094                         quad->point(2).fX, quad->point(2).fY, quad->point(3).fX, quad->point(3).fY,
1095                         uv.point(0).fX, uv.point(0).fY, uv.point(1).fX, uv.point(1).fY,
1096                         uv.point(2).fX, uv.point(2).fY, uv.point(3).fX, uv.point(3).fY);
1097             }
1098         }
1099         return str;
1100     }
1101 #endif
1102 
1103     GrQuadBuffer<ColorSubsetAndAA> fQuads;
1104     sk_sp<GrColorSpaceXform> fTextureColorSpaceXform;
1105     // Most state of TextureOp is packed into these two field to minimize the op's size.
1106     // Historically, increasing the size of TextureOp has caused surprising perf regressions, so
1107     // consider/measure changes with care.
1108     Desc* fDesc;
1109     Metadata fMetadata;
1110 
1111     // This field must go last. When allocating this op, we will allocate extra space to hold
1112     // additional ViewCountPairs immediately after the op's allocation so we can treat this
1113     // as an fProxyCnt-length array.
1114     ViewCountPair fViewCountPairs[1];
1115 
1116     using INHERITED = GrMeshDrawOp;
1117 };
1118 
1119 }  // anonymous namespace
1120 
1121 namespace skgpu::v1 {
1122 
1123 #if GR_TEST_UTILS
ClassID()1124 uint32_t TextureOp::ClassID() {
1125     return TextureOpImpl::ClassID();
1126 }
1127 #endif
1128 
Make(GrRecordingContext * context,GrSurfaceProxyView proxyView,SkAlphaType alphaType,sk_sp<GrColorSpaceXform> textureXform,GrSamplerState::Filter filter,GrSamplerState::MipmapMode mm,const SkPMColor4f & color,Saturate saturate,SkBlendMode blendMode,GrAAType aaType,DrawQuad * quad,const SkRect * subset)1129 GrOp::Owner TextureOp::Make(GrRecordingContext* context,
1130                             GrSurfaceProxyView proxyView,
1131                             SkAlphaType alphaType,
1132                             sk_sp<GrColorSpaceXform> textureXform,
1133                             GrSamplerState::Filter filter,
1134                             GrSamplerState::MipmapMode mm,
1135                             const SkPMColor4f& color,
1136                             Saturate saturate,
1137                             SkBlendMode blendMode,
1138                             GrAAType aaType,
1139                             DrawQuad* quad,
1140                             const SkRect* subset) {
1141     // Apply optimizations that are valid whether or not using TextureOp or FillRectOp
1142     if (subset && subset->contains(proxyView.proxy()->backingStoreBoundsRect())) {
1143         // No need for a shader-based subset if hardware clamping achieves the same effect
1144         subset = nullptr;
1145     }
1146 
1147     if (filter != GrSamplerState::Filter::kNearest || mm != GrSamplerState::MipmapMode::kNone) {
1148         auto [mustFilter, mustMM] = filter_and_mm_have_effect(quad->fLocal, quad->fDevice);
1149         if (!mustFilter) {
1150             filter = GrSamplerState::Filter::kNearest;
1151         }
1152         if (!mustMM) {
1153             mm = GrSamplerState::MipmapMode::kNone;
1154         }
1155     }
1156 
1157     if (blendMode == SkBlendMode::kSrcOver) {
1158         return TextureOpImpl::Make(context, std::move(proxyView), std::move(textureXform), filter,
1159                                    mm, color, saturate, aaType, std::move(quad), subset);
1160     } else {
1161         // Emulate complex blending using FillRectOp
1162         GrSamplerState samplerState(GrSamplerState::WrapMode::kClamp, filter, mm);
1163         GrPaint paint;
1164         paint.setColor4f(color);
1165         paint.setXPFactory(SkBlendMode_AsXPFactory(blendMode));
1166 
1167         std::unique_ptr<GrFragmentProcessor> fp;
1168         const auto& caps = *context->priv().caps();
1169         if (subset) {
1170             SkRect localRect;
1171             if (quad->fLocal.asRect(&localRect)) {
1172                 fp = GrTextureEffect::MakeSubset(std::move(proxyView), alphaType, SkMatrix::I(),
1173                                                  samplerState, *subset, localRect, caps);
1174             } else {
1175                 fp = GrTextureEffect::MakeSubset(std::move(proxyView), alphaType, SkMatrix::I(),
1176                                                  samplerState, *subset, caps);
1177             }
1178         } else {
1179             fp = GrTextureEffect::Make(std::move(proxyView), alphaType, SkMatrix::I(), samplerState,
1180                                        caps);
1181         }
1182         fp = GrColorSpaceXformEffect::Make(std::move(fp), std::move(textureXform));
1183         fp = GrBlendFragmentProcessor::Make(std::move(fp), nullptr, SkBlendMode::kModulate);
1184         if (saturate == Saturate::kYes) {
1185             fp = GrFragmentProcessor::ClampOutput(std::move(fp));
1186         }
1187         paint.setColorFragmentProcessor(std::move(fp));
1188         return FillRectOp::Make(context, std::move(paint), aaType, quad);
1189     }
1190 }
1191 
1192 // A helper class that assists in breaking up bulk API quad draws into manageable chunks.
1193 class TextureOp::BatchSizeLimiter {
1194 public:
BatchSizeLimiter(SurfaceDrawContext * sdc,const GrClip * clip,GrRecordingContext * rContext,int numEntries,GrSamplerState::Filter filter,GrSamplerState::MipmapMode mm,Saturate saturate,SkCanvas::SrcRectConstraint constraint,const SkMatrix & viewMatrix,sk_sp<GrColorSpaceXform> textureColorSpaceXform)1195     BatchSizeLimiter(SurfaceDrawContext* sdc,
1196                      const GrClip* clip,
1197                      GrRecordingContext* rContext,
1198                      int numEntries,
1199                      GrSamplerState::Filter filter,
1200                      GrSamplerState::MipmapMode mm,
1201                      Saturate saturate,
1202                      SkCanvas::SrcRectConstraint constraint,
1203                      const SkMatrix& viewMatrix,
1204                      sk_sp<GrColorSpaceXform> textureColorSpaceXform)
1205             : fSDC(sdc)
1206             , fClip(clip)
1207             , fContext(rContext)
1208             , fFilter(filter)
1209             , fMipmapMode(mm)
1210             , fSaturate(saturate)
1211             , fConstraint(constraint)
1212             , fViewMatrix(viewMatrix)
1213             , fTextureColorSpaceXform(textureColorSpaceXform)
1214             , fNumLeft(numEntries) {}
1215 
createOp(GrTextureSetEntry set[],int clumpSize,GrAAType aaType)1216     void createOp(GrTextureSetEntry set[], int clumpSize, GrAAType aaType) {
1217 
1218         int clumpProxyCount = proxy_run_count(&set[fNumClumped], clumpSize);
1219         GrOp::Owner op = TextureOpImpl::Make(fContext,
1220                                              &set[fNumClumped],
1221                                              clumpSize,
1222                                              clumpProxyCount,
1223                                              fFilter,
1224                                              fMipmapMode,
1225                                              fSaturate,
1226                                              aaType,
1227                                              fConstraint,
1228                                              fViewMatrix,
1229                                              fTextureColorSpaceXform);
1230         fSDC->addDrawOp(fClip, std::move(op));
1231 
1232         fNumLeft -= clumpSize;
1233         fNumClumped += clumpSize;
1234     }
1235 
numLeft() const1236     int numLeft() const { return fNumLeft;  }
baseIndex() const1237     int baseIndex() const { return fNumClumped; }
1238 
1239 private:
1240     SurfaceDrawContext*         fSDC;
1241     const GrClip*               fClip;
1242     GrRecordingContext*         fContext;
1243     GrSamplerState::Filter      fFilter;
1244     GrSamplerState::MipmapMode  fMipmapMode;
1245     Saturate                    fSaturate;
1246     SkCanvas::SrcRectConstraint fConstraint;
1247     const SkMatrix&             fViewMatrix;
1248     sk_sp<GrColorSpaceXform>    fTextureColorSpaceXform;
1249 
1250     int                         fNumLeft;
1251     int                         fNumClumped = 0; // also the offset for the start of the next clump
1252 };
1253 
1254 // Greedily clump quad draws together until the index buffer limit is exceeded.
AddTextureSetOps(SurfaceDrawContext * sdc,const GrClip * clip,GrRecordingContext * context,GrTextureSetEntry set[],int cnt,int proxyRunCnt,GrSamplerState::Filter filter,GrSamplerState::MipmapMode mm,Saturate saturate,SkBlendMode blendMode,GrAAType aaType,SkCanvas::SrcRectConstraint constraint,const SkMatrix & viewMatrix,sk_sp<GrColorSpaceXform> textureColorSpaceXform)1255 void TextureOp::AddTextureSetOps(SurfaceDrawContext* sdc,
1256                                  const GrClip* clip,
1257                                  GrRecordingContext* context,
1258                                  GrTextureSetEntry set[],
1259                                  int cnt,
1260                                  int proxyRunCnt,
1261                                  GrSamplerState::Filter filter,
1262                                  GrSamplerState::MipmapMode mm,
1263                                  Saturate saturate,
1264                                  SkBlendMode blendMode,
1265                                  GrAAType aaType,
1266                                  SkCanvas::SrcRectConstraint constraint,
1267                                  const SkMatrix& viewMatrix,
1268                                  sk_sp<GrColorSpaceXform> textureColorSpaceXform) {
1269     // Ensure that the index buffer limits are lower than the proxy and quad count limits of
1270     // the op's metadata so we don't need to worry about overflow.
1271     SkDEBUGCODE(TextureOpImpl::ValidateResourceLimits();)
1272     SkASSERT(proxy_run_count(set, cnt) == proxyRunCnt);
1273 
1274     // First check if we can support batches as a single op
1275     if (blendMode != SkBlendMode::kSrcOver ||
1276         !context->priv().caps()->dynamicStateArrayGeometryProcessorTextureSupport()) {
1277         // Append each entry as its own op; these may still be GrTextureOps if the blend mode is
1278         // src-over but the backend doesn't support dynamic state changes. Otherwise Make()
1279         // automatically creates the appropriate FillRectOp to emulate TextureOp.
1280         SkMatrix ctm;
1281         for (int i = 0; i < cnt; ++i) {
1282             ctm = viewMatrix;
1283             if (set[i].fPreViewMatrix) {
1284                 ctm.preConcat(*set[i].fPreViewMatrix);
1285             }
1286 
1287             DrawQuad quad;
1288             quad.fEdgeFlags = set[i].fAAFlags;
1289             if (set[i].fDstClipQuad) {
1290                 quad.fDevice = GrQuad::MakeFromSkQuad(set[i].fDstClipQuad, ctm);
1291 
1292                 SkPoint srcPts[4];
1293                 GrMapRectPoints(set[i].fDstRect, set[i].fSrcRect, set[i].fDstClipQuad, srcPts, 4);
1294                 quad.fLocal = GrQuad::MakeFromSkQuad(srcPts, SkMatrix::I());
1295             } else {
1296                 quad.fDevice = GrQuad::MakeFromRect(set[i].fDstRect, ctm);
1297                 quad.fLocal = GrQuad(set[i].fSrcRect);
1298             }
1299 
1300             const SkRect* subset = constraint == SkCanvas::kStrict_SrcRectConstraint
1301                     ? &set[i].fSrcRect : nullptr;
1302 
1303             auto op = Make(context, set[i].fProxyView, set[i].fSrcAlphaType, textureColorSpaceXform,
1304                            filter, mm, set[i].fColor, saturate, blendMode, aaType, &quad, subset);
1305             sdc->addDrawOp(clip, std::move(op));
1306         }
1307         return;
1308     }
1309 
1310     // Second check if we can always just make a single op and avoid the extra iteration
1311     // needed to clump things together.
1312     if (cnt <= std::min(GrResourceProvider::MaxNumNonAAQuads(),
1313                       GrResourceProvider::MaxNumAAQuads())) {
1314         auto op = TextureOpImpl::Make(context, set, cnt, proxyRunCnt, filter, mm, saturate, aaType,
1315                                       constraint, viewMatrix, std::move(textureColorSpaceXform));
1316         sdc->addDrawOp(clip, std::move(op));
1317         return;
1318     }
1319 
1320     BatchSizeLimiter state(sdc, clip, context, cnt, filter, mm, saturate, constraint, viewMatrix,
1321                            std::move(textureColorSpaceXform));
1322 
1323     // kNone and kMSAA never get altered
1324     if (aaType == GrAAType::kNone || aaType == GrAAType::kMSAA) {
1325         // Clump these into series of MaxNumNonAAQuads-sized GrTextureOps
1326         while (state.numLeft() > 0) {
1327             int clumpSize = std::min(state.numLeft(), GrResourceProvider::MaxNumNonAAQuads());
1328 
1329             state.createOp(set, clumpSize, aaType);
1330         }
1331     } else {
1332         // kCoverage can be downgraded to kNone. Note that the following is conservative. kCoverage
1333         // can also get downgraded to kNone if all the quads are on integer coordinates and
1334         // axis-aligned.
1335         SkASSERT(aaType == GrAAType::kCoverage);
1336 
1337         while (state.numLeft() > 0) {
1338             GrAAType runningAA = GrAAType::kNone;
1339             bool clumped = false;
1340 
1341             for (int i = 0; i < state.numLeft(); ++i) {
1342                 int absIndex = state.baseIndex() + i;
1343 
1344                 if (set[absIndex].fAAFlags != GrQuadAAFlags::kNone ||
1345                     runningAA == GrAAType::kCoverage) {
1346 
1347                     if (i >= GrResourceProvider::MaxNumAAQuads()) {
1348                         // Here we either need to boost the AA type to kCoverage, but doing so with
1349                         // all the accumulated quads would overflow, or we have a set of AA quads
1350                         // that has just gotten too large. In either case, calve off the existing
1351                         // quads as their own TextureOp.
1352                         state.createOp(
1353                             set,
1354                             runningAA == GrAAType::kNone ? i : GrResourceProvider::MaxNumAAQuads(),
1355                             runningAA); // maybe downgrading AA here
1356                         clumped = true;
1357                         break;
1358                     }
1359 
1360                     runningAA = GrAAType::kCoverage;
1361                 } else if (runningAA == GrAAType::kNone) {
1362 
1363                     if (i >= GrResourceProvider::MaxNumNonAAQuads()) {
1364                         // Here we've found a consistent batch of non-AA quads that has gotten too
1365                         // large. Calve it off as its own TextureOp.
1366                         state.createOp(set, GrResourceProvider::MaxNumNonAAQuads(),
1367                                        GrAAType::kNone); // definitely downgrading AA here
1368                         clumped = true;
1369                         break;
1370                     }
1371                 }
1372             }
1373 
1374             if (!clumped) {
1375                 // We ran through the above loop w/o hitting a limit. Spit out this last clump of
1376                 // quads and call it a day.
1377                 state.createOp(set, state.numLeft(), runningAA); // maybe downgrading AA here
1378             }
1379         }
1380     }
1381 }
1382 
1383 } // namespace skgpu::v1
1384 
1385 #if GR_TEST_UTILS
1386 #include "include/gpu/GrRecordingContext.h"
1387 #include "src/gpu/GrProxyProvider.h"
1388 #include "src/gpu/GrRecordingContextPriv.h"
1389 
GR_DRAW_OP_TEST_DEFINE(TextureOpImpl)1390 GR_DRAW_OP_TEST_DEFINE(TextureOpImpl) {
1391     SkISize dims;
1392     dims.fHeight = random->nextULessThan(90) + 10;
1393     dims.fWidth = random->nextULessThan(90) + 10;
1394     auto origin = random->nextBool() ? kTopLeft_GrSurfaceOrigin : kBottomLeft_GrSurfaceOrigin;
1395     GrMipmapped mipMapped = random->nextBool() ? GrMipmapped::kYes : GrMipmapped::kNo;
1396     SkBackingFit fit = SkBackingFit::kExact;
1397     if (mipMapped == GrMipmapped::kNo) {
1398         fit = random->nextBool() ? SkBackingFit::kApprox : SkBackingFit::kExact;
1399     }
1400     const GrBackendFormat format =
1401             context->priv().caps()->getDefaultBackendFormat(GrColorType::kRGBA_8888,
1402                                                             GrRenderable::kNo);
1403     GrProxyProvider* proxyProvider = context->priv().proxyProvider();
1404     sk_sp<GrTextureProxy> proxy = proxyProvider->createProxy(
1405             format, dims, GrRenderable::kNo, 1, mipMapped, fit, SkBudgeted::kNo, GrProtected::kNo,
1406             GrInternalSurfaceFlags::kNone);
1407 
1408     SkRect rect = GrTest::TestRect(random);
1409     SkRect srcRect;
1410     srcRect.fLeft = random->nextRangeScalar(0.f, proxy->width() / 2.f);
1411     srcRect.fRight = random->nextRangeScalar(0.f, proxy->width()) + proxy->width() / 2.f;
1412     srcRect.fTop = random->nextRangeScalar(0.f, proxy->height() / 2.f);
1413     srcRect.fBottom = random->nextRangeScalar(0.f, proxy->height()) + proxy->height() / 2.f;
1414     SkMatrix viewMatrix = GrTest::TestMatrixPreservesRightAngles(random);
1415     SkPMColor4f color = SkPMColor4f::FromBytes_RGBA(SkColorToPremulGrColor(random->nextU()));
1416     GrSamplerState::Filter filter = (GrSamplerState::Filter)random->nextULessThan(
1417             static_cast<uint32_t>(GrSamplerState::Filter::kLast) + 1);
1418     GrSamplerState::MipmapMode mm = GrSamplerState::MipmapMode::kNone;
1419     if (mipMapped == GrMipmapped::kYes) {
1420         mm = (GrSamplerState::MipmapMode)random->nextULessThan(
1421                 static_cast<uint32_t>(GrSamplerState::MipmapMode::kLast) + 1);
1422     }
1423 
1424     auto texXform = GrTest::TestColorXform(random);
1425     GrAAType aaType = GrAAType::kNone;
1426     if (random->nextBool()) {
1427         aaType = (numSamples > 1) ? GrAAType::kMSAA : GrAAType::kCoverage;
1428     }
1429     GrQuadAAFlags aaFlags = GrQuadAAFlags::kNone;
1430     aaFlags |= random->nextBool() ? GrQuadAAFlags::kLeft : GrQuadAAFlags::kNone;
1431     aaFlags |= random->nextBool() ? GrQuadAAFlags::kTop : GrQuadAAFlags::kNone;
1432     aaFlags |= random->nextBool() ? GrQuadAAFlags::kRight : GrQuadAAFlags::kNone;
1433     aaFlags |= random->nextBool() ? GrQuadAAFlags::kBottom : GrQuadAAFlags::kNone;
1434     bool useSubset = random->nextBool();
1435     auto saturate = random->nextBool() ? skgpu::v1::TextureOp::Saturate::kYes
1436                                        : skgpu::v1::TextureOp::Saturate::kNo;
1437     GrSurfaceProxyView proxyView(
1438             std::move(proxy), origin,
1439             context->priv().caps()->getReadSwizzle(format, GrColorType::kRGBA_8888));
1440     auto alphaType = static_cast<SkAlphaType>(
1441             random->nextRangeU(kUnknown_SkAlphaType + 1, kLastEnum_SkAlphaType));
1442 
1443     DrawQuad quad = {GrQuad::MakeFromRect(rect, viewMatrix), GrQuad(srcRect), aaFlags};
1444     return skgpu::v1::TextureOp::Make(context, std::move(proxyView), alphaType,
1445                                       std::move(texXform), filter, mm, color, saturate,
1446                                       SkBlendMode::kSrcOver, aaType, &quad,
1447                                       useSubset ? &srcRect : nullptr);
1448 }
1449 
1450 #endif // GR_TEST_UTILS
1451