blob: 78f514c1c63db013110ae374fbbc83d2f3537c18 [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
Florin Malitaf77db112018-05-10 09:52:27 -040074template <int N, typename T, bool MEM_MOVE>
75static bool validate_array(SkReadBuffer& buffer, size_t count, SkSTArray<N, T, MEM_MOVE>* array) {
Kevin Lubickdaebae92018-05-17 11:29:10 -040076 if (!buffer.validateCanReadN<T>(count)) {
Florin Malitaf77db112018-05-10 09:52:27 -040077 return false;
78 }
79
80 array->resize_back(count);
81 return true;
82}
83
reed9fa60da2014-08-21 07:59:51 -070084bool SkGradientShaderBase::DescriptorScope::unflatten(SkReadBuffer& buffer) {
Mike Reed70bc94f2017-06-08 12:45:52 -040085 // New gradient format. Includes floating point color, color space, densely packed flags
86 uint32_t flags = buffer.readUInt();
reed9fa60da2014-08-21 07:59:51 -070087
Mike Reed70bc94f2017-06-08 12:45:52 -040088 fTileMode = (SkShader::TileMode)((flags >> kTileModeShift_GSF) & kTileModeMask_GSF);
89 fGradFlags = (flags >> kGradFlagsShift_GSF) & kGradFlagsMask_GSF;
reed9fa60da2014-08-21 07:59:51 -070090
Mike Reed70bc94f2017-06-08 12:45:52 -040091 fCount = buffer.getArrayCount();
Florin Malitaf77db112018-05-10 09:52:27 -040092
93 if (!(validate_array(buffer, fCount, &fColorStorage) &&
94 buffer.readColor4fArray(fColorStorage.begin(), fCount))) {
Mike Reed70bc94f2017-06-08 12:45:52 -040095 return false;
96 }
Florin Malitaf77db112018-05-10 09:52:27 -040097 fColors = fColorStorage.begin();
98
Mike Reed70bc94f2017-06-08 12:45:52 -040099 if (SkToBool(flags & kHasColorSpace_GSF)) {
100 sk_sp<SkData> data = buffer.readByteArrayAsData();
Florin Malitac2ea3272018-05-10 09:41:38 -0400101 fColorSpace = data ? SkColorSpace::Deserialize(data->data(), data->size()) : nullptr;
Mike Reed70bc94f2017-06-08 12:45:52 -0400102 } else {
brianosmane25d71c2016-09-28 11:27:28 -0700103 fColorSpace = nullptr;
Mike Reed70bc94f2017-06-08 12:45:52 -0400104 }
105 if (SkToBool(flags & kHasPosition_GSF)) {
Florin Malitaf77db112018-05-10 09:52:27 -0400106 if (!(validate_array(buffer, fCount, &fPosStorage) &&
107 buffer.readScalarArray(fPosStorage.begin(), fCount))) {
Mike Reed70bc94f2017-06-08 12:45:52 -0400108 return false;
brianosmane25d71c2016-09-28 11:27:28 -0700109 }
Florin Malitaf77db112018-05-10 09:52:27 -0400110 fPos = fPosStorage.begin();
reed9fa60da2014-08-21 07:59:51 -0700111 } else {
Mike Reed70bc94f2017-06-08 12:45:52 -0400112 fPos = nullptr;
113 }
114 if (SkToBool(flags & kHasLocalMatrix_GSF)) {
115 fLocalMatrix = &fLocalMatrixStorage;
116 buffer.readMatrix(&fLocalMatrixStorage);
117 } else {
118 fLocalMatrix = nullptr;
reed9fa60da2014-08-21 07:59:51 -0700119 }
120 return buffer.isValid();
121}
122
123////////////////////////////////////////////////////////////////////////////////////////////
124
mtkleincc695fe2014-12-10 10:29:19 -0800125SkGradientShaderBase::SkGradientShaderBase(const Descriptor& desc, const SkMatrix& ptsToUnit)
reedaddf2ed2014-08-11 08:28:24 -0700126 : INHERITED(desc.fLocalMatrix)
mtkleincc695fe2014-12-10 10:29:19 -0800127 , fPtsToUnit(ptsToUnit)
Florin Malitaabc85752018-04-25 22:18:37 -0400128 , fColorSpace(desc.fColorSpace ? desc.fColorSpace : SkColorSpace::MakeSRGBLinear())
Florin Malita39d71de2017-10-31 11:33:49 -0400129 , fColorsAreOpaque(true)
commit-bot@chromium.org9c9005a2014-04-28 14:55:39 +0000130{
mtkleincc695fe2014-12-10 10:29:19 -0800131 fPtsToUnit.getType(); // Precache so reads are threadsafe.
reed@google.com437d6eb2013-05-23 19:03:05 +0000132 SkASSERT(desc.fCount > 1);
rileya@google.com589708b2012-07-26 20:04:23 +0000133
fmalita6d7e4e82016-09-20 06:55:16 -0700134 fGradFlags = static_cast<uint8_t>(desc.fGradFlags);
rileya@google.com589708b2012-07-26 20:04:23 +0000135
reed@google.com437d6eb2013-05-23 19:03:05 +0000136 SkASSERT((unsigned)desc.fTileMode < SkShader::kTileModeCount);
reed@google.com437d6eb2013-05-23 19:03:05 +0000137 fTileMode = desc.fTileMode;
rileya@google.com589708b2012-07-26 20:04:23 +0000138
rileya@google.com589708b2012-07-26 20:04:23 +0000139 /* Note: we let the caller skip the first and/or last position.
140 i.e. pos[0] = 0.3, pos[1] = 0.7
141 In these cases, we insert dummy entries to ensure that the final data
142 will be bracketed by [0, 1].
143 i.e. our_pos[0] = 0, our_pos[1] = 0.3, our_pos[2] = 0.7, our_pos[3] = 1
144
145 Thus colorCount (the caller's value, and fColorCount (our value) may
146 differ by up to 2. In the above example:
147 colorCount = 2
148 fColorCount = 4
149 */
reed@google.com437d6eb2013-05-23 19:03:05 +0000150 fColorCount = desc.fCount;
rileya@google.com589708b2012-07-26 20:04:23 +0000151 // check if we need to add in dummy start and/or end position/colors
152 bool dummyFirst = false;
153 bool dummyLast = false;
reed@google.com437d6eb2013-05-23 19:03:05 +0000154 if (desc.fPos) {
155 dummyFirst = desc.fPos[0] != 0;
156 dummyLast = desc.fPos[desc.fCount - 1] != SK_Scalar1;
rileya@google.com589708b2012-07-26 20:04:23 +0000157 fColorCount += dummyFirst + dummyLast;
158 }
159
Mike Reed62ce2ca2018-02-19 14:20:15 -0500160 size_t storageSize = fColorCount * (sizeof(SkColor4f) + (desc.fPos ? sizeof(SkScalar) : 0));
Florin Malita89ab2402017-11-01 10:14:57 -0400161 fOrigColors4f = reinterpret_cast<SkColor4f*>(fStorage.reset(storageSize));
Mike Reed62ce2ca2018-02-19 14:20:15 -0500162 fOrigPos = desc.fPos ? reinterpret_cast<SkScalar*>(fOrigColors4f + fColorCount)
163 : nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +0000164
brianosmane25d71c2016-09-28 11:27:28 -0700165 // Now copy over the colors, adding the dummies as needed
166 SkColor4f* origColors = fOrigColors4f;
167 if (dummyFirst) {
168 *origColors++ = desc.fColors[0];
169 }
Florin Malita39d71de2017-10-31 11:33:49 -0400170 for (int i = 0; i < desc.fCount; ++i) {
Mike Reed62ce2ca2018-02-19 14:20:15 -0500171 origColors[i] = desc.fColors[i];
Florin Malita39d71de2017-10-31 11:33:49 -0400172 fColorsAreOpaque = fColorsAreOpaque && (desc.fColors[i].fA == 1);
173 }
brianosmane25d71c2016-09-28 11:27:28 -0700174 if (dummyLast) {
Mike Reed62ce2ca2018-02-19 14:20:15 -0500175 origColors += desc.fCount;
176 *origColors = desc.fColors[desc.fCount - 1];
brianosmane25d71c2016-09-28 11:27:28 -0700177 }
brianosmanb9c51372016-09-15 11:09:45 -0700178
Florin Malita89ab2402017-11-01 10:14:57 -0400179 if (desc.fPos) {
Florin Malita64bb78e2017-11-03 12:54:07 -0400180 SkScalar prev = 0;
Mike Reed62ce2ca2018-02-19 14:20:15 -0500181 SkScalar* origPosPtr = fOrigPos;
Florin Malita64bb78e2017-11-03 12:54:07 -0400182 *origPosPtr++ = prev; // force the first pos to 0
reed9fa60da2014-08-21 07:59:51 -0700183
Florin Malita89ab2402017-11-01 10:14:57 -0400184 int startIndex = dummyFirst ? 0 : 1;
185 int count = desc.fCount + dummyLast;
Florin Malita64bb78e2017-11-03 12:54:07 -0400186
187 bool uniformStops = true;
188 const SkScalar uniformStep = desc.fPos[startIndex] - prev;
Florin Malita89ab2402017-11-01 10:14:57 -0400189 for (int i = startIndex; i < count; i++) {
Florin Malita3e20d022017-11-03 12:11:38 -0400190 // Pin the last value to 1.0, and make sure pos is monotonic.
Florin Malita64bb78e2017-11-03 12:54:07 -0400191 auto curr = (i == desc.fCount) ? 1 : SkScalarPin(desc.fPos[i], prev, 1);
192 uniformStops &= SkScalarNearlyEqual(uniformStep, curr - prev);
193
194 *origPosPtr++ = prev = curr;
reed9fa60da2014-08-21 07:59:51 -0700195 }
Florin Malita64bb78e2017-11-03 12:54:07 -0400196
Florin Malita64bb78e2017-11-03 12:54:07 -0400197 // If the stops are uniform, treat them as implicit.
Mike Reed62ce2ca2018-02-19 14:20:15 -0500198 if (uniformStops) {
Florin Malita64bb78e2017-11-03 12:54:07 -0400199 fOrigPos = nullptr;
200 }
rileya@google.com589708b2012-07-26 20:04:23 +0000201 }
rileya@google.com589708b2012-07-26 20:04:23 +0000202}
203
Florin Malita89ab2402017-11-01 10:14:57 -0400204SkGradientShaderBase::~SkGradientShaderBase() {}
rileya@google.com589708b2012-07-26 20:04:23 +0000205
commit-bot@chromium.org8b0e8ac2014-01-30 18:58:24 +0000206void SkGradientShaderBase::flatten(SkWriteBuffer& buffer) const {
reed9fa60da2014-08-21 07:59:51 -0700207 Descriptor desc;
brianosmane25d71c2016-09-28 11:27:28 -0700208 desc.fColors = fOrigColors4f;
brianosmanb9c51372016-09-15 11:09:45 -0700209 desc.fColorSpace = fColorSpace;
reed9fa60da2014-08-21 07:59:51 -0700210 desc.fPos = fOrigPos;
211 desc.fCount = fColorCount;
212 desc.fTileMode = fTileMode;
213 desc.fGradFlags = fGradFlags;
214
215 const SkMatrix& m = this->getLocalMatrix();
halcanary96fcdcc2015-08-27 07:41:13 -0700216 desc.fLocalMatrix = m.isIdentity() ? nullptr : &m;
reed9fa60da2014-08-21 07:59:51 -0700217 desc.flatten(buffer);
rileya@google.com589708b2012-07-26 20:04:23 +0000218}
219
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400220static void add_stop_color(SkJumper_GradientCtx* ctx, size_t stop, SkPM4f Fs, SkPM4f Bs) {
221 (ctx->fs[0])[stop] = Fs.r();
222 (ctx->fs[1])[stop] = Fs.g();
223 (ctx->fs[2])[stop] = Fs.b();
224 (ctx->fs[3])[stop] = Fs.a();
225 (ctx->bs[0])[stop] = Bs.r();
226 (ctx->bs[1])[stop] = Bs.g();
227 (ctx->bs[2])[stop] = Bs.b();
228 (ctx->bs[3])[stop] = Bs.a();
Mike Kleinf945cbb2017-05-17 09:30:58 -0400229}
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400230
231static void add_const_color(SkJumper_GradientCtx* ctx, size_t stop, SkPM4f color) {
232 add_stop_color(ctx, stop, SkPM4f::FromPremulRGBA(0,0,0,0), color);
Mike Kleinf945cbb2017-05-17 09:30:58 -0400233}
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400234
235// Calculate a factor F and a bias B so that color = F*t + B when t is in range of
236// the stop. Assume that the distance between stops is 1/gapCount.
237static void init_stop_evenly(
238 SkJumper_GradientCtx* ctx, float gapCount, size_t stop, SkPM4f c_l, SkPM4f c_r) {
Mike Klein68768172017-05-17 09:54:36 -0400239 // Clankium's GCC 4.9 targeting ARMv7 is barfing when we use Sk4f math here, so go scalar...
240 SkPM4f Fs = {{
241 (c_r.r() - c_l.r()) * gapCount,
242 (c_r.g() - c_l.g()) * gapCount,
243 (c_r.b() - c_l.b()) * gapCount,
244 (c_r.a() - c_l.a()) * gapCount,
245 }};
246 SkPM4f Bs = {{
247 c_l.r() - Fs.r()*(stop/gapCount),
248 c_l.g() - Fs.g()*(stop/gapCount),
249 c_l.b() - Fs.b()*(stop/gapCount),
250 c_l.a() - Fs.a()*(stop/gapCount),
251 }};
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400252 add_stop_color(ctx, stop, Fs, Bs);
Mike Kleinf945cbb2017-05-17 09:30:58 -0400253}
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400254
255// For each stop we calculate a bias B and a scale factor F, such that
256// for any t between stops n and n+1, the color we want is B[n] + F[n]*t.
257static void init_stop_pos(
258 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 -0400259 // See note about Clankium's old compiler in init_stop_evenly().
260 SkPM4f Fs = {{
261 (c_r.r() - c_l.r()) / (t_r - t_l),
262 (c_r.g() - c_l.g()) / (t_r - t_l),
263 (c_r.b() - c_l.b()) / (t_r - t_l),
264 (c_r.a() - c_l.a()) / (t_r - t_l),
265 }};
266 SkPM4f Bs = {{
267 c_l.r() - Fs.r()*t_l,
268 c_l.g() - Fs.g()*t_l,
269 c_l.b() - Fs.b()*t_l,
270 c_l.a() - Fs.a()*t_l,
271 }};
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400272 ctx->ts[stop] = t_l;
273 add_stop_color(ctx, stop, Fs, Bs);
Mike Kleinf945cbb2017-05-17 09:30:58 -0400274}
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400275
Mike Reed1d8c42e2017-08-29 14:58:19 -0400276bool SkGradientShaderBase::onAppendStages(const StageRec& rec) const {
277 SkRasterPipeline* p = rec.fPipeline;
278 SkArenaAlloc* alloc = rec.fAlloc;
279 SkColorSpace* dstCS = rec.fDstCS;
Mike Reed62ce2ca2018-02-19 14:20:15 -0500280 SkJumper_DecalTileCtx* decal_ctx = nullptr;
Mike Reed1d8c42e2017-08-29 14:58:19 -0400281
Mike Kleina3771842017-05-04 19:38:48 -0400282 SkMatrix matrix;
Mike Reed1d8c42e2017-08-29 14:58:19 -0400283 if (!this->computeTotalInverse(rec.fCTM, rec.fLocalM, &matrix)) {
Mike Kleina3771842017-05-04 19:38:48 -0400284 return false;
285 }
Florin Malita50b20842017-07-29 19:08:28 -0400286 matrix.postConcat(fPtsToUnit);
Mike Kleina3771842017-05-04 19:38:48 -0400287
Florin Malita2e409002017-06-28 14:46:54 -0400288 SkRasterPipeline_<256> postPipeline;
Mike Kleina3771842017-05-04 19:38:48 -0400289
Mike Kleine8de0242018-03-10 12:37:11 -0500290 p->append(SkRasterPipeline::seed_shader);
Mike Reed6b59bf42017-07-03 21:26:44 -0400291 p->append_matrix(alloc, matrix);
Florin Malita50b20842017-07-29 19:08:28 -0400292 this->appendGradientStages(alloc, p, &postPipeline);
Mike Kleine7598532017-05-11 11:29:29 -0400293
Mike Reed62ce2ca2018-02-19 14:20:15 -0500294 switch(fTileMode) {
Mike Klein9f85d682017-05-23 07:52:01 -0400295 case kMirror_TileMode: p->append(SkRasterPipeline::mirror_x_1); break;
296 case kRepeat_TileMode: p->append(SkRasterPipeline::repeat_x_1); break;
Mike Reeddfc0e912018-02-16 12:40:18 -0500297 case kDecal_TileMode:
Mike Reed62ce2ca2018-02-19 14:20:15 -0500298 decal_ctx = alloc->make<SkJumper_DecalTileCtx>();
299 decal_ctx->limit_x = SkBits2Float(SkFloat2Bits(1.0f) + 1);
300 // reuse mask + limit_x stage, or create a custom decal_1 that just stores the mask
301 p->append(SkRasterPipeline::decal_x, decal_ctx);
302 // fall-through to clamp
Mike Kleine7598532017-05-11 11:29:29 -0400303 case kClamp_TileMode:
304 if (!fOrigPos) {
305 // We clamp only when the stops are evenly spaced.
306 // If not, there may be hard stops, and clamping ruins hard stops at 0 and/or 1.
Mike Klein5c7960b2017-05-11 10:59:22 -0400307 // In that case, we must make sure we're using the general "gradient" stage,
Mike Kleine7598532017-05-11 11:29:29 -0400308 // which is the only stage that will correctly handle unclamped t.
Mike Klein9f85d682017-05-23 07:52:01 -0400309 p->append(SkRasterPipeline::clamp_x_1);
Mike Kleine7598532017-05-11 11:29:29 -0400310 }
Mike Reed62ce2ca2018-02-19 14:20:15 -0500311 break;
Mike Kleine7598532017-05-11 11:29:29 -0400312 }
Mike Kleina3771842017-05-04 19:38:48 -0400313
314 const bool premulGrad = fGradFlags & SkGradientShader::kInterpolateColorsInPremul_Flag;
315 auto prepareColor = [premulGrad, dstCS, this](int i) {
Florin Malita0e36b3f2017-06-05 23:33:45 -0400316 SkColor4f c = this->getXformedColor(i, dstCS);
Mike Kleina3771842017-05-04 19:38:48 -0400317 return premulGrad ? c.premul()
318 : SkPM4f::From4f(Sk4f::Load(&c));
319 };
320
321 // The two-stop case with stops at 0 and 1.
322 if (fColorCount == 2 && fOrigPos == nullptr) {
323 const SkPM4f c_l = prepareColor(0),
Mike Reed1d8c42e2017-08-29 14:58:19 -0400324 c_r = prepareColor(1);
Mike Kleina3771842017-05-04 19:38:48 -0400325
326 // See F and B below.
327 auto* f_and_b = alloc->makeArrayDefault<SkPM4f>(2);
328 f_and_b[0] = SkPM4f::From4f(c_r.to4f() - c_l.to4f());
329 f_and_b[1] = c_l;
330
Mike Klein5c7960b2017-05-11 10:59:22 -0400331 p->append(SkRasterPipeline::evenly_spaced_2_stop_gradient, f_and_b);
Mike Kleina3771842017-05-04 19:38:48 -0400332 } else {
Herb Derby4de13042017-05-15 10:49:39 -0400333 auto* ctx = alloc->make<SkJumper_GradientCtx>();
Herb Derby4de13042017-05-15 10:49:39 -0400334
335 // Note: In order to handle clamps in search, the search assumes a stop conceptully placed
336 // at -inf. Therefore, the max number of stops is fColorCount+1.
337 for (int i = 0; i < 4; i++) {
338 // Allocate at least at for the AVX2 gather from a YMM register.
339 ctx->fs[i] = alloc->makeArray<float>(std::max(fColorCount+1, 8));
340 ctx->bs[i] = alloc->makeArray<float>(std::max(fColorCount+1, 8));
341 }
342
Mike Kleina3771842017-05-04 19:38:48 -0400343 if (fOrigPos == nullptr) {
344 // Handle evenly distributed stops.
345
Herb Derby4de13042017-05-15 10:49:39 -0400346 size_t stopCount = fColorCount;
347 float gapCount = stopCount - 1;
Mike Kleina3771842017-05-04 19:38:48 -0400348
Herb Derby4de13042017-05-15 10:49:39 -0400349 SkPM4f c_l = prepareColor(0);
350 for (size_t i = 0; i < stopCount - 1; i++) {
Mike Kleina3771842017-05-04 19:38:48 -0400351 SkPM4f c_r = prepareColor(i + 1);
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400352 init_stop_evenly(ctx, gapCount, i, c_l, c_r);
Mike Kleina3771842017-05-04 19:38:48 -0400353 c_l = c_r;
354 }
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400355 add_const_color(ctx, stopCount - 1, c_l);
Mike Kleina3771842017-05-04 19:38:48 -0400356
Herb Derby4de13042017-05-15 10:49:39 -0400357 ctx->stopCount = stopCount;
358 p->append(SkRasterPipeline::evenly_spaced_gradient, ctx);
Mike Kleina3771842017-05-04 19:38:48 -0400359 } else {
360 // Handle arbitrary stops.
361
Herb Derby4de13042017-05-15 10:49:39 -0400362 ctx->ts = alloc->makeArray<float>(fColorCount+1);
363
Mike Kleina3771842017-05-04 19:38:48 -0400364 // Remove the dummy stops inserted by SkGradientShaderBase::SkGradientShaderBase
365 // because they are naturally handled by the search method.
366 int firstStop;
367 int lastStop;
368 if (fColorCount > 2) {
369 firstStop = fOrigColors4f[0] != fOrigColors4f[1] ? 0 : 1;
370 lastStop = fOrigColors4f[fColorCount - 2] != fOrigColors4f[fColorCount - 1]
371 ? fColorCount - 1 : fColorCount - 2;
372 } else {
373 firstStop = 0;
374 lastStop = 1;
375 }
Mike Kleina3771842017-05-04 19:38:48 -0400376
Mike Kleina3771842017-05-04 19:38:48 -0400377 size_t stopCount = 0;
378 float t_l = fOrigPos[firstStop];
379 SkPM4f c_l = prepareColor(firstStop);
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400380 add_const_color(ctx, stopCount++, c_l);
Mike Kleina3771842017-05-04 19:38:48 -0400381 // N.B. lastStop is the index of the last stop, not one after.
382 for (int i = firstStop; i < lastStop; i++) {
383 float t_r = fOrigPos[i + 1];
384 SkPM4f c_r = prepareColor(i + 1);
Florin Malita3e20d022017-11-03 12:11:38 -0400385 SkASSERT(t_l <= t_r);
Mike Kleina3771842017-05-04 19:38:48 -0400386 if (t_l < t_r) {
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400387 init_stop_pos(ctx, stopCount, t_l, t_r, c_l, c_r);
Mike Kleina3771842017-05-04 19:38:48 -0400388 stopCount += 1;
389 }
390 t_l = t_r;
391 c_l = c_r;
392 }
393
Herb Derby4de13042017-05-15 10:49:39 -0400394 ctx->ts[stopCount] = t_l;
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400395 add_const_color(ctx, stopCount++, c_l);
Mike Kleina3771842017-05-04 19:38:48 -0400396
Herb Derby4de13042017-05-15 10:49:39 -0400397 ctx->stopCount = stopCount;
398 p->append(SkRasterPipeline::gradient, ctx);
Mike Kleina3771842017-05-04 19:38:48 -0400399 }
Mike Kleina3771842017-05-04 19:38:48 -0400400 }
401
Mike Reed62ce2ca2018-02-19 14:20:15 -0500402 if (decal_ctx) {
403 p->append(SkRasterPipeline::check_decal_mask, decal_ctx);
404 }
405
Mike Kleina3771842017-05-04 19:38:48 -0400406 if (!premulGrad && !this->colorsAreOpaque()) {
Mike Kleine7598532017-05-11 11:29:29 -0400407 p->append(SkRasterPipeline::premul);
Mike Kleina3771842017-05-04 19:38:48 -0400408 }
409
Florin Malita2e409002017-06-28 14:46:54 -0400410 p->extend(postPipeline);
411
Mike Kleina3771842017-05-04 19:38:48 -0400412 return true;
413}
414
415
rileya@google.com589708b2012-07-26 20:04:23 +0000416bool SkGradientShaderBase::isOpaque() const {
Mike Reed62ce2ca2018-02-19 14:20:15 -0500417 return fColorsAreOpaque && (this->getTileMode() != SkShader::kDecal_TileMode);
418}
419
reed8367b8c2014-08-22 08:30:20 -0700420static unsigned rounded_divide(unsigned numer, unsigned denom) {
421 return (numer + (denom >> 1)) / denom;
422}
423
424bool SkGradientShaderBase::onAsLuminanceColor(SkColor* lum) const {
425 // we just compute an average color.
426 // possibly we could weight this based on the proportional width for each color
427 // assuming they are not evenly distributed in the fPos array.
428 int r = 0;
429 int g = 0;
430 int b = 0;
431 const int n = fColorCount;
Florin Malita39d71de2017-10-31 11:33:49 -0400432 // TODO: use linear colors?
reed8367b8c2014-08-22 08:30:20 -0700433 for (int i = 0; i < n; ++i) {
Florin Malita39d71de2017-10-31 11:33:49 -0400434 SkColor c = this->getLegacyColor(i);
reed8367b8c2014-08-22 08:30:20 -0700435 r += SkColorGetR(c);
436 g += SkColorGetG(c);
437 b += SkColorGetB(c);
438 }
439 *lum = SkColorSetRGB(rounded_divide(r, n), rounded_divide(g, n), rounded_divide(b, n));
440 return true;
441}
442
Florin Malita39d71de2017-10-31 11:33:49 -0400443SkGradientShaderBase::AutoXformColors::AutoXformColors(const SkGradientShaderBase& grad,
444 SkColorSpaceXformer* xformer)
445 : fColors(grad.fColorCount) {
446 // TODO: stay in 4f to preserve precision?
447
448 SkAutoSTMalloc<8, SkColor> origColors(grad.fColorCount);
449 for (int i = 0; i < grad.fColorCount; ++i) {
450 origColors[i] = grad.getLegacyColor(i);
451 }
452
453 xformer->apply(fColors.get(), origColors.get(), grad.fColorCount);
454}
455
Florin Malitad4e9ec82017-10-25 18:00:26 -0400456static constexpr int kGradientTextureSize = 256;
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000457
Florin Malita84d7cf92017-10-25 15:31:54 -0400458void SkGradientShaderBase::initLinearBitmap(SkBitmap* bitmap, GradientBitmapType bitmapType) const {
brianosmand4546092016-09-22 12:31:58 -0700459 const bool interpInPremul = SkToBool(fGradFlags &
460 SkGradientShader::kInterpolateColorsInPremul_Flag);
brianosmand4546092016-09-22 12:31:58 -0700461 SkHalf* pixelsF16 = reinterpret_cast<SkHalf*>(bitmap->getPixels());
Florin Malita84d7cf92017-10-25 15:31:54 -0400462 uint32_t* pixels32 = reinterpret_cast<uint32_t*>(bitmap->getPixels());
brianosmand4546092016-09-22 12:31:58 -0700463
464 typedef std::function<void(const Sk4f&, int)> pixelWriteFn_t;
465
466 pixelWriteFn_t writeF16Pixel = [&](const Sk4f& x, int index) {
467 Sk4h c = SkFloatToHalf_finite_ftz(x);
468 pixelsF16[4*index+0] = c[0];
469 pixelsF16[4*index+1] = c[1];
470 pixelsF16[4*index+2] = c[2];
471 pixelsF16[4*index+3] = c[3];
472 };
473 pixelWriteFn_t writeS32Pixel = [&](const Sk4f& c, int index) {
Florin Malita84d7cf92017-10-25 15:31:54 -0400474 pixels32[index] = Sk4f_toS32(c);
475 };
476 pixelWriteFn_t writeL32Pixel = [&](const Sk4f& c, int index) {
477 pixels32[index] = Sk4f_toL32(c);
brianosmand4546092016-09-22 12:31:58 -0700478 };
479
480 pixelWriteFn_t writeSizedPixel =
Florin Malita84d7cf92017-10-25 15:31:54 -0400481 (bitmapType == GradientBitmapType::kHalfFloat) ? writeF16Pixel :
482 (bitmapType == GradientBitmapType::kSRGB ) ? writeS32Pixel : writeL32Pixel;
brianosmand4546092016-09-22 12:31:58 -0700483 pixelWriteFn_t writeUnpremulPixel = [&](const Sk4f& c, int index) {
484 writeSizedPixel(c * Sk4f(c[3], c[3], c[3], 1.0f), index);
485 };
486
487 pixelWriteFn_t writePixel = interpInPremul ? writeSizedPixel : writeUnpremulPixel;
488
Florin Malita84d7cf92017-10-25 15:31:54 -0400489 // When not in legacy mode, we just want the original 4f colors - so we pass in
490 // our own CS for identity/no transform.
491 auto* cs = bitmapType != GradientBitmapType::kLegacy ? fColorSpace.get() : nullptr;
492
brianosmand4546092016-09-22 12:31:58 -0700493 int prevIndex = 0;
494 for (int i = 1; i < fColorCount; i++) {
Florin Malitaed6ae562017-10-28 11:06:48 -0400495 // Historically, stops have been mapped to [0, 256], with 256 then nudged to the
496 // next smaller value, then truncate for the texture index. This seems to produce
497 // the best results for some common distributions, so we preserve the behavior.
498 int nextIndex = SkTMin(this->getPos(i) * kGradientTextureSize,
499 SkIntToScalar(kGradientTextureSize - 1));
brianosmand4546092016-09-22 12:31:58 -0700500
501 if (nextIndex > prevIndex) {
Florin Malita84d7cf92017-10-25 15:31:54 -0400502 SkColor4f color0 = this->getXformedColor(i - 1, cs),
503 color1 = this->getXformedColor(i , cs);
504 Sk4f c0 = Sk4f::Load(color0.vec()),
505 c1 = Sk4f::Load(color1.vec());
506
brianosmand4546092016-09-22 12:31:58 -0700507 if (interpInPremul) {
508 c0 = c0 * Sk4f(c0[3], c0[3], c0[3], 1.0f);
509 c1 = c1 * Sk4f(c1[3], c1[3], c1[3], 1.0f);
510 }
511
512 Sk4f step = Sk4f(1.0f / static_cast<float>(nextIndex - prevIndex));
513 Sk4f delta = (c1 - c0) * step;
514
515 for (int curIndex = prevIndex; curIndex <= nextIndex; ++curIndex) {
516 writePixel(c0, curIndex);
517 c0 += delta;
518 }
519 }
520 prevIndex = nextIndex;
521 }
Florin Malitad4e9ec82017-10-25 18:00:26 -0400522 SkASSERT(prevIndex == kGradientTextureSize - 1);
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000523}
524
Florin Malita0e36b3f2017-06-05 23:33:45 -0400525SkColor4f SkGradientShaderBase::getXformedColor(size_t i, SkColorSpace* dstCS) const {
Florin Malita79363b62017-11-01 15:43:52 -0400526 if (dstCS) {
527 return to_colorspace(fOrigColors4f[i], fColorSpace.get(), dstCS);
528 }
529
530 // Legacy/srgb color.
Florin Malita79363b62017-11-01 15:43:52 -0400531 // We quantize upfront to ensure stable SkColor round-trips.
532 auto rgb255 = sk_linear_to_srgb(Sk4f::Load(fOrigColors4f[i].vec()));
533 auto rgb = SkNx_cast<float>(rgb255) * (1/255.0f);
534 return { rgb[0], rgb[1], rgb[2], fOrigColors4f[i].fA };
Florin Malita0e36b3f2017-06-05 23:33:45 -0400535}
536
reed086eea92016-05-04 17:12:46 -0700537SK_DECLARE_STATIC_MUTEX(gGradientCacheMutex);
rileya@google.com589708b2012-07-26 20:04:23 +0000538/*
539 * Because our caller might rebuild the same (logically the same) gradient
540 * over and over, we'd like to return exactly the same "bitmap" if possible,
541 * allowing the client to utilize a cache of our bitmap (e.g. with a GPU).
542 * To do that, we maintain a private cache of built-bitmaps, based on our
Brian Osmanfe3e8582017-10-20 11:27:49 -0400543 * colors and positions.
rileya@google.com589708b2012-07-26 20:04:23 +0000544 */
brianosmand4546092016-09-22 12:31:58 -0700545void SkGradientShaderBase::getGradientTableBitmap(SkBitmap* bitmap,
546 GradientBitmapType bitmapType) const {
brianosmand4546092016-09-22 12:31:58 -0700547 // build our key: [numColors + colors[] + {positions[]} + flags + colorType ]
Florin Malita39d71de2017-10-31 11:33:49 -0400548 static_assert(sizeof(SkColor4f) % sizeof(int32_t) == 0, "");
549 const int colorsAsIntCount = fColorCount * sizeof(SkColor4f) / sizeof(int32_t);
550 int count = 1 + colorsAsIntCount + 1 + 1;
rileya@google.com589708b2012-07-26 20:04:23 +0000551 if (fColorCount > 2) {
Florin Malitacad3b8c2017-10-28 21:42:50 -0400552 count += fColorCount - 1;
rileya@google.com589708b2012-07-26 20:04:23 +0000553 }
554
Florin Malita39d71de2017-10-31 11:33:49 -0400555 SkAutoSTMalloc<64, int32_t> storage(count);
rileya@google.com589708b2012-07-26 20:04:23 +0000556 int32_t* buffer = storage.get();
557
558 *buffer++ = fColorCount;
Florin Malita39d71de2017-10-31 11:33:49 -0400559 memcpy(buffer, fOrigColors4f, fColorCount * sizeof(SkColor4f));
560 buffer += colorsAsIntCount;
rileya@google.com589708b2012-07-26 20:04:23 +0000561 if (fColorCount > 2) {
562 for (int i = 1; i < fColorCount; i++) {
Florin Malitacad3b8c2017-10-28 21:42:50 -0400563 *buffer++ = SkFloat2Bits(this->getPos(i));
rileya@google.com589708b2012-07-26 20:04:23 +0000564 }
565 }
reed@google.com3d3a8602013-05-24 14:58:44 +0000566 *buffer++ = fGradFlags;
brianosmand4546092016-09-22 12:31:58 -0700567 *buffer++ = static_cast<int32_t>(bitmapType);
rileya@google.com589708b2012-07-26 20:04:23 +0000568 SkASSERT(buffer - storage.get() == count);
569
570 ///////////////////////////////////
571
reeda6cac4c2014-08-21 10:50:25 -0700572 static SkGradientBitmapCache* gCache;
brianosmand4546092016-09-22 12:31:58 -0700573 // 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 +0000574 static const int MAX_NUM_CACHED_GRADIENT_BITMAPS = 32;
bungemand6aeb6d2014-07-25 11:52:47 -0700575 SkAutoMutexAcquire ama(gGradientCacheMutex);
rileya@google.com589708b2012-07-26 20:04:23 +0000576
halcanary96fcdcc2015-08-27 07:41:13 -0700577 if (nullptr == gCache) {
halcanary385fe4d2015-08-26 13:07:48 -0700578 gCache = new SkGradientBitmapCache(MAX_NUM_CACHED_GRADIENT_BITMAPS);
rileya@google.com589708b2012-07-26 20:04:23 +0000579 }
580 size_t size = count * sizeof(int32_t);
581
582 if (!gCache->find(storage.get(), size, bitmap)) {
Florin Malitad4e9ec82017-10-25 18:00:26 -0400583 // For these cases we use the bitmap cache, but not the GradientShaderCache. So just
584 // allocate and populate the bitmap's data directly.
Florin Malita63376532017-10-24 10:56:52 -0400585
Florin Malitad4e9ec82017-10-25 18:00:26 -0400586 SkImageInfo info;
587 switch (bitmapType) {
588 case GradientBitmapType::kLegacy:
589 info = SkImageInfo::Make(kGradientTextureSize, 1, kRGBA_8888_SkColorType,
590 kPremul_SkAlphaType);
591 break;
592 case GradientBitmapType::kSRGB:
593 info = SkImageInfo::Make(kGradientTextureSize, 1, kRGBA_8888_SkColorType,
594 kPremul_SkAlphaType, SkColorSpace::MakeSRGB());
595 break;
596 case GradientBitmapType::kHalfFloat:
597 info = SkImageInfo::Make(kGradientTextureSize, 1, kRGBA_F16_SkColorType,
598 kPremul_SkAlphaType, SkColorSpace::MakeSRGBLinear());
599 break;
brianosmand4546092016-09-22 12:31:58 -0700600 }
Florin Malitad4e9ec82017-10-25 18:00:26 -0400601
602 bitmap->allocPixels(info);
603 this->initLinearBitmap(bitmap, bitmapType);
Robert Phillips7a926392018-02-01 15:49:54 -0500604 bitmap->setImmutable();
rileya@google.com589708b2012-07-26 20:04:23 +0000605 gCache->add(storage.get(), size, *bitmap);
606 }
607}
608
Florin Malita5f379a82017-10-18 16:22:35 -0400609void SkGradientShaderBase::commonAsAGradient(GradientInfo* info) const {
rileya@google.com589708b2012-07-26 20:04:23 +0000610 if (info) {
611 if (info->fColorCount >= fColorCount) {
612 if (info->fColors) {
Florin Malita39d71de2017-10-31 11:33:49 -0400613 for (int i = 0; i < fColorCount; ++i) {
614 info->fColors[i] = this->getLegacyColor(i);
615 }
rileya@google.com589708b2012-07-26 20:04:23 +0000616 }
617 if (info->fColorOffsets) {
Florin Malitaed6ae562017-10-28 11:06:48 -0400618 for (int i = 0; i < fColorCount; ++i) {
619 info->fColorOffsets[i] = this->getPos(i);
rileya@google.com589708b2012-07-26 20:04:23 +0000620 }
621 }
622 }
623 info->fColorCount = fColorCount;
624 info->fTileMode = fTileMode;
reed@google.com3d3a8602013-05-24 14:58:44 +0000625 info->fGradientFlags = fGradFlags;
rileya@google.com589708b2012-07-26 20:04:23 +0000626 }
627}
628
robertphillips@google.com76f9e932013-01-15 20:17:47 +0000629void SkGradientShaderBase::toString(SkString* str) const {
630
631 str->appendf("%d colors: ", fColorCount);
632
633 for (int i = 0; i < fColorCount; ++i) {
Florin Malita39d71de2017-10-31 11:33:49 -0400634 str->appendHex(this->getLegacyColor(i), 8);
robertphillips@google.com76f9e932013-01-15 20:17:47 +0000635 if (i < fColorCount-1) {
636 str->append(", ");
637 }
638 }
639
640 if (fColorCount > 2) {
641 str->append(" points: (");
642 for (int i = 0; i < fColorCount; ++i) {
Florin Malitaed6ae562017-10-28 11:06:48 -0400643 str->appendScalar(this->getPos(i));
robertphillips@google.com76f9e932013-01-15 20:17:47 +0000644 if (i < fColorCount-1) {
645 str->append(", ");
646 }
647 }
648 str->append(")");
649 }
650
651 static const char* gTileModeName[SkShader::kTileModeCount] = {
Mike Reeddfc0e912018-02-16 12:40:18 -0500652 "clamp", "repeat", "mirror", "decal",
robertphillips@google.com76f9e932013-01-15 20:17:47 +0000653 };
654
655 str->append(" ");
656 str->append(gTileModeName[fTileMode]);
657
robertphillips@google.com76f9e932013-01-15 20:17:47 +0000658 this->INHERITED::toString(str);
659}
robertphillips@google.com76f9e932013-01-15 20:17:47 +0000660
rileya@google.com589708b2012-07-26 20:04:23 +0000661///////////////////////////////////////////////////////////////////////////////
662///////////////////////////////////////////////////////////////////////////////
663
reed1b747302015-01-06 07:13:19 -0800664// Return true if these parameters are valid/legal/safe to construct a gradient
665//
brianosmane25d71c2016-09-28 11:27:28 -0700666static bool valid_grad(const SkColor4f colors[], const SkScalar pos[], int count,
667 unsigned tileMode) {
halcanary96fcdcc2015-08-27 07:41:13 -0700668 return nullptr != colors && count >= 1 && tileMode < (unsigned)SkShader::kTileModeCount;
reed1b747302015-01-06 07:13:19 -0800669}
670
reed@google.com437d6eb2013-05-23 19:03:05 +0000671static void desc_init(SkGradientShaderBase::Descriptor* desc,
brianosmane25d71c2016-09-28 11:27:28 -0700672 const SkColor4f colors[], sk_sp<SkColorSpace> colorSpace,
673 const SkScalar pos[], int colorCount,
reedaddf2ed2014-08-11 08:28:24 -0700674 SkShader::TileMode mode, uint32_t flags, const SkMatrix* localMatrix) {
fmalita748d6202016-05-11 11:39:58 -0700675 SkASSERT(colorCount > 1);
676
commit-bot@chromium.org6c5aea22014-04-22 16:25:15 +0000677 desc->fColors = colors;
brianosmane25d71c2016-09-28 11:27:28 -0700678 desc->fColorSpace = std::move(colorSpace);
commit-bot@chromium.org6c5aea22014-04-22 16:25:15 +0000679 desc->fPos = pos;
680 desc->fCount = colorCount;
681 desc->fTileMode = mode;
commit-bot@chromium.org6c5aea22014-04-22 16:25:15 +0000682 desc->fGradFlags = flags;
reedaddf2ed2014-08-11 08:28:24 -0700683 desc->fLocalMatrix = localMatrix;
reed@google.com437d6eb2013-05-23 19:03:05 +0000684}
685
brianosmane25d71c2016-09-28 11:27:28 -0700686// assumes colors is SkColor4f* and pos is SkScalar*
fmenozzie9fd0f82016-08-19 07:50:57 -0700687#define EXPAND_1_COLOR(count) \
brianosmane25d71c2016-09-28 11:27:28 -0700688 SkColor4f tmp[2]; \
fmenozzie9fd0f82016-08-19 07:50:57 -0700689 do { \
690 if (1 == count) { \
691 tmp[0] = tmp[1] = colors[0]; \
692 colors = tmp; \
693 pos = nullptr; \
694 count = 2; \
695 } \
696 } while (0)
697
fmenozzi68d952c2016-08-19 08:56:56 -0700698struct ColorStopOptimizer {
brianosmane25d71c2016-09-28 11:27:28 -0700699 ColorStopOptimizer(const SkColor4f* colors, const SkScalar* pos,
fmenozzi68d952c2016-08-19 08:56:56 -0700700 int count, SkShader::TileMode mode)
701 : fColors(colors)
702 , fPos(pos)
703 , fCount(count) {
704
705 if (!pos || count != 3) {
706 return;
707 }
708
709 if (SkScalarNearlyEqual(pos[0], 0.0f) &&
710 SkScalarNearlyEqual(pos[1], 0.0f) &&
711 SkScalarNearlyEqual(pos[2], 1.0f)) {
712
713 if (SkShader::kRepeat_TileMode == mode ||
714 SkShader::kMirror_TileMode == mode ||
715 colors[0] == colors[1]) {
716
fmalita582a6562016-08-22 06:28:57 -0700717 // Ignore the leftmost color/pos.
718 fColors += 1;
719 fPos += 1;
720 fCount = 2;
fmenozzi68d952c2016-08-19 08:56:56 -0700721 }
722 } else if (SkScalarNearlyEqual(pos[0], 0.0f) &&
723 SkScalarNearlyEqual(pos[1], 1.0f) &&
724 SkScalarNearlyEqual(pos[2], 1.0f)) {
725
726 if (SkShader::kRepeat_TileMode == mode ||
727 SkShader::kMirror_TileMode == mode ||
728 colors[1] == colors[2]) {
729
fmalita582a6562016-08-22 06:28:57 -0700730 // Ignore the rightmost color/pos.
fmenozzi68d952c2016-08-19 08:56:56 -0700731 fCount = 2;
732 }
733 }
734 }
735
brianosmane25d71c2016-09-28 11:27:28 -0700736 const SkColor4f* fColors;
737 const SkScalar* fPos;
738 int fCount;
739};
740
741struct ColorConverter {
742 ColorConverter(const SkColor* colors, int count) {
743 for (int i = 0; i < count; ++i) {
744 fColors4f.push_back(SkColor4f::FromColor(colors[i]));
745 }
746 }
747
748 SkSTArray<2, SkColor4f, true> fColors4f;
fmenozzi68d952c2016-08-19 08:56:56 -0700749};
750
reed8a21c9f2016-03-08 18:50:00 -0800751sk_sp<SkShader> SkGradientShader::MakeLinear(const SkPoint pts[2],
fmenozzi68d952c2016-08-19 08:56:56 -0700752 const SkColor colors[],
753 const SkScalar pos[], int colorCount,
754 SkShader::TileMode mode,
755 uint32_t flags,
756 const SkMatrix* localMatrix) {
brianosmane25d71c2016-09-28 11:27:28 -0700757 ColorConverter converter(colors, colorCount);
758 return MakeLinear(pts, converter.fColors4f.begin(), nullptr, pos, colorCount, mode, flags,
759 localMatrix);
760}
761
762sk_sp<SkShader> SkGradientShader::MakeLinear(const SkPoint pts[2],
763 const SkColor4f colors[],
764 sk_sp<SkColorSpace> colorSpace,
765 const SkScalar pos[], int colorCount,
766 SkShader::TileMode mode,
767 uint32_t flags,
768 const SkMatrix* localMatrix) {
fmalitac5231042016-08-10 05:45:50 -0700769 if (!pts || !SkScalarIsFinite((pts[1] - pts[0]).length())) {
halcanary96fcdcc2015-08-27 07:41:13 -0700770 return nullptr;
reed1b747302015-01-06 07:13:19 -0800771 }
772 if (!valid_grad(colors, pos, colorCount, mode)) {
halcanary96fcdcc2015-08-27 07:41:13 -0700773 return nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +0000774 }
fmenozzie9fd0f82016-08-19 07:50:57 -0700775 if (1 == colorCount) {
brianosmane25d71c2016-09-28 11:27:28 -0700776 return SkShader::MakeColorShader(colors[0], std::move(colorSpace));
fmenozzie9fd0f82016-08-19 07:50:57 -0700777 }
Florin Malita8d3ffad2017-02-03 18:21:17 +0000778 if (localMatrix && !localMatrix->invert(nullptr)) {
779 return nullptr;
780 }
rileya@google.com589708b2012-07-26 20:04:23 +0000781
fmenozzi68d952c2016-08-19 08:56:56 -0700782 ColorStopOptimizer opt(colors, pos, colorCount, mode);
783
reed@google.com437d6eb2013-05-23 19:03:05 +0000784 SkGradientShaderBase::Descriptor desc;
brianosmane25d71c2016-09-28 11:27:28 -0700785 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
786 localMatrix);
reed8a21c9f2016-03-08 18:50:00 -0800787 return sk_make_sp<SkLinearGradient>(pts, desc);
rileya@google.com589708b2012-07-26 20:04:23 +0000788}
789
reed8a21c9f2016-03-08 18:50:00 -0800790sk_sp<SkShader> SkGradientShader::MakeRadial(const SkPoint& center, SkScalar radius,
brianosmane25d71c2016-09-28 11:27:28 -0700791 const SkColor colors[],
792 const SkScalar pos[], int colorCount,
793 SkShader::TileMode mode,
794 uint32_t flags,
795 const SkMatrix* localMatrix) {
796 ColorConverter converter(colors, colorCount);
797 return MakeRadial(center, radius, converter.fColors4f.begin(), nullptr, pos, colorCount, mode,
798 flags, localMatrix);
799}
800
801sk_sp<SkShader> SkGradientShader::MakeRadial(const SkPoint& center, SkScalar radius,
802 const SkColor4f colors[],
803 sk_sp<SkColorSpace> colorSpace,
804 const SkScalar pos[], int colorCount,
805 SkShader::TileMode mode,
806 uint32_t flags,
807 const SkMatrix* localMatrix) {
reed1b747302015-01-06 07:13:19 -0800808 if (radius <= 0) {
halcanary96fcdcc2015-08-27 07:41:13 -0700809 return nullptr;
reed1b747302015-01-06 07:13:19 -0800810 }
811 if (!valid_grad(colors, pos, colorCount, mode)) {
halcanary96fcdcc2015-08-27 07:41:13 -0700812 return nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +0000813 }
fmenozzie9fd0f82016-08-19 07:50:57 -0700814 if (1 == colorCount) {
brianosmane25d71c2016-09-28 11:27:28 -0700815 return SkShader::MakeColorShader(colors[0], std::move(colorSpace));
fmenozzie9fd0f82016-08-19 07:50:57 -0700816 }
Florin Malita8d3ffad2017-02-03 18:21:17 +0000817 if (localMatrix && !localMatrix->invert(nullptr)) {
818 return nullptr;
819 }
rileya@google.com589708b2012-07-26 20:04:23 +0000820
fmenozzi68d952c2016-08-19 08:56:56 -0700821 ColorStopOptimizer opt(colors, pos, colorCount, mode);
822
reed@google.com437d6eb2013-05-23 19:03:05 +0000823 SkGradientShaderBase::Descriptor desc;
brianosmane25d71c2016-09-28 11:27:28 -0700824 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
825 localMatrix);
reed8a21c9f2016-03-08 18:50:00 -0800826 return sk_make_sp<SkRadialGradient>(center, radius, desc);
rileya@google.com589708b2012-07-26 20:04:23 +0000827}
828
reed8a21c9f2016-03-08 18:50:00 -0800829sk_sp<SkShader> SkGradientShader::MakeTwoPointConical(const SkPoint& start,
brianosmane25d71c2016-09-28 11:27:28 -0700830 SkScalar startRadius,
831 const SkPoint& end,
832 SkScalar endRadius,
833 const SkColor colors[],
834 const SkScalar pos[],
835 int colorCount,
836 SkShader::TileMode mode,
837 uint32_t flags,
838 const SkMatrix* localMatrix) {
839 ColorConverter converter(colors, colorCount);
840 return MakeTwoPointConical(start, startRadius, end, endRadius, converter.fColors4f.begin(),
841 nullptr, pos, colorCount, mode, flags, localMatrix);
842}
843
844sk_sp<SkShader> SkGradientShader::MakeTwoPointConical(const SkPoint& start,
845 SkScalar startRadius,
846 const SkPoint& end,
847 SkScalar endRadius,
848 const SkColor4f colors[],
849 sk_sp<SkColorSpace> colorSpace,
850 const SkScalar pos[],
851 int colorCount,
852 SkShader::TileMode mode,
853 uint32_t flags,
854 const SkMatrix* localMatrix) {
reed1b747302015-01-06 07:13:19 -0800855 if (startRadius < 0 || endRadius < 0) {
halcanary96fcdcc2015-08-27 07:41:13 -0700856 return nullptr;
reed1b747302015-01-06 07:13:19 -0800857 }
Florin Malita327290f2017-07-07 09:23:16 -0400858 if (SkScalarNearlyZero((start - end).length()) && SkScalarNearlyZero(startRadius)) {
859 // We can treat this gradient as radial, which is faster.
860 return MakeRadial(start, endRadius, colors, std::move(colorSpace), pos, colorCount,
861 mode, flags, localMatrix);
862 }
reed1b747302015-01-06 07:13:19 -0800863 if (!valid_grad(colors, pos, colorCount, mode)) {
halcanary96fcdcc2015-08-27 07:41:13 -0700864 return nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +0000865 }
fmalita5edf82e2016-03-03 06:41:54 -0800866 if (startRadius == endRadius) {
867 if (start == end || startRadius == 0) {
reed8a21c9f2016-03-08 18:50:00 -0800868 return SkShader::MakeEmptyShader();
fmalita5edf82e2016-03-03 06:41:54 -0800869 }
rileya@google.com589708b2012-07-26 20:04:23 +0000870 }
Florin Malita8d3ffad2017-02-03 18:21:17 +0000871 if (localMatrix && !localMatrix->invert(nullptr)) {
872 return nullptr;
873 }
reed6b7a6c72016-08-18 16:13:50 -0700874 EXPAND_1_COLOR(colorCount);
rileya@google.com589708b2012-07-26 20:04:23 +0000875
fmenozzi68d952c2016-08-19 08:56:56 -0700876 ColorStopOptimizer opt(colors, pos, colorCount, mode);
877
reed@google.com437d6eb2013-05-23 19:03:05 +0000878 SkGradientShaderBase::Descriptor desc;
Florin Malita5f379a82017-10-18 16:22:35 -0400879 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
880 localMatrix);
881 return SkTwoPointConicalGradient::Create(start, startRadius, end, endRadius, desc);
rileya@google.com589708b2012-07-26 20:04:23 +0000882}
883
reed8a21c9f2016-03-08 18:50:00 -0800884sk_sp<SkShader> SkGradientShader::MakeSweep(SkScalar cx, SkScalar cy,
brianosmane25d71c2016-09-28 11:27:28 -0700885 const SkColor colors[],
886 const SkScalar pos[],
887 int colorCount,
Florin Malita5a9a9812017-08-01 16:38:08 -0400888 SkShader::TileMode mode,
889 SkScalar startAngle,
890 SkScalar endAngle,
brianosmane25d71c2016-09-28 11:27:28 -0700891 uint32_t flags,
892 const SkMatrix* localMatrix) {
893 ColorConverter converter(colors, colorCount);
Florin Malita5a9a9812017-08-01 16:38:08 -0400894 return MakeSweep(cx, cy, converter.fColors4f.begin(), nullptr, pos, colorCount,
895 mode, startAngle, endAngle, flags, localMatrix);
brianosmane25d71c2016-09-28 11:27:28 -0700896}
897
898sk_sp<SkShader> SkGradientShader::MakeSweep(SkScalar cx, SkScalar cy,
899 const SkColor4f colors[],
900 sk_sp<SkColorSpace> colorSpace,
901 const SkScalar pos[],
902 int colorCount,
Florin Malita5a9a9812017-08-01 16:38:08 -0400903 SkShader::TileMode mode,
904 SkScalar startAngle,
905 SkScalar endAngle,
brianosmane25d71c2016-09-28 11:27:28 -0700906 uint32_t flags,
907 const SkMatrix* localMatrix) {
Florin Malita5a9a9812017-08-01 16:38:08 -0400908 if (!valid_grad(colors, pos, colorCount, mode)) {
halcanary96fcdcc2015-08-27 07:41:13 -0700909 return nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +0000910 }
fmenozzie9fd0f82016-08-19 07:50:57 -0700911 if (1 == colorCount) {
brianosmane25d71c2016-09-28 11:27:28 -0700912 return SkShader::MakeColorShader(colors[0], std::move(colorSpace));
fmenozzie9fd0f82016-08-19 07:50:57 -0700913 }
Florin Malita5a9a9812017-08-01 16:38:08 -0400914 if (startAngle >= endAngle) {
915 return nullptr;
916 }
Florin Malita8d3ffad2017-02-03 18:21:17 +0000917 if (localMatrix && !localMatrix->invert(nullptr)) {
918 return nullptr;
919 }
rileya@google.com589708b2012-07-26 20:04:23 +0000920
Florin Malita5a9a9812017-08-01 16:38:08 -0400921 if (startAngle <= 0 && endAngle >= 360) {
922 // If the t-range includes [0,1], then we can always use clamping (presumably faster).
923 mode = SkShader::kClamp_TileMode;
924 }
fmenozzi68d952c2016-08-19 08:56:56 -0700925
926 ColorStopOptimizer opt(colors, pos, colorCount, mode);
927
reed@google.com437d6eb2013-05-23 19:03:05 +0000928 SkGradientShaderBase::Descriptor desc;
brianosmane25d71c2016-09-28 11:27:28 -0700929 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
930 localMatrix);
Florin Malita5a9a9812017-08-01 16:38:08 -0400931
932 const SkScalar t0 = startAngle / 360,
933 t1 = endAngle / 360;
934
935 return sk_make_sp<SkSweepGradient>(SkPoint::Make(cx, cy), t0, t1, desc);
rileya@google.com589708b2012-07-26 20:04:23 +0000936}
937
938SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_START(SkGradientShader)
939 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkLinearGradient)
940 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkRadialGradient)
941 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkSweepGradient)
rileya@google.com589708b2012-07-26 20:04:23 +0000942 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkTwoPointConicalGradient)
943SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_END
rileya@google.comd7cc6512012-07-27 14:00:39 +0000944
945///////////////////////////////////////////////////////////////////////////////
946
bsalomon@google.comcf8fb1f2012-08-02 14:03:32 +0000947#if SK_SUPPORT_GPU
948
Brian Osman5911a7c2017-10-25 12:52:31 -0400949#include "GrColorSpaceXform.h"
brianosmana6359362016-03-21 06:55:37 -0700950#include "GrContext.h"
Robert Phillips1afd4cd2018-01-08 13:40:32 -0500951#include "GrContextPriv.h"
Brian Salomon94efbf52016-11-29 13:43:05 -0500952#include "GrShaderCaps.h"
ajuma95243eb2016-08-24 08:19:02 -0700953#include "GrTextureStripAtlas.h"
egdanielf5294392015-10-21 07:14:17 -0700954#include "gl/GrGLContext.h"
egdaniel2d721d32015-11-11 13:06:05 -0800955#include "glsl/GrGLSLFragmentShaderBuilder.h"
egdaniel018fb622015-10-28 07:26:40 -0700956#include "glsl/GrGLSLProgramDataManager.h"
egdaniel7ea439b2015-12-03 09:20:44 -0800957#include "glsl/GrGLSLUniformHandler.h"
bsalomon@google.comcf8fb1f2012-08-02 14:03:32 +0000958#include "SkGr.h"
959
fmenozzi55d318d2016-08-09 08:05:57 -0700960void GrGradientEffect::GLSLProcessor::emitUniforms(GrGLSLUniformHandler* uniformHandler,
961 const GrGradientEffect& ge) {
Florin Malita14a8dd72017-11-08 15:46:42 -0500962 switch (ge.fStrategy) {
963 case GrGradientEffect::InterpolationStrategy::kThreshold:
964 case GrGradientEffect::InterpolationStrategy::kThresholdClamp0:
965 case GrGradientEffect::InterpolationStrategy::kThresholdClamp1:
966 fThresholdUni = uniformHandler->addUniform(kFragment_GrShaderFlag,
967 kFloat_GrSLType,
968 kHigh_GrSLPrecision,
969 "Threshold");
970 // fall through
971 case GrGradientEffect::InterpolationStrategy::kSingle:
972 fIntervalsUni = uniformHandler->addUniformArray(kFragment_GrShaderFlag,
973 kHalf4_GrSLType,
974 "Intervals",
975 ge.fIntervals.count());
976 break;
977 case GrGradientEffect::InterpolationStrategy::kTexture:
978 fFSYUni = uniformHandler->addUniform(kFragment_GrShaderFlag, kHalf_GrSLType,
979 "GradientYCoordFS");
980 break;
bsalomon@google.com82d12232013-09-09 15:36:26 +0000981 }
982}
983
fmenozzi55d318d2016-08-09 08:05:57 -0700984void GrGradientEffect::GLSLProcessor::onSetData(const GrGLSLProgramDataManager& pdman,
Brian Salomonab015ef2017-04-04 10:15:51 -0400985 const GrFragmentProcessor& processor) {
joshualittb0a8a372014-09-23 09:50:21 -0700986 const GrGradientEffect& e = processor.cast<GrGradientEffect>();
bsalomon@google.com82d12232013-09-09 15:36:26 +0000987
Florin Malita14a8dd72017-11-08 15:46:42 -0500988 switch (e.fStrategy) {
989 case GrGradientEffect::InterpolationStrategy::kThreshold:
990 case GrGradientEffect::InterpolationStrategy::kThresholdClamp0:
991 case GrGradientEffect::InterpolationStrategy::kThresholdClamp1:
992 pdman.set1f(fThresholdUni, e.fThreshold);
Brian Salomon466ad992016-10-13 16:08:36 -0400993 // fall through
Florin Malita14a8dd72017-11-08 15:46:42 -0500994 case GrGradientEffect::InterpolationStrategy::kSingle:
995 pdman.set4fv(fIntervalsUni, e.fIntervals.count(),
996 reinterpret_cast<const float*>(e.fIntervals.begin()));
fmenozzicd9a1d02016-08-15 07:03:47 -0700997 break;
Florin Malita14a8dd72017-11-08 15:46:42 -0500998 case GrGradientEffect::InterpolationStrategy::kTexture:
999 if (e.fYCoord != fCachedYCoord) {
1000 pdman.set1f(fFSYUni, e.fYCoord);
1001 fCachedYCoord = e.fYCoord;
fmenozzicd9a1d02016-08-15 07:03:47 -07001002 }
1003 break;
rileya@google.comb3e50f22012-08-20 17:43:08 +00001004 }
1005}
1006
Florin Malitae657dc82017-11-03 08:46:18 -04001007void GrGradientEffect::onGetGLSLProcessorKey(const GrShaderCaps&, GrProcessorKeyBuilder* b) const {
1008 b->add32(GLSLProcessor::GenBaseGradientKey(*this));
1009}
1010
fmenozzi55d318d2016-08-09 08:05:57 -07001011uint32_t GrGradientEffect::GLSLProcessor::GenBaseGradientKey(const GrProcessor& processor) {
joshualittb0a8a372014-09-23 09:50:21 -07001012 const GrGradientEffect& e = processor.cast<GrGradientEffect>();
skia.committer@gmail.com9a070f22013-09-10 07:01:44 +00001013
Florin Malita14a8dd72017-11-08 15:46:42 -05001014 // Build a key using the following bit allocation:
1015 static constexpr uint32_t kStrategyBits = 3;
1016 static constexpr uint32_t kPremulBits = 1;
1017 SkDEBUGCODE(static constexpr uint32_t kWrapModeBits = 2;)
bsalomon@google.com82d12232013-09-09 15:36:26 +00001018
Florin Malita14a8dd72017-11-08 15:46:42 -05001019 uint32_t key = static_cast<uint32_t>(e.fStrategy);
1020 SkASSERT(key < (1 << kStrategyBits));
1021
1022 // This is already baked into the table for texture gradients,
1023 // and only changes behavior for analytical gradients.
1024 if (e.fStrategy != InterpolationStrategy::kTexture &&
1025 e.fPremulType == GrGradientEffect::kBeforeInterp_PremulType) {
1026 key |= 1 << kStrategyBits;
1027 SkASSERT(key < (1 << (kStrategyBits + kPremulBits)));
bsalomon@google.com82d12232013-09-09 15:36:26 +00001028 }
1029
Florin Malita14a8dd72017-11-08 15:46:42 -05001030 key |= static_cast<uint32_t>(e.fWrapMode) << (kStrategyBits + kPremulBits);
1031 SkASSERT(key < (1 << (kStrategyBits + kPremulBits + kWrapModeBits)));
fmenozzicd9a1d02016-08-15 07:03:47 -07001032
bsalomon@google.com82d12232013-09-09 15:36:26 +00001033 return key;
bsalomon@google.comd8b5fac2012-11-01 17:02:46 +00001034}
1035
Florin Malitab81a8b92017-08-08 12:14:17 -04001036void GrGradientEffect::GLSLProcessor::emitAnalyticalColor(GrGLSLFPFragmentBuilder* fragBuilder,
1037 GrGLSLUniformHandler* uniformHandler,
1038 const GrShaderCaps* shaderCaps,
1039 const GrGradientEffect& ge,
1040 const char* t,
1041 const char* outputColor,
1042 const char* inputColor) {
1043 // First, apply tiling rules.
Brian Salomon2bbdcc42017-09-07 12:36:34 -04001044 switch (ge.fWrapMode) {
1045 case GrSamplerState::WrapMode::kClamp:
Florin Malita14a8dd72017-11-08 15:46:42 -05001046 switch (ge.fStrategy) {
1047 case GrGradientEffect::InterpolationStrategy::kThresholdClamp0:
1048 // allow t > 1, in order to hit the clamp interval (1, inf)
1049 fragBuilder->codeAppendf("half tiled_t = max(%s, 0.0);", t);
1050 break;
1051 case GrGradientEffect::InterpolationStrategy::kThresholdClamp1:
1052 // allow t < 0, in order to hit the clamp interval (-inf, 0)
1053 fragBuilder->codeAppendf("half tiled_t = min(%s, 1.0);", t);
1054 break;
1055 default:
1056 // regular [0, 1] clamping
1057 fragBuilder->codeAppendf("half tiled_t = clamp(%s, 0.0, 1.0);", t);
1058 }
Brian Salomon2bbdcc42017-09-07 12:36:34 -04001059 break;
1060 case GrSamplerState::WrapMode::kRepeat:
Florin Malita14a8dd72017-11-08 15:46:42 -05001061 fragBuilder->codeAppendf("half tiled_t = fract(%s);", t);
Brian Salomon2bbdcc42017-09-07 12:36:34 -04001062 break;
1063 case GrSamplerState::WrapMode::kMirrorRepeat:
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001064 fragBuilder->codeAppendf("half t_1 = %s - 1.0;", t);
Greg Daniel10ed2432017-12-01 16:19:43 -05001065 fragBuilder->codeAppendf("half tiled_t = t_1 - 2.0 * floor(t_1 * 0.5) - 1.0;");
1066 if (shaderCaps->mustDoOpBetweenFloorAndAbs()) {
1067 // At this point the expected value of tiled_t should between -1 and 1, so this
1068 // clamp has no effect other than to break up the floor and abs calls and make sure
1069 // the compiler doesn't merge them back together.
1070 fragBuilder->codeAppendf("tiled_t = clamp(tiled_t, -1.0, 1.0);");
1071 }
1072 fragBuilder->codeAppendf("tiled_t = abs(tiled_t);");
Brian Salomon2bbdcc42017-09-07 12:36:34 -04001073 break;
Florin Malita8a0044f2017-08-07 14:38:22 -04001074 }
Florin Malita8a0044f2017-08-07 14:38:22 -04001075
Florin Malitab81a8b92017-08-08 12:14:17 -04001076 // Calculate the color.
Florin Malita14a8dd72017-11-08 15:46:42 -05001077 const char* intervals = uniformHandler->getUniformCStr(fIntervalsUni);
fmenozzicd9a1d02016-08-15 07:03:47 -07001078
Florin Malita14a8dd72017-11-08 15:46:42 -05001079 switch (ge.fStrategy) {
1080 case GrGradientEffect::InterpolationStrategy::kSingle:
1081 SkASSERT(ge.fIntervals.count() == 2);
1082 fragBuilder->codeAppendf(
1083 "half4 color_scale = %s[0],"
1084 " color_bias = %s[1];"
1085 , intervals, intervals
1086 );
fmenozzicd9a1d02016-08-15 07:03:47 -07001087 break;
Florin Malita14a8dd72017-11-08 15:46:42 -05001088 case GrGradientEffect::InterpolationStrategy::kThreshold:
1089 case GrGradientEffect::InterpolationStrategy::kThresholdClamp0:
1090 case GrGradientEffect::InterpolationStrategy::kThresholdClamp1:
1091 {
1092 SkASSERT(ge.fIntervals.count() == 4);
1093 const char* threshold = uniformHandler->getUniformCStr(fThresholdUni);
1094 fragBuilder->codeAppendf(
1095 "half4 color_scale, color_bias;"
1096 "if (tiled_t < %s) {"
1097 " color_scale = %s[0];"
1098 " color_bias = %s[1];"
1099 "} else {"
1100 " color_scale = %s[2];"
1101 " color_bias = %s[3];"
1102 "}"
1103 , threshold, intervals, intervals, intervals, intervals
1104 );
1105 } break;
Florin Malitab81a8b92017-08-08 12:14:17 -04001106 default:
1107 SkASSERT(false);
fmenozzicd9a1d02016-08-15 07:03:47 -07001108 break;
bsalomon@google.com82d12232013-09-09 15:36:26 +00001109 }
Florin Malitab81a8b92017-08-08 12:14:17 -04001110
Florin Malita14a8dd72017-11-08 15:46:42 -05001111 fragBuilder->codeAppend("half4 colorTemp = tiled_t * color_scale + color_bias;");
1112
Brian Osmanfe3e8582017-10-20 11:27:49 -04001113 // We could skip this step if all colors are known to be opaque. Two considerations:
Florin Malitab81a8b92017-08-08 12:14:17 -04001114 // The gradient SkShader reporting opaque is more restrictive than necessary in the two
1115 // pt case. Make sure the key reflects this optimization (and note that it can use the
Brian Osmanfe3e8582017-10-20 11:27:49 -04001116 // same shader as the kBeforeInterp case).
Florin Malita14a8dd72017-11-08 15:46:42 -05001117 if (ge.fPremulType == GrGradientEffect::kAfterInterp_PremulType) {
Florin Malitab81a8b92017-08-08 12:14:17 -04001118 fragBuilder->codeAppend("colorTemp.rgb *= colorTemp.a;");
1119 }
Brian Osman5911a7c2017-10-25 12:52:31 -04001120
1121 // 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 -04001122 // range. The simplest solution is to always clamp our (premul) value here. We only need to
1123 // clamp RGB, but that causes hangs on the Tegra3 Nexus7. Clamping RGBA avoids the problem.
1124 fragBuilder->codeAppend("colorTemp = clamp(colorTemp, 0, colorTemp.a);");
Florin Malitab81a8b92017-08-08 12:14:17 -04001125
1126 fragBuilder->codeAppendf("%s = %s * colorTemp;", outputColor, inputColor);
1127}
1128
1129void GrGradientEffect::GLSLProcessor::emitColor(GrGLSLFPFragmentBuilder* fragBuilder,
1130 GrGLSLUniformHandler* uniformHandler,
1131 const GrShaderCaps* shaderCaps,
1132 const GrGradientEffect& ge,
1133 const char* gradientTValue,
1134 const char* outputColor,
1135 const char* inputColor,
1136 const TextureSamplers& texSamplers) {
Florin Malita14a8dd72017-11-08 15:46:42 -05001137 if (ge.fStrategy != InterpolationStrategy::kTexture) {
Florin Malitab81a8b92017-08-08 12:14:17 -04001138 this->emitAnalyticalColor(fragBuilder, uniformHandler, shaderCaps, ge, gradientTValue,
1139 outputColor, inputColor);
1140 return;
1141 }
1142
Florin Malitab81a8b92017-08-08 12:14:17 -04001143 const char* fsyuni = uniformHandler->getUniformCStr(fFSYUni);
1144
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001145 fragBuilder->codeAppendf("half2 coord = half2(%s, %s);", gradientTValue, fsyuni);
Florin Malitab81a8b92017-08-08 12:14:17 -04001146 fragBuilder->codeAppendf("%s = ", outputColor);
1147 fragBuilder->appendTextureLookupAndModulate(inputColor, texSamplers[0], "coord",
Brian Osman5911a7c2017-10-25 12:52:31 -04001148 kFloat2_GrSLType);
Florin Malitab81a8b92017-08-08 12:14:17 -04001149 fragBuilder->codeAppend(";");
rileya@google.comd7cc6512012-07-27 14:00:39 +00001150}
1151
1152/////////////////////////////////////////////////////////////////////
1153
Brian Salomon587e08f2017-01-27 10:59:27 -05001154inline GrFragmentProcessor::OptimizationFlags GrGradientEffect::OptFlags(bool isOpaque) {
Brian Salomonf3b995b2017-02-15 10:22:23 -05001155 return isOpaque
1156 ? kPreservesOpaqueInput_OptimizationFlag |
1157 kCompatibleWithCoverageAsAlpha_OptimizationFlag
1158 : kCompatibleWithCoverageAsAlpha_OptimizationFlag;
Brian Salomon587e08f2017-01-27 10:59:27 -05001159}
1160
Florin Malita14a8dd72017-11-08 15:46:42 -05001161void GrGradientEffect::addInterval(const SkGradientShaderBase& shader, size_t idx0, size_t idx1,
1162 SkColorSpace* dstCS) {
1163 SkASSERT(idx0 <= idx1);
1164 const auto c4f0 = shader.getXformedColor(idx0, dstCS),
1165 c4f1 = shader.getXformedColor(idx1, dstCS);
1166 const auto c0 = (fPremulType == kBeforeInterp_PremulType)
1167 ? c4f0.premul().to4f() : Sk4f::Load(c4f0.vec()),
1168 c1 = (fPremulType == kBeforeInterp_PremulType)
1169 ? c4f1.premul().to4f() : Sk4f::Load(c4f1.vec());
1170 const auto t0 = shader.getPos(idx0),
1171 t1 = shader.getPos(idx1),
1172 dt = t1 - t0;
1173 SkASSERT(dt >= 0);
1174 // dt can be 0 for clamp intervals => in this case we want a scale == 0
1175 const auto scale = SkScalarNearlyZero(dt) ? 0 : (c1 - c0) / dt,
1176 bias = c0 - t0 * scale;
1177
1178 // Intervals are stored as (scale, bias) tuples.
1179 SkASSERT(!(fIntervals.count() & 1));
1180 fIntervals.emplace_back(scale[0], scale[1], scale[2], scale[3]);
1181 fIntervals.emplace_back( bias[0], bias[1], bias[2], bias[3]);
1182}
1183
Ethan Nicholasabff9562017-10-09 10:54:08 -04001184GrGradientEffect::GrGradientEffect(ClassID classID, const CreateArgs& args, bool isOpaque)
Florin Malita14a8dd72017-11-08 15:46:42 -05001185 : INHERITED(classID, OptFlags(isOpaque))
1186 , fWrapMode(args.fWrapMode)
1187 , fRow(-1)
1188 , fIsOpaque(args.fShader->isOpaque())
1189 , fStrategy(InterpolationStrategy::kTexture)
1190 , fThreshold(0) {
1191
brianosman9557c272016-09-15 06:59:15 -07001192 const SkGradientShaderBase& shader(*args.fShader);
bsalomon@google.com82d12232013-09-09 15:36:26 +00001193
Florin Malita14a8dd72017-11-08 15:46:42 -05001194 fPremulType = (args.fShader->getGradFlags() & SkGradientShader::kInterpolateColorsInPremul_Flag)
1195 ? kBeforeInterp_PremulType : kAfterInterp_PremulType;
bsalomon@google.com371e1052013-01-11 21:08:55 +00001196
Florin Malita14a8dd72017-11-08 15:46:42 -05001197 // First, determine the interpolation strategy and params.
1198 switch (shader.fColorCount) {
1199 case 2:
1200 SkASSERT(!shader.fOrigPos);
1201 fStrategy = InterpolationStrategy::kSingle;
1202 this->addInterval(shader, 0, 1, args.fDstColorSpace);
1203 break;
1204 case 3:
1205 fThreshold = shader.getPos(1);
bsalomon@google.com1ce49fc2012-09-18 14:14:49 +00001206
Florin Malita14a8dd72017-11-08 15:46:42 -05001207 if (shader.fOrigPos) {
1208 SkASSERT(SkScalarNearlyEqual(shader.fOrigPos[0], 0));
1209 SkASSERT(SkScalarNearlyEqual(shader.fOrigPos[2], 1));
1210 if (SkScalarNearlyEqual(shader.fOrigPos[1], 0)) {
1211 // hard stop on the left edge.
1212 if (fWrapMode == GrSamplerState::WrapMode::kClamp) {
1213 fStrategy = InterpolationStrategy::kThresholdClamp1;
1214 // Clamp interval (scale == 0, bias == colors[0]).
1215 this->addInterval(shader, 0, 0, args.fDstColorSpace);
1216 } else {
1217 // We can ignore the hard stop when not clamping.
1218 fStrategy = InterpolationStrategy::kSingle;
1219 }
1220 this->addInterval(shader, 1, 2, args.fDstColorSpace);
1221 break;
1222 }
Brian Osmand43f7b62017-10-19 15:42:01 -04001223
Florin Malita14a8dd72017-11-08 15:46:42 -05001224 if (SkScalarNearlyEqual(shader.fOrigPos[1], 1)) {
1225 // hard stop on the right edge.
1226 this->addInterval(shader, 0, 1, args.fDstColorSpace);
1227 if (fWrapMode == GrSamplerState::WrapMode::kClamp) {
1228 fStrategy = InterpolationStrategy::kThresholdClamp0;
1229 // Clamp interval (scale == 0, bias == colors[2]).
1230 this->addInterval(shader, 2, 2, args.fDstColorSpace);
1231 } else {
1232 // We can ignore the hard stop when not clamping.
1233 fStrategy = InterpolationStrategy::kSingle;
1234 }
1235 break;
1236 }
Brian Osmand43f7b62017-10-19 15:42:01 -04001237 }
1238
Florin Malita14a8dd72017-11-08 15:46:42 -05001239 // Two arbitrary interpolation intervals.
1240 fStrategy = InterpolationStrategy::kThreshold;
1241 this->addInterval(shader, 0, 1, args.fDstColorSpace);
1242 this->addInterval(shader, 1, 2, args.fDstColorSpace);
1243 break;
1244 case 4:
1245 if (shader.fOrigPos && SkScalarNearlyEqual(shader.fOrigPos[1], shader.fOrigPos[2])) {
1246 SkASSERT(SkScalarNearlyEqual(shader.fOrigPos[0], 0));
1247 SkASSERT(SkScalarNearlyEqual(shader.fOrigPos[3], 1));
fmenozzi2a495912016-08-12 06:33:52 -07001248
Florin Malita14a8dd72017-11-08 15:46:42 -05001249 // Single hard stop => two arbitrary interpolation intervals.
1250 fStrategy = InterpolationStrategy::kThreshold;
1251 fThreshold = shader.getPos(1);
1252 this->addInterval(shader, 0, 1, args.fDstColorSpace);
1253 this->addInterval(shader, 2, 3, args.fDstColorSpace);
1254 }
1255 break;
1256 default:
1257 break;
fmenozzi2a495912016-08-12 06:33:52 -07001258 }
fmenozzicd9a1d02016-08-15 07:03:47 -07001259
Florin Malita14a8dd72017-11-08 15:46:42 -05001260 // Now that we've locked down a strategy, adjust any dependent params.
1261 if (fStrategy != InterpolationStrategy::kTexture) {
1262 // Analytical cases.
1263 fCoordTransform.reset(*args.fMatrix);
1264 } else {
1265 SkGradientShaderBase::GradientBitmapType bitmapType =
1266 SkGradientShaderBase::GradientBitmapType::kLegacy;
Brian Salomonc7fe0f72018-05-11 10:14:21 -04001267 auto caps = args.fContext->contextPriv().caps();
Florin Malita14a8dd72017-11-08 15:46:42 -05001268 if (args.fDstColorSpace) {
1269 // Try to use F16 if we can
Brian Salomonc7fe0f72018-05-11 10:14:21 -04001270 if (caps->isConfigTexturable(kRGBA_half_GrPixelConfig)) {
Florin Malita14a8dd72017-11-08 15:46:42 -05001271 bitmapType = SkGradientShaderBase::GradientBitmapType::kHalfFloat;
Brian Salomonc7fe0f72018-05-11 10:14:21 -04001272 } else if (caps->isConfigTexturable(kSRGBA_8888_GrPixelConfig)) {
Florin Malita14a8dd72017-11-08 15:46:42 -05001273 bitmapType = SkGradientShaderBase::GradientBitmapType::kSRGB;
fmenozzicd9a1d02016-08-15 07:03:47 -07001274 } else {
Florin Malita14a8dd72017-11-08 15:46:42 -05001275 // This can happen, but only if someone explicitly creates an unsupported
1276 // (eg sRGB) surface. Just fall back to legacy behavior.
fmenozzicd9a1d02016-08-15 07:03:47 -07001277 }
Florin Malita14a8dd72017-11-08 15:46:42 -05001278 }
fmenozzicd9a1d02016-08-15 07:03:47 -07001279
Florin Malita14a8dd72017-11-08 15:46:42 -05001280 SkBitmap bitmap;
1281 shader.getGradientTableBitmap(&bitmap, bitmapType);
1282 SkASSERT(1 == bitmap.height() && SkIsPow2(bitmap.width()));
fmenozzicd9a1d02016-08-15 07:03:47 -07001283
Robert Phillips41a3b872018-03-09 12:00:34 -05001284 auto atlasManager = args.fContext->contextPriv().textureStripAtlasManager();
Florin Malita14a8dd72017-11-08 15:46:42 -05001285
1286 GrTextureStripAtlas::Desc desc;
1287 desc.fWidth = bitmap.width();
1288 desc.fHeight = 32;
Robert Phillips7a926392018-02-01 15:49:54 -05001289 desc.fRowHeight = bitmap.height(); // always 1 here
Brian Salomonc7fe0f72018-05-11 10:14:21 -04001290 desc.fConfig = SkImageInfo2GrPixelConfig(bitmap.info(), *caps);
Robert Phillips96b6d532018-03-19 10:57:42 -04001291 fAtlas = atlasManager->refAtlas(desc);
Florin Malita14a8dd72017-11-08 15:46:42 -05001292 SkASSERT(fAtlas);
1293
1294 // We always filter the gradient table. Each table is one row of a texture, always
1295 // y-clamp.
1296 GrSamplerState samplerState(args.fWrapMode, GrSamplerState::Filter::kBilerp);
1297
Robert Phillips41a3b872018-03-09 12:00:34 -05001298 fRow = fAtlas->lockRow(args.fContext, bitmap);
Florin Malita14a8dd72017-11-08 15:46:42 -05001299 if (-1 != fRow) {
1300 fYCoord = fAtlas->getYOffset(fRow)+SK_ScalarHalf*fAtlas->getNormalizedTexelHeight();
1301 // This is 1/2 places where auto-normalization is disabled
1302 fCoordTransform.reset(*args.fMatrix, fAtlas->asTextureProxyRef().get(), false);
1303 fTextureSampler.reset(fAtlas->asTextureProxyRef(), samplerState);
1304 } else {
1305 // In this instance we know the samplerState state is:
1306 // clampY, bilerp
1307 // and the proxy is:
1308 // exact fit, power of two in both dimensions
1309 // Only the x-tileMode is unknown. However, given all the other knowns we know
Robert Phillips7a926392018-02-01 15:49:54 -05001310 // that GrMakeCachedImageProxy is sufficient (i.e., it won't need to be
Florin Malita14a8dd72017-11-08 15:46:42 -05001311 // extracted to a subset or mipmapped).
Robert Phillips7a926392018-02-01 15:49:54 -05001312
1313 SkASSERT(bitmap.isImmutable());
1314 sk_sp<SkImage> srcImage = SkImage::MakeFromBitmap(bitmap);
1315 if (!srcImage) {
1316 return;
1317 }
1318
1319 sk_sp<GrTextureProxy> proxy = GrMakeCachedImageProxy(
Robert Phillips1afd4cd2018-01-08 13:40:32 -05001320 args.fContext->contextPriv().proxyProvider(),
Robert Phillips7a926392018-02-01 15:49:54 -05001321 std::move(srcImage));
Florin Malita14a8dd72017-11-08 15:46:42 -05001322 if (!proxy) {
1323 SkDebugf("Gradient won't draw. Could not create texture.");
1324 return;
1325 }
1326 // This is 2/2 places where auto-normalization is disabled
1327 fCoordTransform.reset(*args.fMatrix, proxy.get(), false);
1328 fTextureSampler.reset(std::move(proxy), samplerState);
1329 fYCoord = SK_ScalarHalf;
1330 }
1331
1332 this->addTextureSampler(&fTextureSampler);
fmenozzicd9a1d02016-08-15 07:03:47 -07001333 }
1334
bsalomon@google.com77af6802013-10-02 13:04:56 +00001335 this->addCoordTransform(&fCoordTransform);
rileya@google.comd7cc6512012-07-27 14:00:39 +00001336}
1337
Brian Salomonf8480b92017-07-27 15:45:59 -04001338GrGradientEffect::GrGradientEffect(const GrGradientEffect& that)
Ethan Nicholasabff9562017-10-09 10:54:08 -04001339 : INHERITED(that.classID(), OptFlags(that.fIsOpaque))
Florin Malita14a8dd72017-11-08 15:46:42 -05001340 , fIntervals(that.fIntervals)
Brian Salomon2bbdcc42017-09-07 12:36:34 -04001341 , fWrapMode(that.fWrapMode)
Brian Salomonf8480b92017-07-27 15:45:59 -04001342 , fCoordTransform(that.fCoordTransform)
1343 , fTextureSampler(that.fTextureSampler)
1344 , fYCoord(that.fYCoord)
1345 , fAtlas(that.fAtlas)
1346 , fRow(that.fRow)
1347 , fIsOpaque(that.fIsOpaque)
Florin Malita14a8dd72017-11-08 15:46:42 -05001348 , fStrategy(that.fStrategy)
1349 , fThreshold(that.fThreshold)
Brian Salomonf8480b92017-07-27 15:45:59 -04001350 , fPremulType(that.fPremulType) {
1351 this->addCoordTransform(&fCoordTransform);
Florin Malita14a8dd72017-11-08 15:46:42 -05001352 if (fStrategy == InterpolationStrategy::kTexture) {
Brian Salomonf8480b92017-07-27 15:45:59 -04001353 this->addTextureSampler(&fTextureSampler);
1354 }
1355 if (this->useAtlas()) {
1356 fAtlas->lockRow(fRow);
1357 }
1358}
1359
rileya@google.comd7cc6512012-07-27 14:00:39 +00001360GrGradientEffect::~GrGradientEffect() {
rileya@google.comb3e50f22012-08-20 17:43:08 +00001361 if (this->useAtlas()) {
1362 fAtlas->unlockRow(fRow);
rileya@google.comb3e50f22012-08-20 17:43:08 +00001363 }
rileya@google.comd7cc6512012-07-27 14:00:39 +00001364}
1365
bsalomon0e08fc12014-10-15 08:19:04 -07001366bool GrGradientEffect::onIsEqual(const GrFragmentProcessor& processor) const {
fmenozzicd9a1d02016-08-15 07:03:47 -07001367 const GrGradientEffect& ge = processor.cast<GrGradientEffect>();
bsalomon@google.com82d12232013-09-09 15:36:26 +00001368
Florin Malita14a8dd72017-11-08 15:46:42 -05001369 if (fWrapMode != ge.fWrapMode || fStrategy != ge.fStrategy) {
Brian Salomon466ad992016-10-13 16:08:36 -04001370 return false;
1371 }
Florin Malita14a8dd72017-11-08 15:46:42 -05001372
Brian Salomon466ad992016-10-13 16:08:36 -04001373 SkASSERT(this->useAtlas() == ge.useAtlas());
Florin Malita14a8dd72017-11-08 15:46:42 -05001374 if (fStrategy == InterpolationStrategy::kTexture) {
1375 if (fYCoord != ge.fYCoord) {
Brian Salomon466ad992016-10-13 16:08:36 -04001376 return false;
1377 }
1378 } else {
Florin Malita14a8dd72017-11-08 15:46:42 -05001379 if (fThreshold != ge.fThreshold ||
1380 fIntervals != ge.fIntervals ||
1381 fPremulType != ge.fPremulType) {
Brian Salomon466ad992016-10-13 16:08:36 -04001382 return false;
1383 }
bsalomon@google.com82d12232013-09-09 15:36:26 +00001384 }
Brian Osman5911a7c2017-10-25 12:52:31 -04001385 return true;
bsalomon@google.com68b58c92013-01-17 16:50:08 +00001386}
1387
Hal Canary6f6961e2017-01-31 13:50:44 -05001388#if GR_TEST_UTILS
Brian Osman3f748602016-10-03 18:29:03 -04001389GrGradientEffect::RandomGradientParams::RandomGradientParams(SkRandom* random) {
Brian Salomon5d4cd9e2017-02-09 11:16:46 -05001390 // Set color count to min of 2 so that we don't trigger the const color optimization and make
1391 // a non-gradient processor.
1392 fColorCount = random->nextRangeU(2, kMaxRandomGradientColors);
Brian Osmana2196532016-10-17 12:48:13 -04001393 fUseColors4f = random->nextBool();
bsalomon@google.comd4726202012-08-03 14:34:46 +00001394
1395 // if one color, omit stops, otherwise randomly decide whether or not to
Brian Osman3f748602016-10-03 18:29:03 -04001396 if (fColorCount == 1 || (fColorCount >= 2 && random->nextBool())) {
1397 fStops = nullptr;
1398 } else {
1399 fStops = fStopStorage;
bsalomon@google.comd4726202012-08-03 14:34:46 +00001400 }
1401
Brian Osmana2196532016-10-17 12:48:13 -04001402 // if using SkColor4f, attach a random (possibly null) color space (with linear gamma)
1403 if (fUseColors4f) {
1404 fColorSpace = GrTest::TestColorSpace(random);
1405 if (fColorSpace) {
Brian Osman36703d92017-12-12 14:09:31 -05001406 fColorSpace = fColorSpace->makeLinearGamma();
Brian Osmana2196532016-10-17 12:48:13 -04001407 }
1408 }
1409
bsalomon@google.com81712882012-11-01 17:12:34 +00001410 SkScalar stop = 0.f;
Brian Osman3f748602016-10-03 18:29:03 -04001411 for (int i = 0; i < fColorCount; ++i) {
Brian Osmana2196532016-10-17 12:48:13 -04001412 if (fUseColors4f) {
1413 fColors4f[i].fR = random->nextUScalar1();
1414 fColors4f[i].fG = random->nextUScalar1();
1415 fColors4f[i].fB = random->nextUScalar1();
1416 fColors4f[i].fA = random->nextUScalar1();
1417 } else {
1418 fColors[i] = random->nextU();
1419 }
Brian Osman3f748602016-10-03 18:29:03 -04001420 if (fStops) {
1421 fStops[i] = stop;
1422 stop = i < fColorCount - 1 ? stop + random->nextUScalar1() * (1.f - stop) : 1.f;
bsalomon@google.comd4726202012-08-03 14:34:46 +00001423 }
1424 }
Brian Osman3f748602016-10-03 18:29:03 -04001425 fTileMode = static_cast<SkShader::TileMode>(random->nextULessThan(SkShader::kTileModeCount));
bsalomon@google.comd4726202012-08-03 14:34:46 +00001426}
Hal Canary6f6961e2017-01-31 13:50:44 -05001427#endif
bsalomon@google.comd4726202012-08-03 14:34:46 +00001428
bsalomon@google.comcf8fb1f2012-08-02 14:03:32 +00001429#endif