blob: c5894fa189f4e7387a2d2a2f4ba497357f466506 [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>
Mike Kleinc0bd9f92019-04-23 12:05:21 -05009#include "include/core/SkMallocPixelRef.h"
10#include "include/private/SkFloatBits.h"
11#include "include/private/SkHalf.h"
Mike Klein85754d52020-01-22 10:04:11 -060012#include "include/private/SkVx.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050013#include "src/core/SkColorSpacePriv.h"
14#include "src/core/SkConvertPixels.h"
15#include "src/core/SkReadBuffer.h"
Mike Klein85754d52020-01-22 10:04:11 -060016#include "src/core/SkVM.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050017#include "src/core/SkWriteBuffer.h"
18#include "src/shaders/gradients/Sk4fLinearGradient.h"
19#include "src/shaders/gradients/SkGradientShaderPriv.h"
20#include "src/shaders/gradients/SkLinearGradient.h"
21#include "src/shaders/gradients/SkRadialGradient.h"
22#include "src/shaders/gradients/SkSweepGradient.h"
23#include "src/shaders/gradients/SkTwoPointConicalGradient.h"
rileya@google.com589708b2012-07-26 20:04:23 +000024
brianosmane25d71c2016-09-28 11:27:28 -070025enum GradientSerializationFlags {
26 // Bits 29:31 used for various boolean flags
27 kHasPosition_GSF = 0x80000000,
28 kHasLocalMatrix_GSF = 0x40000000,
29 kHasColorSpace_GSF = 0x20000000,
30
31 // Bits 12:28 unused
32
33 // Bits 8:11 for fTileMode
34 kTileModeShift_GSF = 8,
35 kTileModeMask_GSF = 0xF,
36
37 // Bits 0:7 for fGradFlags (note that kForce4fContext_PrivateFlag is 0x80)
38 kGradFlagsShift_GSF = 0,
39 kGradFlagsMask_GSF = 0xFF,
40};
41
reed9fa60da2014-08-21 07:59:51 -070042void SkGradientShaderBase::Descriptor::flatten(SkWriteBuffer& buffer) const {
brianosmane25d71c2016-09-28 11:27:28 -070043 uint32_t flags = 0;
reed9fa60da2014-08-21 07:59:51 -070044 if (fPos) {
brianosmane25d71c2016-09-28 11:27:28 -070045 flags |= kHasPosition_GSF;
reed9fa60da2014-08-21 07:59:51 -070046 }
reed9fa60da2014-08-21 07:59:51 -070047 if (fLocalMatrix) {
brianosmane25d71c2016-09-28 11:27:28 -070048 flags |= kHasLocalMatrix_GSF;
49 }
50 sk_sp<SkData> colorSpaceData = fColorSpace ? fColorSpace->serialize() : nullptr;
51 if (colorSpaceData) {
52 flags |= kHasColorSpace_GSF;
53 }
54 SkASSERT(static_cast<uint32_t>(fTileMode) <= kTileModeMask_GSF);
Mike Reedfae8fce2019-04-03 10:27:45 -040055 flags |= ((unsigned)fTileMode << kTileModeShift_GSF);
brianosmane25d71c2016-09-28 11:27:28 -070056 SkASSERT(fGradFlags <= kGradFlagsMask_GSF);
57 flags |= (fGradFlags << kGradFlagsShift_GSF);
58
59 buffer.writeUInt(flags);
60
61 buffer.writeColor4fArray(fColors, fCount);
62 if (colorSpaceData) {
63 buffer.writeDataAsByteArray(colorSpaceData.get());
64 }
65 if (fPos) {
66 buffer.writeScalarArray(fPos, fCount);
67 }
68 if (fLocalMatrix) {
reed9fa60da2014-08-21 07:59:51 -070069 buffer.writeMatrix(*fLocalMatrix);
reed9fa60da2014-08-21 07:59:51 -070070 }
71}
72
Florin Malitaf77db112018-05-10 09:52:27 -040073template <int N, typename T, bool MEM_MOVE>
74static bool validate_array(SkReadBuffer& buffer, size_t count, SkSTArray<N, T, MEM_MOVE>* array) {
Kevin Lubickdaebae92018-05-17 11:29:10 -040075 if (!buffer.validateCanReadN<T>(count)) {
Florin Malitaf77db112018-05-10 09:52:27 -040076 return false;
77 }
78
79 array->resize_back(count);
80 return true;
81}
82
reed9fa60da2014-08-21 07:59:51 -070083bool SkGradientShaderBase::DescriptorScope::unflatten(SkReadBuffer& buffer) {
Mike Reed70bc94f2017-06-08 12:45:52 -040084 // New gradient format. Includes floating point color, color space, densely packed flags
85 uint32_t flags = buffer.readUInt();
reed9fa60da2014-08-21 07:59:51 -070086
Mike Reedfae8fce2019-04-03 10:27:45 -040087 fTileMode = (SkTileMode)((flags >> kTileModeShift_GSF) & kTileModeMask_GSF);
Mike Reed70bc94f2017-06-08 12:45:52 -040088 fGradFlags = (flags >> kGradFlagsShift_GSF) & kGradFlagsMask_GSF;
reed9fa60da2014-08-21 07:59:51 -070089
Mike Reed70bc94f2017-06-08 12:45:52 -040090 fCount = buffer.getArrayCount();
Florin Malitaf77db112018-05-10 09:52:27 -040091
92 if (!(validate_array(buffer, fCount, &fColorStorage) &&
93 buffer.readColor4fArray(fColorStorage.begin(), fCount))) {
Mike Reed70bc94f2017-06-08 12:45:52 -040094 return false;
95 }
Florin Malitaf77db112018-05-10 09:52:27 -040096 fColors = fColorStorage.begin();
97
Mike Reed70bc94f2017-06-08 12:45:52 -040098 if (SkToBool(flags & kHasColorSpace_GSF)) {
99 sk_sp<SkData> data = buffer.readByteArrayAsData();
Florin Malitac2ea3272018-05-10 09:41:38 -0400100 fColorSpace = data ? SkColorSpace::Deserialize(data->data(), data->size()) : nullptr;
Mike Reed70bc94f2017-06-08 12:45:52 -0400101 } else {
brianosmane25d71c2016-09-28 11:27:28 -0700102 fColorSpace = nullptr;
Mike Reed70bc94f2017-06-08 12:45:52 -0400103 }
104 if (SkToBool(flags & kHasPosition_GSF)) {
Florin Malitaf77db112018-05-10 09:52:27 -0400105 if (!(validate_array(buffer, fCount, &fPosStorage) &&
106 buffer.readScalarArray(fPosStorage.begin(), fCount))) {
Mike Reed70bc94f2017-06-08 12:45:52 -0400107 return false;
brianosmane25d71c2016-09-28 11:27:28 -0700108 }
Florin Malitaf77db112018-05-10 09:52:27 -0400109 fPos = fPosStorage.begin();
reed9fa60da2014-08-21 07:59:51 -0700110 } else {
Mike Reed70bc94f2017-06-08 12:45:52 -0400111 fPos = nullptr;
112 }
113 if (SkToBool(flags & kHasLocalMatrix_GSF)) {
114 fLocalMatrix = &fLocalMatrixStorage;
115 buffer.readMatrix(&fLocalMatrixStorage);
116 } else {
117 fLocalMatrix = nullptr;
reed9fa60da2014-08-21 07:59:51 -0700118 }
119 return buffer.isValid();
120}
121
122////////////////////////////////////////////////////////////////////////////////////////////
123
mtkleincc695fe2014-12-10 10:29:19 -0800124SkGradientShaderBase::SkGradientShaderBase(const Descriptor& desc, const SkMatrix& ptsToUnit)
reedaddf2ed2014-08-11 08:28:24 -0700125 : INHERITED(desc.fLocalMatrix)
mtkleincc695fe2014-12-10 10:29:19 -0800126 , fPtsToUnit(ptsToUnit)
Brian Osman6667fb12018-07-03 16:44:02 -0400127 , fColorSpace(desc.fColorSpace ? desc.fColorSpace : SkColorSpace::MakeSRGB())
Florin Malita39d71de2017-10-31 11:33:49 -0400128 , fColorsAreOpaque(true)
commit-bot@chromium.org9c9005a2014-04-28 14:55:39 +0000129{
mtkleincc695fe2014-12-10 10:29:19 -0800130 fPtsToUnit.getType(); // Precache so reads are threadsafe.
reed@google.com437d6eb2013-05-23 19:03:05 +0000131 SkASSERT(desc.fCount > 1);
rileya@google.com589708b2012-07-26 20:04:23 +0000132
fmalita6d7e4e82016-09-20 06:55:16 -0700133 fGradFlags = static_cast<uint8_t>(desc.fGradFlags);
rileya@google.com589708b2012-07-26 20:04:23 +0000134
Mike Reedfae8fce2019-04-03 10:27:45 -0400135 SkASSERT((unsigned)desc.fTileMode < kSkTileModeCount);
reed@google.com437d6eb2013-05-23 19:03:05 +0000136 fTileMode = desc.fTileMode;
rileya@google.com589708b2012-07-26 20:04:23 +0000137
rileya@google.com589708b2012-07-26 20:04:23 +0000138 /* Note: we let the caller skip the first and/or last position.
139 i.e. pos[0] = 0.3, pos[1] = 0.7
140 In these cases, we insert dummy entries to ensure that the final data
141 will be bracketed by [0, 1].
142 i.e. our_pos[0] = 0, our_pos[1] = 0.3, our_pos[2] = 0.7, our_pos[3] = 1
143
144 Thus colorCount (the caller's value, and fColorCount (our value) may
145 differ by up to 2. In the above example:
146 colorCount = 2
147 fColorCount = 4
148 */
reed@google.com437d6eb2013-05-23 19:03:05 +0000149 fColorCount = desc.fCount;
rileya@google.com589708b2012-07-26 20:04:23 +0000150 // check if we need to add in dummy start and/or end position/colors
151 bool dummyFirst = false;
152 bool dummyLast = false;
reed@google.com437d6eb2013-05-23 19:03:05 +0000153 if (desc.fPos) {
154 dummyFirst = desc.fPos[0] != 0;
155 dummyLast = desc.fPos[desc.fCount - 1] != SK_Scalar1;
rileya@google.com589708b2012-07-26 20:04:23 +0000156 fColorCount += dummyFirst + dummyLast;
157 }
158
Mike Reed62ce2ca2018-02-19 14:20:15 -0500159 size_t storageSize = fColorCount * (sizeof(SkColor4f) + (desc.fPos ? sizeof(SkScalar) : 0));
Florin Malita89ab2402017-11-01 10:14:57 -0400160 fOrigColors4f = reinterpret_cast<SkColor4f*>(fStorage.reset(storageSize));
Mike Reed62ce2ca2018-02-19 14:20:15 -0500161 fOrigPos = desc.fPos ? reinterpret_cast<SkScalar*>(fOrigColors4f + fColorCount)
162 : nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +0000163
brianosmane25d71c2016-09-28 11:27:28 -0700164 // Now copy over the colors, adding the dummies as needed
165 SkColor4f* origColors = fOrigColors4f;
166 if (dummyFirst) {
167 *origColors++ = desc.fColors[0];
168 }
Florin Malita39d71de2017-10-31 11:33:49 -0400169 for (int i = 0; i < desc.fCount; ++i) {
Mike Reed62ce2ca2018-02-19 14:20:15 -0500170 origColors[i] = desc.fColors[i];
Florin Malita39d71de2017-10-31 11:33:49 -0400171 fColorsAreOpaque = fColorsAreOpaque && (desc.fColors[i].fA == 1);
172 }
brianosmane25d71c2016-09-28 11:27:28 -0700173 if (dummyLast) {
Mike Reed62ce2ca2018-02-19 14:20:15 -0500174 origColors += desc.fCount;
175 *origColors = desc.fColors[desc.fCount - 1];
brianosmane25d71c2016-09-28 11:27:28 -0700176 }
brianosmanb9c51372016-09-15 11:09:45 -0700177
Florin Malita89ab2402017-11-01 10:14:57 -0400178 if (desc.fPos) {
Florin Malita64bb78e2017-11-03 12:54:07 -0400179 SkScalar prev = 0;
Mike Reed62ce2ca2018-02-19 14:20:15 -0500180 SkScalar* origPosPtr = fOrigPos;
Florin Malita64bb78e2017-11-03 12:54:07 -0400181 *origPosPtr++ = prev; // force the first pos to 0
reed9fa60da2014-08-21 07:59:51 -0700182
Florin Malita89ab2402017-11-01 10:14:57 -0400183 int startIndex = dummyFirst ? 0 : 1;
184 int count = desc.fCount + dummyLast;
Florin Malita64bb78e2017-11-03 12:54:07 -0400185
186 bool uniformStops = true;
187 const SkScalar uniformStep = desc.fPos[startIndex] - prev;
Florin Malita89ab2402017-11-01 10:14:57 -0400188 for (int i = startIndex; i < count; i++) {
Florin Malita3e20d022017-11-03 12:11:38 -0400189 // Pin the last value to 1.0, and make sure pos is monotonic.
Brian Osmanaba642c2020-02-06 12:52:25 -0500190 auto curr = (i == desc.fCount) ? 1 : SkTPin(desc.fPos[i], prev, 1.0f);
Florin Malita64bb78e2017-11-03 12:54:07 -0400191 uniformStops &= SkScalarNearlyEqual(uniformStep, curr - prev);
192
193 *origPosPtr++ = prev = curr;
reed9fa60da2014-08-21 07:59:51 -0700194 }
Florin Malita64bb78e2017-11-03 12:54:07 -0400195
Florin Malita64bb78e2017-11-03 12:54:07 -0400196 // If the stops are uniform, treat them as implicit.
Mike Reed62ce2ca2018-02-19 14:20:15 -0500197 if (uniformStops) {
Florin Malita64bb78e2017-11-03 12:54:07 -0400198 fOrigPos = nullptr;
199 }
rileya@google.com589708b2012-07-26 20:04:23 +0000200 }
rileya@google.com589708b2012-07-26 20:04:23 +0000201}
202
Florin Malita89ab2402017-11-01 10:14:57 -0400203SkGradientShaderBase::~SkGradientShaderBase() {}
rileya@google.com589708b2012-07-26 20:04:23 +0000204
commit-bot@chromium.org8b0e8ac2014-01-30 18:58:24 +0000205void SkGradientShaderBase::flatten(SkWriteBuffer& buffer) const {
reed9fa60da2014-08-21 07:59:51 -0700206 Descriptor desc;
brianosmane25d71c2016-09-28 11:27:28 -0700207 desc.fColors = fOrigColors4f;
brianosmanb9c51372016-09-15 11:09:45 -0700208 desc.fColorSpace = fColorSpace;
reed9fa60da2014-08-21 07:59:51 -0700209 desc.fPos = fOrigPos;
210 desc.fCount = fColorCount;
211 desc.fTileMode = fTileMode;
212 desc.fGradFlags = fGradFlags;
213
214 const SkMatrix& m = this->getLocalMatrix();
halcanary96fcdcc2015-08-27 07:41:13 -0700215 desc.fLocalMatrix = m.isIdentity() ? nullptr : &m;
reed9fa60da2014-08-21 07:59:51 -0700216 desc.flatten(buffer);
rileya@google.com589708b2012-07-26 20:04:23 +0000217}
218
Mike Kleinb11ab572018-10-24 06:42:14 -0400219static void add_stop_color(SkRasterPipeline_GradientCtx* ctx, size_t stop, SkPMColor4f Fs, SkPMColor4f Bs) {
Brian Osman781e3502018-10-03 15:42:47 -0400220 (ctx->fs[0])[stop] = Fs.fR;
221 (ctx->fs[1])[stop] = Fs.fG;
222 (ctx->fs[2])[stop] = Fs.fB;
223 (ctx->fs[3])[stop] = Fs.fA;
Mike Klein85754d52020-01-22 10:04:11 -0600224
Brian Osman781e3502018-10-03 15:42:47 -0400225 (ctx->bs[0])[stop] = Bs.fR;
226 (ctx->bs[1])[stop] = Bs.fG;
227 (ctx->bs[2])[stop] = Bs.fB;
228 (ctx->bs[3])[stop] = Bs.fA;
Mike Kleinf945cbb2017-05-17 09:30:58 -0400229}
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400230
Mike Kleinb11ab572018-10-24 06:42:14 -0400231static void add_const_color(SkRasterPipeline_GradientCtx* ctx, size_t stop, SkPMColor4f color) {
Brian Osman781e3502018-10-03 15:42:47 -0400232 add_stop_color(ctx, stop, { 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(
Mike Kleinb11ab572018-10-24 06:42:14 -0400238 SkRasterPipeline_GradientCtx* ctx, float gapCount, size_t stop, SkPMColor4f c_l, SkPMColor4f 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...
Brian Osman781e3502018-10-03 15:42:47 -0400240 SkPMColor4f Fs = {
241 (c_r.fR - c_l.fR) * gapCount,
242 (c_r.fG - c_l.fG) * gapCount,
243 (c_r.fB - c_l.fB) * gapCount,
244 (c_r.fA - c_l.fA) * gapCount,
245 };
246 SkPMColor4f Bs = {
247 c_l.fR - Fs.fR*(stop/gapCount),
248 c_l.fG - Fs.fG*(stop/gapCount),
249 c_l.fB - Fs.fB*(stop/gapCount),
250 c_l.fA - Fs.fA*(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(
Mike Kleinb11ab572018-10-24 06:42:14 -0400258 SkRasterPipeline_GradientCtx* ctx, size_t stop, float t_l, float t_r, SkPMColor4f c_l, SkPMColor4f c_r) {
Mike Klein68768172017-05-17 09:54:36 -0400259 // See note about Clankium's old compiler in init_stop_evenly().
Brian Osman781e3502018-10-03 15:42:47 -0400260 SkPMColor4f Fs = {
261 (c_r.fR - c_l.fR) / (t_r - t_l),
262 (c_r.fG - c_l.fG) / (t_r - t_l),
263 (c_r.fB - c_l.fB) / (t_r - t_l),
264 (c_r.fA - c_l.fA) / (t_r - t_l),
265 };
266 SkPMColor4f Bs = {
267 c_l.fR - Fs.fR*t_l,
268 c_l.fG - Fs.fG*t_l,
269 c_l.fB - Fs.fB*t_l,
270 c_l.fA - Fs.fA*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 Reed1386b2d2019-03-13 21:15:05 -0400276bool SkGradientShaderBase::onAppendStages(const SkStageRec& rec) const {
Mike Reed1d8c42e2017-08-29 14:58:19 -0400277 SkRasterPipeline* p = rec.fPipeline;
278 SkArenaAlloc* alloc = rec.fAlloc;
Mike Kleinb11ab572018-10-24 06:42:14 -0400279 SkRasterPipeline_DecalTileCtx* decal_ctx = nullptr;
Mike Reed1d8c42e2017-08-29 14:58:19 -0400280
Mike Kleina3771842017-05-04 19:38:48 -0400281 SkMatrix matrix;
Mike Reed1d8c42e2017-08-29 14:58:19 -0400282 if (!this->computeTotalInverse(rec.fCTM, rec.fLocalM, &matrix)) {
Mike Kleina3771842017-05-04 19:38:48 -0400283 return false;
284 }
Florin Malita50b20842017-07-29 19:08:28 -0400285 matrix.postConcat(fPtsToUnit);
Mike Kleina3771842017-05-04 19:38:48 -0400286
Florin Malita2e409002017-06-28 14:46:54 -0400287 SkRasterPipeline_<256> postPipeline;
Mike Kleina3771842017-05-04 19:38:48 -0400288
Mike Kleine8de0242018-03-10 12:37:11 -0500289 p->append(SkRasterPipeline::seed_shader);
Mike Reed6b59bf42017-07-03 21:26:44 -0400290 p->append_matrix(alloc, matrix);
Florin Malita50b20842017-07-29 19:08:28 -0400291 this->appendGradientStages(alloc, p, &postPipeline);
Mike Kleine7598532017-05-11 11:29:29 -0400292
Mike Reed62ce2ca2018-02-19 14:20:15 -0500293 switch(fTileMode) {
Mike Reedfae8fce2019-04-03 10:27:45 -0400294 case SkTileMode::kMirror: p->append(SkRasterPipeline::mirror_x_1); break;
295 case SkTileMode::kRepeat: p->append(SkRasterPipeline::repeat_x_1); break;
296 case SkTileMode::kDecal:
Mike Kleinb11ab572018-10-24 06:42:14 -0400297 decal_ctx = alloc->make<SkRasterPipeline_DecalTileCtx>();
Mike Reed62ce2ca2018-02-19 14:20:15 -0500298 decal_ctx->limit_x = SkBits2Float(SkFloat2Bits(1.0f) + 1);
299 // reuse mask + limit_x stage, or create a custom decal_1 that just stores the mask
300 p->append(SkRasterPipeline::decal_x, decal_ctx);
301 // fall-through to clamp
Mike Reedfae8fce2019-04-03 10:27:45 -0400302 case SkTileMode::kClamp:
Mike Kleine7598532017-05-11 11:29:29 -0400303 if (!fOrigPos) {
304 // We clamp only when the stops are evenly spaced.
305 // If not, there may be hard stops, and clamping ruins hard stops at 0 and/or 1.
Mike Klein5c7960b2017-05-11 10:59:22 -0400306 // In that case, we must make sure we're using the general "gradient" stage,
Mike Kleine7598532017-05-11 11:29:29 -0400307 // which is the only stage that will correctly handle unclamped t.
Mike Klein9f85d682017-05-23 07:52:01 -0400308 p->append(SkRasterPipeline::clamp_x_1);
Mike Kleine7598532017-05-11 11:29:29 -0400309 }
Mike Reed62ce2ca2018-02-19 14:20:15 -0500310 break;
Mike Kleine7598532017-05-11 11:29:29 -0400311 }
Mike Kleina3771842017-05-04 19:38:48 -0400312
313 const bool premulGrad = fGradFlags & SkGradientShader::kInterpolateColorsInPremul_Flag;
Brian Osman6667fb12018-07-03 16:44:02 -0400314
315 // Transform all of the colors to destination color space
316 SkColor4fXformer xformedColors(fOrigColors4f, fColorCount, fColorSpace.get(), rec.fDstCS);
317
318 auto prepareColor = [premulGrad, &xformedColors](int i) {
319 SkColor4f c = xformedColors.fColors[i];
Brian Osman781e3502018-10-03 15:42:47 -0400320 return premulGrad ? c.premul()
321 : SkPMColor4f{ c.fR, c.fG, c.fB, c.fA };
Mike Kleina3771842017-05-04 19:38:48 -0400322 };
323
324 // The two-stop case with stops at 0 and 1.
325 if (fColorCount == 2 && fOrigPos == nullptr) {
Brian Osman781e3502018-10-03 15:42:47 -0400326 const SkPMColor4f c_l = prepareColor(0),
327 c_r = prepareColor(1);
Mike Kleina3771842017-05-04 19:38:48 -0400328
329 // See F and B below.
Mike Kleinb11ab572018-10-24 06:42:14 -0400330 auto ctx = alloc->make<SkRasterPipeline_EvenlySpaced2StopGradientCtx>();
Brian Osman781e3502018-10-03 15:42:47 -0400331 (Sk4f::Load(c_r.vec()) - Sk4f::Load(c_l.vec())).store(ctx->f);
332 ( Sk4f::Load(c_l.vec())).store(ctx->b);
Mike Klein24de6482018-09-07 12:05:29 -0400333 ctx->interpolatedInPremul = premulGrad;
Mike Kleina3771842017-05-04 19:38:48 -0400334
Mike Klein24de6482018-09-07 12:05:29 -0400335 p->append(SkRasterPipeline::evenly_spaced_2_stop_gradient, ctx);
Mike Kleina3771842017-05-04 19:38:48 -0400336 } else {
Mike Kleinb11ab572018-10-24 06:42:14 -0400337 auto* ctx = alloc->make<SkRasterPipeline_GradientCtx>();
Mike Klein24de6482018-09-07 12:05:29 -0400338 ctx->interpolatedInPremul = premulGrad;
Herb Derby4de13042017-05-15 10:49:39 -0400339
340 // Note: In order to handle clamps in search, the search assumes a stop conceptully placed
341 // at -inf. Therefore, the max number of stops is fColorCount+1.
342 for (int i = 0; i < 4; i++) {
343 // Allocate at least at for the AVX2 gather from a YMM register.
344 ctx->fs[i] = alloc->makeArray<float>(std::max(fColorCount+1, 8));
345 ctx->bs[i] = alloc->makeArray<float>(std::max(fColorCount+1, 8));
346 }
347
Mike Kleina3771842017-05-04 19:38:48 -0400348 if (fOrigPos == nullptr) {
349 // Handle evenly distributed stops.
350
Herb Derby4de13042017-05-15 10:49:39 -0400351 size_t stopCount = fColorCount;
352 float gapCount = stopCount - 1;
Mike Kleina3771842017-05-04 19:38:48 -0400353
Brian Osman781e3502018-10-03 15:42:47 -0400354 SkPMColor4f c_l = prepareColor(0);
Herb Derby4de13042017-05-15 10:49:39 -0400355 for (size_t i = 0; i < stopCount - 1; i++) {
Brian Osman781e3502018-10-03 15:42:47 -0400356 SkPMColor4f c_r = prepareColor(i + 1);
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400357 init_stop_evenly(ctx, gapCount, i, c_l, c_r);
Mike Kleina3771842017-05-04 19:38:48 -0400358 c_l = c_r;
359 }
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400360 add_const_color(ctx, stopCount - 1, c_l);
Mike Kleina3771842017-05-04 19:38:48 -0400361
Herb Derby4de13042017-05-15 10:49:39 -0400362 ctx->stopCount = stopCount;
363 p->append(SkRasterPipeline::evenly_spaced_gradient, ctx);
Mike Kleina3771842017-05-04 19:38:48 -0400364 } else {
365 // Handle arbitrary stops.
366
Herb Derby4de13042017-05-15 10:49:39 -0400367 ctx->ts = alloc->makeArray<float>(fColorCount+1);
368
Mike Kleina3771842017-05-04 19:38:48 -0400369 // Remove the dummy stops inserted by SkGradientShaderBase::SkGradientShaderBase
370 // because they are naturally handled by the search method.
371 int firstStop;
372 int lastStop;
373 if (fColorCount > 2) {
374 firstStop = fOrigColors4f[0] != fOrigColors4f[1] ? 0 : 1;
375 lastStop = fOrigColors4f[fColorCount - 2] != fOrigColors4f[fColorCount - 1]
376 ? fColorCount - 1 : fColorCount - 2;
377 } else {
378 firstStop = 0;
379 lastStop = 1;
380 }
Mike Kleina3771842017-05-04 19:38:48 -0400381
Mike Kleina3771842017-05-04 19:38:48 -0400382 size_t stopCount = 0;
383 float t_l = fOrigPos[firstStop];
Brian Osman781e3502018-10-03 15:42:47 -0400384 SkPMColor4f c_l = prepareColor(firstStop);
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400385 add_const_color(ctx, stopCount++, c_l);
Mike Kleina3771842017-05-04 19:38:48 -0400386 // N.B. lastStop is the index of the last stop, not one after.
387 for (int i = firstStop; i < lastStop; i++) {
388 float t_r = fOrigPos[i + 1];
Brian Osman781e3502018-10-03 15:42:47 -0400389 SkPMColor4f c_r = prepareColor(i + 1);
Florin Malita3e20d022017-11-03 12:11:38 -0400390 SkASSERT(t_l <= t_r);
Mike Kleina3771842017-05-04 19:38:48 -0400391 if (t_l < t_r) {
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400392 init_stop_pos(ctx, stopCount, t_l, t_r, c_l, c_r);
Mike Kleina3771842017-05-04 19:38:48 -0400393 stopCount += 1;
394 }
395 t_l = t_r;
396 c_l = c_r;
397 }
398
Herb Derby4de13042017-05-15 10:49:39 -0400399 ctx->ts[stopCount] = t_l;
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400400 add_const_color(ctx, stopCount++, c_l);
Mike Kleina3771842017-05-04 19:38:48 -0400401
Herb Derby4de13042017-05-15 10:49:39 -0400402 ctx->stopCount = stopCount;
403 p->append(SkRasterPipeline::gradient, ctx);
Mike Kleina3771842017-05-04 19:38:48 -0400404 }
Mike Kleina3771842017-05-04 19:38:48 -0400405 }
406
Mike Reed62ce2ca2018-02-19 14:20:15 -0500407 if (decal_ctx) {
408 p->append(SkRasterPipeline::check_decal_mask, decal_ctx);
409 }
410
Mike Kleina3771842017-05-04 19:38:48 -0400411 if (!premulGrad && !this->colorsAreOpaque()) {
Mike Kleine7598532017-05-11 11:29:29 -0400412 p->append(SkRasterPipeline::premul);
Mike Kleina3771842017-05-04 19:38:48 -0400413 }
414
Florin Malita2e409002017-06-28 14:46:54 -0400415 p->extend(postPipeline);
416
Mike Kleina3771842017-05-04 19:38:48 -0400417 return true;
418}
419
Mike Klein276a7852020-03-15 08:46:09 -0500420skvm::Color SkGradientShaderBase::onProgram(skvm::Builder* p, skvm::F32 x, skvm::F32 y,
Mike Reed6352f002020-03-14 23:30:10 -0400421 const SkMatrix& ctm, const SkMatrix* localM,
422 SkFilterQuality quality, SkColorSpace* dstCS,
Mike Klein276a7852020-03-15 08:46:09 -0500423 skvm::Uniforms* uniforms, SkArenaAlloc* alloc) const {
Mike Klein85754d52020-01-22 10:04:11 -0600424 SkMatrix inv;
425 if (!this->computeTotalInverse(ctm, localM, &inv)) {
Mike Reed6352f002020-03-14 23:30:10 -0400426 return {};
Mike Klein85754d52020-01-22 10:04:11 -0600427 }
428 inv.postConcat(fPtsToUnit);
429 inv.normalizePerspective();
430
Mike Klein85754d52020-01-22 10:04:11 -0600431 SkShaderBase::ApplyMatrix(p, inv, &x,&y,uniforms);
Mike Klein85754d52020-01-22 10:04:11 -0600432
Mike Kleince9e0602020-01-29 09:47:44 -0600433 skvm::I32 mask = p->splat(~0);
434 skvm::F32 t = this->transformT(p,uniforms, x,y, &mask);
Mike Kleincaf5ee42020-01-28 16:11:34 -0600435
436 // Perhaps unexpectedly, clamping is handled naturally by our search, so we
437 // don't explicitly clamp t to [0,1]. That clamp would break hard stops
438 // right at 0 or 1 boundaries in kClamp mode. (kRepeat and kMirror always
439 // produce values in [0,1].)
Mike Klein85754d52020-01-22 10:04:11 -0600440 switch(fTileMode) {
Mike Kleincaf5ee42020-01-28 16:11:34 -0600441 case SkTileMode::kClamp:
442 break;
443
444 case SkTileMode::kDecal:
Mike Kleince9e0602020-01-29 09:47:44 -0600445 mask = p->bit_and(mask, p->eq(t, p->clamp(t, p->splat(0.0f), p->splat(1.0f))));
Mike Kleincaf5ee42020-01-28 16:11:34 -0600446 break;
447
448 case SkTileMode::kRepeat:
449 t = p->sub(t, p->floor(t));
450 break;
451
Mike Klein85754d52020-01-22 10:04:11 -0600452 case SkTileMode::kMirror: {
453 // t = | (t-1) - 2*(floor( (t-1)*0.5 )) - 1 |
454 // {-A-} {--------B-------}
455 skvm::F32 A = p->sub(t, p->splat(1.0f)),
456 B = p->floor( p->mul(A, p->splat(0.5f)));
457 t = p->abs(p->sub(p->sub(A, p->add(B,B)),
458 p->splat(1.0f)));
459 } break;
460 }
461
462 // Transform our colors as we want them interpolated, in dst color space, possibly premul.
463 SkImageInfo common = SkImageInfo::Make(fColorCount,1, kRGBA_F32_SkColorType
464 , kUnpremul_SkAlphaType),
465 src = common.makeColorSpace(fColorSpace),
466 dst = common.makeColorSpace(sk_ref_sp(dstCS));
467 if (fGradFlags & SkGradientShader::kInterpolateColorsInPremul_Flag) {
468 dst = dst.makeAlphaType(kPremul_SkAlphaType);
469 }
470
471 std::vector<float> rgba(4*fColorCount); // TODO: SkSTArray?
472 SkConvertPixels(dst, rgba.data(), dst.minRowBytes(),
473 src, fOrigColors4f, src.minRowBytes());
474
475 // Transform our colors into a scale factor f and bias b such that for
476 // any t between stops i and i+1, the color we want is mad(t, f[i], b[i]).
477 using F4 = skvx::Vec<4,float>;
478 struct FB { F4 f,b; };
Mike Reed6352f002020-03-14 23:30:10 -0400479 skvm::Color color;
Mike Klein85754d52020-01-22 10:04:11 -0600480
481 if (fColorCount == 2) {
482 // 2-stop gradients have colors at 0 and 1, and so must be evenly spaced.
483 SkASSERT(fOrigPos == nullptr);
484
485 // With 2 stops, we upload the single FB as uniforms and interpolate directly with t.
486 F4 lo = F4::Load(rgba.data() + 0),
487 hi = F4::Load(rgba.data() + 4);
488 F4 F = hi - lo,
489 B = lo;
490
491 auto T = p->clamp(t, p->splat(0.0f), p->splat(1.0f));
Mike Reed6352f002020-03-14 23:30:10 -0400492 color = {
493 p->mad(T, p->uniformF(uniforms->pushF(F[0])), p->uniformF(uniforms->pushF(B[0]))),
494 p->mad(T, p->uniformF(uniforms->pushF(F[1])), p->uniformF(uniforms->pushF(B[1]))),
495 p->mad(T, p->uniformF(uniforms->pushF(F[2])), p->uniformF(uniforms->pushF(B[2]))),
496 p->mad(T, p->uniformF(uniforms->pushF(F[3])), p->uniformF(uniforms->pushF(B[3]))),
497 };
Mike Klein85754d52020-01-22 10:04:11 -0600498 } else {
499 // To handle clamps in search we add a conceptual stop at t=-inf, so we
500 // may need up to fColorCount+1 FBs and fColorCount t stops between them:
501 //
502 // FBs: [color 0] [color 0->1] [color 1->2] [color 2->3] ...
503 // stops: (-inf) t0 t1 t2 ...
504 //
505 // Both these arrays could end up shorter if any hard stops share the same t.
506 FB* fb = alloc->makeArrayDefault<FB>(fColorCount+1);
507 std::vector<float> stops; // TODO: SkSTArray?
508 stops.reserve(fColorCount);
509
510 // Here's our conceptual stop at t=-inf covering all t<=0, clamping to our first color.
511 float t_lo = this->getPos(0);
512 F4 color_lo = F4::Load(rgba.data());
513 fb[0] = { 0.0f, color_lo };
514 // N.B. No stops[] entry for this implicit -inf.
515
516 // Now the non-edge cases, calculating scale and bias between adjacent normal stops.
517 for (int i = 1; i < fColorCount; i++) {
518 float t_hi = this->getPos(i);
519 F4 color_hi = F4::Load(rgba.data() + 4*i);
520
521 // If t_lo == t_hi, we're on a hard stop, and transition immediately to the next color.
522 SkASSERT(t_lo <= t_hi);
523 if (t_lo < t_hi) {
524 F4 f = (color_hi - color_lo) / (t_hi - t_lo),
525 b = color_lo - f*t_lo;
526 stops.push_back(t_lo);
527 fb[stops.size()] = {f,b};
528 }
529
530 t_lo = t_hi;
531 color_lo = color_hi;
532 }
533 // Anything >= our final t clamps to our final color.
534 stops.push_back(t_lo);
535 fb[stops.size()] = { 0.0f, color_lo };
536
537 // We'll gather FBs from that array we just created.
538 skvm::Builder::Uniform fbs = uniforms->pushPtr(fb);
539
540 // Find the two stops we need to interpolate.
541 skvm::I32 ix;
542 if (fOrigPos == nullptr) {
543 // Evenly spaced stops... we can calculate ix directly.
544 // Of note: we need to clamp t and skip over that conceptual -inf stop we made up.
545 ix = p->trunc(p->mad(p->clamp(t, p->splat(0.0f), p->splat(1.0f)),
546 p->uniformF(uniforms->pushF(stops.size() - 1.0f)),
547 p->splat(1.0f)));
548 } else {
549 // Starting ix at 0 bakes in our conceptual first stop at -inf.
550 // TODO: good place to experiment with a loop in skvm.... stops.size() can be huge.
551 ix = p->splat(0);
552 for (float stop : stops) {
553 // ix += (t >= stop) ? +1 : 0 ~~>
554 // ix -= (t >= stop) ? -1 : 0
555 ix = p->sub(ix, p->gte(t, p->uniformF(uniforms->pushF(stop))));
556 }
557 // TODO: we could skip any of the dummy stops GradientShaderBase's ctor added
558 // to ensure the full [0,1] span is covered. This linear search doesn't need
559 // them for correctness, and it'd be up to two fewer stops to check.
560 // N.B. we do still need those stops for the fOrigPos == nullptr direct math path.
561 }
562
563 // A scale factor and bias for each lane, 8 total.
564 // TODO: simpler, faster, tidier to push 8 uniform pointers, one for each struct lane?
565 ix = p->shl(ix, 3); skvm::F32 Fr = p->bit_cast(p->gather32(fbs, ix));
566 ix = p->add(ix, p->splat(1)); skvm::F32 Fg = p->bit_cast(p->gather32(fbs, ix));
567 ix = p->add(ix, p->splat(1)); skvm::F32 Fb = p->bit_cast(p->gather32(fbs, ix));
568 ix = p->add(ix, p->splat(1)); skvm::F32 Fa = p->bit_cast(p->gather32(fbs, ix));
569
570 ix = p->add(ix, p->splat(1)); skvm::F32 Br = p->bit_cast(p->gather32(fbs, ix));
571 ix = p->add(ix, p->splat(1)); skvm::F32 Bg = p->bit_cast(p->gather32(fbs, ix));
572 ix = p->add(ix, p->splat(1)); skvm::F32 Bb = p->bit_cast(p->gather32(fbs, ix));
573 ix = p->add(ix, p->splat(1)); skvm::F32 Ba = p->bit_cast(p->gather32(fbs, ix));
574
575 // This is what we've been building towards!
Mike Reed6352f002020-03-14 23:30:10 -0400576 color = {
577 p->mad(t, Fr, Br),
578 p->mad(t, Fg, Bg),
579 p->mad(t, Fb, Bb),
580 p->mad(t, Fa, Ba),
581 };
Mike Klein85754d52020-01-22 10:04:11 -0600582 }
583
584 // If we interpolated unpremul, premul now to match our output convention.
585 if (0 == (fGradFlags & SkGradientShader::kInterpolateColorsInPremul_Flag)
586 && !fColorsAreOpaque) {
Mike Reed6352f002020-03-14 23:30:10 -0400587 color = p->premul(color);
Mike Klein85754d52020-01-22 10:04:11 -0600588 }
589
Mike Reed6352f002020-03-14 23:30:10 -0400590 return {
591 p->bit_cast(p->bit_and(mask, p->bit_cast(color.r))),
592 p->bit_cast(p->bit_and(mask, p->bit_cast(color.g))),
593 p->bit_cast(p->bit_and(mask, p->bit_cast(color.b))),
594 p->bit_cast(p->bit_and(mask, p->bit_cast(color.a))),
595 };
Mike Klein85754d52020-01-22 10:04:11 -0600596}
597
Mike Kleina3771842017-05-04 19:38:48 -0400598
rileya@google.com589708b2012-07-26 20:04:23 +0000599bool SkGradientShaderBase::isOpaque() const {
Mike Reedfae8fce2019-04-03 10:27:45 -0400600 return fColorsAreOpaque && (this->getTileMode() != SkTileMode::kDecal);
Mike Reed62ce2ca2018-02-19 14:20:15 -0500601}
602
reed8367b8c2014-08-22 08:30:20 -0700603static unsigned rounded_divide(unsigned numer, unsigned denom) {
604 return (numer + (denom >> 1)) / denom;
605}
606
607bool SkGradientShaderBase::onAsLuminanceColor(SkColor* lum) const {
608 // we just compute an average color.
609 // possibly we could weight this based on the proportional width for each color
610 // assuming they are not evenly distributed in the fPos array.
611 int r = 0;
612 int g = 0;
613 int b = 0;
614 const int n = fColorCount;
Florin Malita39d71de2017-10-31 11:33:49 -0400615 // TODO: use linear colors?
reed8367b8c2014-08-22 08:30:20 -0700616 for (int i = 0; i < n; ++i) {
Florin Malita39d71de2017-10-31 11:33:49 -0400617 SkColor c = this->getLegacyColor(i);
reed8367b8c2014-08-22 08:30:20 -0700618 r += SkColorGetR(c);
619 g += SkColorGetG(c);
620 b += SkColorGetB(c);
621 }
622 *lum = SkColorSetRGB(rounded_divide(r, n), rounded_divide(g, n), rounded_divide(b, n));
623 return true;
624}
625
Brian Osman6667fb12018-07-03 16:44:02 -0400626SkColor4fXformer::SkColor4fXformer(const SkColor4f* colors, int colorCount,
627 SkColorSpace* src, SkColorSpace* dst) {
Brian Osman6667fb12018-07-03 16:44:02 -0400628 fColors = colors;
Brian Osmanccd39952018-07-06 16:16:43 -0400629
Mike Kleinf9f68ff2018-10-12 14:23:06 -0400630 if (dst && !SkColorSpace::Equals(src, dst)) {
Brian Osman6667fb12018-07-03 16:44:02 -0400631 fStorage.reset(colorCount);
Brian Salomon5dfcf132018-10-12 14:39:32 +0000632
633 auto info = SkImageInfo::Make(colorCount,1, kRGBA_F32_SkColorType, kUnpremul_SkAlphaType);
634
635 SkConvertPixels(info.makeColorSpace(sk_ref_sp(dst)), fStorage.begin(), info.minRowBytes(),
636 info.makeColorSpace(sk_ref_sp(src)), fColors , info.minRowBytes());
637
Brian Osman6667fb12018-07-03 16:44:02 -0400638 fColors = fStorage.begin();
639 }
640}
641
Florin Malita5f379a82017-10-18 16:22:35 -0400642void SkGradientShaderBase::commonAsAGradient(GradientInfo* info) const {
rileya@google.com589708b2012-07-26 20:04:23 +0000643 if (info) {
644 if (info->fColorCount >= fColorCount) {
645 if (info->fColors) {
Florin Malita39d71de2017-10-31 11:33:49 -0400646 for (int i = 0; i < fColorCount; ++i) {
647 info->fColors[i] = this->getLegacyColor(i);
648 }
rileya@google.com589708b2012-07-26 20:04:23 +0000649 }
650 if (info->fColorOffsets) {
Florin Malitaed6ae562017-10-28 11:06:48 -0400651 for (int i = 0; i < fColorCount; ++i) {
652 info->fColorOffsets[i] = this->getPos(i);
rileya@google.com589708b2012-07-26 20:04:23 +0000653 }
654 }
655 }
656 info->fColorCount = fColorCount;
657 info->fTileMode = fTileMode;
reed@google.com3d3a8602013-05-24 14:58:44 +0000658 info->fGradientFlags = fGradFlags;
rileya@google.com589708b2012-07-26 20:04:23 +0000659 }
660}
661
662///////////////////////////////////////////////////////////////////////////////
663///////////////////////////////////////////////////////////////////////////////
664
reed1b747302015-01-06 07:13:19 -0800665// Return true if these parameters are valid/legal/safe to construct a gradient
666//
brianosmane25d71c2016-09-28 11:27:28 -0700667static bool valid_grad(const SkColor4f colors[], const SkScalar pos[], int count,
Mike Reedfae8fce2019-04-03 10:27:45 -0400668 SkTileMode tileMode) {
669 return nullptr != colors && count >= 1 && (unsigned)tileMode < kSkTileModeCount;
reed1b747302015-01-06 07:13:19 -0800670}
671
reed@google.com437d6eb2013-05-23 19:03:05 +0000672static void desc_init(SkGradientShaderBase::Descriptor* desc,
brianosmane25d71c2016-09-28 11:27:28 -0700673 const SkColor4f colors[], sk_sp<SkColorSpace> colorSpace,
674 const SkScalar pos[], int colorCount,
Mike Reedfae8fce2019-04-03 10:27:45 -0400675 SkTileMode mode, uint32_t flags, const SkMatrix* localMatrix) {
fmalita748d6202016-05-11 11:39:58 -0700676 SkASSERT(colorCount > 1);
677
commit-bot@chromium.org6c5aea22014-04-22 16:25:15 +0000678 desc->fColors = colors;
brianosmane25d71c2016-09-28 11:27:28 -0700679 desc->fColorSpace = std::move(colorSpace);
commit-bot@chromium.org6c5aea22014-04-22 16:25:15 +0000680 desc->fPos = pos;
681 desc->fCount = colorCount;
682 desc->fTileMode = mode;
commit-bot@chromium.org6c5aea22014-04-22 16:25:15 +0000683 desc->fGradFlags = flags;
reedaddf2ed2014-08-11 08:28:24 -0700684 desc->fLocalMatrix = localMatrix;
reed@google.com437d6eb2013-05-23 19:03:05 +0000685}
686
Mike Klein024072a2018-11-11 00:26:30 +0000687static SkColor4f average_gradient_color(const SkColor4f colors[], const SkScalar pos[],
688 int colorCount) {
689 // The gradient is a piecewise linear interpolation between colors. For a given interval,
690 // the integral between the two endpoints is 0.5 * (ci + cj) * (pj - pi), which provides that
691 // intervals average color. The overall average color is thus the sum of each piece. The thing
692 // to keep in mind is that the provided gradient definition may implicitly use p=0 and p=1.
693 Sk4f blend(0.0);
694 // Bake 1/(colorCount - 1) uniform stop difference into this scale factor
695 SkScalar wScale = pos ? 0.5 : 0.5 / (colorCount - 1);
696 for (int i = 0; i < colorCount - 1; ++i) {
697 // Calculate the average color for the interval between pos(i) and pos(i+1)
698 Sk4f c0 = Sk4f::Load(&colors[i]);
699 Sk4f c1 = Sk4f::Load(&colors[i + 1]);
700 // when pos == null, there are colorCount uniformly distributed stops, going from 0 to 1,
701 // so pos[i + 1] - pos[i] = 1/(colorCount-1)
702 SkScalar w = pos ? (pos[i + 1] - pos[i]) : SK_Scalar1;
703 blend += wScale * w * (c1 + c0);
704 }
705
706 // Now account for any implicit intervals at the start or end of the stop definitions
707 if (pos) {
708 if (pos[0] > 0.0) {
709 // The first color is fixed between p = 0 to pos[0], so 0.5 * (ci + cj) * (pj - pi)
710 // becomes 0.5 * (c + c) * (pj - 0) = c * pj
711 Sk4f c = Sk4f::Load(&colors[0]);
712 blend += pos[0] * c;
713 }
714 if (pos[colorCount - 1] < SK_Scalar1) {
715 // The last color is fixed between pos[n-1] to p = 1, so 0.5 * (ci + cj) * (pj - pi)
716 // becomes 0.5 * (c + c) * (1 - pi) = c * (1 - pi)
717 Sk4f c = Sk4f::Load(&colors[colorCount - 1]);
718 blend += (1 - pos[colorCount - 1]) * c;
719 }
720 }
721
722 SkColor4f avg;
723 blend.store(&avg);
724 return avg;
725}
726
Michael Ludwigd431c722018-11-16 10:00:24 -0500727// The default SkScalarNearlyZero threshold of .0024 is too big and causes regressions for svg
728// gradients defined in the wild.
729static constexpr SkScalar kDegenerateThreshold = SK_Scalar1 / (1 << 15);
730
Mike Klein024072a2018-11-11 00:26:30 +0000731// Except for special circumstances of clamped gradients, every gradient shape--when degenerate--
732// can be mapped to the same fallbacks. The specific shape factories must account for special
733// clamped conditions separately, this will always return the last color for clamped gradients.
734static sk_sp<SkShader> make_degenerate_gradient(const SkColor4f colors[], const SkScalar pos[],
735 int colorCount, sk_sp<SkColorSpace> colorSpace,
Mike Reedfae8fce2019-04-03 10:27:45 -0400736 SkTileMode mode) {
Mike Klein024072a2018-11-11 00:26:30 +0000737 switch(mode) {
Mike Reedfae8fce2019-04-03 10:27:45 -0400738 case SkTileMode::kDecal:
Mike Klein024072a2018-11-11 00:26:30 +0000739 // normally this would reject the area outside of the interpolation region, so since
740 // inside region is empty when the radii are equal, the entire draw region is empty
Mike Reedc8bea7d2019-04-09 13:55:36 -0400741 return SkShaders::Empty();
Mike Reedfae8fce2019-04-03 10:27:45 -0400742 case SkTileMode::kRepeat:
743 case SkTileMode::kMirror:
Mike Klein024072a2018-11-11 00:26:30 +0000744 // repeat and mirror are treated the same: the border colors are never visible,
745 // but approximate the final color as infinite repetitions of the colors, so
746 // it can be represented as the average color of the gradient.
Mike Reedc8bea7d2019-04-09 13:55:36 -0400747 return SkShaders::Color(
Mike Klein024072a2018-11-11 00:26:30 +0000748 average_gradient_color(colors, pos, colorCount), std::move(colorSpace));
Mike Reedfae8fce2019-04-03 10:27:45 -0400749 case SkTileMode::kClamp:
Mike Klein024072a2018-11-11 00:26:30 +0000750 // Depending on how the gradient shape degenerates, there may be a more specialized
751 // fallback representation for the factories to use, but this is a reasonable default.
Mike Reedc8bea7d2019-04-09 13:55:36 -0400752 return SkShaders::Color(colors[colorCount - 1], std::move(colorSpace));
Mike Klein024072a2018-11-11 00:26:30 +0000753 }
Mike Reedfae8fce2019-04-03 10:27:45 -0400754 SkDEBUGFAIL("Should not be reached");
755 return nullptr;
Mike Klein024072a2018-11-11 00:26:30 +0000756}
757
brianosmane25d71c2016-09-28 11:27:28 -0700758// assumes colors is SkColor4f* and pos is SkScalar*
fmenozzie9fd0f82016-08-19 07:50:57 -0700759#define EXPAND_1_COLOR(count) \
brianosmane25d71c2016-09-28 11:27:28 -0700760 SkColor4f tmp[2]; \
fmenozzie9fd0f82016-08-19 07:50:57 -0700761 do { \
762 if (1 == count) { \
763 tmp[0] = tmp[1] = colors[0]; \
764 colors = tmp; \
765 pos = nullptr; \
766 count = 2; \
767 } \
768 } while (0)
769
fmenozzi68d952c2016-08-19 08:56:56 -0700770struct ColorStopOptimizer {
Mike Reedfae8fce2019-04-03 10:27:45 -0400771 ColorStopOptimizer(const SkColor4f* colors, const SkScalar* pos, int count, SkTileMode mode)
fmenozzi68d952c2016-08-19 08:56:56 -0700772 : fColors(colors)
773 , fPos(pos)
774 , fCount(count) {
775
776 if (!pos || count != 3) {
777 return;
778 }
779
780 if (SkScalarNearlyEqual(pos[0], 0.0f) &&
781 SkScalarNearlyEqual(pos[1], 0.0f) &&
782 SkScalarNearlyEqual(pos[2], 1.0f)) {
783
Mike Reedfae8fce2019-04-03 10:27:45 -0400784 if (SkTileMode::kRepeat == mode || SkTileMode::kMirror == mode ||
fmenozzi68d952c2016-08-19 08:56:56 -0700785 colors[0] == colors[1]) {
786
fmalita582a6562016-08-22 06:28:57 -0700787 // Ignore the leftmost color/pos.
788 fColors += 1;
789 fPos += 1;
790 fCount = 2;
fmenozzi68d952c2016-08-19 08:56:56 -0700791 }
792 } else if (SkScalarNearlyEqual(pos[0], 0.0f) &&
793 SkScalarNearlyEqual(pos[1], 1.0f) &&
794 SkScalarNearlyEqual(pos[2], 1.0f)) {
795
Mike Reedfae8fce2019-04-03 10:27:45 -0400796 if (SkTileMode::kRepeat == mode || SkTileMode::kMirror == mode ||
fmenozzi68d952c2016-08-19 08:56:56 -0700797 colors[1] == colors[2]) {
798
fmalita582a6562016-08-22 06:28:57 -0700799 // Ignore the rightmost color/pos.
fmenozzi68d952c2016-08-19 08:56:56 -0700800 fCount = 2;
801 }
802 }
803 }
804
brianosmane25d71c2016-09-28 11:27:28 -0700805 const SkColor4f* fColors;
806 const SkScalar* fPos;
807 int fCount;
808};
809
810struct ColorConverter {
811 ColorConverter(const SkColor* colors, int count) {
Brian Osman6667fb12018-07-03 16:44:02 -0400812 const float ONE_OVER_255 = 1.f / 255;
brianosmane25d71c2016-09-28 11:27:28 -0700813 for (int i = 0; i < count; ++i) {
Brian Osman6667fb12018-07-03 16:44:02 -0400814 fColors4f.push_back({
815 SkColorGetR(colors[i]) * ONE_OVER_255,
816 SkColorGetG(colors[i]) * ONE_OVER_255,
817 SkColorGetB(colors[i]) * ONE_OVER_255,
818 SkColorGetA(colors[i]) * ONE_OVER_255 });
brianosmane25d71c2016-09-28 11:27:28 -0700819 }
820 }
821
822 SkSTArray<2, SkColor4f, true> fColors4f;
fmenozzi68d952c2016-08-19 08:56:56 -0700823};
824
reed8a21c9f2016-03-08 18:50:00 -0800825sk_sp<SkShader> SkGradientShader::MakeLinear(const SkPoint pts[2],
fmenozzi68d952c2016-08-19 08:56:56 -0700826 const SkColor colors[],
827 const SkScalar pos[], int colorCount,
Mike Reedfae8fce2019-04-03 10:27:45 -0400828 SkTileMode mode,
fmenozzi68d952c2016-08-19 08:56:56 -0700829 uint32_t flags,
830 const SkMatrix* localMatrix) {
brianosmane25d71c2016-09-28 11:27:28 -0700831 ColorConverter converter(colors, colorCount);
832 return MakeLinear(pts, converter.fColors4f.begin(), nullptr, pos, colorCount, mode, flags,
833 localMatrix);
834}
835
836sk_sp<SkShader> SkGradientShader::MakeLinear(const SkPoint pts[2],
837 const SkColor4f colors[],
838 sk_sp<SkColorSpace> colorSpace,
839 const SkScalar pos[], int colorCount,
Mike Reedfae8fce2019-04-03 10:27:45 -0400840 SkTileMode mode,
brianosmane25d71c2016-09-28 11:27:28 -0700841 uint32_t flags,
842 const SkMatrix* localMatrix) {
fmalitac5231042016-08-10 05:45:50 -0700843 if (!pts || !SkScalarIsFinite((pts[1] - pts[0]).length())) {
halcanary96fcdcc2015-08-27 07:41:13 -0700844 return nullptr;
reed1b747302015-01-06 07:13:19 -0800845 }
846 if (!valid_grad(colors, pos, colorCount, mode)) {
halcanary96fcdcc2015-08-27 07:41:13 -0700847 return nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +0000848 }
fmenozzie9fd0f82016-08-19 07:50:57 -0700849 if (1 == colorCount) {
Mike Reedc8bea7d2019-04-09 13:55:36 -0400850 return SkShaders::Color(colors[0], std::move(colorSpace));
fmenozzie9fd0f82016-08-19 07:50:57 -0700851 }
Florin Malita8d3ffad2017-02-03 18:21:17 +0000852 if (localMatrix && !localMatrix->invert(nullptr)) {
853 return nullptr;
854 }
rileya@google.com589708b2012-07-26 20:04:23 +0000855
Michael Ludwigd431c722018-11-16 10:00:24 -0500856 if (SkScalarNearlyZero((pts[1] - pts[0]).length(), kDegenerateThreshold)) {
Mike Klein024072a2018-11-11 00:26:30 +0000857 // Degenerate gradient, the only tricky complication is when in clamp mode, the limit of
858 // the gradient approaches two half planes of solid color (first and last). However, they
859 // are divided by the line perpendicular to the start and end point, which becomes undefined
860 // once start and end are exactly the same, so just use the end color for a stable solution.
861 return make_degenerate_gradient(colors, pos, colorCount, std::move(colorSpace), mode);
862 }
863
fmenozzi68d952c2016-08-19 08:56:56 -0700864 ColorStopOptimizer opt(colors, pos, colorCount, mode);
865
reed@google.com437d6eb2013-05-23 19:03:05 +0000866 SkGradientShaderBase::Descriptor desc;
brianosmane25d71c2016-09-28 11:27:28 -0700867 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
868 localMatrix);
reed8a21c9f2016-03-08 18:50:00 -0800869 return sk_make_sp<SkLinearGradient>(pts, desc);
rileya@google.com589708b2012-07-26 20:04:23 +0000870}
871
reed8a21c9f2016-03-08 18:50:00 -0800872sk_sp<SkShader> SkGradientShader::MakeRadial(const SkPoint& center, SkScalar radius,
brianosmane25d71c2016-09-28 11:27:28 -0700873 const SkColor colors[],
874 const SkScalar pos[], int colorCount,
Mike Reedfae8fce2019-04-03 10:27:45 -0400875 SkTileMode mode,
brianosmane25d71c2016-09-28 11:27:28 -0700876 uint32_t flags,
877 const SkMatrix* localMatrix) {
878 ColorConverter converter(colors, colorCount);
879 return MakeRadial(center, radius, converter.fColors4f.begin(), nullptr, pos, colorCount, mode,
880 flags, localMatrix);
881}
882
883sk_sp<SkShader> SkGradientShader::MakeRadial(const SkPoint& center, SkScalar radius,
884 const SkColor4f colors[],
885 sk_sp<SkColorSpace> colorSpace,
886 const SkScalar pos[], int colorCount,
Mike Reedfae8fce2019-04-03 10:27:45 -0400887 SkTileMode mode,
brianosmane25d71c2016-09-28 11:27:28 -0700888 uint32_t flags,
889 const SkMatrix* localMatrix) {
Mike Klein024072a2018-11-11 00:26:30 +0000890 if (radius < 0) {
halcanary96fcdcc2015-08-27 07:41:13 -0700891 return nullptr;
reed1b747302015-01-06 07:13:19 -0800892 }
893 if (!valid_grad(colors, pos, colorCount, mode)) {
halcanary96fcdcc2015-08-27 07:41:13 -0700894 return nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +0000895 }
fmenozzie9fd0f82016-08-19 07:50:57 -0700896 if (1 == colorCount) {
Mike Reedc8bea7d2019-04-09 13:55:36 -0400897 return SkShaders::Color(colors[0], std::move(colorSpace));
fmenozzie9fd0f82016-08-19 07:50:57 -0700898 }
Florin Malita8d3ffad2017-02-03 18:21:17 +0000899 if (localMatrix && !localMatrix->invert(nullptr)) {
900 return nullptr;
901 }
rileya@google.com589708b2012-07-26 20:04:23 +0000902
Michael Ludwigd431c722018-11-16 10:00:24 -0500903 if (SkScalarNearlyZero(radius, kDegenerateThreshold)) {
Mike Klein024072a2018-11-11 00:26:30 +0000904 // Degenerate gradient optimization, and no special logic needed for clamped radial gradient
905 return make_degenerate_gradient(colors, pos, colorCount, std::move(colorSpace), mode);
906 }
907
fmenozzi68d952c2016-08-19 08:56:56 -0700908 ColorStopOptimizer opt(colors, pos, colorCount, mode);
909
reed@google.com437d6eb2013-05-23 19:03:05 +0000910 SkGradientShaderBase::Descriptor desc;
brianosmane25d71c2016-09-28 11:27:28 -0700911 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
912 localMatrix);
reed8a21c9f2016-03-08 18:50:00 -0800913 return sk_make_sp<SkRadialGradient>(center, radius, desc);
rileya@google.com589708b2012-07-26 20:04:23 +0000914}
915
reed8a21c9f2016-03-08 18:50:00 -0800916sk_sp<SkShader> SkGradientShader::MakeTwoPointConical(const SkPoint& start,
brianosmane25d71c2016-09-28 11:27:28 -0700917 SkScalar startRadius,
918 const SkPoint& end,
919 SkScalar endRadius,
920 const SkColor colors[],
921 const SkScalar pos[],
922 int colorCount,
Mike Reedfae8fce2019-04-03 10:27:45 -0400923 SkTileMode mode,
brianosmane25d71c2016-09-28 11:27:28 -0700924 uint32_t flags,
925 const SkMatrix* localMatrix) {
926 ColorConverter converter(colors, colorCount);
927 return MakeTwoPointConical(start, startRadius, end, endRadius, converter.fColors4f.begin(),
928 nullptr, pos, colorCount, mode, flags, localMatrix);
929}
930
931sk_sp<SkShader> SkGradientShader::MakeTwoPointConical(const SkPoint& start,
932 SkScalar startRadius,
933 const SkPoint& end,
934 SkScalar endRadius,
935 const SkColor4f colors[],
936 sk_sp<SkColorSpace> colorSpace,
937 const SkScalar pos[],
938 int colorCount,
Mike Reedfae8fce2019-04-03 10:27:45 -0400939 SkTileMode mode,
brianosmane25d71c2016-09-28 11:27:28 -0700940 uint32_t flags,
941 const SkMatrix* localMatrix) {
reed1b747302015-01-06 07:13:19 -0800942 if (startRadius < 0 || endRadius < 0) {
halcanary96fcdcc2015-08-27 07:41:13 -0700943 return nullptr;
reed1b747302015-01-06 07:13:19 -0800944 }
945 if (!valid_grad(colors, pos, colorCount, mode)) {
halcanary96fcdcc2015-08-27 07:41:13 -0700946 return nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +0000947 }
Michael Ludwigd431c722018-11-16 10:00:24 -0500948 if (SkScalarNearlyZero((start - end).length(), kDegenerateThreshold)) {
Mike Klein024072a2018-11-11 00:26:30 +0000949 // If the center positions are the same, then the gradient is the radial variant of a 2 pt
950 // conical gradient, an actual radial gradient (startRadius == 0), or it is fully degenerate
951 // (startRadius == endRadius).
Michael Ludwigd431c722018-11-16 10:00:24 -0500952 if (SkScalarNearlyEqual(startRadius, endRadius, kDegenerateThreshold)) {
Mike Klein024072a2018-11-11 00:26:30 +0000953 // Degenerate case, where the interpolation region area approaches zero. The proper
954 // behavior depends on the tile mode, which is consistent with the default degenerate
955 // gradient behavior, except when mode = clamp and the radii > 0.
Mike Reedfae8fce2019-04-03 10:27:45 -0400956 if (mode == SkTileMode::kClamp && endRadius > kDegenerateThreshold) {
Mike Klein024072a2018-11-11 00:26:30 +0000957 // The interpolation region becomes an infinitely thin ring at the radius, so the
958 // final gradient will be the first color repeated from p=0 to 1, and then a hard
959 // stop switching to the last color at p=1.
960 static constexpr SkScalar circlePos[3] = {0, 1, 1};
961 SkColor4f reColors[3] = {colors[0], colors[0], colors[colorCount - 1]};
962 return MakeRadial(start, endRadius, reColors, std::move(colorSpace),
963 circlePos, 3, mode, flags, localMatrix);
964 } else {
965 // Otherwise use the default degenerate case
966 return make_degenerate_gradient(
967 colors, pos, colorCount, std::move(colorSpace), mode);
968 }
Michael Ludwigd431c722018-11-16 10:00:24 -0500969 } else if (SkScalarNearlyZero(startRadius, kDegenerateThreshold)) {
Mike Klein024072a2018-11-11 00:26:30 +0000970 // We can treat this gradient as radial, which is faster. If we got here, we know
971 // that endRadius is not equal to 0, so this produces a meaningful gradient
972 return MakeRadial(start, endRadius, colors, std::move(colorSpace), pos, colorCount,
973 mode, flags, localMatrix);
Brian Osman2dfab272018-11-06 00:41:40 +0000974 }
Mike Klein024072a2018-11-11 00:26:30 +0000975 // Else it's the 2pt conical radial variant with no degenerate radii, so fall through to the
976 // regular 2pt constructor.
Brian Osman2dfab272018-11-06 00:41:40 +0000977 }
Mike Klein024072a2018-11-11 00:26:30 +0000978
Florin Malita8d3ffad2017-02-03 18:21:17 +0000979 if (localMatrix && !localMatrix->invert(nullptr)) {
980 return nullptr;
981 }
reed6b7a6c72016-08-18 16:13:50 -0700982 EXPAND_1_COLOR(colorCount);
rileya@google.com589708b2012-07-26 20:04:23 +0000983
fmenozzi68d952c2016-08-19 08:56:56 -0700984 ColorStopOptimizer opt(colors, pos, colorCount, mode);
985
reed@google.com437d6eb2013-05-23 19:03:05 +0000986 SkGradientShaderBase::Descriptor desc;
Florin Malita5f379a82017-10-18 16:22:35 -0400987 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
988 localMatrix);
989 return SkTwoPointConicalGradient::Create(start, startRadius, end, endRadius, desc);
rileya@google.com589708b2012-07-26 20:04:23 +0000990}
991
reed8a21c9f2016-03-08 18:50:00 -0800992sk_sp<SkShader> SkGradientShader::MakeSweep(SkScalar cx, SkScalar cy,
brianosmane25d71c2016-09-28 11:27:28 -0700993 const SkColor colors[],
994 const SkScalar pos[],
995 int colorCount,
Mike Reedfae8fce2019-04-03 10:27:45 -0400996 SkTileMode mode,
Florin Malita5a9a9812017-08-01 16:38:08 -0400997 SkScalar startAngle,
998 SkScalar endAngle,
brianosmane25d71c2016-09-28 11:27:28 -0700999 uint32_t flags,
1000 const SkMatrix* localMatrix) {
1001 ColorConverter converter(colors, colorCount);
Florin Malita5a9a9812017-08-01 16:38:08 -04001002 return MakeSweep(cx, cy, converter.fColors4f.begin(), nullptr, pos, colorCount,
1003 mode, startAngle, endAngle, flags, localMatrix);
brianosmane25d71c2016-09-28 11:27:28 -07001004}
1005
1006sk_sp<SkShader> SkGradientShader::MakeSweep(SkScalar cx, SkScalar cy,
1007 const SkColor4f colors[],
1008 sk_sp<SkColorSpace> colorSpace,
1009 const SkScalar pos[],
1010 int colorCount,
Mike Reedfae8fce2019-04-03 10:27:45 -04001011 SkTileMode mode,
Florin Malita5a9a9812017-08-01 16:38:08 -04001012 SkScalar startAngle,
1013 SkScalar endAngle,
brianosmane25d71c2016-09-28 11:27:28 -07001014 uint32_t flags,
1015 const SkMatrix* localMatrix) {
Florin Malita5a9a9812017-08-01 16:38:08 -04001016 if (!valid_grad(colors, pos, colorCount, mode)) {
halcanary96fcdcc2015-08-27 07:41:13 -07001017 return nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +00001018 }
fmenozzie9fd0f82016-08-19 07:50:57 -07001019 if (1 == colorCount) {
Mike Reedc8bea7d2019-04-09 13:55:36 -04001020 return SkShaders::Color(colors[0], std::move(colorSpace));
fmenozzie9fd0f82016-08-19 07:50:57 -07001021 }
Mike Klein024072a2018-11-11 00:26:30 +00001022 if (!SkScalarIsFinite(startAngle) || !SkScalarIsFinite(endAngle) || startAngle > endAngle) {
Florin Malita5a9a9812017-08-01 16:38:08 -04001023 return nullptr;
1024 }
Florin Malita8d3ffad2017-02-03 18:21:17 +00001025 if (localMatrix && !localMatrix->invert(nullptr)) {
1026 return nullptr;
1027 }
rileya@google.com589708b2012-07-26 20:04:23 +00001028
Michael Ludwigd431c722018-11-16 10:00:24 -05001029 if (SkScalarNearlyEqual(startAngle, endAngle, kDegenerateThreshold)) {
Mike Klein024072a2018-11-11 00:26:30 +00001030 // Degenerate gradient, which should follow default degenerate behavior unless it is
1031 // clamped and the angle is greater than 0.
Mike Reedfae8fce2019-04-03 10:27:45 -04001032 if (mode == SkTileMode::kClamp && endAngle > kDegenerateThreshold) {
Mike Klein024072a2018-11-11 00:26:30 +00001033 // In this case, the first color is repeated from 0 to the angle, then a hardstop
1034 // switches to the last color (all other colors are compressed to the infinitely thin
1035 // interpolation region).
1036 static constexpr SkScalar clampPos[3] = {0, 1, 1};
1037 SkColor4f reColors[3] = {colors[0], colors[0], colors[colorCount - 1]};
1038 return MakeSweep(cx, cy, reColors, std::move(colorSpace), clampPos, 3, mode, 0,
1039 endAngle, flags, localMatrix);
1040 } else {
1041 return make_degenerate_gradient(colors, pos, colorCount, std::move(colorSpace), mode);
1042 }
1043 }
1044
Florin Malita5a9a9812017-08-01 16:38:08 -04001045 if (startAngle <= 0 && endAngle >= 360) {
1046 // If the t-range includes [0,1], then we can always use clamping (presumably faster).
Mike Reedfae8fce2019-04-03 10:27:45 -04001047 mode = SkTileMode::kClamp;
Florin Malita5a9a9812017-08-01 16:38:08 -04001048 }
fmenozzi68d952c2016-08-19 08:56:56 -07001049
1050 ColorStopOptimizer opt(colors, pos, colorCount, mode);
1051
reed@google.com437d6eb2013-05-23 19:03:05 +00001052 SkGradientShaderBase::Descriptor desc;
brianosmane25d71c2016-09-28 11:27:28 -07001053 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
1054 localMatrix);
Florin Malita5a9a9812017-08-01 16:38:08 -04001055
1056 const SkScalar t0 = startAngle / 360,
1057 t1 = endAngle / 360;
1058
1059 return sk_make_sp<SkSweepGradient>(SkPoint::Make(cx, cy), t0, t1, desc);
rileya@google.com589708b2012-07-26 20:04:23 +00001060}
1061
Mike Kleinfa5f6ce2018-10-20 08:21:31 -04001062void SkGradientShader::RegisterFlattenables() {
Brian Salomon23356442018-11-30 15:33:19 -05001063 SK_REGISTER_FLATTENABLE(SkLinearGradient);
1064 SK_REGISTER_FLATTENABLE(SkRadialGradient);
1065 SK_REGISTER_FLATTENABLE(SkSweepGradient);
1066 SK_REGISTER_FLATTENABLE(SkTwoPointConicalGradient);
Mike Klein12956722018-10-19 10:00:21 -04001067}