blob: 803f4c4e85ad305f1ec5f3c244b500aec13db35e [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.
Florin Malita64bb78e2017-11-03 12:54:07 -0400190 auto curr = (i == desc.fCount) ? 1 : SkScalarPin(desc.fPos[i], prev, 1);
191 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 Klein85754d52020-01-22 10:04:11 -0600420bool SkGradientShaderBase::onProgram(skvm::Builder* p,
421 const SkMatrix& ctm, const SkMatrix* localM,
422 SkFilterQuality quality, SkColorSpace* dstCS,
423 skvm::Uniforms* uniforms, SkArenaAlloc* alloc,
424 skvm::F32 x, skvm::F32 y,
425 skvm::F32* r, skvm::F32* g, skvm::F32* b, skvm::F32* a) const {
426 SkMatrix inv;
427 if (!this->computeTotalInverse(ctm, localM, &inv)) {
428 return false;
429 }
430 inv.postConcat(fPtsToUnit);
431 inv.normalizePerspective();
432
Mike Klein85754d52020-01-22 10:04:11 -0600433 SkShaderBase::ApplyMatrix(p, inv, &x,&y,uniforms);
Mike Klein85754d52020-01-22 10:04:11 -0600434
Mike Kleincaf5ee42020-01-28 16:11:34 -0600435 skvm::I32 keep;
436 skvm::F32 t;
437 switch (this->transformT(p,uniforms, x,y, &t)) {
438 case MaskNeeded::None: keep = p->splat(~0); break;
439 case MaskNeeded::NaNs: keep = p->eq(t,t); break;
440 default: return false;
441 }
442 t = p->bit_cast(p->bit_and(keep, p->bit_cast(t))); // if (!keep) t = 0
443
444 // Perhaps unexpectedly, clamping is handled naturally by our search, so we
445 // don't explicitly clamp t to [0,1]. That clamp would break hard stops
446 // right at 0 or 1 boundaries in kClamp mode. (kRepeat and kMirror always
447 // produce values in [0,1].)
Mike Klein85754d52020-01-22 10:04:11 -0600448 switch(fTileMode) {
Mike Kleincaf5ee42020-01-28 16:11:34 -0600449 case SkTileMode::kClamp:
450 break;
451
452 case SkTileMode::kDecal:
453 keep = p->bit_and(keep, p->eq(t, p->clamp(t, p->splat(0.0f), p->splat(1.0f))));
454 break;
455
456 case SkTileMode::kRepeat:
457 t = p->sub(t, p->floor(t));
458 break;
459
Mike Klein85754d52020-01-22 10:04:11 -0600460 case SkTileMode::kMirror: {
461 // t = | (t-1) - 2*(floor( (t-1)*0.5 )) - 1 |
462 // {-A-} {--------B-------}
463 skvm::F32 A = p->sub(t, p->splat(1.0f)),
464 B = p->floor( p->mul(A, p->splat(0.5f)));
465 t = p->abs(p->sub(p->sub(A, p->add(B,B)),
466 p->splat(1.0f)));
467 } break;
468 }
469
470 // Transform our colors as we want them interpolated, in dst color space, possibly premul.
471 SkImageInfo common = SkImageInfo::Make(fColorCount,1, kRGBA_F32_SkColorType
472 , kUnpremul_SkAlphaType),
473 src = common.makeColorSpace(fColorSpace),
474 dst = common.makeColorSpace(sk_ref_sp(dstCS));
475 if (fGradFlags & SkGradientShader::kInterpolateColorsInPremul_Flag) {
476 dst = dst.makeAlphaType(kPremul_SkAlphaType);
477 }
478
479 std::vector<float> rgba(4*fColorCount); // TODO: SkSTArray?
480 SkConvertPixels(dst, rgba.data(), dst.minRowBytes(),
481 src, fOrigColors4f, src.minRowBytes());
482
483 // Transform our colors into a scale factor f and bias b such that for
484 // any t between stops i and i+1, the color we want is mad(t, f[i], b[i]).
485 using F4 = skvx::Vec<4,float>;
486 struct FB { F4 f,b; };
487
488 if (fColorCount == 2) {
489 // 2-stop gradients have colors at 0 and 1, and so must be evenly spaced.
490 SkASSERT(fOrigPos == nullptr);
491
492 // With 2 stops, we upload the single FB as uniforms and interpolate directly with t.
493 F4 lo = F4::Load(rgba.data() + 0),
494 hi = F4::Load(rgba.data() + 4);
495 F4 F = hi - lo,
496 B = lo;
497
498 auto T = p->clamp(t, p->splat(0.0f), p->splat(1.0f));
499 *r = p->mad(T, p->uniformF(uniforms->pushF(F[0])), p->uniformF(uniforms->pushF(B[0])));
500 *g = p->mad(T, p->uniformF(uniforms->pushF(F[1])), p->uniformF(uniforms->pushF(B[1])));
501 *b = p->mad(T, p->uniformF(uniforms->pushF(F[2])), p->uniformF(uniforms->pushF(B[2])));
502 *a = p->mad(T, p->uniformF(uniforms->pushF(F[3])), p->uniformF(uniforms->pushF(B[3])));
503 } else {
504 // To handle clamps in search we add a conceptual stop at t=-inf, so we
505 // may need up to fColorCount+1 FBs and fColorCount t stops between them:
506 //
507 // FBs: [color 0] [color 0->1] [color 1->2] [color 2->3] ...
508 // stops: (-inf) t0 t1 t2 ...
509 //
510 // Both these arrays could end up shorter if any hard stops share the same t.
511 FB* fb = alloc->makeArrayDefault<FB>(fColorCount+1);
512 std::vector<float> stops; // TODO: SkSTArray?
513 stops.reserve(fColorCount);
514
515 // Here's our conceptual stop at t=-inf covering all t<=0, clamping to our first color.
516 float t_lo = this->getPos(0);
517 F4 color_lo = F4::Load(rgba.data());
518 fb[0] = { 0.0f, color_lo };
519 // N.B. No stops[] entry for this implicit -inf.
520
521 // Now the non-edge cases, calculating scale and bias between adjacent normal stops.
522 for (int i = 1; i < fColorCount; i++) {
523 float t_hi = this->getPos(i);
524 F4 color_hi = F4::Load(rgba.data() + 4*i);
525
526 // If t_lo == t_hi, we're on a hard stop, and transition immediately to the next color.
527 SkASSERT(t_lo <= t_hi);
528 if (t_lo < t_hi) {
529 F4 f = (color_hi - color_lo) / (t_hi - t_lo),
530 b = color_lo - f*t_lo;
531 stops.push_back(t_lo);
532 fb[stops.size()] = {f,b};
533 }
534
535 t_lo = t_hi;
536 color_lo = color_hi;
537 }
538 // Anything >= our final t clamps to our final color.
539 stops.push_back(t_lo);
540 fb[stops.size()] = { 0.0f, color_lo };
541
542 // We'll gather FBs from that array we just created.
543 skvm::Builder::Uniform fbs = uniforms->pushPtr(fb);
544
545 // Find the two stops we need to interpolate.
546 skvm::I32 ix;
547 if (fOrigPos == nullptr) {
548 // Evenly spaced stops... we can calculate ix directly.
549 // Of note: we need to clamp t and skip over that conceptual -inf stop we made up.
550 ix = p->trunc(p->mad(p->clamp(t, p->splat(0.0f), p->splat(1.0f)),
551 p->uniformF(uniforms->pushF(stops.size() - 1.0f)),
552 p->splat(1.0f)));
553 } else {
554 // Starting ix at 0 bakes in our conceptual first stop at -inf.
555 // TODO: good place to experiment with a loop in skvm.... stops.size() can be huge.
556 ix = p->splat(0);
557 for (float stop : stops) {
558 // ix += (t >= stop) ? +1 : 0 ~~>
559 // ix -= (t >= stop) ? -1 : 0
560 ix = p->sub(ix, p->gte(t, p->uniformF(uniforms->pushF(stop))));
561 }
562 // TODO: we could skip any of the dummy stops GradientShaderBase's ctor added
563 // to ensure the full [0,1] span is covered. This linear search doesn't need
564 // them for correctness, and it'd be up to two fewer stops to check.
565 // N.B. we do still need those stops for the fOrigPos == nullptr direct math path.
566 }
567
568 // A scale factor and bias for each lane, 8 total.
569 // TODO: simpler, faster, tidier to push 8 uniform pointers, one for each struct lane?
570 ix = p->shl(ix, 3); skvm::F32 Fr = p->bit_cast(p->gather32(fbs, ix));
571 ix = p->add(ix, p->splat(1)); skvm::F32 Fg = p->bit_cast(p->gather32(fbs, ix));
572 ix = p->add(ix, p->splat(1)); skvm::F32 Fb = p->bit_cast(p->gather32(fbs, ix));
573 ix = p->add(ix, p->splat(1)); skvm::F32 Fa = p->bit_cast(p->gather32(fbs, ix));
574
575 ix = p->add(ix, p->splat(1)); skvm::F32 Br = p->bit_cast(p->gather32(fbs, ix));
576 ix = p->add(ix, p->splat(1)); skvm::F32 Bg = p->bit_cast(p->gather32(fbs, ix));
577 ix = p->add(ix, p->splat(1)); skvm::F32 Bb = p->bit_cast(p->gather32(fbs, ix));
578 ix = p->add(ix, p->splat(1)); skvm::F32 Ba = p->bit_cast(p->gather32(fbs, ix));
579
580 // This is what we've been building towards!
581 *r = p->mad(t, Fr, Br);
582 *g = p->mad(t, Fg, Bg);
583 *b = p->mad(t, Fb, Bb);
584 *a = p->mad(t, Fa, Ba);
585 }
586
587 // If we interpolated unpremul, premul now to match our output convention.
588 if (0 == (fGradFlags & SkGradientShader::kInterpolateColorsInPremul_Flag)
589 && !fColorsAreOpaque) {
590 p->premul(r,g,b,*a);
591 }
592
Mike Kleincaf5ee42020-01-28 16:11:34 -0600593 *r = p->bit_cast(p->bit_and(keep, p->bit_cast(*r)));
594 *g = p->bit_cast(p->bit_and(keep, p->bit_cast(*g)));
595 *b = p->bit_cast(p->bit_and(keep, p->bit_cast(*b)));
596 *a = p->bit_cast(p->bit_and(keep, p->bit_cast(*a)));
Mike Klein85754d52020-01-22 10:04:11 -0600597 return true;
598}
599
Mike Kleina3771842017-05-04 19:38:48 -0400600
rileya@google.com589708b2012-07-26 20:04:23 +0000601bool SkGradientShaderBase::isOpaque() const {
Mike Reedfae8fce2019-04-03 10:27:45 -0400602 return fColorsAreOpaque && (this->getTileMode() != SkTileMode::kDecal);
Mike Reed62ce2ca2018-02-19 14:20:15 -0500603}
604
reed8367b8c2014-08-22 08:30:20 -0700605static unsigned rounded_divide(unsigned numer, unsigned denom) {
606 return (numer + (denom >> 1)) / denom;
607}
608
609bool SkGradientShaderBase::onAsLuminanceColor(SkColor* lum) const {
610 // we just compute an average color.
611 // possibly we could weight this based on the proportional width for each color
612 // assuming they are not evenly distributed in the fPos array.
613 int r = 0;
614 int g = 0;
615 int b = 0;
616 const int n = fColorCount;
Florin Malita39d71de2017-10-31 11:33:49 -0400617 // TODO: use linear colors?
reed8367b8c2014-08-22 08:30:20 -0700618 for (int i = 0; i < n; ++i) {
Florin Malita39d71de2017-10-31 11:33:49 -0400619 SkColor c = this->getLegacyColor(i);
reed8367b8c2014-08-22 08:30:20 -0700620 r += SkColorGetR(c);
621 g += SkColorGetG(c);
622 b += SkColorGetB(c);
623 }
624 *lum = SkColorSetRGB(rounded_divide(r, n), rounded_divide(g, n), rounded_divide(b, n));
625 return true;
626}
627
Brian Osman6667fb12018-07-03 16:44:02 -0400628SkColor4fXformer::SkColor4fXformer(const SkColor4f* colors, int colorCount,
629 SkColorSpace* src, SkColorSpace* dst) {
Brian Osman6667fb12018-07-03 16:44:02 -0400630 fColors = colors;
Brian Osmanccd39952018-07-06 16:16:43 -0400631
Mike Kleinf9f68ff2018-10-12 14:23:06 -0400632 if (dst && !SkColorSpace::Equals(src, dst)) {
Brian Osman6667fb12018-07-03 16:44:02 -0400633 fStorage.reset(colorCount);
Brian Salomon5dfcf132018-10-12 14:39:32 +0000634
635 auto info = SkImageInfo::Make(colorCount,1, kRGBA_F32_SkColorType, kUnpremul_SkAlphaType);
636
637 SkConvertPixels(info.makeColorSpace(sk_ref_sp(dst)), fStorage.begin(), info.minRowBytes(),
638 info.makeColorSpace(sk_ref_sp(src)), fColors , info.minRowBytes());
639
Brian Osman6667fb12018-07-03 16:44:02 -0400640 fColors = fStorage.begin();
641 }
642}
643
Florin Malita5f379a82017-10-18 16:22:35 -0400644void SkGradientShaderBase::commonAsAGradient(GradientInfo* info) const {
rileya@google.com589708b2012-07-26 20:04:23 +0000645 if (info) {
646 if (info->fColorCount >= fColorCount) {
647 if (info->fColors) {
Florin Malita39d71de2017-10-31 11:33:49 -0400648 for (int i = 0; i < fColorCount; ++i) {
649 info->fColors[i] = this->getLegacyColor(i);
650 }
rileya@google.com589708b2012-07-26 20:04:23 +0000651 }
652 if (info->fColorOffsets) {
Florin Malitaed6ae562017-10-28 11:06:48 -0400653 for (int i = 0; i < fColorCount; ++i) {
654 info->fColorOffsets[i] = this->getPos(i);
rileya@google.com589708b2012-07-26 20:04:23 +0000655 }
656 }
657 }
658 info->fColorCount = fColorCount;
659 info->fTileMode = fTileMode;
reed@google.com3d3a8602013-05-24 14:58:44 +0000660 info->fGradientFlags = fGradFlags;
rileya@google.com589708b2012-07-26 20:04:23 +0000661 }
662}
663
664///////////////////////////////////////////////////////////////////////////////
665///////////////////////////////////////////////////////////////////////////////
666
reed1b747302015-01-06 07:13:19 -0800667// Return true if these parameters are valid/legal/safe to construct a gradient
668//
brianosmane25d71c2016-09-28 11:27:28 -0700669static bool valid_grad(const SkColor4f colors[], const SkScalar pos[], int count,
Mike Reedfae8fce2019-04-03 10:27:45 -0400670 SkTileMode tileMode) {
671 return nullptr != colors && count >= 1 && (unsigned)tileMode < kSkTileModeCount;
reed1b747302015-01-06 07:13:19 -0800672}
673
reed@google.com437d6eb2013-05-23 19:03:05 +0000674static void desc_init(SkGradientShaderBase::Descriptor* desc,
brianosmane25d71c2016-09-28 11:27:28 -0700675 const SkColor4f colors[], sk_sp<SkColorSpace> colorSpace,
676 const SkScalar pos[], int colorCount,
Mike Reedfae8fce2019-04-03 10:27:45 -0400677 SkTileMode mode, uint32_t flags, const SkMatrix* localMatrix) {
fmalita748d6202016-05-11 11:39:58 -0700678 SkASSERT(colorCount > 1);
679
commit-bot@chromium.org6c5aea22014-04-22 16:25:15 +0000680 desc->fColors = colors;
brianosmane25d71c2016-09-28 11:27:28 -0700681 desc->fColorSpace = std::move(colorSpace);
commit-bot@chromium.org6c5aea22014-04-22 16:25:15 +0000682 desc->fPos = pos;
683 desc->fCount = colorCount;
684 desc->fTileMode = mode;
commit-bot@chromium.org6c5aea22014-04-22 16:25:15 +0000685 desc->fGradFlags = flags;
reedaddf2ed2014-08-11 08:28:24 -0700686 desc->fLocalMatrix = localMatrix;
reed@google.com437d6eb2013-05-23 19:03:05 +0000687}
688
Mike Klein024072a2018-11-11 00:26:30 +0000689static SkColor4f average_gradient_color(const SkColor4f colors[], const SkScalar pos[],
690 int colorCount) {
691 // The gradient is a piecewise linear interpolation between colors. For a given interval,
692 // the integral between the two endpoints is 0.5 * (ci + cj) * (pj - pi), which provides that
693 // intervals average color. The overall average color is thus the sum of each piece. The thing
694 // to keep in mind is that the provided gradient definition may implicitly use p=0 and p=1.
695 Sk4f blend(0.0);
696 // Bake 1/(colorCount - 1) uniform stop difference into this scale factor
697 SkScalar wScale = pos ? 0.5 : 0.5 / (colorCount - 1);
698 for (int i = 0; i < colorCount - 1; ++i) {
699 // Calculate the average color for the interval between pos(i) and pos(i+1)
700 Sk4f c0 = Sk4f::Load(&colors[i]);
701 Sk4f c1 = Sk4f::Load(&colors[i + 1]);
702 // when pos == null, there are colorCount uniformly distributed stops, going from 0 to 1,
703 // so pos[i + 1] - pos[i] = 1/(colorCount-1)
704 SkScalar w = pos ? (pos[i + 1] - pos[i]) : SK_Scalar1;
705 blend += wScale * w * (c1 + c0);
706 }
707
708 // Now account for any implicit intervals at the start or end of the stop definitions
709 if (pos) {
710 if (pos[0] > 0.0) {
711 // The first color is fixed between p = 0 to pos[0], so 0.5 * (ci + cj) * (pj - pi)
712 // becomes 0.5 * (c + c) * (pj - 0) = c * pj
713 Sk4f c = Sk4f::Load(&colors[0]);
714 blend += pos[0] * c;
715 }
716 if (pos[colorCount - 1] < SK_Scalar1) {
717 // The last color is fixed between pos[n-1] to p = 1, so 0.5 * (ci + cj) * (pj - pi)
718 // becomes 0.5 * (c + c) * (1 - pi) = c * (1 - pi)
719 Sk4f c = Sk4f::Load(&colors[colorCount - 1]);
720 blend += (1 - pos[colorCount - 1]) * c;
721 }
722 }
723
724 SkColor4f avg;
725 blend.store(&avg);
726 return avg;
727}
728
Michael Ludwigd431c722018-11-16 10:00:24 -0500729// The default SkScalarNearlyZero threshold of .0024 is too big and causes regressions for svg
730// gradients defined in the wild.
731static constexpr SkScalar kDegenerateThreshold = SK_Scalar1 / (1 << 15);
732
Mike Klein024072a2018-11-11 00:26:30 +0000733// Except for special circumstances of clamped gradients, every gradient shape--when degenerate--
734// can be mapped to the same fallbacks. The specific shape factories must account for special
735// clamped conditions separately, this will always return the last color for clamped gradients.
736static sk_sp<SkShader> make_degenerate_gradient(const SkColor4f colors[], const SkScalar pos[],
737 int colorCount, sk_sp<SkColorSpace> colorSpace,
Mike Reedfae8fce2019-04-03 10:27:45 -0400738 SkTileMode mode) {
Mike Klein024072a2018-11-11 00:26:30 +0000739 switch(mode) {
Mike Reedfae8fce2019-04-03 10:27:45 -0400740 case SkTileMode::kDecal:
Mike Klein024072a2018-11-11 00:26:30 +0000741 // normally this would reject the area outside of the interpolation region, so since
742 // inside region is empty when the radii are equal, the entire draw region is empty
Mike Reedc8bea7d2019-04-09 13:55:36 -0400743 return SkShaders::Empty();
Mike Reedfae8fce2019-04-03 10:27:45 -0400744 case SkTileMode::kRepeat:
745 case SkTileMode::kMirror:
Mike Klein024072a2018-11-11 00:26:30 +0000746 // repeat and mirror are treated the same: the border colors are never visible,
747 // but approximate the final color as infinite repetitions of the colors, so
748 // it can be represented as the average color of the gradient.
Mike Reedc8bea7d2019-04-09 13:55:36 -0400749 return SkShaders::Color(
Mike Klein024072a2018-11-11 00:26:30 +0000750 average_gradient_color(colors, pos, colorCount), std::move(colorSpace));
Mike Reedfae8fce2019-04-03 10:27:45 -0400751 case SkTileMode::kClamp:
Mike Klein024072a2018-11-11 00:26:30 +0000752 // Depending on how the gradient shape degenerates, there may be a more specialized
753 // fallback representation for the factories to use, but this is a reasonable default.
Mike Reedc8bea7d2019-04-09 13:55:36 -0400754 return SkShaders::Color(colors[colorCount - 1], std::move(colorSpace));
Mike Klein024072a2018-11-11 00:26:30 +0000755 }
Mike Reedfae8fce2019-04-03 10:27:45 -0400756 SkDEBUGFAIL("Should not be reached");
757 return nullptr;
Mike Klein024072a2018-11-11 00:26:30 +0000758}
759
brianosmane25d71c2016-09-28 11:27:28 -0700760// assumes colors is SkColor4f* and pos is SkScalar*
fmenozzie9fd0f82016-08-19 07:50:57 -0700761#define EXPAND_1_COLOR(count) \
brianosmane25d71c2016-09-28 11:27:28 -0700762 SkColor4f tmp[2]; \
fmenozzie9fd0f82016-08-19 07:50:57 -0700763 do { \
764 if (1 == count) { \
765 tmp[0] = tmp[1] = colors[0]; \
766 colors = tmp; \
767 pos = nullptr; \
768 count = 2; \
769 } \
770 } while (0)
771
fmenozzi68d952c2016-08-19 08:56:56 -0700772struct ColorStopOptimizer {
Mike Reedfae8fce2019-04-03 10:27:45 -0400773 ColorStopOptimizer(const SkColor4f* colors, const SkScalar* pos, int count, SkTileMode mode)
fmenozzi68d952c2016-08-19 08:56:56 -0700774 : fColors(colors)
775 , fPos(pos)
776 , fCount(count) {
777
778 if (!pos || count != 3) {
779 return;
780 }
781
782 if (SkScalarNearlyEqual(pos[0], 0.0f) &&
783 SkScalarNearlyEqual(pos[1], 0.0f) &&
784 SkScalarNearlyEqual(pos[2], 1.0f)) {
785
Mike Reedfae8fce2019-04-03 10:27:45 -0400786 if (SkTileMode::kRepeat == mode || SkTileMode::kMirror == mode ||
fmenozzi68d952c2016-08-19 08:56:56 -0700787 colors[0] == colors[1]) {
788
fmalita582a6562016-08-22 06:28:57 -0700789 // Ignore the leftmost color/pos.
790 fColors += 1;
791 fPos += 1;
792 fCount = 2;
fmenozzi68d952c2016-08-19 08:56:56 -0700793 }
794 } else if (SkScalarNearlyEqual(pos[0], 0.0f) &&
795 SkScalarNearlyEqual(pos[1], 1.0f) &&
796 SkScalarNearlyEqual(pos[2], 1.0f)) {
797
Mike Reedfae8fce2019-04-03 10:27:45 -0400798 if (SkTileMode::kRepeat == mode || SkTileMode::kMirror == mode ||
fmenozzi68d952c2016-08-19 08:56:56 -0700799 colors[1] == colors[2]) {
800
fmalita582a6562016-08-22 06:28:57 -0700801 // Ignore the rightmost color/pos.
fmenozzi68d952c2016-08-19 08:56:56 -0700802 fCount = 2;
803 }
804 }
805 }
806
brianosmane25d71c2016-09-28 11:27:28 -0700807 const SkColor4f* fColors;
808 const SkScalar* fPos;
809 int fCount;
810};
811
812struct ColorConverter {
813 ColorConverter(const SkColor* colors, int count) {
Brian Osman6667fb12018-07-03 16:44:02 -0400814 const float ONE_OVER_255 = 1.f / 255;
brianosmane25d71c2016-09-28 11:27:28 -0700815 for (int i = 0; i < count; ++i) {
Brian Osman6667fb12018-07-03 16:44:02 -0400816 fColors4f.push_back({
817 SkColorGetR(colors[i]) * ONE_OVER_255,
818 SkColorGetG(colors[i]) * ONE_OVER_255,
819 SkColorGetB(colors[i]) * ONE_OVER_255,
820 SkColorGetA(colors[i]) * ONE_OVER_255 });
brianosmane25d71c2016-09-28 11:27:28 -0700821 }
822 }
823
824 SkSTArray<2, SkColor4f, true> fColors4f;
fmenozzi68d952c2016-08-19 08:56:56 -0700825};
826
reed8a21c9f2016-03-08 18:50:00 -0800827sk_sp<SkShader> SkGradientShader::MakeLinear(const SkPoint pts[2],
fmenozzi68d952c2016-08-19 08:56:56 -0700828 const SkColor colors[],
829 const SkScalar pos[], int colorCount,
Mike Reedfae8fce2019-04-03 10:27:45 -0400830 SkTileMode mode,
fmenozzi68d952c2016-08-19 08:56:56 -0700831 uint32_t flags,
832 const SkMatrix* localMatrix) {
brianosmane25d71c2016-09-28 11:27:28 -0700833 ColorConverter converter(colors, colorCount);
834 return MakeLinear(pts, converter.fColors4f.begin(), nullptr, pos, colorCount, mode, flags,
835 localMatrix);
836}
837
838sk_sp<SkShader> SkGradientShader::MakeLinear(const SkPoint pts[2],
839 const SkColor4f colors[],
840 sk_sp<SkColorSpace> colorSpace,
841 const SkScalar pos[], int colorCount,
Mike Reedfae8fce2019-04-03 10:27:45 -0400842 SkTileMode mode,
brianosmane25d71c2016-09-28 11:27:28 -0700843 uint32_t flags,
844 const SkMatrix* localMatrix) {
fmalitac5231042016-08-10 05:45:50 -0700845 if (!pts || !SkScalarIsFinite((pts[1] - pts[0]).length())) {
halcanary96fcdcc2015-08-27 07:41:13 -0700846 return nullptr;
reed1b747302015-01-06 07:13:19 -0800847 }
848 if (!valid_grad(colors, pos, colorCount, mode)) {
halcanary96fcdcc2015-08-27 07:41:13 -0700849 return nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +0000850 }
fmenozzie9fd0f82016-08-19 07:50:57 -0700851 if (1 == colorCount) {
Mike Reedc8bea7d2019-04-09 13:55:36 -0400852 return SkShaders::Color(colors[0], std::move(colorSpace));
fmenozzie9fd0f82016-08-19 07:50:57 -0700853 }
Florin Malita8d3ffad2017-02-03 18:21:17 +0000854 if (localMatrix && !localMatrix->invert(nullptr)) {
855 return nullptr;
856 }
rileya@google.com589708b2012-07-26 20:04:23 +0000857
Michael Ludwigd431c722018-11-16 10:00:24 -0500858 if (SkScalarNearlyZero((pts[1] - pts[0]).length(), kDegenerateThreshold)) {
Mike Klein024072a2018-11-11 00:26:30 +0000859 // Degenerate gradient, the only tricky complication is when in clamp mode, the limit of
860 // the gradient approaches two half planes of solid color (first and last). However, they
861 // are divided by the line perpendicular to the start and end point, which becomes undefined
862 // once start and end are exactly the same, so just use the end color for a stable solution.
863 return make_degenerate_gradient(colors, pos, colorCount, std::move(colorSpace), mode);
864 }
865
fmenozzi68d952c2016-08-19 08:56:56 -0700866 ColorStopOptimizer opt(colors, pos, colorCount, mode);
867
reed@google.com437d6eb2013-05-23 19:03:05 +0000868 SkGradientShaderBase::Descriptor desc;
brianosmane25d71c2016-09-28 11:27:28 -0700869 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
870 localMatrix);
reed8a21c9f2016-03-08 18:50:00 -0800871 return sk_make_sp<SkLinearGradient>(pts, desc);
rileya@google.com589708b2012-07-26 20:04:23 +0000872}
873
reed8a21c9f2016-03-08 18:50:00 -0800874sk_sp<SkShader> SkGradientShader::MakeRadial(const SkPoint& center, SkScalar radius,
brianosmane25d71c2016-09-28 11:27:28 -0700875 const SkColor colors[],
876 const SkScalar pos[], int colorCount,
Mike Reedfae8fce2019-04-03 10:27:45 -0400877 SkTileMode mode,
brianosmane25d71c2016-09-28 11:27:28 -0700878 uint32_t flags,
879 const SkMatrix* localMatrix) {
880 ColorConverter converter(colors, colorCount);
881 return MakeRadial(center, radius, converter.fColors4f.begin(), nullptr, pos, colorCount, mode,
882 flags, localMatrix);
883}
884
885sk_sp<SkShader> SkGradientShader::MakeRadial(const SkPoint& center, SkScalar radius,
886 const SkColor4f colors[],
887 sk_sp<SkColorSpace> colorSpace,
888 const SkScalar pos[], int colorCount,
Mike Reedfae8fce2019-04-03 10:27:45 -0400889 SkTileMode mode,
brianosmane25d71c2016-09-28 11:27:28 -0700890 uint32_t flags,
891 const SkMatrix* localMatrix) {
Mike Klein024072a2018-11-11 00:26:30 +0000892 if (radius < 0) {
halcanary96fcdcc2015-08-27 07:41:13 -0700893 return nullptr;
reed1b747302015-01-06 07:13:19 -0800894 }
895 if (!valid_grad(colors, pos, colorCount, mode)) {
halcanary96fcdcc2015-08-27 07:41:13 -0700896 return nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +0000897 }
fmenozzie9fd0f82016-08-19 07:50:57 -0700898 if (1 == colorCount) {
Mike Reedc8bea7d2019-04-09 13:55:36 -0400899 return SkShaders::Color(colors[0], std::move(colorSpace));
fmenozzie9fd0f82016-08-19 07:50:57 -0700900 }
Florin Malita8d3ffad2017-02-03 18:21:17 +0000901 if (localMatrix && !localMatrix->invert(nullptr)) {
902 return nullptr;
903 }
rileya@google.com589708b2012-07-26 20:04:23 +0000904
Michael Ludwigd431c722018-11-16 10:00:24 -0500905 if (SkScalarNearlyZero(radius, kDegenerateThreshold)) {
Mike Klein024072a2018-11-11 00:26:30 +0000906 // Degenerate gradient optimization, and no special logic needed for clamped radial gradient
907 return make_degenerate_gradient(colors, pos, colorCount, std::move(colorSpace), mode);
908 }
909
fmenozzi68d952c2016-08-19 08:56:56 -0700910 ColorStopOptimizer opt(colors, pos, colorCount, mode);
911
reed@google.com437d6eb2013-05-23 19:03:05 +0000912 SkGradientShaderBase::Descriptor desc;
brianosmane25d71c2016-09-28 11:27:28 -0700913 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
914 localMatrix);
reed8a21c9f2016-03-08 18:50:00 -0800915 return sk_make_sp<SkRadialGradient>(center, radius, desc);
rileya@google.com589708b2012-07-26 20:04:23 +0000916}
917
reed8a21c9f2016-03-08 18:50:00 -0800918sk_sp<SkShader> SkGradientShader::MakeTwoPointConical(const SkPoint& start,
brianosmane25d71c2016-09-28 11:27:28 -0700919 SkScalar startRadius,
920 const SkPoint& end,
921 SkScalar endRadius,
922 const SkColor colors[],
923 const SkScalar pos[],
924 int colorCount,
Mike Reedfae8fce2019-04-03 10:27:45 -0400925 SkTileMode mode,
brianosmane25d71c2016-09-28 11:27:28 -0700926 uint32_t flags,
927 const SkMatrix* localMatrix) {
928 ColorConverter converter(colors, colorCount);
929 return MakeTwoPointConical(start, startRadius, end, endRadius, converter.fColors4f.begin(),
930 nullptr, pos, colorCount, mode, flags, localMatrix);
931}
932
933sk_sp<SkShader> SkGradientShader::MakeTwoPointConical(const SkPoint& start,
934 SkScalar startRadius,
935 const SkPoint& end,
936 SkScalar endRadius,
937 const SkColor4f colors[],
938 sk_sp<SkColorSpace> colorSpace,
939 const SkScalar pos[],
940 int colorCount,
Mike Reedfae8fce2019-04-03 10:27:45 -0400941 SkTileMode mode,
brianosmane25d71c2016-09-28 11:27:28 -0700942 uint32_t flags,
943 const SkMatrix* localMatrix) {
reed1b747302015-01-06 07:13:19 -0800944 if (startRadius < 0 || endRadius < 0) {
halcanary96fcdcc2015-08-27 07:41:13 -0700945 return nullptr;
reed1b747302015-01-06 07:13:19 -0800946 }
947 if (!valid_grad(colors, pos, colorCount, mode)) {
halcanary96fcdcc2015-08-27 07:41:13 -0700948 return nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +0000949 }
Michael Ludwigd431c722018-11-16 10:00:24 -0500950 if (SkScalarNearlyZero((start - end).length(), kDegenerateThreshold)) {
Mike Klein024072a2018-11-11 00:26:30 +0000951 // If the center positions are the same, then the gradient is the radial variant of a 2 pt
952 // conical gradient, an actual radial gradient (startRadius == 0), or it is fully degenerate
953 // (startRadius == endRadius).
Michael Ludwigd431c722018-11-16 10:00:24 -0500954 if (SkScalarNearlyEqual(startRadius, endRadius, kDegenerateThreshold)) {
Mike Klein024072a2018-11-11 00:26:30 +0000955 // Degenerate case, where the interpolation region area approaches zero. The proper
956 // behavior depends on the tile mode, which is consistent with the default degenerate
957 // gradient behavior, except when mode = clamp and the radii > 0.
Mike Reedfae8fce2019-04-03 10:27:45 -0400958 if (mode == SkTileMode::kClamp && endRadius > kDegenerateThreshold) {
Mike Klein024072a2018-11-11 00:26:30 +0000959 // The interpolation region becomes an infinitely thin ring at the radius, so the
960 // final gradient will be the first color repeated from p=0 to 1, and then a hard
961 // stop switching to the last color at p=1.
962 static constexpr SkScalar circlePos[3] = {0, 1, 1};
963 SkColor4f reColors[3] = {colors[0], colors[0], colors[colorCount - 1]};
964 return MakeRadial(start, endRadius, reColors, std::move(colorSpace),
965 circlePos, 3, mode, flags, localMatrix);
966 } else {
967 // Otherwise use the default degenerate case
968 return make_degenerate_gradient(
969 colors, pos, colorCount, std::move(colorSpace), mode);
970 }
Michael Ludwigd431c722018-11-16 10:00:24 -0500971 } else if (SkScalarNearlyZero(startRadius, kDegenerateThreshold)) {
Mike Klein024072a2018-11-11 00:26:30 +0000972 // We can treat this gradient as radial, which is faster. If we got here, we know
973 // that endRadius is not equal to 0, so this produces a meaningful gradient
974 return MakeRadial(start, endRadius, colors, std::move(colorSpace), pos, colorCount,
975 mode, flags, localMatrix);
Brian Osman2dfab272018-11-06 00:41:40 +0000976 }
Mike Klein024072a2018-11-11 00:26:30 +0000977 // Else it's the 2pt conical radial variant with no degenerate radii, so fall through to the
978 // regular 2pt constructor.
Brian Osman2dfab272018-11-06 00:41:40 +0000979 }
Mike Klein024072a2018-11-11 00:26:30 +0000980
Florin Malita8d3ffad2017-02-03 18:21:17 +0000981 if (localMatrix && !localMatrix->invert(nullptr)) {
982 return nullptr;
983 }
reed6b7a6c72016-08-18 16:13:50 -0700984 EXPAND_1_COLOR(colorCount);
rileya@google.com589708b2012-07-26 20:04:23 +0000985
fmenozzi68d952c2016-08-19 08:56:56 -0700986 ColorStopOptimizer opt(colors, pos, colorCount, mode);
987
reed@google.com437d6eb2013-05-23 19:03:05 +0000988 SkGradientShaderBase::Descriptor desc;
Florin Malita5f379a82017-10-18 16:22:35 -0400989 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
990 localMatrix);
991 return SkTwoPointConicalGradient::Create(start, startRadius, end, endRadius, desc);
rileya@google.com589708b2012-07-26 20:04:23 +0000992}
993
reed8a21c9f2016-03-08 18:50:00 -0800994sk_sp<SkShader> SkGradientShader::MakeSweep(SkScalar cx, SkScalar cy,
brianosmane25d71c2016-09-28 11:27:28 -0700995 const SkColor colors[],
996 const SkScalar pos[],
997 int colorCount,
Mike Reedfae8fce2019-04-03 10:27:45 -0400998 SkTileMode mode,
Florin Malita5a9a9812017-08-01 16:38:08 -0400999 SkScalar startAngle,
1000 SkScalar endAngle,
brianosmane25d71c2016-09-28 11:27:28 -07001001 uint32_t flags,
1002 const SkMatrix* localMatrix) {
1003 ColorConverter converter(colors, colorCount);
Florin Malita5a9a9812017-08-01 16:38:08 -04001004 return MakeSweep(cx, cy, converter.fColors4f.begin(), nullptr, pos, colorCount,
1005 mode, startAngle, endAngle, flags, localMatrix);
brianosmane25d71c2016-09-28 11:27:28 -07001006}
1007
1008sk_sp<SkShader> SkGradientShader::MakeSweep(SkScalar cx, SkScalar cy,
1009 const SkColor4f colors[],
1010 sk_sp<SkColorSpace> colorSpace,
1011 const SkScalar pos[],
1012 int colorCount,
Mike Reedfae8fce2019-04-03 10:27:45 -04001013 SkTileMode mode,
Florin Malita5a9a9812017-08-01 16:38:08 -04001014 SkScalar startAngle,
1015 SkScalar endAngle,
brianosmane25d71c2016-09-28 11:27:28 -07001016 uint32_t flags,
1017 const SkMatrix* localMatrix) {
Florin Malita5a9a9812017-08-01 16:38:08 -04001018 if (!valid_grad(colors, pos, colorCount, mode)) {
halcanary96fcdcc2015-08-27 07:41:13 -07001019 return nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +00001020 }
fmenozzie9fd0f82016-08-19 07:50:57 -07001021 if (1 == colorCount) {
Mike Reedc8bea7d2019-04-09 13:55:36 -04001022 return SkShaders::Color(colors[0], std::move(colorSpace));
fmenozzie9fd0f82016-08-19 07:50:57 -07001023 }
Mike Klein024072a2018-11-11 00:26:30 +00001024 if (!SkScalarIsFinite(startAngle) || !SkScalarIsFinite(endAngle) || startAngle > endAngle) {
Florin Malita5a9a9812017-08-01 16:38:08 -04001025 return nullptr;
1026 }
Florin Malita8d3ffad2017-02-03 18:21:17 +00001027 if (localMatrix && !localMatrix->invert(nullptr)) {
1028 return nullptr;
1029 }
rileya@google.com589708b2012-07-26 20:04:23 +00001030
Michael Ludwigd431c722018-11-16 10:00:24 -05001031 if (SkScalarNearlyEqual(startAngle, endAngle, kDegenerateThreshold)) {
Mike Klein024072a2018-11-11 00:26:30 +00001032 // Degenerate gradient, which should follow default degenerate behavior unless it is
1033 // clamped and the angle is greater than 0.
Mike Reedfae8fce2019-04-03 10:27:45 -04001034 if (mode == SkTileMode::kClamp && endAngle > kDegenerateThreshold) {
Mike Klein024072a2018-11-11 00:26:30 +00001035 // In this case, the first color is repeated from 0 to the angle, then a hardstop
1036 // switches to the last color (all other colors are compressed to the infinitely thin
1037 // interpolation region).
1038 static constexpr SkScalar clampPos[3] = {0, 1, 1};
1039 SkColor4f reColors[3] = {colors[0], colors[0], colors[colorCount - 1]};
1040 return MakeSweep(cx, cy, reColors, std::move(colorSpace), clampPos, 3, mode, 0,
1041 endAngle, flags, localMatrix);
1042 } else {
1043 return make_degenerate_gradient(colors, pos, colorCount, std::move(colorSpace), mode);
1044 }
1045 }
1046
Florin Malita5a9a9812017-08-01 16:38:08 -04001047 if (startAngle <= 0 && endAngle >= 360) {
1048 // If the t-range includes [0,1], then we can always use clamping (presumably faster).
Mike Reedfae8fce2019-04-03 10:27:45 -04001049 mode = SkTileMode::kClamp;
Florin Malita5a9a9812017-08-01 16:38:08 -04001050 }
fmenozzi68d952c2016-08-19 08:56:56 -07001051
1052 ColorStopOptimizer opt(colors, pos, colorCount, mode);
1053
reed@google.com437d6eb2013-05-23 19:03:05 +00001054 SkGradientShaderBase::Descriptor desc;
brianosmane25d71c2016-09-28 11:27:28 -07001055 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
1056 localMatrix);
Florin Malita5a9a9812017-08-01 16:38:08 -04001057
1058 const SkScalar t0 = startAngle / 360,
1059 t1 = endAngle / 360;
1060
1061 return sk_make_sp<SkSweepGradient>(SkPoint::Make(cx, cy), t0, t1, desc);
rileya@google.com589708b2012-07-26 20:04:23 +00001062}
1063
Mike Kleinfa5f6ce2018-10-20 08:21:31 -04001064void SkGradientShader::RegisterFlattenables() {
Brian Salomon23356442018-11-30 15:33:19 -05001065 SK_REGISTER_FLATTENABLE(SkLinearGradient);
1066 SK_REGISTER_FLATTENABLE(SkRadialGradient);
1067 SK_REGISTER_FLATTENABLE(SkSweepGradient);
1068 SK_REGISTER_FLATTENABLE(SkTwoPointConicalGradient);
Mike Klein12956722018-10-19 10:00:21 -04001069}