1 /*
2  * Copyright 2020 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 "modules/skottie/src/effects/Effects.h"
9 
10 #include "include/core/SkColorFilter.h"
11 #include "include/effects/SkRuntimeEffect.h"
12 #include "include/private/SkTPin.h"
13 #include "modules/skottie/src/Adapter.h"
14 #include "modules/skottie/src/SkottieJson.h"
15 #include "modules/skottie/src/SkottieValue.h"
16 #include "modules/sksg/include/SkSGColorFilter.h"
17 
18 namespace skottie::internal {
19 
20 namespace  {
21 
22 // The contrast effect transfer function can be approximated with the following
23 // 3rd degree polynomial:
24 //
25 //   f(x) = -2πC/3 * x³ + πC * x² + (1 - πC/3) * x
26 //
27 // where C is the normalized contrast value [-1..1].
28 //
29 // Derivation:
30 //
31 //   - start off with sampling the AE contrast effect for various contrast/input values [1]
32 //
33 //   - apply cubic polynomial curve fitting to determine best-fit coefficients for given
34 //     contrast values [2]
35 //
36 //   - observations:
37 //       * negative contrast appears clamped at -0.5 (-50)
38 //       * a,b coefficients vary linearly vs. contrast
39 //       * the b coefficient for max contrast (1.0) looks kinda familiar: 3.14757 - coincidence?
40 //         probably not.  let's run with it: b == πC
41 //
42 //   - additionally, we expect the following to hold:
43 //       * f(0  ) = 0   \     | d = 0
44 //       * f(1  ) = 1    | => | a = -2b/3
45 //       * f(0.5) = 0.5 /     | c = 1 - b/3
46 //
47 //   - this yields a pretty decent approximation: [3]
48 //
49 //
50 // Note (courtesy of mtklein, reed): [4] seems to yield a closer approximation, but requires
51 // a more expensive sin
52 //
53 //   f(x) = x + a * sin(2πx)/2π
54 //
55 // [1] https://www.desmos.com/calculator/oksptqpo8z
56 // [2] https://www.desmos.com/calculator/oukrf6yahn
57 // [3] https://www.desmos.com/calculator/ehem0vy3ft
58 // [4] https://www.desmos.com/calculator/5t4xi10q4v
59 //
60 
61 #ifndef SKOTTIE_ACCURATE_CONTRAST_APPROXIMATION
make_contrast_coeffs(float contrast)62 static sk_sp<SkData> make_contrast_coeffs(float contrast) {
63     struct { float a, b, c; } coeffs;
64 
65     coeffs.b = SK_ScalarPI * contrast;
66     coeffs.a = -2 * coeffs.b / 3;
67     coeffs.c =  1 - coeffs.b / 3;
68 
69     return SkData::MakeWithCopy(&coeffs, sizeof(coeffs));
70 }
71 
72 static constexpr char CONTRAST_EFFECT[] = R"(
73     uniform half a;
74     uniform half b;
75     uniform half c;
76 
77     half4 main(half4 color) {
78         // C' = a*C^3 + b*C^2 + c*C
79         color.rgb = ((a*color.rgb + b)*color.rgb + c)*color.rgb;
80         return color;
81     }
82 )";
83 #else
84 // More accurate (but slower) approximation:
85 //
86 //   f(x) = x + a * sin(2πx)
87 //
88 //   a = -contrast/3π
89 //
90 static sk_sp<SkData> make_contrast_coeffs(float contrast) {
91     const auto coeff_a = -contrast / (3 * SK_ScalarPI);
92 
93     return SkData::MakeWithCopy(&coeff_a, sizeof(coeff_a));
94 }
95 
96 static constexpr char CONTRAST_EFFECT[] = R"(
97     uniform half a;
98 
99     half4 main(half4 color) {
100         color.rgb += a * sin(color.rgb * 6.283185);
101         return color;
102     }
103 )";
104 
105 #endif
106 
107 // Brightness transfer function approximation:
108 //
109 //   f(x) = 1 - (1 - x)^(2^(1.8*B))
110 //
111 // where B is the normalized [-1..1] brightness value
112 //
113 // Visualization: https://www.desmos.com/calculator/wuyqa2wtol
114 //
make_brightness_coeffs(float brightness)115 static sk_sp<SkData> make_brightness_coeffs(float brightness) {
116     const float coeff_a = std::pow(2.0f, brightness * 1.8f);
117 
118     return SkData::MakeWithCopy(&coeff_a, sizeof(coeff_a));
119 }
120 
121 static constexpr char BRIGHTNESS_EFFECT[] = R"(
122     uniform half a;
123 
124     half4 main(half4 color) {
125         color.rgb = 1 - pow(1 - color.rgb, half3(a));
126         return color;
127     }
128 )";
129 
130 class BrightnessContrastAdapter final : public DiscardableAdapterBase<BrightnessContrastAdapter,
131                                                                       sksg::ExternalColorFilter> {
132 public:
BrightnessContrastAdapter(const skjson::ArrayValue & jprops,const AnimationBuilder & abuilder,sk_sp<sksg::RenderNode> layer)133     BrightnessContrastAdapter(const skjson::ArrayValue& jprops,
134                               const AnimationBuilder& abuilder,
135                               sk_sp<sksg::RenderNode> layer)
136         : INHERITED(sksg::ExternalColorFilter::Make(std::move(layer)))
137         , fBrightnessEffect(SkRuntimeEffect::MakeForColorFilter(SkString(BRIGHTNESS_EFFECT)).effect)
138         , fContrastEffect(SkRuntimeEffect::MakeForColorFilter(SkString(CONTRAST_EFFECT)).effect) {
139         SkASSERT(fBrightnessEffect);
140         SkASSERT(fContrastEffect);
141 
142         enum : size_t {
143             kBrightness_Index = 0,
144               kContrast_Index = 1,
145              kUseLegacy_Index = 2,
146         };
147 
148         EffectBinder(jprops, abuilder, this)
149             .bind(kBrightness_Index, fBrightness)
150             .bind(  kContrast_Index, fContrast  )
151             .bind( kUseLegacy_Index, fUseLegacy );
152     }
153 
154 private:
onSync()155     void onSync() override {
156         this->node()->setColorFilter(SkScalarRoundToInt(fUseLegacy)
157                                         ? this->makeLegacyCF()
158                                         : this->makeCF());
159     }
160 
makeLegacyCF() const161     sk_sp<SkColorFilter> makeLegacyCF() const {
162         // In 'legacy' mode, brightness is
163         //
164         //   - in the [-100..100] range
165         //   - applied component-wise as a direct offset (255-based)
166         //   - (neutral value: 0)
167         //   - transfer function: https://www.desmos.com/calculator/zne0oqwwzb
168         //
169         // while contrast is
170         //
171         //   - in the [-100..100] range
172         //   - applied as a component-wise linear transformation (scale+offset), such that
173         //
174         //       -100 always yields mid-gray: contrast(x, -100) == 0.5
175         //          0 is the neutral value:   contrast(x,    0) == x
176         //        100 always yields white:    contrast(x,  100) == 1
177         //
178         //   - transfer function: https://www.desmos.com/calculator/x5rxzhowhs
179         //
180 
181         // Normalize to [-1..1]
182         const auto brightness = SkTPin(fBrightness, -100.0f, 100.0f) / 255, // [-100/255 .. 100/255]
183                    contrast   = SkTPin(fContrast  , -100.0f, 100.0f) / 100; // [      -1 ..       1]
184 
185         // The component scale is derived from contrast:
186         //
187         //   Contrast[-1 .. 0] -> Scale[0 .. 1]
188         //   Contrast( 0 .. 1] -> Scale(1 .. +inf)
189         const auto S = contrast > 0
190             ? 1 / std::max(1 - contrast, SK_ScalarNearlyZero)
191             : 1 + contrast;
192 
193         // The component offset is derived from both brightness and contrast:
194         //
195         //   Brightness[-100/255 .. 100/255] -> Offset[-100/255 .. 100/255]
196         //   Contrast  [      -1 ..       0] -> Offset[     0.5 ..       0]
197         //   Contrast  (       0 ..       1] -> Offset(       0 ..    -inf)
198         //
199         // Why do these pre/post compose depending on contrast scale, you ask?
200         // Because AE - that's why!
201         const auto B = 0.5f * (1 - S) + brightness * std::max(S, 1.0f);
202 
203         const float cm[] = {
204             S, 0, 0, 0, B,
205             0, S, 0, 0, B,
206             0, 0, S, 0, B,
207             0, 0, 0, 1, 0,
208         };
209 
210         return SkColorFilters::Matrix(cm);
211     }
212 
makeCF() const213     sk_sp<SkColorFilter> makeCF() const {
214         const auto brightness = SkTPin(fBrightness, -150.0f, 150.0f) / 150, // [-1.0 .. 1]
215                      contrast = SkTPin(fContrast  ,  -50.0f, 100.0f) / 100; // [-0.5 .. 1]
216 
217         auto b_eff = SkScalarNearlyZero(brightness)
218                    ? nullptr
219                    : fBrightnessEffect->makeColorFilter(make_brightness_coeffs(brightness)),
220              c_eff = SkScalarNearlyZero(fContrast)
221                    ? nullptr
222                    : fContrastEffect->makeColorFilter(make_contrast_coeffs(contrast));
223 
224         return SkColorFilters::Compose(std::move(c_eff), std::move(b_eff));
225     }
226 
227     const sk_sp<SkRuntimeEffect> fBrightnessEffect,
228                                    fContrastEffect;
229 
230     ScalarValue fBrightness = 0,
231                 fContrast   = 0,
232                 fUseLegacy  = 0;
233 
234     using INHERITED = DiscardableAdapterBase<BrightnessContrastAdapter, sksg::ExternalColorFilter>;
235 };
236 
237 } // namespace
238 
attachBrightnessContrastEffect(const skjson::ArrayValue & jprops,sk_sp<sksg::RenderNode> layer) const239 sk_sp<sksg::RenderNode> EffectBuilder::attachBrightnessContrastEffect(
240         const skjson::ArrayValue& jprops, sk_sp<sksg::RenderNode> layer) const {
241     return fBuilder->attachDiscardableAdapter<BrightnessContrastAdapter>(jprops,
242                                                                          *fBuilder,
243                                                                          std::move(layer));
244 }
245 
246 } // namespace skottie::internal
247