GrTextureDomain.cpp revision b5fb5af5734dcc31a5e29212db39f0da71f92f2d
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/GrGLFragmentProcessor.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("%s = ", outColor);
68            builder->appendTextureLookupAndModulate(inModulateColor, sampler,
69                                                      inCoords.c_str());
70            builder->codeAppend(";");
71            break;
72        }
73        case kClamp_Mode: {
74            SkString clampedCoords;
75            clampedCoords.appendf("clamp(%s, %s.xy, %s.zw)",
76                                  inCoords.c_str(), fDomainName.c_str(), fDomainName.c_str());
77
78            builder->codeAppendf("%s = ", outColor);
79            builder->appendTextureLookupAndModulate(inModulateColor, sampler,
80                                                      clampedCoords.c_str());
81            builder->codeAppend(";");
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("vec4 outside = vec4(0.0, 0.0, 0.0, 0.0);");
97                builder->codeAppend("vec4 inside = ");
98                builder->appendTextureLookupAndModulate(inModulateColor, sampler,
99                                                          inCoords.c_str());
100                builder->codeAppend(";");
101
102                builder->codeAppend(GrGLShaderVar::PrecisionString(kHigh_GrSLPrecision,
103                                                                   program->ctxInfo().standard()));
104                builder->codeAppendf("float x = (%s).x;", inCoords.c_str());
105                builder->codeAppend(GrGLShaderVar::PrecisionString(kHigh_GrSLPrecision,
106                                                                   program->ctxInfo().standard()));
107                builder->codeAppendf("float y = (%s).y;", inCoords.c_str());
108
109                builder->codeAppendf("x = abs(2.0*(x - %s.x)/(%s.z - %s.x) - 1.0);",
110                                     domain, domain, domain);
111                builder->codeAppendf("y = abs(2.0*(y - %s.y)/(%s.w - %s.y) - 1.0);",
112                                     domain, domain, domain);
113                builder->codeAppend("float blend = step(1.0, max(x, y));");
114                builder->codeAppendf("%s = mix(inside, outside, blend);", outColor);
115            } else {
116                builder->codeAppend("bvec4 outside;\n");
117                builder->codeAppendf("outside.xy = lessThan(%s, %s.xy);", inCoords.c_str(),
118                                       domain);
119                builder->codeAppendf("outside.zw = greaterThan(%s, %s.zw);", inCoords.c_str(),
120                                       domain);
121                builder->codeAppendf("%s = any(outside) ? vec4(0.0, 0.0, 0.0, 0.0) : ",
122                                       outColor);
123                builder->appendTextureLookupAndModulate(inModulateColor, sampler,
124                                                          inCoords.c_str());
125                builder->codeAppend(";");
126            }
127            break;
128        }
129        case kRepeat_Mode: {
130            SkString clampedCoords;
131            clampedCoords.printf("mod(%s - %s.xy, %s.zw - %s.xy) + %s.xy",
132                                 inCoords.c_str(), fDomainName.c_str(), fDomainName.c_str(),
133                                 fDomainName.c_str(), fDomainName.c_str());
134
135            builder->codeAppendf("%s = ", outColor);
136            builder->appendTextureLookupAndModulate(inModulateColor, sampler,
137                                                      clampedCoords.c_str());
138            builder->codeAppend(";");
139            break;
140        }
141    }
142}
143
144void GrTextureDomain::GLDomain::setData(const GrGLProgramDataManager& pdman,
145                                        const GrTextureDomain& textureDomain,
146                                        GrSurfaceOrigin textureOrigin) {
147    SkASSERT(textureDomain.mode() == fMode);
148    if (kIgnore_Mode != textureDomain.mode()) {
149        GrGLfloat values[kPrevDomainCount] = {
150            SkScalarToFloat(textureDomain.domain().left()),
151            SkScalarToFloat(textureDomain.domain().top()),
152            SkScalarToFloat(textureDomain.domain().right()),
153            SkScalarToFloat(textureDomain.domain().bottom())
154        };
155        // vertical flip if necessary
156        if (kBottomLeft_GrSurfaceOrigin == textureOrigin) {
157            values[1] = 1.0f - values[1];
158            values[3] = 1.0f - values[3];
159            // The top and bottom were just flipped, so correct the ordering
160            // of elements so that values = (l, t, r, b).
161            SkTSwap(values[1], values[3]);
162        }
163        if (0 != memcmp(values, fPrevDomain, kPrevDomainCount * sizeof(GrGLfloat))) {
164            pdman.set4fv(fDomainUni, 1, values);
165            memcpy(fPrevDomain, values, kPrevDomainCount * sizeof(GrGLfloat));
166        }
167    }
168}
169
170
171//////////////////////////////////////////////////////////////////////////////
172
173class GrGLTextureDomainEffect : public GrGLFragmentProcessor {
174public:
175    GrGLTextureDomainEffect(const GrProcessor&);
176
177    virtual void emitCode(EmitArgs&) override;
178
179    static inline void GenKey(const GrProcessor&, const GrGLSLCaps&, GrProcessorKeyBuilder*);
180
181protected:
182    void onSetData(const GrGLProgramDataManager&, const GrProcessor&) override;
183
184private:
185    GrTextureDomain::GLDomain         fGLDomain;
186    typedef GrGLFragmentProcessor INHERITED;
187};
188
189GrGLTextureDomainEffect::GrGLTextureDomainEffect(const GrProcessor&) {
190}
191
192void GrGLTextureDomainEffect::emitCode(EmitArgs& args) {
193    const GrTextureDomainEffect& textureDomainEffect = args.fFp.cast<GrTextureDomainEffect>();
194    const GrTextureDomain& domain = textureDomainEffect.textureDomain();
195
196    GrGLFragmentBuilder* fsBuilder = args.fBuilder->getFragmentShaderBuilder();
197    SkString coords2D = fsBuilder->ensureFSCoords2D(args.fCoords, 0);
198    fGLDomain.sampleTexture(fsBuilder, domain, args.fOutputColor, coords2D, args.fSamplers[0],
199                            args.fInputColor);
200}
201
202void GrGLTextureDomainEffect::onSetData(const GrGLProgramDataManager& pdman,
203                                      const GrProcessor& processor) {
204    const GrTextureDomainEffect& textureDomainEffect = processor.cast<GrTextureDomainEffect>();
205    const GrTextureDomain& domain = textureDomainEffect.textureDomain();
206    fGLDomain.setData(pdman, domain, processor.texture(0)->origin());
207}
208
209void GrGLTextureDomainEffect::GenKey(const GrProcessor& processor, const GrGLSLCaps&,
210                                     GrProcessorKeyBuilder* b) {
211    const GrTextureDomain& domain = processor.cast<GrTextureDomainEffect>().textureDomain();
212    b->add32(GrTextureDomain::GLDomain::DomainKey(domain));
213}
214
215
216///////////////////////////////////////////////////////////////////////////////
217
218GrFragmentProcessor* GrTextureDomainEffect::Create(GrProcessorDataManager* procDataManager,
219                                                   GrTexture* texture,
220                                                   const SkMatrix& matrix,
221                                                   const SkRect& domain,
222                                                   GrTextureDomain::Mode mode,
223                                                   GrTextureParams::FilterMode filterMode,
224                                                   GrCoordSet coordSet) {
225    static const SkRect kFullRect = {0, 0, SK_Scalar1, SK_Scalar1};
226    if (GrTextureDomain::kIgnore_Mode == mode ||
227        (GrTextureDomain::kClamp_Mode == mode && domain.contains(kFullRect))) {
228        return GrSimpleTextureEffect::Create(procDataManager, texture, matrix, filterMode);
229    } else {
230
231        return SkNEW_ARGS(GrTextureDomainEffect, (procDataManager,
232                                                  texture,
233                                                  matrix,
234                                                  domain,
235                                                  mode,
236                                                  filterMode,
237                                                  coordSet));
238    }
239}
240
241GrTextureDomainEffect::GrTextureDomainEffect(GrProcessorDataManager* procDataManager,
242                                             GrTexture* texture,
243                                             const SkMatrix& matrix,
244                                             const SkRect& domain,
245                                             GrTextureDomain::Mode mode,
246                                             GrTextureParams::FilterMode filterMode,
247                                             GrCoordSet coordSet)
248    : GrSingleTextureEffect(procDataManager, 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::onGetGLProcessorKey(const GrGLSLCaps& caps,
260                                              GrProcessorKeyBuilder* b) const {
261    GrGLTextureDomainEffect::GenKey(*this, caps, b);
262}
263
264GrGLFragmentProcessor* GrTextureDomainEffect::onCreateGLInstance() 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(GrProcessorTestData* d) {
290    int texIdx = d->fRandom->nextBool() ? GrProcessorUnitTest::kSkiaPMTextureIdx :
291                                          GrProcessorUnitTest::kAlphaTextureIdx;
292    SkRect domain;
293    domain.fLeft = d->fRandom->nextUScalar1();
294    domain.fRight = d->fRandom->nextRangeScalar(domain.fLeft, SK_Scalar1);
295    domain.fTop = d->fRandom->nextUScalar1();
296    domain.fBottom = d->fRandom->nextRangeScalar(domain.fTop, SK_Scalar1);
297    GrTextureDomain::Mode mode =
298        (GrTextureDomain::Mode) d->fRandom->nextULessThan(GrTextureDomain::kModeCount);
299    const SkMatrix& matrix = GrTest::TestMatrix(d->fRandom);
300    bool bilerp = mode != GrTextureDomain::kRepeat_Mode ? d->fRandom->nextBool() : false;
301    GrCoordSet coords = d->fRandom->nextBool() ? kLocal_GrCoordSet : kDevice_GrCoordSet;
302    return GrTextureDomainEffect::Create(d->fProcDataManager,
303                                         d->fTextures[texIdx],
304                                         matrix,
305                                         domain,
306                                         mode,
307                                         bilerp ? GrTextureParams::kBilerp_FilterMode : GrTextureParams::kNone_FilterMode,
308                                         coords);
309}
310