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 "Benchmark.h"
9#include "SkCanvas.h"
10#include "SkPath.h"
11#include "SkPathOps.h"
12
13class ClipStrategyBench : public Benchmark {
14public:
15    enum class Mode {
16        kClipPath,
17        kMask,
18    };
19
20    ClipStrategyBench(Mode mode, size_t count)
21        : fMode(mode)
22        , fCount(count)
23        , fName("clip_strategy_"){
24
25        if (fMode == Mode::kClipPath) {
26            fName.append("path_");
27            this->forEachClipCircle([&](float x, float y, float r) {
28                fClipPath.addCircle(x, y, r);
29            });
30        } else {
31            fName.append("mask_");
32        }
33        fName.appendf("%zu", count);
34    }
35
36    ~ClipStrategyBench() override = default;
37
38protected:
39    const char* onGetName() override {
40        return fName.c_str();
41    }
42
43    void onDraw(int loops, SkCanvas* canvas) override {
44        SkPaint p, srcIn;
45        p.setAntiAlias(true);
46        srcIn.setBlendMode(SkBlendMode::kSrcIn);
47
48        for (int i = 0; i < loops; ++i) {
49            SkAutoCanvasRestore acr(canvas, false);
50
51            if (fMode == Mode::kClipPath) {
52                canvas->save();
53                canvas->clipPath(fClipPath, true);
54            } else {
55                canvas->saveLayer(nullptr, nullptr);
56                this->forEachClipCircle([&](float x, float y, float r) {
57                    canvas->drawCircle(x, y, r, p);
58                });
59                canvas->saveLayer(nullptr, &srcIn);
60            }
61            canvas->drawColor(SK_ColorGREEN);
62        }
63    }
64
65private:
66    template <typename Func>
67    void forEachClipCircle(Func&& func) {
68        auto q = static_cast<float>(this->getSize().x()) / (fCount + 1);
69        for (size_t i = 1; i <= fCount; ++i) {
70            auto x = q * i;
71            func(x, x, q / 2);
72        }
73    }
74
75    Mode     fMode;
76    size_t   fCount;
77    SkString fName;
78    SkPath   fClipPath;
79
80    typedef Benchmark INHERITED;
81};
82
83DEF_BENCH( return new ClipStrategyBench(ClipStrategyBench::Mode::kClipPath, 1  );)
84DEF_BENCH( return new ClipStrategyBench(ClipStrategyBench::Mode::kClipPath, 5  );)
85DEF_BENCH( return new ClipStrategyBench(ClipStrategyBench::Mode::kClipPath, 10 );)
86DEF_BENCH( return new ClipStrategyBench(ClipStrategyBench::Mode::kClipPath, 100);)
87
88DEF_BENCH( return new ClipStrategyBench(ClipStrategyBench::Mode::kMask, 1  );)
89DEF_BENCH( return new ClipStrategyBench(ClipStrategyBench::Mode::kMask, 5  );)
90DEF_BENCH( return new ClipStrategyBench(ClipStrategyBench::Mode::kMask, 10 );)
91DEF_BENCH( return new ClipStrategyBench(ClipStrategyBench::Mode::kMask, 100);)
92