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