blob: 871c7ba55e777a3b3ee5d1382c6e75a9046e28a6 [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
Florin Malita89ab2402017-11-01 10:14:57 -0400152 size_t storageSize = fColorCount * (sizeof(SkColor4f) + (desc.fPos ? sizeof(SkScalar) : 0));
153 fOrigColors4f = reinterpret_cast<SkColor4f*>(fStorage.reset(storageSize));
154 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) {
163 origColors[i] = desc.fColors[i];
164 fColorsAreOpaque = fColorsAreOpaque && (desc.fColors[i].fA == 1);
165 }
brianosmane25d71c2016-09-28 11:27:28 -0700166 if (dummyLast) {
167 origColors += desc.fCount;
168 *origColors = desc.fColors[desc.fCount - 1];
169 }
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;
Florin Malita89ab2402017-11-01 10:14:57 -0400183 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.
200 if (uniformStops) {
201 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;
282
Mike Kleina3771842017-05-04 19:38:48 -0400283 SkMatrix matrix;
Mike Reed1d8c42e2017-08-29 14:58:19 -0400284 if (!this->computeTotalInverse(rec.fCTM, rec.fLocalM, &matrix)) {
Mike Kleina3771842017-05-04 19:38:48 -0400285 return false;
286 }
Florin Malita50b20842017-07-29 19:08:28 -0400287 matrix.postConcat(fPtsToUnit);
Mike Kleina3771842017-05-04 19:38:48 -0400288
Florin Malita2e409002017-06-28 14:46:54 -0400289 SkRasterPipeline_<256> postPipeline;
Mike Kleina3771842017-05-04 19:38:48 -0400290
Mike Klein85f85362017-10-17 14:22:58 -0400291 p->append_seed_shader();
Mike Reed6b59bf42017-07-03 21:26:44 -0400292 p->append_matrix(alloc, matrix);
Florin Malita50b20842017-07-29 19:08:28 -0400293 this->appendGradientStages(alloc, p, &postPipeline);
Mike Kleine7598532017-05-11 11:29:29 -0400294
295 switch(fTileMode) {
Mike Klein9f85d682017-05-23 07:52:01 -0400296 case kMirror_TileMode: p->append(SkRasterPipeline::mirror_x_1); break;
297 case kRepeat_TileMode: p->append(SkRasterPipeline::repeat_x_1); break;
Mike Kleine7598532017-05-11 11:29:29 -0400298 case kClamp_TileMode:
299 if (!fOrigPos) {
300 // We clamp only when the stops are evenly spaced.
301 // If not, there may be hard stops, and clamping ruins hard stops at 0 and/or 1.
Mike Klein5c7960b2017-05-11 10:59:22 -0400302 // In that case, we must make sure we're using the general "gradient" stage,
Mike Kleine7598532017-05-11 11:29:29 -0400303 // which is the only stage that will correctly handle unclamped t.
Mike Klein9f85d682017-05-23 07:52:01 -0400304 p->append(SkRasterPipeline::clamp_x_1);
Mike Kleine7598532017-05-11 11:29:29 -0400305 }
306 }
Mike Kleina3771842017-05-04 19:38:48 -0400307
308 const bool premulGrad = fGradFlags & SkGradientShader::kInterpolateColorsInPremul_Flag;
309 auto prepareColor = [premulGrad, dstCS, this](int i) {
Florin Malita0e36b3f2017-06-05 23:33:45 -0400310 SkColor4f c = this->getXformedColor(i, dstCS);
Mike Kleina3771842017-05-04 19:38:48 -0400311 return premulGrad ? c.premul()
312 : SkPM4f::From4f(Sk4f::Load(&c));
313 };
314
315 // The two-stop case with stops at 0 and 1.
316 if (fColorCount == 2 && fOrigPos == nullptr) {
317 const SkPM4f c_l = prepareColor(0),
Mike Reed1d8c42e2017-08-29 14:58:19 -0400318 c_r = prepareColor(1);
Mike Kleina3771842017-05-04 19:38:48 -0400319
320 // See F and B below.
321 auto* f_and_b = alloc->makeArrayDefault<SkPM4f>(2);
322 f_and_b[0] = SkPM4f::From4f(c_r.to4f() - c_l.to4f());
323 f_and_b[1] = c_l;
324
Mike Klein5c7960b2017-05-11 10:59:22 -0400325 p->append(SkRasterPipeline::evenly_spaced_2_stop_gradient, f_and_b);
Mike Kleina3771842017-05-04 19:38:48 -0400326 } else {
Herb Derby4de13042017-05-15 10:49:39 -0400327 auto* ctx = alloc->make<SkJumper_GradientCtx>();
Herb Derby4de13042017-05-15 10:49:39 -0400328
329 // Note: In order to handle clamps in search, the search assumes a stop conceptully placed
330 // at -inf. Therefore, the max number of stops is fColorCount+1.
331 for (int i = 0; i < 4; i++) {
332 // Allocate at least at for the AVX2 gather from a YMM register.
333 ctx->fs[i] = alloc->makeArray<float>(std::max(fColorCount+1, 8));
334 ctx->bs[i] = alloc->makeArray<float>(std::max(fColorCount+1, 8));
335 }
336
Mike Kleina3771842017-05-04 19:38:48 -0400337 if (fOrigPos == nullptr) {
338 // Handle evenly distributed stops.
339
Herb Derby4de13042017-05-15 10:49:39 -0400340 size_t stopCount = fColorCount;
341 float gapCount = stopCount - 1;
Mike Kleina3771842017-05-04 19:38:48 -0400342
Herb Derby4de13042017-05-15 10:49:39 -0400343 SkPM4f c_l = prepareColor(0);
344 for (size_t i = 0; i < stopCount - 1; i++) {
Mike Kleina3771842017-05-04 19:38:48 -0400345 SkPM4f c_r = prepareColor(i + 1);
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400346 init_stop_evenly(ctx, gapCount, i, c_l, c_r);
Mike Kleina3771842017-05-04 19:38:48 -0400347 c_l = c_r;
348 }
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400349 add_const_color(ctx, stopCount - 1, c_l);
Mike Kleina3771842017-05-04 19:38:48 -0400350
Herb Derby4de13042017-05-15 10:49:39 -0400351 ctx->stopCount = stopCount;
352 p->append(SkRasterPipeline::evenly_spaced_gradient, ctx);
Mike Kleina3771842017-05-04 19:38:48 -0400353 } else {
354 // Handle arbitrary stops.
355
Herb Derby4de13042017-05-15 10:49:39 -0400356 ctx->ts = alloc->makeArray<float>(fColorCount+1);
357
Mike Kleina3771842017-05-04 19:38:48 -0400358 // Remove the dummy stops inserted by SkGradientShaderBase::SkGradientShaderBase
359 // because they are naturally handled by the search method.
360 int firstStop;
361 int lastStop;
362 if (fColorCount > 2) {
363 firstStop = fOrigColors4f[0] != fOrigColors4f[1] ? 0 : 1;
364 lastStop = fOrigColors4f[fColorCount - 2] != fOrigColors4f[fColorCount - 1]
365 ? fColorCount - 1 : fColorCount - 2;
366 } else {
367 firstStop = 0;
368 lastStop = 1;
369 }
Mike Kleina3771842017-05-04 19:38:48 -0400370
Mike Kleina3771842017-05-04 19:38:48 -0400371 size_t stopCount = 0;
372 float t_l = fOrigPos[firstStop];
373 SkPM4f c_l = prepareColor(firstStop);
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400374 add_const_color(ctx, stopCount++, c_l);
Mike Kleina3771842017-05-04 19:38:48 -0400375 // N.B. lastStop is the index of the last stop, not one after.
376 for (int i = firstStop; i < lastStop; i++) {
377 float t_r = fOrigPos[i + 1];
378 SkPM4f c_r = prepareColor(i + 1);
Florin Malita3e20d022017-11-03 12:11:38 -0400379 SkASSERT(t_l <= t_r);
Mike Kleina3771842017-05-04 19:38:48 -0400380 if (t_l < t_r) {
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400381 init_stop_pos(ctx, stopCount, t_l, t_r, c_l, c_r);
Mike Kleina3771842017-05-04 19:38:48 -0400382 stopCount += 1;
383 }
384 t_l = t_r;
385 c_l = c_r;
386 }
387
Herb Derby4de13042017-05-15 10:49:39 -0400388 ctx->ts[stopCount] = t_l;
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400389 add_const_color(ctx, stopCount++, c_l);
Mike Kleina3771842017-05-04 19:38:48 -0400390
Herb Derby4de13042017-05-15 10:49:39 -0400391 ctx->stopCount = stopCount;
392 p->append(SkRasterPipeline::gradient, ctx);
Mike Kleina3771842017-05-04 19:38:48 -0400393 }
Mike Kleina3771842017-05-04 19:38:48 -0400394 }
395
396 if (!premulGrad && !this->colorsAreOpaque()) {
Mike Kleine7598532017-05-11 11:29:29 -0400397 p->append(SkRasterPipeline::premul);
Mike Kleina3771842017-05-04 19:38:48 -0400398 }
399
Florin Malita2e409002017-06-28 14:46:54 -0400400 p->extend(postPipeline);
401
Mike Kleina3771842017-05-04 19:38:48 -0400402 return true;
403}
404
405
rileya@google.com589708b2012-07-26 20:04:23 +0000406bool SkGradientShaderBase::isOpaque() const {
407 return fColorsAreOpaque;
408}
409
reed8367b8c2014-08-22 08:30:20 -0700410static unsigned rounded_divide(unsigned numer, unsigned denom) {
411 return (numer + (denom >> 1)) / denom;
412}
413
414bool SkGradientShaderBase::onAsLuminanceColor(SkColor* lum) const {
415 // we just compute an average color.
416 // possibly we could weight this based on the proportional width for each color
417 // assuming they are not evenly distributed in the fPos array.
418 int r = 0;
419 int g = 0;
420 int b = 0;
421 const int n = fColorCount;
Florin Malita39d71de2017-10-31 11:33:49 -0400422 // TODO: use linear colors?
reed8367b8c2014-08-22 08:30:20 -0700423 for (int i = 0; i < n; ++i) {
Florin Malita39d71de2017-10-31 11:33:49 -0400424 SkColor c = this->getLegacyColor(i);
reed8367b8c2014-08-22 08:30:20 -0700425 r += SkColorGetR(c);
426 g += SkColorGetG(c);
427 b += SkColorGetB(c);
428 }
429 *lum = SkColorSetRGB(rounded_divide(r, n), rounded_divide(g, n), rounded_divide(b, n));
430 return true;
431}
432
Florin Malita39d71de2017-10-31 11:33:49 -0400433SkGradientShaderBase::AutoXformColors::AutoXformColors(const SkGradientShaderBase& grad,
434 SkColorSpaceXformer* xformer)
435 : fColors(grad.fColorCount) {
436 // TODO: stay in 4f to preserve precision?
437
438 SkAutoSTMalloc<8, SkColor> origColors(grad.fColorCount);
439 for (int i = 0; i < grad.fColorCount; ++i) {
440 origColors[i] = grad.getLegacyColor(i);
441 }
442
443 xformer->apply(fColors.get(), origColors.get(), grad.fColorCount);
444}
445
Florin Malitad4e9ec82017-10-25 18:00:26 -0400446static constexpr int kGradientTextureSize = 256;
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000447
Florin Malita84d7cf92017-10-25 15:31:54 -0400448void SkGradientShaderBase::initLinearBitmap(SkBitmap* bitmap, GradientBitmapType bitmapType) const {
brianosmand4546092016-09-22 12:31:58 -0700449 const bool interpInPremul = SkToBool(fGradFlags &
450 SkGradientShader::kInterpolateColorsInPremul_Flag);
brianosmand4546092016-09-22 12:31:58 -0700451 SkHalf* pixelsF16 = reinterpret_cast<SkHalf*>(bitmap->getPixels());
Florin Malita84d7cf92017-10-25 15:31:54 -0400452 uint32_t* pixels32 = reinterpret_cast<uint32_t*>(bitmap->getPixels());
brianosmand4546092016-09-22 12:31:58 -0700453
454 typedef std::function<void(const Sk4f&, int)> pixelWriteFn_t;
455
456 pixelWriteFn_t writeF16Pixel = [&](const Sk4f& x, int index) {
457 Sk4h c = SkFloatToHalf_finite_ftz(x);
458 pixelsF16[4*index+0] = c[0];
459 pixelsF16[4*index+1] = c[1];
460 pixelsF16[4*index+2] = c[2];
461 pixelsF16[4*index+3] = c[3];
462 };
463 pixelWriteFn_t writeS32Pixel = [&](const Sk4f& c, int index) {
Florin Malita84d7cf92017-10-25 15:31:54 -0400464 pixels32[index] = Sk4f_toS32(c);
465 };
466 pixelWriteFn_t writeL32Pixel = [&](const Sk4f& c, int index) {
467 pixels32[index] = Sk4f_toL32(c);
brianosmand4546092016-09-22 12:31:58 -0700468 };
469
470 pixelWriteFn_t writeSizedPixel =
Florin Malita84d7cf92017-10-25 15:31:54 -0400471 (bitmapType == GradientBitmapType::kHalfFloat) ? writeF16Pixel :
472 (bitmapType == GradientBitmapType::kSRGB ) ? writeS32Pixel : writeL32Pixel;
brianosmand4546092016-09-22 12:31:58 -0700473 pixelWriteFn_t writeUnpremulPixel = [&](const Sk4f& c, int index) {
474 writeSizedPixel(c * Sk4f(c[3], c[3], c[3], 1.0f), index);
475 };
476
477 pixelWriteFn_t writePixel = interpInPremul ? writeSizedPixel : writeUnpremulPixel;
478
Florin Malita84d7cf92017-10-25 15:31:54 -0400479 // When not in legacy mode, we just want the original 4f colors - so we pass in
480 // our own CS for identity/no transform.
481 auto* cs = bitmapType != GradientBitmapType::kLegacy ? fColorSpace.get() : nullptr;
482
brianosmand4546092016-09-22 12:31:58 -0700483 int prevIndex = 0;
484 for (int i = 1; i < fColorCount; i++) {
Florin Malitaed6ae562017-10-28 11:06:48 -0400485 // Historically, stops have been mapped to [0, 256], with 256 then nudged to the
486 // next smaller value, then truncate for the texture index. This seems to produce
487 // the best results for some common distributions, so we preserve the behavior.
488 int nextIndex = SkTMin(this->getPos(i) * kGradientTextureSize,
489 SkIntToScalar(kGradientTextureSize - 1));
brianosmand4546092016-09-22 12:31:58 -0700490
491 if (nextIndex > prevIndex) {
Florin Malita84d7cf92017-10-25 15:31:54 -0400492 SkColor4f color0 = this->getXformedColor(i - 1, cs),
493 color1 = this->getXformedColor(i , cs);
494 Sk4f c0 = Sk4f::Load(color0.vec()),
495 c1 = Sk4f::Load(color1.vec());
496
brianosmand4546092016-09-22 12:31:58 -0700497 if (interpInPremul) {
498 c0 = c0 * Sk4f(c0[3], c0[3], c0[3], 1.0f);
499 c1 = c1 * Sk4f(c1[3], c1[3], c1[3], 1.0f);
500 }
501
502 Sk4f step = Sk4f(1.0f / static_cast<float>(nextIndex - prevIndex));
503 Sk4f delta = (c1 - c0) * step;
504
505 for (int curIndex = prevIndex; curIndex <= nextIndex; ++curIndex) {
506 writePixel(c0, curIndex);
507 c0 += delta;
508 }
509 }
510 prevIndex = nextIndex;
511 }
Florin Malitad4e9ec82017-10-25 18:00:26 -0400512 SkASSERT(prevIndex == kGradientTextureSize - 1);
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000513}
514
Florin Malita0e36b3f2017-06-05 23:33:45 -0400515SkColor4f SkGradientShaderBase::getXformedColor(size_t i, SkColorSpace* dstCS) const {
Florin Malita79363b62017-11-01 15:43:52 -0400516 if (dstCS) {
517 return to_colorspace(fOrigColors4f[i], fColorSpace.get(), dstCS);
518 }
519
520 // Legacy/srgb color.
Florin Malita79363b62017-11-01 15:43:52 -0400521 // We quantize upfront to ensure stable SkColor round-trips.
522 auto rgb255 = sk_linear_to_srgb(Sk4f::Load(fOrigColors4f[i].vec()));
523 auto rgb = SkNx_cast<float>(rgb255) * (1/255.0f);
524 return { rgb[0], rgb[1], rgb[2], fOrigColors4f[i].fA };
Florin Malita0e36b3f2017-06-05 23:33:45 -0400525}
526
reed086eea92016-05-04 17:12:46 -0700527SK_DECLARE_STATIC_MUTEX(gGradientCacheMutex);
rileya@google.com589708b2012-07-26 20:04:23 +0000528/*
529 * Because our caller might rebuild the same (logically the same) gradient
530 * over and over, we'd like to return exactly the same "bitmap" if possible,
531 * allowing the client to utilize a cache of our bitmap (e.g. with a GPU).
532 * To do that, we maintain a private cache of built-bitmaps, based on our
Brian Osmanfe3e8582017-10-20 11:27:49 -0400533 * colors and positions.
rileya@google.com589708b2012-07-26 20:04:23 +0000534 */
brianosmand4546092016-09-22 12:31:58 -0700535void SkGradientShaderBase::getGradientTableBitmap(SkBitmap* bitmap,
536 GradientBitmapType bitmapType) const {
brianosmand4546092016-09-22 12:31:58 -0700537 // build our key: [numColors + colors[] + {positions[]} + flags + colorType ]
Florin Malita39d71de2017-10-31 11:33:49 -0400538 static_assert(sizeof(SkColor4f) % sizeof(int32_t) == 0, "");
539 const int colorsAsIntCount = fColorCount * sizeof(SkColor4f) / sizeof(int32_t);
540 int count = 1 + colorsAsIntCount + 1 + 1;
rileya@google.com589708b2012-07-26 20:04:23 +0000541 if (fColorCount > 2) {
Florin Malitacad3b8c2017-10-28 21:42:50 -0400542 count += fColorCount - 1;
rileya@google.com589708b2012-07-26 20:04:23 +0000543 }
544
Florin Malita39d71de2017-10-31 11:33:49 -0400545 SkAutoSTMalloc<64, int32_t> storage(count);
rileya@google.com589708b2012-07-26 20:04:23 +0000546 int32_t* buffer = storage.get();
547
548 *buffer++ = fColorCount;
Florin Malita39d71de2017-10-31 11:33:49 -0400549 memcpy(buffer, fOrigColors4f, fColorCount * sizeof(SkColor4f));
550 buffer += colorsAsIntCount;
rileya@google.com589708b2012-07-26 20:04:23 +0000551 if (fColorCount > 2) {
552 for (int i = 1; i < fColorCount; i++) {
Florin Malitacad3b8c2017-10-28 21:42:50 -0400553 *buffer++ = SkFloat2Bits(this->getPos(i));
rileya@google.com589708b2012-07-26 20:04:23 +0000554 }
555 }
reed@google.com3d3a8602013-05-24 14:58:44 +0000556 *buffer++ = fGradFlags;
brianosmand4546092016-09-22 12:31:58 -0700557 *buffer++ = static_cast<int32_t>(bitmapType);
rileya@google.com589708b2012-07-26 20:04:23 +0000558 SkASSERT(buffer - storage.get() == count);
559
560 ///////////////////////////////////
561
reeda6cac4c2014-08-21 10:50:25 -0700562 static SkGradientBitmapCache* gCache;
brianosmand4546092016-09-22 12:31:58 -0700563 // 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 +0000564 static const int MAX_NUM_CACHED_GRADIENT_BITMAPS = 32;
bungemand6aeb6d2014-07-25 11:52:47 -0700565 SkAutoMutexAcquire ama(gGradientCacheMutex);
rileya@google.com589708b2012-07-26 20:04:23 +0000566
halcanary96fcdcc2015-08-27 07:41:13 -0700567 if (nullptr == gCache) {
halcanary385fe4d2015-08-26 13:07:48 -0700568 gCache = new SkGradientBitmapCache(MAX_NUM_CACHED_GRADIENT_BITMAPS);
rileya@google.com589708b2012-07-26 20:04:23 +0000569 }
570 size_t size = count * sizeof(int32_t);
571
572 if (!gCache->find(storage.get(), size, bitmap)) {
Florin Malitad4e9ec82017-10-25 18:00:26 -0400573 // For these cases we use the bitmap cache, but not the GradientShaderCache. So just
574 // allocate and populate the bitmap's data directly.
Florin Malita63376532017-10-24 10:56:52 -0400575
Florin Malitad4e9ec82017-10-25 18:00:26 -0400576 SkImageInfo info;
577 switch (bitmapType) {
578 case GradientBitmapType::kLegacy:
579 info = SkImageInfo::Make(kGradientTextureSize, 1, kRGBA_8888_SkColorType,
580 kPremul_SkAlphaType);
581 break;
582 case GradientBitmapType::kSRGB:
583 info = SkImageInfo::Make(kGradientTextureSize, 1, kRGBA_8888_SkColorType,
584 kPremul_SkAlphaType, SkColorSpace::MakeSRGB());
585 break;
586 case GradientBitmapType::kHalfFloat:
587 info = SkImageInfo::Make(kGradientTextureSize, 1, kRGBA_F16_SkColorType,
588 kPremul_SkAlphaType, SkColorSpace::MakeSRGBLinear());
589 break;
brianosmand4546092016-09-22 12:31:58 -0700590 }
Florin Malitad4e9ec82017-10-25 18:00:26 -0400591
592 bitmap->allocPixels(info);
593 this->initLinearBitmap(bitmap, bitmapType);
Robert Phillips7a926392018-02-01 15:49:54 -0500594 bitmap->setImmutable();
rileya@google.com589708b2012-07-26 20:04:23 +0000595 gCache->add(storage.get(), size, *bitmap);
596 }
597}
598
Florin Malita5f379a82017-10-18 16:22:35 -0400599void SkGradientShaderBase::commonAsAGradient(GradientInfo* info) const {
rileya@google.com589708b2012-07-26 20:04:23 +0000600 if (info) {
601 if (info->fColorCount >= fColorCount) {
602 if (info->fColors) {
Florin Malita39d71de2017-10-31 11:33:49 -0400603 for (int i = 0; i < fColorCount; ++i) {
604 info->fColors[i] = this->getLegacyColor(i);
605 }
rileya@google.com589708b2012-07-26 20:04:23 +0000606 }
607 if (info->fColorOffsets) {
Florin Malitaed6ae562017-10-28 11:06:48 -0400608 for (int i = 0; i < fColorCount; ++i) {
609 info->fColorOffsets[i] = this->getPos(i);
rileya@google.com589708b2012-07-26 20:04:23 +0000610 }
611 }
612 }
613 info->fColorCount = fColorCount;
614 info->fTileMode = fTileMode;
reed@google.com3d3a8602013-05-24 14:58:44 +0000615 info->fGradientFlags = fGradFlags;
rileya@google.com589708b2012-07-26 20:04:23 +0000616 }
617}
618
commit-bot@chromium.org0f10f7b2014-03-13 18:02:17 +0000619#ifndef SK_IGNORE_TO_STRING
robertphillips@google.com76f9e932013-01-15 20:17:47 +0000620void SkGradientShaderBase::toString(SkString* str) const {
621
622 str->appendf("%d colors: ", fColorCount);
623
624 for (int i = 0; i < fColorCount; ++i) {
Florin Malita39d71de2017-10-31 11:33:49 -0400625 str->appendHex(this->getLegacyColor(i), 8);
robertphillips@google.com76f9e932013-01-15 20:17:47 +0000626 if (i < fColorCount-1) {
627 str->append(", ");
628 }
629 }
630
631 if (fColorCount > 2) {
632 str->append(" points: (");
633 for (int i = 0; i < fColorCount; ++i) {
Florin Malitaed6ae562017-10-28 11:06:48 -0400634 str->appendScalar(this->getPos(i));
robertphillips@google.com76f9e932013-01-15 20:17:47 +0000635 if (i < fColorCount-1) {
636 str->append(", ");
637 }
638 }
639 str->append(")");
640 }
641
642 static const char* gTileModeName[SkShader::kTileModeCount] = {
643 "clamp", "repeat", "mirror"
644 };
645
646 str->append(" ");
647 str->append(gTileModeName[fTileMode]);
648
robertphillips@google.com76f9e932013-01-15 20:17:47 +0000649 this->INHERITED::toString(str);
650}
651#endif
652
rileya@google.com589708b2012-07-26 20:04:23 +0000653///////////////////////////////////////////////////////////////////////////////
654///////////////////////////////////////////////////////////////////////////////
655
reed1b747302015-01-06 07:13:19 -0800656// Return true if these parameters are valid/legal/safe to construct a gradient
657//
brianosmane25d71c2016-09-28 11:27:28 -0700658static bool valid_grad(const SkColor4f colors[], const SkScalar pos[], int count,
659 unsigned tileMode) {
halcanary96fcdcc2015-08-27 07:41:13 -0700660 return nullptr != colors && count >= 1 && tileMode < (unsigned)SkShader::kTileModeCount;
reed1b747302015-01-06 07:13:19 -0800661}
662
reed@google.com437d6eb2013-05-23 19:03:05 +0000663static void desc_init(SkGradientShaderBase::Descriptor* desc,
brianosmane25d71c2016-09-28 11:27:28 -0700664 const SkColor4f colors[], sk_sp<SkColorSpace> colorSpace,
665 const SkScalar pos[], int colorCount,
reedaddf2ed2014-08-11 08:28:24 -0700666 SkShader::TileMode mode, uint32_t flags, const SkMatrix* localMatrix) {
fmalita748d6202016-05-11 11:39:58 -0700667 SkASSERT(colorCount > 1);
668
commit-bot@chromium.org6c5aea22014-04-22 16:25:15 +0000669 desc->fColors = colors;
brianosmane25d71c2016-09-28 11:27:28 -0700670 desc->fColorSpace = std::move(colorSpace);
commit-bot@chromium.org6c5aea22014-04-22 16:25:15 +0000671 desc->fPos = pos;
672 desc->fCount = colorCount;
673 desc->fTileMode = mode;
commit-bot@chromium.org6c5aea22014-04-22 16:25:15 +0000674 desc->fGradFlags = flags;
reedaddf2ed2014-08-11 08:28:24 -0700675 desc->fLocalMatrix = localMatrix;
reed@google.com437d6eb2013-05-23 19:03:05 +0000676}
677
brianosmane25d71c2016-09-28 11:27:28 -0700678// assumes colors is SkColor4f* and pos is SkScalar*
fmenozzie9fd0f82016-08-19 07:50:57 -0700679#define EXPAND_1_COLOR(count) \
brianosmane25d71c2016-09-28 11:27:28 -0700680 SkColor4f tmp[2]; \
fmenozzie9fd0f82016-08-19 07:50:57 -0700681 do { \
682 if (1 == count) { \
683 tmp[0] = tmp[1] = colors[0]; \
684 colors = tmp; \
685 pos = nullptr; \
686 count = 2; \
687 } \
688 } while (0)
689
fmenozzi68d952c2016-08-19 08:56:56 -0700690struct ColorStopOptimizer {
brianosmane25d71c2016-09-28 11:27:28 -0700691 ColorStopOptimizer(const SkColor4f* colors, const SkScalar* pos,
fmenozzi68d952c2016-08-19 08:56:56 -0700692 int count, SkShader::TileMode mode)
693 : fColors(colors)
694 , fPos(pos)
695 , fCount(count) {
696
697 if (!pos || count != 3) {
698 return;
699 }
700
701 if (SkScalarNearlyEqual(pos[0], 0.0f) &&
702 SkScalarNearlyEqual(pos[1], 0.0f) &&
703 SkScalarNearlyEqual(pos[2], 1.0f)) {
704
705 if (SkShader::kRepeat_TileMode == mode ||
706 SkShader::kMirror_TileMode == mode ||
707 colors[0] == colors[1]) {
708
fmalita582a6562016-08-22 06:28:57 -0700709 // Ignore the leftmost color/pos.
710 fColors += 1;
711 fPos += 1;
712 fCount = 2;
fmenozzi68d952c2016-08-19 08:56:56 -0700713 }
714 } else if (SkScalarNearlyEqual(pos[0], 0.0f) &&
715 SkScalarNearlyEqual(pos[1], 1.0f) &&
716 SkScalarNearlyEqual(pos[2], 1.0f)) {
717
718 if (SkShader::kRepeat_TileMode == mode ||
719 SkShader::kMirror_TileMode == mode ||
720 colors[1] == colors[2]) {
721
fmalita582a6562016-08-22 06:28:57 -0700722 // Ignore the rightmost color/pos.
fmenozzi68d952c2016-08-19 08:56:56 -0700723 fCount = 2;
724 }
725 }
726 }
727
brianosmane25d71c2016-09-28 11:27:28 -0700728 const SkColor4f* fColors;
729 const SkScalar* fPos;
730 int fCount;
731};
732
733struct ColorConverter {
734 ColorConverter(const SkColor* colors, int count) {
735 for (int i = 0; i < count; ++i) {
736 fColors4f.push_back(SkColor4f::FromColor(colors[i]));
737 }
738 }
739
740 SkSTArray<2, SkColor4f, true> fColors4f;
fmenozzi68d952c2016-08-19 08:56:56 -0700741};
742
reed8a21c9f2016-03-08 18:50:00 -0800743sk_sp<SkShader> SkGradientShader::MakeLinear(const SkPoint pts[2],
fmenozzi68d952c2016-08-19 08:56:56 -0700744 const SkColor colors[],
745 const SkScalar pos[], int colorCount,
746 SkShader::TileMode mode,
747 uint32_t flags,
748 const SkMatrix* localMatrix) {
brianosmane25d71c2016-09-28 11:27:28 -0700749 ColorConverter converter(colors, colorCount);
750 return MakeLinear(pts, converter.fColors4f.begin(), nullptr, pos, colorCount, mode, flags,
751 localMatrix);
752}
753
754sk_sp<SkShader> SkGradientShader::MakeLinear(const SkPoint pts[2],
755 const SkColor4f colors[],
756 sk_sp<SkColorSpace> colorSpace,
757 const SkScalar pos[], int colorCount,
758 SkShader::TileMode mode,
759 uint32_t flags,
760 const SkMatrix* localMatrix) {
fmalitac5231042016-08-10 05:45:50 -0700761 if (!pts || !SkScalarIsFinite((pts[1] - pts[0]).length())) {
halcanary96fcdcc2015-08-27 07:41:13 -0700762 return nullptr;
reed1b747302015-01-06 07:13:19 -0800763 }
764 if (!valid_grad(colors, pos, colorCount, mode)) {
halcanary96fcdcc2015-08-27 07:41:13 -0700765 return nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +0000766 }
fmenozzie9fd0f82016-08-19 07:50:57 -0700767 if (1 == colorCount) {
brianosmane25d71c2016-09-28 11:27:28 -0700768 return SkShader::MakeColorShader(colors[0], std::move(colorSpace));
fmenozzie9fd0f82016-08-19 07:50:57 -0700769 }
Florin Malita8d3ffad2017-02-03 18:21:17 +0000770 if (localMatrix && !localMatrix->invert(nullptr)) {
771 return nullptr;
772 }
rileya@google.com589708b2012-07-26 20:04:23 +0000773
fmenozzi68d952c2016-08-19 08:56:56 -0700774 ColorStopOptimizer opt(colors, pos, colorCount, mode);
775
reed@google.com437d6eb2013-05-23 19:03:05 +0000776 SkGradientShaderBase::Descriptor desc;
brianosmane25d71c2016-09-28 11:27:28 -0700777 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
778 localMatrix);
reed8a21c9f2016-03-08 18:50:00 -0800779 return sk_make_sp<SkLinearGradient>(pts, desc);
rileya@google.com589708b2012-07-26 20:04:23 +0000780}
781
reed8a21c9f2016-03-08 18:50:00 -0800782sk_sp<SkShader> SkGradientShader::MakeRadial(const SkPoint& center, SkScalar radius,
brianosmane25d71c2016-09-28 11:27:28 -0700783 const SkColor colors[],
784 const SkScalar pos[], int colorCount,
785 SkShader::TileMode mode,
786 uint32_t flags,
787 const SkMatrix* localMatrix) {
788 ColorConverter converter(colors, colorCount);
789 return MakeRadial(center, radius, converter.fColors4f.begin(), nullptr, pos, colorCount, mode,
790 flags, localMatrix);
791}
792
793sk_sp<SkShader> SkGradientShader::MakeRadial(const SkPoint& center, SkScalar radius,
794 const SkColor4f colors[],
795 sk_sp<SkColorSpace> colorSpace,
796 const SkScalar pos[], int colorCount,
797 SkShader::TileMode mode,
798 uint32_t flags,
799 const SkMatrix* localMatrix) {
reed1b747302015-01-06 07:13:19 -0800800 if (radius <= 0) {
halcanary96fcdcc2015-08-27 07:41:13 -0700801 return nullptr;
reed1b747302015-01-06 07:13:19 -0800802 }
803 if (!valid_grad(colors, pos, colorCount, mode)) {
halcanary96fcdcc2015-08-27 07:41:13 -0700804 return nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +0000805 }
fmenozzie9fd0f82016-08-19 07:50:57 -0700806 if (1 == colorCount) {
brianosmane25d71c2016-09-28 11:27:28 -0700807 return SkShader::MakeColorShader(colors[0], std::move(colorSpace));
fmenozzie9fd0f82016-08-19 07:50:57 -0700808 }
Florin Malita8d3ffad2017-02-03 18:21:17 +0000809 if (localMatrix && !localMatrix->invert(nullptr)) {
810 return nullptr;
811 }
rileya@google.com589708b2012-07-26 20:04:23 +0000812
fmenozzi68d952c2016-08-19 08:56:56 -0700813 ColorStopOptimizer opt(colors, pos, colorCount, mode);
814
reed@google.com437d6eb2013-05-23 19:03:05 +0000815 SkGradientShaderBase::Descriptor desc;
brianosmane25d71c2016-09-28 11:27:28 -0700816 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
817 localMatrix);
reed8a21c9f2016-03-08 18:50:00 -0800818 return sk_make_sp<SkRadialGradient>(center, radius, desc);
rileya@google.com589708b2012-07-26 20:04:23 +0000819}
820
reed8a21c9f2016-03-08 18:50:00 -0800821sk_sp<SkShader> SkGradientShader::MakeTwoPointConical(const SkPoint& start,
brianosmane25d71c2016-09-28 11:27:28 -0700822 SkScalar startRadius,
823 const SkPoint& end,
824 SkScalar endRadius,
825 const SkColor colors[],
826 const SkScalar pos[],
827 int colorCount,
828 SkShader::TileMode mode,
829 uint32_t flags,
830 const SkMatrix* localMatrix) {
831 ColorConverter converter(colors, colorCount);
832 return MakeTwoPointConical(start, startRadius, end, endRadius, converter.fColors4f.begin(),
833 nullptr, pos, colorCount, mode, flags, localMatrix);
834}
835
836sk_sp<SkShader> SkGradientShader::MakeTwoPointConical(const SkPoint& start,
837 SkScalar startRadius,
838 const SkPoint& end,
839 SkScalar endRadius,
840 const SkColor4f colors[],
841 sk_sp<SkColorSpace> colorSpace,
842 const SkScalar pos[],
843 int colorCount,
844 SkShader::TileMode mode,
845 uint32_t flags,
846 const SkMatrix* localMatrix) {
reed1b747302015-01-06 07:13:19 -0800847 if (startRadius < 0 || endRadius < 0) {
halcanary96fcdcc2015-08-27 07:41:13 -0700848 return nullptr;
reed1b747302015-01-06 07:13:19 -0800849 }
Florin Malita327290f2017-07-07 09:23:16 -0400850 if (SkScalarNearlyZero((start - end).length()) && SkScalarNearlyZero(startRadius)) {
851 // We can treat this gradient as radial, which is faster.
852 return MakeRadial(start, endRadius, colors, std::move(colorSpace), pos, colorCount,
853 mode, flags, localMatrix);
854 }
reed1b747302015-01-06 07:13:19 -0800855 if (!valid_grad(colors, pos, colorCount, mode)) {
halcanary96fcdcc2015-08-27 07:41:13 -0700856 return nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +0000857 }
fmalita5edf82e2016-03-03 06:41:54 -0800858 if (startRadius == endRadius) {
859 if (start == end || startRadius == 0) {
reed8a21c9f2016-03-08 18:50:00 -0800860 return SkShader::MakeEmptyShader();
fmalita5edf82e2016-03-03 06:41:54 -0800861 }
rileya@google.com589708b2012-07-26 20:04:23 +0000862 }
Florin Malita8d3ffad2017-02-03 18:21:17 +0000863 if (localMatrix && !localMatrix->invert(nullptr)) {
864 return nullptr;
865 }
reed6b7a6c72016-08-18 16:13:50 -0700866 EXPAND_1_COLOR(colorCount);
rileya@google.com589708b2012-07-26 20:04:23 +0000867
fmenozzi68d952c2016-08-19 08:56:56 -0700868 ColorStopOptimizer opt(colors, pos, colorCount, mode);
869
reed@google.com437d6eb2013-05-23 19:03:05 +0000870 SkGradientShaderBase::Descriptor desc;
Florin Malita5f379a82017-10-18 16:22:35 -0400871 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
872 localMatrix);
873 return SkTwoPointConicalGradient::Create(start, startRadius, end, endRadius, desc);
rileya@google.com589708b2012-07-26 20:04:23 +0000874}
875
reed8a21c9f2016-03-08 18:50:00 -0800876sk_sp<SkShader> SkGradientShader::MakeSweep(SkScalar cx, SkScalar cy,
brianosmane25d71c2016-09-28 11:27:28 -0700877 const SkColor colors[],
878 const SkScalar pos[],
879 int colorCount,
Florin Malita5a9a9812017-08-01 16:38:08 -0400880 SkShader::TileMode mode,
881 SkScalar startAngle,
882 SkScalar endAngle,
brianosmane25d71c2016-09-28 11:27:28 -0700883 uint32_t flags,
884 const SkMatrix* localMatrix) {
885 ColorConverter converter(colors, colorCount);
Florin Malita5a9a9812017-08-01 16:38:08 -0400886 return MakeSweep(cx, cy, converter.fColors4f.begin(), nullptr, pos, colorCount,
887 mode, startAngle, endAngle, flags, localMatrix);
brianosmane25d71c2016-09-28 11:27:28 -0700888}
889
890sk_sp<SkShader> SkGradientShader::MakeSweep(SkScalar cx, SkScalar cy,
891 const SkColor4f colors[],
892 sk_sp<SkColorSpace> colorSpace,
893 const SkScalar pos[],
894 int colorCount,
Florin Malita5a9a9812017-08-01 16:38:08 -0400895 SkShader::TileMode mode,
896 SkScalar startAngle,
897 SkScalar endAngle,
brianosmane25d71c2016-09-28 11:27:28 -0700898 uint32_t flags,
899 const SkMatrix* localMatrix) {
Florin Malita5a9a9812017-08-01 16:38:08 -0400900 if (!valid_grad(colors, pos, colorCount, mode)) {
halcanary96fcdcc2015-08-27 07:41:13 -0700901 return nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +0000902 }
fmenozzie9fd0f82016-08-19 07:50:57 -0700903 if (1 == colorCount) {
brianosmane25d71c2016-09-28 11:27:28 -0700904 return SkShader::MakeColorShader(colors[0], std::move(colorSpace));
fmenozzie9fd0f82016-08-19 07:50:57 -0700905 }
Florin Malita5a9a9812017-08-01 16:38:08 -0400906 if (startAngle >= endAngle) {
907 return nullptr;
908 }
Florin Malita8d3ffad2017-02-03 18:21:17 +0000909 if (localMatrix && !localMatrix->invert(nullptr)) {
910 return nullptr;
911 }
rileya@google.com589708b2012-07-26 20:04:23 +0000912
Florin Malita5a9a9812017-08-01 16:38:08 -0400913 if (startAngle <= 0 && endAngle >= 360) {
914 // If the t-range includes [0,1], then we can always use clamping (presumably faster).
915 mode = SkShader::kClamp_TileMode;
916 }
fmenozzi68d952c2016-08-19 08:56:56 -0700917
918 ColorStopOptimizer opt(colors, pos, colorCount, mode);
919
reed@google.com437d6eb2013-05-23 19:03:05 +0000920 SkGradientShaderBase::Descriptor desc;
brianosmane25d71c2016-09-28 11:27:28 -0700921 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
922 localMatrix);
Florin Malita5a9a9812017-08-01 16:38:08 -0400923
924 const SkScalar t0 = startAngle / 360,
925 t1 = endAngle / 360;
926
927 return sk_make_sp<SkSweepGradient>(SkPoint::Make(cx, cy), t0, t1, desc);
rileya@google.com589708b2012-07-26 20:04:23 +0000928}
929
930SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_START(SkGradientShader)
931 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkLinearGradient)
932 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkRadialGradient)
933 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkSweepGradient)
rileya@google.com589708b2012-07-26 20:04:23 +0000934 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkTwoPointConicalGradient)
935SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_END
rileya@google.comd7cc6512012-07-27 14:00:39 +0000936
937///////////////////////////////////////////////////////////////////////////////
938
bsalomon@google.comcf8fb1f2012-08-02 14:03:32 +0000939#if SK_SUPPORT_GPU
940
Brian Osman5911a7c2017-10-25 12:52:31 -0400941#include "GrColorSpaceXform.h"
brianosmana6359362016-03-21 06:55:37 -0700942#include "GrContext.h"
Robert Phillips1afd4cd2018-01-08 13:40:32 -0500943#include "GrContextPriv.h"
Brian Salomon94efbf52016-11-29 13:43:05 -0500944#include "GrShaderCaps.h"
ajuma95243eb2016-08-24 08:19:02 -0700945#include "GrTextureStripAtlas.h"
egdanielf5294392015-10-21 07:14:17 -0700946#include "gl/GrGLContext.h"
egdaniel2d721d32015-11-11 13:06:05 -0800947#include "glsl/GrGLSLFragmentShaderBuilder.h"
egdaniel018fb622015-10-28 07:26:40 -0700948#include "glsl/GrGLSLProgramDataManager.h"
egdaniel7ea439b2015-12-03 09:20:44 -0800949#include "glsl/GrGLSLUniformHandler.h"
bsalomon@google.comcf8fb1f2012-08-02 14:03:32 +0000950#include "SkGr.h"
951
fmenozzi55d318d2016-08-09 08:05:57 -0700952void GrGradientEffect::GLSLProcessor::emitUniforms(GrGLSLUniformHandler* uniformHandler,
953 const GrGradientEffect& ge) {
Florin Malita14a8dd72017-11-08 15:46:42 -0500954 switch (ge.fStrategy) {
955 case GrGradientEffect::InterpolationStrategy::kThreshold:
956 case GrGradientEffect::InterpolationStrategy::kThresholdClamp0:
957 case GrGradientEffect::InterpolationStrategy::kThresholdClamp1:
958 fThresholdUni = uniformHandler->addUniform(kFragment_GrShaderFlag,
959 kFloat_GrSLType,
960 kHigh_GrSLPrecision,
961 "Threshold");
962 // fall through
963 case GrGradientEffect::InterpolationStrategy::kSingle:
964 fIntervalsUni = uniformHandler->addUniformArray(kFragment_GrShaderFlag,
965 kHalf4_GrSLType,
966 "Intervals",
967 ge.fIntervals.count());
968 break;
969 case GrGradientEffect::InterpolationStrategy::kTexture:
970 fFSYUni = uniformHandler->addUniform(kFragment_GrShaderFlag, kHalf_GrSLType,
971 "GradientYCoordFS");
972 break;
bsalomon@google.com82d12232013-09-09 15:36:26 +0000973 }
974}
975
fmenozzi55d318d2016-08-09 08:05:57 -0700976void GrGradientEffect::GLSLProcessor::onSetData(const GrGLSLProgramDataManager& pdman,
Brian Salomonab015ef2017-04-04 10:15:51 -0400977 const GrFragmentProcessor& processor) {
joshualittb0a8a372014-09-23 09:50:21 -0700978 const GrGradientEffect& e = processor.cast<GrGradientEffect>();
bsalomon@google.com82d12232013-09-09 15:36:26 +0000979
Florin Malita14a8dd72017-11-08 15:46:42 -0500980 switch (e.fStrategy) {
981 case GrGradientEffect::InterpolationStrategy::kThreshold:
982 case GrGradientEffect::InterpolationStrategy::kThresholdClamp0:
983 case GrGradientEffect::InterpolationStrategy::kThresholdClamp1:
984 pdman.set1f(fThresholdUni, e.fThreshold);
Brian Salomon466ad992016-10-13 16:08:36 -0400985 // fall through
Florin Malita14a8dd72017-11-08 15:46:42 -0500986 case GrGradientEffect::InterpolationStrategy::kSingle:
987 pdman.set4fv(fIntervalsUni, e.fIntervals.count(),
988 reinterpret_cast<const float*>(e.fIntervals.begin()));
fmenozzicd9a1d02016-08-15 07:03:47 -0700989 break;
Florin Malita14a8dd72017-11-08 15:46:42 -0500990 case GrGradientEffect::InterpolationStrategy::kTexture:
991 if (e.fYCoord != fCachedYCoord) {
992 pdman.set1f(fFSYUni, e.fYCoord);
993 fCachedYCoord = e.fYCoord;
fmenozzicd9a1d02016-08-15 07:03:47 -0700994 }
995 break;
rileya@google.comb3e50f22012-08-20 17:43:08 +0000996 }
997}
998
Florin Malitae657dc82017-11-03 08:46:18 -0400999void GrGradientEffect::onGetGLSLProcessorKey(const GrShaderCaps&, GrProcessorKeyBuilder* b) const {
1000 b->add32(GLSLProcessor::GenBaseGradientKey(*this));
1001}
1002
fmenozzi55d318d2016-08-09 08:05:57 -07001003uint32_t GrGradientEffect::GLSLProcessor::GenBaseGradientKey(const GrProcessor& processor) {
joshualittb0a8a372014-09-23 09:50:21 -07001004 const GrGradientEffect& e = processor.cast<GrGradientEffect>();
skia.committer@gmail.com9a070f22013-09-10 07:01:44 +00001005
Florin Malita14a8dd72017-11-08 15:46:42 -05001006 // Build a key using the following bit allocation:
1007 static constexpr uint32_t kStrategyBits = 3;
1008 static constexpr uint32_t kPremulBits = 1;
1009 SkDEBUGCODE(static constexpr uint32_t kWrapModeBits = 2;)
bsalomon@google.com82d12232013-09-09 15:36:26 +00001010
Florin Malita14a8dd72017-11-08 15:46:42 -05001011 uint32_t key = static_cast<uint32_t>(e.fStrategy);
1012 SkASSERT(key < (1 << kStrategyBits));
1013
1014 // This is already baked into the table for texture gradients,
1015 // and only changes behavior for analytical gradients.
1016 if (e.fStrategy != InterpolationStrategy::kTexture &&
1017 e.fPremulType == GrGradientEffect::kBeforeInterp_PremulType) {
1018 key |= 1 << kStrategyBits;
1019 SkASSERT(key < (1 << (kStrategyBits + kPremulBits)));
bsalomon@google.com82d12232013-09-09 15:36:26 +00001020 }
1021
Florin Malita14a8dd72017-11-08 15:46:42 -05001022 key |= static_cast<uint32_t>(e.fWrapMode) << (kStrategyBits + kPremulBits);
1023 SkASSERT(key < (1 << (kStrategyBits + kPremulBits + kWrapModeBits)));
fmenozzicd9a1d02016-08-15 07:03:47 -07001024
bsalomon@google.com82d12232013-09-09 15:36:26 +00001025 return key;
bsalomon@google.comd8b5fac2012-11-01 17:02:46 +00001026}
1027
Florin Malitab81a8b92017-08-08 12:14:17 -04001028void GrGradientEffect::GLSLProcessor::emitAnalyticalColor(GrGLSLFPFragmentBuilder* fragBuilder,
1029 GrGLSLUniformHandler* uniformHandler,
1030 const GrShaderCaps* shaderCaps,
1031 const GrGradientEffect& ge,
1032 const char* t,
1033 const char* outputColor,
1034 const char* inputColor) {
1035 // First, apply tiling rules.
Brian Salomon2bbdcc42017-09-07 12:36:34 -04001036 switch (ge.fWrapMode) {
1037 case GrSamplerState::WrapMode::kClamp:
Florin Malita14a8dd72017-11-08 15:46:42 -05001038 switch (ge.fStrategy) {
1039 case GrGradientEffect::InterpolationStrategy::kThresholdClamp0:
1040 // allow t > 1, in order to hit the clamp interval (1, inf)
1041 fragBuilder->codeAppendf("half tiled_t = max(%s, 0.0);", t);
1042 break;
1043 case GrGradientEffect::InterpolationStrategy::kThresholdClamp1:
1044 // allow t < 0, in order to hit the clamp interval (-inf, 0)
1045 fragBuilder->codeAppendf("half tiled_t = min(%s, 1.0);", t);
1046 break;
1047 default:
1048 // regular [0, 1] clamping
1049 fragBuilder->codeAppendf("half tiled_t = clamp(%s, 0.0, 1.0);", t);
1050 }
Brian Salomon2bbdcc42017-09-07 12:36:34 -04001051 break;
1052 case GrSamplerState::WrapMode::kRepeat:
Florin Malita14a8dd72017-11-08 15:46:42 -05001053 fragBuilder->codeAppendf("half tiled_t = fract(%s);", t);
Brian Salomon2bbdcc42017-09-07 12:36:34 -04001054 break;
1055 case GrSamplerState::WrapMode::kMirrorRepeat:
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001056 fragBuilder->codeAppendf("half t_1 = %s - 1.0;", t);
Greg Daniel10ed2432017-12-01 16:19:43 -05001057 fragBuilder->codeAppendf("half tiled_t = t_1 - 2.0 * floor(t_1 * 0.5) - 1.0;");
1058 if (shaderCaps->mustDoOpBetweenFloorAndAbs()) {
1059 // At this point the expected value of tiled_t should between -1 and 1, so this
1060 // clamp has no effect other than to break up the floor and abs calls and make sure
1061 // the compiler doesn't merge them back together.
1062 fragBuilder->codeAppendf("tiled_t = clamp(tiled_t, -1.0, 1.0);");
1063 }
1064 fragBuilder->codeAppendf("tiled_t = abs(tiled_t);");
Brian Salomon2bbdcc42017-09-07 12:36:34 -04001065 break;
Florin Malita8a0044f2017-08-07 14:38:22 -04001066 }
Florin Malita8a0044f2017-08-07 14:38:22 -04001067
Florin Malitab81a8b92017-08-08 12:14:17 -04001068 // Calculate the color.
Florin Malita14a8dd72017-11-08 15:46:42 -05001069 const char* intervals = uniformHandler->getUniformCStr(fIntervalsUni);
fmenozzicd9a1d02016-08-15 07:03:47 -07001070
Florin Malita14a8dd72017-11-08 15:46:42 -05001071 switch (ge.fStrategy) {
1072 case GrGradientEffect::InterpolationStrategy::kSingle:
1073 SkASSERT(ge.fIntervals.count() == 2);
1074 fragBuilder->codeAppendf(
1075 "half4 color_scale = %s[0],"
1076 " color_bias = %s[1];"
1077 , intervals, intervals
1078 );
fmenozzicd9a1d02016-08-15 07:03:47 -07001079 break;
Florin Malita14a8dd72017-11-08 15:46:42 -05001080 case GrGradientEffect::InterpolationStrategy::kThreshold:
1081 case GrGradientEffect::InterpolationStrategy::kThresholdClamp0:
1082 case GrGradientEffect::InterpolationStrategy::kThresholdClamp1:
1083 {
1084 SkASSERT(ge.fIntervals.count() == 4);
1085 const char* threshold = uniformHandler->getUniformCStr(fThresholdUni);
1086 fragBuilder->codeAppendf(
1087 "half4 color_scale, color_bias;"
1088 "if (tiled_t < %s) {"
1089 " color_scale = %s[0];"
1090 " color_bias = %s[1];"
1091 "} else {"
1092 " color_scale = %s[2];"
1093 " color_bias = %s[3];"
1094 "}"
1095 , threshold, intervals, intervals, intervals, intervals
1096 );
1097 } break;
Florin Malitab81a8b92017-08-08 12:14:17 -04001098 default:
1099 SkASSERT(false);
fmenozzicd9a1d02016-08-15 07:03:47 -07001100 break;
bsalomon@google.com82d12232013-09-09 15:36:26 +00001101 }
Florin Malitab81a8b92017-08-08 12:14:17 -04001102
Florin Malita14a8dd72017-11-08 15:46:42 -05001103 fragBuilder->codeAppend("half4 colorTemp = tiled_t * color_scale + color_bias;");
1104
Brian Osmanfe3e8582017-10-20 11:27:49 -04001105 // We could skip this step if all colors are known to be opaque. Two considerations:
Florin Malitab81a8b92017-08-08 12:14:17 -04001106 // The gradient SkShader reporting opaque is more restrictive than necessary in the two
1107 // pt case. Make sure the key reflects this optimization (and note that it can use the
Brian Osmanfe3e8582017-10-20 11:27:49 -04001108 // same shader as the kBeforeInterp case).
Florin Malita14a8dd72017-11-08 15:46:42 -05001109 if (ge.fPremulType == GrGradientEffect::kAfterInterp_PremulType) {
Florin Malitab81a8b92017-08-08 12:14:17 -04001110 fragBuilder->codeAppend("colorTemp.rgb *= colorTemp.a;");
1111 }
Brian Osman5911a7c2017-10-25 12:52:31 -04001112
1113 // 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 -04001114 // range. The simplest solution is to always clamp our (premul) value here. We only need to
1115 // clamp RGB, but that causes hangs on the Tegra3 Nexus7. Clamping RGBA avoids the problem.
1116 fragBuilder->codeAppend("colorTemp = clamp(colorTemp, 0, colorTemp.a);");
Florin Malitab81a8b92017-08-08 12:14:17 -04001117
1118 fragBuilder->codeAppendf("%s = %s * colorTemp;", outputColor, inputColor);
1119}
1120
1121void GrGradientEffect::GLSLProcessor::emitColor(GrGLSLFPFragmentBuilder* fragBuilder,
1122 GrGLSLUniformHandler* uniformHandler,
1123 const GrShaderCaps* shaderCaps,
1124 const GrGradientEffect& ge,
1125 const char* gradientTValue,
1126 const char* outputColor,
1127 const char* inputColor,
1128 const TextureSamplers& texSamplers) {
Florin Malita14a8dd72017-11-08 15:46:42 -05001129 if (ge.fStrategy != InterpolationStrategy::kTexture) {
Florin Malitab81a8b92017-08-08 12:14:17 -04001130 this->emitAnalyticalColor(fragBuilder, uniformHandler, shaderCaps, ge, gradientTValue,
1131 outputColor, inputColor);
1132 return;
1133 }
1134
Florin Malitab81a8b92017-08-08 12:14:17 -04001135 const char* fsyuni = uniformHandler->getUniformCStr(fFSYUni);
1136
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001137 fragBuilder->codeAppendf("half2 coord = half2(%s, %s);", gradientTValue, fsyuni);
Florin Malitab81a8b92017-08-08 12:14:17 -04001138 fragBuilder->codeAppendf("%s = ", outputColor);
1139 fragBuilder->appendTextureLookupAndModulate(inputColor, texSamplers[0], "coord",
Brian Osman5911a7c2017-10-25 12:52:31 -04001140 kFloat2_GrSLType);
Florin Malitab81a8b92017-08-08 12:14:17 -04001141 fragBuilder->codeAppend(";");
rileya@google.comd7cc6512012-07-27 14:00:39 +00001142}
1143
1144/////////////////////////////////////////////////////////////////////
1145
Brian Salomon587e08f2017-01-27 10:59:27 -05001146inline GrFragmentProcessor::OptimizationFlags GrGradientEffect::OptFlags(bool isOpaque) {
Brian Salomonf3b995b2017-02-15 10:22:23 -05001147 return isOpaque
1148 ? kPreservesOpaqueInput_OptimizationFlag |
1149 kCompatibleWithCoverageAsAlpha_OptimizationFlag
1150 : kCompatibleWithCoverageAsAlpha_OptimizationFlag;
Brian Salomon587e08f2017-01-27 10:59:27 -05001151}
1152
Florin Malita14a8dd72017-11-08 15:46:42 -05001153void GrGradientEffect::addInterval(const SkGradientShaderBase& shader, size_t idx0, size_t idx1,
1154 SkColorSpace* dstCS) {
1155 SkASSERT(idx0 <= idx1);
1156 const auto c4f0 = shader.getXformedColor(idx0, dstCS),
1157 c4f1 = shader.getXformedColor(idx1, dstCS);
1158 const auto c0 = (fPremulType == kBeforeInterp_PremulType)
1159 ? c4f0.premul().to4f() : Sk4f::Load(c4f0.vec()),
1160 c1 = (fPremulType == kBeforeInterp_PremulType)
1161 ? c4f1.premul().to4f() : Sk4f::Load(c4f1.vec());
1162 const auto t0 = shader.getPos(idx0),
1163 t1 = shader.getPos(idx1),
1164 dt = t1 - t0;
1165 SkASSERT(dt >= 0);
1166 // dt can be 0 for clamp intervals => in this case we want a scale == 0
1167 const auto scale = SkScalarNearlyZero(dt) ? 0 : (c1 - c0) / dt,
1168 bias = c0 - t0 * scale;
1169
1170 // Intervals are stored as (scale, bias) tuples.
1171 SkASSERT(!(fIntervals.count() & 1));
1172 fIntervals.emplace_back(scale[0], scale[1], scale[2], scale[3]);
1173 fIntervals.emplace_back( bias[0], bias[1], bias[2], bias[3]);
1174}
1175
Ethan Nicholasabff9562017-10-09 10:54:08 -04001176GrGradientEffect::GrGradientEffect(ClassID classID, const CreateArgs& args, bool isOpaque)
Florin Malita14a8dd72017-11-08 15:46:42 -05001177 : INHERITED(classID, OptFlags(isOpaque))
1178 , fWrapMode(args.fWrapMode)
1179 , fRow(-1)
1180 , fIsOpaque(args.fShader->isOpaque())
1181 , fStrategy(InterpolationStrategy::kTexture)
1182 , fThreshold(0) {
1183
brianosman9557c272016-09-15 06:59:15 -07001184 const SkGradientShaderBase& shader(*args.fShader);
bsalomon@google.com82d12232013-09-09 15:36:26 +00001185
Florin Malita14a8dd72017-11-08 15:46:42 -05001186 fPremulType = (args.fShader->getGradFlags() & SkGradientShader::kInterpolateColorsInPremul_Flag)
1187 ? kBeforeInterp_PremulType : kAfterInterp_PremulType;
bsalomon@google.com371e1052013-01-11 21:08:55 +00001188
Florin Malita14a8dd72017-11-08 15:46:42 -05001189 // First, determine the interpolation strategy and params.
1190 switch (shader.fColorCount) {
1191 case 2:
1192 SkASSERT(!shader.fOrigPos);
1193 fStrategy = InterpolationStrategy::kSingle;
1194 this->addInterval(shader, 0, 1, args.fDstColorSpace);
1195 break;
1196 case 3:
1197 fThreshold = shader.getPos(1);
bsalomon@google.com1ce49fc2012-09-18 14:14:49 +00001198
Florin Malita14a8dd72017-11-08 15:46:42 -05001199 if (shader.fOrigPos) {
1200 SkASSERT(SkScalarNearlyEqual(shader.fOrigPos[0], 0));
1201 SkASSERT(SkScalarNearlyEqual(shader.fOrigPos[2], 1));
1202 if (SkScalarNearlyEqual(shader.fOrigPos[1], 0)) {
1203 // hard stop on the left edge.
1204 if (fWrapMode == GrSamplerState::WrapMode::kClamp) {
1205 fStrategy = InterpolationStrategy::kThresholdClamp1;
1206 // Clamp interval (scale == 0, bias == colors[0]).
1207 this->addInterval(shader, 0, 0, args.fDstColorSpace);
1208 } else {
1209 // We can ignore the hard stop when not clamping.
1210 fStrategy = InterpolationStrategy::kSingle;
1211 }
1212 this->addInterval(shader, 1, 2, args.fDstColorSpace);
1213 break;
1214 }
Brian Osmand43f7b62017-10-19 15:42:01 -04001215
Florin Malita14a8dd72017-11-08 15:46:42 -05001216 if (SkScalarNearlyEqual(shader.fOrigPos[1], 1)) {
1217 // hard stop on the right edge.
1218 this->addInterval(shader, 0, 1, args.fDstColorSpace);
1219 if (fWrapMode == GrSamplerState::WrapMode::kClamp) {
1220 fStrategy = InterpolationStrategy::kThresholdClamp0;
1221 // Clamp interval (scale == 0, bias == colors[2]).
1222 this->addInterval(shader, 2, 2, args.fDstColorSpace);
1223 } else {
1224 // We can ignore the hard stop when not clamping.
1225 fStrategy = InterpolationStrategy::kSingle;
1226 }
1227 break;
1228 }
Brian Osmand43f7b62017-10-19 15:42:01 -04001229 }
1230
Florin Malita14a8dd72017-11-08 15:46:42 -05001231 // Two arbitrary interpolation intervals.
1232 fStrategy = InterpolationStrategy::kThreshold;
1233 this->addInterval(shader, 0, 1, args.fDstColorSpace);
1234 this->addInterval(shader, 1, 2, args.fDstColorSpace);
1235 break;
1236 case 4:
1237 if (shader.fOrigPos && SkScalarNearlyEqual(shader.fOrigPos[1], shader.fOrigPos[2])) {
1238 SkASSERT(SkScalarNearlyEqual(shader.fOrigPos[0], 0));
1239 SkASSERT(SkScalarNearlyEqual(shader.fOrigPos[3], 1));
fmenozzi2a495912016-08-12 06:33:52 -07001240
Florin Malita14a8dd72017-11-08 15:46:42 -05001241 // Single hard stop => two arbitrary interpolation intervals.
1242 fStrategy = InterpolationStrategy::kThreshold;
1243 fThreshold = shader.getPos(1);
1244 this->addInterval(shader, 0, 1, args.fDstColorSpace);
1245 this->addInterval(shader, 2, 3, args.fDstColorSpace);
1246 }
1247 break;
1248 default:
1249 break;
fmenozzi2a495912016-08-12 06:33:52 -07001250 }
fmenozzicd9a1d02016-08-15 07:03:47 -07001251
Florin Malita14a8dd72017-11-08 15:46:42 -05001252 // Now that we've locked down a strategy, adjust any dependent params.
1253 if (fStrategy != InterpolationStrategy::kTexture) {
1254 // Analytical cases.
1255 fCoordTransform.reset(*args.fMatrix);
1256 } else {
1257 SkGradientShaderBase::GradientBitmapType bitmapType =
1258 SkGradientShaderBase::GradientBitmapType::kLegacy;
1259 if (args.fDstColorSpace) {
1260 // Try to use F16 if we can
1261 if (args.fContext->caps()->isConfigTexturable(kRGBA_half_GrPixelConfig)) {
1262 bitmapType = SkGradientShaderBase::GradientBitmapType::kHalfFloat;
1263 } else if (args.fContext->caps()->isConfigTexturable(kSRGBA_8888_GrPixelConfig)) {
1264 bitmapType = SkGradientShaderBase::GradientBitmapType::kSRGB;
fmenozzicd9a1d02016-08-15 07:03:47 -07001265 } else {
Florin Malita14a8dd72017-11-08 15:46:42 -05001266 // This can happen, but only if someone explicitly creates an unsupported
1267 // (eg sRGB) surface. Just fall back to legacy behavior.
fmenozzicd9a1d02016-08-15 07:03:47 -07001268 }
Florin Malita14a8dd72017-11-08 15:46:42 -05001269 }
fmenozzicd9a1d02016-08-15 07:03:47 -07001270
Florin Malita14a8dd72017-11-08 15:46:42 -05001271 SkBitmap bitmap;
1272 shader.getGradientTableBitmap(&bitmap, bitmapType);
1273 SkASSERT(1 == bitmap.height() && SkIsPow2(bitmap.width()));
fmenozzicd9a1d02016-08-15 07:03:47 -07001274
Florin Malita14a8dd72017-11-08 15:46:42 -05001275
1276 GrTextureStripAtlas::Desc desc;
1277 desc.fWidth = bitmap.width();
1278 desc.fHeight = 32;
Robert Phillips7a926392018-02-01 15:49:54 -05001279 desc.fRowHeight = bitmap.height(); // always 1 here
Florin Malita14a8dd72017-11-08 15:46:42 -05001280 desc.fContext = args.fContext;
1281 desc.fConfig = SkImageInfo2GrPixelConfig(bitmap.info(), *args.fContext->caps());
1282 fAtlas = GrTextureStripAtlas::GetAtlas(desc);
1283 SkASSERT(fAtlas);
1284
1285 // We always filter the gradient table. Each table is one row of a texture, always
1286 // y-clamp.
1287 GrSamplerState samplerState(args.fWrapMode, GrSamplerState::Filter::kBilerp);
1288
1289 fRow = fAtlas->lockRow(bitmap);
1290 if (-1 != fRow) {
1291 fYCoord = fAtlas->getYOffset(fRow)+SK_ScalarHalf*fAtlas->getNormalizedTexelHeight();
1292 // This is 1/2 places where auto-normalization is disabled
1293 fCoordTransform.reset(*args.fMatrix, fAtlas->asTextureProxyRef().get(), false);
1294 fTextureSampler.reset(fAtlas->asTextureProxyRef(), samplerState);
1295 } else {
1296 // In this instance we know the samplerState state is:
1297 // clampY, bilerp
1298 // and the proxy is:
1299 // exact fit, power of two in both dimensions
1300 // Only the x-tileMode is unknown. However, given all the other knowns we know
Robert Phillips7a926392018-02-01 15:49:54 -05001301 // that GrMakeCachedImageProxy is sufficient (i.e., it won't need to be
Florin Malita14a8dd72017-11-08 15:46:42 -05001302 // extracted to a subset or mipmapped).
Robert Phillips7a926392018-02-01 15:49:54 -05001303
1304 SkASSERT(bitmap.isImmutable());
1305 sk_sp<SkImage> srcImage = SkImage::MakeFromBitmap(bitmap);
1306 if (!srcImage) {
1307 return;
1308 }
1309
1310 sk_sp<GrTextureProxy> proxy = GrMakeCachedImageProxy(
Robert Phillips1afd4cd2018-01-08 13:40:32 -05001311 args.fContext->contextPriv().proxyProvider(),
Robert Phillips7a926392018-02-01 15:49:54 -05001312 std::move(srcImage));
Florin Malita14a8dd72017-11-08 15:46:42 -05001313 if (!proxy) {
1314 SkDebugf("Gradient won't draw. Could not create texture.");
1315 return;
1316 }
1317 // This is 2/2 places where auto-normalization is disabled
1318 fCoordTransform.reset(*args.fMatrix, proxy.get(), false);
1319 fTextureSampler.reset(std::move(proxy), samplerState);
1320 fYCoord = SK_ScalarHalf;
1321 }
1322
1323 this->addTextureSampler(&fTextureSampler);
fmenozzicd9a1d02016-08-15 07:03:47 -07001324 }
1325
bsalomon@google.com77af6802013-10-02 13:04:56 +00001326 this->addCoordTransform(&fCoordTransform);
rileya@google.comd7cc6512012-07-27 14:00:39 +00001327}
1328
Brian Salomonf8480b92017-07-27 15:45:59 -04001329GrGradientEffect::GrGradientEffect(const GrGradientEffect& that)
Ethan Nicholasabff9562017-10-09 10:54:08 -04001330 : INHERITED(that.classID(), OptFlags(that.fIsOpaque))
Florin Malita14a8dd72017-11-08 15:46:42 -05001331 , fIntervals(that.fIntervals)
Brian Salomon2bbdcc42017-09-07 12:36:34 -04001332 , fWrapMode(that.fWrapMode)
Brian Salomonf8480b92017-07-27 15:45:59 -04001333 , fCoordTransform(that.fCoordTransform)
1334 , fTextureSampler(that.fTextureSampler)
1335 , fYCoord(that.fYCoord)
1336 , fAtlas(that.fAtlas)
1337 , fRow(that.fRow)
1338 , fIsOpaque(that.fIsOpaque)
Florin Malita14a8dd72017-11-08 15:46:42 -05001339 , fStrategy(that.fStrategy)
1340 , fThreshold(that.fThreshold)
Brian Salomonf8480b92017-07-27 15:45:59 -04001341 , fPremulType(that.fPremulType) {
1342 this->addCoordTransform(&fCoordTransform);
Florin Malita14a8dd72017-11-08 15:46:42 -05001343 if (fStrategy == InterpolationStrategy::kTexture) {
Brian Salomonf8480b92017-07-27 15:45:59 -04001344 this->addTextureSampler(&fTextureSampler);
1345 }
1346 if (this->useAtlas()) {
1347 fAtlas->lockRow(fRow);
1348 }
1349}
1350
rileya@google.comd7cc6512012-07-27 14:00:39 +00001351GrGradientEffect::~GrGradientEffect() {
rileya@google.comb3e50f22012-08-20 17:43:08 +00001352 if (this->useAtlas()) {
1353 fAtlas->unlockRow(fRow);
rileya@google.comb3e50f22012-08-20 17:43:08 +00001354 }
rileya@google.comd7cc6512012-07-27 14:00:39 +00001355}
1356
bsalomon0e08fc12014-10-15 08:19:04 -07001357bool GrGradientEffect::onIsEqual(const GrFragmentProcessor& processor) const {
fmenozzicd9a1d02016-08-15 07:03:47 -07001358 const GrGradientEffect& ge = processor.cast<GrGradientEffect>();
bsalomon@google.com82d12232013-09-09 15:36:26 +00001359
Florin Malita14a8dd72017-11-08 15:46:42 -05001360 if (fWrapMode != ge.fWrapMode || fStrategy != ge.fStrategy) {
Brian Salomon466ad992016-10-13 16:08:36 -04001361 return false;
1362 }
Florin Malita14a8dd72017-11-08 15:46:42 -05001363
Brian Salomon466ad992016-10-13 16:08:36 -04001364 SkASSERT(this->useAtlas() == ge.useAtlas());
Florin Malita14a8dd72017-11-08 15:46:42 -05001365 if (fStrategy == InterpolationStrategy::kTexture) {
1366 if (fYCoord != ge.fYCoord) {
Brian Salomon466ad992016-10-13 16:08:36 -04001367 return false;
1368 }
1369 } else {
Florin Malita14a8dd72017-11-08 15:46:42 -05001370 if (fThreshold != ge.fThreshold ||
1371 fIntervals != ge.fIntervals ||
1372 fPremulType != ge.fPremulType) {
Brian Salomon466ad992016-10-13 16:08:36 -04001373 return false;
1374 }
bsalomon@google.com82d12232013-09-09 15:36:26 +00001375 }
Brian Osman5911a7c2017-10-25 12:52:31 -04001376 return true;
bsalomon@google.com68b58c92013-01-17 16:50:08 +00001377}
1378
Hal Canary6f6961e2017-01-31 13:50:44 -05001379#if GR_TEST_UTILS
Brian Osman3f748602016-10-03 18:29:03 -04001380GrGradientEffect::RandomGradientParams::RandomGradientParams(SkRandom* random) {
Brian Salomon5d4cd9e2017-02-09 11:16:46 -05001381 // Set color count to min of 2 so that we don't trigger the const color optimization and make
1382 // a non-gradient processor.
1383 fColorCount = random->nextRangeU(2, kMaxRandomGradientColors);
Brian Osmana2196532016-10-17 12:48:13 -04001384 fUseColors4f = random->nextBool();
bsalomon@google.comd4726202012-08-03 14:34:46 +00001385
1386 // if one color, omit stops, otherwise randomly decide whether or not to
Brian Osman3f748602016-10-03 18:29:03 -04001387 if (fColorCount == 1 || (fColorCount >= 2 && random->nextBool())) {
1388 fStops = nullptr;
1389 } else {
1390 fStops = fStopStorage;
bsalomon@google.comd4726202012-08-03 14:34:46 +00001391 }
1392
Brian Osmana2196532016-10-17 12:48:13 -04001393 // if using SkColor4f, attach a random (possibly null) color space (with linear gamma)
1394 if (fUseColors4f) {
1395 fColorSpace = GrTest::TestColorSpace(random);
1396 if (fColorSpace) {
Brian Osman36703d92017-12-12 14:09:31 -05001397 fColorSpace = fColorSpace->makeLinearGamma();
Brian Osmana2196532016-10-17 12:48:13 -04001398 }
1399 }
1400
bsalomon@google.com81712882012-11-01 17:12:34 +00001401 SkScalar stop = 0.f;
Brian Osman3f748602016-10-03 18:29:03 -04001402 for (int i = 0; i < fColorCount; ++i) {
Brian Osmana2196532016-10-17 12:48:13 -04001403 if (fUseColors4f) {
1404 fColors4f[i].fR = random->nextUScalar1();
1405 fColors4f[i].fG = random->nextUScalar1();
1406 fColors4f[i].fB = random->nextUScalar1();
1407 fColors4f[i].fA = random->nextUScalar1();
1408 } else {
1409 fColors[i] = random->nextU();
1410 }
Brian Osman3f748602016-10-03 18:29:03 -04001411 if (fStops) {
1412 fStops[i] = stop;
1413 stop = i < fColorCount - 1 ? stop + random->nextUScalar1() * (1.f - stop) : 1.f;
bsalomon@google.comd4726202012-08-03 14:34:46 +00001414 }
1415 }
Brian Osman3f748602016-10-03 18:29:03 -04001416 fTileMode = static_cast<SkShader::TileMode>(random->nextULessThan(SkShader::kTileModeCount));
bsalomon@google.comd4726202012-08-03 14:34:46 +00001417}
Hal Canary6f6961e2017-01-31 13:50:44 -05001418#endif
bsalomon@google.comd4726202012-08-03 14:34:46 +00001419
bsalomon@google.comcf8fb1f2012-08-02 14:03:32 +00001420#endif