• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2018 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 "src/gpu/gradients/GrGradientShader.h"
9 
10 #include "src/gpu/gradients/generated/GrClampedGradientEffect.h"
11 #include "src/gpu/gradients/generated/GrTiledGradientEffect.h"
12 
13 #include "src/gpu/gradients/generated/GrLinearGradientLayout.h"
14 #include "src/gpu/gradients/generated/GrRadialGradientLayout.h"
15 #include "src/gpu/gradients/generated/GrSweepGradientLayout.h"
16 #include "src/gpu/gradients/generated/GrTwoPointConicalGradientLayout.h"
17 
18 #include "src/gpu/gradients/GrGradientBitmapCache.h"
19 #include "src/gpu/gradients/generated/GrDualIntervalGradientColorizer.h"
20 #include "src/gpu/gradients/generated/GrSingleIntervalGradientColorizer.h"
21 #include "src/gpu/gradients/generated/GrTextureGradientColorizer.h"
22 #include "src/gpu/gradients/generated/GrUnrolledBinaryGradientColorizer.h"
23 
24 #include "include/private/GrRecordingContext.h"
25 #include "src/gpu/GrCaps.h"
26 #include "src/gpu/GrColor.h"
27 #include "src/gpu/GrColorInfo.h"
28 #include "src/gpu/GrRecordingContextPriv.h"
29 #include "src/gpu/SkGr.h"
30 
31 // Intervals smaller than this (that aren't hard stops) on low-precision-only devices force us to
32 // use the textured gradient
33 static const SkScalar kLowPrecisionIntervalLimit = 0.01f;
34 
35 // Each cache entry costs 1K or 2K of RAM. Each bitmap will be 1x256 at either 32bpp or 64bpp.
36 static const int kMaxNumCachedGradientBitmaps = 32;
37 static const int kGradientTextureSize = 256;
38 
39 // NOTE: signature takes raw pointers to the color/pos arrays and a count to make it easy for
40 // MakeColorizer to transparently take care of hard stops at the end points of the gradient.
make_textured_colorizer(const SkPMColor4f * colors,const SkScalar * positions,int count,bool premul,const GrFPArgs & args)41 static std::unique_ptr<GrFragmentProcessor> make_textured_colorizer(const SkPMColor4f* colors,
42         const SkScalar* positions, int count, bool premul, const GrFPArgs& args) {
43     static GrGradientBitmapCache gCache(kMaxNumCachedGradientBitmaps, kGradientTextureSize);
44 
45     // Use 8888 or F16, depending on the destination config.
46     // TODO: Use 1010102 for opaque gradients, at least if destination is 1010102?
47     SkColorType colorType = kRGBA_8888_SkColorType;
48     if (GrColorTypeIsWiderThan(args.fDstColorInfo->colorType(), 8)) {
49         auto f16Format = args.fContext->priv().caps()->getDefaultBackendFormat(
50                 GrColorType::kRGBA_F16, GrRenderable::kNo);
51         if (f16Format.isValid()) {
52             colorType = kRGBA_F16_SkColorType;
53         }
54     }
55     SkAlphaType alphaType = premul ? kPremul_SkAlphaType : kUnpremul_SkAlphaType;
56 
57     SkBitmap bitmap;
58     gCache.getGradient(colors, positions, count, colorType, alphaType, &bitmap);
59     SkASSERT(1 == bitmap.height() && SkIsPow2(bitmap.width()));
60     SkASSERT(bitmap.isImmutable());
61 
62     auto view = GrMakeCachedBitmapProxyView(args.fContext, bitmap);
63     if (!view.proxy()) {
64         SkDebugf("Gradient won't draw. Could not create texture.");
65         return nullptr;
66     }
67 
68     return GrTextureGradientColorizer::Make(std::move(view));
69 }
70 
71 // Analyze the shader's color stops and positions and chooses an appropriate colorizer to represent
72 // the gradient.
make_colorizer(const SkPMColor4f * colors,const SkScalar * positions,int count,bool premul,const GrFPArgs & args)73 static std::unique_ptr<GrFragmentProcessor> make_colorizer(const SkPMColor4f* colors,
74         const SkScalar* positions, int count, bool premul, const GrFPArgs& args) {
75     // If there are hard stops at the beginning or end, the first and/or last color should be
76     // ignored by the colorizer since it should only be used in a clamped border color. By detecting
77     // and removing these stops at the beginning, it makes optimizing the remaining color stops
78     // simpler.
79 
80     // SkGradientShaderBase guarantees that pos[0] == 0 by adding a dummy
81     bool bottomHardStop = SkScalarNearlyEqual(positions[0], positions[1]);
82     // The same is true for pos[end] == 1
83     bool topHardStop = SkScalarNearlyEqual(positions[count - 2], positions[count - 1]);
84 
85     int offset = 0;
86     if (bottomHardStop) {
87         offset += 1;
88         count--;
89     }
90     if (topHardStop) {
91         count--;
92     }
93 
94     // Two remaining colors means a single interval from 0 to 1
95     // (but it may have originally been a 3 or 4 color gradient with 1-2 hard stops at the ends)
96     if (count == 2) {
97         return GrSingleIntervalGradientColorizer::Make(colors[offset], colors[offset + 1]);
98     }
99 
100     // Do an early test for the texture fallback to skip all of the other tests for specific
101     // analytic support of the gradient (and compatibility with the hardware), when it's definitely
102     // impossible to use an analytic solution.
103     bool tryAnalyticColorizer = count <= GrUnrolledBinaryGradientColorizer::kMaxColorCount;
104 
105     // The remaining analytic colorizers use scale*t+bias, and the scale/bias values can become
106     // quite large when thresholds are close (but still outside the hardstop limit). If float isn't
107     // 32-bit, output can be incorrect if the thresholds are too close together. However, the
108     // analytic shaders are higher quality, so they can be used with lower precision hardware when
109     // the thresholds are not ill-conditioned.
110     const GrShaderCaps* caps = args.fContext->priv().caps()->shaderCaps();
111     if (!caps->floatIs32Bits() && tryAnalyticColorizer) {
112         // Could run into problems, check if thresholds are close together (with a limit of .01, so
113         // that scales will be less than 100, which leaves 4 decimals of precision on 16-bit).
114         for (int i = offset; i < count - 1; i++) {
115             SkScalar dt = SkScalarAbs(positions[i] - positions[i + 1]);
116             if (dt <= kLowPrecisionIntervalLimit && dt > SK_ScalarNearlyZero) {
117                 tryAnalyticColorizer = false;
118                 break;
119             }
120         }
121     }
122 
123     if (tryAnalyticColorizer) {
124         if (count == 3) {
125             // Must be a dual interval gradient, where the middle point is at offset+1 and the two
126             // intervals share the middle color stop.
127             return GrDualIntervalGradientColorizer::Make(colors[offset], colors[offset + 1],
128                                                          colors[offset + 1], colors[offset + 2],
129                                                          positions[offset + 1]);
130         } else if (count == 4 && SkScalarNearlyEqual(positions[offset + 1],
131                                                      positions[offset + 2])) {
132             // Two separate intervals that join at the same threshold position
133             return GrDualIntervalGradientColorizer::Make(colors[offset], colors[offset + 1],
134                                                          colors[offset + 2], colors[offset + 3],
135                                                          positions[offset + 1]);
136         }
137 
138         // The single and dual intervals are a specialized case of the unrolled binary search
139         // colorizer which can analytically render gradients of up to 8 intervals (up to 9 or 16
140         // colors depending on how many hard stops are inserted).
141         std::unique_ptr<GrFragmentProcessor> unrolled = GrUnrolledBinaryGradientColorizer::Make(
142                 colors + offset, positions + offset, count);
143         if (unrolled) {
144             return unrolled;
145         }
146     }
147 
148     // Otherwise fall back to a rasterized gradient sampled by a texture, which can handle
149     // arbitrary gradients (the only downside being sampling resolution).
150     return make_textured_colorizer(colors + offset, positions + offset, count, premul, args);
151 }
152 
153 // Combines the colorizer and layout with an appropriately configured master effect based on the
154 // gradient's tile mode
make_gradient(const SkGradientShaderBase & shader,const GrFPArgs & args,std::unique_ptr<GrFragmentProcessor> layout)155 static std::unique_ptr<GrFragmentProcessor> make_gradient(const SkGradientShaderBase& shader,
156         const GrFPArgs& args, std::unique_ptr<GrFragmentProcessor> layout) {
157     // No shader is possible if a layout couldn't be created, e.g. a layout-specific Make() returned
158     // null.
159     if (layout == nullptr) {
160         return nullptr;
161     }
162 
163     // Convert all colors into destination space and into SkPMColor4fs, and handle
164     // premul issues depending on the interpolation mode
165     bool inputPremul = shader.getGradFlags() & SkGradientShader::kInterpolateColorsInPremul_Flag;
166     bool allOpaque = true;
167     SkAutoSTMalloc<4, SkPMColor4f> colors(shader.fColorCount);
168     SkColor4fXformer xformedColors(shader.fOrigColors4f, shader.fColorCount,
169                                    shader.fColorSpace.get(), args.fDstColorInfo->colorSpace());
170     for (int i = 0; i < shader.fColorCount; i++) {
171         const SkColor4f& upmColor = xformedColors.fColors[i];
172         colors[i] = inputPremul ? upmColor.premul()
173                                 : SkPMColor4f{ upmColor.fR, upmColor.fG, upmColor.fB, upmColor.fA };
174         if (allOpaque && !SkScalarNearlyEqual(colors[i].fA, 1.0)) {
175             allOpaque = false;
176         }
177     }
178 
179     // SkGradientShader stores positions implicitly when they are evenly spaced, but the getPos()
180     // implementation performs a branch for every position index. Since the shader conversion
181     // requires lots of position tests, calculate all of the positions up front if needed.
182     SkTArray<SkScalar, true> implicitPos;
183     SkScalar* positions;
184     if (shader.fOrigPos) {
185         positions = shader.fOrigPos;
186     } else {
187         implicitPos.reserve(shader.fColorCount);
188         SkScalar posScale = SK_Scalar1 / (shader.fColorCount - 1);
189         for (int i = 0 ; i < shader.fColorCount; i++) {
190             implicitPos.push_back(SkIntToScalar(i) * posScale);
191         }
192         positions = implicitPos.begin();
193     }
194 
195     // All gradients are colorized the same way, regardless of layout
196     std::unique_ptr<GrFragmentProcessor> colorizer = make_colorizer(
197             colors.get(), positions, shader.fColorCount, inputPremul, args);
198     if (colorizer == nullptr) {
199         return nullptr;
200     }
201 
202     // The master effect has to export premul colors, but under certain conditions it doesn't need
203     // to do anything to achieve that: i.e. its interpolating already premul colors (inputPremul)
204     // or all the colors have a = 1, in which case premul is a no op. Note that this allOpaque
205     // check is more permissive than SkGradientShaderBase's isOpaque(), since we can optimize away
206     // the make-premul op for two point conical gradients (which report false for isOpaque).
207     bool makePremul = !inputPremul && !allOpaque;
208 
209     // All tile modes are supported (unless something was added to SkShader)
210     std::unique_ptr<GrFragmentProcessor> master;
211     switch(shader.getTileMode()) {
212         case SkTileMode::kRepeat:
213             master = GrTiledGradientEffect::Make(std::move(colorizer), std::move(layout),
214                                                  /* mirror */ false, makePremul, allOpaque);
215             break;
216         case SkTileMode::kMirror:
217             master = GrTiledGradientEffect::Make(std::move(colorizer), std::move(layout),
218                                                  /* mirror */ true, makePremul, allOpaque);
219             break;
220         case SkTileMode::kClamp:
221             // For the clamped mode, the border colors are the first and last colors, corresponding
222             // to t=0 and t=1, because SkGradientShaderBase enforces that by adding color stops as
223             // appropriate. If there is a hard stop, this grabs the expected outer colors for the
224             // border.
225             master = GrClampedGradientEffect::Make(std::move(colorizer), std::move(layout),
226                     colors[0], colors[shader.fColorCount - 1], makePremul, allOpaque);
227             break;
228         case SkTileMode::kDecal:
229             // Even if the gradient colors are opaque, the decal borders are transparent so
230             // disable that optimization
231             master = GrClampedGradientEffect::Make(std::move(colorizer), std::move(layout),
232                     SK_PMColor4fTRANSPARENT, SK_PMColor4fTRANSPARENT,
233                     makePremul, /* colorsAreOpaque */ false);
234             break;
235     }
236 
237     if (master == nullptr) {
238         // Unexpected tile mode
239         return nullptr;
240     }
241     if (args.fInputColorIsOpaque) {
242         return GrFragmentProcessor::OverrideInput(std::move(master), SK_PMColor4fWHITE, false);
243     }
244     return GrFragmentProcessor::MulChildByInputAlpha(std::move(master));
245 }
246 
247 namespace GrGradientShader {
248 
MakeLinear(const SkLinearGradient & shader,const GrFPArgs & args)249 std::unique_ptr<GrFragmentProcessor> MakeLinear(const SkLinearGradient& shader,
250                                                 const GrFPArgs& args) {
251     return make_gradient(shader, args, GrLinearGradientLayout::Make(shader, args));
252 }
253 
MakeRadial(const SkRadialGradient & shader,const GrFPArgs & args)254 std::unique_ptr<GrFragmentProcessor> MakeRadial(const SkRadialGradient& shader,
255                                                 const GrFPArgs& args) {
256     return make_gradient(shader,args, GrRadialGradientLayout::Make(shader, args));
257 }
258 
MakeSweep(const SkSweepGradient & shader,const GrFPArgs & args)259 std::unique_ptr<GrFragmentProcessor> MakeSweep(const SkSweepGradient& shader,
260                                                const GrFPArgs& args) {
261     return make_gradient(shader,args, GrSweepGradientLayout::Make(shader, args));
262 }
263 
MakeConical(const SkTwoPointConicalGradient & shader,const GrFPArgs & args)264 std::unique_ptr<GrFragmentProcessor> MakeConical(const SkTwoPointConicalGradient& shader,
265                                                  const GrFPArgs& args) {
266     return make_gradient(shader, args, GrTwoPointConicalGradientLayout::Make(shader, args));
267 }
268 
269 #if GR_TEST_UTILS
RandomParams(SkRandom * random)270 RandomParams::RandomParams(SkRandom* random) {
271     // Set color count to min of 2 so that we don't trigger the const color optimization and make
272     // a non-gradient processor.
273     fColorCount = random->nextRangeU(2, kMaxRandomGradientColors);
274     fUseColors4f = random->nextBool();
275 
276     // if one color, omit stops, otherwise randomly decide whether or not to
277     if (fColorCount == 1 || (fColorCount >= 2 && random->nextBool())) {
278         fStops = nullptr;
279     } else {
280         fStops = fStopStorage;
281     }
282 
283     // if using SkColor4f, attach a random (possibly null) color space (with linear gamma)
284     if (fUseColors4f) {
285         fColorSpace = GrTest::TestColorSpace(random);
286     }
287 
288     SkScalar stop = 0.f;
289     for (int i = 0; i < fColorCount; ++i) {
290         if (fUseColors4f) {
291             fColors4f[i].fR = random->nextUScalar1();
292             fColors4f[i].fG = random->nextUScalar1();
293             fColors4f[i].fB = random->nextUScalar1();
294             fColors4f[i].fA = random->nextUScalar1();
295         } else {
296             fColors[i] = random->nextU();
297         }
298         if (fStops) {
299             fStops[i] = stop;
300             stop = i < fColorCount - 1 ? stop + random->nextUScalar1() * (1.f - stop) : 1.f;
301         }
302     }
303     fTileMode = static_cast<SkTileMode>(random->nextULessThan(kSkTileModeCount));
304 }
305 #endif
306 
307 }
308