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