blob: 8f0c5c836e4eff44e65942ec7993e7f333ff7e1a [file] [log] [blame]
rileya@google.com589708b2012-07-26 20:04:23 +00001/*
2 * Copyright 2006 The Android Open Source Project
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
Herb Derby4de13042017-05-15 10:49:39 -04008#include <algorithm>
fmalitabc590c02016-02-22 09:12:33 -08009#include "Sk4fLinearGradient.h"
raftias94888332016-10-18 10:02:51 -070010#include "SkColorSpace_XYZ.h"
Florin Malita39d71de2017-10-31 11:33:49 -040011#include "SkColorSpaceXformer.h"
Florin Malitacad3b8c2017-10-28 21:42:50 -040012#include "SkFloatBits.h"
Florin Malitad4e9ec82017-10-25 18:00:26 -040013#include "SkGradientBitmapCache.h"
rileya@google.com589708b2012-07-26 20:04:23 +000014#include "SkGradientShaderPriv.h"
brianosmand4546092016-09-22 12:31:58 -070015#include "SkHalf.h"
rileya@google.com589708b2012-07-26 20:04:23 +000016#include "SkLinearGradient.h"
Mike Reed6b3155c2017-04-03 14:41:44 -040017#include "SkMallocPixelRef.h"
rileya@google.com589708b2012-07-26 20:04:23 +000018#include "SkRadialGradient.h"
Florin Malitad4e9ec82017-10-25 18:00:26 -040019#include "SkReadBuffer.h"
Mike Klein02ab8cc2017-05-04 22:41:05 +000020#include "SkSweepGradient.h"
Mike Kleina3771842017-05-04 19:38:48 -040021#include "SkTwoPointConicalGradient.h"
Florin Malitad4e9ec82017-10-25 18:00:26 -040022#include "SkWriteBuffer.h"
Herb Derby4de13042017-05-15 10:49:39 -040023#include "../../jumper/SkJumper.h"
24
rileya@google.com589708b2012-07-26 20:04:23 +000025
brianosmane25d71c2016-09-28 11:27:28 -070026enum GradientSerializationFlags {
27 // Bits 29:31 used for various boolean flags
28 kHasPosition_GSF = 0x80000000,
29 kHasLocalMatrix_GSF = 0x40000000,
30 kHasColorSpace_GSF = 0x20000000,
31
32 // Bits 12:28 unused
33
34 // Bits 8:11 for fTileMode
35 kTileModeShift_GSF = 8,
36 kTileModeMask_GSF = 0xF,
37
38 // Bits 0:7 for fGradFlags (note that kForce4fContext_PrivateFlag is 0x80)
39 kGradFlagsShift_GSF = 0,
40 kGradFlagsMask_GSF = 0xFF,
41};
42
reed9fa60da2014-08-21 07:59:51 -070043void SkGradientShaderBase::Descriptor::flatten(SkWriteBuffer& buffer) const {
brianosmane25d71c2016-09-28 11:27:28 -070044 uint32_t flags = 0;
reed9fa60da2014-08-21 07:59:51 -070045 if (fPos) {
brianosmane25d71c2016-09-28 11:27:28 -070046 flags |= kHasPosition_GSF;
reed9fa60da2014-08-21 07:59:51 -070047 }
reed9fa60da2014-08-21 07:59:51 -070048 if (fLocalMatrix) {
brianosmane25d71c2016-09-28 11:27:28 -070049 flags |= kHasLocalMatrix_GSF;
50 }
51 sk_sp<SkData> colorSpaceData = fColorSpace ? fColorSpace->serialize() : nullptr;
52 if (colorSpaceData) {
53 flags |= kHasColorSpace_GSF;
54 }
55 SkASSERT(static_cast<uint32_t>(fTileMode) <= kTileModeMask_GSF);
56 flags |= (fTileMode << kTileModeShift_GSF);
57 SkASSERT(fGradFlags <= kGradFlagsMask_GSF);
58 flags |= (fGradFlags << kGradFlagsShift_GSF);
59
60 buffer.writeUInt(flags);
61
62 buffer.writeColor4fArray(fColors, fCount);
63 if (colorSpaceData) {
64 buffer.writeDataAsByteArray(colorSpaceData.get());
65 }
66 if (fPos) {
67 buffer.writeScalarArray(fPos, fCount);
68 }
69 if (fLocalMatrix) {
reed9fa60da2014-08-21 07:59:51 -070070 buffer.writeMatrix(*fLocalMatrix);
reed9fa60da2014-08-21 07:59:51 -070071 }
72}
73
74bool SkGradientShaderBase::DescriptorScope::unflatten(SkReadBuffer& buffer) {
Mike Reed70bc94f2017-06-08 12:45:52 -040075 // New gradient format. Includes floating point color, color space, densely packed flags
76 uint32_t flags = buffer.readUInt();
reed9fa60da2014-08-21 07:59:51 -070077
Mike Reed70bc94f2017-06-08 12:45:52 -040078 fTileMode = (SkShader::TileMode)((flags >> kTileModeShift_GSF) & kTileModeMask_GSF);
79 fGradFlags = (flags >> kGradFlagsShift_GSF) & kGradFlagsMask_GSF;
reed9fa60da2014-08-21 07:59:51 -070080
Mike Reed70bc94f2017-06-08 12:45:52 -040081 fCount = buffer.getArrayCount();
82 if (fCount > kStorageCount) {
83 size_t allocSize = (sizeof(SkColor4f) + sizeof(SkScalar)) * fCount;
84 fDynamicStorage.reset(allocSize);
85 fColors = (SkColor4f*)fDynamicStorage.get();
86 fPos = (SkScalar*)(fColors + fCount);
87 } else {
88 fColors = fColorStorage;
89 fPos = fPosStorage;
90 }
91 if (!buffer.readColor4fArray(mutableColors(), fCount)) {
92 return false;
93 }
94 if (SkToBool(flags & kHasColorSpace_GSF)) {
95 sk_sp<SkData> data = buffer.readByteArrayAsData();
96 fColorSpace = SkColorSpace::Deserialize(data->data(), data->size());
97 } else {
brianosmane25d71c2016-09-28 11:27:28 -070098 fColorSpace = nullptr;
Mike Reed70bc94f2017-06-08 12:45:52 -040099 }
100 if (SkToBool(flags & kHasPosition_GSF)) {
101 if (!buffer.readScalarArray(mutablePos(), fCount)) {
102 return false;
brianosmane25d71c2016-09-28 11:27:28 -0700103 }
reed9fa60da2014-08-21 07:59:51 -0700104 } else {
Mike Reed70bc94f2017-06-08 12:45:52 -0400105 fPos = nullptr;
106 }
107 if (SkToBool(flags & kHasLocalMatrix_GSF)) {
108 fLocalMatrix = &fLocalMatrixStorage;
109 buffer.readMatrix(&fLocalMatrixStorage);
110 } else {
111 fLocalMatrix = nullptr;
reed9fa60da2014-08-21 07:59:51 -0700112 }
113 return buffer.isValid();
114}
115
116////////////////////////////////////////////////////////////////////////////////////////////
117
mtkleincc695fe2014-12-10 10:29:19 -0800118SkGradientShaderBase::SkGradientShaderBase(const Descriptor& desc, const SkMatrix& ptsToUnit)
reedaddf2ed2014-08-11 08:28:24 -0700119 : INHERITED(desc.fLocalMatrix)
mtkleincc695fe2014-12-10 10:29:19 -0800120 , fPtsToUnit(ptsToUnit)
Florin Malita39d71de2017-10-31 11:33:49 -0400121 , fColorsAreOpaque(true)
commit-bot@chromium.org9c9005a2014-04-28 14:55:39 +0000122{
mtkleincc695fe2014-12-10 10:29:19 -0800123 fPtsToUnit.getType(); // Precache so reads are threadsafe.
reed@google.com437d6eb2013-05-23 19:03:05 +0000124 SkASSERT(desc.fCount > 1);
rileya@google.com589708b2012-07-26 20:04:23 +0000125
fmalita6d7e4e82016-09-20 06:55:16 -0700126 fGradFlags = static_cast<uint8_t>(desc.fGradFlags);
rileya@google.com589708b2012-07-26 20:04:23 +0000127
reed@google.com437d6eb2013-05-23 19:03:05 +0000128 SkASSERT((unsigned)desc.fTileMode < SkShader::kTileModeCount);
reed@google.com437d6eb2013-05-23 19:03:05 +0000129 fTileMode = desc.fTileMode;
rileya@google.com589708b2012-07-26 20:04:23 +0000130
rileya@google.com589708b2012-07-26 20:04:23 +0000131 /* Note: we let the caller skip the first and/or last position.
132 i.e. pos[0] = 0.3, pos[1] = 0.7
133 In these cases, we insert dummy entries to ensure that the final data
134 will be bracketed by [0, 1].
135 i.e. our_pos[0] = 0, our_pos[1] = 0.3, our_pos[2] = 0.7, our_pos[3] = 1
136
137 Thus colorCount (the caller's value, and fColorCount (our value) may
138 differ by up to 2. In the above example:
139 colorCount = 2
140 fColorCount = 4
141 */
reed@google.com437d6eb2013-05-23 19:03:05 +0000142 fColorCount = desc.fCount;
rileya@google.com589708b2012-07-26 20:04:23 +0000143 // check if we need to add in dummy start and/or end position/colors
144 bool dummyFirst = false;
145 bool dummyLast = false;
reed@google.com437d6eb2013-05-23 19:03:05 +0000146 if (desc.fPos) {
147 dummyFirst = desc.fPos[0] != 0;
148 dummyLast = desc.fPos[desc.fCount - 1] != SK_Scalar1;
rileya@google.com589708b2012-07-26 20:04:23 +0000149 fColorCount += dummyFirst + dummyLast;
150 }
151
Mike Reed62ce2ca2018-02-19 14:20:15 -0500152 size_t storageSize = fColorCount * (sizeof(SkColor4f) + (desc.fPos ? sizeof(SkScalar) : 0));
Florin Malita89ab2402017-11-01 10:14:57 -0400153 fOrigColors4f = reinterpret_cast<SkColor4f*>(fStorage.reset(storageSize));
Mike Reed62ce2ca2018-02-19 14:20:15 -0500154 fOrigPos = desc.fPos ? reinterpret_cast<SkScalar*>(fOrigColors4f + fColorCount)
155 : nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +0000156
brianosmane25d71c2016-09-28 11:27:28 -0700157 // Now copy over the colors, adding the dummies as needed
158 SkColor4f* origColors = fOrigColors4f;
159 if (dummyFirst) {
160 *origColors++ = desc.fColors[0];
161 }
Florin Malita39d71de2017-10-31 11:33:49 -0400162 for (int i = 0; i < desc.fCount; ++i) {
Mike Reed62ce2ca2018-02-19 14:20:15 -0500163 origColors[i] = desc.fColors[i];
Florin Malita39d71de2017-10-31 11:33:49 -0400164 fColorsAreOpaque = fColorsAreOpaque && (desc.fColors[i].fA == 1);
165 }
brianosmane25d71c2016-09-28 11:27:28 -0700166 if (dummyLast) {
Mike Reed62ce2ca2018-02-19 14:20:15 -0500167 origColors += desc.fCount;
168 *origColors = desc.fColors[desc.fCount - 1];
brianosmane25d71c2016-09-28 11:27:28 -0700169 }
brianosmanb9c51372016-09-15 11:09:45 -0700170
brianosmane25d71c2016-09-28 11:27:28 -0700171 if (!desc.fColorSpace) {
172 // This happens if we were constructed from SkColors, so our colors are really sRGB
Matt Sarett77a7a1b2017-02-07 13:56:11 -0500173 fColorSpace = SkColorSpace::MakeSRGBLinear();
brianosmanb9c51372016-09-15 11:09:45 -0700174 } else {
brianosmane25d71c2016-09-28 11:27:28 -0700175 // The color space refers to the float colors, so it must be linear gamma
Brian Osmanf06ead92017-10-30 13:47:41 -0400176 // TODO: GPU code no longer requires this (see GrGradientEffect). Remove this restriction?
brianosmane25d71c2016-09-28 11:27:28 -0700177 SkASSERT(desc.fColorSpace->gammaIsLinear());
brianosmanb9c51372016-09-15 11:09:45 -0700178 fColorSpace = desc.fColorSpace;
rileya@google.com589708b2012-07-26 20:04:23 +0000179 }
180
Florin Malita89ab2402017-11-01 10:14:57 -0400181 if (desc.fPos) {
Florin Malita64bb78e2017-11-03 12:54:07 -0400182 SkScalar prev = 0;
Mike Reed62ce2ca2018-02-19 14:20:15 -0500183 SkScalar* origPosPtr = fOrigPos;
Florin Malita64bb78e2017-11-03 12:54:07 -0400184 *origPosPtr++ = prev; // force the first pos to 0
reed9fa60da2014-08-21 07:59:51 -0700185
Florin Malita89ab2402017-11-01 10:14:57 -0400186 int startIndex = dummyFirst ? 0 : 1;
187 int count = desc.fCount + dummyLast;
Florin Malita64bb78e2017-11-03 12:54:07 -0400188
189 bool uniformStops = true;
190 const SkScalar uniformStep = desc.fPos[startIndex] - prev;
Florin Malita89ab2402017-11-01 10:14:57 -0400191 for (int i = startIndex; i < count; i++) {
Florin Malita3e20d022017-11-03 12:11:38 -0400192 // Pin the last value to 1.0, and make sure pos is monotonic.
Florin Malita64bb78e2017-11-03 12:54:07 -0400193 auto curr = (i == desc.fCount) ? 1 : SkScalarPin(desc.fPos[i], prev, 1);
194 uniformStops &= SkScalarNearlyEqual(uniformStep, curr - prev);
195
196 *origPosPtr++ = prev = curr;
reed9fa60da2014-08-21 07:59:51 -0700197 }
Florin Malita64bb78e2017-11-03 12:54:07 -0400198
Florin Malita64bb78e2017-11-03 12:54:07 -0400199 // If the stops are uniform, treat them as implicit.
Mike Reed62ce2ca2018-02-19 14:20:15 -0500200 if (uniformStops) {
Florin Malita64bb78e2017-11-03 12:54:07 -0400201 fOrigPos = nullptr;
202 }
rileya@google.com589708b2012-07-26 20:04:23 +0000203 }
rileya@google.com589708b2012-07-26 20:04:23 +0000204}
205
Florin Malita89ab2402017-11-01 10:14:57 -0400206SkGradientShaderBase::~SkGradientShaderBase() {}
rileya@google.com589708b2012-07-26 20:04:23 +0000207
commit-bot@chromium.org8b0e8ac2014-01-30 18:58:24 +0000208void SkGradientShaderBase::flatten(SkWriteBuffer& buffer) const {
reed9fa60da2014-08-21 07:59:51 -0700209 Descriptor desc;
brianosmane25d71c2016-09-28 11:27:28 -0700210 desc.fColors = fOrigColors4f;
brianosmanb9c51372016-09-15 11:09:45 -0700211 desc.fColorSpace = fColorSpace;
reed9fa60da2014-08-21 07:59:51 -0700212 desc.fPos = fOrigPos;
213 desc.fCount = fColorCount;
214 desc.fTileMode = fTileMode;
215 desc.fGradFlags = fGradFlags;
216
217 const SkMatrix& m = this->getLocalMatrix();
halcanary96fcdcc2015-08-27 07:41:13 -0700218 desc.fLocalMatrix = m.isIdentity() ? nullptr : &m;
reed9fa60da2014-08-21 07:59:51 -0700219 desc.flatten(buffer);
rileya@google.com589708b2012-07-26 20:04:23 +0000220}
221
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400222static void add_stop_color(SkJumper_GradientCtx* ctx, size_t stop, SkPM4f Fs, SkPM4f Bs) {
223 (ctx->fs[0])[stop] = Fs.r();
224 (ctx->fs[1])[stop] = Fs.g();
225 (ctx->fs[2])[stop] = Fs.b();
226 (ctx->fs[3])[stop] = Fs.a();
227 (ctx->bs[0])[stop] = Bs.r();
228 (ctx->bs[1])[stop] = Bs.g();
229 (ctx->bs[2])[stop] = Bs.b();
230 (ctx->bs[3])[stop] = Bs.a();
Mike Kleinf945cbb2017-05-17 09:30:58 -0400231}
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400232
233static void add_const_color(SkJumper_GradientCtx* ctx, size_t stop, SkPM4f color) {
234 add_stop_color(ctx, stop, SkPM4f::FromPremulRGBA(0,0,0,0), color);
Mike Kleinf945cbb2017-05-17 09:30:58 -0400235}
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400236
237// Calculate a factor F and a bias B so that color = F*t + B when t is in range of
238// the stop. Assume that the distance between stops is 1/gapCount.
239static void init_stop_evenly(
240 SkJumper_GradientCtx* ctx, float gapCount, size_t stop, SkPM4f c_l, SkPM4f c_r) {
Mike Klein68768172017-05-17 09:54:36 -0400241 // Clankium's GCC 4.9 targeting ARMv7 is barfing when we use Sk4f math here, so go scalar...
242 SkPM4f Fs = {{
243 (c_r.r() - c_l.r()) * gapCount,
244 (c_r.g() - c_l.g()) * gapCount,
245 (c_r.b() - c_l.b()) * gapCount,
246 (c_r.a() - c_l.a()) * gapCount,
247 }};
248 SkPM4f Bs = {{
249 c_l.r() - Fs.r()*(stop/gapCount),
250 c_l.g() - Fs.g()*(stop/gapCount),
251 c_l.b() - Fs.b()*(stop/gapCount),
252 c_l.a() - Fs.a()*(stop/gapCount),
253 }};
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400254 add_stop_color(ctx, stop, Fs, Bs);
Mike Kleinf945cbb2017-05-17 09:30:58 -0400255}
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400256
257// For each stop we calculate a bias B and a scale factor F, such that
258// for any t between stops n and n+1, the color we want is B[n] + F[n]*t.
259static void init_stop_pos(
260 SkJumper_GradientCtx* ctx, size_t stop, float t_l, float t_r, SkPM4f c_l, SkPM4f c_r) {
Mike Klein68768172017-05-17 09:54:36 -0400261 // See note about Clankium's old compiler in init_stop_evenly().
262 SkPM4f Fs = {{
263 (c_r.r() - c_l.r()) / (t_r - t_l),
264 (c_r.g() - c_l.g()) / (t_r - t_l),
265 (c_r.b() - c_l.b()) / (t_r - t_l),
266 (c_r.a() - c_l.a()) / (t_r - t_l),
267 }};
268 SkPM4f Bs = {{
269 c_l.r() - Fs.r()*t_l,
270 c_l.g() - Fs.g()*t_l,
271 c_l.b() - Fs.b()*t_l,
272 c_l.a() - Fs.a()*t_l,
273 }};
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400274 ctx->ts[stop] = t_l;
275 add_stop_color(ctx, stop, Fs, Bs);
Mike Kleinf945cbb2017-05-17 09:30:58 -0400276}
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400277
Mike Reed1d8c42e2017-08-29 14:58:19 -0400278bool SkGradientShaderBase::onAppendStages(const StageRec& rec) const {
279 SkRasterPipeline* p = rec.fPipeline;
280 SkArenaAlloc* alloc = rec.fAlloc;
281 SkColorSpace* dstCS = rec.fDstCS;
Mike Reed62ce2ca2018-02-19 14:20:15 -0500282 SkJumper_DecalTileCtx* decal_ctx = nullptr;
Mike Reed1d8c42e2017-08-29 14:58:19 -0400283
Mike Kleina3771842017-05-04 19:38:48 -0400284 SkMatrix matrix;
Mike Reed1d8c42e2017-08-29 14:58:19 -0400285 if (!this->computeTotalInverse(rec.fCTM, rec.fLocalM, &matrix)) {
Mike Kleina3771842017-05-04 19:38:48 -0400286 return false;
287 }
Florin Malita50b20842017-07-29 19:08:28 -0400288 matrix.postConcat(fPtsToUnit);
Mike Kleina3771842017-05-04 19:38:48 -0400289
Florin Malita2e409002017-06-28 14:46:54 -0400290 SkRasterPipeline_<256> postPipeline;
Mike Kleina3771842017-05-04 19:38:48 -0400291
Mike Klein85f85362017-10-17 14:22:58 -0400292 p->append_seed_shader();
Mike Reed6b59bf42017-07-03 21:26:44 -0400293 p->append_matrix(alloc, matrix);
Florin Malita50b20842017-07-29 19:08:28 -0400294 this->appendGradientStages(alloc, p, &postPipeline);
Mike Kleine7598532017-05-11 11:29:29 -0400295
Mike Reed62ce2ca2018-02-19 14:20:15 -0500296 switch(fTileMode) {
Mike Klein9f85d682017-05-23 07:52:01 -0400297 case kMirror_TileMode: p->append(SkRasterPipeline::mirror_x_1); break;
298 case kRepeat_TileMode: p->append(SkRasterPipeline::repeat_x_1); break;
Mike Reeddfc0e912018-02-16 12:40:18 -0500299 case kDecal_TileMode:
Mike Reed62ce2ca2018-02-19 14:20:15 -0500300 decal_ctx = alloc->make<SkJumper_DecalTileCtx>();
301 decal_ctx->limit_x = SkBits2Float(SkFloat2Bits(1.0f) + 1);
302 // reuse mask + limit_x stage, or create a custom decal_1 that just stores the mask
303 p->append(SkRasterPipeline::decal_x, decal_ctx);
304 // fall-through to clamp
Mike Kleine7598532017-05-11 11:29:29 -0400305 case kClamp_TileMode:
306 if (!fOrigPos) {
307 // We clamp only when the stops are evenly spaced.
308 // If not, there may be hard stops, and clamping ruins hard stops at 0 and/or 1.
Mike Klein5c7960b2017-05-11 10:59:22 -0400309 // In that case, we must make sure we're using the general "gradient" stage,
Mike Kleine7598532017-05-11 11:29:29 -0400310 // which is the only stage that will correctly handle unclamped t.
Mike Klein9f85d682017-05-23 07:52:01 -0400311 p->append(SkRasterPipeline::clamp_x_1);
Mike Kleine7598532017-05-11 11:29:29 -0400312 }
Mike Reed62ce2ca2018-02-19 14:20:15 -0500313 break;
Mike Kleine7598532017-05-11 11:29:29 -0400314 }
Mike Kleina3771842017-05-04 19:38:48 -0400315
316 const bool premulGrad = fGradFlags & SkGradientShader::kInterpolateColorsInPremul_Flag;
317 auto prepareColor = [premulGrad, dstCS, this](int i) {
Florin Malita0e36b3f2017-06-05 23:33:45 -0400318 SkColor4f c = this->getXformedColor(i, dstCS);
Mike Kleina3771842017-05-04 19:38:48 -0400319 return premulGrad ? c.premul()
320 : SkPM4f::From4f(Sk4f::Load(&c));
321 };
322
323 // The two-stop case with stops at 0 and 1.
324 if (fColorCount == 2 && fOrigPos == nullptr) {
325 const SkPM4f c_l = prepareColor(0),
Mike Reed1d8c42e2017-08-29 14:58:19 -0400326 c_r = prepareColor(1);
Mike Kleina3771842017-05-04 19:38:48 -0400327
328 // See F and B below.
329 auto* f_and_b = alloc->makeArrayDefault<SkPM4f>(2);
330 f_and_b[0] = SkPM4f::From4f(c_r.to4f() - c_l.to4f());
331 f_and_b[1] = c_l;
332
Mike Klein5c7960b2017-05-11 10:59:22 -0400333 p->append(SkRasterPipeline::evenly_spaced_2_stop_gradient, f_and_b);
Mike Kleina3771842017-05-04 19:38:48 -0400334 } else {
Herb Derby4de13042017-05-15 10:49:39 -0400335 auto* ctx = alloc->make<SkJumper_GradientCtx>();
Herb Derby4de13042017-05-15 10:49:39 -0400336
337 // Note: In order to handle clamps in search, the search assumes a stop conceptully placed
338 // at -inf. Therefore, the max number of stops is fColorCount+1.
339 for (int i = 0; i < 4; i++) {
340 // Allocate at least at for the AVX2 gather from a YMM register.
341 ctx->fs[i] = alloc->makeArray<float>(std::max(fColorCount+1, 8));
342 ctx->bs[i] = alloc->makeArray<float>(std::max(fColorCount+1, 8));
343 }
344
Mike Kleina3771842017-05-04 19:38:48 -0400345 if (fOrigPos == nullptr) {
346 // Handle evenly distributed stops.
347
Herb Derby4de13042017-05-15 10:49:39 -0400348 size_t stopCount = fColorCount;
349 float gapCount = stopCount - 1;
Mike Kleina3771842017-05-04 19:38:48 -0400350
Herb Derby4de13042017-05-15 10:49:39 -0400351 SkPM4f c_l = prepareColor(0);
352 for (size_t i = 0; i < stopCount - 1; i++) {
Mike Kleina3771842017-05-04 19:38:48 -0400353 SkPM4f c_r = prepareColor(i + 1);
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400354 init_stop_evenly(ctx, gapCount, i, c_l, c_r);
Mike Kleina3771842017-05-04 19:38:48 -0400355 c_l = c_r;
356 }
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400357 add_const_color(ctx, stopCount - 1, c_l);
Mike Kleina3771842017-05-04 19:38:48 -0400358
Herb Derby4de13042017-05-15 10:49:39 -0400359 ctx->stopCount = stopCount;
360 p->append(SkRasterPipeline::evenly_spaced_gradient, ctx);
Mike Kleina3771842017-05-04 19:38:48 -0400361 } else {
362 // Handle arbitrary stops.
363
Herb Derby4de13042017-05-15 10:49:39 -0400364 ctx->ts = alloc->makeArray<float>(fColorCount+1);
365
Mike Kleina3771842017-05-04 19:38:48 -0400366 // Remove the dummy stops inserted by SkGradientShaderBase::SkGradientShaderBase
367 // because they are naturally handled by the search method.
368 int firstStop;
369 int lastStop;
370 if (fColorCount > 2) {
371 firstStop = fOrigColors4f[0] != fOrigColors4f[1] ? 0 : 1;
372 lastStop = fOrigColors4f[fColorCount - 2] != fOrigColors4f[fColorCount - 1]
373 ? fColorCount - 1 : fColorCount - 2;
374 } else {
375 firstStop = 0;
376 lastStop = 1;
377 }
Mike Kleina3771842017-05-04 19:38:48 -0400378
Mike Kleina3771842017-05-04 19:38:48 -0400379 size_t stopCount = 0;
380 float t_l = fOrigPos[firstStop];
381 SkPM4f c_l = prepareColor(firstStop);
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400382 add_const_color(ctx, stopCount++, c_l);
Mike Kleina3771842017-05-04 19:38:48 -0400383 // N.B. lastStop is the index of the last stop, not one after.
384 for (int i = firstStop; i < lastStop; i++) {
385 float t_r = fOrigPos[i + 1];
386 SkPM4f c_r = prepareColor(i + 1);
Florin Malita3e20d022017-11-03 12:11:38 -0400387 SkASSERT(t_l <= t_r);
Mike Kleina3771842017-05-04 19:38:48 -0400388 if (t_l < t_r) {
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400389 init_stop_pos(ctx, stopCount, t_l, t_r, c_l, c_r);
Mike Kleina3771842017-05-04 19:38:48 -0400390 stopCount += 1;
391 }
392 t_l = t_r;
393 c_l = c_r;
394 }
395
Herb Derby4de13042017-05-15 10:49:39 -0400396 ctx->ts[stopCount] = t_l;
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400397 add_const_color(ctx, stopCount++, c_l);
Mike Kleina3771842017-05-04 19:38:48 -0400398
Herb Derby4de13042017-05-15 10:49:39 -0400399 ctx->stopCount = stopCount;
400 p->append(SkRasterPipeline::gradient, ctx);
Mike Kleina3771842017-05-04 19:38:48 -0400401 }
Mike Kleina3771842017-05-04 19:38:48 -0400402 }
403
Mike Reed62ce2ca2018-02-19 14:20:15 -0500404 if (decal_ctx) {
405 p->append(SkRasterPipeline::check_decal_mask, decal_ctx);
406 }
407
Mike Kleina3771842017-05-04 19:38:48 -0400408 if (!premulGrad && !this->colorsAreOpaque()) {
Mike Kleine7598532017-05-11 11:29:29 -0400409 p->append(SkRasterPipeline::premul);
Mike Kleina3771842017-05-04 19:38:48 -0400410 }
411
Florin Malita2e409002017-06-28 14:46:54 -0400412 p->extend(postPipeline);
413
Mike Kleina3771842017-05-04 19:38:48 -0400414 return true;
415}
416
417
rileya@google.com589708b2012-07-26 20:04:23 +0000418bool SkGradientShaderBase::isOpaque() const {
Mike Reed62ce2ca2018-02-19 14:20:15 -0500419 return fColorsAreOpaque && (this->getTileMode() != SkShader::kDecal_TileMode);
420}
421
422bool SkGradientShaderBase::onIsRasterPipelineOnly(const SkMatrix& ctm) const {
423 if (this->getTileMode() == SkShader::kDecal_TileMode) {
424 return true;
425 }
426 return this->INHERITED::onIsRasterPipelineOnly(ctm);
rileya@google.com589708b2012-07-26 20:04:23 +0000427}
428
reed8367b8c2014-08-22 08:30:20 -0700429static unsigned rounded_divide(unsigned numer, unsigned denom) {
430 return (numer + (denom >> 1)) / denom;
431}
432
433bool SkGradientShaderBase::onAsLuminanceColor(SkColor* lum) const {
434 // we just compute an average color.
435 // possibly we could weight this based on the proportional width for each color
436 // assuming they are not evenly distributed in the fPos array.
437 int r = 0;
438 int g = 0;
439 int b = 0;
440 const int n = fColorCount;
Florin Malita39d71de2017-10-31 11:33:49 -0400441 // TODO: use linear colors?
reed8367b8c2014-08-22 08:30:20 -0700442 for (int i = 0; i < n; ++i) {
Florin Malita39d71de2017-10-31 11:33:49 -0400443 SkColor c = this->getLegacyColor(i);
reed8367b8c2014-08-22 08:30:20 -0700444 r += SkColorGetR(c);
445 g += SkColorGetG(c);
446 b += SkColorGetB(c);
447 }
448 *lum = SkColorSetRGB(rounded_divide(r, n), rounded_divide(g, n), rounded_divide(b, n));
449 return true;
450}
451
Florin Malita39d71de2017-10-31 11:33:49 -0400452SkGradientShaderBase::AutoXformColors::AutoXformColors(const SkGradientShaderBase& grad,
453 SkColorSpaceXformer* xformer)
454 : fColors(grad.fColorCount) {
455 // TODO: stay in 4f to preserve precision?
456
457 SkAutoSTMalloc<8, SkColor> origColors(grad.fColorCount);
458 for (int i = 0; i < grad.fColorCount; ++i) {
459 origColors[i] = grad.getLegacyColor(i);
460 }
461
462 xformer->apply(fColors.get(), origColors.get(), grad.fColorCount);
463}
464
Florin Malitad4e9ec82017-10-25 18:00:26 -0400465static constexpr int kGradientTextureSize = 256;
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000466
Florin Malita84d7cf92017-10-25 15:31:54 -0400467void SkGradientShaderBase::initLinearBitmap(SkBitmap* bitmap, GradientBitmapType bitmapType) const {
brianosmand4546092016-09-22 12:31:58 -0700468 const bool interpInPremul = SkToBool(fGradFlags &
469 SkGradientShader::kInterpolateColorsInPremul_Flag);
brianosmand4546092016-09-22 12:31:58 -0700470 SkHalf* pixelsF16 = reinterpret_cast<SkHalf*>(bitmap->getPixels());
Florin Malita84d7cf92017-10-25 15:31:54 -0400471 uint32_t* pixels32 = reinterpret_cast<uint32_t*>(bitmap->getPixels());
brianosmand4546092016-09-22 12:31:58 -0700472
473 typedef std::function<void(const Sk4f&, int)> pixelWriteFn_t;
474
475 pixelWriteFn_t writeF16Pixel = [&](const Sk4f& x, int index) {
476 Sk4h c = SkFloatToHalf_finite_ftz(x);
477 pixelsF16[4*index+0] = c[0];
478 pixelsF16[4*index+1] = c[1];
479 pixelsF16[4*index+2] = c[2];
480 pixelsF16[4*index+3] = c[3];
481 };
482 pixelWriteFn_t writeS32Pixel = [&](const Sk4f& c, int index) {
Florin Malita84d7cf92017-10-25 15:31:54 -0400483 pixels32[index] = Sk4f_toS32(c);
484 };
485 pixelWriteFn_t writeL32Pixel = [&](const Sk4f& c, int index) {
486 pixels32[index] = Sk4f_toL32(c);
brianosmand4546092016-09-22 12:31:58 -0700487 };
488
489 pixelWriteFn_t writeSizedPixel =
Florin Malita84d7cf92017-10-25 15:31:54 -0400490 (bitmapType == GradientBitmapType::kHalfFloat) ? writeF16Pixel :
491 (bitmapType == GradientBitmapType::kSRGB ) ? writeS32Pixel : writeL32Pixel;
brianosmand4546092016-09-22 12:31:58 -0700492 pixelWriteFn_t writeUnpremulPixel = [&](const Sk4f& c, int index) {
493 writeSizedPixel(c * Sk4f(c[3], c[3], c[3], 1.0f), index);
494 };
495
496 pixelWriteFn_t writePixel = interpInPremul ? writeSizedPixel : writeUnpremulPixel;
497
Florin Malita84d7cf92017-10-25 15:31:54 -0400498 // When not in legacy mode, we just want the original 4f colors - so we pass in
499 // our own CS for identity/no transform.
500 auto* cs = bitmapType != GradientBitmapType::kLegacy ? fColorSpace.get() : nullptr;
501
brianosmand4546092016-09-22 12:31:58 -0700502 int prevIndex = 0;
503 for (int i = 1; i < fColorCount; i++) {
Florin Malitaed6ae562017-10-28 11:06:48 -0400504 // Historically, stops have been mapped to [0, 256], with 256 then nudged to the
505 // next smaller value, then truncate for the texture index. This seems to produce
506 // the best results for some common distributions, so we preserve the behavior.
507 int nextIndex = SkTMin(this->getPos(i) * kGradientTextureSize,
508 SkIntToScalar(kGradientTextureSize - 1));
brianosmand4546092016-09-22 12:31:58 -0700509
510 if (nextIndex > prevIndex) {
Florin Malita84d7cf92017-10-25 15:31:54 -0400511 SkColor4f color0 = this->getXformedColor(i - 1, cs),
512 color1 = this->getXformedColor(i , cs);
513 Sk4f c0 = Sk4f::Load(color0.vec()),
514 c1 = Sk4f::Load(color1.vec());
515
brianosmand4546092016-09-22 12:31:58 -0700516 if (interpInPremul) {
517 c0 = c0 * Sk4f(c0[3], c0[3], c0[3], 1.0f);
518 c1 = c1 * Sk4f(c1[3], c1[3], c1[3], 1.0f);
519 }
520
521 Sk4f step = Sk4f(1.0f / static_cast<float>(nextIndex - prevIndex));
522 Sk4f delta = (c1 - c0) * step;
523
524 for (int curIndex = prevIndex; curIndex <= nextIndex; ++curIndex) {
525 writePixel(c0, curIndex);
526 c0 += delta;
527 }
528 }
529 prevIndex = nextIndex;
530 }
Florin Malitad4e9ec82017-10-25 18:00:26 -0400531 SkASSERT(prevIndex == kGradientTextureSize - 1);
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000532}
533
Florin Malita0e36b3f2017-06-05 23:33:45 -0400534SkColor4f SkGradientShaderBase::getXformedColor(size_t i, SkColorSpace* dstCS) const {
Florin Malita79363b62017-11-01 15:43:52 -0400535 if (dstCS) {
536 return to_colorspace(fOrigColors4f[i], fColorSpace.get(), dstCS);
537 }
538
539 // Legacy/srgb color.
Florin Malita79363b62017-11-01 15:43:52 -0400540 // We quantize upfront to ensure stable SkColor round-trips.
541 auto rgb255 = sk_linear_to_srgb(Sk4f::Load(fOrigColors4f[i].vec()));
542 auto rgb = SkNx_cast<float>(rgb255) * (1/255.0f);
543 return { rgb[0], rgb[1], rgb[2], fOrigColors4f[i].fA };
Florin Malita0e36b3f2017-06-05 23:33:45 -0400544}
545
reed086eea92016-05-04 17:12:46 -0700546SK_DECLARE_STATIC_MUTEX(gGradientCacheMutex);
rileya@google.com589708b2012-07-26 20:04:23 +0000547/*
548 * Because our caller might rebuild the same (logically the same) gradient
549 * over and over, we'd like to return exactly the same "bitmap" if possible,
550 * allowing the client to utilize a cache of our bitmap (e.g. with a GPU).
551 * To do that, we maintain a private cache of built-bitmaps, based on our
Brian Osmanfe3e8582017-10-20 11:27:49 -0400552 * colors and positions.
rileya@google.com589708b2012-07-26 20:04:23 +0000553 */
brianosmand4546092016-09-22 12:31:58 -0700554void SkGradientShaderBase::getGradientTableBitmap(SkBitmap* bitmap,
555 GradientBitmapType bitmapType) const {
brianosmand4546092016-09-22 12:31:58 -0700556 // build our key: [numColors + colors[] + {positions[]} + flags + colorType ]
Florin Malita39d71de2017-10-31 11:33:49 -0400557 static_assert(sizeof(SkColor4f) % sizeof(int32_t) == 0, "");
558 const int colorsAsIntCount = fColorCount * sizeof(SkColor4f) / sizeof(int32_t);
559 int count = 1 + colorsAsIntCount + 1 + 1;
rileya@google.com589708b2012-07-26 20:04:23 +0000560 if (fColorCount > 2) {
Florin Malitacad3b8c2017-10-28 21:42:50 -0400561 count += fColorCount - 1;
rileya@google.com589708b2012-07-26 20:04:23 +0000562 }
563
Florin Malita39d71de2017-10-31 11:33:49 -0400564 SkAutoSTMalloc<64, int32_t> storage(count);
rileya@google.com589708b2012-07-26 20:04:23 +0000565 int32_t* buffer = storage.get();
566
567 *buffer++ = fColorCount;
Florin Malita39d71de2017-10-31 11:33:49 -0400568 memcpy(buffer, fOrigColors4f, fColorCount * sizeof(SkColor4f));
569 buffer += colorsAsIntCount;
rileya@google.com589708b2012-07-26 20:04:23 +0000570 if (fColorCount > 2) {
571 for (int i = 1; i < fColorCount; i++) {
Florin Malitacad3b8c2017-10-28 21:42:50 -0400572 *buffer++ = SkFloat2Bits(this->getPos(i));
rileya@google.com589708b2012-07-26 20:04:23 +0000573 }
574 }
reed@google.com3d3a8602013-05-24 14:58:44 +0000575 *buffer++ = fGradFlags;
brianosmand4546092016-09-22 12:31:58 -0700576 *buffer++ = static_cast<int32_t>(bitmapType);
rileya@google.com589708b2012-07-26 20:04:23 +0000577 SkASSERT(buffer - storage.get() == count);
578
579 ///////////////////////////////////
580
reeda6cac4c2014-08-21 10:50:25 -0700581 static SkGradientBitmapCache* gCache;
brianosmand4546092016-09-22 12:31:58 -0700582 // each cache cost 1K or 2K of RAM, since each bitmap will be 1x256 at either 32bpp or 64bpp
rileya@google.com589708b2012-07-26 20:04:23 +0000583 static const int MAX_NUM_CACHED_GRADIENT_BITMAPS = 32;
bungemand6aeb6d2014-07-25 11:52:47 -0700584 SkAutoMutexAcquire ama(gGradientCacheMutex);
rileya@google.com589708b2012-07-26 20:04:23 +0000585
halcanary96fcdcc2015-08-27 07:41:13 -0700586 if (nullptr == gCache) {
halcanary385fe4d2015-08-26 13:07:48 -0700587 gCache = new SkGradientBitmapCache(MAX_NUM_CACHED_GRADIENT_BITMAPS);
rileya@google.com589708b2012-07-26 20:04:23 +0000588 }
589 size_t size = count * sizeof(int32_t);
590
591 if (!gCache->find(storage.get(), size, bitmap)) {
Florin Malitad4e9ec82017-10-25 18:00:26 -0400592 // For these cases we use the bitmap cache, but not the GradientShaderCache. So just
593 // allocate and populate the bitmap's data directly.
Florin Malita63376532017-10-24 10:56:52 -0400594
Florin Malitad4e9ec82017-10-25 18:00:26 -0400595 SkImageInfo info;
596 switch (bitmapType) {
597 case GradientBitmapType::kLegacy:
598 info = SkImageInfo::Make(kGradientTextureSize, 1, kRGBA_8888_SkColorType,
599 kPremul_SkAlphaType);
600 break;
601 case GradientBitmapType::kSRGB:
602 info = SkImageInfo::Make(kGradientTextureSize, 1, kRGBA_8888_SkColorType,
603 kPremul_SkAlphaType, SkColorSpace::MakeSRGB());
604 break;
605 case GradientBitmapType::kHalfFloat:
606 info = SkImageInfo::Make(kGradientTextureSize, 1, kRGBA_F16_SkColorType,
607 kPremul_SkAlphaType, SkColorSpace::MakeSRGBLinear());
608 break;
brianosmand4546092016-09-22 12:31:58 -0700609 }
Florin Malitad4e9ec82017-10-25 18:00:26 -0400610
611 bitmap->allocPixels(info);
612 this->initLinearBitmap(bitmap, bitmapType);
Robert Phillips7a926392018-02-01 15:49:54 -0500613 bitmap->setImmutable();
rileya@google.com589708b2012-07-26 20:04:23 +0000614 gCache->add(storage.get(), size, *bitmap);
615 }
616}
617
Florin Malita5f379a82017-10-18 16:22:35 -0400618void SkGradientShaderBase::commonAsAGradient(GradientInfo* info) const {
rileya@google.com589708b2012-07-26 20:04:23 +0000619 if (info) {
620 if (info->fColorCount >= fColorCount) {
621 if (info->fColors) {
Florin Malita39d71de2017-10-31 11:33:49 -0400622 for (int i = 0; i < fColorCount; ++i) {
623 info->fColors[i] = this->getLegacyColor(i);
624 }
rileya@google.com589708b2012-07-26 20:04:23 +0000625 }
626 if (info->fColorOffsets) {
Florin Malitaed6ae562017-10-28 11:06:48 -0400627 for (int i = 0; i < fColorCount; ++i) {
628 info->fColorOffsets[i] = this->getPos(i);
rileya@google.com589708b2012-07-26 20:04:23 +0000629 }
630 }
631 }
632 info->fColorCount = fColorCount;
633 info->fTileMode = fTileMode;
reed@google.com3d3a8602013-05-24 14:58:44 +0000634 info->fGradientFlags = fGradFlags;
rileya@google.com589708b2012-07-26 20:04:23 +0000635 }
636}
637
commit-bot@chromium.org0f10f7b2014-03-13 18:02:17 +0000638#ifndef SK_IGNORE_TO_STRING
robertphillips@google.com76f9e932013-01-15 20:17:47 +0000639void SkGradientShaderBase::toString(SkString* str) const {
640
641 str->appendf("%d colors: ", fColorCount);
642
643 for (int i = 0; i < fColorCount; ++i) {
Florin Malita39d71de2017-10-31 11:33:49 -0400644 str->appendHex(this->getLegacyColor(i), 8);
robertphillips@google.com76f9e932013-01-15 20:17:47 +0000645 if (i < fColorCount-1) {
646 str->append(", ");
647 }
648 }
649
650 if (fColorCount > 2) {
651 str->append(" points: (");
652 for (int i = 0; i < fColorCount; ++i) {
Florin Malitaed6ae562017-10-28 11:06:48 -0400653 str->appendScalar(this->getPos(i));
robertphillips@google.com76f9e932013-01-15 20:17:47 +0000654 if (i < fColorCount-1) {
655 str->append(", ");
656 }
657 }
658 str->append(")");
659 }
660
661 static const char* gTileModeName[SkShader::kTileModeCount] = {
Mike Reeddfc0e912018-02-16 12:40:18 -0500662 "clamp", "repeat", "mirror", "decal",
robertphillips@google.com76f9e932013-01-15 20:17:47 +0000663 };
664
665 str->append(" ");
666 str->append(gTileModeName[fTileMode]);
667
robertphillips@google.com76f9e932013-01-15 20:17:47 +0000668 this->INHERITED::toString(str);
669}
670#endif
671
rileya@google.com589708b2012-07-26 20:04:23 +0000672///////////////////////////////////////////////////////////////////////////////
673///////////////////////////////////////////////////////////////////////////////
674
reed1b747302015-01-06 07:13:19 -0800675// Return true if these parameters are valid/legal/safe to construct a gradient
676//
brianosmane25d71c2016-09-28 11:27:28 -0700677static bool valid_grad(const SkColor4f colors[], const SkScalar pos[], int count,
678 unsigned tileMode) {
halcanary96fcdcc2015-08-27 07:41:13 -0700679 return nullptr != colors && count >= 1 && tileMode < (unsigned)SkShader::kTileModeCount;
reed1b747302015-01-06 07:13:19 -0800680}
681
reed@google.com437d6eb2013-05-23 19:03:05 +0000682static void desc_init(SkGradientShaderBase::Descriptor* desc,
brianosmane25d71c2016-09-28 11:27:28 -0700683 const SkColor4f colors[], sk_sp<SkColorSpace> colorSpace,
684 const SkScalar pos[], int colorCount,
reedaddf2ed2014-08-11 08:28:24 -0700685 SkShader::TileMode mode, uint32_t flags, const SkMatrix* localMatrix) {
fmalita748d6202016-05-11 11:39:58 -0700686 SkASSERT(colorCount > 1);
687
commit-bot@chromium.org6c5aea22014-04-22 16:25:15 +0000688 desc->fColors = colors;
brianosmane25d71c2016-09-28 11:27:28 -0700689 desc->fColorSpace = std::move(colorSpace);
commit-bot@chromium.org6c5aea22014-04-22 16:25:15 +0000690 desc->fPos = pos;
691 desc->fCount = colorCount;
692 desc->fTileMode = mode;
commit-bot@chromium.org6c5aea22014-04-22 16:25:15 +0000693 desc->fGradFlags = flags;
reedaddf2ed2014-08-11 08:28:24 -0700694 desc->fLocalMatrix = localMatrix;
reed@google.com437d6eb2013-05-23 19:03:05 +0000695}
696
brianosmane25d71c2016-09-28 11:27:28 -0700697// assumes colors is SkColor4f* and pos is SkScalar*
fmenozzie9fd0f82016-08-19 07:50:57 -0700698#define EXPAND_1_COLOR(count) \
brianosmane25d71c2016-09-28 11:27:28 -0700699 SkColor4f tmp[2]; \
fmenozzie9fd0f82016-08-19 07:50:57 -0700700 do { \
701 if (1 == count) { \
702 tmp[0] = tmp[1] = colors[0]; \
703 colors = tmp; \
704 pos = nullptr; \
705 count = 2; \
706 } \
707 } while (0)
708
fmenozzi68d952c2016-08-19 08:56:56 -0700709struct ColorStopOptimizer {
brianosmane25d71c2016-09-28 11:27:28 -0700710 ColorStopOptimizer(const SkColor4f* colors, const SkScalar* pos,
fmenozzi68d952c2016-08-19 08:56:56 -0700711 int count, SkShader::TileMode mode)
712 : fColors(colors)
713 , fPos(pos)
714 , fCount(count) {
715
716 if (!pos || count != 3) {
717 return;
718 }
719
720 if (SkScalarNearlyEqual(pos[0], 0.0f) &&
721 SkScalarNearlyEqual(pos[1], 0.0f) &&
722 SkScalarNearlyEqual(pos[2], 1.0f)) {
723
724 if (SkShader::kRepeat_TileMode == mode ||
725 SkShader::kMirror_TileMode == mode ||
726 colors[0] == colors[1]) {
727
fmalita582a6562016-08-22 06:28:57 -0700728 // Ignore the leftmost color/pos.
729 fColors += 1;
730 fPos += 1;
731 fCount = 2;
fmenozzi68d952c2016-08-19 08:56:56 -0700732 }
733 } else if (SkScalarNearlyEqual(pos[0], 0.0f) &&
734 SkScalarNearlyEqual(pos[1], 1.0f) &&
735 SkScalarNearlyEqual(pos[2], 1.0f)) {
736
737 if (SkShader::kRepeat_TileMode == mode ||
738 SkShader::kMirror_TileMode == mode ||
739 colors[1] == colors[2]) {
740
fmalita582a6562016-08-22 06:28:57 -0700741 // Ignore the rightmost color/pos.
fmenozzi68d952c2016-08-19 08:56:56 -0700742 fCount = 2;
743 }
744 }
745 }
746
brianosmane25d71c2016-09-28 11:27:28 -0700747 const SkColor4f* fColors;
748 const SkScalar* fPos;
749 int fCount;
750};
751
752struct ColorConverter {
753 ColorConverter(const SkColor* colors, int count) {
754 for (int i = 0; i < count; ++i) {
755 fColors4f.push_back(SkColor4f::FromColor(colors[i]));
756 }
757 }
758
759 SkSTArray<2, SkColor4f, true> fColors4f;
fmenozzi68d952c2016-08-19 08:56:56 -0700760};
761
reed8a21c9f2016-03-08 18:50:00 -0800762sk_sp<SkShader> SkGradientShader::MakeLinear(const SkPoint pts[2],
fmenozzi68d952c2016-08-19 08:56:56 -0700763 const SkColor colors[],
764 const SkScalar pos[], int colorCount,
765 SkShader::TileMode mode,
766 uint32_t flags,
767 const SkMatrix* localMatrix) {
brianosmane25d71c2016-09-28 11:27:28 -0700768 ColorConverter converter(colors, colorCount);
769 return MakeLinear(pts, converter.fColors4f.begin(), nullptr, pos, colorCount, mode, flags,
770 localMatrix);
771}
772
773sk_sp<SkShader> SkGradientShader::MakeLinear(const SkPoint pts[2],
774 const SkColor4f colors[],
775 sk_sp<SkColorSpace> colorSpace,
776 const SkScalar pos[], int colorCount,
777 SkShader::TileMode mode,
778 uint32_t flags,
779 const SkMatrix* localMatrix) {
fmalitac5231042016-08-10 05:45:50 -0700780 if (!pts || !SkScalarIsFinite((pts[1] - pts[0]).length())) {
halcanary96fcdcc2015-08-27 07:41:13 -0700781 return nullptr;
reed1b747302015-01-06 07:13:19 -0800782 }
783 if (!valid_grad(colors, pos, colorCount, mode)) {
halcanary96fcdcc2015-08-27 07:41:13 -0700784 return nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +0000785 }
fmenozzie9fd0f82016-08-19 07:50:57 -0700786 if (1 == colorCount) {
brianosmane25d71c2016-09-28 11:27:28 -0700787 return SkShader::MakeColorShader(colors[0], std::move(colorSpace));
fmenozzie9fd0f82016-08-19 07:50:57 -0700788 }
Florin Malita8d3ffad2017-02-03 18:21:17 +0000789 if (localMatrix && !localMatrix->invert(nullptr)) {
790 return nullptr;
791 }
rileya@google.com589708b2012-07-26 20:04:23 +0000792
fmenozzi68d952c2016-08-19 08:56:56 -0700793 ColorStopOptimizer opt(colors, pos, colorCount, mode);
794
reed@google.com437d6eb2013-05-23 19:03:05 +0000795 SkGradientShaderBase::Descriptor desc;
brianosmane25d71c2016-09-28 11:27:28 -0700796 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
797 localMatrix);
reed8a21c9f2016-03-08 18:50:00 -0800798 return sk_make_sp<SkLinearGradient>(pts, desc);
rileya@google.com589708b2012-07-26 20:04:23 +0000799}
800
reed8a21c9f2016-03-08 18:50:00 -0800801sk_sp<SkShader> SkGradientShader::MakeRadial(const SkPoint& center, SkScalar radius,
brianosmane25d71c2016-09-28 11:27:28 -0700802 const SkColor colors[],
803 const SkScalar pos[], int colorCount,
804 SkShader::TileMode mode,
805 uint32_t flags,
806 const SkMatrix* localMatrix) {
807 ColorConverter converter(colors, colorCount);
808 return MakeRadial(center, radius, converter.fColors4f.begin(), nullptr, pos, colorCount, mode,
809 flags, localMatrix);
810}
811
812sk_sp<SkShader> SkGradientShader::MakeRadial(const SkPoint& center, SkScalar radius,
813 const SkColor4f colors[],
814 sk_sp<SkColorSpace> colorSpace,
815 const SkScalar pos[], int colorCount,
816 SkShader::TileMode mode,
817 uint32_t flags,
818 const SkMatrix* localMatrix) {
reed1b747302015-01-06 07:13:19 -0800819 if (radius <= 0) {
halcanary96fcdcc2015-08-27 07:41:13 -0700820 return nullptr;
reed1b747302015-01-06 07:13:19 -0800821 }
822 if (!valid_grad(colors, pos, colorCount, mode)) {
halcanary96fcdcc2015-08-27 07:41:13 -0700823 return nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +0000824 }
fmenozzie9fd0f82016-08-19 07:50:57 -0700825 if (1 == colorCount) {
brianosmane25d71c2016-09-28 11:27:28 -0700826 return SkShader::MakeColorShader(colors[0], std::move(colorSpace));
fmenozzie9fd0f82016-08-19 07:50:57 -0700827 }
Florin Malita8d3ffad2017-02-03 18:21:17 +0000828 if (localMatrix && !localMatrix->invert(nullptr)) {
829 return nullptr;
830 }
rileya@google.com589708b2012-07-26 20:04:23 +0000831
fmenozzi68d952c2016-08-19 08:56:56 -0700832 ColorStopOptimizer opt(colors, pos, colorCount, mode);
833
reed@google.com437d6eb2013-05-23 19:03:05 +0000834 SkGradientShaderBase::Descriptor desc;
brianosmane25d71c2016-09-28 11:27:28 -0700835 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
836 localMatrix);
reed8a21c9f2016-03-08 18:50:00 -0800837 return sk_make_sp<SkRadialGradient>(center, radius, desc);
rileya@google.com589708b2012-07-26 20:04:23 +0000838}
839
reed8a21c9f2016-03-08 18:50:00 -0800840sk_sp<SkShader> SkGradientShader::MakeTwoPointConical(const SkPoint& start,
brianosmane25d71c2016-09-28 11:27:28 -0700841 SkScalar startRadius,
842 const SkPoint& end,
843 SkScalar endRadius,
844 const SkColor colors[],
845 const SkScalar pos[],
846 int colorCount,
847 SkShader::TileMode mode,
848 uint32_t flags,
849 const SkMatrix* localMatrix) {
850 ColorConverter converter(colors, colorCount);
851 return MakeTwoPointConical(start, startRadius, end, endRadius, converter.fColors4f.begin(),
852 nullptr, pos, colorCount, mode, flags, localMatrix);
853}
854
855sk_sp<SkShader> SkGradientShader::MakeTwoPointConical(const SkPoint& start,
856 SkScalar startRadius,
857 const SkPoint& end,
858 SkScalar endRadius,
859 const SkColor4f colors[],
860 sk_sp<SkColorSpace> colorSpace,
861 const SkScalar pos[],
862 int colorCount,
863 SkShader::TileMode mode,
864 uint32_t flags,
865 const SkMatrix* localMatrix) {
reed1b747302015-01-06 07:13:19 -0800866 if (startRadius < 0 || endRadius < 0) {
halcanary96fcdcc2015-08-27 07:41:13 -0700867 return nullptr;
reed1b747302015-01-06 07:13:19 -0800868 }
Florin Malita327290f2017-07-07 09:23:16 -0400869 if (SkScalarNearlyZero((start - end).length()) && SkScalarNearlyZero(startRadius)) {
870 // We can treat this gradient as radial, which is faster.
871 return MakeRadial(start, endRadius, colors, std::move(colorSpace), pos, colorCount,
872 mode, flags, localMatrix);
873 }
reed1b747302015-01-06 07:13:19 -0800874 if (!valid_grad(colors, pos, colorCount, mode)) {
halcanary96fcdcc2015-08-27 07:41:13 -0700875 return nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +0000876 }
fmalita5edf82e2016-03-03 06:41:54 -0800877 if (startRadius == endRadius) {
878 if (start == end || startRadius == 0) {
reed8a21c9f2016-03-08 18:50:00 -0800879 return SkShader::MakeEmptyShader();
fmalita5edf82e2016-03-03 06:41:54 -0800880 }
rileya@google.com589708b2012-07-26 20:04:23 +0000881 }
Florin Malita8d3ffad2017-02-03 18:21:17 +0000882 if (localMatrix && !localMatrix->invert(nullptr)) {
883 return nullptr;
884 }
reed6b7a6c72016-08-18 16:13:50 -0700885 EXPAND_1_COLOR(colorCount);
rileya@google.com589708b2012-07-26 20:04:23 +0000886
fmenozzi68d952c2016-08-19 08:56:56 -0700887 ColorStopOptimizer opt(colors, pos, colorCount, mode);
888
reed@google.com437d6eb2013-05-23 19:03:05 +0000889 SkGradientShaderBase::Descriptor desc;
Florin Malita5f379a82017-10-18 16:22:35 -0400890 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
891 localMatrix);
892 return SkTwoPointConicalGradient::Create(start, startRadius, end, endRadius, desc);
rileya@google.com589708b2012-07-26 20:04:23 +0000893}
894
reed8a21c9f2016-03-08 18:50:00 -0800895sk_sp<SkShader> SkGradientShader::MakeSweep(SkScalar cx, SkScalar cy,
brianosmane25d71c2016-09-28 11:27:28 -0700896 const SkColor colors[],
897 const SkScalar pos[],
898 int colorCount,
Florin Malita5a9a9812017-08-01 16:38:08 -0400899 SkShader::TileMode mode,
900 SkScalar startAngle,
901 SkScalar endAngle,
brianosmane25d71c2016-09-28 11:27:28 -0700902 uint32_t flags,
903 const SkMatrix* localMatrix) {
904 ColorConverter converter(colors, colorCount);
Florin Malita5a9a9812017-08-01 16:38:08 -0400905 return MakeSweep(cx, cy, converter.fColors4f.begin(), nullptr, pos, colorCount,
906 mode, startAngle, endAngle, flags, localMatrix);
brianosmane25d71c2016-09-28 11:27:28 -0700907}
908
909sk_sp<SkShader> SkGradientShader::MakeSweep(SkScalar cx, SkScalar cy,
910 const SkColor4f colors[],
911 sk_sp<SkColorSpace> colorSpace,
912 const SkScalar pos[],
913 int colorCount,
Florin Malita5a9a9812017-08-01 16:38:08 -0400914 SkShader::TileMode mode,
915 SkScalar startAngle,
916 SkScalar endAngle,
brianosmane25d71c2016-09-28 11:27:28 -0700917 uint32_t flags,
918 const SkMatrix* localMatrix) {
Florin Malita5a9a9812017-08-01 16:38:08 -0400919 if (!valid_grad(colors, pos, colorCount, mode)) {
halcanary96fcdcc2015-08-27 07:41:13 -0700920 return nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +0000921 }
fmenozzie9fd0f82016-08-19 07:50:57 -0700922 if (1 == colorCount) {
brianosmane25d71c2016-09-28 11:27:28 -0700923 return SkShader::MakeColorShader(colors[0], std::move(colorSpace));
fmenozzie9fd0f82016-08-19 07:50:57 -0700924 }
Florin Malita5a9a9812017-08-01 16:38:08 -0400925 if (startAngle >= endAngle) {
926 return nullptr;
927 }
Florin Malita8d3ffad2017-02-03 18:21:17 +0000928 if (localMatrix && !localMatrix->invert(nullptr)) {
929 return nullptr;
930 }
rileya@google.com589708b2012-07-26 20:04:23 +0000931
Florin Malita5a9a9812017-08-01 16:38:08 -0400932 if (startAngle <= 0 && endAngle >= 360) {
933 // If the t-range includes [0,1], then we can always use clamping (presumably faster).
934 mode = SkShader::kClamp_TileMode;
935 }
fmenozzi68d952c2016-08-19 08:56:56 -0700936
937 ColorStopOptimizer opt(colors, pos, colorCount, mode);
938
reed@google.com437d6eb2013-05-23 19:03:05 +0000939 SkGradientShaderBase::Descriptor desc;
brianosmane25d71c2016-09-28 11:27:28 -0700940 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
941 localMatrix);
Florin Malita5a9a9812017-08-01 16:38:08 -0400942
943 const SkScalar t0 = startAngle / 360,
944 t1 = endAngle / 360;
945
946 return sk_make_sp<SkSweepGradient>(SkPoint::Make(cx, cy), t0, t1, desc);
rileya@google.com589708b2012-07-26 20:04:23 +0000947}
948
949SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_START(SkGradientShader)
950 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkLinearGradient)
951 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkRadialGradient)
952 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkSweepGradient)
rileya@google.com589708b2012-07-26 20:04:23 +0000953 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkTwoPointConicalGradient)
954SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_END
rileya@google.comd7cc6512012-07-27 14:00:39 +0000955
956///////////////////////////////////////////////////////////////////////////////
957
bsalomon@google.comcf8fb1f2012-08-02 14:03:32 +0000958#if SK_SUPPORT_GPU
959
Brian Osman5911a7c2017-10-25 12:52:31 -0400960#include "GrColorSpaceXform.h"
brianosmana6359362016-03-21 06:55:37 -0700961#include "GrContext.h"
Robert Phillips1afd4cd2018-01-08 13:40:32 -0500962#include "GrContextPriv.h"
Brian Salomon94efbf52016-11-29 13:43:05 -0500963#include "GrShaderCaps.h"
ajuma95243eb2016-08-24 08:19:02 -0700964#include "GrTextureStripAtlas.h"
egdanielf5294392015-10-21 07:14:17 -0700965#include "gl/GrGLContext.h"
egdaniel2d721d32015-11-11 13:06:05 -0800966#include "glsl/GrGLSLFragmentShaderBuilder.h"
egdaniel018fb622015-10-28 07:26:40 -0700967#include "glsl/GrGLSLProgramDataManager.h"
egdaniel7ea439b2015-12-03 09:20:44 -0800968#include "glsl/GrGLSLUniformHandler.h"
bsalomon@google.comcf8fb1f2012-08-02 14:03:32 +0000969#include "SkGr.h"
970
fmenozzi55d318d2016-08-09 08:05:57 -0700971void GrGradientEffect::GLSLProcessor::emitUniforms(GrGLSLUniformHandler* uniformHandler,
972 const GrGradientEffect& ge) {
Florin Malita14a8dd72017-11-08 15:46:42 -0500973 switch (ge.fStrategy) {
974 case GrGradientEffect::InterpolationStrategy::kThreshold:
975 case GrGradientEffect::InterpolationStrategy::kThresholdClamp0:
976 case GrGradientEffect::InterpolationStrategy::kThresholdClamp1:
977 fThresholdUni = uniformHandler->addUniform(kFragment_GrShaderFlag,
978 kFloat_GrSLType,
979 kHigh_GrSLPrecision,
980 "Threshold");
981 // fall through
982 case GrGradientEffect::InterpolationStrategy::kSingle:
983 fIntervalsUni = uniformHandler->addUniformArray(kFragment_GrShaderFlag,
984 kHalf4_GrSLType,
985 "Intervals",
986 ge.fIntervals.count());
987 break;
988 case GrGradientEffect::InterpolationStrategy::kTexture:
989 fFSYUni = uniformHandler->addUniform(kFragment_GrShaderFlag, kHalf_GrSLType,
990 "GradientYCoordFS");
991 break;
bsalomon@google.com82d12232013-09-09 15:36:26 +0000992 }
993}
994
fmenozzi55d318d2016-08-09 08:05:57 -0700995void GrGradientEffect::GLSLProcessor::onSetData(const GrGLSLProgramDataManager& pdman,
Brian Salomonab015ef2017-04-04 10:15:51 -0400996 const GrFragmentProcessor& processor) {
joshualittb0a8a372014-09-23 09:50:21 -0700997 const GrGradientEffect& e = processor.cast<GrGradientEffect>();
bsalomon@google.com82d12232013-09-09 15:36:26 +0000998
Florin Malita14a8dd72017-11-08 15:46:42 -0500999 switch (e.fStrategy) {
1000 case GrGradientEffect::InterpolationStrategy::kThreshold:
1001 case GrGradientEffect::InterpolationStrategy::kThresholdClamp0:
1002 case GrGradientEffect::InterpolationStrategy::kThresholdClamp1:
1003 pdman.set1f(fThresholdUni, e.fThreshold);
Brian Salomon466ad992016-10-13 16:08:36 -04001004 // fall through
Florin Malita14a8dd72017-11-08 15:46:42 -05001005 case GrGradientEffect::InterpolationStrategy::kSingle:
1006 pdman.set4fv(fIntervalsUni, e.fIntervals.count(),
1007 reinterpret_cast<const float*>(e.fIntervals.begin()));
fmenozzicd9a1d02016-08-15 07:03:47 -07001008 break;
Florin Malita14a8dd72017-11-08 15:46:42 -05001009 case GrGradientEffect::InterpolationStrategy::kTexture:
1010 if (e.fYCoord != fCachedYCoord) {
1011 pdman.set1f(fFSYUni, e.fYCoord);
1012 fCachedYCoord = e.fYCoord;
fmenozzicd9a1d02016-08-15 07:03:47 -07001013 }
1014 break;
rileya@google.comb3e50f22012-08-20 17:43:08 +00001015 }
1016}
1017
Florin Malitae657dc82017-11-03 08:46:18 -04001018void GrGradientEffect::onGetGLSLProcessorKey(const GrShaderCaps&, GrProcessorKeyBuilder* b) const {
1019 b->add32(GLSLProcessor::GenBaseGradientKey(*this));
1020}
1021
fmenozzi55d318d2016-08-09 08:05:57 -07001022uint32_t GrGradientEffect::GLSLProcessor::GenBaseGradientKey(const GrProcessor& processor) {
joshualittb0a8a372014-09-23 09:50:21 -07001023 const GrGradientEffect& e = processor.cast<GrGradientEffect>();
skia.committer@gmail.com9a070f22013-09-10 07:01:44 +00001024
Florin Malita14a8dd72017-11-08 15:46:42 -05001025 // Build a key using the following bit allocation:
1026 static constexpr uint32_t kStrategyBits = 3;
1027 static constexpr uint32_t kPremulBits = 1;
1028 SkDEBUGCODE(static constexpr uint32_t kWrapModeBits = 2;)
bsalomon@google.com82d12232013-09-09 15:36:26 +00001029
Florin Malita14a8dd72017-11-08 15:46:42 -05001030 uint32_t key = static_cast<uint32_t>(e.fStrategy);
1031 SkASSERT(key < (1 << kStrategyBits));
1032
1033 // This is already baked into the table for texture gradients,
1034 // and only changes behavior for analytical gradients.
1035 if (e.fStrategy != InterpolationStrategy::kTexture &&
1036 e.fPremulType == GrGradientEffect::kBeforeInterp_PremulType) {
1037 key |= 1 << kStrategyBits;
1038 SkASSERT(key < (1 << (kStrategyBits + kPremulBits)));
bsalomon@google.com82d12232013-09-09 15:36:26 +00001039 }
1040
Florin Malita14a8dd72017-11-08 15:46:42 -05001041 key |= static_cast<uint32_t>(e.fWrapMode) << (kStrategyBits + kPremulBits);
1042 SkASSERT(key < (1 << (kStrategyBits + kPremulBits + kWrapModeBits)));
fmenozzicd9a1d02016-08-15 07:03:47 -07001043
bsalomon@google.com82d12232013-09-09 15:36:26 +00001044 return key;
bsalomon@google.comd8b5fac2012-11-01 17:02:46 +00001045}
1046
Florin Malitab81a8b92017-08-08 12:14:17 -04001047void GrGradientEffect::GLSLProcessor::emitAnalyticalColor(GrGLSLFPFragmentBuilder* fragBuilder,
1048 GrGLSLUniformHandler* uniformHandler,
1049 const GrShaderCaps* shaderCaps,
1050 const GrGradientEffect& ge,
1051 const char* t,
1052 const char* outputColor,
1053 const char* inputColor) {
1054 // First, apply tiling rules.
Brian Salomon2bbdcc42017-09-07 12:36:34 -04001055 switch (ge.fWrapMode) {
1056 case GrSamplerState::WrapMode::kClamp:
Florin Malita14a8dd72017-11-08 15:46:42 -05001057 switch (ge.fStrategy) {
1058 case GrGradientEffect::InterpolationStrategy::kThresholdClamp0:
1059 // allow t > 1, in order to hit the clamp interval (1, inf)
1060 fragBuilder->codeAppendf("half tiled_t = max(%s, 0.0);", t);
1061 break;
1062 case GrGradientEffect::InterpolationStrategy::kThresholdClamp1:
1063 // allow t < 0, in order to hit the clamp interval (-inf, 0)
1064 fragBuilder->codeAppendf("half tiled_t = min(%s, 1.0);", t);
1065 break;
1066 default:
1067 // regular [0, 1] clamping
1068 fragBuilder->codeAppendf("half tiled_t = clamp(%s, 0.0, 1.0);", t);
1069 }
Brian Salomon2bbdcc42017-09-07 12:36:34 -04001070 break;
1071 case GrSamplerState::WrapMode::kRepeat:
Florin Malita14a8dd72017-11-08 15:46:42 -05001072 fragBuilder->codeAppendf("half tiled_t = fract(%s);", t);
Brian Salomon2bbdcc42017-09-07 12:36:34 -04001073 break;
1074 case GrSamplerState::WrapMode::kMirrorRepeat:
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001075 fragBuilder->codeAppendf("half t_1 = %s - 1.0;", t);
Greg Daniel10ed2432017-12-01 16:19:43 -05001076 fragBuilder->codeAppendf("half tiled_t = t_1 - 2.0 * floor(t_1 * 0.5) - 1.0;");
1077 if (shaderCaps->mustDoOpBetweenFloorAndAbs()) {
1078 // At this point the expected value of tiled_t should between -1 and 1, so this
1079 // clamp has no effect other than to break up the floor and abs calls and make sure
1080 // the compiler doesn't merge them back together.
1081 fragBuilder->codeAppendf("tiled_t = clamp(tiled_t, -1.0, 1.0);");
1082 }
1083 fragBuilder->codeAppendf("tiled_t = abs(tiled_t);");
Brian Salomon2bbdcc42017-09-07 12:36:34 -04001084 break;
Florin Malita8a0044f2017-08-07 14:38:22 -04001085 }
Florin Malita8a0044f2017-08-07 14:38:22 -04001086
Florin Malitab81a8b92017-08-08 12:14:17 -04001087 // Calculate the color.
Florin Malita14a8dd72017-11-08 15:46:42 -05001088 const char* intervals = uniformHandler->getUniformCStr(fIntervalsUni);
fmenozzicd9a1d02016-08-15 07:03:47 -07001089
Florin Malita14a8dd72017-11-08 15:46:42 -05001090 switch (ge.fStrategy) {
1091 case GrGradientEffect::InterpolationStrategy::kSingle:
1092 SkASSERT(ge.fIntervals.count() == 2);
1093 fragBuilder->codeAppendf(
1094 "half4 color_scale = %s[0],"
1095 " color_bias = %s[1];"
1096 , intervals, intervals
1097 );
fmenozzicd9a1d02016-08-15 07:03:47 -07001098 break;
Florin Malita14a8dd72017-11-08 15:46:42 -05001099 case GrGradientEffect::InterpolationStrategy::kThreshold:
1100 case GrGradientEffect::InterpolationStrategy::kThresholdClamp0:
1101 case GrGradientEffect::InterpolationStrategy::kThresholdClamp1:
1102 {
1103 SkASSERT(ge.fIntervals.count() == 4);
1104 const char* threshold = uniformHandler->getUniformCStr(fThresholdUni);
1105 fragBuilder->codeAppendf(
1106 "half4 color_scale, color_bias;"
1107 "if (tiled_t < %s) {"
1108 " color_scale = %s[0];"
1109 " color_bias = %s[1];"
1110 "} else {"
1111 " color_scale = %s[2];"
1112 " color_bias = %s[3];"
1113 "}"
1114 , threshold, intervals, intervals, intervals, intervals
1115 );
1116 } break;
Florin Malitab81a8b92017-08-08 12:14:17 -04001117 default:
1118 SkASSERT(false);
fmenozzicd9a1d02016-08-15 07:03:47 -07001119 break;
bsalomon@google.com82d12232013-09-09 15:36:26 +00001120 }
Florin Malitab81a8b92017-08-08 12:14:17 -04001121
Florin Malita14a8dd72017-11-08 15:46:42 -05001122 fragBuilder->codeAppend("half4 colorTemp = tiled_t * color_scale + color_bias;");
1123
Brian Osmanfe3e8582017-10-20 11:27:49 -04001124 // We could skip this step if all colors are known to be opaque. Two considerations:
Florin Malitab81a8b92017-08-08 12:14:17 -04001125 // The gradient SkShader reporting opaque is more restrictive than necessary in the two
1126 // pt case. Make sure the key reflects this optimization (and note that it can use the
Brian Osmanfe3e8582017-10-20 11:27:49 -04001127 // same shader as the kBeforeInterp case).
Florin Malita14a8dd72017-11-08 15:46:42 -05001128 if (ge.fPremulType == GrGradientEffect::kAfterInterp_PremulType) {
Florin Malitab81a8b92017-08-08 12:14:17 -04001129 fragBuilder->codeAppend("colorTemp.rgb *= colorTemp.a;");
1130 }
Brian Osman5911a7c2017-10-25 12:52:31 -04001131
1132 // If the input colors were floats, or there was a color space xform, we may end up out of
Brian Osman8f912d52017-10-26 12:10:11 -04001133 // range. The simplest solution is to always clamp our (premul) value here. We only need to
1134 // clamp RGB, but that causes hangs on the Tegra3 Nexus7. Clamping RGBA avoids the problem.
1135 fragBuilder->codeAppend("colorTemp = clamp(colorTemp, 0, colorTemp.a);");
Florin Malitab81a8b92017-08-08 12:14:17 -04001136
1137 fragBuilder->codeAppendf("%s = %s * colorTemp;", outputColor, inputColor);
1138}
1139
1140void GrGradientEffect::GLSLProcessor::emitColor(GrGLSLFPFragmentBuilder* fragBuilder,
1141 GrGLSLUniformHandler* uniformHandler,
1142 const GrShaderCaps* shaderCaps,
1143 const GrGradientEffect& ge,
1144 const char* gradientTValue,
1145 const char* outputColor,
1146 const char* inputColor,
1147 const TextureSamplers& texSamplers) {
Florin Malita14a8dd72017-11-08 15:46:42 -05001148 if (ge.fStrategy != InterpolationStrategy::kTexture) {
Florin Malitab81a8b92017-08-08 12:14:17 -04001149 this->emitAnalyticalColor(fragBuilder, uniformHandler, shaderCaps, ge, gradientTValue,
1150 outputColor, inputColor);
1151 return;
1152 }
1153
Florin Malitab81a8b92017-08-08 12:14:17 -04001154 const char* fsyuni = uniformHandler->getUniformCStr(fFSYUni);
1155
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001156 fragBuilder->codeAppendf("half2 coord = half2(%s, %s);", gradientTValue, fsyuni);
Florin Malitab81a8b92017-08-08 12:14:17 -04001157 fragBuilder->codeAppendf("%s = ", outputColor);
1158 fragBuilder->appendTextureLookupAndModulate(inputColor, texSamplers[0], "coord",
Brian Osman5911a7c2017-10-25 12:52:31 -04001159 kFloat2_GrSLType);
Florin Malitab81a8b92017-08-08 12:14:17 -04001160 fragBuilder->codeAppend(";");
rileya@google.comd7cc6512012-07-27 14:00:39 +00001161}
1162
1163/////////////////////////////////////////////////////////////////////
1164
Brian Salomon587e08f2017-01-27 10:59:27 -05001165inline GrFragmentProcessor::OptimizationFlags GrGradientEffect::OptFlags(bool isOpaque) {
Brian Salomonf3b995b2017-02-15 10:22:23 -05001166 return isOpaque
1167 ? kPreservesOpaqueInput_OptimizationFlag |
1168 kCompatibleWithCoverageAsAlpha_OptimizationFlag
1169 : kCompatibleWithCoverageAsAlpha_OptimizationFlag;
Brian Salomon587e08f2017-01-27 10:59:27 -05001170}
1171
Florin Malita14a8dd72017-11-08 15:46:42 -05001172void GrGradientEffect::addInterval(const SkGradientShaderBase& shader, size_t idx0, size_t idx1,
1173 SkColorSpace* dstCS) {
1174 SkASSERT(idx0 <= idx1);
1175 const auto c4f0 = shader.getXformedColor(idx0, dstCS),
1176 c4f1 = shader.getXformedColor(idx1, dstCS);
1177 const auto c0 = (fPremulType == kBeforeInterp_PremulType)
1178 ? c4f0.premul().to4f() : Sk4f::Load(c4f0.vec()),
1179 c1 = (fPremulType == kBeforeInterp_PremulType)
1180 ? c4f1.premul().to4f() : Sk4f::Load(c4f1.vec());
1181 const auto t0 = shader.getPos(idx0),
1182 t1 = shader.getPos(idx1),
1183 dt = t1 - t0;
1184 SkASSERT(dt >= 0);
1185 // dt can be 0 for clamp intervals => in this case we want a scale == 0
1186 const auto scale = SkScalarNearlyZero(dt) ? 0 : (c1 - c0) / dt,
1187 bias = c0 - t0 * scale;
1188
1189 // Intervals are stored as (scale, bias) tuples.
1190 SkASSERT(!(fIntervals.count() & 1));
1191 fIntervals.emplace_back(scale[0], scale[1], scale[2], scale[3]);
1192 fIntervals.emplace_back( bias[0], bias[1], bias[2], bias[3]);
1193}
1194
Ethan Nicholasabff9562017-10-09 10:54:08 -04001195GrGradientEffect::GrGradientEffect(ClassID classID, const CreateArgs& args, bool isOpaque)
Florin Malita14a8dd72017-11-08 15:46:42 -05001196 : INHERITED(classID, OptFlags(isOpaque))
1197 , fWrapMode(args.fWrapMode)
1198 , fRow(-1)
1199 , fIsOpaque(args.fShader->isOpaque())
1200 , fStrategy(InterpolationStrategy::kTexture)
1201 , fThreshold(0) {
1202
brianosman9557c272016-09-15 06:59:15 -07001203 const SkGradientShaderBase& shader(*args.fShader);
bsalomon@google.com82d12232013-09-09 15:36:26 +00001204
Florin Malita14a8dd72017-11-08 15:46:42 -05001205 fPremulType = (args.fShader->getGradFlags() & SkGradientShader::kInterpolateColorsInPremul_Flag)
1206 ? kBeforeInterp_PremulType : kAfterInterp_PremulType;
bsalomon@google.com371e1052013-01-11 21:08:55 +00001207
Florin Malita14a8dd72017-11-08 15:46:42 -05001208 // First, determine the interpolation strategy and params.
1209 switch (shader.fColorCount) {
1210 case 2:
1211 SkASSERT(!shader.fOrigPos);
1212 fStrategy = InterpolationStrategy::kSingle;
1213 this->addInterval(shader, 0, 1, args.fDstColorSpace);
1214 break;
1215 case 3:
1216 fThreshold = shader.getPos(1);
bsalomon@google.com1ce49fc2012-09-18 14:14:49 +00001217
Florin Malita14a8dd72017-11-08 15:46:42 -05001218 if (shader.fOrigPos) {
1219 SkASSERT(SkScalarNearlyEqual(shader.fOrigPos[0], 0));
1220 SkASSERT(SkScalarNearlyEqual(shader.fOrigPos[2], 1));
1221 if (SkScalarNearlyEqual(shader.fOrigPos[1], 0)) {
1222 // hard stop on the left edge.
1223 if (fWrapMode == GrSamplerState::WrapMode::kClamp) {
1224 fStrategy = InterpolationStrategy::kThresholdClamp1;
1225 // Clamp interval (scale == 0, bias == colors[0]).
1226 this->addInterval(shader, 0, 0, args.fDstColorSpace);
1227 } else {
1228 // We can ignore the hard stop when not clamping.
1229 fStrategy = InterpolationStrategy::kSingle;
1230 }
1231 this->addInterval(shader, 1, 2, args.fDstColorSpace);
1232 break;
1233 }
Brian Osmand43f7b62017-10-19 15:42:01 -04001234
Florin Malita14a8dd72017-11-08 15:46:42 -05001235 if (SkScalarNearlyEqual(shader.fOrigPos[1], 1)) {
1236 // hard stop on the right edge.
1237 this->addInterval(shader, 0, 1, args.fDstColorSpace);
1238 if (fWrapMode == GrSamplerState::WrapMode::kClamp) {
1239 fStrategy = InterpolationStrategy::kThresholdClamp0;
1240 // Clamp interval (scale == 0, bias == colors[2]).
1241 this->addInterval(shader, 2, 2, args.fDstColorSpace);
1242 } else {
1243 // We can ignore the hard stop when not clamping.
1244 fStrategy = InterpolationStrategy::kSingle;
1245 }
1246 break;
1247 }
Brian Osmand43f7b62017-10-19 15:42:01 -04001248 }
1249
Florin Malita14a8dd72017-11-08 15:46:42 -05001250 // Two arbitrary interpolation intervals.
1251 fStrategy = InterpolationStrategy::kThreshold;
1252 this->addInterval(shader, 0, 1, args.fDstColorSpace);
1253 this->addInterval(shader, 1, 2, args.fDstColorSpace);
1254 break;
1255 case 4:
1256 if (shader.fOrigPos && SkScalarNearlyEqual(shader.fOrigPos[1], shader.fOrigPos[2])) {
1257 SkASSERT(SkScalarNearlyEqual(shader.fOrigPos[0], 0));
1258 SkASSERT(SkScalarNearlyEqual(shader.fOrigPos[3], 1));
fmenozzi2a495912016-08-12 06:33:52 -07001259
Florin Malita14a8dd72017-11-08 15:46:42 -05001260 // Single hard stop => two arbitrary interpolation intervals.
1261 fStrategy = InterpolationStrategy::kThreshold;
1262 fThreshold = shader.getPos(1);
1263 this->addInterval(shader, 0, 1, args.fDstColorSpace);
1264 this->addInterval(shader, 2, 3, args.fDstColorSpace);
1265 }
1266 break;
1267 default:
1268 break;
fmenozzi2a495912016-08-12 06:33:52 -07001269 }
fmenozzicd9a1d02016-08-15 07:03:47 -07001270
Florin Malita14a8dd72017-11-08 15:46:42 -05001271 // Now that we've locked down a strategy, adjust any dependent params.
1272 if (fStrategy != InterpolationStrategy::kTexture) {
1273 // Analytical cases.
1274 fCoordTransform.reset(*args.fMatrix);
1275 } else {
1276 SkGradientShaderBase::GradientBitmapType bitmapType =
1277 SkGradientShaderBase::GradientBitmapType::kLegacy;
1278 if (args.fDstColorSpace) {
1279 // Try to use F16 if we can
1280 if (args.fContext->caps()->isConfigTexturable(kRGBA_half_GrPixelConfig)) {
1281 bitmapType = SkGradientShaderBase::GradientBitmapType::kHalfFloat;
1282 } else if (args.fContext->caps()->isConfigTexturable(kSRGBA_8888_GrPixelConfig)) {
1283 bitmapType = SkGradientShaderBase::GradientBitmapType::kSRGB;
fmenozzicd9a1d02016-08-15 07:03:47 -07001284 } else {
Florin Malita14a8dd72017-11-08 15:46:42 -05001285 // This can happen, but only if someone explicitly creates an unsupported
1286 // (eg sRGB) surface. Just fall back to legacy behavior.
fmenozzicd9a1d02016-08-15 07:03:47 -07001287 }
Florin Malita14a8dd72017-11-08 15:46:42 -05001288 }
fmenozzicd9a1d02016-08-15 07:03:47 -07001289
Florin Malita14a8dd72017-11-08 15:46:42 -05001290 SkBitmap bitmap;
1291 shader.getGradientTableBitmap(&bitmap, bitmapType);
1292 SkASSERT(1 == bitmap.height() && SkIsPow2(bitmap.width()));
fmenozzicd9a1d02016-08-15 07:03:47 -07001293
Florin Malita14a8dd72017-11-08 15:46:42 -05001294
1295 GrTextureStripAtlas::Desc desc;
1296 desc.fWidth = bitmap.width();
1297 desc.fHeight = 32;
Robert Phillips7a926392018-02-01 15:49:54 -05001298 desc.fRowHeight = bitmap.height(); // always 1 here
Florin Malita14a8dd72017-11-08 15:46:42 -05001299 desc.fContext = args.fContext;
1300 desc.fConfig = SkImageInfo2GrPixelConfig(bitmap.info(), *args.fContext->caps());
1301 fAtlas = GrTextureStripAtlas::GetAtlas(desc);
1302 SkASSERT(fAtlas);
1303
1304 // We always filter the gradient table. Each table is one row of a texture, always
1305 // y-clamp.
1306 GrSamplerState samplerState(args.fWrapMode, GrSamplerState::Filter::kBilerp);
1307
1308 fRow = fAtlas->lockRow(bitmap);
1309 if (-1 != fRow) {
1310 fYCoord = fAtlas->getYOffset(fRow)+SK_ScalarHalf*fAtlas->getNormalizedTexelHeight();
1311 // This is 1/2 places where auto-normalization is disabled
1312 fCoordTransform.reset(*args.fMatrix, fAtlas->asTextureProxyRef().get(), false);
1313 fTextureSampler.reset(fAtlas->asTextureProxyRef(), samplerState);
1314 } else {
1315 // In this instance we know the samplerState state is:
1316 // clampY, bilerp
1317 // and the proxy is:
1318 // exact fit, power of two in both dimensions
1319 // Only the x-tileMode is unknown. However, given all the other knowns we know
Robert Phillips7a926392018-02-01 15:49:54 -05001320 // that GrMakeCachedImageProxy is sufficient (i.e., it won't need to be
Florin Malita14a8dd72017-11-08 15:46:42 -05001321 // extracted to a subset or mipmapped).
Robert Phillips7a926392018-02-01 15:49:54 -05001322
1323 SkASSERT(bitmap.isImmutable());
1324 sk_sp<SkImage> srcImage = SkImage::MakeFromBitmap(bitmap);
1325 if (!srcImage) {
1326 return;
1327 }
1328
1329 sk_sp<GrTextureProxy> proxy = GrMakeCachedImageProxy(
Robert Phillips1afd4cd2018-01-08 13:40:32 -05001330 args.fContext->contextPriv().proxyProvider(),
Robert Phillips7a926392018-02-01 15:49:54 -05001331 std::move(srcImage));
Florin Malita14a8dd72017-11-08 15:46:42 -05001332 if (!proxy) {
1333 SkDebugf("Gradient won't draw. Could not create texture.");
1334 return;
1335 }
1336 // This is 2/2 places where auto-normalization is disabled
1337 fCoordTransform.reset(*args.fMatrix, proxy.get(), false);
1338 fTextureSampler.reset(std::move(proxy), samplerState);
1339 fYCoord = SK_ScalarHalf;
1340 }
1341
1342 this->addTextureSampler(&fTextureSampler);
fmenozzicd9a1d02016-08-15 07:03:47 -07001343 }
1344
bsalomon@google.com77af6802013-10-02 13:04:56 +00001345 this->addCoordTransform(&fCoordTransform);
rileya@google.comd7cc6512012-07-27 14:00:39 +00001346}
1347
Brian Salomonf8480b92017-07-27 15:45:59 -04001348GrGradientEffect::GrGradientEffect(const GrGradientEffect& that)
Ethan Nicholasabff9562017-10-09 10:54:08 -04001349 : INHERITED(that.classID(), OptFlags(that.fIsOpaque))
Florin Malita14a8dd72017-11-08 15:46:42 -05001350 , fIntervals(that.fIntervals)
Brian Salomon2bbdcc42017-09-07 12:36:34 -04001351 , fWrapMode(that.fWrapMode)
Brian Salomonf8480b92017-07-27 15:45:59 -04001352 , fCoordTransform(that.fCoordTransform)
1353 , fTextureSampler(that.fTextureSampler)
1354 , fYCoord(that.fYCoord)
1355 , fAtlas(that.fAtlas)
1356 , fRow(that.fRow)
1357 , fIsOpaque(that.fIsOpaque)
Florin Malita14a8dd72017-11-08 15:46:42 -05001358 , fStrategy(that.fStrategy)
1359 , fThreshold(that.fThreshold)
Brian Salomonf8480b92017-07-27 15:45:59 -04001360 , fPremulType(that.fPremulType) {
1361 this->addCoordTransform(&fCoordTransform);
Florin Malita14a8dd72017-11-08 15:46:42 -05001362 if (fStrategy == InterpolationStrategy::kTexture) {
Brian Salomonf8480b92017-07-27 15:45:59 -04001363 this->addTextureSampler(&fTextureSampler);
1364 }
1365 if (this->useAtlas()) {
1366 fAtlas->lockRow(fRow);
1367 }
1368}
1369
rileya@google.comd7cc6512012-07-27 14:00:39 +00001370GrGradientEffect::~GrGradientEffect() {
rileya@google.comb3e50f22012-08-20 17:43:08 +00001371 if (this->useAtlas()) {
1372 fAtlas->unlockRow(fRow);
rileya@google.comb3e50f22012-08-20 17:43:08 +00001373 }
rileya@google.comd7cc6512012-07-27 14:00:39 +00001374}
1375
bsalomon0e08fc12014-10-15 08:19:04 -07001376bool GrGradientEffect::onIsEqual(const GrFragmentProcessor& processor) const {
fmenozzicd9a1d02016-08-15 07:03:47 -07001377 const GrGradientEffect& ge = processor.cast<GrGradientEffect>();
bsalomon@google.com82d12232013-09-09 15:36:26 +00001378
Florin Malita14a8dd72017-11-08 15:46:42 -05001379 if (fWrapMode != ge.fWrapMode || fStrategy != ge.fStrategy) {
Brian Salomon466ad992016-10-13 16:08:36 -04001380 return false;
1381 }
Florin Malita14a8dd72017-11-08 15:46:42 -05001382
Brian Salomon466ad992016-10-13 16:08:36 -04001383 SkASSERT(this->useAtlas() == ge.useAtlas());
Florin Malita14a8dd72017-11-08 15:46:42 -05001384 if (fStrategy == InterpolationStrategy::kTexture) {
1385 if (fYCoord != ge.fYCoord) {
Brian Salomon466ad992016-10-13 16:08:36 -04001386 return false;
1387 }
1388 } else {
Florin Malita14a8dd72017-11-08 15:46:42 -05001389 if (fThreshold != ge.fThreshold ||
1390 fIntervals != ge.fIntervals ||
1391 fPremulType != ge.fPremulType) {
Brian Salomon466ad992016-10-13 16:08:36 -04001392 return false;
1393 }
bsalomon@google.com82d12232013-09-09 15:36:26 +00001394 }
Brian Osman5911a7c2017-10-25 12:52:31 -04001395 return true;
bsalomon@google.com68b58c92013-01-17 16:50:08 +00001396}
1397
Hal Canary6f6961e2017-01-31 13:50:44 -05001398#if GR_TEST_UTILS
Brian Osman3f748602016-10-03 18:29:03 -04001399GrGradientEffect::RandomGradientParams::RandomGradientParams(SkRandom* random) {
Brian Salomon5d4cd9e2017-02-09 11:16:46 -05001400 // Set color count to min of 2 so that we don't trigger the const color optimization and make
1401 // a non-gradient processor.
1402 fColorCount = random->nextRangeU(2, kMaxRandomGradientColors);
Brian Osmana2196532016-10-17 12:48:13 -04001403 fUseColors4f = random->nextBool();
bsalomon@google.comd4726202012-08-03 14:34:46 +00001404
1405 // if one color, omit stops, otherwise randomly decide whether or not to
Brian Osman3f748602016-10-03 18:29:03 -04001406 if (fColorCount == 1 || (fColorCount >= 2 && random->nextBool())) {
1407 fStops = nullptr;
1408 } else {
1409 fStops = fStopStorage;
bsalomon@google.comd4726202012-08-03 14:34:46 +00001410 }
1411
Brian Osmana2196532016-10-17 12:48:13 -04001412 // if using SkColor4f, attach a random (possibly null) color space (with linear gamma)
1413 if (fUseColors4f) {
1414 fColorSpace = GrTest::TestColorSpace(random);
1415 if (fColorSpace) {
Brian Osman36703d92017-12-12 14:09:31 -05001416 fColorSpace = fColorSpace->makeLinearGamma();
Brian Osmana2196532016-10-17 12:48:13 -04001417 }
1418 }
1419
bsalomon@google.com81712882012-11-01 17:12:34 +00001420 SkScalar stop = 0.f;
Brian Osman3f748602016-10-03 18:29:03 -04001421 for (int i = 0; i < fColorCount; ++i) {
Brian Osmana2196532016-10-17 12:48:13 -04001422 if (fUseColors4f) {
1423 fColors4f[i].fR = random->nextUScalar1();
1424 fColors4f[i].fG = random->nextUScalar1();
1425 fColors4f[i].fB = random->nextUScalar1();
1426 fColors4f[i].fA = random->nextUScalar1();
1427 } else {
1428 fColors[i] = random->nextU();
1429 }
Brian Osman3f748602016-10-03 18:29:03 -04001430 if (fStops) {
1431 fStops[i] = stop;
1432 stop = i < fColorCount - 1 ? stop + random->nextUScalar1() * (1.f - stop) : 1.f;
bsalomon@google.comd4726202012-08-03 14:34:46 +00001433 }
1434 }
Brian Osman3f748602016-10-03 18:29:03 -04001435 fTileMode = static_cast<SkShader::TileMode>(random->nextULessThan(SkShader::kTileModeCount));
bsalomon@google.comd4726202012-08-03 14:34:46 +00001436}
Hal Canary6f6961e2017-01-31 13:50:44 -05001437#endif
bsalomon@google.comd4726202012-08-03 14:34:46 +00001438
bsalomon@google.comcf8fb1f2012-08-02 14:03:32 +00001439#endif