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 #include "GrMatrixConvolutionEffect.h"
8
9 #include "GrTexture.h"
10 #include "GrTextureProxy.h"
11 #include "glsl/GrGLSLFragmentProcessor.h"
12 #include "glsl/GrGLSLFragmentShaderBuilder.h"
13 #include "glsl/GrGLSLProgramDataManager.h"
14 #include "glsl/GrGLSLUniformHandler.h"
15 #include "../private/GrGLSL.h"
16
17 class GrGLMatrixConvolutionEffect : public GrGLSLFragmentProcessor {
18 public:
19 void emitCode(EmitArgs&) override;
20
21 static inline void GenKey(const GrProcessor&, const GrShaderCaps&, GrProcessorKeyBuilder*);
22
23 protected:
24 void onSetData(const GrGLSLProgramDataManager&, const GrFragmentProcessor&) override;
25
26 private:
27 typedef GrGLSLProgramDataManager::UniformHandle UniformHandle;
28
29 UniformHandle fKernelUni;
30 UniformHandle fImageIncrementUni;
31 UniformHandle fKernelOffsetUni;
32 UniformHandle fGainUni;
33 UniformHandle fBiasUni;
34 GrTextureDomain::GLDomain fDomain;
35
36 typedef GrGLSLFragmentProcessor INHERITED;
37 };
38
emitCode(EmitArgs & args)39 void GrGLMatrixConvolutionEffect::emitCode(EmitArgs& args) {
40 const GrMatrixConvolutionEffect& mce = args.fFp.cast<GrMatrixConvolutionEffect>();
41 const GrTextureDomain& domain = mce.domain();
42
43 int kWidth = mce.kernelSize().width();
44 int kHeight = mce.kernelSize().height();
45
46 int arrayCount = (kWidth * kHeight + 3) / 4;
47 SkASSERT(4 * arrayCount >= kWidth * kHeight);
48
49 GrGLSLUniformHandler* uniformHandler = args.fUniformHandler;
50 fImageIncrementUni = uniformHandler->addUniform(kFragment_GrShaderFlag, kHalf2_GrSLType,
51 "ImageIncrement");
52 fKernelUni = uniformHandler->addUniformArray(kFragment_GrShaderFlag, kHalf4_GrSLType,
53 "Kernel",
54 arrayCount);
55 fKernelOffsetUni = uniformHandler->addUniform(kFragment_GrShaderFlag, kHalf2_GrSLType,
56 "KernelOffset");
57 fGainUni = uniformHandler->addUniform(kFragment_GrShaderFlag, kHalf_GrSLType, "Gain");
58 fBiasUni = uniformHandler->addUniform(kFragment_GrShaderFlag, kHalf_GrSLType, "Bias");
59
60 const char* kernelOffset = uniformHandler->getUniformCStr(fKernelOffsetUni);
61 const char* imgInc = uniformHandler->getUniformCStr(fImageIncrementUni);
62 const char* kernel = uniformHandler->getUniformCStr(fKernelUni);
63 const char* gain = uniformHandler->getUniformCStr(fGainUni);
64 const char* bias = uniformHandler->getUniformCStr(fBiasUni);
65
66 GrGLSLFPFragmentBuilder* fragBuilder = args.fFragBuilder;
67 SkString coords2D = fragBuilder->ensureCoords2D(args.fTransformedCoords[0]);
68 fragBuilder->codeAppend("half4 sum = half4(0, 0, 0, 0);");
69 fragBuilder->codeAppendf("float2 coord = %s - %s * %s;", coords2D.c_str(), kernelOffset, imgInc);
70 fragBuilder->codeAppend("half4 c;");
71
72 const char* kVecSuffix[4] = { ".x", ".y", ".z", ".w" };
73 for (int y = 0; y < kHeight; y++) {
74 for (int x = 0; x < kWidth; x++) {
75 GrGLSLShaderBuilder::ShaderBlock block(fragBuilder);
76 int offset = y*kWidth + x;
77
78 fragBuilder->codeAppendf("half k = %s[%d]%s;", kernel, offset / 4,
79 kVecSuffix[offset & 0x3]);
80 SkString coord;
81 coord.printf("coord + half2(%d, %d) * %s", x, y, imgInc);
82 fDomain.sampleTexture(fragBuilder,
83 uniformHandler,
84 args.fShaderCaps,
85 domain,
86 "c",
87 coord,
88 args.fTexSamplers[0]);
89 if (!mce.convolveAlpha()) {
90 fragBuilder->codeAppend("c.rgb /= c.a;");
91 fragBuilder->codeAppend("c.rgb = clamp(c.rgb, 0.0, 1.0);");
92 }
93 fragBuilder->codeAppend("sum += c * k;");
94 }
95 }
96 if (mce.convolveAlpha()) {
97 fragBuilder->codeAppendf("%s = sum * %s + %s;", args.fOutputColor, gain, bias);
98 fragBuilder->codeAppendf("%s.a = clamp(%s.a, 0, 1);", args.fOutputColor, args.fOutputColor);
99 fragBuilder->codeAppendf("%s.rgb = clamp(%s.rgb, 0.0, %s.a);",
100 args.fOutputColor, args.fOutputColor, args.fOutputColor);
101 } else {
102 fDomain.sampleTexture(fragBuilder,
103 uniformHandler,
104 args.fShaderCaps,
105 domain,
106 "c",
107 coords2D,
108 args.fTexSamplers[0]);
109 fragBuilder->codeAppendf("%s.a = c.a;", args.fOutputColor);
110 fragBuilder->codeAppendf("%s.rgb = clamp(sum.rgb * %s + %s, 0, 1);", args.fOutputColor, gain, bias);
111 fragBuilder->codeAppendf("%s.rgb *= %s.a;", args.fOutputColor, args.fOutputColor);
112 }
113 fragBuilder->codeAppendf("%s *= %s;\n", args.fOutputColor, args.fInputColor);
114 }
115
GenKey(const GrProcessor & processor,const GrShaderCaps &,GrProcessorKeyBuilder * b)116 void GrGLMatrixConvolutionEffect::GenKey(const GrProcessor& processor,
117 const GrShaderCaps&, GrProcessorKeyBuilder* b) {
118 const GrMatrixConvolutionEffect& m = processor.cast<GrMatrixConvolutionEffect>();
119 SkASSERT(m.kernelSize().width() <= 0x7FFF && m.kernelSize().height() <= 0xFFFF);
120 uint32_t key = m.kernelSize().width() << 16 | m.kernelSize().height();
121 key |= m.convolveAlpha() ? 1U << 31 : 0;
122 b->add32(key);
123 b->add32(GrTextureDomain::GLDomain::DomainKey(m.domain()));
124 }
125
onSetData(const GrGLSLProgramDataManager & pdman,const GrFragmentProcessor & processor)126 void GrGLMatrixConvolutionEffect::onSetData(const GrGLSLProgramDataManager& pdman,
127 const GrFragmentProcessor& processor) {
128 const GrMatrixConvolutionEffect& conv = processor.cast<GrMatrixConvolutionEffect>();
129 GrSurfaceProxy* proxy = conv.textureSampler(0).proxy();
130 GrTexture* texture = proxy->priv().peekTexture();
131
132 float imageIncrement[2];
133 float ySign = proxy->origin() == kTopLeft_GrSurfaceOrigin ? 1.0f : -1.0f;
134 imageIncrement[0] = 1.0f / texture->width();
135 imageIncrement[1] = ySign / texture->height();
136 pdman.set2fv(fImageIncrementUni, 1, imageIncrement);
137 pdman.set2fv(fKernelOffsetUni, 1, conv.kernelOffset());
138 int kernelCount = conv.kernelSize().width() * conv.kernelSize().height();
139 int arrayCount = (kernelCount + 3) / 4;
140 SkASSERT(4 * arrayCount >= kernelCount);
141 pdman.set4fv(fKernelUni, arrayCount, conv.kernel());
142 pdman.set1f(fGainUni, conv.gain());
143 pdman.set1f(fBiasUni, conv.bias());
144 fDomain.setData(pdman, conv.domain(), proxy);
145 }
146
GrMatrixConvolutionEffect(sk_sp<GrTextureProxy> proxy,const SkIRect & bounds,const SkISize & kernelSize,const SkScalar * kernel,SkScalar gain,SkScalar bias,const SkIPoint & kernelOffset,GrTextureDomain::Mode tileMode,bool convolveAlpha)147 GrMatrixConvolutionEffect::GrMatrixConvolutionEffect(sk_sp<GrTextureProxy> proxy,
148 const SkIRect& bounds,
149 const SkISize& kernelSize,
150 const SkScalar* kernel,
151 SkScalar gain,
152 SkScalar bias,
153 const SkIPoint& kernelOffset,
154 GrTextureDomain::Mode tileMode,
155 bool convolveAlpha)
156 // To advertise either the modulation or opaqueness optimizations we'd have to examine the
157 // parameters.
158 : INHERITED(kGrMatrixConvolutionEffect_ClassID, kNone_OptimizationFlags)
159 , fCoordTransform(proxy.get())
160 , fDomain(proxy.get(), GrTextureDomain::MakeTexelDomainForMode(bounds, tileMode), tileMode)
161 , fTextureSampler(std::move(proxy))
162 , fKernelSize(kernelSize)
163 , fGain(SkScalarToFloat(gain))
164 , fBias(SkScalarToFloat(bias) / 255.0f)
165 , fConvolveAlpha(convolveAlpha) {
166 this->addCoordTransform(&fCoordTransform);
167 this->addTextureSampler(&fTextureSampler);
168 for (int i = 0; i < kernelSize.width() * kernelSize.height(); i++) {
169 fKernel[i] = SkScalarToFloat(kernel[i]);
170 }
171 fKernelOffset[0] = static_cast<float>(kernelOffset.x());
172 fKernelOffset[1] = static_cast<float>(kernelOffset.y());
173 }
174
GrMatrixConvolutionEffect(const GrMatrixConvolutionEffect & that)175 GrMatrixConvolutionEffect::GrMatrixConvolutionEffect(const GrMatrixConvolutionEffect& that)
176 : INHERITED(kGrMatrixConvolutionEffect_ClassID, kNone_OptimizationFlags)
177 , fCoordTransform(that.fCoordTransform)
178 , fDomain(that.fDomain)
179 , fTextureSampler(that.fTextureSampler)
180 , fKernelSize(that.fKernelSize)
181 , fGain(that.fGain)
182 , fBias(that.fBias)
183 , fConvolveAlpha(that.fConvolveAlpha) {
184 this->addCoordTransform(&fCoordTransform);
185 this->addTextureSampler(&fTextureSampler);
186 memcpy(fKernel, that.fKernel, sizeof(float) * fKernelSize.width() * fKernelSize.height());
187 memcpy(fKernelOffset, that.fKernelOffset, sizeof(fKernelOffset));
188 }
189
clone() const190 std::unique_ptr<GrFragmentProcessor> GrMatrixConvolutionEffect::clone() const {
191 return std::unique_ptr<GrFragmentProcessor>(new GrMatrixConvolutionEffect(*this));
192 }
193
onGetGLSLProcessorKey(const GrShaderCaps & caps,GrProcessorKeyBuilder * b) const194 void GrMatrixConvolutionEffect::onGetGLSLProcessorKey(const GrShaderCaps& caps,
195 GrProcessorKeyBuilder* b) const {
196 GrGLMatrixConvolutionEffect::GenKey(*this, caps, b);
197 }
198
onCreateGLSLInstance() const199 GrGLSLFragmentProcessor* GrMatrixConvolutionEffect::onCreateGLSLInstance() const {
200 return new GrGLMatrixConvolutionEffect;
201 }
202
onIsEqual(const GrFragmentProcessor & sBase) const203 bool GrMatrixConvolutionEffect::onIsEqual(const GrFragmentProcessor& sBase) const {
204 const GrMatrixConvolutionEffect& s = sBase.cast<GrMatrixConvolutionEffect>();
205 return fKernelSize == s.kernelSize() &&
206 !memcmp(fKernel, s.kernel(),
207 fKernelSize.width() * fKernelSize.height() * sizeof(float)) &&
208 fGain == s.gain() &&
209 fBias == s.bias() &&
210 !memcmp(fKernelOffset, s.kernelOffset(), sizeof(fKernelOffset)) &&
211 fConvolveAlpha == s.convolveAlpha() &&
212 fDomain == s.domain();
213 }
214
fill_in_2D_gaussian_kernel(float * kernel,int width,int height,SkScalar sigmaX,SkScalar sigmaY)215 static void fill_in_2D_gaussian_kernel(float* kernel, int width, int height,
216 SkScalar sigmaX, SkScalar sigmaY) {
217 SkASSERT(width * height <= MAX_KERNEL_SIZE);
218 const float sigmaXDenom = 1.0f / (2.0f * SkScalarToFloat(SkScalarSquare(sigmaX)));
219 const float sigmaYDenom = 1.0f / (2.0f * SkScalarToFloat(SkScalarSquare(sigmaY)));
220 const int xRadius = width / 2;
221 const int yRadius = height / 2;
222
223 float sum = 0.0f;
224 for (int x = 0; x < width; x++) {
225 float xTerm = static_cast<float>(x - xRadius);
226 xTerm = xTerm * xTerm * sigmaXDenom;
227 for (int y = 0; y < height; y++) {
228 float yTerm = static_cast<float>(y - yRadius);
229 float xyTerm = sk_float_exp(-(xTerm + yTerm * yTerm * sigmaYDenom));
230 // Note that the constant term (1/(sqrt(2*pi*sigma^2)) of the Gaussian
231 // is dropped here, since we renormalize the kernel below.
232 kernel[y * width + x] = xyTerm;
233 sum += xyTerm;
234 }
235 }
236 // Normalize the kernel
237 float scale = 1.0f / sum;
238 for (int i = 0; i < width * height; ++i) {
239 kernel[i] *= scale;
240 }
241 }
242
243 // Static function to create a 2D convolution
MakeGaussian(sk_sp<GrTextureProxy> proxy,const SkIRect & bounds,const SkISize & kernelSize,SkScalar gain,SkScalar bias,const SkIPoint & kernelOffset,GrTextureDomain::Mode tileMode,bool convolveAlpha,SkScalar sigmaX,SkScalar sigmaY)244 std::unique_ptr<GrFragmentProcessor> GrMatrixConvolutionEffect::MakeGaussian(
245 sk_sp<GrTextureProxy> proxy,
246 const SkIRect& bounds,
247 const SkISize& kernelSize,
248 SkScalar gain,
249 SkScalar bias,
250 const SkIPoint& kernelOffset,
251 GrTextureDomain::Mode tileMode,
252 bool convolveAlpha,
253 SkScalar sigmaX,
254 SkScalar sigmaY) {
255 float kernel[MAX_KERNEL_SIZE];
256
257 fill_in_2D_gaussian_kernel(kernel, kernelSize.width(), kernelSize.height(), sigmaX, sigmaY);
258
259 return std::unique_ptr<GrFragmentProcessor>(
260 new GrMatrixConvolutionEffect(std::move(proxy), bounds, kernelSize, kernel, gain, bias,
261 kernelOffset, tileMode, convolveAlpha));
262 }
263
264 GR_DEFINE_FRAGMENT_PROCESSOR_TEST(GrMatrixConvolutionEffect);
265
266 #if GR_TEST_UTILS
TestCreate(GrProcessorTestData * d)267 std::unique_ptr<GrFragmentProcessor> GrMatrixConvolutionEffect::TestCreate(GrProcessorTestData* d) {
268 int texIdx = d->fRandom->nextBool() ? GrProcessorUnitTest::kSkiaPMTextureIdx
269 : GrProcessorUnitTest::kAlphaTextureIdx;
270 sk_sp<GrTextureProxy> proxy = d->textureProxy(texIdx);
271
272 int width = d->fRandom->nextRangeU(1, MAX_KERNEL_SIZE);
273 int height = d->fRandom->nextRangeU(1, MAX_KERNEL_SIZE / width);
274 SkISize kernelSize = SkISize::Make(width, height);
275 std::unique_ptr<SkScalar[]> kernel(new SkScalar[width * height]);
276 for (int i = 0; i < width * height; i++) {
277 kernel.get()[i] = d->fRandom->nextSScalar1();
278 }
279 SkScalar gain = d->fRandom->nextSScalar1();
280 SkScalar bias = d->fRandom->nextSScalar1();
281 SkIPoint kernelOffset = SkIPoint::Make(d->fRandom->nextRangeU(0, kernelSize.width()),
282 d->fRandom->nextRangeU(0, kernelSize.height()));
283 SkIRect bounds = SkIRect::MakeXYWH(d->fRandom->nextRangeU(0, proxy->width()),
284 d->fRandom->nextRangeU(0, proxy->height()),
285 d->fRandom->nextRangeU(0, proxy->width()),
286 d->fRandom->nextRangeU(0, proxy->height()));
287 GrTextureDomain::Mode tileMode =
288 static_cast<GrTextureDomain::Mode>(d->fRandom->nextRangeU(0, 2));
289 bool convolveAlpha = d->fRandom->nextBool();
290 return GrMatrixConvolutionEffect::Make(std::move(proxy),
291 bounds,
292 kernelSize,
293 kernel.get(),
294 gain,
295 bias,
296 kernelOffset,
297 tileMode,
298 convolveAlpha);
299 }
300 #endif
301