1/*
2 * Copyright 2012 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 "GrTextureDomain.h"
9#include "GrInvariantOutput.h"
10#include "GrSimpleTextureEffect.h"
11#include "SkFloatingPoint.h"
12#include "gl/GrGLProcessor.h"
13#include "gl/builders/GrGLProgramBuilder.h"
14
15GrTextureDomain::GrTextureDomain(const SkRect& domain, Mode mode, int index)
16    : fIndex(index) {
17
18    static const SkRect kFullRect = {0, 0, SK_Scalar1, SK_Scalar1};
19    if (domain.contains(kFullRect) && kClamp_Mode == mode) {
20        fMode = kIgnore_Mode;
21    } else {
22        fMode = mode;
23    }
24
25    if (fMode != kIgnore_Mode) {
26        // We don't currently handle domains that are empty or don't intersect the texture.
27        // It is OK if the domain rect is a line or point, but it should not be inverted. We do not
28        // handle rects that do not intersect the [0..1]x[0..1] rect.
29        SkASSERT(domain.fLeft <= domain.fRight);
30        SkASSERT(domain.fTop <= domain.fBottom);
31        fDomain.fLeft = SkScalarPin(domain.fLeft, kFullRect.fLeft, kFullRect.fRight);
32        fDomain.fRight = SkScalarPin(domain.fRight, kFullRect.fLeft, kFullRect.fRight);
33        fDomain.fTop = SkScalarPin(domain.fTop, kFullRect.fTop, kFullRect.fBottom);
34        fDomain.fBottom = SkScalarPin(domain.fBottom, kFullRect.fTop, kFullRect.fBottom);
35        SkASSERT(fDomain.fLeft <= fDomain.fRight);
36        SkASSERT(fDomain.fTop <= fDomain.fBottom);
37    }
38}
39
40//////////////////////////////////////////////////////////////////////////////
41
42void GrTextureDomain::GLDomain::sampleTexture(GrGLShaderBuilder* builder,
43                                              const GrTextureDomain& textureDomain,
44                                              const char* outColor,
45                                              const SkString& inCoords,
46                                              const GrGLProcessor::TextureSampler sampler,
47                                              const char* inModulateColor) {
48    SkASSERT((Mode)-1 == fMode || textureDomain.mode() == fMode);
49    SkDEBUGCODE(fMode = textureDomain.mode();)
50
51    GrGLProgramBuilder* program = builder->getProgramBuilder();
52
53    if (textureDomain.mode() != kIgnore_Mode && !fDomainUni.isValid()) {
54        const char* name;
55        SkString uniName("TexDom");
56        if (textureDomain.fIndex >= 0) {
57            uniName.appendS32(textureDomain.fIndex);
58        }
59        fDomainUni = program->addUniform(GrGLProgramBuilder::kFragment_Visibility,
60                                         kVec4f_GrSLType, kDefault_GrSLPrecision,
61                                         uniName.c_str(), &name);
62        fDomainName = name;
63    }
64
65    switch (textureDomain.mode()) {
66        case kIgnore_Mode: {
67            builder->codeAppendf("\t%s = ", outColor);
68            builder->appendTextureLookupAndModulate(inModulateColor, sampler,
69                                                      inCoords.c_str());
70            builder->codeAppend(";\n");
71            break;
72        }
73        case kClamp_Mode: {
74            SkString clampedCoords;
75            clampedCoords.appendf("\tclamp(%s, %s.xy, %s.zw)",
76                                  inCoords.c_str(), fDomainName.c_str(), fDomainName.c_str());
77
78            builder->codeAppendf("\t%s = ", outColor);
79            builder->appendTextureLookupAndModulate(inModulateColor, sampler,
80                                                      clampedCoords.c_str());
81            builder->codeAppend(";\n");
82            break;
83        }
84        case kDecal_Mode: {
85            // Add a block since we're going to declare variables.
86            GrGLShaderBuilder::ShaderBlock block(builder);
87
88            const char* domain = fDomainName.c_str();
89            if (kImagination_GrGLVendor == program->ctxInfo().vendor()) {
90                // On the NexusS and GalaxyNexus, the other path (with the 'any'
91                // call) causes the compilation error "Calls to any function that
92                // may require a gradient calculation inside a conditional block
93                // may return undefined results". This appears to be an issue with
94                // the 'any' call since even the simple "result=black; if (any())
95                // result=white;" code fails to compile.
96                builder->codeAppend("\tvec4 outside = vec4(0.0, 0.0, 0.0, 0.0);\n");
97                builder->codeAppend("\tvec4 inside = ");
98                builder->appendTextureLookupAndModulate(inModulateColor, sampler,
99                                                          inCoords.c_str());
100                builder->codeAppend(";\n");
101                builder->codeAppendf("\tfloat x = (%s).x;\n", inCoords.c_str());
102                builder->codeAppendf("\tfloat y = (%s).y;\n", inCoords.c_str());
103
104                builder->codeAppendf("\tx = abs(2.0*(x - %s.x)/(%s.z - %s.x) - 1.0);\n",
105                                       domain, domain, domain);
106                builder->codeAppendf("\ty = abs(2.0*(y - %s.y)/(%s.w - %s.y) - 1.0);\n",
107                                       domain, domain, domain);
108                builder->codeAppend("\tfloat blend = step(1.0, max(x, y));\n");
109                builder->codeAppendf("\t%s = mix(inside, outside, blend);\n", outColor);
110            } else {
111                builder->codeAppend("\tbvec4 outside;\n");
112                builder->codeAppendf("\toutside.xy = lessThan(%s, %s.xy);\n", inCoords.c_str(),
113                                       domain);
114                builder->codeAppendf("\toutside.zw = greaterThan(%s, %s.zw);\n", inCoords.c_str(),
115                                       domain);
116                builder->codeAppendf("\t%s = any(outside) ? vec4(0.0, 0.0, 0.0, 0.0) : ",
117                                       outColor);
118                builder->appendTextureLookupAndModulate(inModulateColor, sampler,
119                                                          inCoords.c_str());
120                builder->codeAppend(";\n");
121            }
122            break;
123        }
124        case kRepeat_Mode: {
125            SkString clampedCoords;
126            clampedCoords.printf("\tmod(%s - %s.xy, %s.zw - %s.xy) + %s.xy",
127                                 inCoords.c_str(), fDomainName.c_str(), fDomainName.c_str(),
128                                 fDomainName.c_str(), fDomainName.c_str());
129
130            builder->codeAppendf("\t%s = ", outColor);
131            builder->appendTextureLookupAndModulate(inModulateColor, sampler,
132                                                      clampedCoords.c_str());
133            builder->codeAppend(";\n");
134            break;
135        }
136    }
137}
138
139void GrTextureDomain::GLDomain::setData(const GrGLProgramDataManager& pdman,
140                                        const GrTextureDomain& textureDomain,
141                                        GrSurfaceOrigin textureOrigin) {
142    SkASSERT(textureDomain.mode() == fMode);
143    if (kIgnore_Mode != textureDomain.mode()) {
144        GrGLfloat values[4] = {
145            SkScalarToFloat(textureDomain.domain().left()),
146            SkScalarToFloat(textureDomain.domain().top()),
147            SkScalarToFloat(textureDomain.domain().right()),
148            SkScalarToFloat(textureDomain.domain().bottom())
149        };
150        // vertical flip if necessary
151        if (kBottomLeft_GrSurfaceOrigin == textureOrigin) {
152            values[1] = 1.0f - values[1];
153            values[3] = 1.0f - values[3];
154            // The top and bottom were just flipped, so correct the ordering
155            // of elements so that values = (l, t, r, b).
156            SkTSwap(values[1], values[3]);
157        }
158        if (0 != memcmp(values, fPrevDomain, 4 * sizeof(GrGLfloat))) {
159            pdman.set4fv(fDomainUni, 1, values);
160            memcpy(fPrevDomain, values, 4 * sizeof(GrGLfloat));
161        }
162    }
163}
164
165
166//////////////////////////////////////////////////////////////////////////////
167
168class GrGLTextureDomainEffect : public GrGLFragmentProcessor {
169public:
170    GrGLTextureDomainEffect(const GrProcessor&);
171
172    virtual void emitCode(GrGLFPBuilder*,
173                          const GrFragmentProcessor&,
174                          const char* outputColor,
175                          const char* inputColor,
176                          const TransformedCoordsArray&,
177                          const TextureSamplerArray&) override;
178
179    void setData(const GrGLProgramDataManager&, const GrProcessor&) override;
180
181    static inline void GenKey(const GrProcessor&, const GrGLSLCaps&, GrProcessorKeyBuilder*);
182
183private:
184    GrTextureDomain::GLDomain         fGLDomain;
185    typedef GrGLFragmentProcessor INHERITED;
186};
187
188GrGLTextureDomainEffect::GrGLTextureDomainEffect(const GrProcessor&) {
189}
190
191void GrGLTextureDomainEffect::emitCode(GrGLFPBuilder* builder,
192                                       const GrFragmentProcessor& fp,
193                                       const char* outputColor,
194                                       const char* inputColor,
195                                       const TransformedCoordsArray& coords,
196                                       const TextureSamplerArray& samplers) {
197    const GrTextureDomainEffect& textureDomainEffect = fp.cast<GrTextureDomainEffect>();
198    const GrTextureDomain& domain = textureDomainEffect.textureDomain();
199
200    GrGLFragmentBuilder* fsBuilder = builder->getFragmentShaderBuilder();
201    SkString coords2D = fsBuilder->ensureFSCoords2D(coords, 0);
202    fGLDomain.sampleTexture(fsBuilder, domain, outputColor, coords2D, samplers[0], inputColor);
203}
204
205void GrGLTextureDomainEffect::setData(const GrGLProgramDataManager& pdman,
206                                      const GrProcessor& processor) {
207    const GrTextureDomainEffect& textureDomainEffect = processor.cast<GrTextureDomainEffect>();
208    const GrTextureDomain& domain = textureDomainEffect.textureDomain();
209    fGLDomain.setData(pdman, domain, processor.texture(0)->origin());
210}
211
212void GrGLTextureDomainEffect::GenKey(const GrProcessor& processor, const GrGLSLCaps&,
213                                     GrProcessorKeyBuilder* b) {
214    const GrTextureDomain& domain = processor.cast<GrTextureDomainEffect>().textureDomain();
215    b->add32(GrTextureDomain::GLDomain::DomainKey(domain));
216}
217
218
219///////////////////////////////////////////////////////////////////////////////
220
221GrFragmentProcessor* GrTextureDomainEffect::Create(GrTexture* texture,
222                                                   const SkMatrix& matrix,
223                                                   const SkRect& domain,
224                                                   GrTextureDomain::Mode mode,
225                                                   GrTextureParams::FilterMode filterMode,
226                                                   GrCoordSet coordSet) {
227    static const SkRect kFullRect = {0, 0, SK_Scalar1, SK_Scalar1};
228    if (GrTextureDomain::kIgnore_Mode == mode ||
229        (GrTextureDomain::kClamp_Mode == mode && domain.contains(kFullRect))) {
230        return GrSimpleTextureEffect::Create(texture, matrix, filterMode);
231    } else {
232
233        return SkNEW_ARGS(GrTextureDomainEffect, (texture,
234                                                  matrix,
235                                                  domain,
236                                                  mode,
237                                                  filterMode,
238                                                  coordSet));
239    }
240}
241
242GrTextureDomainEffect::GrTextureDomainEffect(GrTexture* texture,
243                                             const SkMatrix& matrix,
244                                             const SkRect& domain,
245                                             GrTextureDomain::Mode mode,
246                                             GrTextureParams::FilterMode filterMode,
247                                             GrCoordSet coordSet)
248    : GrSingleTextureEffect(texture, matrix, filterMode, coordSet)
249    , fTextureDomain(domain, mode) {
250    SkASSERT(mode != GrTextureDomain::kRepeat_Mode ||
251            filterMode == GrTextureParams::kNone_FilterMode);
252    this->initClassID<GrTextureDomainEffect>();
253}
254
255GrTextureDomainEffect::~GrTextureDomainEffect() {
256
257}
258
259void GrTextureDomainEffect::getGLProcessorKey(const GrGLSLCaps& caps,
260                                              GrProcessorKeyBuilder* b) const {
261    GrGLTextureDomainEffect::GenKey(*this, caps, b);
262}
263
264GrGLFragmentProcessor* GrTextureDomainEffect::createGLInstance() const  {
265    return SkNEW_ARGS(GrGLTextureDomainEffect, (*this));
266}
267
268bool GrTextureDomainEffect::onIsEqual(const GrFragmentProcessor& sBase) const {
269    const GrTextureDomainEffect& s = sBase.cast<GrTextureDomainEffect>();
270    return this->fTextureDomain == s.fTextureDomain;
271}
272
273void GrTextureDomainEffect::onComputeInvariantOutput(GrInvariantOutput* inout) const {
274    if (GrTextureDomain::kDecal_Mode == fTextureDomain.mode()) { // TODO: helper
275        if (GrPixelConfigIsAlphaOnly(this->texture(0)->config())) {
276            inout->mulByUnknownSingleComponent();
277        } else {
278            inout->mulByUnknownFourComponents();
279        }
280    } else {
281        this->updateInvariantOutputForModulation(inout);
282    }
283}
284
285///////////////////////////////////////////////////////////////////////////////
286
287GR_DEFINE_FRAGMENT_PROCESSOR_TEST(GrTextureDomainEffect);
288
289GrFragmentProcessor* GrTextureDomainEffect::TestCreate(SkRandom* random,
290                                                       GrContext*,
291                                                       const GrDrawTargetCaps&,
292                                                       GrTexture* textures[]) {
293    int texIdx = random->nextBool() ? GrProcessorUnitTest::kSkiaPMTextureIdx :
294                                      GrProcessorUnitTest::kAlphaTextureIdx;
295    SkRect domain;
296    domain.fLeft = random->nextUScalar1();
297    domain.fRight = random->nextRangeScalar(domain.fLeft, SK_Scalar1);
298    domain.fTop = random->nextUScalar1();
299    domain.fBottom = random->nextRangeScalar(domain.fTop, SK_Scalar1);
300    GrTextureDomain::Mode mode =
301        (GrTextureDomain::Mode) random->nextULessThan(GrTextureDomain::kModeCount);
302    const SkMatrix& matrix = GrTest::TestMatrix(random);
303    bool bilerp = mode != GrTextureDomain::kRepeat_Mode ? random->nextBool() : false;
304    GrCoordSet coords = random->nextBool() ? kLocal_GrCoordSet : kDevice_GrCoordSet;
305    return GrTextureDomainEffect::Create(textures[texIdx],
306                                         matrix,
307                                         domain,
308                                         mode,
309                                         bilerp ? GrTextureParams::kBilerp_FilterMode : GrTextureParams::kNone_FilterMode,
310                                         coords);
311}
312