blob: f61bb7c2d462d8040f1c8e27b529a8634dada599 [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"
Florin Malitaf77db112018-05-10 09:52:27 -040020#include "SkSafeMath.h"
Mike Klein02ab8cc2017-05-04 22:41:05 +000021#include "SkSweepGradient.h"
Mike Kleina3771842017-05-04 19:38:48 -040022#include "SkTwoPointConicalGradient.h"
Florin Malitad4e9ec82017-10-25 18:00:26 -040023#include "SkWriteBuffer.h"
Herb Derby4de13042017-05-15 10:49:39 -040024#include "../../jumper/SkJumper.h"
25
rileya@google.com589708b2012-07-26 20:04:23 +000026
brianosmane25d71c2016-09-28 11:27:28 -070027enum GradientSerializationFlags {
28 // Bits 29:31 used for various boolean flags
29 kHasPosition_GSF = 0x80000000,
30 kHasLocalMatrix_GSF = 0x40000000,
31 kHasColorSpace_GSF = 0x20000000,
32
33 // Bits 12:28 unused
34
35 // Bits 8:11 for fTileMode
36 kTileModeShift_GSF = 8,
37 kTileModeMask_GSF = 0xF,
38
39 // Bits 0:7 for fGradFlags (note that kForce4fContext_PrivateFlag is 0x80)
40 kGradFlagsShift_GSF = 0,
41 kGradFlagsMask_GSF = 0xFF,
42};
43
reed9fa60da2014-08-21 07:59:51 -070044void SkGradientShaderBase::Descriptor::flatten(SkWriteBuffer& buffer) const {
brianosmane25d71c2016-09-28 11:27:28 -070045 uint32_t flags = 0;
reed9fa60da2014-08-21 07:59:51 -070046 if (fPos) {
brianosmane25d71c2016-09-28 11:27:28 -070047 flags |= kHasPosition_GSF;
reed9fa60da2014-08-21 07:59:51 -070048 }
reed9fa60da2014-08-21 07:59:51 -070049 if (fLocalMatrix) {
brianosmane25d71c2016-09-28 11:27:28 -070050 flags |= kHasLocalMatrix_GSF;
51 }
52 sk_sp<SkData> colorSpaceData = fColorSpace ? fColorSpace->serialize() : nullptr;
53 if (colorSpaceData) {
54 flags |= kHasColorSpace_GSF;
55 }
56 SkASSERT(static_cast<uint32_t>(fTileMode) <= kTileModeMask_GSF);
57 flags |= (fTileMode << kTileModeShift_GSF);
58 SkASSERT(fGradFlags <= kGradFlagsMask_GSF);
59 flags |= (fGradFlags << kGradFlagsShift_GSF);
60
61 buffer.writeUInt(flags);
62
63 buffer.writeColor4fArray(fColors, fCount);
64 if (colorSpaceData) {
65 buffer.writeDataAsByteArray(colorSpaceData.get());
66 }
67 if (fPos) {
68 buffer.writeScalarArray(fPos, fCount);
69 }
70 if (fLocalMatrix) {
reed9fa60da2014-08-21 07:59:51 -070071 buffer.writeMatrix(*fLocalMatrix);
reed9fa60da2014-08-21 07:59:51 -070072 }
73}
74
Florin Malitaf77db112018-05-10 09:52:27 -040075template <int N, typename T, bool MEM_MOVE>
76static bool validate_array(SkReadBuffer& buffer, size_t count, SkSTArray<N, T, MEM_MOVE>* array) {
77 SkSafeMath safe;
78 const auto expectedSize = safe.mul(sizeof(T), count);
79
80 if (!buffer.validate(safe && expectedSize <= buffer.available())) {
81 return false;
82 }
83
84 array->resize_back(count);
85 return true;
86}
87
reed9fa60da2014-08-21 07:59:51 -070088bool SkGradientShaderBase::DescriptorScope::unflatten(SkReadBuffer& buffer) {
Mike Reed70bc94f2017-06-08 12:45:52 -040089 // New gradient format. Includes floating point color, color space, densely packed flags
90 uint32_t flags = buffer.readUInt();
reed9fa60da2014-08-21 07:59:51 -070091
Mike Reed70bc94f2017-06-08 12:45:52 -040092 fTileMode = (SkShader::TileMode)((flags >> kTileModeShift_GSF) & kTileModeMask_GSF);
93 fGradFlags = (flags >> kGradFlagsShift_GSF) & kGradFlagsMask_GSF;
reed9fa60da2014-08-21 07:59:51 -070094
Mike Reed70bc94f2017-06-08 12:45:52 -040095 fCount = buffer.getArrayCount();
Florin Malitaf77db112018-05-10 09:52:27 -040096
97 if (!(validate_array(buffer, fCount, &fColorStorage) &&
98 buffer.readColor4fArray(fColorStorage.begin(), fCount))) {
Mike Reed70bc94f2017-06-08 12:45:52 -040099 return false;
100 }
Florin Malitaf77db112018-05-10 09:52:27 -0400101 fColors = fColorStorage.begin();
102
Mike Reed70bc94f2017-06-08 12:45:52 -0400103 if (SkToBool(flags & kHasColorSpace_GSF)) {
104 sk_sp<SkData> data = buffer.readByteArrayAsData();
105 fColorSpace = SkColorSpace::Deserialize(data->data(), data->size());
106 } else {
brianosmane25d71c2016-09-28 11:27:28 -0700107 fColorSpace = nullptr;
Mike Reed70bc94f2017-06-08 12:45:52 -0400108 }
109 if (SkToBool(flags & kHasPosition_GSF)) {
Florin Malitaf77db112018-05-10 09:52:27 -0400110 if (!(validate_array(buffer, fCount, &fPosStorage) &&
111 buffer.readScalarArray(fPosStorage.begin(), fCount))) {
Mike Reed70bc94f2017-06-08 12:45:52 -0400112 return false;
brianosmane25d71c2016-09-28 11:27:28 -0700113 }
Florin Malitaf77db112018-05-10 09:52:27 -0400114 fPos = fPosStorage.begin();
reed9fa60da2014-08-21 07:59:51 -0700115 } else {
Mike Reed70bc94f2017-06-08 12:45:52 -0400116 fPos = nullptr;
117 }
118 if (SkToBool(flags & kHasLocalMatrix_GSF)) {
119 fLocalMatrix = &fLocalMatrixStorage;
120 buffer.readMatrix(&fLocalMatrixStorage);
121 } else {
122 fLocalMatrix = nullptr;
reed9fa60da2014-08-21 07:59:51 -0700123 }
124 return buffer.isValid();
125}
126
127////////////////////////////////////////////////////////////////////////////////////////////
128
mtkleincc695fe2014-12-10 10:29:19 -0800129SkGradientShaderBase::SkGradientShaderBase(const Descriptor& desc, const SkMatrix& ptsToUnit)
reedaddf2ed2014-08-11 08:28:24 -0700130 : INHERITED(desc.fLocalMatrix)
mtkleincc695fe2014-12-10 10:29:19 -0800131 , fPtsToUnit(ptsToUnit)
Florin Malitaabc85752018-04-25 22:18:37 -0400132 , fColorSpace(desc.fColorSpace ? desc.fColorSpace : SkColorSpace::MakeSRGBLinear())
Florin Malita39d71de2017-10-31 11:33:49 -0400133 , fColorsAreOpaque(true)
commit-bot@chromium.org9c9005a2014-04-28 14:55:39 +0000134{
mtkleincc695fe2014-12-10 10:29:19 -0800135 fPtsToUnit.getType(); // Precache so reads are threadsafe.
reed@google.com437d6eb2013-05-23 19:03:05 +0000136 SkASSERT(desc.fCount > 1);
rileya@google.com589708b2012-07-26 20:04:23 +0000137
fmalita6d7e4e82016-09-20 06:55:16 -0700138 fGradFlags = static_cast<uint8_t>(desc.fGradFlags);
rileya@google.com589708b2012-07-26 20:04:23 +0000139
reed@google.com437d6eb2013-05-23 19:03:05 +0000140 SkASSERT((unsigned)desc.fTileMode < SkShader::kTileModeCount);
reed@google.com437d6eb2013-05-23 19:03:05 +0000141 fTileMode = desc.fTileMode;
rileya@google.com589708b2012-07-26 20:04:23 +0000142
rileya@google.com589708b2012-07-26 20:04:23 +0000143 /* Note: we let the caller skip the first and/or last position.
144 i.e. pos[0] = 0.3, pos[1] = 0.7
145 In these cases, we insert dummy entries to ensure that the final data
146 will be bracketed by [0, 1].
147 i.e. our_pos[0] = 0, our_pos[1] = 0.3, our_pos[2] = 0.7, our_pos[3] = 1
148
149 Thus colorCount (the caller's value, and fColorCount (our value) may
150 differ by up to 2. In the above example:
151 colorCount = 2
152 fColorCount = 4
153 */
reed@google.com437d6eb2013-05-23 19:03:05 +0000154 fColorCount = desc.fCount;
rileya@google.com589708b2012-07-26 20:04:23 +0000155 // check if we need to add in dummy start and/or end position/colors
156 bool dummyFirst = false;
157 bool dummyLast = false;
reed@google.com437d6eb2013-05-23 19:03:05 +0000158 if (desc.fPos) {
159 dummyFirst = desc.fPos[0] != 0;
160 dummyLast = desc.fPos[desc.fCount - 1] != SK_Scalar1;
rileya@google.com589708b2012-07-26 20:04:23 +0000161 fColorCount += dummyFirst + dummyLast;
162 }
163
Mike Reed62ce2ca2018-02-19 14:20:15 -0500164 size_t storageSize = fColorCount * (sizeof(SkColor4f) + (desc.fPos ? sizeof(SkScalar) : 0));
Florin Malita89ab2402017-11-01 10:14:57 -0400165 fOrigColors4f = reinterpret_cast<SkColor4f*>(fStorage.reset(storageSize));
Mike Reed62ce2ca2018-02-19 14:20:15 -0500166 fOrigPos = desc.fPos ? reinterpret_cast<SkScalar*>(fOrigColors4f + fColorCount)
167 : nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +0000168
brianosmane25d71c2016-09-28 11:27:28 -0700169 // Now copy over the colors, adding the dummies as needed
170 SkColor4f* origColors = fOrigColors4f;
171 if (dummyFirst) {
172 *origColors++ = desc.fColors[0];
173 }
Florin Malita39d71de2017-10-31 11:33:49 -0400174 for (int i = 0; i < desc.fCount; ++i) {
Mike Reed62ce2ca2018-02-19 14:20:15 -0500175 origColors[i] = desc.fColors[i];
Florin Malita39d71de2017-10-31 11:33:49 -0400176 fColorsAreOpaque = fColorsAreOpaque && (desc.fColors[i].fA == 1);
177 }
brianosmane25d71c2016-09-28 11:27:28 -0700178 if (dummyLast) {
Mike Reed62ce2ca2018-02-19 14:20:15 -0500179 origColors += desc.fCount;
180 *origColors = desc.fColors[desc.fCount - 1];
brianosmane25d71c2016-09-28 11:27:28 -0700181 }
brianosmanb9c51372016-09-15 11:09:45 -0700182
Florin Malita89ab2402017-11-01 10:14:57 -0400183 if (desc.fPos) {
Florin Malita64bb78e2017-11-03 12:54:07 -0400184 SkScalar prev = 0;
Mike Reed62ce2ca2018-02-19 14:20:15 -0500185 SkScalar* origPosPtr = fOrigPos;
Florin Malita64bb78e2017-11-03 12:54:07 -0400186 *origPosPtr++ = prev; // force the first pos to 0
reed9fa60da2014-08-21 07:59:51 -0700187
Florin Malita89ab2402017-11-01 10:14:57 -0400188 int startIndex = dummyFirst ? 0 : 1;
189 int count = desc.fCount + dummyLast;
Florin Malita64bb78e2017-11-03 12:54:07 -0400190
191 bool uniformStops = true;
192 const SkScalar uniformStep = desc.fPos[startIndex] - prev;
Florin Malita89ab2402017-11-01 10:14:57 -0400193 for (int i = startIndex; i < count; i++) {
Florin Malita3e20d022017-11-03 12:11:38 -0400194 // Pin the last value to 1.0, and make sure pos is monotonic.
Florin Malita64bb78e2017-11-03 12:54:07 -0400195 auto curr = (i == desc.fCount) ? 1 : SkScalarPin(desc.fPos[i], prev, 1);
196 uniformStops &= SkScalarNearlyEqual(uniformStep, curr - prev);
197
198 *origPosPtr++ = prev = curr;
reed9fa60da2014-08-21 07:59:51 -0700199 }
Florin Malita64bb78e2017-11-03 12:54:07 -0400200
Florin Malita64bb78e2017-11-03 12:54:07 -0400201 // If the stops are uniform, treat them as implicit.
Mike Reed62ce2ca2018-02-19 14:20:15 -0500202 if (uniformStops) {
Florin Malita64bb78e2017-11-03 12:54:07 -0400203 fOrigPos = nullptr;
204 }
rileya@google.com589708b2012-07-26 20:04:23 +0000205 }
rileya@google.com589708b2012-07-26 20:04:23 +0000206}
207
Florin Malita89ab2402017-11-01 10:14:57 -0400208SkGradientShaderBase::~SkGradientShaderBase() {}
rileya@google.com589708b2012-07-26 20:04:23 +0000209
commit-bot@chromium.org8b0e8ac2014-01-30 18:58:24 +0000210void SkGradientShaderBase::flatten(SkWriteBuffer& buffer) const {
reed9fa60da2014-08-21 07:59:51 -0700211 Descriptor desc;
brianosmane25d71c2016-09-28 11:27:28 -0700212 desc.fColors = fOrigColors4f;
brianosmanb9c51372016-09-15 11:09:45 -0700213 desc.fColorSpace = fColorSpace;
reed9fa60da2014-08-21 07:59:51 -0700214 desc.fPos = fOrigPos;
215 desc.fCount = fColorCount;
216 desc.fTileMode = fTileMode;
217 desc.fGradFlags = fGradFlags;
218
219 const SkMatrix& m = this->getLocalMatrix();
halcanary96fcdcc2015-08-27 07:41:13 -0700220 desc.fLocalMatrix = m.isIdentity() ? nullptr : &m;
reed9fa60da2014-08-21 07:59:51 -0700221 desc.flatten(buffer);
rileya@google.com589708b2012-07-26 20:04:23 +0000222}
223
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400224static void add_stop_color(SkJumper_GradientCtx* ctx, size_t stop, SkPM4f Fs, SkPM4f Bs) {
225 (ctx->fs[0])[stop] = Fs.r();
226 (ctx->fs[1])[stop] = Fs.g();
227 (ctx->fs[2])[stop] = Fs.b();
228 (ctx->fs[3])[stop] = Fs.a();
229 (ctx->bs[0])[stop] = Bs.r();
230 (ctx->bs[1])[stop] = Bs.g();
231 (ctx->bs[2])[stop] = Bs.b();
232 (ctx->bs[3])[stop] = Bs.a();
Mike Kleinf945cbb2017-05-17 09:30:58 -0400233}
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400234
235static void add_const_color(SkJumper_GradientCtx* ctx, size_t stop, SkPM4f color) {
236 add_stop_color(ctx, stop, SkPM4f::FromPremulRGBA(0,0,0,0), color);
Mike Kleinf945cbb2017-05-17 09:30:58 -0400237}
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400238
239// Calculate a factor F and a bias B so that color = F*t + B when t is in range of
240// the stop. Assume that the distance between stops is 1/gapCount.
241static void init_stop_evenly(
242 SkJumper_GradientCtx* ctx, float gapCount, size_t stop, SkPM4f c_l, SkPM4f c_r) {
Mike Klein68768172017-05-17 09:54:36 -0400243 // Clankium's GCC 4.9 targeting ARMv7 is barfing when we use Sk4f math here, so go scalar...
244 SkPM4f Fs = {{
245 (c_r.r() - c_l.r()) * gapCount,
246 (c_r.g() - c_l.g()) * gapCount,
247 (c_r.b() - c_l.b()) * gapCount,
248 (c_r.a() - c_l.a()) * gapCount,
249 }};
250 SkPM4f Bs = {{
251 c_l.r() - Fs.r()*(stop/gapCount),
252 c_l.g() - Fs.g()*(stop/gapCount),
253 c_l.b() - Fs.b()*(stop/gapCount),
254 c_l.a() - Fs.a()*(stop/gapCount),
255 }};
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400256 add_stop_color(ctx, stop, Fs, Bs);
Mike Kleinf945cbb2017-05-17 09:30:58 -0400257}
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400258
259// For each stop we calculate a bias B and a scale factor F, such that
260// for any t between stops n and n+1, the color we want is B[n] + F[n]*t.
261static void init_stop_pos(
262 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 -0400263 // See note about Clankium's old compiler in init_stop_evenly().
264 SkPM4f Fs = {{
265 (c_r.r() - c_l.r()) / (t_r - t_l),
266 (c_r.g() - c_l.g()) / (t_r - t_l),
267 (c_r.b() - c_l.b()) / (t_r - t_l),
268 (c_r.a() - c_l.a()) / (t_r - t_l),
269 }};
270 SkPM4f Bs = {{
271 c_l.r() - Fs.r()*t_l,
272 c_l.g() - Fs.g()*t_l,
273 c_l.b() - Fs.b()*t_l,
274 c_l.a() - Fs.a()*t_l,
275 }};
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400276 ctx->ts[stop] = t_l;
277 add_stop_color(ctx, stop, Fs, Bs);
Mike Kleinf945cbb2017-05-17 09:30:58 -0400278}
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400279
Mike Reed1d8c42e2017-08-29 14:58:19 -0400280bool SkGradientShaderBase::onAppendStages(const StageRec& rec) const {
281 SkRasterPipeline* p = rec.fPipeline;
282 SkArenaAlloc* alloc = rec.fAlloc;
283 SkColorSpace* dstCS = rec.fDstCS;
Mike Reed62ce2ca2018-02-19 14:20:15 -0500284 SkJumper_DecalTileCtx* decal_ctx = nullptr;
Mike Reed1d8c42e2017-08-29 14:58:19 -0400285
Mike Kleina3771842017-05-04 19:38:48 -0400286 SkMatrix matrix;
Mike Reed1d8c42e2017-08-29 14:58:19 -0400287 if (!this->computeTotalInverse(rec.fCTM, rec.fLocalM, &matrix)) {
Mike Kleina3771842017-05-04 19:38:48 -0400288 return false;
289 }
Florin Malita50b20842017-07-29 19:08:28 -0400290 matrix.postConcat(fPtsToUnit);
Mike Kleina3771842017-05-04 19:38:48 -0400291
Florin Malita2e409002017-06-28 14:46:54 -0400292 SkRasterPipeline_<256> postPipeline;
Mike Kleina3771842017-05-04 19:38:48 -0400293
Mike Kleine8de0242018-03-10 12:37:11 -0500294 p->append(SkRasterPipeline::seed_shader);
Mike Reed6b59bf42017-07-03 21:26:44 -0400295 p->append_matrix(alloc, matrix);
Florin Malita50b20842017-07-29 19:08:28 -0400296 this->appendGradientStages(alloc, p, &postPipeline);
Mike Kleine7598532017-05-11 11:29:29 -0400297
Mike Reed62ce2ca2018-02-19 14:20:15 -0500298 switch(fTileMode) {
Mike Klein9f85d682017-05-23 07:52:01 -0400299 case kMirror_TileMode: p->append(SkRasterPipeline::mirror_x_1); break;
300 case kRepeat_TileMode: p->append(SkRasterPipeline::repeat_x_1); break;
Mike Reeddfc0e912018-02-16 12:40:18 -0500301 case kDecal_TileMode:
Mike Reed62ce2ca2018-02-19 14:20:15 -0500302 decal_ctx = alloc->make<SkJumper_DecalTileCtx>();
303 decal_ctx->limit_x = SkBits2Float(SkFloat2Bits(1.0f) + 1);
304 // reuse mask + limit_x stage, or create a custom decal_1 that just stores the mask
305 p->append(SkRasterPipeline::decal_x, decal_ctx);
306 // fall-through to clamp
Mike Kleine7598532017-05-11 11:29:29 -0400307 case kClamp_TileMode:
308 if (!fOrigPos) {
309 // We clamp only when the stops are evenly spaced.
310 // If not, there may be hard stops, and clamping ruins hard stops at 0 and/or 1.
Mike Klein5c7960b2017-05-11 10:59:22 -0400311 // In that case, we must make sure we're using the general "gradient" stage,
Mike Kleine7598532017-05-11 11:29:29 -0400312 // which is the only stage that will correctly handle unclamped t.
Mike Klein9f85d682017-05-23 07:52:01 -0400313 p->append(SkRasterPipeline::clamp_x_1);
Mike Kleine7598532017-05-11 11:29:29 -0400314 }
Mike Reed62ce2ca2018-02-19 14:20:15 -0500315 break;
Mike Kleine7598532017-05-11 11:29:29 -0400316 }
Mike Kleina3771842017-05-04 19:38:48 -0400317
318 const bool premulGrad = fGradFlags & SkGradientShader::kInterpolateColorsInPremul_Flag;
319 auto prepareColor = [premulGrad, dstCS, this](int i) {
Florin Malita0e36b3f2017-06-05 23:33:45 -0400320 SkColor4f c = this->getXformedColor(i, dstCS);
Mike Kleina3771842017-05-04 19:38:48 -0400321 return premulGrad ? c.premul()
322 : SkPM4f::From4f(Sk4f::Load(&c));
323 };
324
325 // The two-stop case with stops at 0 and 1.
326 if (fColorCount == 2 && fOrigPos == nullptr) {
327 const SkPM4f c_l = prepareColor(0),
Mike Reed1d8c42e2017-08-29 14:58:19 -0400328 c_r = prepareColor(1);
Mike Kleina3771842017-05-04 19:38:48 -0400329
330 // See F and B below.
331 auto* f_and_b = alloc->makeArrayDefault<SkPM4f>(2);
332 f_and_b[0] = SkPM4f::From4f(c_r.to4f() - c_l.to4f());
333 f_and_b[1] = c_l;
334
Mike Klein5c7960b2017-05-11 10:59:22 -0400335 p->append(SkRasterPipeline::evenly_spaced_2_stop_gradient, f_and_b);
Mike Kleina3771842017-05-04 19:38:48 -0400336 } else {
Herb Derby4de13042017-05-15 10:49:39 -0400337 auto* ctx = alloc->make<SkJumper_GradientCtx>();
Herb Derby4de13042017-05-15 10:49:39 -0400338
339 // Note: In order to handle clamps in search, the search assumes a stop conceptully placed
340 // at -inf. Therefore, the max number of stops is fColorCount+1.
341 for (int i = 0; i < 4; i++) {
342 // Allocate at least at for the AVX2 gather from a YMM register.
343 ctx->fs[i] = alloc->makeArray<float>(std::max(fColorCount+1, 8));
344 ctx->bs[i] = alloc->makeArray<float>(std::max(fColorCount+1, 8));
345 }
346
Mike Kleina3771842017-05-04 19:38:48 -0400347 if (fOrigPos == nullptr) {
348 // Handle evenly distributed stops.
349
Herb Derby4de13042017-05-15 10:49:39 -0400350 size_t stopCount = fColorCount;
351 float gapCount = stopCount - 1;
Mike Kleina3771842017-05-04 19:38:48 -0400352
Herb Derby4de13042017-05-15 10:49:39 -0400353 SkPM4f c_l = prepareColor(0);
354 for (size_t i = 0; i < stopCount - 1; i++) {
Mike Kleina3771842017-05-04 19:38:48 -0400355 SkPM4f c_r = prepareColor(i + 1);
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400356 init_stop_evenly(ctx, gapCount, i, c_l, c_r);
Mike Kleina3771842017-05-04 19:38:48 -0400357 c_l = c_r;
358 }
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400359 add_const_color(ctx, stopCount - 1, c_l);
Mike Kleina3771842017-05-04 19:38:48 -0400360
Herb Derby4de13042017-05-15 10:49:39 -0400361 ctx->stopCount = stopCount;
362 p->append(SkRasterPipeline::evenly_spaced_gradient, ctx);
Mike Kleina3771842017-05-04 19:38:48 -0400363 } else {
364 // Handle arbitrary stops.
365
Herb Derby4de13042017-05-15 10:49:39 -0400366 ctx->ts = alloc->makeArray<float>(fColorCount+1);
367
Mike Kleina3771842017-05-04 19:38:48 -0400368 // Remove the dummy stops inserted by SkGradientShaderBase::SkGradientShaderBase
369 // because they are naturally handled by the search method.
370 int firstStop;
371 int lastStop;
372 if (fColorCount > 2) {
373 firstStop = fOrigColors4f[0] != fOrigColors4f[1] ? 0 : 1;
374 lastStop = fOrigColors4f[fColorCount - 2] != fOrigColors4f[fColorCount - 1]
375 ? fColorCount - 1 : fColorCount - 2;
376 } else {
377 firstStop = 0;
378 lastStop = 1;
379 }
Mike Kleina3771842017-05-04 19:38:48 -0400380
Mike Kleina3771842017-05-04 19:38:48 -0400381 size_t stopCount = 0;
382 float t_l = fOrigPos[firstStop];
383 SkPM4f c_l = prepareColor(firstStop);
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400384 add_const_color(ctx, stopCount++, c_l);
Mike Kleina3771842017-05-04 19:38:48 -0400385 // N.B. lastStop is the index of the last stop, not one after.
386 for (int i = firstStop; i < lastStop; i++) {
387 float t_r = fOrigPos[i + 1];
388 SkPM4f c_r = prepareColor(i + 1);
Florin Malita3e20d022017-11-03 12:11:38 -0400389 SkASSERT(t_l <= t_r);
Mike Kleina3771842017-05-04 19:38:48 -0400390 if (t_l < t_r) {
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400391 init_stop_pos(ctx, stopCount, t_l, t_r, c_l, c_r);
Mike Kleina3771842017-05-04 19:38:48 -0400392 stopCount += 1;
393 }
394 t_l = t_r;
395 c_l = c_r;
396 }
397
Herb Derby4de13042017-05-15 10:49:39 -0400398 ctx->ts[stopCount] = t_l;
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400399 add_const_color(ctx, stopCount++, c_l);
Mike Kleina3771842017-05-04 19:38:48 -0400400
Herb Derby4de13042017-05-15 10:49:39 -0400401 ctx->stopCount = stopCount;
402 p->append(SkRasterPipeline::gradient, ctx);
Mike Kleina3771842017-05-04 19:38:48 -0400403 }
Mike Kleina3771842017-05-04 19:38:48 -0400404 }
405
Mike Reed62ce2ca2018-02-19 14:20:15 -0500406 if (decal_ctx) {
407 p->append(SkRasterPipeline::check_decal_mask, decal_ctx);
408 }
409
Mike Kleina3771842017-05-04 19:38:48 -0400410 if (!premulGrad && !this->colorsAreOpaque()) {
Mike Kleine7598532017-05-11 11:29:29 -0400411 p->append(SkRasterPipeline::premul);
Mike Kleina3771842017-05-04 19:38:48 -0400412 }
413
Florin Malita2e409002017-06-28 14:46:54 -0400414 p->extend(postPipeline);
415
Mike Kleina3771842017-05-04 19:38:48 -0400416 return true;
417}
418
419
rileya@google.com589708b2012-07-26 20:04:23 +0000420bool SkGradientShaderBase::isOpaque() const {
Mike Reed62ce2ca2018-02-19 14:20:15 -0500421 return fColorsAreOpaque && (this->getTileMode() != SkShader::kDecal_TileMode);
422}
423
reed8367b8c2014-08-22 08:30:20 -0700424static unsigned rounded_divide(unsigned numer, unsigned denom) {
425 return (numer + (denom >> 1)) / denom;
426}
427
428bool SkGradientShaderBase::onAsLuminanceColor(SkColor* lum) const {
429 // we just compute an average color.
430 // possibly we could weight this based on the proportional width for each color
431 // assuming they are not evenly distributed in the fPos array.
432 int r = 0;
433 int g = 0;
434 int b = 0;
435 const int n = fColorCount;
Florin Malita39d71de2017-10-31 11:33:49 -0400436 // TODO: use linear colors?
reed8367b8c2014-08-22 08:30:20 -0700437 for (int i = 0; i < n; ++i) {
Florin Malita39d71de2017-10-31 11:33:49 -0400438 SkColor c = this->getLegacyColor(i);
reed8367b8c2014-08-22 08:30:20 -0700439 r += SkColorGetR(c);
440 g += SkColorGetG(c);
441 b += SkColorGetB(c);
442 }
443 *lum = SkColorSetRGB(rounded_divide(r, n), rounded_divide(g, n), rounded_divide(b, n));
444 return true;
445}
446
Florin Malita39d71de2017-10-31 11:33:49 -0400447SkGradientShaderBase::AutoXformColors::AutoXformColors(const SkGradientShaderBase& grad,
448 SkColorSpaceXformer* xformer)
449 : fColors(grad.fColorCount) {
450 // TODO: stay in 4f to preserve precision?
451
452 SkAutoSTMalloc<8, SkColor> origColors(grad.fColorCount);
453 for (int i = 0; i < grad.fColorCount; ++i) {
454 origColors[i] = grad.getLegacyColor(i);
455 }
456
457 xformer->apply(fColors.get(), origColors.get(), grad.fColorCount);
458}
459
Florin Malitad4e9ec82017-10-25 18:00:26 -0400460static constexpr int kGradientTextureSize = 256;
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000461
Florin Malita84d7cf92017-10-25 15:31:54 -0400462void SkGradientShaderBase::initLinearBitmap(SkBitmap* bitmap, GradientBitmapType bitmapType) const {
brianosmand4546092016-09-22 12:31:58 -0700463 const bool interpInPremul = SkToBool(fGradFlags &
464 SkGradientShader::kInterpolateColorsInPremul_Flag);
brianosmand4546092016-09-22 12:31:58 -0700465 SkHalf* pixelsF16 = reinterpret_cast<SkHalf*>(bitmap->getPixels());
Florin Malita84d7cf92017-10-25 15:31:54 -0400466 uint32_t* pixels32 = reinterpret_cast<uint32_t*>(bitmap->getPixels());
brianosmand4546092016-09-22 12:31:58 -0700467
468 typedef std::function<void(const Sk4f&, int)> pixelWriteFn_t;
469
470 pixelWriteFn_t writeF16Pixel = [&](const Sk4f& x, int index) {
471 Sk4h c = SkFloatToHalf_finite_ftz(x);
472 pixelsF16[4*index+0] = c[0];
473 pixelsF16[4*index+1] = c[1];
474 pixelsF16[4*index+2] = c[2];
475 pixelsF16[4*index+3] = c[3];
476 };
477 pixelWriteFn_t writeS32Pixel = [&](const Sk4f& c, int index) {
Florin Malita84d7cf92017-10-25 15:31:54 -0400478 pixels32[index] = Sk4f_toS32(c);
479 };
480 pixelWriteFn_t writeL32Pixel = [&](const Sk4f& c, int index) {
481 pixels32[index] = Sk4f_toL32(c);
brianosmand4546092016-09-22 12:31:58 -0700482 };
483
484 pixelWriteFn_t writeSizedPixel =
Florin Malita84d7cf92017-10-25 15:31:54 -0400485 (bitmapType == GradientBitmapType::kHalfFloat) ? writeF16Pixel :
486 (bitmapType == GradientBitmapType::kSRGB ) ? writeS32Pixel : writeL32Pixel;
brianosmand4546092016-09-22 12:31:58 -0700487 pixelWriteFn_t writeUnpremulPixel = [&](const Sk4f& c, int index) {
488 writeSizedPixel(c * Sk4f(c[3], c[3], c[3], 1.0f), index);
489 };
490
491 pixelWriteFn_t writePixel = interpInPremul ? writeSizedPixel : writeUnpremulPixel;
492
Florin Malita84d7cf92017-10-25 15:31:54 -0400493 // When not in legacy mode, we just want the original 4f colors - so we pass in
494 // our own CS for identity/no transform.
495 auto* cs = bitmapType != GradientBitmapType::kLegacy ? fColorSpace.get() : nullptr;
496
brianosmand4546092016-09-22 12:31:58 -0700497 int prevIndex = 0;
498 for (int i = 1; i < fColorCount; i++) {
Florin Malitaed6ae562017-10-28 11:06:48 -0400499 // Historically, stops have been mapped to [0, 256], with 256 then nudged to the
500 // next smaller value, then truncate for the texture index. This seems to produce
501 // the best results for some common distributions, so we preserve the behavior.
502 int nextIndex = SkTMin(this->getPos(i) * kGradientTextureSize,
503 SkIntToScalar(kGradientTextureSize - 1));
brianosmand4546092016-09-22 12:31:58 -0700504
505 if (nextIndex > prevIndex) {
Florin Malita84d7cf92017-10-25 15:31:54 -0400506 SkColor4f color0 = this->getXformedColor(i - 1, cs),
507 color1 = this->getXformedColor(i , cs);
508 Sk4f c0 = Sk4f::Load(color0.vec()),
509 c1 = Sk4f::Load(color1.vec());
510
brianosmand4546092016-09-22 12:31:58 -0700511 if (interpInPremul) {
512 c0 = c0 * Sk4f(c0[3], c0[3], c0[3], 1.0f);
513 c1 = c1 * Sk4f(c1[3], c1[3], c1[3], 1.0f);
514 }
515
516 Sk4f step = Sk4f(1.0f / static_cast<float>(nextIndex - prevIndex));
517 Sk4f delta = (c1 - c0) * step;
518
519 for (int curIndex = prevIndex; curIndex <= nextIndex; ++curIndex) {
520 writePixel(c0, curIndex);
521 c0 += delta;
522 }
523 }
524 prevIndex = nextIndex;
525 }
Florin Malitad4e9ec82017-10-25 18:00:26 -0400526 SkASSERT(prevIndex == kGradientTextureSize - 1);
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000527}
528
Florin Malita0e36b3f2017-06-05 23:33:45 -0400529SkColor4f SkGradientShaderBase::getXformedColor(size_t i, SkColorSpace* dstCS) const {
Florin Malita79363b62017-11-01 15:43:52 -0400530 if (dstCS) {
531 return to_colorspace(fOrigColors4f[i], fColorSpace.get(), dstCS);
532 }
533
534 // Legacy/srgb color.
Florin Malita79363b62017-11-01 15:43:52 -0400535 // We quantize upfront to ensure stable SkColor round-trips.
536 auto rgb255 = sk_linear_to_srgb(Sk4f::Load(fOrigColors4f[i].vec()));
537 auto rgb = SkNx_cast<float>(rgb255) * (1/255.0f);
538 return { rgb[0], rgb[1], rgb[2], fOrigColors4f[i].fA };
Florin Malita0e36b3f2017-06-05 23:33:45 -0400539}
540
reed086eea92016-05-04 17:12:46 -0700541SK_DECLARE_STATIC_MUTEX(gGradientCacheMutex);
rileya@google.com589708b2012-07-26 20:04:23 +0000542/*
543 * Because our caller might rebuild the same (logically the same) gradient
544 * over and over, we'd like to return exactly the same "bitmap" if possible,
545 * allowing the client to utilize a cache of our bitmap (e.g. with a GPU).
546 * To do that, we maintain a private cache of built-bitmaps, based on our
Brian Osmanfe3e8582017-10-20 11:27:49 -0400547 * colors and positions.
rileya@google.com589708b2012-07-26 20:04:23 +0000548 */
brianosmand4546092016-09-22 12:31:58 -0700549void SkGradientShaderBase::getGradientTableBitmap(SkBitmap* bitmap,
550 GradientBitmapType bitmapType) const {
brianosmand4546092016-09-22 12:31:58 -0700551 // build our key: [numColors + colors[] + {positions[]} + flags + colorType ]
Florin Malita39d71de2017-10-31 11:33:49 -0400552 static_assert(sizeof(SkColor4f) % sizeof(int32_t) == 0, "");
553 const int colorsAsIntCount = fColorCount * sizeof(SkColor4f) / sizeof(int32_t);
554 int count = 1 + colorsAsIntCount + 1 + 1;
rileya@google.com589708b2012-07-26 20:04:23 +0000555 if (fColorCount > 2) {
Florin Malitacad3b8c2017-10-28 21:42:50 -0400556 count += fColorCount - 1;
rileya@google.com589708b2012-07-26 20:04:23 +0000557 }
558
Florin Malita39d71de2017-10-31 11:33:49 -0400559 SkAutoSTMalloc<64, int32_t> storage(count);
rileya@google.com589708b2012-07-26 20:04:23 +0000560 int32_t* buffer = storage.get();
561
562 *buffer++ = fColorCount;
Florin Malita39d71de2017-10-31 11:33:49 -0400563 memcpy(buffer, fOrigColors4f, fColorCount * sizeof(SkColor4f));
564 buffer += colorsAsIntCount;
rileya@google.com589708b2012-07-26 20:04:23 +0000565 if (fColorCount > 2) {
566 for (int i = 1; i < fColorCount; i++) {
Florin Malitacad3b8c2017-10-28 21:42:50 -0400567 *buffer++ = SkFloat2Bits(this->getPos(i));
rileya@google.com589708b2012-07-26 20:04:23 +0000568 }
569 }
reed@google.com3d3a8602013-05-24 14:58:44 +0000570 *buffer++ = fGradFlags;
brianosmand4546092016-09-22 12:31:58 -0700571 *buffer++ = static_cast<int32_t>(bitmapType);
rileya@google.com589708b2012-07-26 20:04:23 +0000572 SkASSERT(buffer - storage.get() == count);
573
574 ///////////////////////////////////
575
reeda6cac4c2014-08-21 10:50:25 -0700576 static SkGradientBitmapCache* gCache;
brianosmand4546092016-09-22 12:31:58 -0700577 // 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 +0000578 static const int MAX_NUM_CACHED_GRADIENT_BITMAPS = 32;
bungemand6aeb6d2014-07-25 11:52:47 -0700579 SkAutoMutexAcquire ama(gGradientCacheMutex);
rileya@google.com589708b2012-07-26 20:04:23 +0000580
halcanary96fcdcc2015-08-27 07:41:13 -0700581 if (nullptr == gCache) {
halcanary385fe4d2015-08-26 13:07:48 -0700582 gCache = new SkGradientBitmapCache(MAX_NUM_CACHED_GRADIENT_BITMAPS);
rileya@google.com589708b2012-07-26 20:04:23 +0000583 }
584 size_t size = count * sizeof(int32_t);
585
586 if (!gCache->find(storage.get(), size, bitmap)) {
Florin Malitad4e9ec82017-10-25 18:00:26 -0400587 // For these cases we use the bitmap cache, but not the GradientShaderCache. So just
588 // allocate and populate the bitmap's data directly.
Florin Malita63376532017-10-24 10:56:52 -0400589
Florin Malitad4e9ec82017-10-25 18:00:26 -0400590 SkImageInfo info;
591 switch (bitmapType) {
592 case GradientBitmapType::kLegacy:
593 info = SkImageInfo::Make(kGradientTextureSize, 1, kRGBA_8888_SkColorType,
594 kPremul_SkAlphaType);
595 break;
596 case GradientBitmapType::kSRGB:
597 info = SkImageInfo::Make(kGradientTextureSize, 1, kRGBA_8888_SkColorType,
598 kPremul_SkAlphaType, SkColorSpace::MakeSRGB());
599 break;
600 case GradientBitmapType::kHalfFloat:
601 info = SkImageInfo::Make(kGradientTextureSize, 1, kRGBA_F16_SkColorType,
602 kPremul_SkAlphaType, SkColorSpace::MakeSRGBLinear());
603 break;
brianosmand4546092016-09-22 12:31:58 -0700604 }
Florin Malitad4e9ec82017-10-25 18:00:26 -0400605
606 bitmap->allocPixels(info);
607 this->initLinearBitmap(bitmap, bitmapType);
Robert Phillips7a926392018-02-01 15:49:54 -0500608 bitmap->setImmutable();
rileya@google.com589708b2012-07-26 20:04:23 +0000609 gCache->add(storage.get(), size, *bitmap);
610 }
611}
612
Florin Malita5f379a82017-10-18 16:22:35 -0400613void SkGradientShaderBase::commonAsAGradient(GradientInfo* info) const {
rileya@google.com589708b2012-07-26 20:04:23 +0000614 if (info) {
615 if (info->fColorCount >= fColorCount) {
616 if (info->fColors) {
Florin Malita39d71de2017-10-31 11:33:49 -0400617 for (int i = 0; i < fColorCount; ++i) {
618 info->fColors[i] = this->getLegacyColor(i);
619 }
rileya@google.com589708b2012-07-26 20:04:23 +0000620 }
621 if (info->fColorOffsets) {
Florin Malitaed6ae562017-10-28 11:06:48 -0400622 for (int i = 0; i < fColorCount; ++i) {
623 info->fColorOffsets[i] = this->getPos(i);
rileya@google.com589708b2012-07-26 20:04:23 +0000624 }
625 }
626 }
627 info->fColorCount = fColorCount;
628 info->fTileMode = fTileMode;
reed@google.com3d3a8602013-05-24 14:58:44 +0000629 info->fGradientFlags = fGradFlags;
rileya@google.com589708b2012-07-26 20:04:23 +0000630 }
631}
632
robertphillips@google.com76f9e932013-01-15 20:17:47 +0000633void SkGradientShaderBase::toString(SkString* str) const {
634
635 str->appendf("%d colors: ", fColorCount);
636
637 for (int i = 0; i < fColorCount; ++i) {
Florin Malita39d71de2017-10-31 11:33:49 -0400638 str->appendHex(this->getLegacyColor(i), 8);
robertphillips@google.com76f9e932013-01-15 20:17:47 +0000639 if (i < fColorCount-1) {
640 str->append(", ");
641 }
642 }
643
644 if (fColorCount > 2) {
645 str->append(" points: (");
646 for (int i = 0; i < fColorCount; ++i) {
Florin Malitaed6ae562017-10-28 11:06:48 -0400647 str->appendScalar(this->getPos(i));
robertphillips@google.com76f9e932013-01-15 20:17:47 +0000648 if (i < fColorCount-1) {
649 str->append(", ");
650 }
651 }
652 str->append(")");
653 }
654
655 static const char* gTileModeName[SkShader::kTileModeCount] = {
Mike Reeddfc0e912018-02-16 12:40:18 -0500656 "clamp", "repeat", "mirror", "decal",
robertphillips@google.com76f9e932013-01-15 20:17:47 +0000657 };
658
659 str->append(" ");
660 str->append(gTileModeName[fTileMode]);
661
robertphillips@google.com76f9e932013-01-15 20:17:47 +0000662 this->INHERITED::toString(str);
663}
robertphillips@google.com76f9e932013-01-15 20:17:47 +0000664
rileya@google.com589708b2012-07-26 20:04:23 +0000665///////////////////////////////////////////////////////////////////////////////
666///////////////////////////////////////////////////////////////////////////////
667
reed1b747302015-01-06 07:13:19 -0800668// Return true if these parameters are valid/legal/safe to construct a gradient
669//
brianosmane25d71c2016-09-28 11:27:28 -0700670static bool valid_grad(const SkColor4f colors[], const SkScalar pos[], int count,
671 unsigned tileMode) {
halcanary96fcdcc2015-08-27 07:41:13 -0700672 return nullptr != colors && count >= 1 && tileMode < (unsigned)SkShader::kTileModeCount;
reed1b747302015-01-06 07:13:19 -0800673}
674
reed@google.com437d6eb2013-05-23 19:03:05 +0000675static void desc_init(SkGradientShaderBase::Descriptor* desc,
brianosmane25d71c2016-09-28 11:27:28 -0700676 const SkColor4f colors[], sk_sp<SkColorSpace> colorSpace,
677 const SkScalar pos[], int colorCount,
reedaddf2ed2014-08-11 08:28:24 -0700678 SkShader::TileMode mode, uint32_t flags, const SkMatrix* localMatrix) {
fmalita748d6202016-05-11 11:39:58 -0700679 SkASSERT(colorCount > 1);
680
commit-bot@chromium.org6c5aea22014-04-22 16:25:15 +0000681 desc->fColors = colors;
brianosmane25d71c2016-09-28 11:27:28 -0700682 desc->fColorSpace = std::move(colorSpace);
commit-bot@chromium.org6c5aea22014-04-22 16:25:15 +0000683 desc->fPos = pos;
684 desc->fCount = colorCount;
685 desc->fTileMode = mode;
commit-bot@chromium.org6c5aea22014-04-22 16:25:15 +0000686 desc->fGradFlags = flags;
reedaddf2ed2014-08-11 08:28:24 -0700687 desc->fLocalMatrix = localMatrix;
reed@google.com437d6eb2013-05-23 19:03:05 +0000688}
689
brianosmane25d71c2016-09-28 11:27:28 -0700690// assumes colors is SkColor4f* and pos is SkScalar*
fmenozzie9fd0f82016-08-19 07:50:57 -0700691#define EXPAND_1_COLOR(count) \
brianosmane25d71c2016-09-28 11:27:28 -0700692 SkColor4f tmp[2]; \
fmenozzie9fd0f82016-08-19 07:50:57 -0700693 do { \
694 if (1 == count) { \
695 tmp[0] = tmp[1] = colors[0]; \
696 colors = tmp; \
697 pos = nullptr; \
698 count = 2; \
699 } \
700 } while (0)
701
fmenozzi68d952c2016-08-19 08:56:56 -0700702struct ColorStopOptimizer {
brianosmane25d71c2016-09-28 11:27:28 -0700703 ColorStopOptimizer(const SkColor4f* colors, const SkScalar* pos,
fmenozzi68d952c2016-08-19 08:56:56 -0700704 int count, SkShader::TileMode mode)
705 : fColors(colors)
706 , fPos(pos)
707 , fCount(count) {
708
709 if (!pos || count != 3) {
710 return;
711 }
712
713 if (SkScalarNearlyEqual(pos[0], 0.0f) &&
714 SkScalarNearlyEqual(pos[1], 0.0f) &&
715 SkScalarNearlyEqual(pos[2], 1.0f)) {
716
717 if (SkShader::kRepeat_TileMode == mode ||
718 SkShader::kMirror_TileMode == mode ||
719 colors[0] == colors[1]) {
720
fmalita582a6562016-08-22 06:28:57 -0700721 // Ignore the leftmost color/pos.
722 fColors += 1;
723 fPos += 1;
724 fCount = 2;
fmenozzi68d952c2016-08-19 08:56:56 -0700725 }
726 } else if (SkScalarNearlyEqual(pos[0], 0.0f) &&
727 SkScalarNearlyEqual(pos[1], 1.0f) &&
728 SkScalarNearlyEqual(pos[2], 1.0f)) {
729
730 if (SkShader::kRepeat_TileMode == mode ||
731 SkShader::kMirror_TileMode == mode ||
732 colors[1] == colors[2]) {
733
fmalita582a6562016-08-22 06:28:57 -0700734 // Ignore the rightmost color/pos.
fmenozzi68d952c2016-08-19 08:56:56 -0700735 fCount = 2;
736 }
737 }
738 }
739
brianosmane25d71c2016-09-28 11:27:28 -0700740 const SkColor4f* fColors;
741 const SkScalar* fPos;
742 int fCount;
743};
744
745struct ColorConverter {
746 ColorConverter(const SkColor* colors, int count) {
747 for (int i = 0; i < count; ++i) {
748 fColors4f.push_back(SkColor4f::FromColor(colors[i]));
749 }
750 }
751
752 SkSTArray<2, SkColor4f, true> fColors4f;
fmenozzi68d952c2016-08-19 08:56:56 -0700753};
754
reed8a21c9f2016-03-08 18:50:00 -0800755sk_sp<SkShader> SkGradientShader::MakeLinear(const SkPoint pts[2],
fmenozzi68d952c2016-08-19 08:56:56 -0700756 const SkColor colors[],
757 const SkScalar pos[], int colorCount,
758 SkShader::TileMode mode,
759 uint32_t flags,
760 const SkMatrix* localMatrix) {
brianosmane25d71c2016-09-28 11:27:28 -0700761 ColorConverter converter(colors, colorCount);
762 return MakeLinear(pts, converter.fColors4f.begin(), nullptr, pos, colorCount, mode, flags,
763 localMatrix);
764}
765
766sk_sp<SkShader> SkGradientShader::MakeLinear(const SkPoint pts[2],
767 const SkColor4f colors[],
768 sk_sp<SkColorSpace> colorSpace,
769 const SkScalar pos[], int colorCount,
770 SkShader::TileMode mode,
771 uint32_t flags,
772 const SkMatrix* localMatrix) {
fmalitac5231042016-08-10 05:45:50 -0700773 if (!pts || !SkScalarIsFinite((pts[1] - pts[0]).length())) {
halcanary96fcdcc2015-08-27 07:41:13 -0700774 return nullptr;
reed1b747302015-01-06 07:13:19 -0800775 }
776 if (!valid_grad(colors, pos, colorCount, mode)) {
halcanary96fcdcc2015-08-27 07:41:13 -0700777 return nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +0000778 }
fmenozzie9fd0f82016-08-19 07:50:57 -0700779 if (1 == colorCount) {
brianosmane25d71c2016-09-28 11:27:28 -0700780 return SkShader::MakeColorShader(colors[0], std::move(colorSpace));
fmenozzie9fd0f82016-08-19 07:50:57 -0700781 }
Florin Malita8d3ffad2017-02-03 18:21:17 +0000782 if (localMatrix && !localMatrix->invert(nullptr)) {
783 return nullptr;
784 }
rileya@google.com589708b2012-07-26 20:04:23 +0000785
fmenozzi68d952c2016-08-19 08:56:56 -0700786 ColorStopOptimizer opt(colors, pos, colorCount, mode);
787
reed@google.com437d6eb2013-05-23 19:03:05 +0000788 SkGradientShaderBase::Descriptor desc;
brianosmane25d71c2016-09-28 11:27:28 -0700789 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
790 localMatrix);
reed8a21c9f2016-03-08 18:50:00 -0800791 return sk_make_sp<SkLinearGradient>(pts, desc);
rileya@google.com589708b2012-07-26 20:04:23 +0000792}
793
reed8a21c9f2016-03-08 18:50:00 -0800794sk_sp<SkShader> SkGradientShader::MakeRadial(const SkPoint& center, SkScalar radius,
brianosmane25d71c2016-09-28 11:27:28 -0700795 const SkColor colors[],
796 const SkScalar pos[], int colorCount,
797 SkShader::TileMode mode,
798 uint32_t flags,
799 const SkMatrix* localMatrix) {
800 ColorConverter converter(colors, colorCount);
801 return MakeRadial(center, radius, converter.fColors4f.begin(), nullptr, pos, colorCount, mode,
802 flags, localMatrix);
803}
804
805sk_sp<SkShader> SkGradientShader::MakeRadial(const SkPoint& center, SkScalar radius,
806 const SkColor4f colors[],
807 sk_sp<SkColorSpace> colorSpace,
808 const SkScalar pos[], int colorCount,
809 SkShader::TileMode mode,
810 uint32_t flags,
811 const SkMatrix* localMatrix) {
reed1b747302015-01-06 07:13:19 -0800812 if (radius <= 0) {
halcanary96fcdcc2015-08-27 07:41:13 -0700813 return nullptr;
reed1b747302015-01-06 07:13:19 -0800814 }
815 if (!valid_grad(colors, pos, colorCount, mode)) {
halcanary96fcdcc2015-08-27 07:41:13 -0700816 return nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +0000817 }
fmenozzie9fd0f82016-08-19 07:50:57 -0700818 if (1 == colorCount) {
brianosmane25d71c2016-09-28 11:27:28 -0700819 return SkShader::MakeColorShader(colors[0], std::move(colorSpace));
fmenozzie9fd0f82016-08-19 07:50:57 -0700820 }
Florin Malita8d3ffad2017-02-03 18:21:17 +0000821 if (localMatrix && !localMatrix->invert(nullptr)) {
822 return nullptr;
823 }
rileya@google.com589708b2012-07-26 20:04:23 +0000824
fmenozzi68d952c2016-08-19 08:56:56 -0700825 ColorStopOptimizer opt(colors, pos, colorCount, mode);
826
reed@google.com437d6eb2013-05-23 19:03:05 +0000827 SkGradientShaderBase::Descriptor desc;
brianosmane25d71c2016-09-28 11:27:28 -0700828 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
829 localMatrix);
reed8a21c9f2016-03-08 18:50:00 -0800830 return sk_make_sp<SkRadialGradient>(center, radius, desc);
rileya@google.com589708b2012-07-26 20:04:23 +0000831}
832
reed8a21c9f2016-03-08 18:50:00 -0800833sk_sp<SkShader> SkGradientShader::MakeTwoPointConical(const SkPoint& start,
brianosmane25d71c2016-09-28 11:27:28 -0700834 SkScalar startRadius,
835 const SkPoint& end,
836 SkScalar endRadius,
837 const SkColor colors[],
838 const SkScalar pos[],
839 int colorCount,
840 SkShader::TileMode mode,
841 uint32_t flags,
842 const SkMatrix* localMatrix) {
843 ColorConverter converter(colors, colorCount);
844 return MakeTwoPointConical(start, startRadius, end, endRadius, converter.fColors4f.begin(),
845 nullptr, pos, colorCount, mode, flags, localMatrix);
846}
847
848sk_sp<SkShader> SkGradientShader::MakeTwoPointConical(const SkPoint& start,
849 SkScalar startRadius,
850 const SkPoint& end,
851 SkScalar endRadius,
852 const SkColor4f colors[],
853 sk_sp<SkColorSpace> colorSpace,
854 const SkScalar pos[],
855 int colorCount,
856 SkShader::TileMode mode,
857 uint32_t flags,
858 const SkMatrix* localMatrix) {
reed1b747302015-01-06 07:13:19 -0800859 if (startRadius < 0 || endRadius < 0) {
halcanary96fcdcc2015-08-27 07:41:13 -0700860 return nullptr;
reed1b747302015-01-06 07:13:19 -0800861 }
Florin Malita327290f2017-07-07 09:23:16 -0400862 if (SkScalarNearlyZero((start - end).length()) && SkScalarNearlyZero(startRadius)) {
863 // We can treat this gradient as radial, which is faster.
864 return MakeRadial(start, endRadius, colors, std::move(colorSpace), pos, colorCount,
865 mode, flags, localMatrix);
866 }
reed1b747302015-01-06 07:13:19 -0800867 if (!valid_grad(colors, pos, colorCount, mode)) {
halcanary96fcdcc2015-08-27 07:41:13 -0700868 return nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +0000869 }
fmalita5edf82e2016-03-03 06:41:54 -0800870 if (startRadius == endRadius) {
871 if (start == end || startRadius == 0) {
reed8a21c9f2016-03-08 18:50:00 -0800872 return SkShader::MakeEmptyShader();
fmalita5edf82e2016-03-03 06:41:54 -0800873 }
rileya@google.com589708b2012-07-26 20:04:23 +0000874 }
Florin Malita8d3ffad2017-02-03 18:21:17 +0000875 if (localMatrix && !localMatrix->invert(nullptr)) {
876 return nullptr;
877 }
reed6b7a6c72016-08-18 16:13:50 -0700878 EXPAND_1_COLOR(colorCount);
rileya@google.com589708b2012-07-26 20:04:23 +0000879
fmenozzi68d952c2016-08-19 08:56:56 -0700880 ColorStopOptimizer opt(colors, pos, colorCount, mode);
881
reed@google.com437d6eb2013-05-23 19:03:05 +0000882 SkGradientShaderBase::Descriptor desc;
Florin Malita5f379a82017-10-18 16:22:35 -0400883 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
884 localMatrix);
885 return SkTwoPointConicalGradient::Create(start, startRadius, end, endRadius, desc);
rileya@google.com589708b2012-07-26 20:04:23 +0000886}
887
reed8a21c9f2016-03-08 18:50:00 -0800888sk_sp<SkShader> SkGradientShader::MakeSweep(SkScalar cx, SkScalar cy,
brianosmane25d71c2016-09-28 11:27:28 -0700889 const SkColor colors[],
890 const SkScalar pos[],
891 int colorCount,
Florin Malita5a9a9812017-08-01 16:38:08 -0400892 SkShader::TileMode mode,
893 SkScalar startAngle,
894 SkScalar endAngle,
brianosmane25d71c2016-09-28 11:27:28 -0700895 uint32_t flags,
896 const SkMatrix* localMatrix) {
897 ColorConverter converter(colors, colorCount);
Florin Malita5a9a9812017-08-01 16:38:08 -0400898 return MakeSweep(cx, cy, converter.fColors4f.begin(), nullptr, pos, colorCount,
899 mode, startAngle, endAngle, flags, localMatrix);
brianosmane25d71c2016-09-28 11:27:28 -0700900}
901
902sk_sp<SkShader> SkGradientShader::MakeSweep(SkScalar cx, SkScalar cy,
903 const SkColor4f colors[],
904 sk_sp<SkColorSpace> colorSpace,
905 const SkScalar pos[],
906 int colorCount,
Florin Malita5a9a9812017-08-01 16:38:08 -0400907 SkShader::TileMode mode,
908 SkScalar startAngle,
909 SkScalar endAngle,
brianosmane25d71c2016-09-28 11:27:28 -0700910 uint32_t flags,
911 const SkMatrix* localMatrix) {
Florin Malita5a9a9812017-08-01 16:38:08 -0400912 if (!valid_grad(colors, pos, colorCount, mode)) {
halcanary96fcdcc2015-08-27 07:41:13 -0700913 return nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +0000914 }
fmenozzie9fd0f82016-08-19 07:50:57 -0700915 if (1 == colorCount) {
brianosmane25d71c2016-09-28 11:27:28 -0700916 return SkShader::MakeColorShader(colors[0], std::move(colorSpace));
fmenozzie9fd0f82016-08-19 07:50:57 -0700917 }
Florin Malita5a9a9812017-08-01 16:38:08 -0400918 if (startAngle >= endAngle) {
919 return nullptr;
920 }
Florin Malita8d3ffad2017-02-03 18:21:17 +0000921 if (localMatrix && !localMatrix->invert(nullptr)) {
922 return nullptr;
923 }
rileya@google.com589708b2012-07-26 20:04:23 +0000924
Florin Malita5a9a9812017-08-01 16:38:08 -0400925 if (startAngle <= 0 && endAngle >= 360) {
926 // If the t-range includes [0,1], then we can always use clamping (presumably faster).
927 mode = SkShader::kClamp_TileMode;
928 }
fmenozzi68d952c2016-08-19 08:56:56 -0700929
930 ColorStopOptimizer opt(colors, pos, colorCount, mode);
931
reed@google.com437d6eb2013-05-23 19:03:05 +0000932 SkGradientShaderBase::Descriptor desc;
brianosmane25d71c2016-09-28 11:27:28 -0700933 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
934 localMatrix);
Florin Malita5a9a9812017-08-01 16:38:08 -0400935
936 const SkScalar t0 = startAngle / 360,
937 t1 = endAngle / 360;
938
939 return sk_make_sp<SkSweepGradient>(SkPoint::Make(cx, cy), t0, t1, desc);
rileya@google.com589708b2012-07-26 20:04:23 +0000940}
941
942SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_START(SkGradientShader)
943 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkLinearGradient)
944 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkRadialGradient)
945 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkSweepGradient)
rileya@google.com589708b2012-07-26 20:04:23 +0000946 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkTwoPointConicalGradient)
947SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_END
rileya@google.comd7cc6512012-07-27 14:00:39 +0000948
949///////////////////////////////////////////////////////////////////////////////
950
bsalomon@google.comcf8fb1f2012-08-02 14:03:32 +0000951#if SK_SUPPORT_GPU
952
Brian Osman5911a7c2017-10-25 12:52:31 -0400953#include "GrColorSpaceXform.h"
brianosmana6359362016-03-21 06:55:37 -0700954#include "GrContext.h"
Robert Phillips1afd4cd2018-01-08 13:40:32 -0500955#include "GrContextPriv.h"
Brian Salomon94efbf52016-11-29 13:43:05 -0500956#include "GrShaderCaps.h"
ajuma95243eb2016-08-24 08:19:02 -0700957#include "GrTextureStripAtlas.h"
egdanielf5294392015-10-21 07:14:17 -0700958#include "gl/GrGLContext.h"
egdaniel2d721d32015-11-11 13:06:05 -0800959#include "glsl/GrGLSLFragmentShaderBuilder.h"
egdaniel018fb622015-10-28 07:26:40 -0700960#include "glsl/GrGLSLProgramDataManager.h"
egdaniel7ea439b2015-12-03 09:20:44 -0800961#include "glsl/GrGLSLUniformHandler.h"
bsalomon@google.comcf8fb1f2012-08-02 14:03:32 +0000962#include "SkGr.h"
963
fmenozzi55d318d2016-08-09 08:05:57 -0700964void GrGradientEffect::GLSLProcessor::emitUniforms(GrGLSLUniformHandler* uniformHandler,
965 const GrGradientEffect& ge) {
Florin Malita14a8dd72017-11-08 15:46:42 -0500966 switch (ge.fStrategy) {
967 case GrGradientEffect::InterpolationStrategy::kThreshold:
968 case GrGradientEffect::InterpolationStrategy::kThresholdClamp0:
969 case GrGradientEffect::InterpolationStrategy::kThresholdClamp1:
970 fThresholdUni = uniformHandler->addUniform(kFragment_GrShaderFlag,
971 kFloat_GrSLType,
972 kHigh_GrSLPrecision,
973 "Threshold");
974 // fall through
975 case GrGradientEffect::InterpolationStrategy::kSingle:
976 fIntervalsUni = uniformHandler->addUniformArray(kFragment_GrShaderFlag,
977 kHalf4_GrSLType,
978 "Intervals",
979 ge.fIntervals.count());
980 break;
981 case GrGradientEffect::InterpolationStrategy::kTexture:
982 fFSYUni = uniformHandler->addUniform(kFragment_GrShaderFlag, kHalf_GrSLType,
983 "GradientYCoordFS");
984 break;
bsalomon@google.com82d12232013-09-09 15:36:26 +0000985 }
986}
987
fmenozzi55d318d2016-08-09 08:05:57 -0700988void GrGradientEffect::GLSLProcessor::onSetData(const GrGLSLProgramDataManager& pdman,
Brian Salomonab015ef2017-04-04 10:15:51 -0400989 const GrFragmentProcessor& processor) {
joshualittb0a8a372014-09-23 09:50:21 -0700990 const GrGradientEffect& e = processor.cast<GrGradientEffect>();
bsalomon@google.com82d12232013-09-09 15:36:26 +0000991
Florin Malita14a8dd72017-11-08 15:46:42 -0500992 switch (e.fStrategy) {
993 case GrGradientEffect::InterpolationStrategy::kThreshold:
994 case GrGradientEffect::InterpolationStrategy::kThresholdClamp0:
995 case GrGradientEffect::InterpolationStrategy::kThresholdClamp1:
996 pdman.set1f(fThresholdUni, e.fThreshold);
Brian Salomon466ad992016-10-13 16:08:36 -0400997 // fall through
Florin Malita14a8dd72017-11-08 15:46:42 -0500998 case GrGradientEffect::InterpolationStrategy::kSingle:
999 pdman.set4fv(fIntervalsUni, e.fIntervals.count(),
1000 reinterpret_cast<const float*>(e.fIntervals.begin()));
fmenozzicd9a1d02016-08-15 07:03:47 -07001001 break;
Florin Malita14a8dd72017-11-08 15:46:42 -05001002 case GrGradientEffect::InterpolationStrategy::kTexture:
1003 if (e.fYCoord != fCachedYCoord) {
1004 pdman.set1f(fFSYUni, e.fYCoord);
1005 fCachedYCoord = e.fYCoord;
fmenozzicd9a1d02016-08-15 07:03:47 -07001006 }
1007 break;
rileya@google.comb3e50f22012-08-20 17:43:08 +00001008 }
1009}
1010
Florin Malitae657dc82017-11-03 08:46:18 -04001011void GrGradientEffect::onGetGLSLProcessorKey(const GrShaderCaps&, GrProcessorKeyBuilder* b) const {
1012 b->add32(GLSLProcessor::GenBaseGradientKey(*this));
1013}
1014
fmenozzi55d318d2016-08-09 08:05:57 -07001015uint32_t GrGradientEffect::GLSLProcessor::GenBaseGradientKey(const GrProcessor& processor) {
joshualittb0a8a372014-09-23 09:50:21 -07001016 const GrGradientEffect& e = processor.cast<GrGradientEffect>();
skia.committer@gmail.com9a070f22013-09-10 07:01:44 +00001017
Florin Malita14a8dd72017-11-08 15:46:42 -05001018 // Build a key using the following bit allocation:
1019 static constexpr uint32_t kStrategyBits = 3;
1020 static constexpr uint32_t kPremulBits = 1;
1021 SkDEBUGCODE(static constexpr uint32_t kWrapModeBits = 2;)
bsalomon@google.com82d12232013-09-09 15:36:26 +00001022
Florin Malita14a8dd72017-11-08 15:46:42 -05001023 uint32_t key = static_cast<uint32_t>(e.fStrategy);
1024 SkASSERT(key < (1 << kStrategyBits));
1025
1026 // This is already baked into the table for texture gradients,
1027 // and only changes behavior for analytical gradients.
1028 if (e.fStrategy != InterpolationStrategy::kTexture &&
1029 e.fPremulType == GrGradientEffect::kBeforeInterp_PremulType) {
1030 key |= 1 << kStrategyBits;
1031 SkASSERT(key < (1 << (kStrategyBits + kPremulBits)));
bsalomon@google.com82d12232013-09-09 15:36:26 +00001032 }
1033
Florin Malita14a8dd72017-11-08 15:46:42 -05001034 key |= static_cast<uint32_t>(e.fWrapMode) << (kStrategyBits + kPremulBits);
1035 SkASSERT(key < (1 << (kStrategyBits + kPremulBits + kWrapModeBits)));
fmenozzicd9a1d02016-08-15 07:03:47 -07001036
bsalomon@google.com82d12232013-09-09 15:36:26 +00001037 return key;
bsalomon@google.comd8b5fac2012-11-01 17:02:46 +00001038}
1039
Florin Malitab81a8b92017-08-08 12:14:17 -04001040void GrGradientEffect::GLSLProcessor::emitAnalyticalColor(GrGLSLFPFragmentBuilder* fragBuilder,
1041 GrGLSLUniformHandler* uniformHandler,
1042 const GrShaderCaps* shaderCaps,
1043 const GrGradientEffect& ge,
1044 const char* t,
1045 const char* outputColor,
1046 const char* inputColor) {
1047 // First, apply tiling rules.
Brian Salomon2bbdcc42017-09-07 12:36:34 -04001048 switch (ge.fWrapMode) {
1049 case GrSamplerState::WrapMode::kClamp:
Florin Malita14a8dd72017-11-08 15:46:42 -05001050 switch (ge.fStrategy) {
1051 case GrGradientEffect::InterpolationStrategy::kThresholdClamp0:
1052 // allow t > 1, in order to hit the clamp interval (1, inf)
1053 fragBuilder->codeAppendf("half tiled_t = max(%s, 0.0);", t);
1054 break;
1055 case GrGradientEffect::InterpolationStrategy::kThresholdClamp1:
1056 // allow t < 0, in order to hit the clamp interval (-inf, 0)
1057 fragBuilder->codeAppendf("half tiled_t = min(%s, 1.0);", t);
1058 break;
1059 default:
1060 // regular [0, 1] clamping
1061 fragBuilder->codeAppendf("half tiled_t = clamp(%s, 0.0, 1.0);", t);
1062 }
Brian Salomon2bbdcc42017-09-07 12:36:34 -04001063 break;
1064 case GrSamplerState::WrapMode::kRepeat:
Florin Malita14a8dd72017-11-08 15:46:42 -05001065 fragBuilder->codeAppendf("half tiled_t = fract(%s);", t);
Brian Salomon2bbdcc42017-09-07 12:36:34 -04001066 break;
1067 case GrSamplerState::WrapMode::kMirrorRepeat:
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001068 fragBuilder->codeAppendf("half t_1 = %s - 1.0;", t);
Greg Daniel10ed2432017-12-01 16:19:43 -05001069 fragBuilder->codeAppendf("half tiled_t = t_1 - 2.0 * floor(t_1 * 0.5) - 1.0;");
1070 if (shaderCaps->mustDoOpBetweenFloorAndAbs()) {
1071 // At this point the expected value of tiled_t should between -1 and 1, so this
1072 // clamp has no effect other than to break up the floor and abs calls and make sure
1073 // the compiler doesn't merge them back together.
1074 fragBuilder->codeAppendf("tiled_t = clamp(tiled_t, -1.0, 1.0);");
1075 }
1076 fragBuilder->codeAppendf("tiled_t = abs(tiled_t);");
Brian Salomon2bbdcc42017-09-07 12:36:34 -04001077 break;
Florin Malita8a0044f2017-08-07 14:38:22 -04001078 }
Florin Malita8a0044f2017-08-07 14:38:22 -04001079
Florin Malitab81a8b92017-08-08 12:14:17 -04001080 // Calculate the color.
Florin Malita14a8dd72017-11-08 15:46:42 -05001081 const char* intervals = uniformHandler->getUniformCStr(fIntervalsUni);
fmenozzicd9a1d02016-08-15 07:03:47 -07001082
Florin Malita14a8dd72017-11-08 15:46:42 -05001083 switch (ge.fStrategy) {
1084 case GrGradientEffect::InterpolationStrategy::kSingle:
1085 SkASSERT(ge.fIntervals.count() == 2);
1086 fragBuilder->codeAppendf(
1087 "half4 color_scale = %s[0],"
1088 " color_bias = %s[1];"
1089 , intervals, intervals
1090 );
fmenozzicd9a1d02016-08-15 07:03:47 -07001091 break;
Florin Malita14a8dd72017-11-08 15:46:42 -05001092 case GrGradientEffect::InterpolationStrategy::kThreshold:
1093 case GrGradientEffect::InterpolationStrategy::kThresholdClamp0:
1094 case GrGradientEffect::InterpolationStrategy::kThresholdClamp1:
1095 {
1096 SkASSERT(ge.fIntervals.count() == 4);
1097 const char* threshold = uniformHandler->getUniformCStr(fThresholdUni);
1098 fragBuilder->codeAppendf(
1099 "half4 color_scale, color_bias;"
1100 "if (tiled_t < %s) {"
1101 " color_scale = %s[0];"
1102 " color_bias = %s[1];"
1103 "} else {"
1104 " color_scale = %s[2];"
1105 " color_bias = %s[3];"
1106 "}"
1107 , threshold, intervals, intervals, intervals, intervals
1108 );
1109 } break;
Florin Malitab81a8b92017-08-08 12:14:17 -04001110 default:
1111 SkASSERT(false);
fmenozzicd9a1d02016-08-15 07:03:47 -07001112 break;
bsalomon@google.com82d12232013-09-09 15:36:26 +00001113 }
Florin Malitab81a8b92017-08-08 12:14:17 -04001114
Florin Malita14a8dd72017-11-08 15:46:42 -05001115 fragBuilder->codeAppend("half4 colorTemp = tiled_t * color_scale + color_bias;");
1116
Brian Osmanfe3e8582017-10-20 11:27:49 -04001117 // We could skip this step if all colors are known to be opaque. Two considerations:
Florin Malitab81a8b92017-08-08 12:14:17 -04001118 // The gradient SkShader reporting opaque is more restrictive than necessary in the two
1119 // pt case. Make sure the key reflects this optimization (and note that it can use the
Brian Osmanfe3e8582017-10-20 11:27:49 -04001120 // same shader as the kBeforeInterp case).
Florin Malita14a8dd72017-11-08 15:46:42 -05001121 if (ge.fPremulType == GrGradientEffect::kAfterInterp_PremulType) {
Florin Malitab81a8b92017-08-08 12:14:17 -04001122 fragBuilder->codeAppend("colorTemp.rgb *= colorTemp.a;");
1123 }
Brian Osman5911a7c2017-10-25 12:52:31 -04001124
1125 // 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 -04001126 // range. The simplest solution is to always clamp our (premul) value here. We only need to
1127 // clamp RGB, but that causes hangs on the Tegra3 Nexus7. Clamping RGBA avoids the problem.
1128 fragBuilder->codeAppend("colorTemp = clamp(colorTemp, 0, colorTemp.a);");
Florin Malitab81a8b92017-08-08 12:14:17 -04001129
1130 fragBuilder->codeAppendf("%s = %s * colorTemp;", outputColor, inputColor);
1131}
1132
1133void GrGradientEffect::GLSLProcessor::emitColor(GrGLSLFPFragmentBuilder* fragBuilder,
1134 GrGLSLUniformHandler* uniformHandler,
1135 const GrShaderCaps* shaderCaps,
1136 const GrGradientEffect& ge,
1137 const char* gradientTValue,
1138 const char* outputColor,
1139 const char* inputColor,
1140 const TextureSamplers& texSamplers) {
Florin Malita14a8dd72017-11-08 15:46:42 -05001141 if (ge.fStrategy != InterpolationStrategy::kTexture) {
Florin Malitab81a8b92017-08-08 12:14:17 -04001142 this->emitAnalyticalColor(fragBuilder, uniformHandler, shaderCaps, ge, gradientTValue,
1143 outputColor, inputColor);
1144 return;
1145 }
1146
Florin Malitab81a8b92017-08-08 12:14:17 -04001147 const char* fsyuni = uniformHandler->getUniformCStr(fFSYUni);
1148
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001149 fragBuilder->codeAppendf("half2 coord = half2(%s, %s);", gradientTValue, fsyuni);
Florin Malitab81a8b92017-08-08 12:14:17 -04001150 fragBuilder->codeAppendf("%s = ", outputColor);
1151 fragBuilder->appendTextureLookupAndModulate(inputColor, texSamplers[0], "coord",
Brian Osman5911a7c2017-10-25 12:52:31 -04001152 kFloat2_GrSLType);
Florin Malitab81a8b92017-08-08 12:14:17 -04001153 fragBuilder->codeAppend(";");
rileya@google.comd7cc6512012-07-27 14:00:39 +00001154}
1155
1156/////////////////////////////////////////////////////////////////////
1157
Brian Salomon587e08f2017-01-27 10:59:27 -05001158inline GrFragmentProcessor::OptimizationFlags GrGradientEffect::OptFlags(bool isOpaque) {
Brian Salomonf3b995b2017-02-15 10:22:23 -05001159 return isOpaque
1160 ? kPreservesOpaqueInput_OptimizationFlag |
1161 kCompatibleWithCoverageAsAlpha_OptimizationFlag
1162 : kCompatibleWithCoverageAsAlpha_OptimizationFlag;
Brian Salomon587e08f2017-01-27 10:59:27 -05001163}
1164
Florin Malita14a8dd72017-11-08 15:46:42 -05001165void GrGradientEffect::addInterval(const SkGradientShaderBase& shader, size_t idx0, size_t idx1,
1166 SkColorSpace* dstCS) {
1167 SkASSERT(idx0 <= idx1);
1168 const auto c4f0 = shader.getXformedColor(idx0, dstCS),
1169 c4f1 = shader.getXformedColor(idx1, dstCS);
1170 const auto c0 = (fPremulType == kBeforeInterp_PremulType)
1171 ? c4f0.premul().to4f() : Sk4f::Load(c4f0.vec()),
1172 c1 = (fPremulType == kBeforeInterp_PremulType)
1173 ? c4f1.premul().to4f() : Sk4f::Load(c4f1.vec());
1174 const auto t0 = shader.getPos(idx0),
1175 t1 = shader.getPos(idx1),
1176 dt = t1 - t0;
1177 SkASSERT(dt >= 0);
1178 // dt can be 0 for clamp intervals => in this case we want a scale == 0
1179 const auto scale = SkScalarNearlyZero(dt) ? 0 : (c1 - c0) / dt,
1180 bias = c0 - t0 * scale;
1181
1182 // Intervals are stored as (scale, bias) tuples.
1183 SkASSERT(!(fIntervals.count() & 1));
1184 fIntervals.emplace_back(scale[0], scale[1], scale[2], scale[3]);
1185 fIntervals.emplace_back( bias[0], bias[1], bias[2], bias[3]);
1186}
1187
Ethan Nicholasabff9562017-10-09 10:54:08 -04001188GrGradientEffect::GrGradientEffect(ClassID classID, const CreateArgs& args, bool isOpaque)
Florin Malita14a8dd72017-11-08 15:46:42 -05001189 : INHERITED(classID, OptFlags(isOpaque))
1190 , fWrapMode(args.fWrapMode)
1191 , fRow(-1)
1192 , fIsOpaque(args.fShader->isOpaque())
1193 , fStrategy(InterpolationStrategy::kTexture)
1194 , fThreshold(0) {
1195
brianosman9557c272016-09-15 06:59:15 -07001196 const SkGradientShaderBase& shader(*args.fShader);
bsalomon@google.com82d12232013-09-09 15:36:26 +00001197
Florin Malita14a8dd72017-11-08 15:46:42 -05001198 fPremulType = (args.fShader->getGradFlags() & SkGradientShader::kInterpolateColorsInPremul_Flag)
1199 ? kBeforeInterp_PremulType : kAfterInterp_PremulType;
bsalomon@google.com371e1052013-01-11 21:08:55 +00001200
Florin Malita14a8dd72017-11-08 15:46:42 -05001201 // First, determine the interpolation strategy and params.
1202 switch (shader.fColorCount) {
1203 case 2:
1204 SkASSERT(!shader.fOrigPos);
1205 fStrategy = InterpolationStrategy::kSingle;
1206 this->addInterval(shader, 0, 1, args.fDstColorSpace);
1207 break;
1208 case 3:
1209 fThreshold = shader.getPos(1);
bsalomon@google.com1ce49fc2012-09-18 14:14:49 +00001210
Florin Malita14a8dd72017-11-08 15:46:42 -05001211 if (shader.fOrigPos) {
1212 SkASSERT(SkScalarNearlyEqual(shader.fOrigPos[0], 0));
1213 SkASSERT(SkScalarNearlyEqual(shader.fOrigPos[2], 1));
1214 if (SkScalarNearlyEqual(shader.fOrigPos[1], 0)) {
1215 // hard stop on the left edge.
1216 if (fWrapMode == GrSamplerState::WrapMode::kClamp) {
1217 fStrategy = InterpolationStrategy::kThresholdClamp1;
1218 // Clamp interval (scale == 0, bias == colors[0]).
1219 this->addInterval(shader, 0, 0, args.fDstColorSpace);
1220 } else {
1221 // We can ignore the hard stop when not clamping.
1222 fStrategy = InterpolationStrategy::kSingle;
1223 }
1224 this->addInterval(shader, 1, 2, args.fDstColorSpace);
1225 break;
1226 }
Brian Osmand43f7b62017-10-19 15:42:01 -04001227
Florin Malita14a8dd72017-11-08 15:46:42 -05001228 if (SkScalarNearlyEqual(shader.fOrigPos[1], 1)) {
1229 // hard stop on the right edge.
1230 this->addInterval(shader, 0, 1, args.fDstColorSpace);
1231 if (fWrapMode == GrSamplerState::WrapMode::kClamp) {
1232 fStrategy = InterpolationStrategy::kThresholdClamp0;
1233 // Clamp interval (scale == 0, bias == colors[2]).
1234 this->addInterval(shader, 2, 2, args.fDstColorSpace);
1235 } else {
1236 // We can ignore the hard stop when not clamping.
1237 fStrategy = InterpolationStrategy::kSingle;
1238 }
1239 break;
1240 }
Brian Osmand43f7b62017-10-19 15:42:01 -04001241 }
1242
Florin Malita14a8dd72017-11-08 15:46:42 -05001243 // Two arbitrary interpolation intervals.
1244 fStrategy = InterpolationStrategy::kThreshold;
1245 this->addInterval(shader, 0, 1, args.fDstColorSpace);
1246 this->addInterval(shader, 1, 2, args.fDstColorSpace);
1247 break;
1248 case 4:
1249 if (shader.fOrigPos && SkScalarNearlyEqual(shader.fOrigPos[1], shader.fOrigPos[2])) {
1250 SkASSERT(SkScalarNearlyEqual(shader.fOrigPos[0], 0));
1251 SkASSERT(SkScalarNearlyEqual(shader.fOrigPos[3], 1));
fmenozzi2a495912016-08-12 06:33:52 -07001252
Florin Malita14a8dd72017-11-08 15:46:42 -05001253 // Single hard stop => two arbitrary interpolation intervals.
1254 fStrategy = InterpolationStrategy::kThreshold;
1255 fThreshold = shader.getPos(1);
1256 this->addInterval(shader, 0, 1, args.fDstColorSpace);
1257 this->addInterval(shader, 2, 3, args.fDstColorSpace);
1258 }
1259 break;
1260 default:
1261 break;
fmenozzi2a495912016-08-12 06:33:52 -07001262 }
fmenozzicd9a1d02016-08-15 07:03:47 -07001263
Florin Malita14a8dd72017-11-08 15:46:42 -05001264 // Now that we've locked down a strategy, adjust any dependent params.
1265 if (fStrategy != InterpolationStrategy::kTexture) {
1266 // Analytical cases.
1267 fCoordTransform.reset(*args.fMatrix);
1268 } else {
1269 SkGradientShaderBase::GradientBitmapType bitmapType =
1270 SkGradientShaderBase::GradientBitmapType::kLegacy;
1271 if (args.fDstColorSpace) {
1272 // Try to use F16 if we can
1273 if (args.fContext->caps()->isConfigTexturable(kRGBA_half_GrPixelConfig)) {
1274 bitmapType = SkGradientShaderBase::GradientBitmapType::kHalfFloat;
1275 } else if (args.fContext->caps()->isConfigTexturable(kSRGBA_8888_GrPixelConfig)) {
1276 bitmapType = SkGradientShaderBase::GradientBitmapType::kSRGB;
fmenozzicd9a1d02016-08-15 07:03:47 -07001277 } else {
Florin Malita14a8dd72017-11-08 15:46:42 -05001278 // This can happen, but only if someone explicitly creates an unsupported
1279 // (eg sRGB) surface. Just fall back to legacy behavior.
fmenozzicd9a1d02016-08-15 07:03:47 -07001280 }
Florin Malita14a8dd72017-11-08 15:46:42 -05001281 }
fmenozzicd9a1d02016-08-15 07:03:47 -07001282
Florin Malita14a8dd72017-11-08 15:46:42 -05001283 SkBitmap bitmap;
1284 shader.getGradientTableBitmap(&bitmap, bitmapType);
1285 SkASSERT(1 == bitmap.height() && SkIsPow2(bitmap.width()));
fmenozzicd9a1d02016-08-15 07:03:47 -07001286
Robert Phillips41a3b872018-03-09 12:00:34 -05001287 auto atlasManager = args.fContext->contextPriv().textureStripAtlasManager();
Florin Malita14a8dd72017-11-08 15:46:42 -05001288
1289 GrTextureStripAtlas::Desc desc;
1290 desc.fWidth = bitmap.width();
1291 desc.fHeight = 32;
Robert Phillips7a926392018-02-01 15:49:54 -05001292 desc.fRowHeight = bitmap.height(); // always 1 here
Florin Malita14a8dd72017-11-08 15:46:42 -05001293 desc.fConfig = SkImageInfo2GrPixelConfig(bitmap.info(), *args.fContext->caps());
Robert Phillips96b6d532018-03-19 10:57:42 -04001294 fAtlas = atlasManager->refAtlas(desc);
Florin Malita14a8dd72017-11-08 15:46:42 -05001295 SkASSERT(fAtlas);
1296
1297 // We always filter the gradient table. Each table is one row of a texture, always
1298 // y-clamp.
1299 GrSamplerState samplerState(args.fWrapMode, GrSamplerState::Filter::kBilerp);
1300
Robert Phillips41a3b872018-03-09 12:00:34 -05001301 fRow = fAtlas->lockRow(args.fContext, bitmap);
Florin Malita14a8dd72017-11-08 15:46:42 -05001302 if (-1 != fRow) {
1303 fYCoord = fAtlas->getYOffset(fRow)+SK_ScalarHalf*fAtlas->getNormalizedTexelHeight();
1304 // This is 1/2 places where auto-normalization is disabled
1305 fCoordTransform.reset(*args.fMatrix, fAtlas->asTextureProxyRef().get(), false);
1306 fTextureSampler.reset(fAtlas->asTextureProxyRef(), samplerState);
1307 } else {
1308 // In this instance we know the samplerState state is:
1309 // clampY, bilerp
1310 // and the proxy is:
1311 // exact fit, power of two in both dimensions
1312 // Only the x-tileMode is unknown. However, given all the other knowns we know
Robert Phillips7a926392018-02-01 15:49:54 -05001313 // that GrMakeCachedImageProxy is sufficient (i.e., it won't need to be
Florin Malita14a8dd72017-11-08 15:46:42 -05001314 // extracted to a subset or mipmapped).
Robert Phillips7a926392018-02-01 15:49:54 -05001315
1316 SkASSERT(bitmap.isImmutable());
1317 sk_sp<SkImage> srcImage = SkImage::MakeFromBitmap(bitmap);
1318 if (!srcImage) {
1319 return;
1320 }
1321
1322 sk_sp<GrTextureProxy> proxy = GrMakeCachedImageProxy(
Robert Phillips1afd4cd2018-01-08 13:40:32 -05001323 args.fContext->contextPriv().proxyProvider(),
Robert Phillips7a926392018-02-01 15:49:54 -05001324 std::move(srcImage));
Florin Malita14a8dd72017-11-08 15:46:42 -05001325 if (!proxy) {
1326 SkDebugf("Gradient won't draw. Could not create texture.");
1327 return;
1328 }
1329 // This is 2/2 places where auto-normalization is disabled
1330 fCoordTransform.reset(*args.fMatrix, proxy.get(), false);
1331 fTextureSampler.reset(std::move(proxy), samplerState);
1332 fYCoord = SK_ScalarHalf;
1333 }
1334
1335 this->addTextureSampler(&fTextureSampler);
fmenozzicd9a1d02016-08-15 07:03:47 -07001336 }
1337
bsalomon@google.com77af6802013-10-02 13:04:56 +00001338 this->addCoordTransform(&fCoordTransform);
rileya@google.comd7cc6512012-07-27 14:00:39 +00001339}
1340
Brian Salomonf8480b92017-07-27 15:45:59 -04001341GrGradientEffect::GrGradientEffect(const GrGradientEffect& that)
Ethan Nicholasabff9562017-10-09 10:54:08 -04001342 : INHERITED(that.classID(), OptFlags(that.fIsOpaque))
Florin Malita14a8dd72017-11-08 15:46:42 -05001343 , fIntervals(that.fIntervals)
Brian Salomon2bbdcc42017-09-07 12:36:34 -04001344 , fWrapMode(that.fWrapMode)
Brian Salomonf8480b92017-07-27 15:45:59 -04001345 , fCoordTransform(that.fCoordTransform)
1346 , fTextureSampler(that.fTextureSampler)
1347 , fYCoord(that.fYCoord)
1348 , fAtlas(that.fAtlas)
1349 , fRow(that.fRow)
1350 , fIsOpaque(that.fIsOpaque)
Florin Malita14a8dd72017-11-08 15:46:42 -05001351 , fStrategy(that.fStrategy)
1352 , fThreshold(that.fThreshold)
Brian Salomonf8480b92017-07-27 15:45:59 -04001353 , fPremulType(that.fPremulType) {
1354 this->addCoordTransform(&fCoordTransform);
Florin Malita14a8dd72017-11-08 15:46:42 -05001355 if (fStrategy == InterpolationStrategy::kTexture) {
Brian Salomonf8480b92017-07-27 15:45:59 -04001356 this->addTextureSampler(&fTextureSampler);
1357 }
1358 if (this->useAtlas()) {
1359 fAtlas->lockRow(fRow);
1360 }
1361}
1362
rileya@google.comd7cc6512012-07-27 14:00:39 +00001363GrGradientEffect::~GrGradientEffect() {
rileya@google.comb3e50f22012-08-20 17:43:08 +00001364 if (this->useAtlas()) {
1365 fAtlas->unlockRow(fRow);
rileya@google.comb3e50f22012-08-20 17:43:08 +00001366 }
rileya@google.comd7cc6512012-07-27 14:00:39 +00001367}
1368
bsalomon0e08fc12014-10-15 08:19:04 -07001369bool GrGradientEffect::onIsEqual(const GrFragmentProcessor& processor) const {
fmenozzicd9a1d02016-08-15 07:03:47 -07001370 const GrGradientEffect& ge = processor.cast<GrGradientEffect>();
bsalomon@google.com82d12232013-09-09 15:36:26 +00001371
Florin Malita14a8dd72017-11-08 15:46:42 -05001372 if (fWrapMode != ge.fWrapMode || fStrategy != ge.fStrategy) {
Brian Salomon466ad992016-10-13 16:08:36 -04001373 return false;
1374 }
Florin Malita14a8dd72017-11-08 15:46:42 -05001375
Brian Salomon466ad992016-10-13 16:08:36 -04001376 SkASSERT(this->useAtlas() == ge.useAtlas());
Florin Malita14a8dd72017-11-08 15:46:42 -05001377 if (fStrategy == InterpolationStrategy::kTexture) {
1378 if (fYCoord != ge.fYCoord) {
Brian Salomon466ad992016-10-13 16:08:36 -04001379 return false;
1380 }
1381 } else {
Florin Malita14a8dd72017-11-08 15:46:42 -05001382 if (fThreshold != ge.fThreshold ||
1383 fIntervals != ge.fIntervals ||
1384 fPremulType != ge.fPremulType) {
Brian Salomon466ad992016-10-13 16:08:36 -04001385 return false;
1386 }
bsalomon@google.com82d12232013-09-09 15:36:26 +00001387 }
Brian Osman5911a7c2017-10-25 12:52:31 -04001388 return true;
bsalomon@google.com68b58c92013-01-17 16:50:08 +00001389}
1390
Hal Canary6f6961e2017-01-31 13:50:44 -05001391#if GR_TEST_UTILS
Brian Osman3f748602016-10-03 18:29:03 -04001392GrGradientEffect::RandomGradientParams::RandomGradientParams(SkRandom* random) {
Brian Salomon5d4cd9e2017-02-09 11:16:46 -05001393 // Set color count to min of 2 so that we don't trigger the const color optimization and make
1394 // a non-gradient processor.
1395 fColorCount = random->nextRangeU(2, kMaxRandomGradientColors);
Brian Osmana2196532016-10-17 12:48:13 -04001396 fUseColors4f = random->nextBool();
bsalomon@google.comd4726202012-08-03 14:34:46 +00001397
1398 // if one color, omit stops, otherwise randomly decide whether or not to
Brian Osman3f748602016-10-03 18:29:03 -04001399 if (fColorCount == 1 || (fColorCount >= 2 && random->nextBool())) {
1400 fStops = nullptr;
1401 } else {
1402 fStops = fStopStorage;
bsalomon@google.comd4726202012-08-03 14:34:46 +00001403 }
1404
Brian Osmana2196532016-10-17 12:48:13 -04001405 // if using SkColor4f, attach a random (possibly null) color space (with linear gamma)
1406 if (fUseColors4f) {
1407 fColorSpace = GrTest::TestColorSpace(random);
1408 if (fColorSpace) {
Brian Osman36703d92017-12-12 14:09:31 -05001409 fColorSpace = fColorSpace->makeLinearGamma();
Brian Osmana2196532016-10-17 12:48:13 -04001410 }
1411 }
1412
bsalomon@google.com81712882012-11-01 17:12:34 +00001413 SkScalar stop = 0.f;
Brian Osman3f748602016-10-03 18:29:03 -04001414 for (int i = 0; i < fColorCount; ++i) {
Brian Osmana2196532016-10-17 12:48:13 -04001415 if (fUseColors4f) {
1416 fColors4f[i].fR = random->nextUScalar1();
1417 fColors4f[i].fG = random->nextUScalar1();
1418 fColors4f[i].fB = random->nextUScalar1();
1419 fColors4f[i].fA = random->nextUScalar1();
1420 } else {
1421 fColors[i] = random->nextU();
1422 }
Brian Osman3f748602016-10-03 18:29:03 -04001423 if (fStops) {
1424 fStops[i] = stop;
1425 stop = i < fColorCount - 1 ? stop + random->nextUScalar1() * (1.f - stop) : 1.f;
bsalomon@google.comd4726202012-08-03 14:34:46 +00001426 }
1427 }
Brian Osman3f748602016-10-03 18:29:03 -04001428 fTileMode = static_cast<SkShader::TileMode>(random->nextULessThan(SkShader::kTileModeCount));
bsalomon@google.comd4726202012-08-03 14:34:46 +00001429}
Hal Canary6f6961e2017-01-31 13:50:44 -05001430#endif
bsalomon@google.comd4726202012-08-03 14:34:46 +00001431
bsalomon@google.comcf8fb1f2012-08-02 14:03:32 +00001432#endif