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__anonf45251680111::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__anonf45251680111::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__anonf45251680111::TextureOpImpl::Metadata351 Metadata(const skgpu::Swizzle& 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 skgpu::Swizzle fSwizzle; // sizeof(skgpu::Swizzle) == 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__anonf45251680111::TextureOpImpl::Metadata380 GrSamplerState::Filter filter() const {
381 return static_cast<GrSamplerState::Filter>(fFilter);
382 }
mipmapMode__anonf45251680111::TextureOpImpl::Metadata383 GrSamplerState::MipmapMode mipmapMode() const {
384 return static_cast<GrSamplerState::MipmapMode>(fMipmapMode);
385 }
aaType__anonf45251680111::TextureOpImpl::Metadata386 GrAAType aaType() const { return static_cast<GrAAType>(fAAType); }
colorType__anonf45251680111::TextureOpImpl::Metadata387 ColorType colorType() const { return static_cast<ColorType>(fColorType); }
subset__anonf45251680111::TextureOpImpl::Metadata388 Subset subset() const { return static_cast<Subset>(fSubset); }
saturate__anonf45251680111::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__anonf45251680111::TextureOpImpl::Desc422 size_t totalSizeInBytes() const {
423 return this->totalNumVertices() * fVertexSpec.vertexSize();
424 }
425
totalNumVertices__anonf45251680111::TextureOpImpl::Desc426 int totalNumVertices() const {
427 return fNumTotalQuads * fVertexSpec.verticesPerQuad();
428 }
429
allocatePrePreparedVertices__anonf45251680111::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 SkDEBUGCODE(auto startMark{vertexData};)
725
726 skgpu::v1::QuadPerEdgeAA::Tessellator tessellator(desc->fVertexSpec, vertexData);
727 for (const auto& op : ChainRange<TextureOpImpl>(texOp)) {
728 auto iter = op.fQuads.iterator();
729 for (unsigned p = 0; p < op.fMetadata.fProxyCount; ++p) {
730 const int quadCnt = op.fViewCountPairs[p].fQuadCnt;
731 SkDEBUGCODE(int meshVertexCnt = quadCnt * desc->fVertexSpec.verticesPerQuad());
732
733 for (int i = 0; i < quadCnt && iter.next(); ++i) {
734 SkASSERT(iter.isLocalValid());
735 const ColorSubsetAndAA& info = iter.metadata();
736
737 tessellator.append(iter.deviceQuad(), iter.localQuad(), info.fColor,
738 info.fSubsetRect, info.aaFlags());
739 }
740
741 SkASSERT((totVerticesSeen + meshVertexCnt) * vertexSize
742 == (size_t)(tessellator.vertexMark() - startMark));
743
744 SkDEBUGCODE(totQuadsSeen += quadCnt;)
745 SkDEBUGCODE(totVerticesSeen += meshVertexCnt);
746 SkASSERT(totQuadsSeen * desc->fVertexSpec.verticesPerQuad() == totVerticesSeen);
747 }
748
749 // If quad counts per proxy were calculated correctly, the entire iterator
750 // should have been consumed.
751 SkASSERT(!iter.next());
752 }
753
754 SkASSERT(desc->totalSizeInBytes() == (size_t)(tessellator.vertexMark() - startMark));
755 SkASSERT(totQuadsSeen == desc->fNumTotalQuads);
756 SkASSERT(totVerticesSeen == desc->totalNumVertices());
757 }
758
759 #ifdef SK_DEBUG
validate_op(GrTextureType textureType,GrAAType aaType,skgpu::Swizzle swizzle,const TextureOpImpl * op)760 static int validate_op(GrTextureType textureType,
761 GrAAType aaType,
762 skgpu::Swizzle swizzle,
763 const TextureOpImpl* op) {
764 SkASSERT(op->fMetadata.fSwizzle == swizzle);
765
766 int quadCount = 0;
767 for (unsigned p = 0; p < op->fMetadata.fProxyCount; ++p) {
768 auto* proxy = op->fViewCountPairs[p].fProxy->asTextureProxy();
769 quadCount += op->fViewCountPairs[p].fQuadCnt;
770 SkASSERT(proxy);
771 SkASSERT(proxy->textureType() == textureType);
772 }
773
774 SkASSERT(aaType == op->fMetadata.aaType());
775 return quadCount;
776 }
777
validate() const778 void validate() const override {
779 // NOTE: Since this is debug-only code, we use the virtual asTextureProxy()
780 auto textureType = fViewCountPairs[0].fProxy->asTextureProxy()->textureType();
781 GrAAType aaType = fMetadata.aaType();
782 skgpu::Swizzle swizzle = fMetadata.fSwizzle;
783
784 int quadCount = validate_op(textureType, aaType, swizzle, this);
785
786 for (const GrOp* tmp = this->prevInChain(); tmp; tmp = tmp->prevInChain()) {
787 quadCount += validate_op(textureType, aaType, swizzle,
788 static_cast<const TextureOpImpl*>(tmp));
789 }
790
791 for (const GrOp* tmp = this->nextInChain(); tmp; tmp = tmp->nextInChain()) {
792 quadCount += validate_op(textureType, aaType, swizzle,
793 static_cast<const TextureOpImpl*>(tmp));
794 }
795
796 SkASSERT(quadCount == this->numChainedQuads());
797 }
798
799 #endif
800
801 #if GR_TEST_UTILS
numQuads() const802 int numQuads() const final { return this->totNumQuads(); }
803 #endif
804
characterize(Desc * desc) const805 void characterize(Desc* desc) const {
806 SkDEBUGCODE(this->validate();)
807
808 GrQuad::Type quadType = GrQuad::Type::kAxisAligned;
809 ColorType colorType = ColorType::kNone;
810 GrQuad::Type srcQuadType = GrQuad::Type::kAxisAligned;
811 Subset subset = Subset::kNo;
812 GrAAType overallAAType = fMetadata.aaType();
813
814 desc->fNumProxies = 0;
815 desc->fNumTotalQuads = 0;
816 int maxQuadsPerMesh = 0;
817
818 for (const auto& op : ChainRange<TextureOpImpl>(this)) {
819 if (op.fQuads.deviceQuadType() > quadType) {
820 quadType = op.fQuads.deviceQuadType();
821 }
822 if (op.fQuads.localQuadType() > srcQuadType) {
823 srcQuadType = op.fQuads.localQuadType();
824 }
825 if (op.fMetadata.subset() == Subset::kYes) {
826 subset = Subset::kYes;
827 }
828 colorType = std::max(colorType, op.fMetadata.colorType());
829 desc->fNumProxies += op.fMetadata.fProxyCount;
830
831 for (unsigned p = 0; p < op.fMetadata.fProxyCount; ++p) {
832 maxQuadsPerMesh = std::max(op.fViewCountPairs[p].fQuadCnt, maxQuadsPerMesh);
833 }
834 desc->fNumTotalQuads += op.totNumQuads();
835
836 if (op.fMetadata.aaType() == GrAAType::kCoverage) {
837 overallAAType = GrAAType::kCoverage;
838 }
839 }
840
841 SkASSERT(desc->fNumTotalQuads == this->numChainedQuads());
842
843 SkASSERT(!CombinedQuadCountWillOverflow(overallAAType, false, desc->fNumTotalQuads));
844
845 auto indexBufferOption = skgpu::v1::QuadPerEdgeAA::CalcIndexBufferOption(overallAAType,
846 maxQuadsPerMesh);
847
848 desc->fVertexSpec = VertexSpec(quadType, colorType, srcQuadType, /* hasLocal */ true,
849 subset, overallAAType, /* alpha as coverage */ true,
850 indexBufferOption);
851
852 SkASSERT(desc->fNumTotalQuads <= skgpu::v1::QuadPerEdgeAA::QuadLimit(indexBufferOption));
853 }
854
totNumQuads() const855 int totNumQuads() const {
856 #ifdef SK_DEBUG
857 int tmp = 0;
858 for (unsigned p = 0; p < fMetadata.fProxyCount; ++p) {
859 tmp += fViewCountPairs[p].fQuadCnt;
860 }
861 SkASSERT(tmp == fMetadata.fTotalQuadCount);
862 #endif
863
864 return fMetadata.fTotalQuadCount;
865 }
866
numChainedQuads() const867 int numChainedQuads() const {
868 int numChainedQuads = this->totNumQuads();
869
870 for (const GrOp* tmp = this->prevInChain(); tmp; tmp = tmp->prevInChain()) {
871 numChainedQuads += ((const TextureOpImpl*)tmp)->totNumQuads();
872 }
873
874 for (const GrOp* tmp = this->nextInChain(); tmp; tmp = tmp->nextInChain()) {
875 numChainedQuads += ((const TextureOpImpl*)tmp)->totNumQuads();
876 }
877
878 return numChainedQuads;
879 }
880
881 // onPrePrepareDraws may or may not have been called at this point
onPrepareDraws(GrMeshDrawTarget * target)882 void onPrepareDraws(GrMeshDrawTarget* target) override {
883 TRACE_EVENT0("skia.gpu", TRACE_FUNC);
884
885 SkDEBUGCODE(this->validate();)
886
887 SkASSERT(!fDesc || fDesc->fPrePreparedVertices);
888
889 if (!fDesc) {
890 SkArenaAlloc* arena = target->allocator();
891 fDesc = arena->make<Desc>();
892 this->characterize(fDesc);
893 SkASSERT(!fDesc->fPrePreparedVertices);
894 }
895
896 size_t vertexSize = fDesc->fVertexSpec.vertexSize();
897
898 void* vdata = target->makeVertexSpace(vertexSize, fDesc->totalNumVertices(),
899 &fDesc->fVertexBuffer, &fDesc->fBaseVertex);
900 if (!vdata) {
901 SkDebugf("Could not allocate vertices\n");
902 return;
903 }
904
905 if (fDesc->fVertexSpec.needsIndexBuffer()) {
906 fDesc->fIndexBuffer = skgpu::v1::QuadPerEdgeAA::GetIndexBuffer(
907 target, fDesc->fVertexSpec.indexBufferOption());
908 if (!fDesc->fIndexBuffer) {
909 SkDebugf("Could not allocate indices\n");
910 return;
911 }
912 }
913
914 if (fDesc->fPrePreparedVertices) {
915 memcpy(vdata, fDesc->fPrePreparedVertices, fDesc->totalSizeInBytes());
916 } else {
917 FillInVertices(target->caps(), this, fDesc, (char*) vdata);
918 }
919 }
920
onExecute(GrOpFlushState * flushState,const SkRect & chainBounds)921 void onExecute(GrOpFlushState* flushState, const SkRect& chainBounds) override {
922 if (!fDesc->fVertexBuffer) {
923 return;
924 }
925
926 if (fDesc->fVertexSpec.needsIndexBuffer() && !fDesc->fIndexBuffer) {
927 return;
928 }
929
930 if (!fDesc->fProgramInfo) {
931 this->createProgramInfo(flushState);
932 SkASSERT(fDesc->fProgramInfo);
933 }
934
935 flushState->bindPipelineAndScissorClip(*fDesc->fProgramInfo, chainBounds);
936 flushState->bindBuffers(std::move(fDesc->fIndexBuffer), nullptr,
937 std::move(fDesc->fVertexBuffer));
938
939 int totQuadsSeen = 0;
940 SkDEBUGCODE(int numDraws = 0;)
941 for (const auto& op : ChainRange<TextureOpImpl>(this)) {
942 for (unsigned p = 0; p < op.fMetadata.fProxyCount; ++p) {
943 const int quadCnt = op.fViewCountPairs[p].fQuadCnt;
944 SkASSERT(numDraws < fDesc->fNumProxies);
945 flushState->bindTextures(fDesc->fProgramInfo->geomProc(),
946 *op.fViewCountPairs[p].fProxy,
947 fDesc->fProgramInfo->pipeline());
948 skgpu::v1::QuadPerEdgeAA::IssueDraw(flushState->caps(), flushState->opsRenderPass(),
949 fDesc->fVertexSpec, totQuadsSeen, quadCnt,
950 fDesc->totalNumVertices(), fDesc->fBaseVertex);
951 totQuadsSeen += quadCnt;
952 SkDEBUGCODE(++numDraws;)
953 }
954 }
955
956 SkASSERT(totQuadsSeen == fDesc->fNumTotalQuads);
957 SkASSERT(numDraws == fDesc->fNumProxies);
958 }
959
propagateCoverageAAThroughoutChain()960 void propagateCoverageAAThroughoutChain() {
961 fMetadata.fAAType = static_cast<uint16_t>(GrAAType::kCoverage);
962
963 for (GrOp* tmp = this->prevInChain(); tmp; tmp = tmp->prevInChain()) {
964 auto tex = static_cast<TextureOpImpl*>(tmp);
965 SkASSERT(tex->fMetadata.aaType() == GrAAType::kCoverage ||
966 tex->fMetadata.aaType() == GrAAType::kNone);
967 tex->fMetadata.fAAType = static_cast<uint16_t>(GrAAType::kCoverage);
968 }
969
970 for (GrOp* tmp = this->nextInChain(); tmp; tmp = tmp->nextInChain()) {
971 auto tex = static_cast<TextureOpImpl*>(tmp);
972 SkASSERT(tex->fMetadata.aaType() == GrAAType::kCoverage ||
973 tex->fMetadata.aaType() == GrAAType::kNone);
974 tex->fMetadata.fAAType = static_cast<uint16_t>(GrAAType::kCoverage);
975 }
976 }
977
onCombineIfPossible(GrOp * t,SkArenaAlloc *,const GrCaps & caps)978 CombineResult onCombineIfPossible(GrOp* t, SkArenaAlloc*, const GrCaps& caps) override {
979 TRACE_EVENT0("skia.gpu", TRACE_FUNC);
980 auto that = t->cast<TextureOpImpl>();
981
982 SkDEBUGCODE(this->validate();)
983 SkDEBUGCODE(that->validate();)
984
985 if (fDesc || that->fDesc) {
986 // This should never happen (since only DDL recorded ops should be prePrepared)
987 // but, in any case, we should never combine ops that that been prePrepared
988 return CombineResult::kCannotCombine;
989 }
990
991 if (fMetadata.subset() != that->fMetadata.subset()) {
992 // It is technically possible to combine operations across subset modes, but performance
993 // testing suggests it's better to make more draw calls where some take advantage of
994 // the more optimal shader path without coordinate clamping.
995 return CombineResult::kCannotCombine;
996 }
997 if (!GrColorSpaceXform::Equals(fTextureColorSpaceXform.get(),
998 that->fTextureColorSpaceXform.get())) {
999 return CombineResult::kCannotCombine;
1000 }
1001
1002 bool upgradeToCoverageAAOnMerge = false;
1003 if (fMetadata.aaType() != that->fMetadata.aaType()) {
1004 if (!CanUpgradeAAOnMerge(fMetadata.aaType(), that->fMetadata.aaType())) {
1005 return CombineResult::kCannotCombine;
1006 }
1007 upgradeToCoverageAAOnMerge = true;
1008 }
1009
1010 if (CombinedQuadCountWillOverflow(fMetadata.aaType(), upgradeToCoverageAAOnMerge,
1011 this->numChainedQuads() + that->numChainedQuads())) {
1012 return CombineResult::kCannotCombine;
1013 }
1014
1015 if (fMetadata.saturate() != that->fMetadata.saturate()) {
1016 return CombineResult::kCannotCombine;
1017 }
1018 if (fMetadata.filter() != that->fMetadata.filter()) {
1019 return CombineResult::kCannotCombine;
1020 }
1021 if (fMetadata.mipmapMode() != that->fMetadata.mipmapMode()) {
1022 return CombineResult::kCannotCombine;
1023 }
1024 if (fMetadata.fSwizzle != that->fMetadata.fSwizzle) {
1025 return CombineResult::kCannotCombine;
1026 }
1027 const auto* thisProxy = fViewCountPairs[0].fProxy.get();
1028 const auto* thatProxy = that->fViewCountPairs[0].fProxy.get();
1029 if (fMetadata.fProxyCount > 1 || that->fMetadata.fProxyCount > 1 ||
1030 thisProxy != thatProxy) {
1031 // We can't merge across different proxies. Check if 'this' can be chained with 'that'.
1032 if (GrTextureProxy::ProxiesAreCompatibleAsDynamicState(thisProxy, thatProxy) &&
1033 caps.dynamicStateArrayGeometryProcessorTextureSupport() &&
1034 fMetadata.aaType() == that->fMetadata.aaType()) {
1035 // We only allow chaining when the aaTypes match bc otherwise the AA type
1036 // reported by the chain can be inconsistent. That is, since chaining doesn't
1037 // propagate revised AA information throughout the chain, the head of the chain
1038 // could have an AA setting of kNone while the chain as a whole could have a
1039 // setting of kCoverage. This inconsistency would then interfere with the validity
1040 // of the CombinedQuadCountWillOverflow calls.
1041 // This problem doesn't occur w/ merging bc we do propagate the AA information
1042 // (in propagateCoverageAAThroughoutChain) below.
1043 return CombineResult::kMayChain;
1044 }
1045 return CombineResult::kCannotCombine;
1046 }
1047
1048 fMetadata.fSubset |= that->fMetadata.fSubset;
1049 fMetadata.fColorType = std::max(fMetadata.fColorType, that->fMetadata.fColorType);
1050
1051 // Concatenate quad lists together
1052 fQuads.concat(that->fQuads);
1053 fViewCountPairs[0].fQuadCnt += that->fQuads.count();
1054 fMetadata.fTotalQuadCount += that->fQuads.count();
1055
1056 if (upgradeToCoverageAAOnMerge) {
1057 // This merger may be the start of a concatenation of two chains. When one
1058 // of the chains mutates its AA the other must follow suit or else the above AA
1059 // check may prevent later ops from chaining together. A specific example of this is
1060 // when chain2 is prepended onto chain1:
1061 // chain1 (that): opA (non-AA/mergeable) opB (non-AA/non-mergeable)
1062 // chain2 (this): opC (cov-AA/non-mergeable) opD (cov-AA/mergeable)
1063 // W/o this propagation, after opD & opA merge, opB and opC would say they couldn't
1064 // chain - which would stop the concatenation process.
1065 this->propagateCoverageAAThroughoutChain();
1066 that->propagateCoverageAAThroughoutChain();
1067 }
1068
1069 SkDEBUGCODE(this->validate();)
1070
1071 return CombineResult::kMerged;
1072 }
1073
1074 #if GR_TEST_UTILS
onDumpInfo() const1075 SkString onDumpInfo() const override {
1076 SkString str = SkStringPrintf("# draws: %d\n", fQuads.count());
1077 auto iter = fQuads.iterator();
1078 for (unsigned p = 0; p < fMetadata.fProxyCount; ++p) {
1079 SkString proxyStr = fViewCountPairs[p].fProxy->dump();
1080 str.append(proxyStr);
1081 str.appendf(", Filter: %d, MM: %d\n",
1082 static_cast<int>(fMetadata.fFilter),
1083 static_cast<int>(fMetadata.fMipmapMode));
1084 for (int i = 0; i < fViewCountPairs[p].fQuadCnt && iter.next(); ++i) {
1085 const GrQuad* quad = iter.deviceQuad();
1086 GrQuad uv = iter.isLocalValid() ? *(iter.localQuad()) : GrQuad();
1087 const ColorSubsetAndAA& info = iter.metadata();
1088 str.appendf(
1089 "%d: Color: 0x%08x, Subset(%d): [L: %.2f, T: %.2f, R: %.2f, B: %.2f]\n"
1090 " UVs [(%.2f, %.2f), (%.2f, %.2f), (%.2f, %.2f), (%.2f, %.2f)]\n"
1091 " Quad [(%.2f, %.2f), (%.2f, %.2f), (%.2f, %.2f), (%.2f, %.2f)]\n",
1092 i, info.fColor.toBytes_RGBA(), fMetadata.fSubset, info.fSubsetRect.fLeft,
1093 info.fSubsetRect.fTop, info.fSubsetRect.fRight, info.fSubsetRect.fBottom,
1094 quad->point(0).fX, quad->point(0).fY, quad->point(1).fX, quad->point(1).fY,
1095 quad->point(2).fX, quad->point(2).fY, quad->point(3).fX, quad->point(3).fY,
1096 uv.point(0).fX, uv.point(0).fY, uv.point(1).fX, uv.point(1).fY,
1097 uv.point(2).fX, uv.point(2).fY, uv.point(3).fX, uv.point(3).fY);
1098 }
1099 }
1100 return str;
1101 }
1102 #endif
1103
1104 GrQuadBuffer<ColorSubsetAndAA> fQuads;
1105 sk_sp<GrColorSpaceXform> fTextureColorSpaceXform;
1106 // Most state of TextureOp is packed into these two field to minimize the op's size.
1107 // Historically, increasing the size of TextureOp has caused surprising perf regressions, so
1108 // consider/measure changes with care.
1109 Desc* fDesc;
1110 Metadata fMetadata;
1111
1112 // This field must go last. When allocating this op, we will allocate extra space to hold
1113 // additional ViewCountPairs immediately after the op's allocation so we can treat this
1114 // as an fProxyCnt-length array.
1115 ViewCountPair fViewCountPairs[1];
1116
1117 using INHERITED = GrMeshDrawOp;
1118 };
1119
1120 } // anonymous namespace
1121
1122 namespace skgpu::v1 {
1123
1124 #if GR_TEST_UTILS
ClassID()1125 uint32_t TextureOp::ClassID() {
1126 return TextureOpImpl::ClassID();
1127 }
1128 #endif
1129
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)1130 GrOp::Owner TextureOp::Make(GrRecordingContext* context,
1131 GrSurfaceProxyView proxyView,
1132 SkAlphaType alphaType,
1133 sk_sp<GrColorSpaceXform> textureXform,
1134 GrSamplerState::Filter filter,
1135 GrSamplerState::MipmapMode mm,
1136 const SkPMColor4f& color,
1137 Saturate saturate,
1138 SkBlendMode blendMode,
1139 GrAAType aaType,
1140 DrawQuad* quad,
1141 const SkRect* subset) {
1142 // Apply optimizations that are valid whether or not using TextureOp or FillRectOp
1143 if (subset && subset->contains(proxyView.proxy()->backingStoreBoundsRect())) {
1144 // No need for a shader-based subset if hardware clamping achieves the same effect
1145 subset = nullptr;
1146 }
1147
1148 if (filter != GrSamplerState::Filter::kNearest || mm != GrSamplerState::MipmapMode::kNone) {
1149 auto [mustFilter, mustMM] = filter_and_mm_have_effect(quad->fLocal, quad->fDevice);
1150 if (!mustFilter) {
1151 filter = GrSamplerState::Filter::kNearest;
1152 }
1153 if (!mustMM) {
1154 mm = GrSamplerState::MipmapMode::kNone;
1155 }
1156 }
1157
1158 if (blendMode == SkBlendMode::kSrcOver) {
1159 return TextureOpImpl::Make(context, std::move(proxyView), std::move(textureXform), filter,
1160 mm, color, saturate, aaType, std::move(quad), subset);
1161 } else {
1162 // Emulate complex blending using FillRectOp
1163 GrSamplerState samplerState(GrSamplerState::WrapMode::kClamp, filter, mm);
1164 GrPaint paint;
1165 paint.setColor4f(color);
1166 paint.setXPFactory(SkBlendMode_AsXPFactory(blendMode));
1167
1168 std::unique_ptr<GrFragmentProcessor> fp;
1169 const auto& caps = *context->priv().caps();
1170 if (subset) {
1171 SkRect localRect;
1172 if (quad->fLocal.asRect(&localRect)) {
1173 fp = GrTextureEffect::MakeSubset(std::move(proxyView), alphaType, SkMatrix::I(),
1174 samplerState, *subset, localRect, caps);
1175 } else {
1176 fp = GrTextureEffect::MakeSubset(std::move(proxyView), alphaType, SkMatrix::I(),
1177 samplerState, *subset, caps);
1178 }
1179 } else {
1180 fp = GrTextureEffect::Make(std::move(proxyView), alphaType, SkMatrix::I(), samplerState,
1181 caps);
1182 }
1183 fp = GrColorSpaceXformEffect::Make(std::move(fp), std::move(textureXform));
1184 fp = GrBlendFragmentProcessor::Make(std::move(fp), nullptr, SkBlendMode::kModulate);
1185 if (saturate == Saturate::kYes) {
1186 fp = GrFragmentProcessor::ClampOutput(std::move(fp));
1187 }
1188 paint.setColorFragmentProcessor(std::move(fp));
1189 return FillRectOp::Make(context, std::move(paint), aaType, quad);
1190 }
1191 }
1192
1193 // A helper class that assists in breaking up bulk API quad draws into manageable chunks.
1194 class TextureOp::BatchSizeLimiter {
1195 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)1196 BatchSizeLimiter(SurfaceDrawContext* sdc,
1197 const GrClip* clip,
1198 GrRecordingContext* rContext,
1199 int numEntries,
1200 GrSamplerState::Filter filter,
1201 GrSamplerState::MipmapMode mm,
1202 Saturate saturate,
1203 SkCanvas::SrcRectConstraint constraint,
1204 const SkMatrix& viewMatrix,
1205 sk_sp<GrColorSpaceXform> textureColorSpaceXform)
1206 : fSDC(sdc)
1207 , fClip(clip)
1208 , fContext(rContext)
1209 , fFilter(filter)
1210 , fMipmapMode(mm)
1211 , fSaturate(saturate)
1212 , fConstraint(constraint)
1213 , fViewMatrix(viewMatrix)
1214 , fTextureColorSpaceXform(textureColorSpaceXform)
1215 , fNumLeft(numEntries) {}
1216
createOp(GrTextureSetEntry set[],int clumpSize,GrAAType aaType)1217 void createOp(GrTextureSetEntry set[], int clumpSize, GrAAType aaType) {
1218
1219 int clumpProxyCount = proxy_run_count(&set[fNumClumped], clumpSize);
1220 GrOp::Owner op = TextureOpImpl::Make(fContext,
1221 &set[fNumClumped],
1222 clumpSize,
1223 clumpProxyCount,
1224 fFilter,
1225 fMipmapMode,
1226 fSaturate,
1227 aaType,
1228 fConstraint,
1229 fViewMatrix,
1230 fTextureColorSpaceXform);
1231 fSDC->addDrawOp(fClip, std::move(op));
1232
1233 fNumLeft -= clumpSize;
1234 fNumClumped += clumpSize;
1235 }
1236
numLeft() const1237 int numLeft() const { return fNumLeft; }
baseIndex() const1238 int baseIndex() const { return fNumClumped; }
1239
1240 private:
1241 SurfaceDrawContext* fSDC;
1242 const GrClip* fClip;
1243 GrRecordingContext* fContext;
1244 GrSamplerState::Filter fFilter;
1245 GrSamplerState::MipmapMode fMipmapMode;
1246 Saturate fSaturate;
1247 SkCanvas::SrcRectConstraint fConstraint;
1248 const SkMatrix& fViewMatrix;
1249 sk_sp<GrColorSpaceXform> fTextureColorSpaceXform;
1250
1251 int fNumLeft;
1252 int fNumClumped = 0; // also the offset for the start of the next clump
1253 };
1254
1255 // 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)1256 void TextureOp::AddTextureSetOps(SurfaceDrawContext* sdc,
1257 const GrClip* clip,
1258 GrRecordingContext* context,
1259 GrTextureSetEntry set[],
1260 int cnt,
1261 int proxyRunCnt,
1262 GrSamplerState::Filter filter,
1263 GrSamplerState::MipmapMode mm,
1264 Saturate saturate,
1265 SkBlendMode blendMode,
1266 GrAAType aaType,
1267 SkCanvas::SrcRectConstraint constraint,
1268 const SkMatrix& viewMatrix,
1269 sk_sp<GrColorSpaceXform> textureColorSpaceXform) {
1270 // Ensure that the index buffer limits are lower than the proxy and quad count limits of
1271 // the op's metadata so we don't need to worry about overflow.
1272 SkDEBUGCODE(TextureOpImpl::ValidateResourceLimits();)
1273 SkASSERT(proxy_run_count(set, cnt) == proxyRunCnt);
1274
1275 // First check if we can support batches as a single op
1276 if (blendMode != SkBlendMode::kSrcOver ||
1277 !context->priv().caps()->dynamicStateArrayGeometryProcessorTextureSupport()) {
1278 // Append each entry as its own op; these may still be GrTextureOps if the blend mode is
1279 // src-over but the backend doesn't support dynamic state changes. Otherwise Make()
1280 // automatically creates the appropriate FillRectOp to emulate TextureOp.
1281 SkMatrix ctm;
1282 for (int i = 0; i < cnt; ++i) {
1283 ctm = viewMatrix;
1284 if (set[i].fPreViewMatrix) {
1285 ctm.preConcat(*set[i].fPreViewMatrix);
1286 }
1287
1288 DrawQuad quad;
1289 quad.fEdgeFlags = set[i].fAAFlags;
1290 if (set[i].fDstClipQuad) {
1291 quad.fDevice = GrQuad::MakeFromSkQuad(set[i].fDstClipQuad, ctm);
1292
1293 SkPoint srcPts[4];
1294 GrMapRectPoints(set[i].fDstRect, set[i].fSrcRect, set[i].fDstClipQuad, srcPts, 4);
1295 quad.fLocal = GrQuad::MakeFromSkQuad(srcPts, SkMatrix::I());
1296 } else {
1297 quad.fDevice = GrQuad::MakeFromRect(set[i].fDstRect, ctm);
1298 quad.fLocal = GrQuad(set[i].fSrcRect);
1299 }
1300
1301 const SkRect* subset = constraint == SkCanvas::kStrict_SrcRectConstraint
1302 ? &set[i].fSrcRect : nullptr;
1303
1304 auto op = Make(context, set[i].fProxyView, set[i].fSrcAlphaType, textureColorSpaceXform,
1305 filter, mm, set[i].fColor, saturate, blendMode, aaType, &quad, subset);
1306 sdc->addDrawOp(clip, std::move(op));
1307 }
1308 return;
1309 }
1310
1311 // Second check if we can always just make a single op and avoid the extra iteration
1312 // needed to clump things together.
1313 if (cnt <= std::min(GrResourceProvider::MaxNumNonAAQuads(),
1314 GrResourceProvider::MaxNumAAQuads())) {
1315 auto op = TextureOpImpl::Make(context, set, cnt, proxyRunCnt, filter, mm, saturate, aaType,
1316 constraint, viewMatrix, std::move(textureColorSpaceXform));
1317 sdc->addDrawOp(clip, std::move(op));
1318 return;
1319 }
1320
1321 BatchSizeLimiter state(sdc, clip, context, cnt, filter, mm, saturate, constraint, viewMatrix,
1322 std::move(textureColorSpaceXform));
1323
1324 // kNone and kMSAA never get altered
1325 if (aaType == GrAAType::kNone || aaType == GrAAType::kMSAA) {
1326 // Clump these into series of MaxNumNonAAQuads-sized GrTextureOps
1327 while (state.numLeft() > 0) {
1328 int clumpSize = std::min(state.numLeft(), GrResourceProvider::MaxNumNonAAQuads());
1329
1330 state.createOp(set, clumpSize, aaType);
1331 }
1332 } else {
1333 // kCoverage can be downgraded to kNone. Note that the following is conservative. kCoverage
1334 // can also get downgraded to kNone if all the quads are on integer coordinates and
1335 // axis-aligned.
1336 SkASSERT(aaType == GrAAType::kCoverage);
1337
1338 while (state.numLeft() > 0) {
1339 GrAAType runningAA = GrAAType::kNone;
1340 bool clumped = false;
1341
1342 for (int i = 0; i < state.numLeft(); ++i) {
1343 int absIndex = state.baseIndex() + i;
1344
1345 if (set[absIndex].fAAFlags != GrQuadAAFlags::kNone ||
1346 runningAA == GrAAType::kCoverage) {
1347
1348 if (i >= GrResourceProvider::MaxNumAAQuads()) {
1349 // Here we either need to boost the AA type to kCoverage, but doing so with
1350 // all the accumulated quads would overflow, or we have a set of AA quads
1351 // that has just gotten too large. In either case, calve off the existing
1352 // quads as their own TextureOp.
1353 state.createOp(
1354 set,
1355 runningAA == GrAAType::kNone ? i : GrResourceProvider::MaxNumAAQuads(),
1356 runningAA); // maybe downgrading AA here
1357 clumped = true;
1358 break;
1359 }
1360
1361 runningAA = GrAAType::kCoverage;
1362 } else if (runningAA == GrAAType::kNone) {
1363
1364 if (i >= GrResourceProvider::MaxNumNonAAQuads()) {
1365 // Here we've found a consistent batch of non-AA quads that has gotten too
1366 // large. Calve it off as its own TextureOp.
1367 state.createOp(set, GrResourceProvider::MaxNumNonAAQuads(),
1368 GrAAType::kNone); // definitely downgrading AA here
1369 clumped = true;
1370 break;
1371 }
1372 }
1373 }
1374
1375 if (!clumped) {
1376 // We ran through the above loop w/o hitting a limit. Spit out this last clump of
1377 // quads and call it a day.
1378 state.createOp(set, state.numLeft(), runningAA); // maybe downgrading AA here
1379 }
1380 }
1381 }
1382 }
1383
1384 } // namespace skgpu::v1
1385
1386 #if GR_TEST_UTILS
1387 #include "include/gpu/GrRecordingContext.h"
1388 #include "src/gpu/GrProxyProvider.h"
1389 #include "src/gpu/GrRecordingContextPriv.h"
1390
GR_DRAW_OP_TEST_DEFINE(TextureOpImpl)1391 GR_DRAW_OP_TEST_DEFINE(TextureOpImpl) {
1392 SkISize dims;
1393 dims.fHeight = random->nextULessThan(90) + 10;
1394 dims.fWidth = random->nextULessThan(90) + 10;
1395 auto origin = random->nextBool() ? kTopLeft_GrSurfaceOrigin : kBottomLeft_GrSurfaceOrigin;
1396 GrMipmapped mipMapped = random->nextBool() ? GrMipmapped::kYes : GrMipmapped::kNo;
1397 SkBackingFit fit = SkBackingFit::kExact;
1398 if (mipMapped == GrMipmapped::kNo) {
1399 fit = random->nextBool() ? SkBackingFit::kApprox : SkBackingFit::kExact;
1400 }
1401 const GrBackendFormat format =
1402 context->priv().caps()->getDefaultBackendFormat(GrColorType::kRGBA_8888,
1403 GrRenderable::kNo);
1404 GrProxyProvider* proxyProvider = context->priv().proxyProvider();
1405 sk_sp<GrTextureProxy> proxy = proxyProvider->createProxy(
1406 format, dims, GrRenderable::kNo, 1, mipMapped, fit, SkBudgeted::kNo, GrProtected::kNo,
1407 GrInternalSurfaceFlags::kNone);
1408
1409 SkRect rect = GrTest::TestRect(random);
1410 SkRect srcRect;
1411 srcRect.fLeft = random->nextRangeScalar(0.f, proxy->width() / 2.f);
1412 srcRect.fRight = random->nextRangeScalar(0.f, proxy->width()) + proxy->width() / 2.f;
1413 srcRect.fTop = random->nextRangeScalar(0.f, proxy->height() / 2.f);
1414 srcRect.fBottom = random->nextRangeScalar(0.f, proxy->height()) + proxy->height() / 2.f;
1415 SkMatrix viewMatrix = GrTest::TestMatrixPreservesRightAngles(random);
1416 SkPMColor4f color = SkPMColor4f::FromBytes_RGBA(SkColorToPremulGrColor(random->nextU()));
1417 GrSamplerState::Filter filter = (GrSamplerState::Filter)random->nextULessThan(
1418 static_cast<uint32_t>(GrSamplerState::Filter::kLast) + 1);
1419 GrSamplerState::MipmapMode mm = GrSamplerState::MipmapMode::kNone;
1420 if (mipMapped == GrMipmapped::kYes) {
1421 mm = (GrSamplerState::MipmapMode)random->nextULessThan(
1422 static_cast<uint32_t>(GrSamplerState::MipmapMode::kLast) + 1);
1423 }
1424
1425 auto texXform = GrTest::TestColorXform(random);
1426 GrAAType aaType = GrAAType::kNone;
1427 if (random->nextBool()) {
1428 aaType = (numSamples > 1) ? GrAAType::kMSAA : GrAAType::kCoverage;
1429 }
1430 GrQuadAAFlags aaFlags = GrQuadAAFlags::kNone;
1431 aaFlags |= random->nextBool() ? GrQuadAAFlags::kLeft : GrQuadAAFlags::kNone;
1432 aaFlags |= random->nextBool() ? GrQuadAAFlags::kTop : GrQuadAAFlags::kNone;
1433 aaFlags |= random->nextBool() ? GrQuadAAFlags::kRight : GrQuadAAFlags::kNone;
1434 aaFlags |= random->nextBool() ? GrQuadAAFlags::kBottom : GrQuadAAFlags::kNone;
1435 bool useSubset = random->nextBool();
1436 auto saturate = random->nextBool() ? skgpu::v1::TextureOp::Saturate::kYes
1437 : skgpu::v1::TextureOp::Saturate::kNo;
1438 GrSurfaceProxyView proxyView(
1439 std::move(proxy), origin,
1440 context->priv().caps()->getReadSwizzle(format, GrColorType::kRGBA_8888));
1441 auto alphaType = static_cast<SkAlphaType>(
1442 random->nextRangeU(kUnknown_SkAlphaType + 1, kLastEnum_SkAlphaType));
1443
1444 DrawQuad quad = {GrQuad::MakeFromRect(rect, viewMatrix), GrQuad(srcRect), aaFlags};
1445 return skgpu::v1::TextureOp::Make(context, std::move(proxyView), alphaType,
1446 std::move(texXform), filter, mm, color, saturate,
1447 SkBlendMode::kSrcOver, aaType, &quad,
1448 useSubset ? &srcRect : nullptr);
1449 }
1450
1451 #endif // GR_TEST_UTILS
1452