Debian Codegraph @

src/gpu/ganesh/gradients/GrGradientShader.cpp

raw
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 #include "src/gpu/ganesh/gradients/GrGradientShader.h"
8
9 #include "include/core/SkAlphaType.h"
10 #include "include/core/SkBitmap.h"
11 #include "include/core/SkColorSpace.h"
12 #include "include/core/SkColorType.h"
13 #include "include/core/SkMatrix.h"
14 #include "include/core/SkRect.h"
15 #include "include/core/SkSamplingOptions.h"
16 #include "include/core/SkString.h"
17 #include "include/core/SkTileMode.h"
18 #include "include/effects/SkGradient.h"
19 #include "include/effects/SkRuntimeEffect.h"
20 #include "include/gpu/GpuTypes.h"
21 #include "include/gpu/ganesh/GrBackendSurface.h"
22 #include "include/gpu/ganesh/GrTypes.h"
23 #include "include/private/base/SkAssert.h"
24 #include "include/private/base/SkDebug.h"
25 #include "include/private/base/SkMath.h"
26 #include "include/private/base/SkOnce.h"
27 #include "include/private/base/SkSpan_impl.h"
28 #include "include/private/base/SkTemplates.h"
29 #include "include/private/gpu/ganesh/GrTypesPriv.h"
30 #include "src/base/SkArenaAlloc.h"
31 #include "src/base/SkMathPriv.h"
32 #include "src/base/SkVx.h"
33 #include "src/core/SkColorData.h"
34 #include "src/core/SkColorSpacePriv.h"
35 #include "src/core/SkRasterPipeline.h"
36 #include "src/core/SkRasterPipelineOpContexts.h"
37 #include "src/core/SkRasterPipelineOpList.h"
38 #include "src/core/SkRuntimeEffectPriv.h"
39 #include "src/gpu/ganesh/GrCaps.h"
40 #include "src/gpu/ganesh/GrColorInfo.h"
41 #include "src/gpu/ganesh/GrColorSpaceXform.h"
42 #include "src/gpu/ganesh/GrFPArgs.h"
43 #include "src/gpu/ganesh/GrFragmentProcessor.h"
44 #include "src/gpu/ganesh/GrSamplerState.h"
45 #include "src/gpu/ganesh/GrShaderCaps.h"
46 #include "src/gpu/ganesh/SkGr.h"
47 #include "src/gpu/ganesh/SurfaceDrawContext.h"
48 #include "src/gpu/ganesh/effects/GrMatrixEffect.h"
49 #include "src/gpu/ganesh/effects/GrSkSLFP.h"
50 #include "src/gpu/ganesh/effects/GrTextureEffect.h"
51 #include "src/gpu/ganesh/gradients/GrGradientBitmapCache.h"
52 #include "src/gpu/ganesh/image/GrMippedBitmap.h"
53 #include "src/shaders/SkShaderBase.h"
54 #include "src/shaders/gradients/SkGradientBaseShader.h"
55
56 #include <algorithm>
57 #include <array>
58 #include <cstddef>
59 #include <tuple>
60 #include <utility>
61
62 struct SkV4;
63
64 #if defined(GPU_TEST_UTILS)
65 #include "src/base/SkRandom.h"
66 #include "src/gpu/ganesh/GrTestUtils.h"
67 #endif
68
69 using namespace skia_private;
70
71 using Vec4 = skvx::Vec<4, float>;
72
73 // Intervals smaller than this (that aren't hard stops) on low-precision-only devices force us to
74 // use the textured gradient
75 static const SkScalar kLowPrecisionIntervalLimit = 0.01f;
76
77 // Each cache entry costs 1K or 2K of RAM. Each bitmap will be 1x256 at either 32bpp or 64bpp.
78 static const int kMaxNumCachedGradientBitmaps = 32;
79 static const int kGradientTextureSize = 256;
80
81 // NOTE: signature takes raw pointers to the color/pos arrays and a count to make it easy for
82 // MakeColorizer to transparently take care of hard stops at the end points of the gradient.
83 static std::unique_ptr<GrFragmentProcessor> make_textured_colorizer(
84 const SkPMColor4f* colors,
85 const SkScalar* positions,
86 int count,
87 bool colorsAreOpaque,
88 const SkGradient::Interpolation& interpolation,
89 const SkColorSpace* intermediateColorSpace,
90 const SkColorSpace* dstColorSpace,
91 const GrFPArgs& args) {
92 static GrGradientBitmapCache gCache(kMaxNumCachedGradientBitmaps, kGradientTextureSize);
93
94 // Use 8888 or F16, depending on the destination config.
95 // TODO: Use 1010102 for opaque gradients, at least if destination is 1010102?
96 SkColorType colorType = kRGBA_8888_SkColorType;
97 if (GrColorTypeIsWiderThan(args.fDstColorInfo->colorType(), 8)) {
98 auto f16Format = args.fSurfaceDrawContext->caps()->getDefaultBackendFormat(
99 GrColorType::kRGBA_F16, GrRenderable::kNo);
100 if (f16Format.isValid()) {
101 colorType = kRGBA_F16_SkColorType;
102 }
103 }
104 SkAlphaType alphaType = static_cast<bool>(interpolation.fInPremul) ? kPremul_SkAlphaType
105 : kUnpremul_SkAlphaType;
106
107 SkBitmap bitmap;
108 gCache.getGradient(colors,
109 positions,
110 count,
111 colorsAreOpaque,
112 interpolation,
113 intermediateColorSpace,
114 dstColorSpace,
115 colorType,
116 alphaType,
117 &bitmap);
118 SkASSERT(1 == bitmap.height() && SkIsPow2(bitmap.width()));
119 SkASSERT(bitmap.isImmutable());
120
121 auto view =
122 std::get<0>(GrMakeCachedBitmapProxyView(args.fSurfaceDrawContext->recordingContext(),
123 GrMippedBitmap(bitmap),
124 /*label=*/"MakeTexturedColorizer",
125 skgpu::Mipmapped::kNo));
126 if (!view) {
127 SkDebugf("Gradient won't draw. Could not create texture.");
128 return nullptr;
129 }
130
131 auto m = SkMatrix::Scale(view.width(), 1.f);
132 return GrTextureEffect::Make(std::move(view), alphaType, m, GrSamplerState::Filter::kLinear);
133 }
134
135 static std::unique_ptr<GrFragmentProcessor> make_single_interval_colorizer(const SkPMColor4f& start,
136 const SkPMColor4f& end) {
137 static const SkRuntimeEffect* effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForShader,
138 "uniform half4 start;"
139 "uniform half4 end;"
140 "half4 main(float2 coord) {"
141 // Clamping and/or wrapping was already handled by the parent shader so the output
142 // color is a simple lerp.
143 "return mix(start, end, half(coord.x));"
144 "}"
145 );
146 return GrSkSLFP::Make(effect, "SingleIntervalColorizer", /*inputFP=*/nullptr,
147 GrSkSLFP::OptFlags::kNone,
148 "start", start,
149 "end", end);
150 }
151
152 static std::unique_ptr<GrFragmentProcessor> make_dual_interval_colorizer(const SkPMColor4f& c0,
153 const SkPMColor4f& c1,
154 const SkPMColor4f& c2,
155 const SkPMColor4f& c3,
156 float threshold) {
157 static const SkRuntimeEffect* effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForShader,
158 "uniform float4 scale[2];"
159 "uniform float4 bias[2];"
160 "uniform half threshold;"
161
162 "half4 main(float2 coord) {"
163 "half t = half(coord.x);"
164
165 "float4 s, b;"
166 "if (t < threshold) {"
167 "s = scale[0];"
168 "b = bias[0];"
169 "} else {"
170 "s = scale[1];"
171 "b = bias[1];"
172 "}"
173
174 "return half4(t * s + b);"
175 "}"
176 );
177
178 // Derive scale and biases from the 4 colors and threshold
179 Vec4 vc0 = Vec4::Load(c0.vec());
180 Vec4 vc1 = Vec4::Load(c1.vec());
181 Vec4 vc2 = Vec4::Load(c2.vec());
182 Vec4 vc3 = Vec4::Load(c3.vec());
183
184 const Vec4 scale[2] = {(vc1 - vc0) / threshold,
185 (vc3 - vc2) / (1 - threshold)};
186 const Vec4 bias[2] = {vc0,
187 vc2 - threshold * scale[1]};
188 return GrSkSLFP::Make(effect, "DualIntervalColorizer", /*inputFP=*/nullptr,
189 GrSkSLFP::OptFlags::kNone,
190 "scale", SkSpan(scale),
191 "bias", SkSpan(bias),
192 "threshold", threshold);
193 }
194
195 // The "unrolled" colorizer contains hand-written nested ifs which perform a binary search.
196 // This works on ES2 hardware that doesn't support non-constant array indexes.
197 // However, to keep code size under control, we are limited to a small number of stops.
198 static constexpr int kMaxUnrolledColorCount = 16;
199 static constexpr int kMaxUnrolledIntervalCount = kMaxUnrolledColorCount / 2;
200
201 static std::unique_ptr<GrFragmentProcessor> make_unrolled_colorizer(int intervalCount,
202 const SkPMColor4f* scale,
203 const SkPMColor4f* bias,
204 SkRect thresholds1_7,
205 SkRect thresholds9_13) {
206 SkASSERT(intervalCount >= 1 && intervalCount <= 8);
207
208 static SkOnce once[kMaxUnrolledIntervalCount];
209 static const SkRuntimeEffect* effects[kMaxUnrolledIntervalCount];
210
211 once[intervalCount - 1]([intervalCount] {
212 SkString sksl;
213
214 // The 7 threshold positions that define the boundaries of the 8 intervals (excluding t = 0,
215 // and t = 1) are packed into two half4s instead of having up to 7 separate scalar uniforms.
216 // For low interval counts, the extra components are ignored in the shader, but the uniform
217 // simplification is worth it. It is assumed thresholds are provided in increasing value,
218 // mapped as:
219 // - thresholds1_7.x = boundary between (0,1) and (2,3) -> 1_2
220 // - .y = boundary between (2,3) and (4,5) -> 3_4
221 // - .z = boundary between (4,5) and (6,7) -> 5_6
222 // - .w = boundary between (6,7) and (8,9) -> 7_8
223 // - thresholds9_13.x = boundary between (8,9) and (10,11) -> 9_10
224 // - .y = boundary between (10,11) and (12,13) -> 11_12
225 // - .z = boundary between (12,13) and (14,15) -> 13_14
226 // - .w = unused
227 sksl.append("uniform half4 thresholds1_7, thresholds9_13;");
228
229 // With the current hardstop detection threshold of 0.00024, the maximum scale and bias
230 // values will be on the order of 4k (since they divide by dt). That is well outside the
231 // precision capabilities of half floats, which can lead to inaccurate gradient calculations
232 sksl.appendf("uniform float4 scale[%d];", intervalCount);
233 sksl.appendf("uniform float4 bias[%d];", intervalCount);
234
235 // Explicit binary search for the proper interval that t falls within. The interval
236 // count checks are constant expressions, which are then optimized to the minimal number
237 // of branches for the specific interval count.
238 sksl.appendf(
239 "half4 main(float2 coord) {"
240 "half t = half(coord.x);"
241 "float4 s, b;"
242 // thresholds1_7.w is mid point for intervals (0,7) and (8,15)
243 "if (%d <= 4 || t < thresholds1_7.w) {"
244 // thresholds1_7.y is mid point for intervals (0,3) and (4,7)
245 "if (%d <= 2 || t < thresholds1_7.y) {"
246 // thresholds1_7.x is mid point for intervals (0,1) and (2,3)
247 "if (%d <= 1 || t < thresholds1_7.x) {"
248 "%s" // s = scale[0]; b = bias[0];
249 "} else {"
250 "%s" // s = scale[1]; b = bias[1];
251 "}"
252 "} else {"
253 // thresholds1_7.z is mid point for intervals (4,5) and (6,7)
254 "if (%d <= 3 || t < thresholds1_7.z) {"
255 "%s" // s = scale[2]; b = bias[2];
256 "} else {"
257 "%s" // s = scale[3]; b = bias[3];
258 "}"
259 "}"
260 "} else {"
261 // thresholds9_13.y is mid point for intervals (8,11) and (12,15)
262 "if (%d <= 6 || t < thresholds9_13.y) {"
263 // thresholds9_13.x is mid point for intervals (8,9) and (10,11)
264 "if (%d <= 5 || t < thresholds9_13.x) {"
265 "%s"
266 "} else {"
267 "%s" // s = scale[5]; b = bias[5];
268 "}"
269 "} else {"
270 // thresholds9_13.z is mid point for intervals (12,13) and (14,15)
271 "if (%d <= 7 || t < thresholds9_13.z) {"
272 "%s" // s = scale[6]; b = bias[6];
273 "} else {"
274 "%s" // s = scale[7]; b = bias[7];
275 "}"
276 "}"
277 "}"
278 "return t * s + b;"
279 "}"
280 , intervalCount,
281 intervalCount,
282 intervalCount,
283 (intervalCount <= 0) ? "" : "s = scale[0]; b = bias[0];",
284 (intervalCount <= 1) ? "" : "s = scale[1]; b = bias[1];",
285 intervalCount,
286 (intervalCount <= 2) ? "" : "s = scale[2]; b = bias[2];",
287 (intervalCount <= 3) ? "" : "s = scale[3]; b = bias[3];",
288 intervalCount,
289 intervalCount,
290 (intervalCount <= 4) ? "" : "s = scale[4]; b = bias[4];",
291 (intervalCount <= 5) ? "" : "s = scale[5]; b = bias[5];",
292 intervalCount,
293 (intervalCount <= 6) ? "" : "s = scale[6]; b = bias[6];",
294 (intervalCount <= 7) ? "" : "s = scale[7]; b = bias[7];");
295
296 auto result = SkRuntimeEffect::MakeForShader(std::move(sksl));
297 SkASSERTF(result.effect, "%s", result.errorText.c_str());
298 effects[intervalCount - 1] = result.effect.release();
299 });
300
301 return GrSkSLFP::Make(effects[intervalCount - 1], "UnrolledBinaryColorizer",
302 /*inputFP=*/nullptr, GrSkSLFP::OptFlags::kNone,
303 "thresholds1_7", thresholds1_7,
304 "thresholds9_13", thresholds9_13,
305 "scale", SkSpan(scale, intervalCount),
306 "bias", SkSpan(bias, intervalCount));
307 }
308
309 // The "looping" colorizer uses a real loop to binary-search the array of gradient stops.
310 static constexpr int kMaxLoopingColorCount = 128;
311 static constexpr int kMaxLoopingIntervalCount = kMaxLoopingColorCount / 2;
312
313 static std::unique_ptr<GrFragmentProcessor> make_looping_colorizer(int intervalCount,
314 const SkPMColor4f* scale,
315 const SkPMColor4f* bias,
316 const SkScalar* thresholds) {
317 SkASSERT(intervalCount >= 1 && intervalCount <= kMaxLoopingIntervalCount);
318 SkASSERT((intervalCount & 3) == 0); // intervals are required to come in groups of four
319 int intervalChunks = intervalCount / 4;
320 int cacheIndex = (size_t)intervalChunks - 1;
321
322 struct EffectCacheEntry {
323 SkOnce once;
324 const SkRuntimeEffect* effect;
325 };
326
327 static EffectCacheEntry effectCache[kMaxLoopingIntervalCount / 4];
328 SkASSERT(cacheIndex >= 0 && cacheIndex < (int)std::size(effectCache));
329 EffectCacheEntry* cacheEntry = &effectCache[cacheIndex];
330
331 cacheEntry->once([intervalCount, intervalChunks, cacheEntry] {
332 SkString sksl;
333
334 // Binary search for the interval that `t` falls within. We can precalculate the number of
335 // loop iterations we need, and we know `t` will always be in range, so we can just loop a
336 // fixed number of times and can be guaranteed to have found the proper element.
337 //
338 // Threshold values are stored in half4s to keep them compact, so the last two rounds of
339 // binary search are hand-unrolled to allow them to use swizzles.
340 //
341 // Note that this colorizer is also designed to handle the case of exactly 4 intervals (a
342 // single chunk). In this case, the binary search for-loop will optimize away entirely, as
343 // it can be proven to execute zero times. We also optimize away the calculation of `4 *
344 // chunk` near the end via an if statement, as the result will always be in chunk 0.
345 int loopCount = SkNextLog2(intervalChunks);
346 sksl.appendf(
347 "#version 300\n" // important space to separate token.
348 "uniform float4 thresholds[%d];"
349 "uniform float4 scale[%d];"
350 "uniform float4 bias[%d];"
351
352 "half4 main(float2 coord) {"
353 "float t = coord.x;"
354
355 // Choose a chunk from thresholds via binary search in a loop.
356 "int low = 0;"
357 "int high = %d;"
358 "int chunk = %d;"
359 "for (int loop = 0; loop < %d; ++loop) {"
360 "if (t < thresholds[chunk].w) {"
361 "high = chunk;"
362 "} else {"
363 "low = chunk + 1;"
364 "}"
365 "chunk = (low + high) / 2;"
366 "}"
367
368 // Choose the final position via explicit 4-way binary search.
369 "int pos;"
370 "if (t < thresholds[chunk].y) {"
371 "pos = (t < thresholds[chunk].x) ? 0 : 1;"
372 "} else {"
373 "pos = (t < thresholds[chunk].z) ? 2 : 3;"
374 "}"
375 "if (%d > 0) {"
376 "pos += 4 * chunk;"
377 "}"
378 "return t * scale[pos] + bias[pos];"
379 "}"
380 , /* thresholds: */ intervalChunks,
381 /* scale: */ intervalCount,
382 /* bias: */ intervalCount,
383 /* high: */ intervalChunks - 1,
384 /* chunk: */ (intervalChunks - 1) / 2,
385 /* loopCount: */ loopCount,
386 /* if (loopCount > 0): */ loopCount);
387
388 auto result = SkRuntimeEffect::MakeForShader(std::move(sksl));
389 SkASSERTF(result.effect, "%s", result.errorText.c_str());
390 cacheEntry->effect = result.effect.release();
391 });
392
393 return GrSkSLFP::Make(cacheEntry->effect, "LoopingBinaryColorizer",
394 /*inputFP=*/nullptr, GrSkSLFP::OptFlags::kNone,
395 "thresholds", SkSpan((const SkV4*)thresholds, intervalChunks),
396 "scale", SkSpan(scale, intervalCount),
397 "bias", SkSpan(bias, intervalCount));
398 }
399
400 // Converts an input array of {colors, positions} into an array of {scales, biases, thresholds}.
401 // The length of the result array may differ from the input due to hard-stops or empty intervals.
402 int build_intervals(int inputLength,
403 const SkPMColor4f* inColors,
404 const SkScalar* inPositions,
405 int outputLength,
406 SkPMColor4f* outScales,
407 SkPMColor4f* outBiases,
408 SkScalar* outThresholds) {
409 // Depending on how the positions resolve into hard stops or regular stops, the number of
410 // intervals specified by the number of colors/positions can change. For instance, a plain
411 // 3 color gradient is two intervals, but a 4 color gradient with a hard stop is also
412 // two intervals. At the most extreme end, an 8 interval gradient made entirely of hard
413 // stops has 16 colors.
414 int intervalCount = 0;
415 for (int i = 0; i < inputLength - 1; i++) {
416 if (intervalCount >= outputLength) {
417 // Already reached our output limit, and haven't run out of color stops. This gradient
418 // cannot be represented without more intervals.
419 return 0;
420 }
421
422 SkScalar t0 = inPositions[i];
423 SkScalar t1 = inPositions[i + 1];
424 SkScalar dt = t1 - t0;
425 // If the interval is empty, skip to the next interval. This will automatically create
426 // distinct hard stop intervals as needed. It also protects against malformed gradients
427 // that have repeated hard stops at the very beginning that are effectively unreachable.
428 if (SkScalarNearlyZero(dt)) {
429 continue;
430 }
431
432 Vec4 c0 = Vec4::Load(inColors[i].vec());
433 Vec4 c1 = Vec4::Load(inColors[i + 1].vec());
434 Vec4 scale = (c1 - c0) / dt;
435 Vec4 bias = c0 - t0 * scale;
436
437 scale.store(outScales + intervalCount);
438 bias.store(outBiases + intervalCount);
439 outThresholds[intervalCount] = t1;
440 intervalCount++;
441 }
442 return intervalCount;
443 }
444
445 static std::unique_ptr<GrFragmentProcessor> make_unrolled_binary_colorizer(
446 const SkPMColor4f* colors, const SkScalar* positions, int count) {
447 if (count > kMaxUnrolledColorCount) {
448 // Definitely cannot represent this gradient configuration
449 return nullptr;
450 }
451
452 SkPMColor4f scales[kMaxUnrolledIntervalCount];
453 SkPMColor4f biases[kMaxUnrolledIntervalCount];
454 SkScalar thresholds[kMaxUnrolledIntervalCount] = {};
455 int intervalCount = build_intervals(count, colors, positions,
456 kMaxUnrolledIntervalCount, scales, biases, thresholds);
457 if (intervalCount <= 0) {
458 return nullptr;
459 }
460
461 SkRect thresholds1_7 = {thresholds[0], thresholds[1], thresholds[2], thresholds[3]},
462 thresholds9_13 = {thresholds[4], thresholds[5], thresholds[6], 0.0};
463
464 return make_unrolled_colorizer(intervalCount, scales, biases, thresholds1_7, thresholds9_13);
465 }
466
467 static std::unique_ptr<GrFragmentProcessor> make_looping_binary_colorizer(const SkPMColor4f* colors,
468 const SkScalar* positions,
469 int count) {
470 if (count > kMaxLoopingColorCount) {
471 // Definitely cannot represent this gradient configuration
472 return nullptr;
473 }
474
475 SkPMColor4f scales[kMaxLoopingIntervalCount];
476 SkPMColor4f biases[kMaxLoopingIntervalCount];
477 SkScalar thresholds[kMaxLoopingIntervalCount] = {};
478 int intervalCount = build_intervals(count, colors, positions,
479 kMaxLoopingIntervalCount, scales, biases, thresholds);
480 if (intervalCount <= 0) {
481 return nullptr;
482 }
483
484 // We round up the number of intervals to the next power of two. This reduces the number of
485 // unique shaders and doesn't require any additional GPU processing power, but this does waste a
486 // handful of uniforms.
487 int roundedSize = std::max(4, SkNextPow2(intervalCount));
488 SkASSERT(roundedSize <= kMaxLoopingIntervalCount);
489 for (; intervalCount < roundedSize; ++intervalCount) {
490 thresholds[intervalCount] = thresholds[intervalCount - 1];
491 scales[intervalCount] = scales[intervalCount - 1];
492 biases[intervalCount] = biases[intervalCount - 1];
493 }
494
495 return make_looping_colorizer(intervalCount, scales, biases, thresholds);
496 }
497
498 // Analyze the shader's color stops and positions and chooses an appropriate colorizer to represent
499 // the gradient.
500 static std::unique_ptr<GrFragmentProcessor> make_uniform_colorizer(const SkPMColor4f* colors,
501 const SkScalar* positions,
502 int count,
503 bool premul,
504 const GrFPArgs& args) {
505 // If there are hard stops at the beginning or end, the first and/or last color should be
506 // ignored by the colorizer since it should only be used in a clamped border color. By detecting
507 // and removing these stops at the beginning, it makes optimizing the remaining color stops
508 // simpler.
509
510 // SkGradientBaseShader guarantees that pos[0] == 0 by adding a default value.
511 bool bottomHardStop = SkScalarNearlyEqual(positions[0], positions[1]);
512 // The same is true for pos[end] == 1
513 bool topHardStop = SkScalarNearlyEqual(positions[count - 2], positions[count - 1]);
514
515 if (bottomHardStop) {
516 colors++;
517 positions++;
518 count--;
519 }
520 if (topHardStop) {
521 count--;
522 }
523
524 // Two remaining colors means a single interval from 0 to 1
525 // (but it may have originally been a 3 or 4 color gradient with 1-2 hard stops at the ends)
526 if (count == 2) {
527 return make_single_interval_colorizer(colors[0], colors[1]);
528 }
529
530 const GrShaderCaps* caps = args.fSurfaceDrawContext->caps()->shaderCaps();
531 auto intervalsExceedPrecisionLimit = [&]() -> bool {
532 // The remaining analytic colorizers use scale*t+bias, and the scale/bias values can become
533 // quite large when thresholds are close (but still outside the hardstop limit). If float
534 // isn't 32-bit, output can be incorrect if the thresholds are too close together. However,
535 // the analytic shaders are higher quality, so they can be used with lower precision
536 // hardware when the thresholds are not ill-conditioned.
537 if (!caps->fFloatIs32Bits) {
538 // Could run into problems. Check if thresholds are close together (with a limit of .01,
539 // so that scales will be less than 100, which leaves 4 decimals of precision on
540 // 16-bit).
541 for (int i = 0; i < count - 1; i++) {
542 SkScalar dt = SkScalarAbs(positions[i] - positions[i + 1]);
543 if (dt <= kLowPrecisionIntervalLimit && dt > SK_ScalarNearlyZero) {
544 return true;
545 }
546 }
547 }
548 return false;
549 };
550
551 auto makeDualIntervalColorizer = [&]() -> std::unique_ptr<GrFragmentProcessor> {
552 // The dual-interval colorizer uses the same principles as the binary-search colorizer, but
553 // is limited to exactly 2 intervals.
554 if (count == 3) {
555 // Must be a dual interval gradient, where the middle point is at 1 and the
556 // two intervals share the middle color stop.
557 return make_dual_interval_colorizer(colors[0], colors[1],
558 colors[1], colors[2],
559 positions[1]);
560 }
561 if (count == 4 && SkScalarNearlyEqual(positions[1], positions[2])) {
562 // Two separate intervals that join at the same threshold position
563 return make_dual_interval_colorizer(colors[0], colors[1],
564 colors[2], colors[3],
565 positions[1]);
566 }
567 // The gradient can't be represented in only two intervals.
568 return nullptr;
569 };
570
571 int binaryColorizerLimit = caps->fNonconstantArrayIndexSupport ? kMaxLoopingColorCount
572 : kMaxUnrolledColorCount;
573 if ((count <= binaryColorizerLimit) && !intervalsExceedPrecisionLimit()) {
574 // The dual-interval colorizer uses the same principles as the binary-search colorizer, but
575 // is limited to exactly 2 intervals.
576 std::unique_ptr<GrFragmentProcessor> colorizer = makeDualIntervalColorizer();
577 if (colorizer) {
578 return colorizer;
579 }
580 // Attempt to create an analytic colorizer that uses a binary-search loop.
581 colorizer = caps->fNonconstantArrayIndexSupport
582 ? make_looping_binary_colorizer(colors, positions, count)
583 : make_unrolled_binary_colorizer(colors, positions, count);
584 if (colorizer) {
585 return colorizer;
586 }
587 }
588
589 // This gradient is too complex for our uniform colorizers. The calling code will fall back to
590 // creating a textured colorizer, instead.
591 return nullptr;
592 }
593
594 // This top-level effect implements clamping on the layout coordinate and requires specifying the
595 // border colors that are used when outside the clamped boundary. Gradients with the
596 // SkTileMode::kClamp should use the colors at their first and last stop (after adding default stops
597 // for t=0,t=1) as the border color. This will automatically replicate the edge color, even when
598 // there is a hard stop.
599 //
600 // The SkTileMode::kDecal can be produced by specifying transparent black as the border colors,
601 // regardless of the gradient's stop colors.
602 static std::unique_ptr<GrFragmentProcessor> make_clamped_gradient(
603 std::unique_ptr<GrFragmentProcessor> colorizer,
604 std::unique_ptr<GrFragmentProcessor> gradLayout,
605 SkPMColor4f leftBorderColor,
606 SkPMColor4f rightBorderColor,
607 bool colorsAreOpaque) {
608 static const SkRuntimeEffect* effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForShader,
609 "uniform shader colorizer;"
610 "uniform shader gradLayout;"
611
612 "uniform half4 leftBorderColor;" // t < 0.0
613 "uniform half4 rightBorderColor;" // t > 1.0
614
615 "uniform int layoutPreservesOpacity;" // specialized
616
617 "half4 main(float2 coord) {"
618 "half4 t = gradLayout.eval(coord);"
619 "half4 outColor;"
620
621 // If t.x is below 0, use the left border color without invoking the child processor.
622 // If any t.x is above 1, use the right border color. Otherwise, t is in the [0, 1]
623 // range assumed by the colorizer FP, so delegate to the child processor.
624 "if (!bool(layoutPreservesOpacity) && t.y < 0) {"
625 // layout has rejected this fragment (rely on sksl to remove this branch if the
626 // layout FP preserves opacity is false)
627 "outColor = half4(0);"
628 "} else if (t.x < 0) {"
629 "outColor = leftBorderColor;"
630 "} else if (t.x > 1.0) {"
631 "outColor = rightBorderColor;"
632 "} else {"
633 // Always sample from (x, 0), discarding y, since the layout FP can use y as a
634 // side-channel.
635 "outColor = colorizer.eval(t.x0);"
636 "}"
637 "return outColor;"
638 "}"
639 );
640
641 // If the layout does not preserve opacity, remove the opaque optimization,
642 // but otherwise respect the provided color opacity state (which should take
643 // into account the opacity of the border colors).
644 bool layoutPreservesOpacity = gradLayout->preservesOpaqueInput();
645 GrSkSLFP::OptFlags optFlags = GrSkSLFP::OptFlags::kCompatibleWithCoverageAsAlpha;
646 if (colorsAreOpaque && layoutPreservesOpacity) {
647 optFlags |= GrSkSLFP::OptFlags::kPreservesOpaqueInput;
648 }
649
650 return GrSkSLFP::Make(effect, "ClampedGradient", /*inputFP=*/nullptr, optFlags,
651 "colorizer", GrSkSLFP::IgnoreOptFlags(std::move(colorizer)),
652 "gradLayout", GrSkSLFP::IgnoreOptFlags(std::move(gradLayout)),
653 "leftBorderColor", leftBorderColor,
654 "rightBorderColor", rightBorderColor,
655 "layoutPreservesOpacity",
656 GrSkSLFP::Specialize<int>(layoutPreservesOpacity));
657 }
658
659 static std::unique_ptr<GrFragmentProcessor> make_tiled_gradient(
660 const GrFPArgs& args,
661 std::unique_ptr<GrFragmentProcessor> colorizer,
662 std::unique_ptr<GrFragmentProcessor> gradLayout,
663 bool mirror,
664 bool colorsAreOpaque) {
665 static const SkRuntimeEffect* effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForShader,
666 "uniform shader colorizer;"
667 "uniform shader gradLayout;"
668
669 "uniform int mirror;" // specialized
670 "uniform int layoutPreservesOpacity;" // specialized
671 "uniform int useFloorAbsWorkaround;" // specialized
672
673 "half4 main(float2 coord) {"
674 "float4 t = gradLayout.eval(coord);"
675
676 "if (!bool(layoutPreservesOpacity) && t.y < 0) {"
677 // layout has rejected this fragment (rely on sksl to remove this branch if the
678 // layout FP preserves opacity is false)
679 "return half4(0);"
680 "} else {"
681 "if (bool(mirror)) {"
682 "float t_1 = t.x - 1;"
683 "float tiled_t = t_1 - 2 * floor(t_1 * 0.5) - 1;"
684 "if (bool(useFloorAbsWorkaround)) {"
685 // At this point the expected value of tiled_t should between -1 and 1, so
686 // this clamp has no effect other than to break up the floor and abs calls
687 // and make sure the compiler doesn't merge them back together.
688 "tiled_t = clamp(tiled_t, -1, 1);"
689 "}"
690 "t.x = abs(tiled_t);"
691 "} else {"
692 // Simple repeat mode
693 "t.x = fract(t.x);"
694 "}"
695
696 // Always sample from (x, 0), discarding y, since the layout FP can use y as a
697 // side-channel.
698 "half4 outColor = colorizer.eval(t.x0);"
699 "return outColor;"
700 "}"
701 "}"
702 );
703
704 // If the layout does not preserve opacity, remove the opaque optimization,
705 // but otherwise respect the provided color opacity state (which should take
706 // into account the opacity of the border colors).
707 bool layoutPreservesOpacity = gradLayout->preservesOpaqueInput();
708 GrSkSLFP::OptFlags optFlags = GrSkSLFP::OptFlags::kCompatibleWithCoverageAsAlpha;
709 if (colorsAreOpaque && layoutPreservesOpacity) {
710 optFlags |= GrSkSLFP::OptFlags::kPreservesOpaqueInput;
711 }
712 const bool useFloorAbsWorkaround =
713 args.fSurfaceDrawContext->caps()->shaderCaps()->fMustDoOpBetweenFloorAndAbs;
714
715 return GrSkSLFP::Make(effect, "TiledGradient", /*inputFP=*/nullptr, optFlags,
716 "colorizer", GrSkSLFP::IgnoreOptFlags(std::move(colorizer)),
717 "gradLayout", GrSkSLFP::IgnoreOptFlags(std::move(gradLayout)),
718 "mirror", GrSkSLFP::Specialize<int>(mirror),
719 "layoutPreservesOpacity",
720 GrSkSLFP::Specialize<int>(layoutPreservesOpacity),
721 "useFloorAbsWorkaround",
722 GrSkSLFP::Specialize<int>(useFloorAbsWorkaround));
723 }
724
725 static std::unique_ptr<GrFragmentProcessor> make_interpolated_to_dst(
726 std::unique_ptr<GrFragmentProcessor> gradient,
727 const SkGradient::Interpolation& interpolation,
728 SkColorSpace* intermediateColorSpace,
729 const GrColorInfo& dstInfo,
730 bool allOpaque) {
731 using ColorSpace = SkGradient::Interpolation::ColorSpace;
732
733 // If these values change, you will need to edit sksl_shared
734 static_assert(static_cast<int>(ColorSpace::kDestination) == 0);
735 static_assert(static_cast<int>(ColorSpace::kSRGBLinear) == 1);
736 static_assert(static_cast<int>(ColorSpace::kLab) == 2);
737 static_assert(static_cast<int>(ColorSpace::kOKLab) == 3);
738 static_assert(static_cast<int>(ColorSpace::kOKLabGamutMap) == 4);
739 static_assert(static_cast<int>(ColorSpace::kLCH) == 5);
740 static_assert(static_cast<int>(ColorSpace::kOKLCH) == 6);
741 static_assert(static_cast<int>(ColorSpace::kOKLCHGamutMap) == 7);
742 static_assert(static_cast<int>(ColorSpace::kSRGB) == 8);
743 static_assert(static_cast<int>(ColorSpace::kHSL) == 9);
744 static_assert(static_cast<int>(ColorSpace::kHWB) == 10);
745
746 static const SkRuntimeEffect* effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForColorFilter,
747 "uniform int colorSpace;" // specialized
748 "uniform int do_unpremul;" // specialized
749
750 "half4 main(half4 color) {"
751 "return $interpolated_to_rgb_unpremul(color, colorSpace, do_unpremul);"
752 "}"
753 );
754
755 // Are we interpreting premul colors? We use this later to decide if we need to inject a final
756 // premultiplication step.
757 bool inputPremul = static_cast<bool>(interpolation.fInPremul);
758
759 switch (interpolation.fColorSpace) {
760 case ColorSpace::kLab:
761 case ColorSpace::kOKLab:
762 case ColorSpace::kOKLabGamutMap:
763 case ColorSpace::kLCH:
764 case ColorSpace::kOKLCH:
765 case ColorSpace::kOKLCHGamutMap:
766 case ColorSpace::kHSL:
767 case ColorSpace::kHWB:
768 // In these exotic spaces, unpremul the colors if necessary (no need to do this if
769 // they're all opaque), and then convert them to the intermediate SkColorSpace
770 gradient = GrSkSLFP::Make(effect, "GradientCS", std::move(gradient),
771 GrSkSLFP::OptFlags::kAll,
772 "colorSpace", GrSkSLFP::Specialize<int>(
773 static_cast<int>(interpolation.fColorSpace)),
774 "do_unpremul", GrSkSLFP::Specialize<int>(
775 inputPremul && !allOpaque));
776 // We just forced the colors back to unpremul. Remember that for below
777 inputPremul = false;
778 break;
779 default:
780 break;
781 }
782
783 // Now transform from intermediate to destination color space. There are two tricky things here:
784 // 1) Normally, we'd pass dstInfo to the transform effect. However, if someone is rendering to
785 // a non-color managed surface (nullptr dst color space), and they chose to interpolate in
786 // any of the exotic spaces, that transform would do nothing, and leave the colors in
787 // whatever intermediate space we chose. That could even be something like XYZ, which will
788 // produce nonsense. So, in this particular case, we break Skia's rules, and treat a null
789 // destination as sRGB.
790 SkColorSpace* dstColorSpace = dstInfo.colorSpace() ? dstInfo.colorSpace() : sk_srgb_singleton();
791
792 // 2) Alpha type: We already tweaked our idea of "inputPremul" above -- if we interpolated in a
793 // non-RGB space, then we had to unpremul the colors to get proper conversion back to RGB.
794 // Our final goal is to emit premul colors, but under certain conditions we don't need to do
795 // anything to achieve that: i.e. its interpolating already premul colors (inputPremul) or
796 // all the colors have a = 1, in which case premul is a no op. Note that this allOpaque check
797 // is more permissive than SkGradientBaseShader's isOpaque(), since we can optimize away the
798 // make-premul op for two point conical gradients (which report false for isOpaque).
799 SkAlphaType intermediateAlphaType = inputPremul ? kPremul_SkAlphaType : kUnpremul_SkAlphaType;
800 SkAlphaType dstAlphaType = kPremul_SkAlphaType;
801
802 // If all the colors were opaque, then we don't need to do any premultiplication. We describe
803 // all the colors as *unpremul*, though. That will eliminate any extra unpremul/premul pair
804 // that would be injected if we have to do a color-space conversion here.
805 if (allOpaque) {
806 intermediateAlphaType = dstAlphaType = kUnpremul_SkAlphaType;
807 }
808
809 return GrColorSpaceXformEffect::Make(std::move(gradient),
810 intermediateColorSpace, intermediateAlphaType,
811 dstColorSpace, dstAlphaType);
812 }
813
814 namespace GrGradientShader {
815
816 /**
817 * Produces an FP that muls its input coords by the inverse of the pending matrix and then
818 * samples the passed FP with those coordinates. 'postInv' is an additional matrix to
819 * post-apply to the inverted pending matrix. If the pending matrix is not invertible the
820 * GrFPResult's bool will be false and the passed FP will be returned to the caller in the
821 * GrFPResult.
822 */
823 static GrFPResult apply_matrix(std::unique_ptr<GrFragmentProcessor> fp,
824 const SkShaders::MatrixRec& rec,
825 const SkMatrix& postInv) {
826 auto [total, ok] = rec.applyForFragmentProcessor(postInv);
827 if (!ok) {
828 return {false, std::move(fp)};
829 }
830 // GrMatrixEffect returns 'fp' if total worked out to identity.
831 return {true, GrMatrixEffect::Make(total, std::move(fp))};
832 }
833
834 // Combines the colorizer and layout with an appropriately configured top-level effect based on the
835 // gradient's tile mode
836 std::unique_ptr<GrFragmentProcessor> MakeGradientFP(const SkGradientBaseShader& shader,
837 const GrFPArgs& args,
838 const SkShaders::MatrixRec& mRec,
839 std::unique_ptr<GrFragmentProcessor> layout,
840 const SkMatrix* overrideMatrix) {
841 // No shader is possible if a layout couldn't be created, e.g. a layout-specific Make() returned
842 // null.
843 if (layout == nullptr) {
844 return nullptr;
845 }
846
847 // Some two-point conical gradients use a custom matrix here. Otherwise, use
848 // SkGradientBaseShader's matrix;
849 if (!overrideMatrix) {
850 overrideMatrix = &shader.getGradientMatrix();
851 }
852 bool success;
853 std::tie(success, layout) = apply_matrix(std::move(layout), mRec, *overrideMatrix);
854 if (!success) {
855 return nullptr;
856 }
857
858 // Convert all colors into destination space and into SkPMColor4fs, and handle
859 // premul issues depending on the interpolation mode.
860 //
861 // SkGradientShader stores positions implicitly when they are evenly spaced, but the getPos()
862 // implementation performs a branch for every position index. Since the shader conversion
863 // requires lots of position tests, instruct the xformer to calculate all of the positions up
864 // front if needed.
865 SkColor4fXformer xformedColors(
866 &shader, args.fDstColorInfo->colorSpace(), /*forceExplicitPositions=*/true);
867 const SkPMColor4f* colors = xformedColors.fColors.begin();
868 const SkScalar* positions = xformedColors.fPositions;
869 const int colorCount = xformedColors.fColors.size();
870
871 bool allOpaque = true;
872 for (int i = 0; i < colorCount; i++) {
873 if (allOpaque && !SkScalarNearlyEqual(colors[i].fA, 1.0)) {
874 allOpaque = false;
875 }
876 }
877
878 // All gradients are colorized the same way, regardless of layout
879 std::unique_ptr<GrFragmentProcessor> colorizer = make_uniform_colorizer(
880 colors, positions, colorCount, shader.interpolateInPremul(), args);
881
882 if (colorizer) {
883 // If we made a uniform colorizer, wrap it in a conversion from interpolated space to
884 // destination. This also applies any final premultiplication.
885 colorizer = make_interpolated_to_dst(std::move(colorizer),
886 shader.interpolation(),
887 xformedColors.fIntermediateColorSpace.get(),
888 *args.fDstColorInfo,
889 allOpaque);
890 } else {
891 // If we failed to make a uniform colorizer, we need to rasterize the gradient to a
892 // texture (which can handle arbitrarily complex gradients). This method directly encodes
893 // the result of the interpolated-to-dst into the texture, so we skip the wrapper FP above.
894 //
895 // Also, note that the texture technique has limited sampling resolution, and always blurs
896 // hard-stops.)
897 colorizer = make_textured_colorizer(colors,
898 positions,
899 colorCount,
900 allOpaque,
901 shader.interpolation(),
902 xformedColors.fIntermediateColorSpace.get(),
903 args.fDstColorInfo->colorSpace(),
904 args);
905 }
906
907 if (colorizer == nullptr) {
908 return nullptr;
909 }
910
911 // If interpolation space is different than destination, wrap the colorizer in a conversion.
912 // This also handles any final premultiplication, etc.
913
914 // All tile modes are supported (unless something was added to SkShader)
915 std::unique_ptr<GrFragmentProcessor> gradient;
916 switch(shader.getTileMode()) {
917 case SkTileMode::kRepeat:
918 gradient = make_tiled_gradient(args, std::move(colorizer), std::move(layout),
919 /* mirror */ false, allOpaque);
920 break;
921 case SkTileMode::kMirror:
922 gradient = make_tiled_gradient(args, std::move(colorizer), std::move(layout),
923 /* mirror */ true, allOpaque);
924 break;
925 case SkTileMode::kClamp: {
926 // For the clamped mode, the border colors are the first and last colors, corresponding
927 // to t=0 and t=1, because SkGradientBaseShader enforces that by adding color stops as
928 // appropriate. If there is a hard stop, this grabs the expected outer colors for the
929 // border.
930
931 // However, we need to finish converting to destination color space. (These are still
932 // in the interpolated color space).
933 SkPMColor4f borderColors[2] = { colors[0], colors[colorCount - 1] };
934 SkArenaAlloc alloc(/*firstHeapAllocation=*/0);
935 SkRasterPipeline p(&alloc);
936 SkRasterPipelineContexts::MemoryCtx ctx = {borderColors, 0};
937
938 p.append(SkRasterPipelineOp::load_f32, &ctx);
939 SkGradientBaseShader::AppendInterpolatedToDstStages(
940 &p,
941 &alloc,
942 allOpaque,
943 shader.interpolation(),
944 xformedColors.fIntermediateColorSpace.get(),
945 args.fDstColorInfo->colorSpace());
946 p.append(SkRasterPipelineOp::store_f32, &ctx);
947 p.run(0, 0, 2, 1);
948
949 gradient = make_clamped_gradient(std::move(colorizer), std::move(layout),
950 borderColors[0], borderColors[1], allOpaque);
951 break;
952 }
953 case SkTileMode::kDecal:
954 // Even if the gradient colors are opaque, the decal borders are transparent so
955 // disable that optimization
956 gradient = make_clamped_gradient(std::move(colorizer), std::move(layout),
957 SK_PMColor4fTRANSPARENT, SK_PMColor4fTRANSPARENT,
958 /* colorsAreOpaque */ false);
959 break;
960 }
961
962 return gradient;
963 }
964
965 std::unique_ptr<GrFragmentProcessor> MakeLinear(const SkLinearGradient& shader,
966 const GrFPArgs& args,
967 const SkShaders::MatrixRec& mRec) {
968 // We add a tiny delta to t. When gradient stops are set up so that a hard stop in a vertically
969 // or horizontally oriented gradient falls exactly at a column or row of pixel centers we can
970 // get slightly different interpolated t values along the column/row. By adding the delta
971 // we will consistently get the color to the "right" of the stop. Of course if the hard stop
972 // falls at X.5 - delta then we still could get inconsistent results, but that is much less
973 // likely. crbug.com/938592
974 // If/when we add filtering of the gradient this can be removed.
975 static const SkRuntimeEffect* effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForShader,
976 "half4 main(float2 coord) {"
977 "return half4(half(coord.x + 0.00001), 1, 0, 0);" // y = 1 for always valid
978 "}"
979 );
980 // The linear gradient never rejects a pixel so it doesn't change opacity
981 auto fp = GrSkSLFP::Make(effect, "LinearLayout", /*inputFP=*/nullptr,
982 GrSkSLFP::OptFlags::kPreservesOpaqueInput);
983 return MakeGradientFP(shader, args, mRec, std::move(fp));
984 }
985
986 #if defined(GPU_TEST_UTILS)
987 RandomParams::RandomParams(SkRandom* random) {
988 // Set color count to min of 2 so that we don't trigger the const color optimization and make
989 // a non-gradient processor.
990 fColorCount = random->nextRangeU(2, kMaxRandomGradientColors);
991 fUseColors4f = random->nextBool();
992
993 // if one color, omit stops, otherwise randomly decide whether or not to
994 if (fColorCount == 1 || (fColorCount >= 2 && random->nextBool())) {
995 fStops = nullptr;
996 } else {
997 fStops = fStopStorage;
998 }
999
1000 // if using SkColor4f, attach a random (possibly null) color space (with linear gamma)
1001 if (fUseColors4f) {
1002 fColorSpace = GrTest::TestColorSpace(random);
1003 }
1004
1005 SkScalar stop = 0.f;
1006 for (int i = 0; i < fColorCount; ++i) {
1007 if (fUseColors4f) {
1008 fColors4f[i].fR = random->nextUScalar1();
1009 fColors4f[i].fG = random->nextUScalar1();
1010 fColors4f[i].fB = random->nextUScalar1();
1011 fColors4f[i].fA = random->nextUScalar1();
1012 } else {
1013 fColors[i] = random->nextU();
1014 }
1015 if (fStops) {
1016 fStops[i] = stop;
1017 stop = i < fColorCount - 1 ? stop + random->nextUScalar1() * (1.f - stop) : 1.f;
1018 }
1019 }
1020 fTileMode = static_cast<SkTileMode>(random->nextULessThan(kSkTileModeCount));
1021 }
1022 #endif
1023
1024 } // namespace GrGradientShader