2 * Copyright 2012 The Android Open Source Project
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
8 #include "SkMorphologyImageFilter.h"
10 #include "SkColorPriv.h"
11 #include "SkFlattenableBuffers.h"
13 #include "SkMorphology_opts.h"
15 #include "GrContext.h"
16 #include "GrTexture.h"
17 #include "GrTBackendEffectFactory.h"
18 #include "gl/GrGLEffect.h"
19 #include "effects/Gr1DKernelEffect.h"
20 #include "SkImageFilterUtils.h"
23 SkMorphologyImageFilter::SkMorphologyImageFilter(SkFlattenableReadBuffer& buffer)
25 fRadius.fWidth = buffer.readInt();
26 fRadius.fHeight = buffer.readInt();
27 buffer.validate((fRadius.fWidth >= 0) &&
28 (fRadius.fHeight >= 0));
31 SkMorphologyImageFilter::SkMorphologyImageFilter(int radiusX, int radiusY, SkImageFilter* input, const CropRect* cropRect)
32 : INHERITED(input, cropRect), fRadius(SkISize::Make(radiusX, radiusY)) {
36 void SkMorphologyImageFilter::flatten(SkFlattenableWriteBuffer& buffer) const {
37 this->INHERITED::flatten(buffer);
38 buffer.writeInt(fRadius.fWidth);
39 buffer.writeInt(fRadius.fHeight);
46 template<MorphDirection direction>
47 static void erode(const SkPMColor* src, SkPMColor* dst,
48 int radius, int width, int height,
49 int srcStride, int dstStride)
51 const int srcStrideX = direction == kX ? 1 : srcStride;
52 const int dstStrideX = direction == kX ? 1 : dstStride;
53 const int srcStrideY = direction == kX ? srcStride : 1;
54 const int dstStrideY = direction == kX ? dstStride : 1;
55 radius = SkMin32(radius, width - 1);
56 const SkPMColor* upperSrc = src + radius * srcStrideX;
57 for (int x = 0; x < width; ++x) {
58 const SkPMColor* lp = src;
59 const SkPMColor* up = upperSrc;
60 SkPMColor* dptr = dst;
61 for (int y = 0; y < height; ++y) {
62 int minB = 255, minG = 255, minR = 255, minA = 255;
63 for (const SkPMColor* p = lp; p <= up; p += srcStrideX) {
64 int b = SkGetPackedB32(*p);
65 int g = SkGetPackedG32(*p);
66 int r = SkGetPackedR32(*p);
67 int a = SkGetPackedA32(*p);
68 if (b < minB) minB = b;
69 if (g < minG) minG = g;
70 if (r < minR) minR = r;
71 if (a < minA) minA = a;
73 *dptr = SkPackARGB32(minA, minR, minG, minB);
78 if (x >= radius) src += srcStrideX;
79 if (x + radius < width - 1) upperSrc += srcStrideX;
84 static void erodeX(const SkBitmap& src, SkBitmap* dst, int radiusX, const SkIRect& bounds)
86 SkMorphologyProc erodeXProc = SkMorphologyGetPlatformProc(kErodeX_SkMorphologyProcType);
88 erodeXProc = erode<kX>;
90 erodeXProc(src.getAddr32(bounds.left(), bounds.top()), dst->getAddr32(0, 0),
91 radiusX, bounds.width(), bounds.height(),
92 src.rowBytesAsPixels(), dst->rowBytesAsPixels());
95 static void erodeY(const SkBitmap& src, SkBitmap* dst, int radiusY, const SkIRect& bounds)
97 SkMorphologyProc erodeYProc = SkMorphologyGetPlatformProc(kErodeY_SkMorphologyProcType);
99 erodeYProc = erode<kY>;
101 erodeYProc(src.getAddr32(bounds.left(), bounds.top()), dst->getAddr32(0, 0),
102 radiusY, bounds.height(), bounds.width(),
103 src.rowBytesAsPixels(), dst->rowBytesAsPixels());
106 template<MorphDirection direction>
107 static void dilate(const SkPMColor* src, SkPMColor* dst,
108 int radius, int width, int height,
109 int srcStride, int dstStride)
111 const int srcStrideX = direction == kX ? 1 : srcStride;
112 const int dstStrideX = direction == kX ? 1 : dstStride;
113 const int srcStrideY = direction == kX ? srcStride : 1;
114 const int dstStrideY = direction == kX ? dstStride : 1;
115 radius = SkMin32(radius, width - 1);
116 const SkPMColor* upperSrc = src + radius * srcStrideX;
117 for (int x = 0; x < width; ++x) {
118 const SkPMColor* lp = src;
119 const SkPMColor* up = upperSrc;
120 SkPMColor* dptr = dst;
121 for (int y = 0; y < height; ++y) {
122 int maxB = 0, maxG = 0, maxR = 0, maxA = 0;
123 for (const SkPMColor* p = lp; p <= up; p += srcStrideX) {
124 int b = SkGetPackedB32(*p);
125 int g = SkGetPackedG32(*p);
126 int r = SkGetPackedR32(*p);
127 int a = SkGetPackedA32(*p);
128 if (b > maxB) maxB = b;
129 if (g > maxG) maxG = g;
130 if (r > maxR) maxR = r;
131 if (a > maxA) maxA = a;
133 *dptr = SkPackARGB32(maxA, maxR, maxG, maxB);
138 if (x >= radius) src += srcStrideX;
139 if (x + radius < width - 1) upperSrc += srcStrideX;
144 static void dilateX(const SkBitmap& src, SkBitmap* dst, int radiusX, const SkIRect& bounds)
146 SkMorphologyProc dilateXProc = SkMorphologyGetPlatformProc(kDilateX_SkMorphologyProcType);
148 dilateXProc = dilate<kX>;
150 dilateXProc(src.getAddr32(bounds.left(), bounds.top()), dst->getAddr32(0, 0),
151 radiusX, bounds.width(), bounds.height(),
152 src.rowBytesAsPixels(), dst->rowBytesAsPixels());
155 static void dilateY(const SkBitmap& src, SkBitmap* dst, int radiusY, const SkIRect& bounds)
157 SkMorphologyProc dilateYProc = SkMorphologyGetPlatformProc(kDilateY_SkMorphologyProcType);
159 dilateYProc = dilate<kY>;
161 dilateYProc(src.getAddr32(bounds.left(), bounds.top()), dst->getAddr32(0, 0),
162 radiusY, bounds.height(), bounds.width(),
163 src.rowBytesAsPixels(), dst->rowBytesAsPixels());
166 bool SkErodeImageFilter::onFilterImage(Proxy* proxy,
167 const SkBitmap& source, const SkMatrix& ctm,
168 SkBitmap* dst, SkIPoint* offset) {
169 SkBitmap src = source;
170 if (getInput(0) && !getInput(0)->filterImage(proxy, source, ctm, &src, offset)) {
174 if (src.config() != SkBitmap::kARGB_8888_Config) {
179 src.getBounds(&bounds);
180 if (!this->applyCropRect(&bounds, ctm)) {
184 SkAutoLockPixels alp(src);
185 if (!src.getPixels()) {
189 dst->setConfig(src.config(), bounds.width(), bounds.height());
192 int width = radius().width();
193 int height = radius().height();
195 if (width < 0 || height < 0) {
199 if (width == 0 && height == 0) {
200 src.extractSubset(dst, bounds);
201 offset->fX += bounds.left();
202 offset->fY += bounds.top();
207 temp.setConfig(dst->config(), dst->width(), dst->height());
208 if (!temp.allocPixels()) {
212 if (width > 0 && height > 0) {
213 erodeX(src, &temp, width, bounds);
214 SkIRect tmpBounds = SkIRect::MakeWH(bounds.width(), bounds.height());
215 erodeY(temp, dst, height, tmpBounds);
216 } else if (width > 0) {
217 erodeX(src, dst, width, bounds);
218 } else if (height > 0) {
219 erodeY(src, dst, height, bounds);
221 offset->fX += bounds.left();
222 offset->fY += bounds.top();
226 bool SkDilateImageFilter::onFilterImage(Proxy* proxy,
227 const SkBitmap& source, const SkMatrix& ctm,
228 SkBitmap* dst, SkIPoint* offset) {
229 SkBitmap src = source;
230 if (getInput(0) && !getInput(0)->filterImage(proxy, source, ctm, &src, offset)) {
233 if (src.config() != SkBitmap::kARGB_8888_Config) {
238 src.getBounds(&bounds);
239 if (!this->applyCropRect(&bounds, ctm)) {
243 SkAutoLockPixels alp(src);
244 if (!src.getPixels()) {
248 dst->setConfig(src.config(), bounds.width(), bounds.height());
251 int width = radius().width();
252 int height = radius().height();
254 if (width < 0 || height < 0) {
258 if (width == 0 && height == 0) {
259 src.extractSubset(dst, bounds);
260 offset->fX += bounds.left();
261 offset->fY += bounds.top();
266 temp.setConfig(dst->config(), dst->width(), dst->height());
267 if (!temp.allocPixels()) {
271 if (width > 0 && height > 0) {
272 dilateX(src, &temp, width, bounds);
273 SkIRect tmpBounds = SkIRect::MakeWH(bounds.width(), bounds.height());
274 dilateY(temp, dst, height, tmpBounds);
275 } else if (width > 0) {
276 dilateX(src, dst, width, bounds);
277 } else if (height > 0) {
278 dilateY(src, dst, height, bounds);
280 offset->fX += bounds.left();
281 offset->fY += bounds.top();
287 ///////////////////////////////////////////////////////////////////////////////
289 class GrGLMorphologyEffect;
292 * Morphology effects. Depending upon the type of morphology, either the
293 * component-wise min (Erode_Type) or max (Dilate_Type) of all pixels in the
294 * kernel is selected as the new color. The new color is modulated by the input
297 class GrMorphologyEffect : public Gr1DKernelEffect {
301 enum MorphologyType {
302 kErode_MorphologyType,
303 kDilate_MorphologyType,
306 static GrEffectRef* Create(GrTexture* tex, Direction dir, int radius, MorphologyType type) {
307 AutoEffectUnref effect(SkNEW_ARGS(GrMorphologyEffect, (tex, dir, radius, type)));
308 return CreateEffectRef(effect);
311 virtual ~GrMorphologyEffect();
313 MorphologyType type() const { return fType; }
315 static const char* Name() { return "Morphology"; }
317 typedef GrGLMorphologyEffect GLEffect;
319 virtual const GrBackendEffectFactory& getFactory() const SK_OVERRIDE;
320 virtual void getConstantColorComponents(GrColor* color, uint32_t* validFlags) const SK_OVERRIDE;
324 MorphologyType fType;
327 virtual bool onIsEqual(const GrEffect&) const SK_OVERRIDE;
329 GrMorphologyEffect(GrTexture*, Direction, int radius, MorphologyType);
331 GR_DECLARE_EFFECT_TEST;
333 typedef Gr1DKernelEffect INHERITED;
336 ///////////////////////////////////////////////////////////////////////////////
338 class GrGLMorphologyEffect : public GrGLEffect {
340 GrGLMorphologyEffect (const GrBackendEffectFactory&, const GrDrawEffect&);
342 virtual void emitCode(GrGLShaderBuilder*,
345 const char* outputColor,
346 const char* inputColor,
347 const TransformedCoordsArray&,
348 const TextureSamplerArray&) SK_OVERRIDE;
350 static inline EffectKey GenKey(const GrDrawEffect&, const GrGLCaps&);
352 virtual void setData(const GrGLUniformManager&, const GrDrawEffect&) SK_OVERRIDE;
355 int width() const { return GrMorphologyEffect::WidthFromRadius(fRadius); }
358 GrMorphologyEffect::MorphologyType fType;
359 GrGLUniformManager::UniformHandle fImageIncrementUni;
361 typedef GrGLEffect INHERITED;
364 GrGLMorphologyEffect::GrGLMorphologyEffect(const GrBackendEffectFactory& factory,
365 const GrDrawEffect& drawEffect)
366 : INHERITED(factory) {
367 const GrMorphologyEffect& m = drawEffect.castEffect<GrMorphologyEffect>();
368 fRadius = m.radius();
372 void GrGLMorphologyEffect::emitCode(GrGLShaderBuilder* builder,
375 const char* outputColor,
376 const char* inputColor,
377 const TransformedCoordsArray& coords,
378 const TextureSamplerArray& samplers) {
379 SkString coords2D = builder->ensureFSCoords2D(coords, 0);
380 fImageIncrementUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
381 kVec2f_GrSLType, "ImageIncrement");
385 case GrMorphologyEffect::kErode_MorphologyType:
386 builder->fsCodeAppendf("\t\t%s = vec4(1, 1, 1, 1);\n", outputColor);
389 case GrMorphologyEffect::kDilate_MorphologyType:
390 builder->fsCodeAppendf("\t\t%s = vec4(0, 0, 0, 0);\n", outputColor);
394 GrCrash("Unexpected type");
395 func = ""; // suppress warning
398 const char* imgInc = builder->getUniformCStr(fImageIncrementUni);
400 builder->fsCodeAppendf("\t\tvec2 coord = %s - %d.0 * %s;\n", coords2D.c_str(), fRadius, imgInc);
401 builder->fsCodeAppendf("\t\tfor (int i = 0; i < %d; i++) {\n", this->width());
402 builder->fsCodeAppendf("\t\t\t%s = %s(%s, ", outputColor, func, outputColor);
403 builder->fsAppendTextureLookup(samplers[0], "coord");
404 builder->fsCodeAppend(");\n");
405 builder->fsCodeAppendf("\t\t\tcoord += %s;\n", imgInc);
406 builder->fsCodeAppend("\t\t}\n");
408 GrGLSLMulVarBy4f(&modulate, 2, outputColor, inputColor);
409 builder->fsCodeAppend(modulate.c_str());
412 GrGLEffect::EffectKey GrGLMorphologyEffect::GenKey(const GrDrawEffect& drawEffect,
414 const GrMorphologyEffect& m = drawEffect.castEffect<GrMorphologyEffect>();
415 EffectKey key = static_cast<EffectKey>(m.radius());
416 key |= (m.type() << 8);
420 void GrGLMorphologyEffect::setData(const GrGLUniformManager& uman,
421 const GrDrawEffect& drawEffect) {
422 const Gr1DKernelEffect& kern = drawEffect.castEffect<Gr1DKernelEffect>();
423 GrTexture& texture = *kern.texture(0);
424 // the code we generated was for a specific kernel radius
425 SkASSERT(kern.radius() == fRadius);
426 float imageIncrement[2] = { 0 };
427 switch (kern.direction()) {
428 case Gr1DKernelEffect::kX_Direction:
429 imageIncrement[0] = 1.0f / texture.width();
431 case Gr1DKernelEffect::kY_Direction:
432 imageIncrement[1] = 1.0f / texture.height();
435 GrCrash("Unknown filter direction.");
437 uman.set2fv(fImageIncrementUni, 0, 1, imageIncrement);
440 ///////////////////////////////////////////////////////////////////////////////
442 GrMorphologyEffect::GrMorphologyEffect(GrTexture* texture,
446 : Gr1DKernelEffect(texture, direction, radius)
450 GrMorphologyEffect::~GrMorphologyEffect() {
453 const GrBackendEffectFactory& GrMorphologyEffect::getFactory() const {
454 return GrTBackendEffectFactory<GrMorphologyEffect>::getInstance();
457 bool GrMorphologyEffect::onIsEqual(const GrEffect& sBase) const {
458 const GrMorphologyEffect& s = CastEffect<GrMorphologyEffect>(sBase);
459 return (this->texture(0) == s.texture(0) &&
460 this->radius() == s.radius() &&
461 this->direction() == s.direction() &&
462 this->type() == s.type());
465 void GrMorphologyEffect::getConstantColorComponents(GrColor* color, uint32_t* validFlags) const {
466 // This is valid because the color components of the result of the kernel all come
467 // exactly from existing values in the source texture.
468 this->updateConstantColorComponentsForModulation(color, validFlags);
471 ///////////////////////////////////////////////////////////////////////////////
473 GR_DEFINE_EFFECT_TEST(GrMorphologyEffect);
475 GrEffectRef* GrMorphologyEffect::TestCreate(SkRandom* random,
477 const GrDrawTargetCaps&,
478 GrTexture* textures[]) {
479 int texIdx = random->nextBool() ? GrEffectUnitTest::kSkiaPMTextureIdx :
480 GrEffectUnitTest::kAlphaTextureIdx;
481 Direction dir = random->nextBool() ? kX_Direction : kY_Direction;
482 static const int kMaxRadius = 10;
483 int radius = random->nextRangeU(1, kMaxRadius);
484 MorphologyType type = random->nextBool() ? GrMorphologyEffect::kErode_MorphologyType :
485 GrMorphologyEffect::kDilate_MorphologyType;
487 return GrMorphologyEffect::Create(textures[texIdx], dir, radius, type);
492 void apply_morphology_pass(GrContext* context,
494 const SkIRect& srcRect,
495 const SkIRect& dstRect,
497 GrMorphologyEffect::MorphologyType morphType,
498 Gr1DKernelEffect::Direction direction) {
500 paint.addColorEffect(GrMorphologyEffect::Create(texture,
503 morphType))->unref();
504 context->drawRectToRect(paint, SkRect::Make(dstRect), SkRect::Make(srcRect));
507 bool apply_morphology(const SkBitmap& input,
509 GrMorphologyEffect::MorphologyType morphType,
512 GrTexture* srcTexture = input.getTexture();
513 SkASSERT(NULL != srcTexture);
514 GrContext* context = srcTexture->getContext();
516 SkAutoTUnref<GrTexture> src(srcTexture);
518 GrContext::AutoMatrix am;
519 am.setIdentity(context);
521 GrContext::AutoClip acs(context, SkRect::MakeWH(SkIntToScalar(srcTexture->width()),
522 SkIntToScalar(srcTexture->height())));
524 SkIRect dstRect = SkIRect::MakeWH(rect.width(), rect.height());
526 desc.fFlags = kRenderTarget_GrTextureFlagBit | kNoStencil_GrTextureFlagBit;
527 desc.fWidth = rect.width();
528 desc.fHeight = rect.height();
529 desc.fConfig = kSkia8888_GrPixelConfig;
530 SkIRect srcRect = rect;
532 if (radius.fWidth > 0) {
533 GrAutoScratchTexture ast(context, desc);
534 GrContext::AutoRenderTarget art(context, ast.texture()->asRenderTarget());
535 apply_morphology_pass(context, src, srcRect, dstRect, radius.fWidth,
536 morphType, Gr1DKernelEffect::kX_Direction);
537 SkIRect clearRect = SkIRect::MakeXYWH(dstRect.fLeft, dstRect.fBottom,
538 dstRect.width(), radius.fHeight);
539 context->clear(&clearRect, GrMorphologyEffect::kErode_MorphologyType == morphType ?
541 SK_ColorTRANSPARENT, false);
542 src.reset(ast.detach());
545 if (radius.fHeight > 0) {
546 GrAutoScratchTexture ast(context, desc);
547 GrContext::AutoRenderTarget art(context, ast.texture()->asRenderTarget());
548 apply_morphology_pass(context, src, srcRect, dstRect, radius.fHeight,
549 morphType, Gr1DKernelEffect::kY_Direction);
550 src.reset(ast.detach());
552 return SkImageFilterUtils::WrapTexture(src, rect.width(), rect.height(), dst);
557 bool SkDilateImageFilter::filterImageGPU(Proxy* proxy, const SkBitmap& src, const SkMatrix& ctm,
558 SkBitmap* result, SkIPoint* offset) {
560 if (!SkImageFilterUtils::GetInputResultGPU(getInput(0), proxy, src, ctm, &input, offset)) {
564 src.getBounds(&bounds);
565 if (!this->applyCropRect(&bounds, ctm)) {
568 int width = radius().width();
569 int height = radius().height();
571 if (width < 0 || height < 0) {
575 if (width == 0 && height == 0) {
576 src.extractSubset(result, bounds);
577 offset->fX += bounds.left();
578 offset->fY += bounds.top();
582 if (!apply_morphology(input, bounds, GrMorphologyEffect::kDilate_MorphologyType, radius(), result)) {
585 offset->fX += bounds.left();
586 offset->fY += bounds.top();
590 bool SkErodeImageFilter::filterImageGPU(Proxy* proxy, const SkBitmap& src, const SkMatrix& ctm,
591 SkBitmap* result, SkIPoint* offset) {
593 if (!SkImageFilterUtils::GetInputResultGPU(getInput(0), proxy, src, ctm, &input, offset)) {
597 src.getBounds(&bounds);
598 if (!this->applyCropRect(&bounds, ctm)) {
601 int width = radius().width();
602 int height = radius().height();
604 if (width < 0 || height < 0) {
608 if (width == 0 && height == 0) {
609 src.extractSubset(result, bounds);
610 offset->fX += bounds.left();
611 offset->fY += bounds.top();
615 if (!apply_morphology(input, bounds, GrMorphologyEffect::kErode_MorphologyType, radius(), result)) {
618 offset->fX += bounds.left();
619 offset->fY += bounds.top();