1/*
2 * Copyright 2015 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 "Test.h"
9#include "SkColor.h"
10#include "SkColorPriv.h"
11#include "SkTaskGroup.h"
12#include <functional>
13
14struct Results { int diffs, diffs_0x00, diffs_0xff, diffs_by_1; };
15
16static bool acceptable(const Results& r) {
17#if 0
18    SkDebugf("%d diffs, %d at 0x00, %d at 0xff, %d off by 1, all out of 65536\n",
19             r.diffs, r.diffs_0x00, r.diffs_0xff, r.diffs_by_1);
20#endif
21    return r.diffs_by_1 == r.diffs   // never off by more than 1
22        && r.diffs_0x00 == 0         // transparent must stay transparent
23        && r.diffs_0xff == 0;        // opaque must stay opaque
24}
25
26template <typename Fn>
27static Results test(Fn&& multiply) {
28    Results r = { 0,0,0,0 };
29    for (int x = 0; x < 256; x++) {
30    for (int y = 0; y < 256; y++) {
31        int p = multiply(x, y),
32            ideal = (x*y+127)/255;
33        if (p != ideal) {
34            r.diffs++;
35            if (x == 0x00 || y == 0x00) { r.diffs_0x00++; }
36            if (x == 0xff || y == 0xff) { r.diffs_0xff++; }
37            if (SkTAbs(ideal - p) == 1) { r.diffs_by_1++; }
38        }
39    }}
40    return r;
41}
42
43DEF_TEST(Blend_byte_multiply, r) {
44    // These are all temptingly close but fundamentally broken.
45    int (*broken[])(int, int) = {
46        [](int x, int y) { return (x*y)>>8; },
47        [](int x, int y) { return (x*y+128)>>8; },
48        [](int x, int y) { y += y>>7; return (x*y)>>8; },
49    };
50    for (auto multiply : broken) { REPORTER_ASSERT(r, !acceptable(test(multiply))); }
51
52    // These are fine to use, but not perfect.
53    int (*fine[])(int, int) = {
54        [](int x, int y) { return (x*y+x)>>8; },
55        [](int x, int y) { return (x*y+y)>>8; },
56        [](int x, int y) { return (x*y+255)>>8; },
57        [](int x, int y) { y += y>>7; return (x*y+128)>>8; },
58    };
59    for (auto multiply : fine) { REPORTER_ASSERT(r, acceptable(test(multiply))); }
60
61    // These are pefect.
62    int (*perfect[])(int, int) = {
63        [](int x, int y) { return (x*y+127)/255; },  // Duh.
64        [](int x, int y) { int p = (x*y+128); return (p+(p>>8))>>8; },
65        [](int x, int y) { return ((x*y+128)*257)>>16; },
66    };
67    for (auto multiply : perfect) { REPORTER_ASSERT(r, test(multiply).diffs == 0); }
68}
69