e6f1f088cbae9f1ca8775643ade00ad1f9bacaa6
[platform/upstream/libSkiaSharp.git] / src / effects / SkAlphaThresholdFilter.cpp
1 /*
2  * Copyright 2013 Google Inc.
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7
8 #include "SkAlphaThresholdFilter.h"
9 #include "SkBitmap.h"
10 #include "SkDevice.h"
11 #include "SkReadBuffer.h"
12 #include "SkWriteBuffer.h"
13 #include "SkRegion.h"
14 #if SK_SUPPORT_GPU
15 #include "GrDrawContext.h"
16 #endif
17
18 class SK_API SkAlphaThresholdFilterImpl : public SkImageFilter {
19 public:
20     SkAlphaThresholdFilterImpl(const SkRegion& region, SkScalar innerThreshold,
21                                SkScalar outerThreshold, SkImageFilter* input);
22
23     SK_TO_STRING_OVERRIDE()
24     SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(SkAlphaThresholdFilterImpl)
25
26 protected:
27     void flatten(SkWriteBuffer&) const override;
28
29     bool onFilterImage(Proxy*, const SkBitmap& src, const Context&,
30                        SkBitmap* result, SkIPoint* offset) const override;
31 #if SK_SUPPORT_GPU
32     bool asFragmentProcessor(GrFragmentProcessor**, GrTexture*, const SkMatrix&,
33                              const SkIRect& bounds) const override;
34 #endif
35
36 private:
37     SkRegion fRegion;
38     SkScalar fInnerThreshold;
39     SkScalar fOuterThreshold;
40     typedef SkImageFilter INHERITED;
41 };
42
43 SkImageFilter* SkAlphaThresholdFilter::Create(const SkRegion& region,
44                                               SkScalar innerThreshold,
45                                               SkScalar outerThreshold,
46                                               SkImageFilter* input) {
47     return new SkAlphaThresholdFilterImpl(region, innerThreshold, outerThreshold, input);
48 }
49
50 #if SK_SUPPORT_GPU
51 #include "GrContext.h"
52 #include "GrCoordTransform.h"
53 #include "GrFragmentProcessor.h"
54 #include "GrInvariantOutput.h"
55 #include "GrTextureAccess.h"
56 #include "effects/GrPorterDuffXferProcessor.h"
57
58 #include "SkGr.h"
59
60 #include "glsl/GrGLSLFragmentProcessor.h"
61 #include "glsl/GrGLSLFragmentShaderBuilder.h"
62 #include "glsl/GrGLSLProgramBuilder.h"
63 #include "glsl/GrGLSLProgramDataManager.h"
64
65 class AlphaThresholdEffect : public GrFragmentProcessor {
66
67 public:
68     static GrFragmentProcessor* Create(GrTexture* texture,
69                                        GrTexture* maskTexture,
70                                        float innerThreshold,
71                                        float outerThreshold) {
72         return new AlphaThresholdEffect(texture, maskTexture, innerThreshold, outerThreshold);
73     }
74
75     virtual ~AlphaThresholdEffect() {};
76
77     const char* name() const override { return "Alpha Threshold"; }
78
79     float innerThreshold() const { return fInnerThreshold; }
80     float outerThreshold() const { return fOuterThreshold; }
81
82 private:
83     AlphaThresholdEffect(GrTexture* texture,
84                          GrTexture* maskTexture,
85                          float innerThreshold,
86                          float outerThreshold)
87         : fInnerThreshold(innerThreshold)
88         , fOuterThreshold(outerThreshold)
89         , fImageCoordTransform(kLocal_GrCoordSet,
90                                GrCoordTransform::MakeDivByTextureWHMatrix(texture), texture,
91                                GrTextureParams::kNone_FilterMode)
92         , fImageTextureAccess(texture)
93         , fMaskCoordTransform(kLocal_GrCoordSet,
94                               GrCoordTransform::MakeDivByTextureWHMatrix(maskTexture), maskTexture,
95                               GrTextureParams::kNone_FilterMode)
96         , fMaskTextureAccess(maskTexture) {
97         this->initClassID<AlphaThresholdEffect>();
98         this->addCoordTransform(&fImageCoordTransform);
99         this->addTextureAccess(&fImageTextureAccess);
100         this->addCoordTransform(&fMaskCoordTransform);
101         this->addTextureAccess(&fMaskTextureAccess);
102     }
103
104     GrGLSLFragmentProcessor* onCreateGLSLInstance() const override;
105
106     void onGetGLSLProcessorKey(const GrGLSLCaps&, GrProcessorKeyBuilder*) const override;
107
108     bool onIsEqual(const GrFragmentProcessor&) const override;
109
110     void onComputeInvariantOutput(GrInvariantOutput* inout) const override;
111
112     GR_DECLARE_FRAGMENT_PROCESSOR_TEST;
113
114     float fInnerThreshold;
115     float fOuterThreshold;
116     GrCoordTransform fImageCoordTransform;
117     GrTextureAccess  fImageTextureAccess;
118     GrCoordTransform fMaskCoordTransform;
119     GrTextureAccess  fMaskTextureAccess;
120
121     typedef GrFragmentProcessor INHERITED;
122 };
123
124 class GrGLAlphaThresholdEffect : public GrGLSLFragmentProcessor {
125 public:
126     GrGLAlphaThresholdEffect(const GrFragmentProcessor&) {}
127
128     virtual void emitCode(EmitArgs&) override;
129
130 protected:
131     void onSetData(const GrGLSLProgramDataManager&, const GrProcessor&) override;
132
133 private:
134
135     GrGLSLProgramDataManager::UniformHandle fInnerThresholdVar;
136     GrGLSLProgramDataManager::UniformHandle fOuterThresholdVar;
137
138     typedef GrGLSLFragmentProcessor INHERITED;
139 };
140
141 void GrGLAlphaThresholdEffect::emitCode(EmitArgs& args) {
142     fInnerThresholdVar = args.fBuilder->addUniform(GrGLSLProgramBuilder::kFragment_Visibility,
143                                                    kFloat_GrSLType, kDefault_GrSLPrecision,
144                                                    "inner_threshold");
145     fOuterThresholdVar = args.fBuilder->addUniform(GrGLSLProgramBuilder::kFragment_Visibility,
146                                                    kFloat_GrSLType, kDefault_GrSLPrecision,
147                                                    "outer_threshold");
148
149     GrGLSLFragmentBuilder* fragBuilder = args.fFragBuilder;
150     SkString coords2D = fragBuilder->ensureFSCoords2D(args.fCoords, 0);
151     SkString maskCoords2D = fragBuilder->ensureFSCoords2D(args.fCoords, 1);
152
153     fragBuilder->codeAppendf("\t\tvec2 coord = %s;\n", coords2D.c_str());
154     fragBuilder->codeAppendf("\t\tvec2 mask_coord = %s;\n", maskCoords2D.c_str());
155     fragBuilder->codeAppend("\t\tvec4 input_color = ");
156     fragBuilder->appendTextureLookup(args.fSamplers[0], "coord");
157     fragBuilder->codeAppend(";\n");
158     fragBuilder->codeAppend("\t\tvec4 mask_color = ");
159     fragBuilder->appendTextureLookup(args.fSamplers[1], "mask_coord");
160     fragBuilder->codeAppend(";\n");
161
162     fragBuilder->codeAppendf("\t\tfloat inner_thresh = %s;\n",
163                              args.fBuilder->getUniformCStr(fInnerThresholdVar));
164     fragBuilder->codeAppendf("\t\tfloat outer_thresh = %s;\n",
165                              args.fBuilder->getUniformCStr(fOuterThresholdVar));
166     fragBuilder->codeAppend("\t\tfloat mask = mask_color.a;\n");
167
168     fragBuilder->codeAppend("vec4 color = input_color;\n");
169     fragBuilder->codeAppend("\t\tif (mask < 0.5) {\n"
170                             "\t\t\tif (color.a > outer_thresh) {\n"
171                             "\t\t\t\tfloat scale = outer_thresh / color.a;\n"
172                             "\t\t\t\tcolor.rgb *= scale;\n"
173                             "\t\t\t\tcolor.a = outer_thresh;\n"
174                             "\t\t\t}\n"
175                             "\t\t} else if (color.a < inner_thresh) {\n"
176                             "\t\t\tfloat scale = inner_thresh / max(0.001, color.a);\n"
177                             "\t\t\tcolor.rgb *= scale;\n"
178                             "\t\t\tcolor.a = inner_thresh;\n"
179                             "\t\t}\n");
180
181     fragBuilder->codeAppendf("%s = %s;\n", args.fOutputColor,
182                              (GrGLSLExpr4(args.fInputColor) * GrGLSLExpr4("color")).c_str());
183 }
184
185 void GrGLAlphaThresholdEffect::onSetData(const GrGLSLProgramDataManager& pdman,
186                                        const GrProcessor& proc) {
187     const AlphaThresholdEffect& alpha_threshold = proc.cast<AlphaThresholdEffect>();
188     pdman.set1f(fInnerThresholdVar, alpha_threshold.innerThreshold());
189     pdman.set1f(fOuterThresholdVar, alpha_threshold.outerThreshold());
190 }
191
192 /////////////////////////////////////////////////////////////////////
193
194 GR_DEFINE_FRAGMENT_PROCESSOR_TEST(AlphaThresholdEffect);
195
196 const GrFragmentProcessor* AlphaThresholdEffect::TestCreate(GrProcessorTestData* d) {
197     GrTexture* bmpTex = d->fTextures[GrProcessorUnitTest::kSkiaPMTextureIdx];
198     GrTexture* maskTex = d->fTextures[GrProcessorUnitTest::kAlphaTextureIdx];
199     float innerThresh = d->fRandom->nextUScalar1();
200     float outerThresh = d->fRandom->nextUScalar1();
201     return AlphaThresholdEffect::Create(bmpTex, maskTex, innerThresh, outerThresh);
202 }
203
204 ///////////////////////////////////////////////////////////////////////////////
205
206 void AlphaThresholdEffect::onGetGLSLProcessorKey(const GrGLSLCaps& caps,
207                                                  GrProcessorKeyBuilder* b) const {
208     GrGLAlphaThresholdEffect::GenKey(*this, caps, b);
209 }
210
211 GrGLSLFragmentProcessor* AlphaThresholdEffect::onCreateGLSLInstance() const {
212     return new GrGLAlphaThresholdEffect(*this);
213 }
214
215 bool AlphaThresholdEffect::onIsEqual(const GrFragmentProcessor& sBase) const {
216     const AlphaThresholdEffect& s = sBase.cast<AlphaThresholdEffect>();
217     return (this->fInnerThreshold == s.fInnerThreshold &&
218             this->fOuterThreshold == s.fOuterThreshold);
219 }
220
221 void AlphaThresholdEffect::onComputeInvariantOutput(GrInvariantOutput* inout) const {
222     if (GrPixelConfigIsAlphaOnly(this->texture(0)->config())) {
223         inout->mulByUnknownSingleComponent();
224     } else if (GrPixelConfigIsOpaque(this->texture(0)->config()) && fOuterThreshold >= 1.f) {
225         inout->mulByUnknownOpaqueFourComponents();
226     } else {
227         inout->mulByUnknownFourComponents();
228     }
229 }
230
231 #endif
232
233 SkFlattenable* SkAlphaThresholdFilterImpl::CreateProc(SkReadBuffer& buffer) {
234     SK_IMAGEFILTER_UNFLATTEN_COMMON(common, 1);
235     SkScalar inner = buffer.readScalar();
236     SkScalar outer = buffer.readScalar();
237     SkRegion rgn;
238     buffer.readRegion(&rgn);
239     return SkAlphaThresholdFilter::Create(rgn, inner, outer, common.getInput(0));
240 }
241
242 SkAlphaThresholdFilterImpl::SkAlphaThresholdFilterImpl(const SkRegion& region,
243                                                        SkScalar innerThreshold,
244                                                        SkScalar outerThreshold,
245                                                        SkImageFilter* input)
246     : INHERITED(1, &input)
247     , fRegion(region)
248     , fInnerThreshold(innerThreshold)
249     , fOuterThreshold(outerThreshold) {
250 }
251
252 #if SK_SUPPORT_GPU
253 bool SkAlphaThresholdFilterImpl::asFragmentProcessor(GrFragmentProcessor** fp,
254                                                      GrTexture* texture,
255                                                      const SkMatrix& inMatrix,
256                                                      const SkIRect&) const {
257     if (fp) {
258         GrContext* context = texture->getContext();
259         GrSurfaceDesc maskDesc;
260         if (context->caps()->isConfigRenderable(kAlpha_8_GrPixelConfig, false)) {
261             maskDesc.fConfig = kAlpha_8_GrPixelConfig;
262         } else {
263             maskDesc.fConfig = kRGBA_8888_GrPixelConfig;
264         }
265         maskDesc.fFlags = kRenderTarget_GrSurfaceFlag;
266         // Add one pixel of border to ensure that clamp mode will be all zeros
267         // the outside.
268         maskDesc.fWidth = texture->width();
269         maskDesc.fHeight = texture->height();
270         SkAutoTUnref<GrTexture> maskTexture(
271             context->textureProvider()->createApproxTexture(maskDesc));
272         if (!maskTexture) {
273             return false;
274         }
275
276         SkAutoTUnref<GrDrawContext> drawContext(
277                                             context->drawContext(maskTexture->asRenderTarget()));
278         if (drawContext) {
279             GrPaint grPaint;
280             grPaint.setPorterDuffXPFactory(SkXfermode::kSrc_Mode);
281             SkRegion::Iterator iter(fRegion);
282             drawContext->clear(nullptr, 0x0, true);
283
284             while (!iter.done()) {
285                 SkRect rect = SkRect::Make(iter.rect());
286                 drawContext->drawRect(GrClip::WideOpen(), grPaint, inMatrix, rect);
287                 iter.next();
288             }
289         }
290
291         *fp = AlphaThresholdEffect::Create(texture,
292                                            maskTexture,
293                                            fInnerThreshold,
294                                            fOuterThreshold);
295     }
296     return true;
297 }
298 #endif
299
300 void SkAlphaThresholdFilterImpl::flatten(SkWriteBuffer& buffer) const {
301     this->INHERITED::flatten(buffer);
302     buffer.writeScalar(fInnerThreshold);
303     buffer.writeScalar(fOuterThreshold);
304     buffer.writeRegion(fRegion);
305 }
306
307 bool SkAlphaThresholdFilterImpl::onFilterImage(Proxy* proxy, const SkBitmap& src,
308                                                const Context& ctx, SkBitmap* dst,
309                                                SkIPoint* offset) const {
310     SkASSERT(src.colorType() == kN32_SkColorType);
311
312     if (src.colorType() != kN32_SkColorType) {
313         return false;
314     }
315
316     SkMatrix localInverse;
317     if (!ctx.ctm().invert(&localInverse)) {
318         return false;
319     }
320
321     SkAutoLockPixels alp(src);
322     SkASSERT(src.getPixels());
323     if (!src.getPixels() || src.width() <= 0 || src.height() <= 0) {
324         return false;
325     }
326
327     SkAutoTUnref<SkBaseDevice> device(proxy->createDevice(src.width(), src.height()));
328     if (!device) {
329         return false;
330     }
331     *dst = device->accessBitmap(false);
332     SkAutoLockPixels alp_dst(*dst);
333
334     U8CPU innerThreshold = (U8CPU)(fInnerThreshold * 0xFF);
335     U8CPU outerThreshold = (U8CPU)(fOuterThreshold * 0xFF);
336     SkColor* sptr = src.getAddr32(0, 0);
337     SkColor* dptr = dst->getAddr32(0, 0);
338     int width = src.width(), height = src.height();
339     for (int y = 0; y < height; ++y) {
340         for (int x = 0; x < width; ++x) {
341             const SkColor& source = sptr[y * width + x];
342             SkColor output_color(source);
343             SkPoint position;
344             localInverse.mapXY((SkScalar)x, (SkScalar)y, &position);
345             if (fRegion.contains((int32_t)position.x(), (int32_t)position.y())) {
346                 if (SkColorGetA(source) < innerThreshold) {
347                     U8CPU alpha = SkColorGetA(source);
348                     if (alpha == 0)
349                         alpha = 1;
350                     float scale = (float)innerThreshold / alpha;
351                     output_color = SkColorSetARGB(innerThreshold,
352                                                   (U8CPU)(SkColorGetR(source) * scale),
353                                                   (U8CPU)(SkColorGetG(source) * scale),
354                                                   (U8CPU)(SkColorGetB(source) * scale));
355                 }
356             } else {
357                 if (SkColorGetA(source) > outerThreshold) {
358                     float scale = (float)outerThreshold / SkColorGetA(source);
359                     output_color = SkColorSetARGB(outerThreshold,
360                                                   (U8CPU)(SkColorGetR(source) * scale),
361                                                   (U8CPU)(SkColorGetG(source) * scale),
362                                                   (U8CPU)(SkColorGetB(source) * scale));
363                 }
364             }
365             dptr[y * dst->width() + x] = output_color;
366         }
367     }
368
369     return true;
370 }
371
372 #ifndef SK_IGNORE_TO_STRING
373 void SkAlphaThresholdFilterImpl::toString(SkString* str) const {
374     str->appendf("SkAlphaThresholdImageFilter: (");
375     str->appendf("inner: %f outer: %f", fInnerThreshold, fOuterThreshold);
376     str->append(")");
377 }
378 #endif
379