blob: c448b4038a4adbf72875497a8d40f3973d6cbcac [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);
rileya@google.com589708b2012-07-26 20:04:23 +0000594 gCache->add(storage.get(), size, *bitmap);
595 }
596}
597
Florin Malita5f379a82017-10-18 16:22:35 -0400598void SkGradientShaderBase::commonAsAGradient(GradientInfo* info) const {
rileya@google.com589708b2012-07-26 20:04:23 +0000599 if (info) {
600 if (info->fColorCount >= fColorCount) {
601 if (info->fColors) {
Florin Malita39d71de2017-10-31 11:33:49 -0400602 for (int i = 0; i < fColorCount; ++i) {
603 info->fColors[i] = this->getLegacyColor(i);
604 }
rileya@google.com589708b2012-07-26 20:04:23 +0000605 }
606 if (info->fColorOffsets) {
Florin Malitaed6ae562017-10-28 11:06:48 -0400607 for (int i = 0; i < fColorCount; ++i) {
608 info->fColorOffsets[i] = this->getPos(i);
rileya@google.com589708b2012-07-26 20:04:23 +0000609 }
610 }
611 }
612 info->fColorCount = fColorCount;
613 info->fTileMode = fTileMode;
reed@google.com3d3a8602013-05-24 14:58:44 +0000614 info->fGradientFlags = fGradFlags;
rileya@google.com589708b2012-07-26 20:04:23 +0000615 }
616}
617
commit-bot@chromium.org0f10f7b2014-03-13 18:02:17 +0000618#ifndef SK_IGNORE_TO_STRING
robertphillips@google.com76f9e932013-01-15 20:17:47 +0000619void SkGradientShaderBase::toString(SkString* str) const {
620
621 str->appendf("%d colors: ", fColorCount);
622
623 for (int i = 0; i < fColorCount; ++i) {
Florin Malita39d71de2017-10-31 11:33:49 -0400624 str->appendHex(this->getLegacyColor(i), 8);
robertphillips@google.com76f9e932013-01-15 20:17:47 +0000625 if (i < fColorCount-1) {
626 str->append(", ");
627 }
628 }
629
630 if (fColorCount > 2) {
631 str->append(" points: (");
632 for (int i = 0; i < fColorCount; ++i) {
Florin Malitaed6ae562017-10-28 11:06:48 -0400633 str->appendScalar(this->getPos(i));
robertphillips@google.com76f9e932013-01-15 20:17:47 +0000634 if (i < fColorCount-1) {
635 str->append(", ");
636 }
637 }
638 str->append(")");
639 }
640
641 static const char* gTileModeName[SkShader::kTileModeCount] = {
642 "clamp", "repeat", "mirror"
643 };
644
645 str->append(" ");
646 str->append(gTileModeName[fTileMode]);
647
robertphillips@google.com76f9e932013-01-15 20:17:47 +0000648 this->INHERITED::toString(str);
649}
650#endif
651
rileya@google.com589708b2012-07-26 20:04:23 +0000652///////////////////////////////////////////////////////////////////////////////
653///////////////////////////////////////////////////////////////////////////////
654
reed1b747302015-01-06 07:13:19 -0800655// Return true if these parameters are valid/legal/safe to construct a gradient
656//
brianosmane25d71c2016-09-28 11:27:28 -0700657static bool valid_grad(const SkColor4f colors[], const SkScalar pos[], int count,
658 unsigned tileMode) {
halcanary96fcdcc2015-08-27 07:41:13 -0700659 return nullptr != colors && count >= 1 && tileMode < (unsigned)SkShader::kTileModeCount;
reed1b747302015-01-06 07:13:19 -0800660}
661
reed@google.com437d6eb2013-05-23 19:03:05 +0000662static void desc_init(SkGradientShaderBase::Descriptor* desc,
brianosmane25d71c2016-09-28 11:27:28 -0700663 const SkColor4f colors[], sk_sp<SkColorSpace> colorSpace,
664 const SkScalar pos[], int colorCount,
reedaddf2ed2014-08-11 08:28:24 -0700665 SkShader::TileMode mode, uint32_t flags, const SkMatrix* localMatrix) {
fmalita748d6202016-05-11 11:39:58 -0700666 SkASSERT(colorCount > 1);
667
commit-bot@chromium.org6c5aea22014-04-22 16:25:15 +0000668 desc->fColors = colors;
brianosmane25d71c2016-09-28 11:27:28 -0700669 desc->fColorSpace = std::move(colorSpace);
commit-bot@chromium.org6c5aea22014-04-22 16:25:15 +0000670 desc->fPos = pos;
671 desc->fCount = colorCount;
672 desc->fTileMode = mode;
commit-bot@chromium.org6c5aea22014-04-22 16:25:15 +0000673 desc->fGradFlags = flags;
reedaddf2ed2014-08-11 08:28:24 -0700674 desc->fLocalMatrix = localMatrix;
reed@google.com437d6eb2013-05-23 19:03:05 +0000675}
676
brianosmane25d71c2016-09-28 11:27:28 -0700677// assumes colors is SkColor4f* and pos is SkScalar*
fmenozzie9fd0f82016-08-19 07:50:57 -0700678#define EXPAND_1_COLOR(count) \
brianosmane25d71c2016-09-28 11:27:28 -0700679 SkColor4f tmp[2]; \
fmenozzie9fd0f82016-08-19 07:50:57 -0700680 do { \
681 if (1 == count) { \
682 tmp[0] = tmp[1] = colors[0]; \
683 colors = tmp; \
684 pos = nullptr; \
685 count = 2; \
686 } \
687 } while (0)
688
fmenozzi68d952c2016-08-19 08:56:56 -0700689struct ColorStopOptimizer {
brianosmane25d71c2016-09-28 11:27:28 -0700690 ColorStopOptimizer(const SkColor4f* colors, const SkScalar* pos,
fmenozzi68d952c2016-08-19 08:56:56 -0700691 int count, SkShader::TileMode mode)
692 : fColors(colors)
693 , fPos(pos)
694 , fCount(count) {
695
696 if (!pos || count != 3) {
697 return;
698 }
699
700 if (SkScalarNearlyEqual(pos[0], 0.0f) &&
701 SkScalarNearlyEqual(pos[1], 0.0f) &&
702 SkScalarNearlyEqual(pos[2], 1.0f)) {
703
704 if (SkShader::kRepeat_TileMode == mode ||
705 SkShader::kMirror_TileMode == mode ||
706 colors[0] == colors[1]) {
707
fmalita582a6562016-08-22 06:28:57 -0700708 // Ignore the leftmost color/pos.
709 fColors += 1;
710 fPos += 1;
711 fCount = 2;
fmenozzi68d952c2016-08-19 08:56:56 -0700712 }
713 } else if (SkScalarNearlyEqual(pos[0], 0.0f) &&
714 SkScalarNearlyEqual(pos[1], 1.0f) &&
715 SkScalarNearlyEqual(pos[2], 1.0f)) {
716
717 if (SkShader::kRepeat_TileMode == mode ||
718 SkShader::kMirror_TileMode == mode ||
719 colors[1] == colors[2]) {
720
fmalita582a6562016-08-22 06:28:57 -0700721 // Ignore the rightmost color/pos.
fmenozzi68d952c2016-08-19 08:56:56 -0700722 fCount = 2;
723 }
724 }
725 }
726
brianosmane25d71c2016-09-28 11:27:28 -0700727 const SkColor4f* fColors;
728 const SkScalar* fPos;
729 int fCount;
730};
731
732struct ColorConverter {
733 ColorConverter(const SkColor* colors, int count) {
734 for (int i = 0; i < count; ++i) {
735 fColors4f.push_back(SkColor4f::FromColor(colors[i]));
736 }
737 }
738
739 SkSTArray<2, SkColor4f, true> fColors4f;
fmenozzi68d952c2016-08-19 08:56:56 -0700740};
741
reed8a21c9f2016-03-08 18:50:00 -0800742sk_sp<SkShader> SkGradientShader::MakeLinear(const SkPoint pts[2],
fmenozzi68d952c2016-08-19 08:56:56 -0700743 const SkColor colors[],
744 const SkScalar pos[], int colorCount,
745 SkShader::TileMode mode,
746 uint32_t flags,
747 const SkMatrix* localMatrix) {
brianosmane25d71c2016-09-28 11:27:28 -0700748 ColorConverter converter(colors, colorCount);
749 return MakeLinear(pts, converter.fColors4f.begin(), nullptr, pos, colorCount, mode, flags,
750 localMatrix);
751}
752
753sk_sp<SkShader> SkGradientShader::MakeLinear(const SkPoint pts[2],
754 const SkColor4f colors[],
755 sk_sp<SkColorSpace> colorSpace,
756 const SkScalar pos[], int colorCount,
757 SkShader::TileMode mode,
758 uint32_t flags,
759 const SkMatrix* localMatrix) {
fmalitac5231042016-08-10 05:45:50 -0700760 if (!pts || !SkScalarIsFinite((pts[1] - pts[0]).length())) {
halcanary96fcdcc2015-08-27 07:41:13 -0700761 return nullptr;
reed1b747302015-01-06 07:13:19 -0800762 }
763 if (!valid_grad(colors, pos, colorCount, mode)) {
halcanary96fcdcc2015-08-27 07:41:13 -0700764 return nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +0000765 }
fmenozzie9fd0f82016-08-19 07:50:57 -0700766 if (1 == colorCount) {
brianosmane25d71c2016-09-28 11:27:28 -0700767 return SkShader::MakeColorShader(colors[0], std::move(colorSpace));
fmenozzie9fd0f82016-08-19 07:50:57 -0700768 }
Florin Malita8d3ffad2017-02-03 18:21:17 +0000769 if (localMatrix && !localMatrix->invert(nullptr)) {
770 return nullptr;
771 }
rileya@google.com589708b2012-07-26 20:04:23 +0000772
fmenozzi68d952c2016-08-19 08:56:56 -0700773 ColorStopOptimizer opt(colors, pos, colorCount, mode);
774
reed@google.com437d6eb2013-05-23 19:03:05 +0000775 SkGradientShaderBase::Descriptor desc;
brianosmane25d71c2016-09-28 11:27:28 -0700776 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
777 localMatrix);
reed8a21c9f2016-03-08 18:50:00 -0800778 return sk_make_sp<SkLinearGradient>(pts, desc);
rileya@google.com589708b2012-07-26 20:04:23 +0000779}
780
reed8a21c9f2016-03-08 18:50:00 -0800781sk_sp<SkShader> SkGradientShader::MakeRadial(const SkPoint& center, SkScalar radius,
brianosmane25d71c2016-09-28 11:27:28 -0700782 const SkColor colors[],
783 const SkScalar pos[], int colorCount,
784 SkShader::TileMode mode,
785 uint32_t flags,
786 const SkMatrix* localMatrix) {
787 ColorConverter converter(colors, colorCount);
788 return MakeRadial(center, radius, converter.fColors4f.begin(), nullptr, pos, colorCount, mode,
789 flags, localMatrix);
790}
791
792sk_sp<SkShader> SkGradientShader::MakeRadial(const SkPoint& center, SkScalar radius,
793 const SkColor4f colors[],
794 sk_sp<SkColorSpace> colorSpace,
795 const SkScalar pos[], int colorCount,
796 SkShader::TileMode mode,
797 uint32_t flags,
798 const SkMatrix* localMatrix) {
reed1b747302015-01-06 07:13:19 -0800799 if (radius <= 0) {
halcanary96fcdcc2015-08-27 07:41:13 -0700800 return nullptr;
reed1b747302015-01-06 07:13:19 -0800801 }
802 if (!valid_grad(colors, pos, colorCount, mode)) {
halcanary96fcdcc2015-08-27 07:41:13 -0700803 return nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +0000804 }
fmenozzie9fd0f82016-08-19 07:50:57 -0700805 if (1 == colorCount) {
brianosmane25d71c2016-09-28 11:27:28 -0700806 return SkShader::MakeColorShader(colors[0], std::move(colorSpace));
fmenozzie9fd0f82016-08-19 07:50:57 -0700807 }
Florin Malita8d3ffad2017-02-03 18:21:17 +0000808 if (localMatrix && !localMatrix->invert(nullptr)) {
809 return nullptr;
810 }
rileya@google.com589708b2012-07-26 20:04:23 +0000811
fmenozzi68d952c2016-08-19 08:56:56 -0700812 ColorStopOptimizer opt(colors, pos, colorCount, mode);
813
reed@google.com437d6eb2013-05-23 19:03:05 +0000814 SkGradientShaderBase::Descriptor desc;
brianosmane25d71c2016-09-28 11:27:28 -0700815 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
816 localMatrix);
reed8a21c9f2016-03-08 18:50:00 -0800817 return sk_make_sp<SkRadialGradient>(center, radius, desc);
rileya@google.com589708b2012-07-26 20:04:23 +0000818}
819
reed8a21c9f2016-03-08 18:50:00 -0800820sk_sp<SkShader> SkGradientShader::MakeTwoPointConical(const SkPoint& start,
brianosmane25d71c2016-09-28 11:27:28 -0700821 SkScalar startRadius,
822 const SkPoint& end,
823 SkScalar endRadius,
824 const SkColor colors[],
825 const SkScalar pos[],
826 int colorCount,
827 SkShader::TileMode mode,
828 uint32_t flags,
829 const SkMatrix* localMatrix) {
830 ColorConverter converter(colors, colorCount);
831 return MakeTwoPointConical(start, startRadius, end, endRadius, converter.fColors4f.begin(),
832 nullptr, pos, colorCount, mode, flags, localMatrix);
833}
834
835sk_sp<SkShader> SkGradientShader::MakeTwoPointConical(const SkPoint& start,
836 SkScalar startRadius,
837 const SkPoint& end,
838 SkScalar endRadius,
839 const SkColor4f colors[],
840 sk_sp<SkColorSpace> colorSpace,
841 const SkScalar pos[],
842 int colorCount,
843 SkShader::TileMode mode,
844 uint32_t flags,
845 const SkMatrix* localMatrix) {
reed1b747302015-01-06 07:13:19 -0800846 if (startRadius < 0 || endRadius < 0) {
halcanary96fcdcc2015-08-27 07:41:13 -0700847 return nullptr;
reed1b747302015-01-06 07:13:19 -0800848 }
Florin Malita327290f2017-07-07 09:23:16 -0400849 if (SkScalarNearlyZero((start - end).length()) && SkScalarNearlyZero(startRadius)) {
850 // We can treat this gradient as radial, which is faster.
851 return MakeRadial(start, endRadius, colors, std::move(colorSpace), pos, colorCount,
852 mode, flags, localMatrix);
853 }
reed1b747302015-01-06 07:13:19 -0800854 if (!valid_grad(colors, pos, colorCount, mode)) {
halcanary96fcdcc2015-08-27 07:41:13 -0700855 return nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +0000856 }
fmalita5edf82e2016-03-03 06:41:54 -0800857 if (startRadius == endRadius) {
858 if (start == end || startRadius == 0) {
reed8a21c9f2016-03-08 18:50:00 -0800859 return SkShader::MakeEmptyShader();
fmalita5edf82e2016-03-03 06:41:54 -0800860 }
rileya@google.com589708b2012-07-26 20:04:23 +0000861 }
Florin Malita8d3ffad2017-02-03 18:21:17 +0000862 if (localMatrix && !localMatrix->invert(nullptr)) {
863 return nullptr;
864 }
reed6b7a6c72016-08-18 16:13:50 -0700865 EXPAND_1_COLOR(colorCount);
rileya@google.com589708b2012-07-26 20:04:23 +0000866
fmenozzi68d952c2016-08-19 08:56:56 -0700867 ColorStopOptimizer opt(colors, pos, colorCount, mode);
868
reed@google.com437d6eb2013-05-23 19:03:05 +0000869 SkGradientShaderBase::Descriptor desc;
Florin Malita5f379a82017-10-18 16:22:35 -0400870 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
871 localMatrix);
872 return SkTwoPointConicalGradient::Create(start, startRadius, end, endRadius, desc);
rileya@google.com589708b2012-07-26 20:04:23 +0000873}
874
reed8a21c9f2016-03-08 18:50:00 -0800875sk_sp<SkShader> SkGradientShader::MakeSweep(SkScalar cx, SkScalar cy,
brianosmane25d71c2016-09-28 11:27:28 -0700876 const SkColor colors[],
877 const SkScalar pos[],
878 int colorCount,
Florin Malita5a9a9812017-08-01 16:38:08 -0400879 SkShader::TileMode mode,
880 SkScalar startAngle,
881 SkScalar endAngle,
brianosmane25d71c2016-09-28 11:27:28 -0700882 uint32_t flags,
883 const SkMatrix* localMatrix) {
884 ColorConverter converter(colors, colorCount);
Florin Malita5a9a9812017-08-01 16:38:08 -0400885 return MakeSweep(cx, cy, converter.fColors4f.begin(), nullptr, pos, colorCount,
886 mode, startAngle, endAngle, flags, localMatrix);
brianosmane25d71c2016-09-28 11:27:28 -0700887}
888
889sk_sp<SkShader> SkGradientShader::MakeSweep(SkScalar cx, SkScalar cy,
890 const SkColor4f colors[],
891 sk_sp<SkColorSpace> colorSpace,
892 const SkScalar pos[],
893 int colorCount,
Florin Malita5a9a9812017-08-01 16:38:08 -0400894 SkShader::TileMode mode,
895 SkScalar startAngle,
896 SkScalar endAngle,
brianosmane25d71c2016-09-28 11:27:28 -0700897 uint32_t flags,
898 const SkMatrix* localMatrix) {
Florin Malita5a9a9812017-08-01 16:38:08 -0400899 if (!valid_grad(colors, pos, colorCount, mode)) {
halcanary96fcdcc2015-08-27 07:41:13 -0700900 return nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +0000901 }
fmenozzie9fd0f82016-08-19 07:50:57 -0700902 if (1 == colorCount) {
brianosmane25d71c2016-09-28 11:27:28 -0700903 return SkShader::MakeColorShader(colors[0], std::move(colorSpace));
fmenozzie9fd0f82016-08-19 07:50:57 -0700904 }
Florin Malita5a9a9812017-08-01 16:38:08 -0400905 if (startAngle >= endAngle) {
906 return nullptr;
907 }
Florin Malita8d3ffad2017-02-03 18:21:17 +0000908 if (localMatrix && !localMatrix->invert(nullptr)) {
909 return nullptr;
910 }
rileya@google.com589708b2012-07-26 20:04:23 +0000911
Florin Malita5a9a9812017-08-01 16:38:08 -0400912 if (startAngle <= 0 && endAngle >= 360) {
913 // If the t-range includes [0,1], then we can always use clamping (presumably faster).
914 mode = SkShader::kClamp_TileMode;
915 }
fmenozzi68d952c2016-08-19 08:56:56 -0700916
917 ColorStopOptimizer opt(colors, pos, colorCount, mode);
918
reed@google.com437d6eb2013-05-23 19:03:05 +0000919 SkGradientShaderBase::Descriptor desc;
brianosmane25d71c2016-09-28 11:27:28 -0700920 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
921 localMatrix);
Florin Malita5a9a9812017-08-01 16:38:08 -0400922
923 const SkScalar t0 = startAngle / 360,
924 t1 = endAngle / 360;
925
926 return sk_make_sp<SkSweepGradient>(SkPoint::Make(cx, cy), t0, t1, desc);
rileya@google.com589708b2012-07-26 20:04:23 +0000927}
928
929SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_START(SkGradientShader)
930 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkLinearGradient)
931 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkRadialGradient)
932 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkSweepGradient)
rileya@google.com589708b2012-07-26 20:04:23 +0000933 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkTwoPointConicalGradient)
934SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_END
rileya@google.comd7cc6512012-07-27 14:00:39 +0000935
936///////////////////////////////////////////////////////////////////////////////
937
bsalomon@google.comcf8fb1f2012-08-02 14:03:32 +0000938#if SK_SUPPORT_GPU
939
Brian Osman5911a7c2017-10-25 12:52:31 -0400940#include "GrColorSpaceXform.h"
brianosmana6359362016-03-21 06:55:37 -0700941#include "GrContext.h"
Brian Salomon94efbf52016-11-29 13:43:05 -0500942#include "GrShaderCaps.h"
ajuma95243eb2016-08-24 08:19:02 -0700943#include "GrTextureStripAtlas.h"
egdanielf5294392015-10-21 07:14:17 -0700944#include "gl/GrGLContext.h"
egdaniel2d721d32015-11-11 13:06:05 -0800945#include "glsl/GrGLSLFragmentShaderBuilder.h"
egdaniel018fb622015-10-28 07:26:40 -0700946#include "glsl/GrGLSLProgramDataManager.h"
egdaniel7ea439b2015-12-03 09:20:44 -0800947#include "glsl/GrGLSLUniformHandler.h"
bsalomon@google.comcf8fb1f2012-08-02 14:03:32 +0000948#include "SkGr.h"
949
fmenozzi55d318d2016-08-09 08:05:57 -0700950void GrGradientEffect::GLSLProcessor::emitUniforms(GrGLSLUniformHandler* uniformHandler,
951 const GrGradientEffect& ge) {
Florin Malita14a8dd72017-11-08 15:46:42 -0500952 switch (ge.fStrategy) {
953 case GrGradientEffect::InterpolationStrategy::kThreshold:
954 case GrGradientEffect::InterpolationStrategy::kThresholdClamp0:
955 case GrGradientEffect::InterpolationStrategy::kThresholdClamp1:
956 fThresholdUni = uniformHandler->addUniform(kFragment_GrShaderFlag,
957 kFloat_GrSLType,
958 kHigh_GrSLPrecision,
959 "Threshold");
960 // fall through
961 case GrGradientEffect::InterpolationStrategy::kSingle:
962 fIntervalsUni = uniformHandler->addUniformArray(kFragment_GrShaderFlag,
963 kHalf4_GrSLType,
964 "Intervals",
965 ge.fIntervals.count());
966 break;
967 case GrGradientEffect::InterpolationStrategy::kTexture:
968 fFSYUni = uniformHandler->addUniform(kFragment_GrShaderFlag, kHalf_GrSLType,
969 "GradientYCoordFS");
970 break;
bsalomon@google.com82d12232013-09-09 15:36:26 +0000971 }
972}
973
fmenozzi55d318d2016-08-09 08:05:57 -0700974void GrGradientEffect::GLSLProcessor::onSetData(const GrGLSLProgramDataManager& pdman,
Brian Salomonab015ef2017-04-04 10:15:51 -0400975 const GrFragmentProcessor& processor) {
joshualittb0a8a372014-09-23 09:50:21 -0700976 const GrGradientEffect& e = processor.cast<GrGradientEffect>();
bsalomon@google.com82d12232013-09-09 15:36:26 +0000977
Florin Malita14a8dd72017-11-08 15:46:42 -0500978 switch (e.fStrategy) {
979 case GrGradientEffect::InterpolationStrategy::kThreshold:
980 case GrGradientEffect::InterpolationStrategy::kThresholdClamp0:
981 case GrGradientEffect::InterpolationStrategy::kThresholdClamp1:
982 pdman.set1f(fThresholdUni, e.fThreshold);
Brian Salomon466ad992016-10-13 16:08:36 -0400983 // fall through
Florin Malita14a8dd72017-11-08 15:46:42 -0500984 case GrGradientEffect::InterpolationStrategy::kSingle:
985 pdman.set4fv(fIntervalsUni, e.fIntervals.count(),
986 reinterpret_cast<const float*>(e.fIntervals.begin()));
fmenozzicd9a1d02016-08-15 07:03:47 -0700987 break;
Florin Malita14a8dd72017-11-08 15:46:42 -0500988 case GrGradientEffect::InterpolationStrategy::kTexture:
989 if (e.fYCoord != fCachedYCoord) {
990 pdman.set1f(fFSYUni, e.fYCoord);
991 fCachedYCoord = e.fYCoord;
fmenozzicd9a1d02016-08-15 07:03:47 -0700992 }
993 break;
rileya@google.comb3e50f22012-08-20 17:43:08 +0000994 }
995}
996
Florin Malitae657dc82017-11-03 08:46:18 -0400997void GrGradientEffect::onGetGLSLProcessorKey(const GrShaderCaps&, GrProcessorKeyBuilder* b) const {
998 b->add32(GLSLProcessor::GenBaseGradientKey(*this));
999}
1000
fmenozzi55d318d2016-08-09 08:05:57 -07001001uint32_t GrGradientEffect::GLSLProcessor::GenBaseGradientKey(const GrProcessor& processor) {
joshualittb0a8a372014-09-23 09:50:21 -07001002 const GrGradientEffect& e = processor.cast<GrGradientEffect>();
skia.committer@gmail.com9a070f22013-09-10 07:01:44 +00001003
Florin Malita14a8dd72017-11-08 15:46:42 -05001004 // Build a key using the following bit allocation:
1005 static constexpr uint32_t kStrategyBits = 3;
1006 static constexpr uint32_t kPremulBits = 1;
1007 SkDEBUGCODE(static constexpr uint32_t kWrapModeBits = 2;)
bsalomon@google.com82d12232013-09-09 15:36:26 +00001008
Florin Malita14a8dd72017-11-08 15:46:42 -05001009 uint32_t key = static_cast<uint32_t>(e.fStrategy);
1010 SkASSERT(key < (1 << kStrategyBits));
1011
1012 // This is already baked into the table for texture gradients,
1013 // and only changes behavior for analytical gradients.
1014 if (e.fStrategy != InterpolationStrategy::kTexture &&
1015 e.fPremulType == GrGradientEffect::kBeforeInterp_PremulType) {
1016 key |= 1 << kStrategyBits;
1017 SkASSERT(key < (1 << (kStrategyBits + kPremulBits)));
bsalomon@google.com82d12232013-09-09 15:36:26 +00001018 }
1019
Florin Malita14a8dd72017-11-08 15:46:42 -05001020 key |= static_cast<uint32_t>(e.fWrapMode) << (kStrategyBits + kPremulBits);
1021 SkASSERT(key < (1 << (kStrategyBits + kPremulBits + kWrapModeBits)));
fmenozzicd9a1d02016-08-15 07:03:47 -07001022
bsalomon@google.com82d12232013-09-09 15:36:26 +00001023 return key;
bsalomon@google.comd8b5fac2012-11-01 17:02:46 +00001024}
1025
Florin Malitab81a8b92017-08-08 12:14:17 -04001026void GrGradientEffect::GLSLProcessor::emitAnalyticalColor(GrGLSLFPFragmentBuilder* fragBuilder,
1027 GrGLSLUniformHandler* uniformHandler,
1028 const GrShaderCaps* shaderCaps,
1029 const GrGradientEffect& ge,
1030 const char* t,
1031 const char* outputColor,
1032 const char* inputColor) {
1033 // First, apply tiling rules.
Brian Salomon2bbdcc42017-09-07 12:36:34 -04001034 switch (ge.fWrapMode) {
1035 case GrSamplerState::WrapMode::kClamp:
Florin Malita14a8dd72017-11-08 15:46:42 -05001036 switch (ge.fStrategy) {
1037 case GrGradientEffect::InterpolationStrategy::kThresholdClamp0:
1038 // allow t > 1, in order to hit the clamp interval (1, inf)
1039 fragBuilder->codeAppendf("half tiled_t = max(%s, 0.0);", t);
1040 break;
1041 case GrGradientEffect::InterpolationStrategy::kThresholdClamp1:
1042 // allow t < 0, in order to hit the clamp interval (-inf, 0)
1043 fragBuilder->codeAppendf("half tiled_t = min(%s, 1.0);", t);
1044 break;
1045 default:
1046 // regular [0, 1] clamping
1047 fragBuilder->codeAppendf("half tiled_t = clamp(%s, 0.0, 1.0);", t);
1048 }
Brian Salomon2bbdcc42017-09-07 12:36:34 -04001049 break;
1050 case GrSamplerState::WrapMode::kRepeat:
Florin Malita14a8dd72017-11-08 15:46:42 -05001051 fragBuilder->codeAppendf("half tiled_t = fract(%s);", t);
Brian Salomon2bbdcc42017-09-07 12:36:34 -04001052 break;
1053 case GrSamplerState::WrapMode::kMirrorRepeat:
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001054 fragBuilder->codeAppendf("half t_1 = %s - 1.0;", t);
Florin Malita14a8dd72017-11-08 15:46:42 -05001055 fragBuilder->codeAppendf("half tiled_t = abs(t_1 - 2.0 * floor(t_1 * 0.5) - 1.0);");
Brian Salomon2bbdcc42017-09-07 12:36:34 -04001056 break;
Florin Malita8a0044f2017-08-07 14:38:22 -04001057 }
Florin Malita8a0044f2017-08-07 14:38:22 -04001058
Florin Malitab81a8b92017-08-08 12:14:17 -04001059 // Calculate the color.
Florin Malita14a8dd72017-11-08 15:46:42 -05001060 const char* intervals = uniformHandler->getUniformCStr(fIntervalsUni);
fmenozzicd9a1d02016-08-15 07:03:47 -07001061
Florin Malita14a8dd72017-11-08 15:46:42 -05001062 switch (ge.fStrategy) {
1063 case GrGradientEffect::InterpolationStrategy::kSingle:
1064 SkASSERT(ge.fIntervals.count() == 2);
1065 fragBuilder->codeAppendf(
1066 "half4 color_scale = %s[0],"
1067 " color_bias = %s[1];"
1068 , intervals, intervals
1069 );
fmenozzicd9a1d02016-08-15 07:03:47 -07001070 break;
Florin Malita14a8dd72017-11-08 15:46:42 -05001071 case GrGradientEffect::InterpolationStrategy::kThreshold:
1072 case GrGradientEffect::InterpolationStrategy::kThresholdClamp0:
1073 case GrGradientEffect::InterpolationStrategy::kThresholdClamp1:
1074 {
1075 SkASSERT(ge.fIntervals.count() == 4);
1076 const char* threshold = uniformHandler->getUniformCStr(fThresholdUni);
1077 fragBuilder->codeAppendf(
1078 "half4 color_scale, color_bias;"
1079 "if (tiled_t < %s) {"
1080 " color_scale = %s[0];"
1081 " color_bias = %s[1];"
1082 "} else {"
1083 " color_scale = %s[2];"
1084 " color_bias = %s[3];"
1085 "}"
1086 , threshold, intervals, intervals, intervals, intervals
1087 );
1088 } break;
Florin Malitab81a8b92017-08-08 12:14:17 -04001089 default:
1090 SkASSERT(false);
fmenozzicd9a1d02016-08-15 07:03:47 -07001091 break;
bsalomon@google.com82d12232013-09-09 15:36:26 +00001092 }
Florin Malitab81a8b92017-08-08 12:14:17 -04001093
Florin Malita14a8dd72017-11-08 15:46:42 -05001094 fragBuilder->codeAppend("half4 colorTemp = tiled_t * color_scale + color_bias;");
1095
Brian Osmanfe3e8582017-10-20 11:27:49 -04001096 // We could skip this step if all colors are known to be opaque. Two considerations:
Florin Malitab81a8b92017-08-08 12:14:17 -04001097 // The gradient SkShader reporting opaque is more restrictive than necessary in the two
1098 // pt case. Make sure the key reflects this optimization (and note that it can use the
Brian Osmanfe3e8582017-10-20 11:27:49 -04001099 // same shader as the kBeforeInterp case).
Florin Malita14a8dd72017-11-08 15:46:42 -05001100 if (ge.fPremulType == GrGradientEffect::kAfterInterp_PremulType) {
Florin Malitab81a8b92017-08-08 12:14:17 -04001101 fragBuilder->codeAppend("colorTemp.rgb *= colorTemp.a;");
1102 }
Brian Osman5911a7c2017-10-25 12:52:31 -04001103
1104 // 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 -04001105 // range. The simplest solution is to always clamp our (premul) value here. We only need to
1106 // clamp RGB, but that causes hangs on the Tegra3 Nexus7. Clamping RGBA avoids the problem.
1107 fragBuilder->codeAppend("colorTemp = clamp(colorTemp, 0, colorTemp.a);");
Florin Malitab81a8b92017-08-08 12:14:17 -04001108
1109 fragBuilder->codeAppendf("%s = %s * colorTemp;", outputColor, inputColor);
1110}
1111
1112void GrGradientEffect::GLSLProcessor::emitColor(GrGLSLFPFragmentBuilder* fragBuilder,
1113 GrGLSLUniformHandler* uniformHandler,
1114 const GrShaderCaps* shaderCaps,
1115 const GrGradientEffect& ge,
1116 const char* gradientTValue,
1117 const char* outputColor,
1118 const char* inputColor,
1119 const TextureSamplers& texSamplers) {
Florin Malita14a8dd72017-11-08 15:46:42 -05001120 if (ge.fStrategy != InterpolationStrategy::kTexture) {
Florin Malitab81a8b92017-08-08 12:14:17 -04001121 this->emitAnalyticalColor(fragBuilder, uniformHandler, shaderCaps, ge, gradientTValue,
1122 outputColor, inputColor);
1123 return;
1124 }
1125
Florin Malitab81a8b92017-08-08 12:14:17 -04001126 const char* fsyuni = uniformHandler->getUniformCStr(fFSYUni);
1127
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001128 fragBuilder->codeAppendf("half2 coord = half2(%s, %s);", gradientTValue, fsyuni);
Florin Malitab81a8b92017-08-08 12:14:17 -04001129 fragBuilder->codeAppendf("%s = ", outputColor);
1130 fragBuilder->appendTextureLookupAndModulate(inputColor, texSamplers[0], "coord",
Brian Osman5911a7c2017-10-25 12:52:31 -04001131 kFloat2_GrSLType);
Florin Malitab81a8b92017-08-08 12:14:17 -04001132 fragBuilder->codeAppend(";");
rileya@google.comd7cc6512012-07-27 14:00:39 +00001133}
1134
1135/////////////////////////////////////////////////////////////////////
1136
Brian Salomon587e08f2017-01-27 10:59:27 -05001137inline GrFragmentProcessor::OptimizationFlags GrGradientEffect::OptFlags(bool isOpaque) {
Brian Salomonf3b995b2017-02-15 10:22:23 -05001138 return isOpaque
1139 ? kPreservesOpaqueInput_OptimizationFlag |
1140 kCompatibleWithCoverageAsAlpha_OptimizationFlag
1141 : kCompatibleWithCoverageAsAlpha_OptimizationFlag;
Brian Salomon587e08f2017-01-27 10:59:27 -05001142}
1143
Florin Malita14a8dd72017-11-08 15:46:42 -05001144void GrGradientEffect::addInterval(const SkGradientShaderBase& shader, size_t idx0, size_t idx1,
1145 SkColorSpace* dstCS) {
1146 SkASSERT(idx0 <= idx1);
1147 const auto c4f0 = shader.getXformedColor(idx0, dstCS),
1148 c4f1 = shader.getXformedColor(idx1, dstCS);
1149 const auto c0 = (fPremulType == kBeforeInterp_PremulType)
1150 ? c4f0.premul().to4f() : Sk4f::Load(c4f0.vec()),
1151 c1 = (fPremulType == kBeforeInterp_PremulType)
1152 ? c4f1.premul().to4f() : Sk4f::Load(c4f1.vec());
1153 const auto t0 = shader.getPos(idx0),
1154 t1 = shader.getPos(idx1),
1155 dt = t1 - t0;
1156 SkASSERT(dt >= 0);
1157 // dt can be 0 for clamp intervals => in this case we want a scale == 0
1158 const auto scale = SkScalarNearlyZero(dt) ? 0 : (c1 - c0) / dt,
1159 bias = c0 - t0 * scale;
1160
1161 // Intervals are stored as (scale, bias) tuples.
1162 SkASSERT(!(fIntervals.count() & 1));
1163 fIntervals.emplace_back(scale[0], scale[1], scale[2], scale[3]);
1164 fIntervals.emplace_back( bias[0], bias[1], bias[2], bias[3]);
1165}
1166
Ethan Nicholasabff9562017-10-09 10:54:08 -04001167GrGradientEffect::GrGradientEffect(ClassID classID, const CreateArgs& args, bool isOpaque)
Florin Malita14a8dd72017-11-08 15:46:42 -05001168 : INHERITED(classID, OptFlags(isOpaque))
1169 , fWrapMode(args.fWrapMode)
1170 , fRow(-1)
1171 , fIsOpaque(args.fShader->isOpaque())
1172 , fStrategy(InterpolationStrategy::kTexture)
1173 , fThreshold(0) {
1174
brianosman9557c272016-09-15 06:59:15 -07001175 const SkGradientShaderBase& shader(*args.fShader);
bsalomon@google.com82d12232013-09-09 15:36:26 +00001176
Florin Malita14a8dd72017-11-08 15:46:42 -05001177 fPremulType = (args.fShader->getGradFlags() & SkGradientShader::kInterpolateColorsInPremul_Flag)
1178 ? kBeforeInterp_PremulType : kAfterInterp_PremulType;
bsalomon@google.com371e1052013-01-11 21:08:55 +00001179
Florin Malita14a8dd72017-11-08 15:46:42 -05001180 // First, determine the interpolation strategy and params.
1181 switch (shader.fColorCount) {
1182 case 2:
1183 SkASSERT(!shader.fOrigPos);
1184 fStrategy = InterpolationStrategy::kSingle;
1185 this->addInterval(shader, 0, 1, args.fDstColorSpace);
1186 break;
1187 case 3:
1188 fThreshold = shader.getPos(1);
bsalomon@google.com1ce49fc2012-09-18 14:14:49 +00001189
Florin Malita14a8dd72017-11-08 15:46:42 -05001190 if (shader.fOrigPos) {
1191 SkASSERT(SkScalarNearlyEqual(shader.fOrigPos[0], 0));
1192 SkASSERT(SkScalarNearlyEqual(shader.fOrigPos[2], 1));
1193 if (SkScalarNearlyEqual(shader.fOrigPos[1], 0)) {
1194 // hard stop on the left edge.
1195 if (fWrapMode == GrSamplerState::WrapMode::kClamp) {
1196 fStrategy = InterpolationStrategy::kThresholdClamp1;
1197 // Clamp interval (scale == 0, bias == colors[0]).
1198 this->addInterval(shader, 0, 0, args.fDstColorSpace);
1199 } else {
1200 // We can ignore the hard stop when not clamping.
1201 fStrategy = InterpolationStrategy::kSingle;
1202 }
1203 this->addInterval(shader, 1, 2, args.fDstColorSpace);
1204 break;
1205 }
Brian Osmand43f7b62017-10-19 15:42:01 -04001206
Florin Malita14a8dd72017-11-08 15:46:42 -05001207 if (SkScalarNearlyEqual(shader.fOrigPos[1], 1)) {
1208 // hard stop on the right edge.
1209 this->addInterval(shader, 0, 1, args.fDstColorSpace);
1210 if (fWrapMode == GrSamplerState::WrapMode::kClamp) {
1211 fStrategy = InterpolationStrategy::kThresholdClamp0;
1212 // Clamp interval (scale == 0, bias == colors[2]).
1213 this->addInterval(shader, 2, 2, args.fDstColorSpace);
1214 } else {
1215 // We can ignore the hard stop when not clamping.
1216 fStrategy = InterpolationStrategy::kSingle;
1217 }
1218 break;
1219 }
Brian Osmand43f7b62017-10-19 15:42:01 -04001220 }
1221
Florin Malita14a8dd72017-11-08 15:46:42 -05001222 // Two arbitrary interpolation intervals.
1223 fStrategy = InterpolationStrategy::kThreshold;
1224 this->addInterval(shader, 0, 1, args.fDstColorSpace);
1225 this->addInterval(shader, 1, 2, args.fDstColorSpace);
1226 break;
1227 case 4:
1228 if (shader.fOrigPos && SkScalarNearlyEqual(shader.fOrigPos[1], shader.fOrigPos[2])) {
1229 SkASSERT(SkScalarNearlyEqual(shader.fOrigPos[0], 0));
1230 SkASSERT(SkScalarNearlyEqual(shader.fOrigPos[3], 1));
fmenozzi2a495912016-08-12 06:33:52 -07001231
Florin Malita14a8dd72017-11-08 15:46:42 -05001232 // Single hard stop => two arbitrary interpolation intervals.
1233 fStrategy = InterpolationStrategy::kThreshold;
1234 fThreshold = shader.getPos(1);
1235 this->addInterval(shader, 0, 1, args.fDstColorSpace);
1236 this->addInterval(shader, 2, 3, args.fDstColorSpace);
1237 }
1238 break;
1239 default:
1240 break;
fmenozzi2a495912016-08-12 06:33:52 -07001241 }
fmenozzicd9a1d02016-08-15 07:03:47 -07001242
Florin Malita14a8dd72017-11-08 15:46:42 -05001243 // Now that we've locked down a strategy, adjust any dependent params.
1244 if (fStrategy != InterpolationStrategy::kTexture) {
1245 // Analytical cases.
1246 fCoordTransform.reset(*args.fMatrix);
1247 } else {
1248 SkGradientShaderBase::GradientBitmapType bitmapType =
1249 SkGradientShaderBase::GradientBitmapType::kLegacy;
1250 if (args.fDstColorSpace) {
1251 // Try to use F16 if we can
1252 if (args.fContext->caps()->isConfigTexturable(kRGBA_half_GrPixelConfig)) {
1253 bitmapType = SkGradientShaderBase::GradientBitmapType::kHalfFloat;
1254 } else if (args.fContext->caps()->isConfigTexturable(kSRGBA_8888_GrPixelConfig)) {
1255 bitmapType = SkGradientShaderBase::GradientBitmapType::kSRGB;
fmenozzicd9a1d02016-08-15 07:03:47 -07001256 } else {
Florin Malita14a8dd72017-11-08 15:46:42 -05001257 // This can happen, but only if someone explicitly creates an unsupported
1258 // (eg sRGB) surface. Just fall back to legacy behavior.
fmenozzicd9a1d02016-08-15 07:03:47 -07001259 }
Florin Malita14a8dd72017-11-08 15:46:42 -05001260 }
fmenozzicd9a1d02016-08-15 07:03:47 -07001261
Florin Malita14a8dd72017-11-08 15:46:42 -05001262 SkBitmap bitmap;
1263 shader.getGradientTableBitmap(&bitmap, bitmapType);
1264 SkASSERT(1 == bitmap.height() && SkIsPow2(bitmap.width()));
fmenozzicd9a1d02016-08-15 07:03:47 -07001265
Florin Malita14a8dd72017-11-08 15:46:42 -05001266
1267 GrTextureStripAtlas::Desc desc;
1268 desc.fWidth = bitmap.width();
1269 desc.fHeight = 32;
1270 desc.fRowHeight = bitmap.height();
1271 desc.fContext = args.fContext;
1272 desc.fConfig = SkImageInfo2GrPixelConfig(bitmap.info(), *args.fContext->caps());
1273 fAtlas = GrTextureStripAtlas::GetAtlas(desc);
1274 SkASSERT(fAtlas);
1275
1276 // We always filter the gradient table. Each table is one row of a texture, always
1277 // y-clamp.
1278 GrSamplerState samplerState(args.fWrapMode, GrSamplerState::Filter::kBilerp);
1279
1280 fRow = fAtlas->lockRow(bitmap);
1281 if (-1 != fRow) {
1282 fYCoord = fAtlas->getYOffset(fRow)+SK_ScalarHalf*fAtlas->getNormalizedTexelHeight();
1283 // This is 1/2 places where auto-normalization is disabled
1284 fCoordTransform.reset(*args.fMatrix, fAtlas->asTextureProxyRef().get(), false);
1285 fTextureSampler.reset(fAtlas->asTextureProxyRef(), samplerState);
1286 } else {
1287 // In this instance we know the samplerState state is:
1288 // clampY, bilerp
1289 // and the proxy is:
1290 // exact fit, power of two in both dimensions
1291 // Only the x-tileMode is unknown. However, given all the other knowns we know
1292 // that GrMakeCachedBitmapProxy is sufficient (i.e., it won't need to be
1293 // extracted to a subset or mipmapped).
1294 sk_sp<GrTextureProxy> proxy = GrMakeCachedBitmapProxy(
1295 args.fContext->resourceProvider(),
1296 bitmap);
1297 if (!proxy) {
1298 SkDebugf("Gradient won't draw. Could not create texture.");
1299 return;
1300 }
1301 // This is 2/2 places where auto-normalization is disabled
1302 fCoordTransform.reset(*args.fMatrix, proxy.get(), false);
1303 fTextureSampler.reset(std::move(proxy), samplerState);
1304 fYCoord = SK_ScalarHalf;
1305 }
1306
1307 this->addTextureSampler(&fTextureSampler);
fmenozzicd9a1d02016-08-15 07:03:47 -07001308 }
1309
bsalomon@google.com77af6802013-10-02 13:04:56 +00001310 this->addCoordTransform(&fCoordTransform);
rileya@google.comd7cc6512012-07-27 14:00:39 +00001311}
1312
Brian Salomonf8480b92017-07-27 15:45:59 -04001313GrGradientEffect::GrGradientEffect(const GrGradientEffect& that)
Ethan Nicholasabff9562017-10-09 10:54:08 -04001314 : INHERITED(that.classID(), OptFlags(that.fIsOpaque))
Florin Malita14a8dd72017-11-08 15:46:42 -05001315 , fIntervals(that.fIntervals)
Brian Salomon2bbdcc42017-09-07 12:36:34 -04001316 , fWrapMode(that.fWrapMode)
Brian Salomonf8480b92017-07-27 15:45:59 -04001317 , fCoordTransform(that.fCoordTransform)
1318 , fTextureSampler(that.fTextureSampler)
1319 , fYCoord(that.fYCoord)
1320 , fAtlas(that.fAtlas)
1321 , fRow(that.fRow)
1322 , fIsOpaque(that.fIsOpaque)
Florin Malita14a8dd72017-11-08 15:46:42 -05001323 , fStrategy(that.fStrategy)
1324 , fThreshold(that.fThreshold)
Brian Salomonf8480b92017-07-27 15:45:59 -04001325 , fPremulType(that.fPremulType) {
1326 this->addCoordTransform(&fCoordTransform);
Florin Malita14a8dd72017-11-08 15:46:42 -05001327 if (fStrategy == InterpolationStrategy::kTexture) {
Brian Salomonf8480b92017-07-27 15:45:59 -04001328 this->addTextureSampler(&fTextureSampler);
1329 }
1330 if (this->useAtlas()) {
1331 fAtlas->lockRow(fRow);
1332 }
1333}
1334
rileya@google.comd7cc6512012-07-27 14:00:39 +00001335GrGradientEffect::~GrGradientEffect() {
rileya@google.comb3e50f22012-08-20 17:43:08 +00001336 if (this->useAtlas()) {
1337 fAtlas->unlockRow(fRow);
rileya@google.comb3e50f22012-08-20 17:43:08 +00001338 }
rileya@google.comd7cc6512012-07-27 14:00:39 +00001339}
1340
bsalomon0e08fc12014-10-15 08:19:04 -07001341bool GrGradientEffect::onIsEqual(const GrFragmentProcessor& processor) const {
fmenozzicd9a1d02016-08-15 07:03:47 -07001342 const GrGradientEffect& ge = processor.cast<GrGradientEffect>();
bsalomon@google.com82d12232013-09-09 15:36:26 +00001343
Florin Malita14a8dd72017-11-08 15:46:42 -05001344 if (fWrapMode != ge.fWrapMode || fStrategy != ge.fStrategy) {
Brian Salomon466ad992016-10-13 16:08:36 -04001345 return false;
1346 }
Florin Malita14a8dd72017-11-08 15:46:42 -05001347
Brian Salomon466ad992016-10-13 16:08:36 -04001348 SkASSERT(this->useAtlas() == ge.useAtlas());
Florin Malita14a8dd72017-11-08 15:46:42 -05001349 if (fStrategy == InterpolationStrategy::kTexture) {
1350 if (fYCoord != ge.fYCoord) {
Brian Salomon466ad992016-10-13 16:08:36 -04001351 return false;
1352 }
1353 } else {
Florin Malita14a8dd72017-11-08 15:46:42 -05001354 if (fThreshold != ge.fThreshold ||
1355 fIntervals != ge.fIntervals ||
1356 fPremulType != ge.fPremulType) {
Brian Salomon466ad992016-10-13 16:08:36 -04001357 return false;
1358 }
bsalomon@google.com82d12232013-09-09 15:36:26 +00001359 }
Brian Osman5911a7c2017-10-25 12:52:31 -04001360 return true;
bsalomon@google.com68b58c92013-01-17 16:50:08 +00001361}
1362
Hal Canary6f6961e2017-01-31 13:50:44 -05001363#if GR_TEST_UTILS
Brian Osman3f748602016-10-03 18:29:03 -04001364GrGradientEffect::RandomGradientParams::RandomGradientParams(SkRandom* random) {
Brian Salomon5d4cd9e2017-02-09 11:16:46 -05001365 // Set color count to min of 2 so that we don't trigger the const color optimization and make
1366 // a non-gradient processor.
1367 fColorCount = random->nextRangeU(2, kMaxRandomGradientColors);
Brian Osmana2196532016-10-17 12:48:13 -04001368 fUseColors4f = random->nextBool();
bsalomon@google.comd4726202012-08-03 14:34:46 +00001369
1370 // if one color, omit stops, otherwise randomly decide whether or not to
Brian Osman3f748602016-10-03 18:29:03 -04001371 if (fColorCount == 1 || (fColorCount >= 2 && random->nextBool())) {
1372 fStops = nullptr;
1373 } else {
1374 fStops = fStopStorage;
bsalomon@google.comd4726202012-08-03 14:34:46 +00001375 }
1376
Brian Osmana2196532016-10-17 12:48:13 -04001377 // if using SkColor4f, attach a random (possibly null) color space (with linear gamma)
1378 if (fUseColors4f) {
1379 fColorSpace = GrTest::TestColorSpace(random);
1380 if (fColorSpace) {
raftias94888332016-10-18 10:02:51 -07001381 SkASSERT(SkColorSpace_Base::Type::kXYZ == as_CSB(fColorSpace)->type());
1382 fColorSpace = static_cast<SkColorSpace_XYZ*>(fColorSpace.get())->makeLinearGamma();
Brian Osmana2196532016-10-17 12:48:13 -04001383 }
1384 }
1385
bsalomon@google.com81712882012-11-01 17:12:34 +00001386 SkScalar stop = 0.f;
Brian Osman3f748602016-10-03 18:29:03 -04001387 for (int i = 0; i < fColorCount; ++i) {
Brian Osmana2196532016-10-17 12:48:13 -04001388 if (fUseColors4f) {
1389 fColors4f[i].fR = random->nextUScalar1();
1390 fColors4f[i].fG = random->nextUScalar1();
1391 fColors4f[i].fB = random->nextUScalar1();
1392 fColors4f[i].fA = random->nextUScalar1();
1393 } else {
1394 fColors[i] = random->nextU();
1395 }
Brian Osman3f748602016-10-03 18:29:03 -04001396 if (fStops) {
1397 fStops[i] = stop;
1398 stop = i < fColorCount - 1 ? stop + random->nextUScalar1() * (1.f - stop) : 1.f;
bsalomon@google.comd4726202012-08-03 14:34:46 +00001399 }
1400 }
Brian Osman3f748602016-10-03 18:29:03 -04001401 fTileMode = static_cast<SkShader::TileMode>(random->nextULessThan(SkShader::kTileModeCount));
bsalomon@google.comd4726202012-08-03 14:34:46 +00001402}
Hal Canary6f6961e2017-01-31 13:50:44 -05001403#endif
bsalomon@google.comd4726202012-08-03 14:34:46 +00001404
bsalomon@google.comcf8fb1f2012-08-02 14:03:32 +00001405#endif