xref: /aosp_15_r20/external/skia/gm/imagemakewithfilter.cpp (revision c8dee2aa9b3f27cf6c858bd81872bdeb2c07ed17)
1 /*
2  * Copyright 2016 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 "gm/gm.h"
9 
10 #include "include/core/SkBlendMode.h"
11 #include "include/core/SkCanvas.h"
12 #include "include/core/SkColor.h"
13 #include "include/core/SkColorFilter.h"
14 #include "include/core/SkFont.h"
15 #include "include/core/SkImage.h"
16 #include "include/core/SkImageFilter.h"
17 #include "include/core/SkImageInfo.h"
18 #include "include/core/SkPaint.h"
19 #include "include/core/SkPoint.h"
20 #include "include/core/SkPoint3.h"
21 #include "include/core/SkRect.h"
22 #include "include/core/SkRefCnt.h"
23 #include "include/core/SkRegion.h"
24 #include "include/core/SkScalar.h"
25 #include "include/core/SkSize.h"
26 #include "include/core/SkString.h"
27 #include "include/core/SkSurface.h"
28 #include "include/core/SkTypes.h"
29 #include "include/effects/SkImageFilters.h"
30 #include "tools/DecodeUtils.h"
31 #include "tools/GpuToolUtils.h"
32 #include "tools/Resources.h"
33 #include "tools/ToolUtils.h"
34 #include "tools/fonts/FontToolUtils.h"
35 
36 #if defined(SK_GANESH)
37 #include "include/gpu/ganesh/GrDirectContext.h"
38 #include "include/gpu/ganesh/SkImageGanesh.h"
39 #endif
40 
41 #if defined(SK_GRAPHITE)
42 #include "include/gpu/graphite/Image.h"
43 #endif
44 
45 #include <utility>
46 
47 ///////////////////////////////////////////////////////////////////////////////
48 
show_bounds(SkCanvas * canvas,const SkIRect * clip,const SkIRect * inSubset,const SkIRect * outSubset)49 static void show_bounds(SkCanvas* canvas, const SkIRect* clip, const SkIRect* inSubset,
50                         const SkIRect* outSubset) {
51     const SkIRect* rects[] { clip, inSubset, outSubset };
52     SkColor colors[] { SK_ColorBLUE, SK_ColorYELLOW, SK_ColorRED };
53 
54     SkPaint paint;
55     paint.setStyle(SkPaint::kStroke_Style);
56 
57     for (size_t i = 0; i < std::size(rects); ++i) {
58         // Skip null bounds rects, since not all methods have subsets
59         if (rects[i]) {
60             paint.setColor(colors[i]);
61             canvas->drawRect(SkRect::Make(*(rects[i])), paint);
62         }
63     }
64 }
65 
66 // Factories for creating image filters, either with or without a cropRect
67 // (this could go away if there was a SkImageFilter::makeWithCropRect() function, but that seems
68 //  less generally useful).
69 typedef sk_sp<SkImageFilter> (*FilterFactory)(sk_sp<SkImage> auxImage, const SkIRect* cropRect);
70 
color_filter_factory(sk_sp<SkImage> auxImage,const SkIRect * cropRect)71 static sk_sp<SkImageFilter> color_filter_factory(sk_sp<SkImage> auxImage, const SkIRect* cropRect) {
72     // The color filter uses kSrcIn so that it respects the transparency introduced by clamping;
73     // using kSrc would just turn the entire out rect to green regardless.
74     auto cf = SkColorFilters::Blend(SK_ColorGREEN, SkBlendMode::kSrcIn);
75     return SkImageFilters::ColorFilter(std::move(cf), nullptr, cropRect);
76 }
77 
blur_filter_factory(sk_sp<SkImage> auxImage,const SkIRect * cropRect)78 static sk_sp<SkImageFilter> blur_filter_factory(sk_sp<SkImage> auxImage, const SkIRect* cropRect) {
79     return SkImageFilters::Blur(2.0f, 2.0f, nullptr, cropRect);
80 }
81 
drop_shadow_factory(sk_sp<SkImage> auxImage,const SkIRect * cropRect)82 static sk_sp<SkImageFilter> drop_shadow_factory(sk_sp<SkImage> auxImage, const SkIRect* cropRect) {
83     return SkImageFilters::DropShadow(10.0f, 5.0f, 3.0f, 3.0f, SK_ColorBLUE, nullptr, cropRect);
84 }
85 
offset_factory(sk_sp<SkImage> auxImage,const SkIRect * cropRect)86 static sk_sp<SkImageFilter> offset_factory(sk_sp<SkImage> auxImage, const SkIRect* cropRect) {
87     return SkImageFilters::Offset(10.f, 5.f, nullptr, cropRect);
88 }
89 
dilate_factory(sk_sp<SkImage> auxImage,const SkIRect * cropRect)90 static sk_sp<SkImageFilter> dilate_factory(sk_sp<SkImage> auxImage, const SkIRect* cropRect) {
91     return SkImageFilters::Dilate(10.f, 5.f, nullptr, cropRect);
92 }
93 
erode_factory(sk_sp<SkImage> auxImage,const SkIRect * cropRect)94 static sk_sp<SkImageFilter> erode_factory(sk_sp<SkImage> auxImage, const SkIRect* cropRect) {
95     return SkImageFilters::Erode(10.f, 5.f, nullptr, cropRect);
96 }
97 
displacement_factory(sk_sp<SkImage> auxImage,const SkIRect * cropRect)98 static sk_sp<SkImageFilter> displacement_factory(sk_sp<SkImage> auxImage, const SkIRect* cropRect) {
99     sk_sp<SkImageFilter> displacement = SkImageFilters::Image(std::move(auxImage),
100                                                               SkFilterMode::kLinear);
101     return SkImageFilters::DisplacementMap(SkColorChannel::kR, SkColorChannel::kG, 40.f,
102                                            std::move(displacement), nullptr, cropRect);
103 }
104 
arithmetic_factory(sk_sp<SkImage> auxImage,const SkIRect * cropRect)105 static sk_sp<SkImageFilter> arithmetic_factory(sk_sp<SkImage> auxImage, const SkIRect* cropRect) {
106     sk_sp<SkImageFilter> background = SkImageFilters::Image(std::move(auxImage),
107                                                             SkFilterMode::kLinear);
108     return SkImageFilters::Arithmetic(0.0f, .6f, 1.f, 0.f, false, std::move(background),
109                                       nullptr, cropRect);
110 }
111 
blend_factory(sk_sp<SkImage> auxImage,const SkIRect * cropRect)112 static sk_sp<SkImageFilter> blend_factory(sk_sp<SkImage> auxImage, const SkIRect* cropRect) {
113     sk_sp<SkImageFilter> background = SkImageFilters::Image(std::move(auxImage),
114                                                             SkFilterMode::kLinear);
115     return SkImageFilters::Blend(
116             SkBlendMode::kModulate, std::move(background), nullptr, cropRect);
117 }
118 
convolution_factory(sk_sp<SkImage> auxImage,const SkIRect * cropRect)119 static sk_sp<SkImageFilter> convolution_factory(sk_sp<SkImage> auxImage, const SkIRect* cropRect) {
120     SkISize kernelSize = SkISize::Make(3, 3);
121     SkIPoint kernelOffset = SkIPoint::Make(1, 1);
122     // A Laplacian edge detector, ee https://en.wikipedia.org/wiki/Kernel_(image_processing)
123     SkScalar kernel[9] = {-1.f, -1.f, -1.f,
124                           -1.f, 8.f, -1.f,
125                           -1.f, -1.f, -1.f};
126     return SkImageFilters::MatrixConvolution(kernelSize, kernel, 1.f, 0.f, kernelOffset,
127                                              SkTileMode::kClamp, false, nullptr, cropRect);
128 }
129 
matrix_factory(sk_sp<SkImage> auxImage,const SkIRect * cropRect)130 static sk_sp<SkImageFilter> matrix_factory(sk_sp<SkImage> auxImage, const SkIRect* cropRect) {
131     SkMatrix matrix = SkMatrix::I();
132     matrix.setRotate(45.f, 50.f, 50.f);
133 
134     // This doesn't support a cropRect
135     return SkImageFilters::MatrixTransform(matrix, SkSamplingOptions(SkFilterMode::kLinear), nullptr);
136 }
137 
lighting_factory(sk_sp<SkImage> auxImage,const SkIRect * cropRect)138 static sk_sp<SkImageFilter> lighting_factory(sk_sp<SkImage> auxImage, const SkIRect* cropRect) {
139     // Must convert the RGB values of the source to alpha, since that is what the lighting filters
140     // use to estimate their normals. This color matrix changes the color to white and the alpha
141     // to be equal to the approx. luminance of the original color.
142     static const float kMatrix[20] = {
143         0.f, 0.f, 0.f, 0.f, 1.f,
144         0.f, 0.f, 0.f, 0.f, 1.f,
145         0.f, 0.f, 0.f, 0.f, 1.f,
146         0.2126f, 0.7152f, 0.0722f, 0.f, 0.f
147     };
148     sk_sp<SkImageFilter> srcToAlpha = SkImageFilters::ColorFilter(
149             SkColorFilters::Matrix(kMatrix), nullptr);
150 
151     // Combine both specular and diffuse into a single DAG since they use separate internal filter
152     // implementations.
153     SkScalar sinAzimuth = SkScalarSin(SkDegreesToRadians(225.f)),
154              cosAzimuth = SkScalarCos(SkDegreesToRadians(225.f));
155 
156     SkPoint3 spotTarget = SkPoint3::Make(SkIntToScalar(40), SkIntToScalar(40), 0);
157     SkPoint3 diffLocation = SkPoint3::Make(spotTarget.fX + 50 * cosAzimuth,
158                                            spotTarget.fY + 50 * sinAzimuth,
159                                            SkIntToScalar(10));
160     SkPoint3 specLocation = SkPoint3::Make(spotTarget.fX - 50 * sinAzimuth,
161                                            spotTarget.fY + 50 * cosAzimuth,
162                                            SkIntToScalar(10));
163     sk_sp<SkImageFilter> diffuse = SkImageFilters::PointLitDiffuse(
164             diffLocation, SK_ColorWHITE, /* scale */ 1.f, /* kd */ 2.f, srcToAlpha, cropRect);
165     sk_sp<SkImageFilter> specular = SkImageFilters::PointLitSpecular(
166             specLocation, SK_ColorRED, /* scale */ 1.f, /* ks */ 1.f, /* shine */ 8.f,
167             srcToAlpha, cropRect);
168     return SkImageFilters::Merge(std::move(diffuse), std::move(specular), cropRect);
169 }
170 
tile_factory(sk_sp<SkImage> auxImage,const SkIRect * cropRect)171 static sk_sp<SkImageFilter> tile_factory(sk_sp<SkImage> auxImage, const SkIRect* cropRect) {
172     // Tile the subset over a large region
173     return SkImageFilters::Tile(SkRect::MakeLTRB(25, 25, 75, 75), SkRect::MakeWH(100, 100),
174                                 nullptr);
175 }
176 
177 namespace {
178     enum class Strategy {
179         // Uses MakeWithFilter, passing in subset and clip directly
180         kMakeWithFilter,
181         // Uses saveLayer after clipRect() to filter on the restore (i.e. reference image)
182         kSaveLayer
183     };
184 }  // namespace
185 
186 // In this GM, we're going to feed the inner portion of a 100x100 mandrill (i.e., strip off a
187 // 25-wide border) through the MakeWithFilter factory. We'll then draw the appropriate subset of the
188 // result to the screen at the given offset. Some filters rely on a secondary image, which will be a
189 // 100x100 checkerboard. The original image is drawn in the background so that alignment is clear
190 // when drawing the result at its reported offset.
191 class ImageMakeWithFilterGM : public skiagm::GM {
192 public:
ImageMakeWithFilterGM(Strategy strategy,bool filterWithCropRect=false)193     ImageMakeWithFilterGM (Strategy strategy, bool filterWithCropRect = false)
194             : fStrategy(strategy)
195             , fFilterWithCropRect(filterWithCropRect)
196             , fMainImage(nullptr)
197             , fAuxImage(nullptr) {}
198 
199 protected:
getName() const200     SkString getName() const override {
201         SkString name = SkString("imagemakewithfilter");
202 
203         if (fFilterWithCropRect) {
204             name.append("_crop");
205         }
206         if (fStrategy == Strategy::kSaveLayer) {
207             name.append("_ref");
208         }
209         return name;
210     }
211 
getISize()212     SkISize getISize() override { return SkISize::Make(1840, 860); }
213 
onOnceBeforeDraw()214     void onOnceBeforeDraw() override {
215         SkImageInfo info = SkImageInfo::MakeN32(100, 100, kUnpremul_SkAlphaType);
216         auto surface = SkSurfaces::Raster(info, nullptr);
217 
218         sk_sp<SkImage> colorImage = ToolUtils::GetResourceAsImage("images/mandrill_128.png");
219         // Resize to 100x100
220         surface->getCanvas()->drawImageRect(
221                 colorImage, SkRect::MakeWH(colorImage->width(), colorImage->height()),
222                 SkRect::MakeWH(info.width(), info.height()), SkSamplingOptions(), nullptr,
223                                             SkCanvas::kStrict_SrcRectConstraint);
224         fMainImage = surface->makeImageSnapshot();
225 
226         ToolUtils::draw_checkerboard(surface->getCanvas());
227         fAuxImage = surface->makeImageSnapshot();
228     }
229 
onDraw(SkCanvas * canvas,SkString * errorMsg)230     DrawResult onDraw(SkCanvas* canvas, SkString* errorMsg) override {
231         FilterFactory filters[] = {
232             color_filter_factory,
233             blur_filter_factory,
234             drop_shadow_factory,
235             offset_factory,
236             dilate_factory,
237             erode_factory,
238             displacement_factory,
239             arithmetic_factory,
240             blend_factory,
241             convolution_factory,
242             matrix_factory,
243             lighting_factory,
244             tile_factory
245         };
246         const char* filterNames[] = {
247             "Color",
248             "Blur",
249             "Drop Shadow",
250             "Offset",
251             "Dilate",
252             "Erode",
253             "Displacement",
254             "Arithmetic",
255             "Blend",
256             "Convolution",
257             "Matrix Xform",
258             "Lighting",
259             "Tile"
260         };
261         static_assert(std::size(filters) == std::size(filterNames), "filter name length");
262 
263         SkIRect clipBounds[] {
264             { -20, -20, 100, 100 },
265             {   0,   0,  75,  75 },
266             {  20,  20, 100, 100 },
267             { -20, -20,  50,  50 },
268             {  20,  20,  50,  50 },
269             {  30,  30,  75,  75 }
270         };
271 
272         auto rContext = canvas->recordingContext();
273         // In a DDL context, we can't use the GPU code paths and we will drop the work – skip.
274         auto dContext = GrAsDirectContext(rContext);
275         if (rContext) {
276             if (!dContext) {
277                 *errorMsg = "Requires a direct context.";
278                 return DrawResult::kSkip;
279             }
280             if (dContext->abandoned()) {
281                 *errorMsg = "Direct context abandoned.";
282                 return DrawResult::kSkip;
283             }
284         }
285 
286         // These need to be GPU-backed when on the GPU to ensure that the image filters use the GPU
287         // code paths (otherwise they may choose to do CPU filtering then upload)
288         sk_sp<SkImage> mainImage = ToolUtils::MakeTextureImage(canvas, fMainImage);
289         sk_sp<SkImage> auxImage = ToolUtils::MakeTextureImage(canvas, fAuxImage);
290         if (!mainImage || !auxImage) {
291             return DrawResult::kFail;
292         }
293         SkASSERT(mainImage && (mainImage->isTextureBacked() || !dContext));
294         SkASSERT(auxImage && (auxImage->isTextureBacked() || !dContext));
295 
296         SkScalar MARGIN = SkIntToScalar(40);
297         SkScalar DX = mainImage->width() + MARGIN;
298         SkScalar DY = auxImage->height() + MARGIN;
299 
300         // Header hinting at what the filters do
301         SkPaint textPaint;
302         textPaint.setAntiAlias(true);
303         SkFont font = ToolUtils::DefaultPortableFont();
304         font.setSize(12);
305         for (size_t i = 0; i < std::size(filterNames); ++i) {
306             canvas->drawString(filterNames[i], DX * i + MARGIN, 15, font, textPaint);
307         }
308 
309         canvas->translate(MARGIN, MARGIN);
310 
311         for (auto clipBound : clipBounds) {
312             canvas->save();
313             for (size_t i = 0; i < std::size(filters); ++i) {
314                 SkIRect subset = SkIRect::MakeXYWH(25, 25, 50, 50);
315                 SkIRect outSubset;
316 
317                 // Draw the original image faintly so that it aids in checking alignment of the
318                 // filtered result.
319                 SkPaint alpha;
320                 alpha.setAlphaf(0.3f);
321                 canvas->drawImage(mainImage, 0, 0, SkSamplingOptions(), &alpha);
322 
323                 this->drawImageWithFilter(canvas, mainImage, auxImage, filters[i], clipBound,
324                                           subset, &outSubset);
325 
326                 // Draw outlines to highlight what was subset, what was cropped, and what was output
327                 // (no output subset is displayed for kSaveLayer since that information isn't avail)
328                 SkIRect* outSubsetBounds = nullptr;
329                 if (fStrategy != Strategy::kSaveLayer) {
330                     outSubsetBounds = &outSubset;
331                 }
332                 show_bounds(canvas, &clipBound, &subset, outSubsetBounds);
333 
334                 canvas->translate(DX, 0);
335             }
336             canvas->restore();
337             canvas->translate(0, DY);
338         }
339         return DrawResult::kOk;
340     }
341 
342 private:
343     Strategy fStrategy;
344     bool fFilterWithCropRect;
345     sk_sp<SkImage> fMainImage;
346     sk_sp<SkImage> fAuxImage;
347 
drawImageWithFilter(SkCanvas * canvas,sk_sp<SkImage> mainImage,sk_sp<SkImage> auxImage,FilterFactory filterFactory,const SkIRect & clip,const SkIRect & subset,SkIRect * dstRect)348     void drawImageWithFilter(SkCanvas* canvas, sk_sp<SkImage> mainImage, sk_sp<SkImage> auxImage,
349                              FilterFactory filterFactory, const SkIRect& clip,
350                              const SkIRect& subset, SkIRect* dstRect) {
351         // When creating the filter with a crop rect equal to the clip, we should expect to see no
352         // difference from a filter without a crop rect. However, if the CTM isn't managed properly
353         // by MakeWithFilter, then the final result will be the incorrect intersection of the clip
354         // and the transformed crop rect.
355         sk_sp<SkImageFilter> filter = filterFactory(auxImage,
356                                                     fFilterWithCropRect ? &clip : nullptr);
357 
358         if (fStrategy == Strategy::kSaveLayer) {
359             SkAutoCanvasRestore acr(canvas, true);
360 
361             // Clip before the saveLayer with the filter
362             canvas->clipRect(SkRect::Make(clip));
363 
364             // Put the image filter on the layer
365             SkPaint paint;
366             paint.setImageFilter(filter);
367             canvas->saveLayer(nullptr, &paint);
368 
369             // Draw the original subset of the image
370             SkRect r = SkRect::Make(subset);
371             canvas->drawImageRect(mainImage, r, r, SkSamplingOptions(),
372                                   nullptr, SkCanvas::kStrict_SrcRectConstraint);
373 
374             *dstRect = subset;
375         } else {
376             sk_sp<SkImage> result;
377             SkIRect outSubset;
378             SkIPoint offset;
379 
380 #if defined(SK_GANESH)
381             if (auto rContext = canvas->recordingContext()) {
382                 result = SkImages::MakeWithFilter(rContext, mainImage, filter.get(),
383                                                   subset, clip, &outSubset, &offset);
384             } else
385 #endif
386 #if defined(SK_GRAPHITE)
387             if (auto recorder = canvas->recorder()){
388                 result = SkImages::MakeWithFilter(recorder, mainImage, filter.get(),
389                                                   subset, clip, &outSubset, &offset);
390             } else
391 #endif
392             {
393                 result = SkImages::MakeWithFilter(mainImage, filter.get(),
394                                                   subset, clip, &outSubset, &offset);
395             }
396 
397             if (!result) {
398                 return;
399             }
400 
401             SkASSERT(mainImage->isTextureBacked() == result->isTextureBacked());
402 
403             *dstRect = SkIRect::MakeXYWH(offset.x(), offset.y(),
404                                          outSubset.width(), outSubset.height());
405             canvas->drawImageRect(result, SkRect::Make(outSubset), SkRect::Make(*dstRect),
406                                   SkSamplingOptions(), nullptr,
407                                   SkCanvas::kStrict_SrcRectConstraint);
408         }
409     }
410 
411     using INHERITED = GM;
412 };
413 // The different strategies should all look the same, with the exception of filters that affect
414 // transparent black (i.e. the lighting filter). In the save layer case, the filter affects the
415 // transparent pixels outside of the drawn subset, whereas the MakeWithFilter is restricted. This
416 // works as intended.
417 DEF_GM( return new ImageMakeWithFilterGM(Strategy::kMakeWithFilter); )
418 DEF_GM( return new ImageMakeWithFilterGM(Strategy::kSaveLayer); )
419 // Test with crop rects on the image filters; should look identical to above if working correctly
420 DEF_GM( return new ImageMakeWithFilterGM(Strategy::kMakeWithFilter, true); )
421 DEF_GM( return new ImageMakeWithFilterGM(Strategy::kSaveLayer, true); )
422