Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / third_party / skia / src / effects / SkMatrixConvolutionImageFilter.cpp
1 /*
2  * Copyright 2012 The Android Open Source Project
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 "SkMatrixConvolutionImageFilter.h"
9 #include "SkBitmap.h"
10 #include "SkColorPriv.h"
11 #include "SkReadBuffer.h"
12 #include "SkWriteBuffer.h"
13 #include "SkRect.h"
14 #include "SkUnPreMultiply.h"
15
16 #if SK_SUPPORT_GPU
17 #include "gl/GrGLEffect.h"
18 #include "effects/GrSingleTextureEffect.h"
19 #include "GrTBackendEffectFactory.h"
20 #include "GrTexture.h"
21 #include "SkMatrix.h"
22 #endif
23
24 static bool tile_mode_is_valid(SkMatrixConvolutionImageFilter::TileMode tileMode) {
25     switch (tileMode) {
26     case SkMatrixConvolutionImageFilter::kClamp_TileMode:
27     case SkMatrixConvolutionImageFilter::kRepeat_TileMode:
28     case SkMatrixConvolutionImageFilter::kClampToBlack_TileMode:
29         return true;
30     default:
31         break;
32     }
33     return false;
34 }
35
36 SkMatrixConvolutionImageFilter::SkMatrixConvolutionImageFilter(
37     const SkISize& kernelSize,
38     const SkScalar* kernel,
39     SkScalar gain,
40     SkScalar bias,
41     const SkIPoint& kernelOffset,
42     TileMode tileMode,
43     bool convolveAlpha,
44     SkImageFilter* input,
45     const CropRect* cropRect)
46   : INHERITED(input, cropRect),
47     fKernelSize(kernelSize),
48     fGain(gain),
49     fBias(bias),
50     fKernelOffset(kernelOffset),
51     fTileMode(tileMode),
52     fConvolveAlpha(convolveAlpha) {
53     uint32_t size = fKernelSize.fWidth * fKernelSize.fHeight;
54     fKernel = SkNEW_ARRAY(SkScalar, size);
55     memcpy(fKernel, kernel, size * sizeof(SkScalar));
56     SkASSERT(kernelSize.fWidth >= 1 && kernelSize.fHeight >= 1);
57     SkASSERT(kernelOffset.fX >= 0 && kernelOffset.fX < kernelSize.fWidth);
58     SkASSERT(kernelOffset.fY >= 0 && kernelOffset.fY < kernelSize.fHeight);
59 }
60
61 SkMatrixConvolutionImageFilter::SkMatrixConvolutionImageFilter(SkReadBuffer& buffer)
62     : INHERITED(1, buffer) {
63     // We need to be able to read at most SK_MaxS32 bytes, so divide that
64     // by the size of a scalar to know how many scalars we can read.
65     static const int32_t kMaxSize = SK_MaxS32 / sizeof(SkScalar);
66     fKernelSize.fWidth = buffer.readInt();
67     fKernelSize.fHeight = buffer.readInt();
68     if ((fKernelSize.fWidth >= 1) && (fKernelSize.fHeight >= 1) &&
69         // Make sure size won't be larger than a signed int,
70         // which would still be extremely large for a kernel,
71         // but we don't impose a hard limit for kernel size
72         (kMaxSize / fKernelSize.fWidth >= fKernelSize.fHeight)) {
73         size_t size = fKernelSize.fWidth * fKernelSize.fHeight;
74         fKernel = SkNEW_ARRAY(SkScalar, size);
75         SkDEBUGCODE(bool success =) buffer.readScalarArray(fKernel, size);
76         SkASSERT(success);
77     } else {
78         fKernel = 0;
79     }
80     fGain = buffer.readScalar();
81     fBias = buffer.readScalar();
82     fKernelOffset.fX = buffer.readInt();
83     fKernelOffset.fY = buffer.readInt();
84     fTileMode = (TileMode) buffer.readInt();
85     fConvolveAlpha = buffer.readBool();
86     buffer.validate((fKernel != 0) &&
87                     SkScalarIsFinite(fGain) &&
88                     SkScalarIsFinite(fBias) &&
89                     tile_mode_is_valid(fTileMode));
90 }
91
92 void SkMatrixConvolutionImageFilter::flatten(SkWriteBuffer& buffer) const {
93     this->INHERITED::flatten(buffer);
94     buffer.writeInt(fKernelSize.fWidth);
95     buffer.writeInt(fKernelSize.fHeight);
96     buffer.writeScalarArray(fKernel, fKernelSize.fWidth * fKernelSize.fHeight);
97     buffer.writeScalar(fGain);
98     buffer.writeScalar(fBias);
99     buffer.writeInt(fKernelOffset.fX);
100     buffer.writeInt(fKernelOffset.fY);
101     buffer.writeInt((int) fTileMode);
102     buffer.writeBool(fConvolveAlpha);
103 }
104
105 SkMatrixConvolutionImageFilter::~SkMatrixConvolutionImageFilter() {
106     delete[] fKernel;
107 }
108
109 class UncheckedPixelFetcher {
110 public:
111     static inline SkPMColor fetch(const SkBitmap& src, int x, int y, const SkIRect& bounds) {
112         return *src.getAddr32(x, y);
113     }
114 };
115
116 class ClampPixelFetcher {
117 public:
118     static inline SkPMColor fetch(const SkBitmap& src, int x, int y, const SkIRect& bounds) {
119         x = SkPin32(x, bounds.fLeft, bounds.fRight - 1);
120         y = SkPin32(y, bounds.fTop, bounds.fBottom - 1);
121         return *src.getAddr32(x, y);
122     }
123 };
124
125 class RepeatPixelFetcher {
126 public:
127     static inline SkPMColor fetch(const SkBitmap& src, int x, int y, const SkIRect& bounds) {
128         x = (x - bounds.left()) % bounds.width() + bounds.left();
129         y = (y - bounds.top()) % bounds.height() + bounds.top();
130         if (x < bounds.left()) {
131             x += bounds.width();
132         }
133         if (y < bounds.top()) {
134             y += bounds.height();
135         }
136         return *src.getAddr32(x, y);
137     }
138 };
139
140 class ClampToBlackPixelFetcher {
141 public:
142     static inline SkPMColor fetch(const SkBitmap& src, int x, int y, const SkIRect& bounds) {
143         if (x < bounds.fLeft || x >= bounds.fRight || y < bounds.fTop || y >= bounds.fBottom) {
144             return 0;
145         } else {
146             return *src.getAddr32(x, y);
147         }
148     }
149 };
150
151 template<class PixelFetcher, bool convolveAlpha>
152 void SkMatrixConvolutionImageFilter::filterPixels(const SkBitmap& src,
153                                                   SkBitmap* result,
154                                                   const SkIRect& r,
155                                                   const SkIRect& bounds) const {
156     SkIRect rect(r);
157     if (!rect.intersect(bounds)) {
158         return;
159     }
160     for (int y = rect.fTop; y < rect.fBottom; ++y) {
161         SkPMColor* dptr = result->getAddr32(rect.fLeft - bounds.fLeft, y - bounds.fTop);
162         for (int x = rect.fLeft; x < rect.fRight; ++x) {
163             SkScalar sumA = 0, sumR = 0, sumG = 0, sumB = 0;
164             for (int cy = 0; cy < fKernelSize.fHeight; cy++) {
165                 for (int cx = 0; cx < fKernelSize.fWidth; cx++) {
166                     SkPMColor s = PixelFetcher::fetch(src,
167                                                       x + cx - fKernelOffset.fX,
168                                                       y + cy - fKernelOffset.fY,
169                                                       bounds);
170                     SkScalar k = fKernel[cy * fKernelSize.fWidth + cx];
171                     if (convolveAlpha) {
172                         sumA += SkScalarMul(SkIntToScalar(SkGetPackedA32(s)), k);
173                     }
174                     sumR += SkScalarMul(SkIntToScalar(SkGetPackedR32(s)), k);
175                     sumG += SkScalarMul(SkIntToScalar(SkGetPackedG32(s)), k);
176                     sumB += SkScalarMul(SkIntToScalar(SkGetPackedB32(s)), k);
177                 }
178             }
179             int a = convolveAlpha
180                   ? SkClampMax(SkScalarFloorToInt(SkScalarMul(sumA, fGain) + fBias), 255)
181                   : 255;
182             int r = SkClampMax(SkScalarFloorToInt(SkScalarMul(sumR, fGain) + fBias), a);
183             int g = SkClampMax(SkScalarFloorToInt(SkScalarMul(sumG, fGain) + fBias), a);
184             int b = SkClampMax(SkScalarFloorToInt(SkScalarMul(sumB, fGain) + fBias), a);
185             if (!convolveAlpha) {
186                 a = SkGetPackedA32(PixelFetcher::fetch(src, x, y, bounds));
187                 *dptr++ = SkPreMultiplyARGB(a, r, g, b);
188             } else {
189                 *dptr++ = SkPackARGB32(a, r, g, b);
190             }
191         }
192     }
193 }
194
195 template<class PixelFetcher>
196 void SkMatrixConvolutionImageFilter::filterPixels(const SkBitmap& src,
197                                                   SkBitmap* result,
198                                                   const SkIRect& rect,
199                                                   const SkIRect& bounds) const {
200     if (fConvolveAlpha) {
201         filterPixels<PixelFetcher, true>(src, result, rect, bounds);
202     } else {
203         filterPixels<PixelFetcher, false>(src, result, rect, bounds);
204     }
205 }
206
207 void SkMatrixConvolutionImageFilter::filterInteriorPixels(const SkBitmap& src,
208                                                           SkBitmap* result,
209                                                           const SkIRect& rect,
210                                                           const SkIRect& bounds) const {
211     filterPixels<UncheckedPixelFetcher>(src, result, rect, bounds);
212 }
213
214 void SkMatrixConvolutionImageFilter::filterBorderPixels(const SkBitmap& src,
215                                                         SkBitmap* result,
216                                                         const SkIRect& rect,
217                                                         const SkIRect& bounds) const {
218     switch (fTileMode) {
219         case kClamp_TileMode:
220             filterPixels<ClampPixelFetcher>(src, result, rect, bounds);
221             break;
222         case kRepeat_TileMode:
223             filterPixels<RepeatPixelFetcher>(src, result, rect, bounds);
224             break;
225         case kClampToBlack_TileMode:
226             filterPixels<ClampToBlackPixelFetcher>(src, result, rect, bounds);
227             break;
228     }
229 }
230
231 // FIXME:  This should be refactored to SkImageFilterUtils for
232 // use by other filters.  For now, we assume the input is always
233 // premultiplied and unpremultiply it
234 static SkBitmap unpremultiplyBitmap(const SkBitmap& src)
235 {
236     SkAutoLockPixels alp(src);
237     if (!src.getPixels()) {
238         return SkBitmap();
239     }
240     SkBitmap result;
241     result.setConfig(src.config(), src.width(), src.height());
242     result.allocPixels();
243     if (!result.getPixels()) {
244         return SkBitmap();
245     }
246     for (int y = 0; y < src.height(); ++y) {
247         const uint32_t* srcRow = src.getAddr32(0, y);
248         uint32_t* dstRow = result.getAddr32(0, y);
249         for (int x = 0; x < src.width(); ++x) {
250             dstRow[x] = SkUnPreMultiply::PMColorToColor(srcRow[x]);
251         }
252     }
253     return result;
254 }
255
256 bool SkMatrixConvolutionImageFilter::onFilterImage(Proxy* proxy,
257                                                    const SkBitmap& source,
258                                                    const Context& ctx,
259                                                    SkBitmap* result,
260                                                    SkIPoint* offset) const {
261     SkBitmap src = source;
262     SkIPoint srcOffset = SkIPoint::Make(0, 0);
263     if (getInput(0) && !getInput(0)->filterImage(proxy, source, ctx, &src, &srcOffset)) {
264         return false;
265     }
266
267     if (src.colorType() != kN32_SkColorType) {
268         return false;
269     }
270
271     SkIRect bounds;
272     if (!this->applyCropRect(ctx, proxy, src, &srcOffset, &bounds, &src)) {
273         return false;
274     }
275
276     if (!fConvolveAlpha && !src.isOpaque()) {
277         src = unpremultiplyBitmap(src);
278     }
279
280     SkAutoLockPixels alp(src);
281     if (!src.getPixels()) {
282         return false;
283     }
284
285     result->setConfig(src.config(), bounds.width(), bounds.height());
286     result->allocPixels();
287     if (!result->getPixels()) {
288         return false;
289     }
290
291     offset->fX = bounds.fLeft;
292     offset->fY = bounds.fTop;
293     bounds.offset(-srcOffset);
294     SkIRect interior = SkIRect::MakeXYWH(bounds.left() + fKernelOffset.fX,
295                                          bounds.top() + fKernelOffset.fY,
296                                          bounds.width() - fKernelSize.fWidth + 1,
297                                          bounds.height() - fKernelSize.fHeight + 1);
298     SkIRect top = SkIRect::MakeLTRB(bounds.left(), bounds.top(), bounds.right(), interior.top());
299     SkIRect bottom = SkIRect::MakeLTRB(bounds.left(), interior.bottom(),
300                                        bounds.right(), bounds.bottom());
301     SkIRect left = SkIRect::MakeLTRB(bounds.left(), interior.top(),
302                                      interior.left(), interior.bottom());
303     SkIRect right = SkIRect::MakeLTRB(interior.right(), interior.top(),
304                                       bounds.right(), interior.bottom());
305     filterBorderPixels(src, result, top, bounds);
306     filterBorderPixels(src, result, left, bounds);
307     filterInteriorPixels(src, result, interior, bounds);
308     filterBorderPixels(src, result, right, bounds);
309     filterBorderPixels(src, result, bottom, bounds);
310     return true;
311 }
312
313 bool SkMatrixConvolutionImageFilter::onFilterBounds(const SkIRect& src, const SkMatrix& ctm,
314                                                     SkIRect* dst) const {
315     SkIRect bounds = src;
316     bounds.fRight += fKernelSize.width() - 1;
317     bounds.fBottom += fKernelSize.height() - 1;
318     bounds.offset(-fKernelOffset);
319     if (getInput(0) && !getInput(0)->filterBounds(bounds, ctm, &bounds)) {
320         return false;
321     }
322     *dst = bounds;
323     return true;
324 }
325
326 #if SK_SUPPORT_GPU
327
328 ///////////////////////////////////////////////////////////////////////////////
329
330 class GrGLMatrixConvolutionEffect;
331
332 class GrMatrixConvolutionEffect : public GrSingleTextureEffect {
333 public:
334     typedef SkMatrixConvolutionImageFilter::TileMode TileMode;
335     static GrEffectRef* Create(GrTexture* texture,
336                                const SkIRect& bounds,
337                                const SkISize& kernelSize,
338                                const SkScalar* kernel,
339                                SkScalar gain,
340                                SkScalar bias,
341                                const SkIPoint& kernelOffset,
342                                TileMode tileMode,
343                                bool convolveAlpha) {
344         AutoEffectUnref effect(SkNEW_ARGS(GrMatrixConvolutionEffect, (texture,
345                                                                       bounds,
346                                                                       kernelSize,
347                                                                       kernel,
348                                                                       gain,
349                                                                       bias,
350                                                                       kernelOffset,
351                                                                       tileMode,
352                                                                       convolveAlpha)));
353         return CreateEffectRef(effect);
354     }
355     virtual ~GrMatrixConvolutionEffect();
356
357     virtual void getConstantColorComponents(GrColor* color,
358                                             uint32_t* validFlags) const SK_OVERRIDE {
359         // TODO: Try to do better?
360         *validFlags = 0;
361     }
362
363     static const char* Name() { return "MatrixConvolution"; }
364     const SkIRect& bounds() const { return fBounds; }
365     const SkISize& kernelSize() const { return fKernelSize; }
366     const float* kernelOffset() const { return fKernelOffset; }
367     const float* kernel() const { return fKernel; }
368     float gain() const { return fGain; }
369     float bias() const { return fBias; }
370     TileMode tileMode() const { return fTileMode; }
371     bool convolveAlpha() const { return fConvolveAlpha; }
372
373     typedef GrGLMatrixConvolutionEffect GLEffect;
374
375     virtual const GrBackendEffectFactory& getFactory() const SK_OVERRIDE;
376
377 private:
378     GrMatrixConvolutionEffect(GrTexture*,
379                               const SkIRect& bounds,
380                               const SkISize& kernelSize,
381                               const SkScalar* kernel,
382                               SkScalar gain,
383                               SkScalar bias,
384                               const SkIPoint& kernelOffset,
385                               TileMode tileMode,
386                               bool convolveAlpha);
387
388     virtual bool onIsEqual(const GrEffect&) const SK_OVERRIDE;
389
390     SkIRect  fBounds;
391     SkISize  fKernelSize;
392     float   *fKernel;
393     float    fGain;
394     float    fBias;
395     float    fKernelOffset[2];
396     TileMode fTileMode;
397     bool     fConvolveAlpha;
398
399     GR_DECLARE_EFFECT_TEST;
400
401     typedef GrSingleTextureEffect INHERITED;
402 };
403
404 class GrGLMatrixConvolutionEffect : public GrGLEffect {
405 public:
406     GrGLMatrixConvolutionEffect(const GrBackendEffectFactory& factory,
407                                 const GrDrawEffect& effect);
408     virtual void emitCode(GrGLShaderBuilder*,
409                           const GrDrawEffect&,
410                           EffectKey,
411                           const char* outputColor,
412                           const char* inputColor,
413                           const TransformedCoordsArray&,
414                           const TextureSamplerArray&) SK_OVERRIDE;
415
416     static inline EffectKey GenKey(const GrDrawEffect&, const GrGLCaps&);
417
418     virtual void setData(const GrGLUniformManager&, const GrDrawEffect&) SK_OVERRIDE;
419
420 private:
421     typedef GrGLUniformManager::UniformHandle        UniformHandle;
422     typedef SkMatrixConvolutionImageFilter::TileMode TileMode;
423     SkISize             fKernelSize;
424     TileMode            fTileMode;
425     bool                fConvolveAlpha;
426
427     UniformHandle       fBoundsUni;
428     UniformHandle       fKernelUni;
429     UniformHandle       fImageIncrementUni;
430     UniformHandle       fKernelOffsetUni;
431     UniformHandle       fGainUni;
432     UniformHandle       fBiasUni;
433
434     typedef GrGLEffect INHERITED;
435 };
436
437 GrGLMatrixConvolutionEffect::GrGLMatrixConvolutionEffect(const GrBackendEffectFactory& factory,
438                                                          const GrDrawEffect& drawEffect)
439     : INHERITED(factory) {
440     const GrMatrixConvolutionEffect& m = drawEffect.castEffect<GrMatrixConvolutionEffect>();
441     fKernelSize = m.kernelSize();
442     fTileMode = m.tileMode();
443     fConvolveAlpha = m.convolveAlpha();
444 }
445
446 static void appendTextureLookup(GrGLShaderBuilder* builder,
447                                 const GrGLShaderBuilder::TextureSampler& sampler,
448                                 const char* coord,
449                                 const char* bounds,
450                                 SkMatrixConvolutionImageFilter::TileMode tileMode) {
451     SkString clampedCoord;
452     switch (tileMode) {
453         case SkMatrixConvolutionImageFilter::kClamp_TileMode:
454             clampedCoord.printf("clamp(%s, %s.xy, %s.zw)", coord, bounds, bounds);
455             coord = clampedCoord.c_str();
456             break;
457         case SkMatrixConvolutionImageFilter::kRepeat_TileMode:
458             clampedCoord.printf("mod(%s - %s.xy, %s.zw - %s.xy) + %s.xy", coord, bounds, bounds, bounds, bounds);
459             coord = clampedCoord.c_str();
460             break;
461         case SkMatrixConvolutionImageFilter::kClampToBlack_TileMode:
462             builder->fsCodeAppendf("clamp(%s, %s.xy, %s.zw) != %s ? vec4(0, 0, 0, 0) : ", coord, bounds, bounds, coord);
463             break;
464     }
465     builder->fsAppendTextureLookup(sampler, coord);
466 }
467
468 void GrGLMatrixConvolutionEffect::emitCode(GrGLShaderBuilder* builder,
469                                            const GrDrawEffect&,
470                                            EffectKey key,
471                                            const char* outputColor,
472                                            const char* inputColor,
473                                            const TransformedCoordsArray& coords,
474                                            const TextureSamplerArray& samplers) {
475     sk_ignore_unused_variable(inputColor);
476     SkString coords2D = builder->ensureFSCoords2D(coords, 0);
477     fBoundsUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
478                                      kVec4f_GrSLType, "Bounds");
479     fImageIncrementUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
480                                              kVec2f_GrSLType, "ImageIncrement");
481     fKernelUni = builder->addUniformArray(GrGLShaderBuilder::kFragment_Visibility,
482                                              kFloat_GrSLType,
483                                              "Kernel",
484                                              fKernelSize.width() * fKernelSize.height());
485     fKernelOffsetUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
486                                              kVec2f_GrSLType, "KernelOffset");
487     fGainUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
488                                    kFloat_GrSLType, "Gain");
489     fBiasUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
490                                    kFloat_GrSLType, "Bias");
491
492     const char* bounds = builder->getUniformCStr(fBoundsUni);
493     const char* kernelOffset = builder->getUniformCStr(fKernelOffsetUni);
494     const char* imgInc = builder->getUniformCStr(fImageIncrementUni);
495     const char* kernel = builder->getUniformCStr(fKernelUni);
496     const char* gain = builder->getUniformCStr(fGainUni);
497     const char* bias = builder->getUniformCStr(fBiasUni);
498     int kWidth = fKernelSize.width();
499     int kHeight = fKernelSize.height();
500
501     builder->fsCodeAppend("\t\tvec4 sum = vec4(0, 0, 0, 0);\n");
502     builder->fsCodeAppendf("\t\tvec2 coord = %s - %s * %s;\n", coords2D.c_str(), kernelOffset, imgInc);
503     builder->fsCodeAppendf("\t\tfor (int y = 0; y < %d; y++) {\n", kHeight);
504     builder->fsCodeAppendf("\t\t\tfor (int x = 0; x < %d; x++) {\n", kWidth);
505     builder->fsCodeAppendf("\t\t\t\tfloat k = %s[y * %d + x];\n", kernel, kWidth);
506     builder->fsCodeAppendf("\t\t\t\tvec2 coord2 = coord + vec2(x, y) * %s;\n", imgInc);
507     builder->fsCodeAppend("\t\t\t\tvec4 c = ");
508     appendTextureLookup(builder, samplers[0], "coord2", bounds, fTileMode);
509     builder->fsCodeAppend(";\n");
510     if (!fConvolveAlpha) {
511         builder->fsCodeAppend("\t\t\t\tc.rgb /= c.a;\n");
512     }
513     builder->fsCodeAppend("\t\t\t\tsum += c * k;\n");
514     builder->fsCodeAppend("\t\t\t}\n");
515     builder->fsCodeAppend("\t\t}\n");
516     if (fConvolveAlpha) {
517         builder->fsCodeAppendf("\t\t%s = sum * %s + %s;\n", outputColor, gain, bias);
518         builder->fsCodeAppendf("\t\t%s.rgb = clamp(%s.rgb, 0.0, %s.a);\n",
519             outputColor, outputColor, outputColor);
520     } else {
521         builder->fsCodeAppend("\t\tvec4 c = ");
522         appendTextureLookup(builder, samplers[0], coords2D.c_str(), bounds, fTileMode);
523         builder->fsCodeAppend(";\n");
524         builder->fsCodeAppendf("\t\t%s.a = c.a;\n", outputColor);
525         builder->fsCodeAppendf("\t\t%s.rgb = sum.rgb * %s + %s;\n", outputColor, gain, bias);
526         builder->fsCodeAppendf("\t\t%s.rgb *= %s.a;\n", outputColor, outputColor);
527     }
528 }
529
530 namespace {
531
532 int encodeXY(int x, int y) {
533     SkASSERT(x >= 1 && y >= 1 && x * y <= 32);
534     if (y < x)
535         return 0x40 | encodeXY(y, x);
536     else
537         return (0x40 >> x) | (y - x);
538 }
539
540 };
541
542 GrGLEffect::EffectKey GrGLMatrixConvolutionEffect::GenKey(const GrDrawEffect& drawEffect,
543                                                           const GrGLCaps&) {
544     const GrMatrixConvolutionEffect& m = drawEffect.castEffect<GrMatrixConvolutionEffect>();
545     EffectKey key = encodeXY(m.kernelSize().width(), m.kernelSize().height());
546     key |= m.tileMode() << 7;
547     key |= m.convolveAlpha() ? 1 << 9 : 0;
548     return key;
549 }
550
551 void GrGLMatrixConvolutionEffect::setData(const GrGLUniformManager& uman,
552                                           const GrDrawEffect& drawEffect) {
553     const GrMatrixConvolutionEffect& conv = drawEffect.castEffect<GrMatrixConvolutionEffect>();
554     GrTexture& texture = *conv.texture(0);
555     // the code we generated was for a specific kernel size
556     SkASSERT(conv.kernelSize() == fKernelSize);
557     SkASSERT(conv.tileMode() == fTileMode);
558     float imageIncrement[2];
559     float ySign = texture.origin() == kTopLeft_GrSurfaceOrigin ? 1.0f : -1.0f;
560     imageIncrement[0] = 1.0f / texture.width();
561     imageIncrement[1] = ySign / texture.height();
562     uman.set2fv(fImageIncrementUni, 1, imageIncrement);
563     uman.set2fv(fKernelOffsetUni, 1, conv.kernelOffset());
564     uman.set1fv(fKernelUni, fKernelSize.width() * fKernelSize.height(), conv.kernel());
565     uman.set1f(fGainUni, conv.gain());
566     uman.set1f(fBiasUni, conv.bias());
567     const SkIRect& bounds = conv.bounds();
568     float left = (float) bounds.left() / texture.width();
569     float top = (float) bounds.top() / texture.height();
570     float right = (float) bounds.right() / texture.width();
571     float bottom = (float) bounds.bottom() / texture.height();
572     if (texture.origin() == kBottomLeft_GrSurfaceOrigin) {
573         uman.set4f(fBoundsUni, left, 1.0f - bottom, right, 1.0f - top);
574     } else {
575         uman.set4f(fBoundsUni, left, top, right, bottom);
576     }
577 }
578
579 GrMatrixConvolutionEffect::GrMatrixConvolutionEffect(GrTexture* texture,
580                                                      const SkIRect& bounds,
581                                                      const SkISize& kernelSize,
582                                                      const SkScalar* kernel,
583                                                      SkScalar gain,
584                                                      SkScalar bias,
585                                                      const SkIPoint& kernelOffset,
586                                                      TileMode tileMode,
587                                                      bool convolveAlpha)
588   : INHERITED(texture, MakeDivByTextureWHMatrix(texture)),
589     fBounds(bounds),
590     fKernelSize(kernelSize),
591     fGain(SkScalarToFloat(gain)),
592     fBias(SkScalarToFloat(bias) / 255.0f),
593     fTileMode(tileMode),
594     fConvolveAlpha(convolveAlpha) {
595     fKernel = new float[kernelSize.width() * kernelSize.height()];
596     for (int i = 0; i < kernelSize.width() * kernelSize.height(); i++) {
597         fKernel[i] = SkScalarToFloat(kernel[i]);
598     }
599     fKernelOffset[0] = static_cast<float>(kernelOffset.x());
600     fKernelOffset[1] = static_cast<float>(kernelOffset.y());
601     this->setWillNotUseInputColor();
602 }
603
604 GrMatrixConvolutionEffect::~GrMatrixConvolutionEffect() {
605     delete[] fKernel;
606 }
607
608 const GrBackendEffectFactory& GrMatrixConvolutionEffect::getFactory() const {
609     return GrTBackendEffectFactory<GrMatrixConvolutionEffect>::getInstance();
610 }
611
612 bool GrMatrixConvolutionEffect::onIsEqual(const GrEffect& sBase) const {
613     const GrMatrixConvolutionEffect& s = CastEffect<GrMatrixConvolutionEffect>(sBase);
614     return this->texture(0) == s.texture(0) &&
615            fKernelSize == s.kernelSize() &&
616            !memcmp(fKernel, s.kernel(),
617                    fKernelSize.width() * fKernelSize.height() * sizeof(float)) &&
618            fGain == s.gain() &&
619            fBias == s.bias() &&
620            fKernelOffset == s.kernelOffset() &&
621            fTileMode == s.tileMode() &&
622            fConvolveAlpha == s.convolveAlpha();
623 }
624
625 GR_DEFINE_EFFECT_TEST(GrMatrixConvolutionEffect);
626
627 // A little bit less than the minimum # uniforms required by DX9SM2 (32).
628 // Allows for a 5x5 kernel (or 25x1, for that matter).
629 #define MAX_KERNEL_SIZE 25
630
631 GrEffectRef* GrMatrixConvolutionEffect::TestCreate(SkRandom* random,
632                                                    GrContext* context,
633                                                    const GrDrawTargetCaps&,
634                                                    GrTexture* textures[]) {
635     int texIdx = random->nextBool() ? GrEffectUnitTest::kSkiaPMTextureIdx :
636                                       GrEffectUnitTest::kAlphaTextureIdx;
637     int width = random->nextRangeU(1, MAX_KERNEL_SIZE);
638     int height = random->nextRangeU(1, MAX_KERNEL_SIZE / width);
639     SkISize kernelSize = SkISize::Make(width, height);
640     SkAutoTDeleteArray<SkScalar> kernel(new SkScalar[width * height]);
641     for (int i = 0; i < width * height; i++) {
642         kernel.get()[i] = random->nextSScalar1();
643     }
644     SkScalar gain = random->nextSScalar1();
645     SkScalar bias = random->nextSScalar1();
646     SkIPoint kernelOffset = SkIPoint::Make(random->nextRangeU(0, kernelSize.width()),
647                                            random->nextRangeU(0, kernelSize.height()));
648     SkIRect bounds = SkIRect::MakeXYWH(random->nextRangeU(0, textures[texIdx]->width()),
649                                        random->nextRangeU(0, textures[texIdx]->height()),
650                                        random->nextRangeU(0, textures[texIdx]->width()),
651                                        random->nextRangeU(0, textures[texIdx]->height()));
652     TileMode tileMode = static_cast<TileMode>(random->nextRangeU(0, 2));
653     bool convolveAlpha = random->nextBool();
654     return GrMatrixConvolutionEffect::Create(textures[texIdx],
655                                              bounds,
656                                              kernelSize,
657                                              kernel.get(),
658                                              gain,
659                                              bias,
660                                              kernelOffset,
661                                              tileMode,
662                                              convolveAlpha);
663 }
664
665 bool SkMatrixConvolutionImageFilter::asNewEffect(GrEffectRef** effect,
666                                                  GrTexture* texture,
667                                                  const SkMatrix&,
668                                                  const SkIRect& bounds
669                                                  ) const {
670     if (!effect) {
671         return fKernelSize.width() * fKernelSize.height() <= MAX_KERNEL_SIZE;
672     }
673     SkASSERT(fKernelSize.width() * fKernelSize.height() <= MAX_KERNEL_SIZE);
674     *effect = GrMatrixConvolutionEffect::Create(texture,
675                                                 bounds,
676                                                 fKernelSize,
677                                                 fKernel,
678                                                 fGain,
679                                                 fBias,
680                                                 fKernelOffset,
681                                                 fTileMode,
682                                                 fConvolveAlpha);
683     return true;
684 }
685
686 ///////////////////////////////////////////////////////////////////////////////
687
688 #endif