2 * Copyright 2011 Google Inc.
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
8 #include "include/core/SkBitmap.h"
9 #include "include/core/SkBlendMode.h"
10 #include "include/core/SkBlurTypes.h"
11 #include "include/core/SkCanvas.h"
12 #include "include/core/SkColor.h"
13 #include "include/core/SkColorPriv.h"
14 #include "include/core/SkImageInfo.h"
15 #include "include/core/SkMaskFilter.h"
16 #include "include/core/SkMath.h"
17 #include "include/core/SkPaint.h"
18 #include "include/core/SkPath.h"
19 #include "include/core/SkPixmap.h"
20 #include "include/core/SkPoint.h"
21 #include "include/core/SkRRect.h"
22 #include "include/core/SkRect.h"
23 #include "include/core/SkRefCnt.h"
24 #include "include/core/SkScalar.h"
25 #include "include/core/SkShader.h"
26 #include "include/core/SkSize.h"
27 #include "include/core/SkSurface.h"
28 #include "include/core/SkTypes.h"
29 #include "include/effects/SkPerlinNoiseShader.h"
30 #include "include/gpu/GrDirectContext.h"
31 #include "include/private/SkFloatBits.h"
32 #include "include/private/SkTPin.h"
33 #include "src/core/SkBlurMask.h"
34 #include "src/core/SkGpuBlurUtils.h"
35 #include "src/core/SkMask.h"
36 #include "src/core/SkMaskFilterBase.h"
37 #include "src/core/SkMathPriv.h"
38 #include "src/effects/SkEmbossMaskFilter.h"
39 #include "tests/Test.h"
40 #include "tools/ToolUtils.h"
41 #include "tools/gpu/GrContextFactory.h"
45 #include <initializer_list>
50 ///////////////////////////////////////////////////////////////////////////////
52 #define ILLEGAL_MODE ((SkXfermode::Mode)-1)
54 static const int outset = 100;
55 static const SkColor bgColor = SK_ColorWHITE;
56 static const int strokeWidth = 4;
58 static void create(SkBitmap* bm, const SkIRect& bound) {
59 bm->allocN32Pixels(bound.width(), bound.height());
62 static void drawBG(SkCanvas* canvas) {
63 canvas->drawColor(bgColor);
68 void (*addPath)(SkPath*);
74 //Beware that paths themselves my draw differently depending on the clip.
75 static void draw50x50Rect(SkPath* path) {
76 path->addRect(0, 0, SkIntToScalar(50), SkIntToScalar(50));
80 static BlurTest tests[] = {
85 { 50 + strokeWidth/2, 50 + strokeWidth/2, 100, 100 },
87 { 40, strokeWidth, 60, 50 - strokeWidth },
91 /** Assumes that the ref draw was completely inside ref canvas --
92 implies that everything outside is "bgColor".
93 Checks that all overlap is the same and that all non-overlap on the
96 static bool compare(const SkBitmap& ref, const SkIRect& iref,
97 const SkBitmap& test, const SkIRect& itest)
99 const int xOff = itest.fLeft - iref.fLeft;
100 const int yOff = itest.fTop - iref.fTop;
102 for (int y = 0; y < test.height(); ++y) {
103 for (int x = 0; x < test.width(); ++x) {
104 SkColor testColor = test.getColor(x, y);
108 if (refX >= 0 && refX < ref.width() &&
109 refY >= 0 && refY < ref.height())
111 refColor = ref.getColor(refX, refY);
115 if (refColor != testColor) {
123 DEF_TEST(BlurDrawing, reporter) {
125 paint.setColor(SK_ColorGRAY);
126 paint.setStyle(SkPaint::kStroke_Style);
127 paint.setStrokeWidth(SkIntToScalar(strokeWidth));
129 SkScalar sigma = SkBlurMask::ConvertRadiusToSigma(SkIntToScalar(5));
130 for (int style = 0; style <= kLastEnum_SkBlurStyle; ++style) {
131 SkBlurStyle blurStyle = static_cast<SkBlurStyle>(style);
133 for (bool respectCTM : { false, true }) {
134 paint.setMaskFilter(SkMaskFilter::MakeBlur(blurStyle, sigma, respectCTM));
136 for (size_t test = 0; test < SK_ARRAY_COUNT(tests); ++test) {
138 tests[test].addPath(&path);
140 paint.getFillPath(path, &strokedPath);
141 SkRect refBound = strokedPath.getBounds();
143 refBound.roundOut(&iref);
144 iref.inset(-outset, -outset);
146 create(&refBitmap, iref);
148 SkCanvas refCanvas(refBitmap);
149 refCanvas.translate(SkIntToScalar(-iref.fLeft),
150 SkIntToScalar(-iref.fTop));
152 refCanvas.drawPath(path, paint);
154 for (int view = 0; view < tests[test].viewLen; ++view) {
155 SkIRect itest = tests[test].views[view];
157 create(&testBitmap, itest);
159 SkCanvas testCanvas(testBitmap);
160 testCanvas.translate(SkIntToScalar(-itest.fLeft),
161 SkIntToScalar(-itest.fTop));
163 testCanvas.drawPath(path, paint);
165 REPORTER_ASSERT(reporter,
166 compare(refBitmap, iref, testBitmap, itest));
173 ///////////////////////////////////////////////////////////////////////////////
175 // Use SkBlurMask::BlurGroundTruth to blur a 'width' x 'height' solid
176 // white rect. Return the right half of the middle row in 'result'.
177 static void ground_truth_2d(int width, int height,
179 int* result, int resultCount) {
182 src.fBounds.setWH(width, height);
183 src.fFormat = SkMask::kA8_Format;
184 src.fRowBytes = src.fBounds.width();
185 src.fImage = SkMask::AllocImage(src.computeTotalImageSize());
187 memset(src.fImage, 0xff, src.computeTotalImageSize());
189 if (!SkBlurMask::BlurGroundTruth(sigma, &dst, src, kNormal_SkBlurStyle)) {
193 int midX = dst.fBounds.x() + dst.fBounds.width()/2;
194 int midY = dst.fBounds.y() + dst.fBounds.height()/2;
195 uint8_t* bytes = dst.getAddr8(midX, midY);
197 for (i = 0; i < dst.fBounds.width()-(midX-dst.fBounds.fLeft); ++i) {
198 if (i < resultCount) {
199 result[i] = bytes[i];
202 for ( ; i < resultCount; ++i) {
206 SkMask::FreeImage(src.fImage);
207 SkMask::FreeImage(dst.fImage);
210 // Implement a step function that is 255 between min and max; 0 elsewhere.
211 static int step(int x, SkScalar min, SkScalar max) {
212 if (min < x && x < max) {
218 // Implement a Gaussian function with 0 mean and std.dev. of 'sigma'.
219 static float gaussian(int x, SkScalar sigma) {
220 float k = SK_Scalar1/(sigma * sqrtf(2.0f*SK_ScalarPI));
221 float exponent = -(x * x) / (2 * sigma * sigma);
222 return k * expf(exponent);
225 // Perform a brute force convolution of a step function with a Gaussian.
226 // Return the right half in 'result'
227 static void brute_force_1d(SkScalar stepMin, SkScalar stepMax,
228 SkScalar gaussianSigma,
229 int* result, int resultCount) {
231 int gaussianRange = SkScalarCeilToInt(10 * gaussianSigma);
233 for (int i = 0; i < resultCount; ++i) {
235 for (int j = -gaussianRange; j < gaussianRange; ++j) {
236 sum += gaussian(j, gaussianSigma) * step(i-j, stepMin, stepMax);
239 result[i] = SkTPin(SkClampPos(int(sum + 0.5f)), 0, 255);
243 static void blur_path(SkCanvas* canvas, const SkPath& path,
244 SkScalar gaussianSigma) {
246 SkScalar midX = path.getBounds().centerX();
247 SkScalar midY = path.getBounds().centerY();
249 canvas->translate(-midX, -midY);
252 blurPaint.setColor(SK_ColorWHITE);
253 blurPaint.setMaskFilter(SkMaskFilter::MakeBlur(kNormal_SkBlurStyle, gaussianSigma));
255 canvas->drawColor(SK_ColorBLACK);
256 canvas->drawPath(path, blurPaint);
259 // Readback the blurred draw results from the canvas
260 static void readback(const SkBitmap& src, int* result, int resultCount) {
262 readback.allocN32Pixels(resultCount, 30);
264 readback.peekPixels(&pm);
265 src.readPixels(pm, 0, 0);
267 const SkPMColor* pixels = pm.addr32(0, 15);
269 for (int i = 0; i < resultCount; ++i) {
270 result[i] = SkColorGetR(pixels[i]);
274 // Draw a blurred version of the provided path.
275 // Return the right half of the middle row in 'result'.
276 static void cpu_blur_path(const SkPath& path, SkScalar gaussianSigma,
277 int* result, int resultCount) {
280 bitmap.allocN32Pixels(resultCount, 30);
281 SkCanvas canvas(bitmap);
283 blur_path(&canvas, path, gaussianSigma);
284 readback(bitmap, result, resultCount);
288 static void write_as_csv(const char* label, SkScalar scale, int* data, int count) {
289 SkDebugf("%s_%.2f,", label, scale);
290 for (int i = 0; i < count-1; ++i) {
291 SkDebugf("%d,", data[i]);
293 SkDebugf("%d\n", data[count-1]);
297 static bool match(int* first, int* second, int count, int tol) {
299 for (int i = 0; i < count; ++i) {
300 delta = first[i] - second[i];
301 if (delta > tol || delta < -tol) {
309 // Test out the normal blur style with a wide range of sigmas
310 DEF_TEST(BlurSigmaRange, reporter) {
311 static const int kSize = 100;
313 // The geometry is offset a smidge to trigger:
314 // https://code.google.com/p/chromium/issues/detail?id=282418
316 rectPath.addRect(0.3f, 0.3f, 100.3f, 100.3f);
318 SkPoint polyPts[] = {
323 { 2.3f, 50.3f } // a little divet to throw off the rect special case
326 polyPath.addPoly(polyPts, SK_ARRAY_COUNT(polyPts), true);
328 int rectSpecialCaseResult[kSize];
329 int generalCaseResult[kSize];
330 int groundTruthResult[kSize];
331 int bruteForce1DResult[kSize];
333 SkScalar sigma = 10.0f;
335 for (int i = 0; i < 4; ++i, sigma /= 10) {
337 cpu_blur_path(rectPath, sigma, rectSpecialCaseResult, kSize);
338 cpu_blur_path(polyPath, sigma, generalCaseResult, kSize);
340 ground_truth_2d(100, 100, sigma, groundTruthResult, kSize);
341 brute_force_1d(-50.0f, 50.0f, sigma, bruteForce1DResult, kSize);
343 REPORTER_ASSERT(reporter, match(rectSpecialCaseResult, bruteForce1DResult, kSize, 5));
344 REPORTER_ASSERT(reporter, match(generalCaseResult, bruteForce1DResult, kSize, 15));
345 REPORTER_ASSERT(reporter, match(groundTruthResult, bruteForce1DResult, kSize, 1));
348 write_as_csv("RectSpecialCase", sigma, rectSpecialCaseResult, kSize);
349 write_as_csv("GeneralCase", sigma, generalCaseResult, kSize);
350 write_as_csv("GPU", sigma, gpuResult, kSize);
351 write_as_csv("GroundTruth2D", sigma, groundTruthResult, kSize);
352 write_as_csv("BruteForce1D", sigma, bruteForce1DResult, kSize);
357 ///////////////////////////////////////////////////////////////////////////////////////////
359 DEF_TEST(BlurAsABlur, reporter) {
360 const SkBlurStyle styles[] = {
361 kNormal_SkBlurStyle, kSolid_SkBlurStyle, kOuter_SkBlurStyle, kInner_SkBlurStyle
363 const SkScalar sigmas[] = {
364 // values <= 0 should not success for a blur
368 // Test asABlur for SkBlurMaskFilter
370 for (size_t i = 0; i < SK_ARRAY_COUNT(styles); ++i) {
371 const SkBlurStyle style = styles[i];
372 for (size_t j = 0; j < SK_ARRAY_COUNT(sigmas); ++j) {
373 const SkScalar sigma = sigmas[j];
374 for (bool respectCTM : { false, true }) {
375 sk_sp<SkMaskFilter> mf(SkMaskFilter::MakeBlur(style, sigma, respectCTM));
376 if (nullptr == mf.get()) {
377 REPORTER_ASSERT(reporter, sigma <= 0);
379 REPORTER_ASSERT(reporter, sigma > 0);
380 SkMaskFilterBase::BlurRec rec;
381 bool success = as_MFB(mf)->asABlur(&rec);
383 REPORTER_ASSERT(reporter, success);
384 REPORTER_ASSERT(reporter, rec.fSigma == sigma);
385 REPORTER_ASSERT(reporter, rec.fStyle == style);
387 REPORTER_ASSERT(reporter, !success);
390 const SkRect src = {0, 0, 100, 100};
391 const auto dst = mf->approximateFilteredBounds(src);
393 // This is a very conservative test. With more knowledge, we could
394 // consider more stringent tests.
395 REPORTER_ASSERT(reporter, dst.contains(src));
401 // Test asABlur for SkEmbossMaskFilter -- should never succeed
404 SkEmbossMaskFilter::Light light = {
405 { 1, 1, 1 }, 0, 127, 127
407 for (size_t j = 0; j < SK_ARRAY_COUNT(sigmas); ++j) {
408 const SkScalar sigma = sigmas[j];
409 auto mf(SkEmbossMaskFilter::Make(sigma, light));
411 SkMaskFilterBase::BlurRec rec;
412 bool success = as_MFB(mf)->asABlur(&rec);
413 REPORTER_ASSERT(reporter, !success);
419 // This exercises the problem discovered in crbug.com/570232. The return value from
420 // SkBlurMask::BoxBlur wasn't being checked in SkBlurMaskFilter.cpp::GrRRectBlurEffect::Create
421 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SmallBoxBlurBug, reporter, ctxInfo) {
423 SkImageInfo info = SkImageInfo::MakeN32Premul(128, 128);
424 auto surface(SkSurface::MakeRenderTarget(ctxInfo.directContext(), SkBudgeted::kNo, info));
425 SkCanvas* canvas = surface->getCanvas();
427 SkRect r = SkRect::MakeXYWH(10, 10, 100, 100);
428 SkRRect rr = SkRRect::MakeRectXY(r, 10, 10);
431 p.setMaskFilter(SkMaskFilter::MakeBlur(kNormal_SkBlurStyle, 0.01f));
433 canvas->drawRRect(rr, p);
436 DEF_TEST(BlurredRRectNinePatchComputation, reporter) {
437 const SkRect r = SkRect::MakeXYWH(10, 10, 100, 100);
438 static const SkScalar kBlurRad = 3.0f;
443 SkScalar rectXs[SkGpuBlurUtils::kBlurRRectMaxDivisions],
444 rectYs[SkGpuBlurUtils::kBlurRRectMaxDivisions];
445 SkScalar texXs[SkGpuBlurUtils::kBlurRRectMaxDivisions],
446 texYs[SkGpuBlurUtils::kBlurRRectMaxDivisions];
448 // not nine-patchable
450 SkVector radii[4] = { { 100, 100 }, { 0, 0 }, { 100, 100 }, { 0, 0 } };
453 rr.setRectRadii(r, radii);
455 ninePatchable = SkGpuBlurUtils::ComputeBlurredRRectParams(rr, rr, kBlurRad, kBlurRad,
457 rectXs, rectYs, texXs, texYs);
458 REPORTER_ASSERT(reporter, !ninePatchable);
463 static const SkScalar kCornerRad = 10.0f;
465 rr.setRectXY(r, kCornerRad, kCornerRad);
467 ninePatchable = SkGpuBlurUtils::ComputeBlurredRRectParams(rr, rr, kBlurRad, kBlurRad,
469 rectXs, rectYs, texXs, texYs);
471 static const SkScalar kAns = 12.0f * kBlurRad + 2.0f * kCornerRad + 1.0f;
472 REPORTER_ASSERT(reporter, ninePatchable);
473 REPORTER_ASSERT(reporter, SkScalarNearlyEqual(SkIntToScalar(size.fWidth), kAns));
474 REPORTER_ASSERT(reporter, SkScalarNearlyEqual(SkIntToScalar(size.fHeight), kAns));
479 static const SkScalar kXCornerRad = 2.0f;
480 static const SkScalar kYCornerRad = 10.0f;
482 rr.setRectXY(r, kXCornerRad, kYCornerRad);
484 ninePatchable = SkGpuBlurUtils::ComputeBlurredRRectParams(rr, rr, kBlurRad, kBlurRad,
486 rectXs, rectYs, texXs, texYs);
488 static const SkScalar kXAns = 12.0f * kBlurRad + 2.0f * kXCornerRad + 1.0f;
489 static const SkScalar kYAns = 12.0f * kBlurRad + 2.0f * kYCornerRad + 1.0f;
491 REPORTER_ASSERT(reporter, ninePatchable);
492 REPORTER_ASSERT(reporter, SkScalarNearlyEqual(SkIntToScalar(size.fWidth), kXAns));
493 REPORTER_ASSERT(reporter, SkScalarNearlyEqual(SkIntToScalar(size.fHeight), kYAns));
497 // https://crbugs.com/787712
498 DEF_TEST(EmbossPerlinCrash, reporter) {
501 static constexpr SkEmbossMaskFilter::Light light = {
502 { 1, 1, 1 }, 0, 127, 127
504 p.setMaskFilter(SkEmbossMaskFilter::Make(1, light));
505 p.setShader(SkPerlinNoiseShader::MakeFractalNoise(1.0f, 1.0f, 2, 0.0f));
507 sk_sp<SkSurface> surface = SkSurface::MakeRasterN32Premul(100, 100);
508 surface->getCanvas()->drawPaint(p);
511 ///////////////////////////////////////////////////////////////////////////////////////////
513 DEF_TEST(BlurZeroSigma, reporter) {
514 auto surf = SkSurface::MakeRasterN32Premul(20, 20);
516 paint.setAntiAlias(true);
518 const SkIRect ir = { 5, 5, 15, 15 };
519 const SkRect r = SkRect::Make(ir);
521 const SkScalar sigmas[] = { 0, SkBits2Float(1) };
522 // if sigma is zero (or nearly so), we need to draw correctly (unblurred) and not crash
524 for (auto sigma : sigmas) {
525 paint.setMaskFilter(SkMaskFilter::MakeBlur(kNormal_SkBlurStyle, sigma));
526 surf->getCanvas()->drawRect(r, paint);
528 ToolUtils::PixelIter iter(surf.get());
530 while (const SkPMColor* p = (const SkPMColor*)iter.next(&loc)) {
531 if (ir.contains(loc.fX, loc.fY)) {
532 // inside the rect we draw (opaque black)
533 REPORTER_ASSERT(reporter, *p == SkPackARGB32(0xFF, 0, 0, 0));
535 // outside the rect we didn't draw at all, no blurred edges
536 REPORTER_ASSERT(reporter, *p == 0);
543 ///////////////////////////////////////////////////////////////////////////////////////////
545 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(BlurMaskBiggerThanDest, reporter, ctxInfo) {
546 auto context = ctxInfo.directContext();
548 SkImageInfo ii = SkImageInfo::Make(32, 32, kRGBA_8888_SkColorType, kPremul_SkAlphaType);
550 sk_sp<SkSurface> dst(SkSurface::MakeRenderTarget(context, SkBudgeted::kNo, ii));
552 ERRORF(reporter, "Could not create surface for test.");
557 p.setColor(SK_ColorRED);
558 p.setMaskFilter(SkMaskFilter::MakeBlur(kNormal_SkBlurStyle, 3));
560 SkCanvas* canvas = dst->getCanvas();
562 canvas->clear(SK_ColorBLACK);
563 canvas->drawCircle(SkPoint::Make(16, 16), 8, p);
566 SkAssertResult(readback.tryAllocPixels(ii));
568 canvas->readPixels(readback, 0, 0);
569 REPORTER_ASSERT(reporter, SkColorGetR(readback.getColor(15, 15)) > 128);
570 REPORTER_ASSERT(reporter, SkColorGetG(readback.getColor(15, 15)) == 0);
571 REPORTER_ASSERT(reporter, SkColorGetB(readback.getColor(15, 15)) == 0);
572 REPORTER_ASSERT(reporter, readback.getColor(31, 31) == SK_ColorBLACK);
575 DEF_TEST(zero_blur, reporter) {
576 SkBitmap alpha, bitmap;
579 paint.setMaskFilter(SkMaskFilter::MakeBlur(kOuter_SkBlurStyle, 3));
581 bitmap.extractAlpha(&alpha, &paint, nullptr, &offset);