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