1 /*
2  * Copyright 2019 Google Inc.
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7 
8 // This test only works with the GPU backend.
9 
10 #include "gm/gm.h"
11 #include "include/core/SkBitmap.h"
12 #include "include/core/SkBlendMode.h"
13 #include "include/core/SkCanvas.h"
14 #include "include/core/SkColor.h"
15 #include "include/core/SkColorFilter.h"
16 #include "include/core/SkData.h"
17 #include "include/core/SkFilterQuality.h"
18 #include "include/core/SkFont.h"
19 #include "include/core/SkImage.h"
20 #include "include/core/SkImageFilter.h"
21 #include "include/core/SkImageInfo.h"
22 #include "include/core/SkMaskFilter.h"
23 #include "include/core/SkMatrix.h"
24 #include "include/core/SkPaint.h"
25 #include "include/core/SkPoint.h"
26 #include "include/core/SkRect.h"
27 #include "include/core/SkRefCnt.h"
28 #include "include/core/SkScalar.h"
29 #include "include/core/SkShader.h"
30 #include "include/core/SkSize.h"
31 #include "include/core/SkString.h"
32 #include "include/core/SkTileMode.h"
33 #include "include/core/SkTypeface.h"
34 #include "include/core/SkTypes.h"
35 #include "include/effects/SkColorMatrix.h"
36 #include "include/effects/SkGradientShader.h"
37 #include "include/effects/SkImageFilters.h"
38 #include "include/effects/SkShaderMaskFilter.h"
39 #include "include/private/SkTArray.h"
40 #include "src/core/SkLineClipper.h"
41 #include "tools/Resources.h"
42 #include "tools/ToolUtils.h"
43 #include "tools/gpu/YUVUtils.h"
44 
45 #include <array>
46 #include <memory>
47 #include <utility>
48 
49 class ClipTileRenderer;
50 using ClipTileRendererArray = SkTArray<sk_sp<ClipTileRenderer>>;
51 
52 // This GM mimics the draw calls used by complex compositors that focus on drawing rectangles
53 // and quadrilaterals with per-edge AA, with complex images, effects, and seamless tiling.
54 // It will be updated to reflect the patterns seen in Chromium's SkiaRenderer. It is currently
55 // restricted to adding draw ops directly in Ganesh since there is no fully-specified public API.
56 static constexpr SkScalar kTileWidth = 40;
57 static constexpr SkScalar kTileHeight = 30;
58 
59 static constexpr int kRowCount = 4;
60 static constexpr int kColCount = 3;
61 
62 // To mimic Chromium's BSP clipping strategy, a set of three lines formed by triangle edges
63 // of the below points are used to clip against the regular tile grid. The tile grid occupies
64 // a 120 x 120 rectangle (40px * 3 cols by 30px * 4 rows).
65 static constexpr SkPoint kClipP1 = {1.75f * kTileWidth, 0.8f * kTileHeight};
66 static constexpr SkPoint kClipP2 = {0.6f * kTileWidth, 2.f * kTileHeight};
67 static constexpr SkPoint kClipP3 = {2.9f * kTileWidth, 3.5f * kTileHeight};
68 
69 ///////////////////////////////////////////////////////////////////////////////////////////////
70 // Utilities for operating on lines and tiles
71 ///////////////////////////////////////////////////////////////////////////////////////////////
72 
73 // p0 and p1 form a segment contained the tile grid, so extends them by a large enough margin
74 // that the output points stored in 'line' are outside the tile grid (thus effectively infinite).
clipping_line_segment(const SkPoint & p0,const SkPoint & p1,SkPoint line[2])75 static void clipping_line_segment(const SkPoint& p0, const SkPoint& p1, SkPoint line[2]) {
76     SkVector v = p1 - p0;
77     // 10f was chosen as a balance between large enough to scale the currently set clip
78     // points outside of the tile grid, but small enough to preserve precision.
79     line[0] = p0 - v * 10.f;
80     line[1] = p1 + v * 10.f;
81 }
82 
83 // Returns true if line segment (p0-p1) intersects with line segment (l0-l1); if true is returned,
84 // the intersection point is stored in 'intersect'.
intersect_line_segments(const SkPoint & p0,const SkPoint & p1,const SkPoint & l0,const SkPoint & l1,SkPoint * intersect)85 static bool intersect_line_segments(const SkPoint& p0, const SkPoint& p1,
86                                     const SkPoint& l0, const SkPoint& l1, SkPoint* intersect) {
87     static constexpr SkScalar kHorizontalTolerance = 0.01f; // Pretty conservative
88 
89     // Use doubles for accuracy, since the clipping strategy used below can create T
90     // junctions, and lower precision could artificially create gaps
91     double pY = (double) p1.fY - (double) p0.fY;
92     double pX = (double) p1.fX - (double) p0.fX;
93     double lY = (double) l1.fY - (double) l0.fY;
94     double lX = (double) l1.fX - (double) l0.fX;
95     double plY = (double) p0.fY - (double) l0.fY;
96     double plX = (double) p0.fX - (double) l0.fX;
97     if (SkScalarNearlyZero(pY, kHorizontalTolerance)) {
98         if (SkScalarNearlyZero(lY, kHorizontalTolerance)) {
99             // Two horizontal lines
100             return false;
101         } else {
102             // Recalculate but swap p and l
103             return intersect_line_segments(l0, l1, p0, p1, intersect);
104         }
105     }
106 
107     // Up to now, the line segments do not form an invalid intersection
108     double lNumerator = plX * pY - plY * pX;
109     double lDenom = lX * pY - lY * pX;
110     if (SkScalarNearlyZero(lDenom)) {
111         // Parallel or identical
112         return false;
113     }
114 
115     // Calculate alphaL that provides the intersection point along (l0-l1), e.g. l0+alphaL*(l1-l0)
116     double alphaL = lNumerator / lDenom;
117     if (alphaL < 0.0 || alphaL > 1.0) {
118         // Outside of the l segment
119         return false;
120     }
121 
122     // Calculate alphaP from the valid alphaL (since it could be outside p segment)
123     // double alphaP = (alphaL * l.fY - pl.fY) / p.fY;
124     double alphaP = (alphaL * lY - plY) / pY;
125     if (alphaP < 0.0 || alphaP > 1.0) {
126         // Outside of p segment
127         return false;
128     }
129 
130     // Is valid, so calculate the actual intersection point
131     *intersect = l1 * SkScalar(alphaL) + l0 * SkScalar(1.0 - alphaL);
132     return true;
133 }
134 
135 // Draw a line through the two points, outset by a fixed length in screen space
draw_outset_line(SkCanvas * canvas,const SkMatrix & local,const SkPoint pts[2],const SkPaint & paint)136 static void draw_outset_line(SkCanvas* canvas, const SkMatrix& local, const SkPoint pts[2],
137                              const SkPaint& paint) {
138     static constexpr SkScalar kLineOutset = 10.f;
139     SkPoint mapped[2];
140     local.mapPoints(mapped, pts, 2);
141     SkVector v = mapped[1] - mapped[0];
142     v.setLength(v.length() + kLineOutset);
143     canvas->drawLine(mapped[1] - v, mapped[0] + v, paint);
144 }
145 
146 // Draw grid of red lines at interior tile boundaries.
draw_tile_boundaries(SkCanvas * canvas,const SkMatrix & local)147 static void draw_tile_boundaries(SkCanvas* canvas, const SkMatrix& local) {
148     SkPaint paint;
149     paint.setAntiAlias(true);
150     paint.setColor(SK_ColorRED);
151     paint.setStyle(SkPaint::kStroke_Style);
152     paint.setStrokeWidth(0.f);
153     for (int x = 1; x < kColCount; ++x) {
154         SkPoint pts[] = {{x * kTileWidth, 0}, {x * kTileWidth, kRowCount * kTileHeight}};
155         draw_outset_line(canvas, local, pts, paint);
156     }
157     for (int y = 1; y < kRowCount; ++y) {
158         SkPoint pts[] = {{0, y * kTileHeight}, {kTileWidth * kColCount, y * kTileHeight}};
159         draw_outset_line(canvas, local, pts, paint);
160     }
161 }
162 
163 // Draw the arbitrary clipping/split boundaries that intersect the tile grid as green lines
draw_clipping_boundaries(SkCanvas * canvas,const SkMatrix & local)164 static void draw_clipping_boundaries(SkCanvas* canvas, const SkMatrix& local) {
165     SkPaint paint;
166     paint.setAntiAlias(true);
167     paint.setColor(SK_ColorGREEN);
168     paint.setStyle(SkPaint::kStroke_Style);
169     paint.setStrokeWidth(0.f);
170 
171     // Clip the "infinite" line segments to a rectangular region outside the tile grid
172     SkRect border = SkRect::MakeWH(kTileWidth * kColCount, kTileHeight * kRowCount);
173 
174     // Draw p1 to p2
175     SkPoint line[2];
176     SkPoint clippedLine[2];
177     clipping_line_segment(kClipP1, kClipP2, line);
178     SkAssertResult(SkLineClipper::IntersectLine(line, border, clippedLine));
179     draw_outset_line(canvas, local, clippedLine, paint);
180 
181     // Draw p2 to p3
182     clipping_line_segment(kClipP2, kClipP3, line);
183     SkAssertResult(SkLineClipper::IntersectLine(line, border, clippedLine));
184     draw_outset_line(canvas, local, clippedLine, paint);
185 
186     // Draw p3 to p1
187     clipping_line_segment(kClipP3, kClipP1, line);
188     SkAssertResult(SkLineClipper::IntersectLine(line, border, clippedLine));
189     draw_outset_line(canvas, local, clippedLine, paint);
190 }
191 
draw_text(SkCanvas * canvas,const char * text)192 static void draw_text(SkCanvas* canvas, const char* text) {
193     SkFont font(ToolUtils::create_portable_typeface(), 12);
194     canvas->drawString(text, 0, 0, font, SkPaint());
195 }
196 
197 /////////////////////////////////////////////////////////////////////////////////////////////////
198 // Abstraction for rendering a possibly clipped tile, that can apply different effects to mimic
199 // the Chromium quad types, and a generic GM template to arrange renderers x transforms in a grid
200 /////////////////////////////////////////////////////////////////////////////////////////////////
201 
202 class ClipTileRenderer : public SkRefCntBase {
203 public:
204     // Draw the base rect, possibly clipped by 'clip' if that is not null. The edges to antialias
205     // are specified in 'edgeAA' (to make manipulation easier than an unsigned bitfield). 'tileID'
206     // represents the location of rect within the tile grid, 'quadID' is the unique ID of the clip
207     // region within the tile (reset for each tile).
208     //
209     // The edgeAA order matches that of clip, so it refers to top, right, bottom, left.
210     // Return draw count
211     virtual int drawTile(SkCanvas* canvas, const SkRect& rect, const SkPoint clip[4],
212                           const bool edgeAA[4], int tileID, int quadID) = 0;
213 
214     virtual void drawBanner(SkCanvas* canvas) = 0;
215 
216     // Return draw count
drawTiles(SkCanvas * canvas)217     virtual int drawTiles(SkCanvas* canvas) {
218         // All three lines in a list
219         SkPoint lines[6];
220         clipping_line_segment(kClipP1, kClipP2, lines);
221         clipping_line_segment(kClipP2, kClipP3, lines + 2);
222         clipping_line_segment(kClipP3, kClipP1, lines + 4);
223 
224         bool edgeAA[4];
225         int tileID = 0;
226         int drawCount = 0;
227         for (int i = 0; i < kRowCount; ++i) {
228             for (int j = 0; j < kColCount; ++j) {
229                 // The unclipped tile geometry
230                 SkRect tile = SkRect::MakeXYWH(j * kTileWidth, i * kTileHeight,
231                                                kTileWidth, kTileHeight);
232                 // Base edge AA flags if there are no clips; clipped lines will only turn off edges
233                 edgeAA[0] = i == 0;             // Top
234                 edgeAA[1] = j == kColCount - 1; // Right
235                 edgeAA[2] = i == kRowCount - 1; // Bottom
236                 edgeAA[3] = j == 0;             // Left
237 
238                 // Now clip against the 3 lines formed by kClipPx and split into general purpose
239                 // quads as needed.
240                 int quadCount = 0;
241                 drawCount += this->clipTile(canvas, tileID, tile, nullptr, edgeAA, lines, 3,
242                                             &quadCount);
243                 tileID++;
244             }
245         }
246 
247         return drawCount;
248     }
249 
250 protected:
maskToFlags(const bool edgeAA[4]) const251     SkCanvas::QuadAAFlags maskToFlags(const bool edgeAA[4]) const {
252         unsigned flags = (edgeAA[0] * SkCanvas::kTop_QuadAAFlag) |
253                          (edgeAA[1] * SkCanvas::kRight_QuadAAFlag) |
254                          (edgeAA[2] * SkCanvas::kBottom_QuadAAFlag) |
255                          (edgeAA[3] * SkCanvas::kLeft_QuadAAFlag);
256         return static_cast<SkCanvas::QuadAAFlags>(flags);
257     }
258 
259     // Recursively splits the quadrilateral against the segments stored in 'lines', which must be
260     // 2 * lineCount long. Increments 'quadCount' for each split quadrilateral, and invokes the
261     // drawTile at leaves.
clipTile(SkCanvas * canvas,int tileID,const SkRect & baseRect,const SkPoint quad[4],const bool edgeAA[4],const SkPoint lines[],int lineCount,int * quadCount)262     int clipTile(SkCanvas* canvas, int tileID, const SkRect& baseRect, const SkPoint quad[4],
263                   const bool edgeAA[4], const SkPoint lines[], int lineCount, int* quadCount) {
264         if (lineCount == 0) {
265             // No lines, so end recursion by drawing the tile. If the tile was never split then
266             // 'quad' remains null so that drawTile() can differentiate how it should draw.
267             int draws = this->drawTile(canvas, baseRect, quad, edgeAA, tileID, *quadCount);
268             *quadCount = *quadCount + 1;
269             return draws;
270         }
271 
272         static constexpr int kTL = 0; // Top-left point index in points array
273         static constexpr int kTR = 1; // Top-right point index in points array
274         static constexpr int kBR = 2; // Bottom-right point index in points array
275         static constexpr int kBL = 3; // Bottom-left point index in points array
276         static constexpr int kS0 = 4; // First split point index in points array
277         static constexpr int kS1 = 5; // Second split point index in points array
278 
279         SkPoint points[6];
280         if (quad) {
281             // Copy the original 4 points into set of points to consider
282             for (int i = 0; i < 4; ++i) {
283                 points[i] = quad[i];
284             }
285         } else {
286             //  Haven't been split yet, so fill in based on the rect
287             baseRect.toQuad(points);
288         }
289 
290         // Consider the first line against the 4 quad edges in tile, which should have 0,1, or 2
291         // intersection points since the tile is convex.
292         int splitIndices[2]; // Edge that was intersected
293         int intersectionCount = 0;
294         for (int i = 0; i < 4; ++i) {
295             SkPoint intersect;
296             if (intersect_line_segments(points[i], points[i == 3 ? 0 : i + 1],
297                                         lines[0], lines[1], &intersect)) {
298                 // If the intersected point is the same as the last found intersection, the line
299                 // runs through a vertex, so don't double count it
300                 bool duplicate = false;
301                 for (int j = 0; j < intersectionCount; ++j) {
302                     if (SkScalarNearlyZero((intersect - points[kS0 + j]).length())) {
303                         duplicate = true;
304                         break;
305                     }
306                 }
307                 if (!duplicate) {
308                     points[kS0 + intersectionCount] = intersect;
309                     splitIndices[intersectionCount] = i;
310                     intersectionCount++;
311                 }
312             }
313         }
314 
315         if (intersectionCount < 2) {
316             // Either the first line never intersected the quad (count == 0), or it intersected at a
317             // single vertex without going through quad area (count == 1), so check next line
318             return this->clipTile(
319                     canvas, tileID, baseRect, quad, edgeAA, lines + 2, lineCount - 1, quadCount);
320         }
321 
322         SkASSERT(intersectionCount == 2);
323         // Split the tile points into 2+ sub quads and recurse to the next lines, which may or may
324         // not further split the tile. Since the configurations are relatively simple, the possible
325         // splits are hardcoded below; subtile quad orderings are such that the sub tiles remain in
326         // clockwise order and match expected edges for QuadAAFlags. subtile indices refer to the
327         // 6-element 'points' array.
328         SkSTArray<3, std::array<int, 4>> subtiles;
329         int s2 = -1; // Index of an original vertex chosen for a artificial split
330         if (splitIndices[1] - splitIndices[0] == 2) {
331             // Opposite edges, so the split trivially forms 2 sub quads
332             if (splitIndices[0] == 0) {
333                 subtiles.push_back({{kTL, kS0, kS1, kBL}});
334                 subtiles.push_back({{kS0, kTR, kBR, kS1}});
335             } else {
336                 subtiles.push_back({{kTL, kTR, kS0, kS1}});
337                 subtiles.push_back({{kS1, kS0, kBR, kBL}});
338             }
339         } else {
340             // Adjacent edges, which makes for a more complicated split, since it forms a degenerate
341             // quad (triangle) and a pentagon that must be artificially split. The pentagon is split
342             // using one of the original vertices (remembered in 's2'), which adds an additional
343             // degenerate quad, but ensures there are no T-junctions.
344             switch(splitIndices[0]) {
345                 case 0:
346                     // Could be connected to edge 1 or edge 3
347                     if (splitIndices[1] == 1) {
348                         s2 = kBL;
349                         subtiles.push_back({{kS0, kTR, kS1, kS0}}); // degenerate
350                         subtiles.push_back({{kTL, kS0, edgeAA[0] ? kS0 : kBL, kBL}}); // degenerate
351                         subtiles.push_back({{kS0, kS1, kBR, kBL}});
352                     } else {
353                         SkASSERT(splitIndices[1] == 3);
354                         s2 = kBR;
355                         subtiles.push_back({{kTL, kS0, kS1, kS1}}); // degenerate
356                         subtiles.push_back({{kS1, edgeAA[3] ? kS1 : kBR, kBR, kBL}}); // degenerate
357                         subtiles.push_back({{kS0, kTR, kBR, kS1}});
358                     }
359                     break;
360                 case 1:
361                     // Edge 0 handled above, should only be connected to edge 2
362                     SkASSERT(splitIndices[1] == 2);
363                     s2 = kTL;
364                     subtiles.push_back({{kS0, kS0, kBR, kS1}}); // degenerate
365                     subtiles.push_back({{kTL, kTR, kS0, edgeAA[1] ? kS0 : kTL}}); // degenerate
366                     subtiles.push_back({{kTL, kS0, kS1, kBL}});
367                     break;
368                 case 2:
369                     // Edge 1 handled above, should only be connected to edge 3
370                     SkASSERT(splitIndices[1] == 3);
371                     s2 = kTR;
372                     subtiles.push_back({{kS1, kS0, kS0, kBL}}); // degenerate
373                     subtiles.push_back({{edgeAA[2] ? kS0 : kTR, kTR, kBR, kS0}}); // degenerate
374                     subtiles.push_back({{kTL, kTR, kS0, kS1}});
375                     break;
376                 case 3:
377                     // Fall through, an adjacent edge split that hits edge 3 should have first found
378                     // been found with edge 0 or edge 2 for the other end
379                 default:
380                     SkASSERT(false);
381                     return 0;
382             }
383         }
384 
385         SkPoint sub[4];
386         bool subAA[4];
387         int draws = 0;
388         for (int i = 0; i < subtiles.count(); ++i) {
389             // Fill in the quad points and update edge AA rules for new interior edges
390             for (int j = 0; j < 4; ++j) {
391                 int p = subtiles[i][j];
392                 sub[j] = points[p];
393 
394                 int np = j == 3 ? subtiles[i][0] : subtiles[i][j + 1];
395                 // The "new" edges are the edges that connect between the two split points or
396                 // between a split point and the chosen s2 point. Otherwise the edge remains aligned
397                 // with the original shape, so should preserve the AA setting.
398                 if ((p >= kS0 && (np == s2 || np >= kS0)) ||
399                     ((np >= kS0) && (p == s2 || p >= kS0))) {
400                     // New edge
401                     subAA[j] = false;
402                 } else {
403                     // The subtiles indices were arranged so that their edge ordering was still top,
404                     // right, bottom, left so 'j' can be used to access edgeAA
405                     subAA[j] = edgeAA[j];
406                 }
407             }
408 
409             // Split the sub quad with the next line
410             draws += this->clipTile(canvas, tileID, baseRect, sub, subAA, lines + 2, lineCount - 1,
411                                     quadCount);
412         }
413         return draws;
414     }
415 };
416 
417 static constexpr int kMatrixCount = 5;
418 
419 class CompositorGM : public skiagm::GM {
420 public:
CompositorGM(const char * name,std::function<ClipTileRendererArray ()> makeRendererFn)421     CompositorGM(const char* name, std::function<ClipTileRendererArray()> makeRendererFn)
422             : fMakeRendererFn(std::move(makeRendererFn))
423             , fName(name) {}
424 
425 protected:
onISize()426     SkISize onISize() override {
427         // Initialize the array of renderers.
428         this->onceBeforeDraw();
429 
430         // The GM draws a grid of renderers (rows) x transforms (col). Within each cell, the
431         // renderer draws the transformed tile grid, which is approximately
432         // (kColCount*kTileWidth, kRowCount*kTileHeight), although it has additional line
433         // visualizations and can be transformed outside of those rectangular bounds (i.e. persp),
434         // so pad the cell dimensions to be conservative. Must also account for the banner text.
435         static constexpr SkScalar kCellWidth = 1.3f * kColCount * kTileWidth;
436         static constexpr SkScalar kCellHeight = 1.3f * kRowCount * kTileHeight;
437         return SkISize::Make(SkScalarRoundToInt(kCellWidth * kMatrixCount + 175.f),
438                              SkScalarRoundToInt(kCellHeight * fRenderers.count() + 75.f));
439     }
440 
onShortName()441     SkString onShortName() override {
442         SkString fullName;
443         fullName.appendf("compositor_quads_%s", fName.c_str());
444         return fullName;
445     }
446 
onOnceBeforeDraw()447     void onOnceBeforeDraw() override {
448         fRenderers = fMakeRendererFn();
449         this->configureMatrices();
450     }
451 
onDraw(SkCanvas * canvas)452     void onDraw(SkCanvas* canvas) override {
453         static constexpr SkScalar kGap = 40.f;
454         static constexpr SkScalar kBannerWidth = 120.f;
455         static constexpr SkScalar kOffset = 15.f;
456 
457         SkTArray<int> drawCounts(fRenderers.count());
458         drawCounts.push_back_n(fRenderers.count(), 0);
459 
460         canvas->save();
461         canvas->translate(kOffset + kBannerWidth, kOffset);
462         for (int i = 0; i < fMatrices.count(); ++i) {
463             canvas->save();
464             draw_text(canvas, fMatrixNames[i].c_str());
465 
466             canvas->translate(0.f, kGap);
467             for (int j = 0; j < fRenderers.count(); ++j) {
468                 canvas->save();
469                 draw_tile_boundaries(canvas, fMatrices[i]);
470                 draw_clipping_boundaries(canvas, fMatrices[i]);
471 
472                 canvas->concat(fMatrices[i]);
473                 drawCounts[j] += fRenderers[j]->drawTiles(canvas);
474 
475                 canvas->restore();
476                 // And advance to the next row
477                 canvas->translate(0.f, kGap + kRowCount * kTileHeight);
478             }
479             // Reset back to the left edge
480             canvas->restore();
481             // And advance to the next column
482             canvas->translate(kGap + kColCount * kTileWidth, 0.f);
483         }
484         canvas->restore();
485 
486         // Print a row header, with total draw counts
487         canvas->save();
488         canvas->translate(kOffset, kGap + 0.5f * kRowCount * kTileHeight);
489         for (int j = 0; j < fRenderers.count(); ++j) {
490             fRenderers[j]->drawBanner(canvas);
491             canvas->translate(0.f, 15.f);
492             draw_text(canvas, SkStringPrintf("Draws = %d", drawCounts[j]).c_str());
493             canvas->translate(0.f, kGap + kRowCount * kTileHeight);
494         }
495         canvas->restore();
496     }
497 
498 private:
499     std::function<ClipTileRendererArray()> fMakeRendererFn;
500     ClipTileRendererArray fRenderers;
501     SkTArray<SkMatrix> fMatrices;
502     SkTArray<SkString> fMatrixNames;
503 
504     SkString fName;
505 
configureMatrices()506     void configureMatrices() {
507         fMatrices.reset();
508         fMatrixNames.reset();
509         fMatrices.push_back_n(kMatrixCount);
510 
511         // Identity
512         fMatrices[0].setIdentity();
513         fMatrixNames.push_back(SkString("Identity"));
514 
515         // Translate/scale
516         fMatrices[1].setTranslate(5.5f, 20.25f);
517         fMatrices[1].postScale(.9f, .7f);
518         fMatrixNames.push_back(SkString("T+S"));
519 
520         // Rotation
521         fMatrices[2].setRotate(20.0f);
522         fMatrices[2].preTranslate(15.f, -20.f);
523         fMatrixNames.push_back(SkString("Rotate"));
524 
525         // Skew
526         fMatrices[3].setSkew(.5f, .25f);
527         fMatrices[3].preTranslate(-30.f, 0.f);
528         fMatrixNames.push_back(SkString("Skew"));
529 
530         // Perspective
531         SkPoint src[4];
532         SkRect::MakeWH(kColCount * kTileWidth, kRowCount * kTileHeight).toQuad(src);
533         SkPoint dst[4] = {{0, 0},
534                           {kColCount * kTileWidth + 10.f, 15.f},
535                           {kColCount * kTileWidth - 28.f, kRowCount * kTileHeight + 40.f},
536                           {25.f, kRowCount * kTileHeight - 15.f}};
537         SkAssertResult(fMatrices[4].setPolyToPoly(src, dst, 4));
538         fMatrices[4].preTranslate(0.f, 10.f);
539         fMatrixNames.push_back(SkString("Perspective"));
540 
541         SkASSERT(fMatrices.count() == fMatrixNames.count());
542     }
543 
544     using INHERITED = skiagm::GM;
545 };
546 
547 ////////////////////////////////////////////////////////////////////////////////////////////////
548 // Implementations of TileRenderer that color the clipped tiles in various ways
549 ////////////////////////////////////////////////////////////////////////////////////////////////
550 
551 class DebugTileRenderer : public ClipTileRenderer {
552 public:
553 
Make()554     static sk_sp<ClipTileRenderer> Make() {
555         // Since aa override is disabled, the quad flags arg doesn't matter.
556         return sk_sp<ClipTileRenderer>(new DebugTileRenderer(SkCanvas::kAll_QuadAAFlags, false));
557     }
558 
MakeAA()559     static sk_sp<ClipTileRenderer> MakeAA() {
560         return sk_sp<ClipTileRenderer>(new DebugTileRenderer(SkCanvas::kAll_QuadAAFlags, true));
561     }
562 
MakeNonAA()563     static sk_sp<ClipTileRenderer> MakeNonAA() {
564         return sk_sp<ClipTileRenderer>(new DebugTileRenderer(SkCanvas::kNone_QuadAAFlags, true));
565     }
566 
drawTile(SkCanvas * canvas,const SkRect & rect,const SkPoint clip[4],const bool edgeAA[4],int tileID,int quadID)567     int drawTile(SkCanvas* canvas, const SkRect& rect, const SkPoint clip[4], const bool edgeAA[4],
568                   int tileID, int quadID) override {
569         // Colorize the tile based on its grid position and quad ID
570         int i = tileID / kColCount;
571         int j = tileID % kColCount;
572 
573         SkColor4f c = {(i + 1.f) / kRowCount, (j + 1.f) / kColCount, .4f, 1.f};
574         float alpha = quadID / 10.f;
575         c.fR = c.fR * (1 - alpha) + alpha;
576         c.fG = c.fG * (1 - alpha) + alpha;
577         c.fB = c.fB * (1 - alpha) + alpha;
578         c.fA = c.fA * (1 - alpha) + alpha;
579 
580         SkCanvas::QuadAAFlags aaFlags = fEnableAAOverride ? fAAOverride : this->maskToFlags(edgeAA);
581         canvas->experimental_DrawEdgeAAQuad(
582                 rect, clip, aaFlags, c.toSkColor(), SkBlendMode::kSrcOver);
583         return 1;
584     }
585 
drawBanner(SkCanvas * canvas)586     void drawBanner(SkCanvas* canvas) override {
587         draw_text(canvas, "Edge AA");
588         canvas->translate(0.f, 15.f);
589 
590         SkString config;
591         static const char* kFormat = "Ext(%s) - Int(%s)";
592         if (fEnableAAOverride) {
593             SkASSERT(fAAOverride == SkCanvas::kAll_QuadAAFlags ||
594                      fAAOverride == SkCanvas::kNone_QuadAAFlags);
595             if (fAAOverride == SkCanvas::kAll_QuadAAFlags) {
596                 config.appendf(kFormat, "yes", "yes");
597             } else {
598                 config.appendf(kFormat, "no", "no");
599             }
600         } else {
601             config.appendf(kFormat, "yes", "no");
602         }
603         draw_text(canvas, config.c_str());
604     }
605 
606 private:
607     SkCanvas::QuadAAFlags fAAOverride;
608     bool fEnableAAOverride;
609 
DebugTileRenderer(SkCanvas::QuadAAFlags aa,bool enableAAOverrde)610     DebugTileRenderer(SkCanvas::QuadAAFlags aa, bool enableAAOverrde)
611             : fAAOverride(aa)
612             , fEnableAAOverride(enableAAOverrde) {}
613 
614     using INHERITED = ClipTileRenderer;
615 };
616 
617 // Tests tmp_drawEdgeAAQuad
618 class SolidColorRenderer : public ClipTileRenderer {
619 public:
620 
Make(const SkColor4f & color)621     static sk_sp<ClipTileRenderer> Make(const SkColor4f& color) {
622         return sk_sp<ClipTileRenderer>(new SolidColorRenderer(color));
623     }
624 
drawTile(SkCanvas * canvas,const SkRect & rect,const SkPoint clip[4],const bool edgeAA[4],int tileID,int quadID)625     int drawTile(SkCanvas* canvas, const SkRect& rect, const SkPoint clip[4], const bool edgeAA[4],
626                   int tileID, int quadID) override {
627         canvas->experimental_DrawEdgeAAQuad(rect, clip, this->maskToFlags(edgeAA),
628                                             fColor.toSkColor(), SkBlendMode::kSrcOver);
629         return 1;
630     }
631 
drawBanner(SkCanvas * canvas)632     void drawBanner(SkCanvas* canvas) override {
633         draw_text(canvas, "Solid Color");
634     }
635 
636 private:
637     SkColor4f fColor;
638 
SolidColorRenderer(const SkColor4f & color)639     SolidColorRenderer(const SkColor4f& color) : fColor(color) {}
640 
641     using INHERITED = ClipTileRenderer;
642 };
643 
644 // Tests drawEdgeAAImageSet(), but can batch the entries together in different ways
645 class TextureSetRenderer : public ClipTileRenderer {
646 public:
647 
MakeUnbatched(sk_sp<SkImage> image)648     static sk_sp<ClipTileRenderer> MakeUnbatched(sk_sp<SkImage> image) {
649         return Make("Texture", "", std::move(image), nullptr, nullptr, nullptr, nullptr,
650                     1.f, true, 0);
651     }
652 
MakeBatched(sk_sp<SkImage> image,int transformCount)653     static sk_sp<ClipTileRenderer> MakeBatched(sk_sp<SkImage> image, int transformCount) {
654         const char* subtitle = transformCount == 0 ? "" : "w/ xforms";
655         return Make("Texture Set", subtitle, std::move(image), nullptr, nullptr, nullptr, nullptr,
656                     1.f, false, transformCount);
657     }
658 
MakeShader(const char * name,sk_sp<SkImage> image,sk_sp<SkShader> shader,bool local)659     static sk_sp<ClipTileRenderer> MakeShader(const char* name, sk_sp<SkImage> image,
660                                               sk_sp<SkShader> shader, bool local) {
661         return Make("Shader", name, std::move(image), std::move(shader),
662                     nullptr, nullptr, nullptr, 1.f, local, 0);
663     }
664 
MakeColorFilter(const char * name,sk_sp<SkImage> image,sk_sp<SkColorFilter> filter)665     static sk_sp<ClipTileRenderer> MakeColorFilter(const char* name, sk_sp<SkImage> image,
666                                                    sk_sp<SkColorFilter> filter) {
667         return Make("Color Filter", name, std::move(image), nullptr, std::move(filter), nullptr,
668                     nullptr, 1.f, false, 0);
669     }
670 
MakeImageFilter(const char * name,sk_sp<SkImage> image,sk_sp<SkImageFilter> filter)671     static sk_sp<ClipTileRenderer> MakeImageFilter(const char* name, sk_sp<SkImage> image,
672                                                    sk_sp<SkImageFilter> filter) {
673         return Make("Image Filter", name, std::move(image), nullptr, nullptr, std::move(filter),
674                     nullptr, 1.f, false, 0);
675     }
676 
MakeMaskFilter(const char * name,sk_sp<SkImage> image,sk_sp<SkMaskFilter> filter)677     static sk_sp<ClipTileRenderer> MakeMaskFilter(const char* name, sk_sp<SkImage> image,
678                                                   sk_sp<SkMaskFilter> filter) {
679         return Make("Mask Filter", name, std::move(image), nullptr, nullptr, nullptr,
680                     std::move(filter), 1.f, false, 0);
681     }
682 
MakeAlpha(sk_sp<SkImage> image,SkScalar alpha)683     static sk_sp<ClipTileRenderer> MakeAlpha(sk_sp<SkImage> image, SkScalar alpha) {
684         return Make("Alpha", SkStringPrintf("a = %.2f", alpha).c_str(), std::move(image), nullptr,
685                     nullptr, nullptr, nullptr, alpha, false, 0);
686     }
687 
Make(const char * topBanner,const char * bottomBanner,sk_sp<SkImage> image,sk_sp<SkShader> shader,sk_sp<SkColorFilter> colorFilter,sk_sp<SkImageFilter> imageFilter,sk_sp<SkMaskFilter> maskFilter,SkScalar paintAlpha,bool resetAfterEachQuad,int transformCount)688     static sk_sp<ClipTileRenderer> Make(const char* topBanner, const char* bottomBanner,
689                                         sk_sp<SkImage> image, sk_sp<SkShader> shader,
690                                         sk_sp<SkColorFilter> colorFilter,
691                                         sk_sp<SkImageFilter> imageFilter,
692                                         sk_sp<SkMaskFilter> maskFilter, SkScalar paintAlpha,
693                                         bool resetAfterEachQuad, int transformCount) {
694         return sk_sp<ClipTileRenderer>(new TextureSetRenderer(topBanner, bottomBanner,
695                 std::move(image), std::move(shader), std::move(colorFilter), std::move(imageFilter),
696                 std::move(maskFilter), paintAlpha, resetAfterEachQuad, transformCount));
697     }
698 
drawTiles(SkCanvas * canvas)699     int drawTiles(SkCanvas* canvas) override {
700         int draws = this->INHERITED::drawTiles(canvas);
701         // Push the last tile set
702         draws += this->drawAndReset(canvas);
703         return draws;
704     }
705 
drawTile(SkCanvas * canvas,const SkRect & rect,const SkPoint clip[4],const bool edgeAA[4],int tileID,int quadID)706     int drawTile(SkCanvas* canvas, const SkRect& rect, const SkPoint clip[4], const bool edgeAA[4],
707                   int tileID, int quadID) override {
708         // Now don't actually draw the tile, accumulate it in the growing entry set
709         bool hasClip = false;
710         if (clip) {
711             // Record the four points into fDstClips
712             fDstClips.push_back_n(4, clip);
713             hasClip = true;
714         }
715 
716         int matrixIdx = -1;
717         if (!fResetEachQuad && fTransformBatchCount > 0) {
718             // Handle transform batching. This works by capturing the CTM of the first tile draw,
719             // and then calculate the difference between that and future CTMs for later tiles.
720             if (fPreViewMatrices.count() == 0) {
721                 fBaseCTM = canvas->getTotalMatrix();
722                 fPreViewMatrices.push_back(SkMatrix::I());
723                 matrixIdx = 0;
724             } else {
725                 // Calculate matrix s.t. getTotalMatrix() = fBaseCTM * M
726                 SkMatrix invBase;
727                 if (!fBaseCTM.invert(&invBase)) {
728                     SkDebugf("Cannot invert CTM, transform batching will not be correct.\n");
729                 } else {
730                     SkMatrix preView = SkMatrix::Concat(invBase, canvas->getTotalMatrix());
731                     if (preView != fPreViewMatrices[fPreViewMatrices.count() - 1]) {
732                         // Add the new matrix
733                         fPreViewMatrices.push_back(preView);
734                     } // else re-use the last matrix
735                     matrixIdx = fPreViewMatrices.count() - 1;
736                 }
737             }
738         }
739 
740         // This acts like the whole image is rendered over the entire tile grid, so derive local
741         // coordinates from 'rect', based on the grid to image transform.
742         SkMatrix gridToImage = SkMatrix::RectToRect(SkRect::MakeWH(kColCount * kTileWidth,
743                                                                    kRowCount * kTileHeight),
744                                                     SkRect::MakeWH(fImage->width(),
745                                                                    fImage->height()));
746         SkRect localRect = gridToImage.mapRect(rect);
747 
748         // drawTextureSet automatically derives appropriate local quad from localRect if clipPtr
749         // is not null.
750         fSetEntries.push_back(
751                 {fImage, localRect, rect, matrixIdx, 1.f, this->maskToFlags(edgeAA), hasClip});
752 
753         if (fResetEachQuad) {
754             // Only ever draw one entry at a time
755             return this->drawAndReset(canvas);
756         } else {
757             return 0;
758         }
759     }
760 
drawBanner(SkCanvas * canvas)761     void drawBanner(SkCanvas* canvas) override {
762         if (fTopBanner.size() > 0) {
763             draw_text(canvas, fTopBanner.c_str());
764         }
765         canvas->translate(0.f, 15.f);
766         if (fBottomBanner.size() > 0) {
767             draw_text(canvas, fBottomBanner.c_str());
768         }
769     }
770 
771 private:
772     SkString fTopBanner;
773     SkString fBottomBanner;
774 
775     sk_sp<SkImage> fImage;
776     sk_sp<SkShader> fShader;
777     sk_sp<SkColorFilter> fColorFilter;
778     sk_sp<SkImageFilter> fImageFilter;
779     sk_sp<SkMaskFilter> fMaskFilter;
780     SkScalar fPaintAlpha;
781 
782     // Batching rules
783     bool fResetEachQuad;
784     int fTransformBatchCount;
785 
786     SkTArray<SkPoint> fDstClips;
787     SkTArray<SkMatrix> fPreViewMatrices;
788     SkTArray<SkCanvas::ImageSetEntry> fSetEntries;
789 
790     SkMatrix fBaseCTM;
791     int fBatchCount;
792 
TextureSetRenderer(const char * topBanner,const char * bottomBanner,sk_sp<SkImage> image,sk_sp<SkShader> shader,sk_sp<SkColorFilter> colorFilter,sk_sp<SkImageFilter> imageFilter,sk_sp<SkMaskFilter> maskFilter,SkScalar paintAlpha,bool resetEachQuad,int transformBatchCount)793     TextureSetRenderer(const char* topBanner,
794                        const char* bottomBanner,
795                        sk_sp<SkImage> image,
796                        sk_sp<SkShader> shader,
797                        sk_sp<SkColorFilter> colorFilter,
798                        sk_sp<SkImageFilter> imageFilter,
799                        sk_sp<SkMaskFilter> maskFilter,
800                        SkScalar paintAlpha,
801                        bool resetEachQuad,
802                        int transformBatchCount)
803             : fTopBanner(topBanner)
804             , fBottomBanner(bottomBanner)
805             , fImage(std::move(image))
806             , fShader(std::move(shader))
807             , fColorFilter(std::move(colorFilter))
808             , fImageFilter(std::move(imageFilter))
809             , fMaskFilter(std::move(maskFilter))
810             , fPaintAlpha(paintAlpha)
811             , fResetEachQuad(resetEachQuad)
812             , fTransformBatchCount(transformBatchCount)
813             , fBatchCount(0) {
814         SkASSERT(transformBatchCount >= 0 && (!resetEachQuad || transformBatchCount == 0));
815     }
816 
configureTilePaint(const SkRect & rect,SkPaint * paint) const817     void configureTilePaint(const SkRect& rect, SkPaint* paint) const {
818         paint->setAntiAlias(true);
819         paint->setBlendMode(SkBlendMode::kSrcOver);
820 
821         // Send non-white RGB, that should be ignored
822         paint->setColor4f({1.f, 0.4f, 0.25f, fPaintAlpha}, nullptr);
823 
824 
825         if (fShader) {
826             if (fResetEachQuad) {
827                 // Apply a local transform in the shader to map from the tile rectangle to (0,0,w,h)
828                 static const SkRect kTarget = SkRect::MakeWH(kTileWidth, kTileHeight);
829                 SkMatrix local = SkMatrix::RectToRect(kTarget, rect);
830                 paint->setShader(fShader->makeWithLocalMatrix(local));
831             } else {
832                 paint->setShader(fShader);
833             }
834         }
835 
836         paint->setColorFilter(fColorFilter);
837         paint->setImageFilter(fImageFilter);
838         paint->setMaskFilter(fMaskFilter);
839     }
840 
drawAndReset(SkCanvas * canvas)841     int drawAndReset(SkCanvas* canvas) {
842         // Early out if there's nothing to draw
843         if (fSetEntries.count() == 0) {
844             SkASSERT(fDstClips.count() == 0 && fPreViewMatrices.count() == 0);
845             return 0;
846         }
847 
848         if (!fResetEachQuad && fTransformBatchCount > 0) {
849             // A batch is completed
850             fBatchCount++;
851             if (fBatchCount < fTransformBatchCount) {
852                 // Haven't hit the point to submit yet, but end the current tile
853                 return 0;
854             }
855 
856             // Submitting all tiles back to where fBaseCTM was the canvas' matrix, while the
857             // canvas currently has the CTM of the last tile batch, so reset it.
858             canvas->setMatrix(fBaseCTM);
859         }
860 
861 #ifdef SK_DEBUG
862         int expectedDstClipCount = 0;
863         for (int i = 0; i < fSetEntries.count(); ++i) {
864             expectedDstClipCount += 4 * fSetEntries[i].fHasClip;
865             SkASSERT(fSetEntries[i].fMatrixIndex < 0 ||
866                      fSetEntries[i].fMatrixIndex < fPreViewMatrices.count());
867         }
868         SkASSERT(expectedDstClipCount == fDstClips.count());
869 #endif
870 
871         SkPaint paint;
872         SkRect lastTileRect = fSetEntries[fSetEntries.count() - 1].fDstRect;
873         this->configureTilePaint(lastTileRect, &paint);
874 
875         canvas->experimental_DrawEdgeAAImageSet(
876                 fSetEntries.begin(), fSetEntries.count(), fDstClips.begin(),
877                 fPreViewMatrices.begin(), SkSamplingOptions(SkFilterMode::kLinear),
878                 &paint, SkCanvas::kFast_SrcRectConstraint);
879 
880         // Reset for next tile
881         fDstClips.reset();
882         fPreViewMatrices.reset();
883         fSetEntries.reset();
884         fBatchCount = 0;
885 
886         return 1;
887     }
888 
889     using INHERITED = ClipTileRenderer;
890 };
891 
892 class YUVTextureSetRenderer : public ClipTileRenderer {
893 public:
MakeFromJPEG(sk_sp<SkData> imageData)894     static sk_sp<ClipTileRenderer> MakeFromJPEG(sk_sp<SkData> imageData) {
895         return sk_sp<ClipTileRenderer>(new YUVTextureSetRenderer(std::move(imageData)));
896     }
897 
drawTiles(SkCanvas * canvas)898     int drawTiles(SkCanvas* canvas) override {
899         // Refresh the SkImage at the start, so that it's not attempted for every set entry
900         if (fYUVData) {
901             fImage = fYUVData->refImage(canvas->recordingContext(),
902                                         sk_gpu_test::LazyYUVImage::Type::kFromPixmaps);
903             if (!fImage) {
904                 return 0;
905             }
906         }
907 
908         int draws = this->INHERITED::drawTiles(canvas);
909         // Push the last tile set
910         draws += this->drawAndReset(canvas);
911         return draws;
912     }
913 
drawTile(SkCanvas * canvas,const SkRect & rect,const SkPoint clip[4],const bool edgeAA[4],int tileID,int quadID)914     int drawTile(SkCanvas* canvas, const SkRect& rect, const SkPoint clip[4], const bool edgeAA[4],
915                   int tileID, int quadID) override {
916         SkASSERT(fImage);
917         // Now don't actually draw the tile, accumulate it in the growing entry set
918         bool hasClip = false;
919         if (clip) {
920             // Record the four points into fDstClips
921             fDstClips.push_back_n(4, clip);
922             hasClip = true;
923         }
924 
925         // This acts like the whole image is rendered over the entire tile grid, so derive local
926         // coordinates from 'rect', based on the grid to image transform.
927         SkMatrix gridToImage = SkMatrix::RectToRect(SkRect::MakeWH(kColCount * kTileWidth,
928                                                                    kRowCount * kTileHeight),
929                                                     SkRect::MakeWH(fImage->width(),
930                                                                    fImage->height()));
931         SkRect localRect = gridToImage.mapRect(rect);
932 
933         // drawTextureSet automatically derives appropriate local quad from localRect if clipPtr
934         // is not null. Also exercise per-entry alpha combined with YUVA images.
935         fSetEntries.push_back(
936                 {fImage, localRect, rect, -1, .5f, this->maskToFlags(edgeAA), hasClip});
937         return 0;
938     }
939 
drawBanner(SkCanvas * canvas)940     void drawBanner(SkCanvas* canvas) override {
941         draw_text(canvas, "Texture");
942         canvas->translate(0.f, 15.f);
943         draw_text(canvas, "YUV + alpha - GPU Only");
944     }
945 
946 private:
947     std::unique_ptr<sk_gpu_test::LazyYUVImage> fYUVData;
948     // The last accessed SkImage from fYUVData, held here for easy access by drawTile
949     sk_sp<SkImage> fImage;
950 
951     SkTArray<SkPoint> fDstClips;
952     SkTArray<SkCanvas::ImageSetEntry> fSetEntries;
953 
YUVTextureSetRenderer(sk_sp<SkData> jpegData)954     YUVTextureSetRenderer(sk_sp<SkData> jpegData)
955             : fYUVData(sk_gpu_test::LazyYUVImage::Make(std::move(jpegData)))
956             , fImage(nullptr) {}
957 
drawAndReset(SkCanvas * canvas)958     int drawAndReset(SkCanvas* canvas) {
959         // Early out if there's nothing to draw
960         if (fSetEntries.count() == 0) {
961             SkASSERT(fDstClips.count() == 0);
962             return 0;
963         }
964 
965 #ifdef SK_DEBUG
966         int expectedDstClipCount = 0;
967         for (int i = 0; i < fSetEntries.count(); ++i) {
968             expectedDstClipCount += 4 * fSetEntries[i].fHasClip;
969         }
970         SkASSERT(expectedDstClipCount == fDstClips.count());
971 #endif
972 
973         SkPaint paint;
974         paint.setAntiAlias(true);
975         paint.setBlendMode(SkBlendMode::kSrcOver);
976 
977         canvas->experimental_DrawEdgeAAImageSet(
978                 fSetEntries.begin(), fSetEntries.count(), fDstClips.begin(), nullptr,
979                 SkSamplingOptions(SkFilterMode::kLinear), &paint,
980                 SkCanvas::kFast_SrcRectConstraint);
981 
982         // Reset for next tile
983         fDstClips.reset();
984         fSetEntries.reset();
985 
986         return 1;
987     }
988 
989     using INHERITED = ClipTileRenderer;
990 };
991 
make_debug_renderers()992 static ClipTileRendererArray make_debug_renderers() {
993     return ClipTileRendererArray{DebugTileRenderer::Make(),
994                                  DebugTileRenderer::MakeAA(),
995                                  DebugTileRenderer::MakeNonAA()};
996 }
997 
make_solid_color_renderers()998 static ClipTileRendererArray make_solid_color_renderers() {
999     return ClipTileRendererArray{SolidColorRenderer::Make({.2f, .8f, .3f, 1.f})};
1000 }
1001 
make_shader_renderers()1002 static ClipTileRendererArray make_shader_renderers() {
1003     static constexpr SkPoint kPts[] = { {0.f, 0.f}, {0.25f * kTileWidth, 0.25f * kTileHeight} };
1004     static constexpr SkColor kColors[] = { SK_ColorBLUE, SK_ColorWHITE };
1005     auto gradient = SkGradientShader::MakeLinear(kPts, kColors, nullptr, 2,
1006                                                  SkTileMode::kMirror);
1007 
1008     auto info = SkImageInfo::Make(1, 1, kAlpha_8_SkColorType, kOpaque_SkAlphaType);
1009     SkBitmap bm;
1010     bm.allocPixels(info);
1011     bm.eraseColor(SK_ColorWHITE);
1012     sk_sp<SkImage> image = bm.asImage();
1013 
1014     return ClipTileRendererArray{
1015                TextureSetRenderer::MakeShader("Gradient", image, gradient, false),
1016                TextureSetRenderer::MakeShader("Local Gradient", image, gradient, true)};
1017 }
1018 
make_image_renderers()1019 static ClipTileRendererArray make_image_renderers() {
1020     sk_sp<SkImage> mandrill = GetResourceAsImage("images/mandrill_512.png");
1021     sk_sp<SkData> mandrillJpeg = GetResourceAsData("images/mandrill_h1v1.jpg");
1022     return ClipTileRendererArray{TextureSetRenderer::MakeUnbatched(mandrill),
1023                                  TextureSetRenderer::MakeBatched(mandrill, 0),
1024                                  TextureSetRenderer::MakeBatched(mandrill, kMatrixCount),
1025                                  YUVTextureSetRenderer::MakeFromJPEG(mandrillJpeg)};
1026 }
1027 
make_filtered_renderers()1028 static ClipTileRendererArray make_filtered_renderers() {
1029     sk_sp<SkImage> mandrill = GetResourceAsImage("images/mandrill_512.png");
1030 
1031     SkColorMatrix cm;
1032     cm.setSaturation(10);
1033     sk_sp<SkColorFilter> colorFilter = SkColorFilters::Matrix(cm);
1034     sk_sp<SkImageFilter> imageFilter = SkImageFilters::Dilate(8, 8, nullptr);
1035 
1036     static constexpr SkColor kAlphas[] = { SK_ColorTRANSPARENT, SK_ColorBLACK };
1037     auto alphaGradient = SkGradientShader::MakeRadial(
1038             {0.5f * kTileWidth * kColCount, 0.5f * kTileHeight * kRowCount},
1039             0.25f * kTileWidth * kColCount, kAlphas, nullptr, 2, SkTileMode::kClamp);
1040     sk_sp<SkMaskFilter> maskFilter = SkShaderMaskFilter::Make(std::move(alphaGradient));
1041 
1042     return ClipTileRendererArray{
1043                TextureSetRenderer::MakeAlpha(mandrill, 0.5f),
1044                TextureSetRenderer::MakeColorFilter("Saturation", mandrill, std::move(colorFilter)),
1045 
1046     // NOTE: won't draw correctly until SkCanvas' AutoLoopers are used to handle image filters
1047                TextureSetRenderer::MakeImageFilter("Dilate", mandrill, std::move(imageFilter)),
1048 
1049     // NOTE: blur mask filters do work (tested locally), but visually they don't make much
1050     // sense, since each quad is blurred independently
1051                TextureSetRenderer::MakeMaskFilter("Shader", mandrill, std::move(maskFilter))};
1052 }
1053 
1054 DEF_GM(return new CompositorGM("debug",  make_debug_renderers);)
1055 DEF_GM(return new CompositorGM("color",  make_solid_color_renderers);)
1056 DEF_GM(return new CompositorGM("shader", make_shader_renderers);)
1057 DEF_GM(return new CompositorGM("image",  make_image_renderers);)
1058 DEF_GM(return new CompositorGM("filter", make_filtered_renderers);)
1059