• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "src/core/SkMatrixPriv.h"
9 #include "src/gpu/effects/GrBicubicEffect.h"
10 
11 #include "include/gpu/GrTexture.h"
12 #include "src/gpu/glsl/GrGLSLFragmentShaderBuilder.h"
13 #include "src/gpu/glsl/GrGLSLProgramDataManager.h"
14 #include "src/gpu/glsl/GrGLSLUniformHandler.h"
15 
16 class GrGLBicubicEffect : public GrGLSLFragmentProcessor {
17 public:
18     void emitCode(EmitArgs&) override;
19 
GenKey(const GrProcessor & effect,const GrShaderCaps &,GrProcessorKeyBuilder * b)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         uint32_t bidir = bicubicEffect.direction() == GrBicubicEffect::Direction::kXY ? 1 : 0;
25         b->add32(bidir | (bicubicEffect.alphaType() << 1));
26     }
27 
28 protected:
29     void onSetData(const GrGLSLProgramDataManager&, const GrFragmentProcessor&) override;
30 
31 private:
32     typedef GrGLSLProgramDataManager::UniformHandle UniformHandle;
33 
34     UniformHandle fDimensions;
35     GrTextureDomain::GLDomain   fDomain;
36 
37     typedef GrGLSLFragmentProcessor INHERITED;
38 };
39 
emitCode(EmitArgs & args)40 void GrGLBicubicEffect::emitCode(EmitArgs& args) {
41     const GrBicubicEffect& bicubicEffect = args.fFp.cast<GrBicubicEffect>();
42 
43     GrGLSLUniformHandler* uniformHandler = args.fUniformHandler;
44     fDimensions = uniformHandler->addUniform(kFragment_GrShaderFlag, kHalf4_GrSLType, "Dimensions");
45 
46     const char* dims = uniformHandler->getUniformCStr(fDimensions);
47 
48     GrGLSLFPFragmentBuilder* fragBuilder = args.fFragBuilder;
49     SkString coords2D = fragBuilder->ensureCoords2D(args.fTransformedCoords[0]);
50 
51     /*
52      * Filter weights come from Don Mitchell & Arun Netravali's 'Reconstruction Filters in Computer
53      * Graphics', ACM SIGGRAPH Computer Graphics 22, 4 (Aug. 1988).
54      * ACM DL: http://dl.acm.org/citation.cfm?id=378514
55      * Free  : http://www.cs.utexas.edu/users/fussell/courses/cs384g/lectures/mitchell/Mitchell.pdf
56      *
57      * The authors define a family of cubic filters with two free parameters (B and C):
58      *
59      *            { (12 - 9B - 6C)|x|^3 + (-18 + 12B + 6C)|x|^2 + (6 - 2B)          if |x| < 1
60      * k(x) = 1/6 { (-B - 6C)|x|^3 + (6B + 30C)|x|^2 + (-12B - 48C)|x| + (8B + 24C) if 1 <= |x| < 2
61      *            { 0                                                               otherwise
62      *
63      * Various well-known cubic splines can be generated, and the authors select (1/3, 1/3) as their
64      * favorite overall spline - this is now commonly known as the Mitchell filter, and is the
65      * source of the specific weights below.
66      *
67      * This is GLSL, so the matrix is column-major (transposed from standard matrix notation).
68      */
69     fragBuilder->codeAppend("half4x4 kMitchellCoefficients = half4x4("
70                             " 1.0 / 18.0,  16.0 / 18.0,   1.0 / 18.0,  0.0 / 18.0,"
71                             "-9.0 / 18.0,   0.0 / 18.0,   9.0 / 18.0,  0.0 / 18.0,"
72                             "15.0 / 18.0, -36.0 / 18.0,  27.0 / 18.0, -6.0 / 18.0,"
73                             "-7.0 / 18.0,  21.0 / 18.0, -21.0 / 18.0,  7.0 / 18.0);");
74     fragBuilder->codeAppendf("float2 coord = %s - %s.xy * float2(0.5);", coords2D.c_str(), dims);
75     // We unnormalize the coord in order to determine our fractional offset (f) within the texel
76     // We then snap coord to a texel center and renormalize. The snap prevents cases where the
77     // starting coords are near a texel boundary and accumulations of dims would cause us to skip/
78     // double hit a texel.
79     fragBuilder->codeAppendf("half2 f = half2(fract(coord * %s.zw));", dims);
80     fragBuilder->codeAppendf("coord = coord + (half2(0.5) - f) * %s.xy;", dims);
81     if (bicubicEffect.direction() == GrBicubicEffect::Direction::kXY) {
82         fragBuilder->codeAppend(
83                 "half4 wx = kMitchellCoefficients * half4(1.0, f.x, f.x * f.x, f.x * f.x * f.x);");
84         fragBuilder->codeAppend(
85                 "half4 wy = kMitchellCoefficients * half4(1.0, f.y, f.y * f.y, f.y * f.y * f.y);");
86         fragBuilder->codeAppend("half4 rowColors[4];");
87         for (int y = 0; y < 4; ++y) {
88             for (int x = 0; x < 4; ++x) {
89                 SkString coord;
90                 coord.printf("coord + %s.xy * float2(%d, %d)", dims, x - 1, y - 1);
91                 SkString sampleVar;
92                 sampleVar.printf("rowColors[%d]", x);
93                 fDomain.sampleTexture(fragBuilder,
94                                       args.fUniformHandler,
95                                       args.fShaderCaps,
96                                       bicubicEffect.domain(),
97                                       sampleVar.c_str(),
98                                       coord,
99                                       args.fTexSamplers[0]);
100             }
101             fragBuilder->codeAppendf(
102                     "half4 s%d = wx.x * rowColors[0] + wx.y * rowColors[1] + wx.z * rowColors[2] + "
103                     "wx.w * rowColors[3];",
104                     y);
105         }
106         fragBuilder->codeAppend(
107                 "half4 bicubicColor = wy.x * s0 + wy.y * s1 + wy.z * s2 + wy.w * s3;");
108     } else {
109         // One of the dims.xy values will be zero. So v here selects the nonzero value of f.
110         fragBuilder->codeAppend("half v = f.x + f.y;");
111         fragBuilder->codeAppend("half v2 = v * v;");
112         fragBuilder->codeAppend("half4 w = kMitchellCoefficients * half4(1.0, v, v2, v2 * v);");
113         fragBuilder->codeAppend("half4 c[4];");
114         for (int i = 0; i < 4; ++i) {
115             SkString coord;
116             coord.printf("coord + %s.xy * half(%d)", dims, i - 1);
117             SkString samplerVar;
118             samplerVar.printf("c[%d]", i);
119             // With added complexity we could apply the domain once in X or Y depending on
120             // direction rather than for each of the four lookups, but then we might not be
121             // be able to share code for Direction::kX and ::kY.
122             fDomain.sampleTexture(fragBuilder,
123                                   args.fUniformHandler,
124                                   args.fShaderCaps,
125                                   bicubicEffect.domain(),
126                                   samplerVar.c_str(),
127                                   coord,
128                                   args.fTexSamplers[0]);
129         }
130         fragBuilder->codeAppend(
131                 "half4 bicubicColor = c[0] * w.x + c[1] * w.y + c[2] * w.z + c[3] * w.w;");
132     }
133     // Bicubic can send colors out of range, so clamp to get them back in (source) gamut.
134     // The kind of clamp we have to do depends on the alpha type.
135     if (kPremul_SkAlphaType == bicubicEffect.alphaType()) {
136         fragBuilder->codeAppend("bicubicColor.a = saturate(bicubicColor.a);");
137         fragBuilder->codeAppend(
138                 "bicubicColor.rgb = max(half3(0.0), min(bicubicColor.rgb, bicubicColor.aaa));");
139     } else {
140         fragBuilder->codeAppend("bicubicColor = saturate(bicubicColor);");
141     }
142     fragBuilder->codeAppendf("%s = bicubicColor * %s;", args.fOutputColor, args.fInputColor);
143 }
144 
onSetData(const GrGLSLProgramDataManager & pdman,const GrFragmentProcessor & processor)145 void GrGLBicubicEffect::onSetData(const GrGLSLProgramDataManager& pdman,
146                                   const GrFragmentProcessor& processor) {
147     const GrBicubicEffect& bicubicEffect = processor.cast<GrBicubicEffect>();
148     GrTextureProxy* proxy = processor.textureSampler(0).proxy();
149     GrTexture* texture = proxy->peekTexture();
150 
151     float dims[4] = {0, 0, 0, 0};
152     if (bicubicEffect.direction() != GrBicubicEffect::Direction::kY) {
153         dims[0] = 1.0f / texture->width();
154         dims[2] = texture->width();
155     }
156     if (bicubicEffect.direction() != GrBicubicEffect::Direction::kX) {
157         dims[1] = 1.0f / texture->height();
158         dims[3] = texture->height();
159     }
160     pdman.set4fv(fDimensions, 1, dims);
161     fDomain.setData(pdman, bicubicEffect.domain(), proxy,
162                     processor.textureSampler(0).samplerState());
163 }
164 
GrBicubicEffect(sk_sp<GrTextureProxy> proxy,const SkMatrix & matrix,const SkRect & domain,const GrSamplerState::WrapMode wrapModes[2],GrTextureDomain::Mode modeX,GrTextureDomain::Mode modeY,Direction direction,SkAlphaType alphaType)165 GrBicubicEffect::GrBicubicEffect(sk_sp<GrTextureProxy> proxy, const SkMatrix& matrix,
166                                  const SkRect& domain, const GrSamplerState::WrapMode wrapModes[2],
167                                  GrTextureDomain::Mode modeX, GrTextureDomain::Mode modeY,
168                                  Direction direction, SkAlphaType alphaType)
169         : INHERITED{kGrBicubicEffect_ClassID,
170                     ModulateForSamplerOptFlags(
171                             proxy->config(),
172                             GrTextureDomain::IsDecalSampled(wrapModes, modeX, modeY))}
173         , fCoordTransform(matrix, proxy.get())
174         , fDomain(proxy.get(), domain, modeX, modeY)
175         , fTextureSampler(std::move(proxy),
176                           GrSamplerState(wrapModes, GrSamplerState::Filter::kNearest))
177         , fAlphaType(alphaType)
178         , fDirection(direction) {
179     this->addCoordTransform(&fCoordTransform);
180     this->setTextureSamplerCnt(1);
181 }
182 
GrBicubicEffect(const GrBicubicEffect & that)183 GrBicubicEffect::GrBicubicEffect(const GrBicubicEffect& that)
184         : INHERITED(kGrBicubicEffect_ClassID, that.optimizationFlags())
185         , fCoordTransform(that.fCoordTransform)
186         , fDomain(that.fDomain)
187         , fTextureSampler(that.fTextureSampler)
188         , fAlphaType(that.fAlphaType)
189         , fDirection(that.fDirection) {
190     this->addCoordTransform(&fCoordTransform);
191     this->setTextureSamplerCnt(1);
192 }
193 
onGetGLSLProcessorKey(const GrShaderCaps & caps,GrProcessorKeyBuilder * b) const194 void GrBicubicEffect::onGetGLSLProcessorKey(const GrShaderCaps& caps,
195                                             GrProcessorKeyBuilder* b) const {
196     GrGLBicubicEffect::GenKey(*this, caps, b);
197 }
198 
onCreateGLSLInstance() const199 GrGLSLFragmentProcessor* GrBicubicEffect::onCreateGLSLInstance() const  {
200     return new GrGLBicubicEffect;
201 }
202 
onIsEqual(const GrFragmentProcessor & sBase) const203 bool GrBicubicEffect::onIsEqual(const GrFragmentProcessor& sBase) const {
204     const GrBicubicEffect& s = sBase.cast<GrBicubicEffect>();
205     return fDomain == s.fDomain && fDirection == s.fDirection && fAlphaType == s.fAlphaType;
206 }
207 
208 GR_DEFINE_FRAGMENT_PROCESSOR_TEST(GrBicubicEffect);
209 
210 #if GR_TEST_UTILS
TestCreate(GrProcessorTestData * d)211 std::unique_ptr<GrFragmentProcessor> GrBicubicEffect::TestCreate(GrProcessorTestData* d) {
212     int texIdx = d->fRandom->nextBool() ? GrProcessorUnitTest::kSkiaPMTextureIdx
213                                         : GrProcessorUnitTest::kAlphaTextureIdx;
214     static const GrSamplerState::WrapMode kClampClamp[] = {GrSamplerState::WrapMode::kClamp,
215                                                            GrSamplerState::WrapMode::kClamp};
216     SkAlphaType alphaType = d->fRandom->nextBool() ? kPremul_SkAlphaType : kUnpremul_SkAlphaType;
217     Direction direction = Direction::kX;
218     switch (d->fRandom->nextULessThan(3)) {
219         case 0:
220             direction = Direction::kX;
221             break;
222         case 1:
223             direction = Direction::kY;
224             break;
225         case 2:
226             direction = Direction::kXY;
227             break;
228     }
229     return GrBicubicEffect::Make(d->textureProxy(texIdx), SkMatrix::I(), kClampClamp, direction,
230                                  alphaType);
231 }
232 #endif
233 
234 //////////////////////////////////////////////////////////////////////////////
235 
ShouldUseBicubic(const SkMatrix & matrix,GrSamplerState::Filter * filterMode)236 bool GrBicubicEffect::ShouldUseBicubic(const SkMatrix& matrix, GrSamplerState::Filter* filterMode) {
237     switch (SkMatrixPriv::AdjustHighQualityFilterLevel(matrix)) {
238         case kNone_SkFilterQuality:
239             *filterMode = GrSamplerState::Filter::kNearest;
240             break;
241         case kLow_SkFilterQuality:
242             *filterMode = GrSamplerState::Filter::kBilerp;
243             break;
244         case kMedium_SkFilterQuality:
245             *filterMode = GrSamplerState::Filter::kMipMap;
246             break;
247         case kHigh_SkFilterQuality:
248             // When we use the bicubic filtering effect each sample is read from the texture using
249             // nearest neighbor sampling.
250             *filterMode = GrSamplerState::Filter::kNearest;
251             return true;
252     }
253     return false;
254 }
255