1/*
2 * Copyright 2014 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 "GrBicubicEffect.h"
9
10#include "GrTexture.h"
11#include "glsl/GrGLSLFragmentShaderBuilder.h"
12#include "glsl/GrGLSLProgramDataManager.h"
13#include "glsl/GrGLSLUniformHandler.h"
14#include "../private/GrGLSL.h"
15
16class GrGLBicubicEffect : public GrGLSLFragmentProcessor {
17public:
18    void emitCode(EmitArgs&) override;
19
20    static inline void GenKey(const GrProcessor& effect, const GrShaderCaps&,
21                              GrProcessorKeyBuilder* b) {
22        const GrBicubicEffect& bicubicEffect = effect.cast<GrBicubicEffect>();
23        b->add32(GrTextureDomain::GLDomain::DomainKey(bicubicEffect.domain()));
24    }
25
26protected:
27    void onSetData(const GrGLSLProgramDataManager&, const GrFragmentProcessor&) override;
28
29private:
30    typedef GrGLSLProgramDataManager::UniformHandle UniformHandle;
31
32    UniformHandle               fImageIncrementUni;
33    GrTextureDomain::GLDomain   fDomain;
34
35    typedef GrGLSLFragmentProcessor INHERITED;
36};
37
38void GrGLBicubicEffect::emitCode(EmitArgs& args) {
39    const GrBicubicEffect& bicubicEffect = args.fFp.cast<GrBicubicEffect>();
40
41    GrGLSLUniformHandler* uniformHandler = args.fUniformHandler;
42    fImageIncrementUni = uniformHandler->addUniform(kFragment_GrShaderFlag, kHalf2_GrSLType,
43                                                    "ImageIncrement");
44
45    const char* imgInc = uniformHandler->getUniformCStr(fImageIncrementUni);
46
47    GrGLSLFPFragmentBuilder* fragBuilder = args.fFragBuilder;
48    SkString coords2D = fragBuilder->ensureCoords2D(args.fTransformedCoords[0]);
49
50    /*
51     * Filter weights come from Don Mitchell & Arun Netravali's 'Reconstruction Filters in Computer
52     * Graphics', ACM SIGGRAPH Computer Graphics 22, 4 (Aug. 1988).
53     * ACM DL: http://dl.acm.org/citation.cfm?id=378514
54     * Free  : http://www.cs.utexas.edu/users/fussell/courses/cs384g/lectures/mitchell/Mitchell.pdf
55     *
56     * The authors define a family of cubic filters with two free parameters (B and C):
57     *
58     *            { (12 - 9B - 6C)|x|^3 + (-18 + 12B + 6C)|x|^2 + (6 - 2B)          if |x| < 1
59     * k(x) = 1/6 { (-B - 6C)|x|^3 + (6B + 30C)|x|^2 + (-12B - 48C)|x| + (8B + 24C) if 1 <= |x| < 2
60     *            { 0                                                               otherwise
61     *
62     * Various well-known cubic splines can be generated, and the authors select (1/3, 1/3) as their
63     * favorite overall spline - this is now commonly known as the Mitchell filter, and is the
64     * source of the specific weights below.
65     *
66     * This is GLSL, so the matrix is column-major (transposed from standard matrix notation).
67     */
68    fragBuilder->codeAppend("half4x4 kMitchellCoefficients = half4x4("
69                            " 1.0 / 18.0,  16.0 / 18.0,   1.0 / 18.0,  0.0 / 18.0,"
70                            "-9.0 / 18.0,   0.0 / 18.0,   9.0 / 18.0,  0.0 / 18.0,"
71                            "15.0 / 18.0, -36.0 / 18.0,  27.0 / 18.0, -6.0 / 18.0,"
72                            "-7.0 / 18.0,  21.0 / 18.0, -21.0 / 18.0,  7.0 / 18.0);");
73    fragBuilder->codeAppendf("float2 coord = %s - %s * float2(0.5);", coords2D.c_str(), imgInc);
74    // We unnormalize the coord in order to determine our fractional offset (f) within the texel
75    // We then snap coord to a texel center and renormalize. The snap prevents cases where the
76    // starting coords are near a texel boundary and accumulations of imgInc would cause us to skip/
77    // double hit a texel.
78    fragBuilder->codeAppendf("coord /= %s;", imgInc);
79    fragBuilder->codeAppend("float2 f = fract(coord);");
80    fragBuilder->codeAppendf("coord = (coord - f + float2(0.5)) * %s;", imgInc);
81    fragBuilder->codeAppend("half4 wx = kMitchellCoefficients * half4(1.0, f.x, f.x * f.x, f.x * f.x * f.x);");
82    fragBuilder->codeAppend("half4 wy = kMitchellCoefficients * half4(1.0, f.y, f.y * f.y, f.y * f.y * f.y);");
83    fragBuilder->codeAppend("half4 rowColors[4];");
84    for (int y = 0; y < 4; ++y) {
85        for (int x = 0; x < 4; ++x) {
86            SkString coord;
87            coord.printf("coord + %s * float2(%d, %d)", imgInc, x - 1, y - 1);
88            SkString sampleVar;
89            sampleVar.printf("rowColors[%d]", x);
90            fDomain.sampleTexture(fragBuilder,
91                                  args.fUniformHandler,
92                                  args.fShaderCaps,
93                                  bicubicEffect.domain(),
94                                  sampleVar.c_str(),
95                                  coord,
96                                  args.fTexSamplers[0]);
97        }
98        fragBuilder->codeAppendf(
99            "half4 s%d = wx.x * rowColors[0] + wx.y * rowColors[1] + wx.z * rowColors[2] + wx.w * rowColors[3];",
100            y);
101    }
102    SkString bicubicColor("(wy.x * s0 + wy.y * s1 + wy.z * s2 + wy.w * s3)");
103    fragBuilder->codeAppendf("%s = %s * %s;", args.fOutputColor, bicubicColor.c_str(),
104                             args.fInputColor);
105}
106
107void GrGLBicubicEffect::onSetData(const GrGLSLProgramDataManager& pdman,
108                                  const GrFragmentProcessor& processor) {
109    const GrBicubicEffect& bicubicEffect = processor.cast<GrBicubicEffect>();
110    GrSurfaceProxy* proxy = processor.textureSampler(0).proxy();
111    GrTexture* texture = proxy->priv().peekTexture();
112
113    float imageIncrement[2];
114    imageIncrement[0] = 1.0f / texture->width();
115    imageIncrement[1] = 1.0f / texture->height();
116    pdman.set2fv(fImageIncrementUni, 1, imageIncrement);
117    fDomain.setData(pdman, bicubicEffect.domain(), proxy);
118}
119
120GrBicubicEffect::GrBicubicEffect(sk_sp<GrTextureProxy> proxy,
121                                 const SkMatrix& matrix,
122                                 const GrSamplerState::WrapMode wrapModes[2])
123        : INHERITED{kGrBicubicEffect_ClassID, ModulateByConfigOptimizationFlags(proxy->config())}
124        , fCoordTransform(matrix, proxy.get())
125        , fDomain(GrTextureDomain::IgnoredDomain())
126        , fTextureSampler(std::move(proxy),
127                          GrSamplerState(wrapModes, GrSamplerState::Filter::kNearest)) {
128    this->addCoordTransform(&fCoordTransform);
129    this->addTextureSampler(&fTextureSampler);
130}
131
132GrBicubicEffect::GrBicubicEffect(sk_sp<GrTextureProxy> proxy,
133                                 const SkMatrix& matrix,
134                                 const SkRect& domain)
135        : INHERITED(kGrBicubicEffect_ClassID, ModulateByConfigOptimizationFlags(proxy->config()))
136        , fCoordTransform(matrix, proxy.get())
137        , fDomain(proxy.get(), domain, GrTextureDomain::kClamp_Mode)
138        , fTextureSampler(std::move(proxy)) {
139    this->addCoordTransform(&fCoordTransform);
140    this->addTextureSampler(&fTextureSampler);
141}
142
143GrBicubicEffect::GrBicubicEffect(const GrBicubicEffect& that)
144        : INHERITED(kGrBicubicEffect_ClassID, that.optimizationFlags())
145        , fCoordTransform(that.fCoordTransform)
146        , fDomain(that.fDomain)
147        , fTextureSampler(that.fTextureSampler) {
148    this->addCoordTransform(&fCoordTransform);
149    this->addTextureSampler(&fTextureSampler);
150}
151
152void GrBicubicEffect::onGetGLSLProcessorKey(const GrShaderCaps& caps,
153                                            GrProcessorKeyBuilder* b) const {
154    GrGLBicubicEffect::GenKey(*this, caps, b);
155}
156
157GrGLSLFragmentProcessor* GrBicubicEffect::onCreateGLSLInstance() const  {
158    return new GrGLBicubicEffect;
159}
160
161bool GrBicubicEffect::onIsEqual(const GrFragmentProcessor& sBase) const {
162    const GrBicubicEffect& s = sBase.cast<GrBicubicEffect>();
163    return fDomain == s.fDomain;
164}
165
166GR_DEFINE_FRAGMENT_PROCESSOR_TEST(GrBicubicEffect);
167
168#if GR_TEST_UTILS
169std::unique_ptr<GrFragmentProcessor> GrBicubicEffect::TestCreate(GrProcessorTestData* d) {
170    int texIdx = d->fRandom->nextBool() ? GrProcessorUnitTest::kSkiaPMTextureIdx
171                                        : GrProcessorUnitTest::kAlphaTextureIdx;
172    static const GrSamplerState::WrapMode kClampClamp[] = {GrSamplerState::WrapMode::kClamp,
173                                                           GrSamplerState::WrapMode::kClamp};
174    return GrBicubicEffect::Make(d->textureProxy(texIdx), SkMatrix::I(), kClampClamp);
175}
176#endif
177
178//////////////////////////////////////////////////////////////////////////////
179
180bool GrBicubicEffect::ShouldUseBicubic(const SkMatrix& matrix, GrSamplerState::Filter* filterMode) {
181    if (matrix.isIdentity()) {
182        *filterMode = GrSamplerState::Filter::kNearest;
183        return false;
184    }
185
186    SkScalar scales[2];
187    if (!matrix.getMinMaxScales(scales) || scales[0] < SK_Scalar1) {
188        // Bicubic doesn't handle arbitrary minimization well, as src texels can be skipped
189        // entirely,
190        *filterMode = GrSamplerState::Filter::kMipMap;
191        return false;
192    }
193    // At this point if scales[1] == SK_Scalar1 then the matrix doesn't do any scaling.
194    if (scales[1] == SK_Scalar1) {
195        if (matrix.rectStaysRect() && SkScalarIsInt(matrix.getTranslateX()) &&
196            SkScalarIsInt(matrix.getTranslateY())) {
197            *filterMode = GrSamplerState::Filter::kNearest;
198        } else {
199            // Use bilerp to handle rotation or fractional translation.
200            *filterMode = GrSamplerState::Filter::kBilerp;
201        }
202        return false;
203    }
204    // When we use the bicubic filtering effect each sample is read from the texture using
205    // nearest neighbor sampling.
206    *filterMode = GrSamplerState::Filter::kNearest;
207    return true;
208}
209