1 /*
2  * Copyright 2020 Google LLC
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 "include/core/SkCanvas.h"
9 #include "include/core/SkImage.h"
10 #include "include/core/SkRefCnt.h"
11 #include "include/core/SkSamplingOptions.h"
12 #include "include/core/SkSurface.h"
13 #include "include/core/SkTypes.h"
14 #include "src/base/SkRandom.h"
15 #include "src/core/SkSamplingPriv.h"
16 #include "tests/Test.h"
17 #include "tools/Resources.h"
18 #include "tools/ToolUtils.h"
19 
20 #include <initializer_list>
21 
22 // In general, sampling under identity matrix should not affect the pixels. However,
23 // cubic resampling when B != 0 is expected to change pixels.
24 //
DEF_TEST(sampling_with_identity_matrix,r)25 DEF_TEST(sampling_with_identity_matrix, r) {
26     const char* names[] = {
27         "images/mandrill_128.png", "images/color_wheel.jpg",
28     };
29 
30     SkRandom rand;
31     for (auto name : names) {
32         auto src = GetResourceAsImage(name);
33         auto surf = SkSurface::MakeRasterN32Premul(src->width(), src->height());
34         auto canvas = surf->getCanvas();
35 
36         auto dotest = [&](const SkSamplingOptions& sampling, bool expect_same) {
37             canvas->clear(0);
38             canvas->drawImage(src.get(), 0, 0, sampling, nullptr);
39             auto dst = surf->makeImageSnapshot();
40 
41             REPORTER_ASSERT(r, SkSamplingPriv::NoChangeWithIdentityMatrix(sampling) == expect_same);
42             REPORTER_ASSERT(r, ToolUtils::equal_pixels(src.get(), dst.get()) == expect_same);
43         };
44 
45         // Exercise all non-cubics -- expecting no changes
46         for (auto m : {SkMipmapMode::kNone, SkMipmapMode::kNearest, SkMipmapMode::kLinear}) {
47             for (auto f : {SkFilterMode::kNearest, SkFilterMode::kLinear}) {
48                 dotest(SkSamplingOptions(f, m), true);
49             }
50         }
51 
52         // Exercise cubic variants with B zero and non-zero
53         constexpr int N = 30;   // try a bunch of random values
54         for (int i = 0; i < N; ++i) {
55             float C = rand.nextF();
56             dotest(SkSamplingOptions({0, C}), true);
57 
58             float B = rand.nextF() * 0.9f + 0.05f;  // non-zero but still within (0,,,1]
59             SkASSERT(B != 0);
60             dotest(SkSamplingOptions({B, C}), false);
61         }
62     }
63 }
64