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