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