C++11 override should now be supported by all of {bots,Chrome,Android,Mozilla}
[platform/upstream/libSkiaSharp.git] / src / gpu / effects / GrConvolutionEffect.cpp
1 /*
2  * Copyright 2012 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 "GrConvolutionEffect.h"
9 #include "gl/GrGLProcessor.h"
10 #include "gl/GrGLSL.h"
11 #include "gl/GrGLTexture.h"
12 #include "gl/builders/GrGLProgramBuilder.h"
13
14 // For brevity
15 typedef GrGLProgramDataManager::UniformHandle UniformHandle;
16
17 class GrGLConvolutionEffect : public GrGLFragmentProcessor {
18 public:
19     GrGLConvolutionEffect(const GrProcessor&);
20
21     virtual void emitCode(GrGLFPBuilder*,
22                           const GrFragmentProcessor&,
23                           const char* outputColor,
24                           const char* inputColor,
25                           const TransformedCoordsArray&,
26                           const TextureSamplerArray&) override;
27
28     void setData(const GrGLProgramDataManager& pdman, const GrProcessor&) override;
29
30     static inline void GenKey(const GrProcessor&, const GrGLCaps&, GrProcessorKeyBuilder*);
31
32 private:
33     int width() const { return Gr1DKernelEffect::WidthFromRadius(fRadius); }
34     bool useBounds() const { return fUseBounds; }
35     Gr1DKernelEffect::Direction direction() const { return fDirection; }
36
37     int                 fRadius;
38     bool                fUseBounds;
39     Gr1DKernelEffect::Direction    fDirection;
40     UniformHandle       fKernelUni;
41     UniformHandle       fImageIncrementUni;
42     UniformHandle       fBoundsUni;
43
44     typedef GrGLFragmentProcessor INHERITED;
45 };
46
47 GrGLConvolutionEffect::GrGLConvolutionEffect(const GrProcessor& processor) {
48     const GrConvolutionEffect& c = processor.cast<GrConvolutionEffect>();
49     fRadius = c.radius();
50     fUseBounds = c.useBounds();
51     fDirection = c.direction();
52 }
53
54 void GrGLConvolutionEffect::emitCode(GrGLFPBuilder* builder,
55                                      const GrFragmentProcessor&,
56                                      const char* outputColor,
57                                      const char* inputColor,
58                                      const TransformedCoordsArray& coords,
59                                      const TextureSamplerArray& samplers) {
60     fImageIncrementUni = builder->addUniform(GrGLProgramBuilder::kFragment_Visibility,
61                                              kVec2f_GrSLType, kDefault_GrSLPrecision,
62                                              "ImageIncrement");
63     if (this->useBounds()) {
64         fBoundsUni = builder->addUniform(GrGLProgramBuilder::kFragment_Visibility,
65                                          kVec2f_GrSLType, kDefault_GrSLPrecision,
66                                          "Bounds");
67     }
68     fKernelUni = builder->addUniformArray(GrGLProgramBuilder::kFragment_Visibility,
69                                           kFloat_GrSLType, kDefault_GrSLPrecision,
70                                           "Kernel", this->width());
71
72     GrGLFPFragmentBuilder* fsBuilder = builder->getFragmentShaderBuilder();
73     SkString coords2D = fsBuilder->ensureFSCoords2D(coords, 0);
74
75     fsBuilder->codeAppendf("\t\t%s = vec4(0, 0, 0, 0);\n", outputColor);
76
77     int width = this->width();
78     const GrGLShaderVar& kernel = builder->getUniformVariable(fKernelUni);
79     const char* imgInc = builder->getUniformCStr(fImageIncrementUni);
80
81     fsBuilder->codeAppendf("\t\tvec2 coord = %s - %d.0 * %s;\n", coords2D.c_str(), fRadius, imgInc);
82
83     // Manually unroll loop because some drivers don't; yields 20-30% speedup.
84     for (int i = 0; i < width; i++) {
85         SkString index;
86         SkString kernelIndex;
87         index.appendS32(i);
88         kernel.appendArrayAccess(index.c_str(), &kernelIndex);
89         fsBuilder->codeAppendf("\t\t%s += ", outputColor);
90         fsBuilder->appendTextureLookup(samplers[0], "coord");
91         if (this->useBounds()) {
92             const char* bounds = builder->getUniformCStr(fBoundsUni);
93             const char* component = this->direction() == Gr1DKernelEffect::kY_Direction ? "y" : "x";
94             fsBuilder->codeAppendf(" * float(coord.%s >= %s.x && coord.%s <= %s.y)",
95                 component, bounds, component, bounds);
96         }
97         fsBuilder->codeAppendf(" * %s;\n", kernelIndex.c_str());
98         fsBuilder->codeAppendf("\t\tcoord += %s;\n", imgInc);
99     }
100
101     SkString modulate;
102     GrGLSLMulVarBy4f(&modulate, outputColor, inputColor);
103     fsBuilder->codeAppend(modulate.c_str());
104 }
105
106 void GrGLConvolutionEffect::setData(const GrGLProgramDataManager& pdman,
107                                     const GrProcessor& processor) {
108     const GrConvolutionEffect& conv = processor.cast<GrConvolutionEffect>();
109     GrTexture& texture = *conv.texture(0);
110     // the code we generated was for a specific kernel radius
111     SkASSERT(conv.radius() == fRadius);
112     float imageIncrement[2] = { 0 };
113     float ySign = texture.origin() != kTopLeft_GrSurfaceOrigin ? 1.0f : -1.0f;
114     switch (conv.direction()) {
115         case Gr1DKernelEffect::kX_Direction:
116             imageIncrement[0] = 1.0f / texture.width();
117             break;
118         case Gr1DKernelEffect::kY_Direction:
119             imageIncrement[1] = ySign / texture.height();
120             break;
121         default:
122             SkFAIL("Unknown filter direction.");
123     }
124     pdman.set2fv(fImageIncrementUni, 1, imageIncrement);
125     if (conv.useBounds()) {
126         const float* bounds = conv.bounds();
127         if (Gr1DKernelEffect::kY_Direction == conv.direction() &&
128             texture.origin() != kTopLeft_GrSurfaceOrigin) {
129             pdman.set2f(fBoundsUni, 1.0f - bounds[1], 1.0f - bounds[0]);
130         } else {
131             pdman.set2f(fBoundsUni, bounds[0], bounds[1]);
132         }
133     }
134     pdman.set1fv(fKernelUni, this->width(), conv.kernel());
135 }
136
137 void GrGLConvolutionEffect::GenKey(const GrProcessor& processor, const GrGLCaps&,
138                                    GrProcessorKeyBuilder* b) {
139     const GrConvolutionEffect& conv = processor.cast<GrConvolutionEffect>();
140     uint32_t key = conv.radius();
141     key <<= 2;
142     if (conv.useBounds()) {
143         key |= 0x2;
144         key |= GrConvolutionEffect::kY_Direction == conv.direction() ? 0x1 : 0x0;
145     }
146     b->add32(key);
147 }
148
149 ///////////////////////////////////////////////////////////////////////////////
150
151 GrConvolutionEffect::GrConvolutionEffect(GrTexture* texture,
152                                          Direction direction,
153                                          int radius,
154                                          const float* kernel,
155                                          bool useBounds,
156                                          float bounds[2])
157     : Gr1DKernelEffect(texture, direction, radius), fUseBounds(useBounds) {
158     this->initClassID<GrConvolutionEffect>();
159     SkASSERT(radius <= kMaxKernelRadius);
160     SkASSERT(kernel);
161     int width = this->width();
162     for (int i = 0; i < width; i++) {
163         fKernel[i] = kernel[i];
164     }
165     memcpy(fBounds, bounds, sizeof(fBounds));
166 }
167
168 GrConvolutionEffect::GrConvolutionEffect(GrTexture* texture,
169                                          Direction direction,
170                                          int radius,
171                                          float gaussianSigma,
172                                          bool useBounds,
173                                          float bounds[2])
174     : Gr1DKernelEffect(texture, direction, radius), fUseBounds(useBounds) {
175     this->initClassID<GrConvolutionEffect>();
176     SkASSERT(radius <= kMaxKernelRadius);
177     int width = this->width();
178
179     float sum = 0.0f;
180     float denom = 1.0f / (2.0f * gaussianSigma * gaussianSigma);
181     for (int i = 0; i < width; ++i) {
182         float x = static_cast<float>(i - this->radius());
183         // Note that the constant term (1/(sqrt(2*pi*sigma^2)) of the Gaussian
184         // is dropped here, since we renormalize the kernel below.
185         fKernel[i] = sk_float_exp(- x * x * denom);
186         sum += fKernel[i];
187     }
188     // Normalize the kernel
189     float scale = 1.0f / sum;
190     for (int i = 0; i < width; ++i) {
191         fKernel[i] *= scale;
192     }
193     memcpy(fBounds, bounds, sizeof(fBounds));
194 }
195
196 GrConvolutionEffect::~GrConvolutionEffect() {
197 }
198
199 void GrConvolutionEffect::getGLProcessorKey(const GrGLCaps& caps,
200                                         GrProcessorKeyBuilder* b) const {
201     GrGLConvolutionEffect::GenKey(*this, caps, b);
202 }
203
204 GrGLFragmentProcessor* GrConvolutionEffect::createGLInstance() const  {
205     return SkNEW_ARGS(GrGLConvolutionEffect, (*this));
206 }
207
208 bool GrConvolutionEffect::onIsEqual(const GrFragmentProcessor& sBase) const {
209     const GrConvolutionEffect& s = sBase.cast<GrConvolutionEffect>();
210     return (this->radius() == s.radius() &&
211             this->direction() == s.direction() &&
212             this->useBounds() == s.useBounds() &&
213             0 == memcmp(fBounds, s.fBounds, sizeof(fBounds)) &&
214             0 == memcmp(fKernel, s.fKernel, this->width() * sizeof(float)));
215 }
216
217 ///////////////////////////////////////////////////////////////////////////////
218
219 GR_DEFINE_FRAGMENT_PROCESSOR_TEST(GrConvolutionEffect);
220
221 GrFragmentProcessor* GrConvolutionEffect::TestCreate(SkRandom* random,
222                                                      GrContext*,
223                                                      const GrDrawTargetCaps&,
224                                                      GrTexture* textures[]) {
225     int texIdx = random->nextBool() ? GrProcessorUnitTest::kSkiaPMTextureIdx :
226                                       GrProcessorUnitTest::kAlphaTextureIdx;
227     Direction dir = random->nextBool() ? kX_Direction : kY_Direction;
228     int radius = random->nextRangeU(1, kMaxKernelRadius);
229     float kernel[kMaxKernelWidth];
230     for (size_t i = 0; i < SK_ARRAY_COUNT(kernel); ++i) {
231         kernel[i] = random->nextSScalar1();
232     }
233     float bounds[2];
234     for (size_t i = 0; i < SK_ARRAY_COUNT(bounds); ++i) {
235         bounds[i] = random->nextF();
236     }
237
238     bool useBounds = random->nextBool();
239     return GrConvolutionEffect::Create(textures[texIdx],
240                                        dir,
241                                        radius,
242                                        kernel,
243                                        useBounds,
244                                        bounds);
245 }