Remove DrawingMgr shims from GrContext
[platform/upstream/libSkiaSharp.git] / src / gpu / effects / GrConfigConversionEffect.cpp
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 "GrConfigConversionEffect.h"
9 #include "GrContext.h"
10 #include "GrDrawContext.h"
11 #include "GrInvariantOutput.h"
12 #include "GrSimpleTextureEffect.h"
13 #include "SkMatrix.h"
14 #include "gl/GrGLFragmentProcessor.h"
15 #include "gl/builders/GrGLProgramBuilder.h"
16
17 class GrGLConfigConversionEffect : public GrGLFragmentProcessor {
18 public:
19     GrGLConfigConversionEffect(const GrProcessor& processor) {
20         const GrConfigConversionEffect& configConversionEffect =
21                 processor.cast<GrConfigConversionEffect>();
22         fSwapRedAndBlue = configConversionEffect.swapsRedAndBlue();
23         fPMConversion = configConversionEffect.pmConversion();
24     }
25
26     virtual void emitCode(EmitArgs& args) override {
27         // Using highp for GLES here in order to avoid some precision issues on specific GPUs.
28         GrGLShaderVar tmpVar("tmpColor", kVec4f_GrSLType, 0, kHigh_GrSLPrecision);
29         SkString tmpDecl;
30         tmpVar.appendDecl(args.fBuilder->ctxInfo(), &tmpDecl);
31
32         GrGLFragmentBuilder* fsBuilder = args.fBuilder->getFragmentShaderBuilder();
33
34         fsBuilder->codeAppendf("%s;", tmpDecl.c_str());
35
36         fsBuilder->codeAppendf("%s = ", tmpVar.c_str());
37         fsBuilder->appendTextureLookup(args.fSamplers[0], args.fCoords[0].c_str(),
38                                        args.fCoords[0].getType());
39         fsBuilder->codeAppend(";");
40
41         if (GrConfigConversionEffect::kNone_PMConversion == fPMConversion) {
42             SkASSERT(fSwapRedAndBlue);
43             fsBuilder->codeAppendf("%s = %s.bgra;", args.fOutputColor, tmpVar.c_str());
44         } else {
45             const char* swiz = fSwapRedAndBlue ? "bgr" : "rgb";
46             switch (fPMConversion) {
47                 case GrConfigConversionEffect::kMulByAlpha_RoundUp_PMConversion:
48                     fsBuilder->codeAppendf(
49                         "%s = vec4(ceil(%s.%s * %s.a * 255.0) / 255.0, %s.a);",
50                         tmpVar.c_str(), tmpVar.c_str(), swiz, tmpVar.c_str(), tmpVar.c_str());
51                     break;
52                 case GrConfigConversionEffect::kMulByAlpha_RoundDown_PMConversion:
53                     // Add a compensation(0.001) here to avoid the side effect of the floor operation.
54                     // In Intel GPUs, the integer value converted from floor(%s.r * 255.0) / 255.0
55                     // is less than the integer value converted from  %s.r by 1 when the %s.r is
56                     // converted from the integer value 2^n, such as 1, 2, 4, 8, etc.
57                     fsBuilder->codeAppendf(
58                         "%s = vec4(floor(%s.%s * %s.a * 255.0 + 0.001) / 255.0, %s.a);",
59                         tmpVar.c_str(), tmpVar.c_str(), swiz, tmpVar.c_str(), tmpVar.c_str());
60                     break;
61                 case GrConfigConversionEffect::kDivByAlpha_RoundUp_PMConversion:
62                     fsBuilder->codeAppendf(
63                         "%s = %s.a <= 0.0 ? vec4(0,0,0,0) : vec4(ceil(%s.%s / %s.a * 255.0) / 255.0, %s.a);",
64                         tmpVar.c_str(), tmpVar.c_str(), tmpVar.c_str(), swiz, tmpVar.c_str(), tmpVar.c_str());
65                     break;
66                 case GrConfigConversionEffect::kDivByAlpha_RoundDown_PMConversion:
67                     fsBuilder->codeAppendf(
68                         "%s = %s.a <= 0.0 ? vec4(0,0,0,0) : vec4(floor(%s.%s / %s.a * 255.0) / 255.0, %s.a);",
69                         tmpVar.c_str(), tmpVar.c_str(), tmpVar.c_str(), swiz, tmpVar.c_str(), tmpVar.c_str());
70                     break;
71                 default:
72                     SkFAIL("Unknown conversion op.");
73                     break;
74             }
75             fsBuilder->codeAppendf("%s = %s;", args.fOutputColor, tmpVar.c_str());
76         }
77         SkString modulate;
78         GrGLSLMulVarBy4f(&modulate, args.fOutputColor, args.fInputColor);
79         fsBuilder->codeAppend(modulate.c_str());
80     }
81
82     static inline void GenKey(const GrProcessor& processor, const GrGLSLCaps&,
83                               GrProcessorKeyBuilder* b) {
84         const GrConfigConversionEffect& conv = processor.cast<GrConfigConversionEffect>();
85         uint32_t key = (conv.swapsRedAndBlue() ? 0 : 1) | (conv.pmConversion() << 1);
86         b->add32(key);
87     }
88
89 private:
90     bool                                    fSwapRedAndBlue;
91     GrConfigConversionEffect::PMConversion  fPMConversion;
92
93     typedef GrGLFragmentProcessor INHERITED;
94
95 };
96
97 ///////////////////////////////////////////////////////////////////////////////
98
99 GrConfigConversionEffect::GrConfigConversionEffect(GrTexture* texture,
100                                                    bool swapRedAndBlue,
101                                                    PMConversion pmConversion,
102                                                    const SkMatrix& matrix)
103     : INHERITED(texture, matrix)
104     , fSwapRedAndBlue(swapRedAndBlue)
105     , fPMConversion(pmConversion) {
106     this->initClassID<GrConfigConversionEffect>();
107     // We expect to get here with non-BGRA/RGBA only if we're doing not doing a premul/unpremul
108     // conversion.
109     SkASSERT((kRGBA_8888_GrPixelConfig == texture->config() ||
110               kBGRA_8888_GrPixelConfig == texture->config()) ||
111               kNone_PMConversion == pmConversion);
112     // Why did we pollute our texture cache instead of using a GrSingleTextureEffect?
113     SkASSERT(swapRedAndBlue || kNone_PMConversion != pmConversion);
114 }
115
116 bool GrConfigConversionEffect::onIsEqual(const GrFragmentProcessor& s) const {
117     const GrConfigConversionEffect& other = s.cast<GrConfigConversionEffect>();
118     return other.fSwapRedAndBlue == fSwapRedAndBlue &&
119            other.fPMConversion == fPMConversion;
120 }
121
122 void GrConfigConversionEffect::onComputeInvariantOutput(GrInvariantOutput* inout) const {
123     this->updateInvariantOutputForModulation(inout);
124 }
125
126 ///////////////////////////////////////////////////////////////////////////////
127
128 GR_DEFINE_FRAGMENT_PROCESSOR_TEST(GrConfigConversionEffect);
129
130 const GrFragmentProcessor* GrConfigConversionEffect::TestCreate(GrProcessorTestData* d) {
131     PMConversion pmConv = static_cast<PMConversion>(d->fRandom->nextULessThan(kPMConversionCnt));
132     bool swapRB;
133     if (kNone_PMConversion == pmConv) {
134         swapRB = true;
135     } else {
136         swapRB = d->fRandom->nextBool();
137     }
138     return new GrConfigConversionEffect(d->fTextures[GrProcessorUnitTest::kSkiaPMTextureIdx],
139                                         swapRB, pmConv, GrTest::TestMatrix(d->fRandom));
140 }
141
142 ///////////////////////////////////////////////////////////////////////////////
143
144 void GrConfigConversionEffect::onGetGLProcessorKey(const GrGLSLCaps& caps,
145                                                  GrProcessorKeyBuilder* b) const {
146     GrGLConfigConversionEffect::GenKey(*this, caps, b);
147 }
148
149 GrGLFragmentProcessor* GrConfigConversionEffect::onCreateGLInstance() const {
150     return new GrGLConfigConversionEffect(*this);
151 }
152
153
154
155 void GrConfigConversionEffect::TestForPreservingPMConversions(GrContext* context,
156                                                               PMConversion* pmToUPMRule,
157                                                               PMConversion* upmToPMRule) {
158     *pmToUPMRule = kNone_PMConversion;
159     *upmToPMRule = kNone_PMConversion;
160     SkAutoTMalloc<uint32_t> data(256 * 256 * 3);
161     uint32_t* srcData = data.get();
162     uint32_t* firstRead = data.get() + 256 * 256;
163     uint32_t* secondRead = data.get() + 2 * 256 * 256;
164
165     // Fill with every possible premultiplied A, color channel value. There will be 256-y duplicate
166     // values in row y. We set r,g, and b to the same value since they are handled identically.
167     for (int y = 0; y < 256; ++y) {
168         for (int x = 0; x < 256; ++x) {
169             uint8_t* color = reinterpret_cast<uint8_t*>(&srcData[256*y + x]);
170             color[3] = y;
171             color[2] = SkTMin(x, y);
172             color[1] = SkTMin(x, y);
173             color[0] = SkTMin(x, y);
174         }
175     }
176
177     GrSurfaceDesc desc;
178     desc.fFlags = kRenderTarget_GrSurfaceFlag;
179     desc.fWidth = 256;
180     desc.fHeight = 256;
181     desc.fConfig = kRGBA_8888_GrPixelConfig;
182
183     SkAutoTUnref<GrTexture> readTex(context->textureProvider()->createTexture(desc, true, nullptr, 0));
184     if (!readTex.get()) {
185         return;
186     }
187     SkAutoTUnref<GrTexture> tempTex(context->textureProvider()->createTexture(desc, true, nullptr, 0));
188     if (!tempTex.get()) {
189         return;
190     }
191     desc.fFlags = kNone_GrSurfaceFlags;
192     SkAutoTUnref<GrTexture> dataTex(context->textureProvider()->createTexture(desc, true, data, 0));
193     if (!dataTex.get()) {
194         return;
195     }
196
197     static const PMConversion kConversionRules[][2] = {
198         {kDivByAlpha_RoundDown_PMConversion, kMulByAlpha_RoundUp_PMConversion},
199         {kDivByAlpha_RoundUp_PMConversion, kMulByAlpha_RoundDown_PMConversion},
200     };
201
202     bool failed = true;
203
204     for (size_t i = 0; i < SK_ARRAY_COUNT(kConversionRules) && failed; ++i) {
205         *pmToUPMRule = kConversionRules[i][0];
206         *upmToPMRule = kConversionRules[i][1];
207
208         static const SkRect kDstRect = SkRect::MakeWH(SkIntToScalar(256), SkIntToScalar(256));
209         static const SkRect kSrcRect = SkRect::MakeWH(SK_Scalar1, SK_Scalar1);
210         // We do a PM->UPM draw from dataTex to readTex and read the data. Then we do a UPM->PM draw
211         // from readTex to tempTex followed by a PM->UPM draw to readTex and finally read the data.
212         // We then verify that two reads produced the same values.
213
214         GrPaint paint1;
215         GrPaint paint2;
216         GrPaint paint3;
217         SkAutoTUnref<GrFragmentProcessor> pmToUPM1(new GrConfigConversionEffect(
218                 dataTex, false, *pmToUPMRule, SkMatrix::I()));
219         SkAutoTUnref<GrFragmentProcessor> upmToPM(new GrConfigConversionEffect(
220                 readTex, false, *upmToPMRule, SkMatrix::I()));
221         SkAutoTUnref<GrFragmentProcessor> pmToUPM2(new GrConfigConversionEffect(
222                 tempTex, false, *pmToUPMRule, SkMatrix::I()));
223
224         paint1.addColorFragmentProcessor(pmToUPM1);
225
226
227         SkAutoTUnref<GrDrawContext> readDrawContext(
228                                     context->drawContext(readTex->asRenderTarget()));
229         if (!readDrawContext) {
230             failed = true;
231             break;
232         }
233
234         readDrawContext->drawNonAARectToRect(GrClip::WideOpen(),
235                                              paint1,
236                                              SkMatrix::I(),
237                                              kDstRect,
238                                              kSrcRect);
239
240         readTex->readPixels(0, 0, 256, 256, kRGBA_8888_GrPixelConfig, firstRead);
241
242         paint2.addColorFragmentProcessor(upmToPM);
243
244         SkAutoTUnref<GrDrawContext> tempDrawContext(
245                                     context->drawContext(tempTex->asRenderTarget()));
246         if (!tempDrawContext) {
247             failed = true;
248             break;
249         }
250         tempDrawContext->drawNonAARectToRect(GrClip::WideOpen(),
251                                              paint2,
252                                              SkMatrix::I(),
253                                              kDstRect,
254                                              kSrcRect);
255
256         paint3.addColorFragmentProcessor(pmToUPM2);
257
258         readDrawContext.reset(context->drawContext(readTex->asRenderTarget()));
259         if (!readDrawContext) {
260             failed = true;
261             break;
262         }
263
264         readDrawContext->drawNonAARectToRect(GrClip::WideOpen(),
265                                              paint3,
266                                              SkMatrix::I(),
267                                              kDstRect,
268                                              kSrcRect);
269
270         readTex->readPixels(0, 0, 256, 256, kRGBA_8888_GrPixelConfig, secondRead);
271
272         failed = false;
273         for (int y = 0; y < 256 && !failed; ++y) {
274             for (int x = 0; x <= y; ++x) {
275                 if (firstRead[256 * y + x] != secondRead[256 * y + x]) {
276                     failed = true;
277                     break;
278                 }
279             }
280         }
281     }
282     if (failed) {
283         *pmToUPMRule = kNone_PMConversion;
284         *upmToPMRule = kNone_PMConversion;
285     }
286 }
287
288 const GrFragmentProcessor* GrConfigConversionEffect::Create(GrTexture* texture,
289                                                             bool swapRedAndBlue,
290                                                             PMConversion pmConversion,
291                                                             const SkMatrix& matrix) {
292     if (!swapRedAndBlue && kNone_PMConversion == pmConversion) {
293         // If we returned a GrConfigConversionEffect that was equivalent to a GrSimpleTextureEffect
294         // then we may pollute our texture cache with redundant shaders. So in the case that no
295         // conversions were requested we instead return a GrSimpleTextureEffect.
296         return GrSimpleTextureEffect::Create(texture, matrix);
297     } else {
298         if (kRGBA_8888_GrPixelConfig != texture->config() &&
299             kBGRA_8888_GrPixelConfig != texture->config() &&
300             kNone_PMConversion != pmConversion) {
301             // The PM conversions assume colors are 0..255
302             return nullptr;
303         }
304         return new GrConfigConversionEffect(texture, swapRedAndBlue, pmConversion, matrix);
305     }
306 }