Implement crop rect support for SkMatrixConvolutionImageFilter.
[platform/upstream/libSkiaSharp.git] / src / effects / SkMagnifierImageFilter.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 "SkBitmap.h"
9 #include "SkMagnifierImageFilter.h"
10 #include "SkColorPriv.h"
11 #include "SkFlattenableBuffers.h"
12
13 ////////////////////////////////////////////////////////////////////////////////
14 #if SK_SUPPORT_GPU
15 #include "effects/GrSingleTextureEffect.h"
16 #include "gl/GrGLEffect.h"
17 #include "gl/GrGLSL.h"
18 #include "gl/GrGLTexture.h"
19 #include "GrTBackendEffectFactory.h"
20
21 class GrGLMagnifierEffect;
22
23 class GrMagnifierEffect : public GrSingleTextureEffect {
24
25 public:
26     static GrEffectRef* Create(GrTexture* texture,
27                                float xOffset,
28                                float yOffset,
29                                float xZoom,
30                                float yZoom,
31                                float xInset,
32                                float yInset) {
33         AutoEffectUnref effect(SkNEW_ARGS(GrMagnifierEffect, (texture,
34                                                               xOffset,
35                                                               yOffset,
36                                                               xZoom,
37                                                               yZoom,
38                                                               xInset,
39                                                               yInset)));
40         return CreateEffectRef(effect);
41     }
42
43     virtual ~GrMagnifierEffect() {};
44
45     static const char* Name() { return "Magnifier"; }
46
47     virtual const GrBackendEffectFactory& getFactory() const SK_OVERRIDE;
48     virtual void getConstantColorComponents(GrColor* color, uint32_t* validFlags) const SK_OVERRIDE;
49
50     float x_offset() const { return fXOffset; }
51     float y_offset() const { return fYOffset; }
52     float x_zoom() const { return fXZoom; }
53     float y_zoom() const { return fYZoom; }
54     float x_inset() const { return fXInset; }
55     float y_inset() const { return fYInset; }
56
57     typedef GrGLMagnifierEffect GLEffect;
58
59 private:
60     GrMagnifierEffect(GrTexture* texture,
61                       float xOffset,
62                       float yOffset,
63                       float xZoom,
64                       float yZoom,
65                       float xInset,
66                       float yInset)
67         : GrSingleTextureEffect(texture, MakeDivByTextureWHMatrix(texture))
68         , fXOffset(xOffset)
69         , fYOffset(yOffset)
70         , fXZoom(xZoom)
71         , fYZoom(yZoom)
72         , fXInset(xInset)
73         , fYInset(yInset) {}
74
75     virtual bool onIsEqual(const GrEffect&) const SK_OVERRIDE;
76
77     GR_DECLARE_EFFECT_TEST;
78
79     float fXOffset;
80     float fYOffset;
81     float fXZoom;
82     float fYZoom;
83     float fXInset;
84     float fYInset;
85
86     typedef GrSingleTextureEffect INHERITED;
87 };
88
89 // For brevity
90 typedef GrGLUniformManager::UniformHandle UniformHandle;
91
92 class GrGLMagnifierEffect : public GrGLEffect {
93 public:
94     GrGLMagnifierEffect(const GrBackendEffectFactory&, const GrDrawEffect&);
95
96     virtual void emitCode(GrGLShaderBuilder*,
97                           const GrDrawEffect&,
98                           EffectKey,
99                           const char* outputColor,
100                           const char* inputColor,
101                           const TransformedCoordsArray&,
102                           const TextureSamplerArray&) SK_OVERRIDE;
103
104     virtual void setData(const GrGLUniformManager&, const GrDrawEffect&) SK_OVERRIDE;
105
106 private:
107     UniformHandle       fOffsetVar;
108     UniformHandle       fZoomVar;
109     UniformHandle       fInsetVar;
110
111     typedef GrGLEffect INHERITED;
112 };
113
114 GrGLMagnifierEffect::GrGLMagnifierEffect(const GrBackendEffectFactory& factory, const GrDrawEffect&)
115     : INHERITED(factory) {
116 }
117
118 void GrGLMagnifierEffect::emitCode(GrGLShaderBuilder* builder,
119                                    const GrDrawEffect&,
120                                    EffectKey key,
121                                    const char* outputColor,
122                                    const char* inputColor,
123                                    const TransformedCoordsArray& coords,
124                                    const TextureSamplerArray& samplers) {
125     SkString coords2D = builder->ensureFSCoords2D(coords, 0);
126     fOffsetVar = builder->addUniform(
127         GrGLShaderBuilder::kFragment_Visibility |
128         GrGLShaderBuilder::kVertex_Visibility,
129         kVec2f_GrSLType, "uOffset");
130     fZoomVar = builder->addUniform(
131         GrGLShaderBuilder::kFragment_Visibility |
132         GrGLShaderBuilder::kVertex_Visibility,
133         kVec2f_GrSLType, "uZoom");
134     fInsetVar = builder->addUniform(
135         GrGLShaderBuilder::kFragment_Visibility |
136         GrGLShaderBuilder::kVertex_Visibility,
137         kVec2f_GrSLType, "uInset");
138
139     builder->fsCodeAppendf("\t\tvec2 coord = %s;\n", coords2D.c_str());
140     builder->fsCodeAppendf("\t\tvec2 zoom_coord = %s + %s / %s;\n",
141                            builder->getUniformCStr(fOffsetVar),
142                            coords2D.c_str(),
143                            builder->getUniformCStr(fZoomVar));
144
145     builder->fsCodeAppend("\t\tvec2 delta = min(coord, vec2(1.0, 1.0) - coord);\n");
146
147     builder->fsCodeAppendf("\t\tdelta = delta / %s;\n", builder->getUniformCStr(fInsetVar));
148
149     builder->fsCodeAppend("\t\tfloat weight = 0.0;\n");
150     builder->fsCodeAppend("\t\tif (delta.s < 2.0 && delta.t < 2.0) {\n");
151     builder->fsCodeAppend("\t\t\tdelta = vec2(2.0, 2.0) - delta;\n");
152     builder->fsCodeAppend("\t\t\tfloat dist = length(delta);\n");
153     builder->fsCodeAppend("\t\t\tdist = max(2.0 - dist, 0.0);\n");
154     builder->fsCodeAppend("\t\t\tweight = min(dist * dist, 1.0);\n");
155     builder->fsCodeAppend("\t\t} else {\n");
156     builder->fsCodeAppend("\t\t\tvec2 delta_squared = delta * delta;\n");
157     builder->fsCodeAppend("\t\t\tweight = min(min(delta_squared.s, delta_squared.y), 1.0);\n");
158     builder->fsCodeAppend("\t\t}\n");
159
160     builder->fsCodeAppend("\t\tvec2 mix_coord = mix(coord, zoom_coord, weight);\n");
161     builder->fsCodeAppend("\t\tvec4 output_color = ");
162     builder->fsAppendTextureLookup(samplers[0], "mix_coord");
163     builder->fsCodeAppend(";\n");
164
165     builder->fsCodeAppendf("\t\t%s = output_color;", outputColor);
166     SkString modulate;
167     GrGLSLMulVarBy4f(&modulate, 2, outputColor, inputColor);
168     builder->fsCodeAppend(modulate.c_str());
169 }
170
171 void GrGLMagnifierEffect::setData(const GrGLUniformManager& uman,
172                                   const GrDrawEffect& drawEffect) {
173     const GrMagnifierEffect& zoom = drawEffect.castEffect<GrMagnifierEffect>();
174     uman.set2f(fOffsetVar, zoom.x_offset(), zoom.y_offset());
175     uman.set2f(fZoomVar, zoom.x_zoom(), zoom.y_zoom());
176     uman.set2f(fInsetVar, zoom.x_inset(), zoom.y_inset());
177 }
178
179 /////////////////////////////////////////////////////////////////////
180
181 GR_DEFINE_EFFECT_TEST(GrMagnifierEffect);
182
183 GrEffectRef* GrMagnifierEffect::TestCreate(SkRandom* random,
184                                            GrContext* context,
185                                            const GrDrawTargetCaps&,
186                                            GrTexture** textures) {
187     GrTexture* texture = textures[0];
188     const int kMaxWidth = 200;
189     const int kMaxHeight = 200;
190     const int kMaxInset = 20;
191     uint32_t width = random->nextULessThan(kMaxWidth);
192     uint32_t height = random->nextULessThan(kMaxHeight);
193     uint32_t x = random->nextULessThan(kMaxWidth - width);
194     uint32_t y = random->nextULessThan(kMaxHeight - height);
195     uint32_t inset = random->nextULessThan(kMaxInset);
196
197     GrEffectRef* effect = GrMagnifierEffect::Create(
198         texture,
199         (float) width / texture->width(),
200         (float) height / texture->height(),
201         texture->width() / (float) x,
202         texture->height() / (float) y,
203         (float) inset / texture->width(),
204         (float) inset / texture->height());
205     SkASSERT(NULL != effect);
206     return effect;
207 }
208
209 ///////////////////////////////////////////////////////////////////////////////
210
211 const GrBackendEffectFactory& GrMagnifierEffect::getFactory() const {
212     return GrTBackendEffectFactory<GrMagnifierEffect>::getInstance();
213 }
214
215 bool GrMagnifierEffect::onIsEqual(const GrEffect& sBase) const {
216     const GrMagnifierEffect& s = CastEffect<GrMagnifierEffect>(sBase);
217     return (this->texture(0) == s.texture(0) &&
218             this->fXOffset == s.fXOffset &&
219             this->fYOffset == s.fYOffset &&
220             this->fXZoom == s.fXZoom &&
221             this->fYZoom == s.fYZoom &&
222             this->fXInset == s.fXInset &&
223             this->fYInset == s.fYInset);
224 }
225
226 void GrMagnifierEffect::getConstantColorComponents(GrColor* color, uint32_t* validFlags) const {
227     this->updateConstantColorComponentsForModulation(color, validFlags);
228 }
229
230 #endif
231
232 ////////////////////////////////////////////////////////////////////////////////
233 SkMagnifierImageFilter::SkMagnifierImageFilter(SkFlattenableReadBuffer& buffer)
234   : INHERITED(buffer) {
235     float x = buffer.readScalar();
236     float y = buffer.readScalar();
237     float width = buffer.readScalar();
238     float height = buffer.readScalar();
239     fSrcRect = SkRect::MakeXYWH(x, y, width, height);
240     fInset = buffer.readScalar();
241 }
242
243 // FIXME:  implement single-input semantics
244 SkMagnifierImageFilter::SkMagnifierImageFilter(SkRect srcRect, SkScalar inset)
245     : INHERITED(0), fSrcRect(srcRect), fInset(inset) {
246     SkASSERT(srcRect.x() >= 0 && srcRect.y() >= 0 && inset >= 0);
247 }
248
249 #if SK_SUPPORT_GPU
250 bool SkMagnifierImageFilter::asNewEffect(GrEffectRef** effect, GrTexture* texture, const SkMatrix&, const SkIRect&) const {
251     if (effect) {
252         *effect = GrMagnifierEffect::Create(texture,
253                                             fSrcRect.x() / texture->width(),
254                                             fSrcRect.y() / texture->height(),
255                                             texture->width() / fSrcRect.width(),
256                                             texture->height() / fSrcRect.height(),
257                                             fInset / texture->width(),
258                                             fInset / texture->height());
259     }
260     return true;
261 }
262 #endif
263
264 void SkMagnifierImageFilter::flatten(SkFlattenableWriteBuffer& buffer) const {
265     this->INHERITED::flatten(buffer);
266     buffer.writeScalar(fSrcRect.x());
267     buffer.writeScalar(fSrcRect.y());
268     buffer.writeScalar(fSrcRect.width());
269     buffer.writeScalar(fSrcRect.height());
270     buffer.writeScalar(fInset);
271 }
272
273 bool SkMagnifierImageFilter::onFilterImage(Proxy*, const SkBitmap& src,
274                                            const SkMatrix&, SkBitmap* dst,
275                                            SkIPoint* offset) {
276     SkASSERT(src.config() == SkBitmap::kARGB_8888_Config);
277     SkASSERT(fSrcRect.width() < src.width());
278     SkASSERT(fSrcRect.height() < src.height());
279
280     if (src.config() != SkBitmap::kARGB_8888_Config) {
281       return false;
282     }
283
284     SkAutoLockPixels alp(src);
285     SkASSERT(src.getPixels());
286     if (!src.getPixels() || src.width() <= 0 || src.height() <= 0) {
287       return false;
288     }
289
290     SkScalar inv_inset = fInset > 0 ? SkScalarInvert(fInset) : SK_Scalar1;
291
292     SkScalar inv_x_zoom = fSrcRect.width() / src.width();
293     SkScalar inv_y_zoom = fSrcRect.height() / src.height();
294
295     dst->setConfig(src.config(), src.width(), src.height());
296     dst->allocPixels();
297     SkColor* sptr = src.getAddr32(0, 0);
298     SkColor* dptr = dst->getAddr32(0, 0);
299     int width = src.width(), height = src.height();
300     for (int y = 0; y < height; ++y) {
301         for (int x = 0; x < width; ++x) {
302             SkScalar x_dist = SkMin32(x, width - x - 1) * inv_inset;
303             SkScalar y_dist = SkMin32(y, height - y - 1) * inv_inset;
304             SkScalar weight = 0;
305
306             static const SkScalar kScalar2 = SkScalar(2);
307
308             // To create a smooth curve at the corners, we need to work on
309             // a square twice the size of the inset.
310             if (x_dist < kScalar2 && y_dist < kScalar2) {
311                 x_dist = kScalar2 - x_dist;
312                 y_dist = kScalar2 - y_dist;
313
314                 SkScalar dist = SkScalarSqrt(SkScalarSquare(x_dist) +
315                                              SkScalarSquare(y_dist));
316                 dist = SkMaxScalar(kScalar2 - dist, 0);
317                 weight = SkMinScalar(SkScalarSquare(dist), SK_Scalar1);
318             } else {
319                 SkScalar sqDist = SkMinScalar(SkScalarSquare(x_dist),
320                                               SkScalarSquare(y_dist));
321                 weight = SkMinScalar(sqDist, SK_Scalar1);
322             }
323
324             SkScalar x_interp = SkScalarMul(weight, (fSrcRect.x() + x * inv_x_zoom)) +
325                            (SK_Scalar1 - weight) * x;
326             SkScalar y_interp = SkScalarMul(weight, (fSrcRect.y() + y * inv_y_zoom)) +
327                            (SK_Scalar1 - weight) * y;
328
329             int x_val = SkMin32(SkScalarFloorToInt(x_interp), width - 1);
330             int y_val = SkMin32(SkScalarFloorToInt(y_interp), height - 1);
331
332             *dptr = sptr[y_val * width + x_val];
333             dptr++;
334         }
335     }
336     return true;
337 }