blob: 60b9e34f79c5d04f9be7c6c311c8ad1e18107f73 [file] [log] [blame]
rileya@google.com589708b2012-07-26 20:04:23 +00001/*
2 * Copyright 2006 The Android Open Source Project
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
Herb Derby4de13042017-05-15 10:49:39 -04008#include <algorithm>
fmalitabc590c02016-02-22 09:12:33 -08009#include "Sk4fLinearGradient.h"
raftias94888332016-10-18 10:02:51 -070010#include "SkColorSpace_XYZ.h"
Florin Malita39d71de2017-10-31 11:33:49 -040011#include "SkColorSpaceXformer.h"
Florin Malitacad3b8c2017-10-28 21:42:50 -040012#include "SkFloatBits.h"
Florin Malitad4e9ec82017-10-25 18:00:26 -040013#include "SkGradientBitmapCache.h"
rileya@google.com589708b2012-07-26 20:04:23 +000014#include "SkGradientShaderPriv.h"
brianosmand4546092016-09-22 12:31:58 -070015#include "SkHalf.h"
rileya@google.com589708b2012-07-26 20:04:23 +000016#include "SkLinearGradient.h"
Mike Reed6b3155c2017-04-03 14:41:44 -040017#include "SkMallocPixelRef.h"
rileya@google.com589708b2012-07-26 20:04:23 +000018#include "SkRadialGradient.h"
Florin Malitad4e9ec82017-10-25 18:00:26 -040019#include "SkReadBuffer.h"
Mike Klein02ab8cc2017-05-04 22:41:05 +000020#include "SkSweepGradient.h"
Mike Kleina3771842017-05-04 19:38:48 -040021#include "SkTwoPointConicalGradient.h"
Florin Malitad4e9ec82017-10-25 18:00:26 -040022#include "SkWriteBuffer.h"
Herb Derby4de13042017-05-15 10:49:39 -040023#include "../../jumper/SkJumper.h"
24
rileya@google.com589708b2012-07-26 20:04:23 +000025
brianosmane25d71c2016-09-28 11:27:28 -070026enum GradientSerializationFlags {
27 // Bits 29:31 used for various boolean flags
28 kHasPosition_GSF = 0x80000000,
29 kHasLocalMatrix_GSF = 0x40000000,
30 kHasColorSpace_GSF = 0x20000000,
31
32 // Bits 12:28 unused
33
34 // Bits 8:11 for fTileMode
35 kTileModeShift_GSF = 8,
36 kTileModeMask_GSF = 0xF,
37
38 // Bits 0:7 for fGradFlags (note that kForce4fContext_PrivateFlag is 0x80)
39 kGradFlagsShift_GSF = 0,
40 kGradFlagsMask_GSF = 0xFF,
41};
42
reed9fa60da2014-08-21 07:59:51 -070043void SkGradientShaderBase::Descriptor::flatten(SkWriteBuffer& buffer) const {
brianosmane25d71c2016-09-28 11:27:28 -070044 uint32_t flags = 0;
reed9fa60da2014-08-21 07:59:51 -070045 if (fPos) {
brianosmane25d71c2016-09-28 11:27:28 -070046 flags |= kHasPosition_GSF;
reed9fa60da2014-08-21 07:59:51 -070047 }
reed9fa60da2014-08-21 07:59:51 -070048 if (fLocalMatrix) {
brianosmane25d71c2016-09-28 11:27:28 -070049 flags |= kHasLocalMatrix_GSF;
50 }
51 sk_sp<SkData> colorSpaceData = fColorSpace ? fColorSpace->serialize() : nullptr;
52 if (colorSpaceData) {
53 flags |= kHasColorSpace_GSF;
54 }
55 SkASSERT(static_cast<uint32_t>(fTileMode) <= kTileModeMask_GSF);
56 flags |= (fTileMode << kTileModeShift_GSF);
57 SkASSERT(fGradFlags <= kGradFlagsMask_GSF);
58 flags |= (fGradFlags << kGradFlagsShift_GSF);
59
60 buffer.writeUInt(flags);
61
62 buffer.writeColor4fArray(fColors, fCount);
63 if (colorSpaceData) {
64 buffer.writeDataAsByteArray(colorSpaceData.get());
65 }
66 if (fPos) {
67 buffer.writeScalarArray(fPos, fCount);
68 }
69 if (fLocalMatrix) {
reed9fa60da2014-08-21 07:59:51 -070070 buffer.writeMatrix(*fLocalMatrix);
reed9fa60da2014-08-21 07:59:51 -070071 }
72}
73
74bool SkGradientShaderBase::DescriptorScope::unflatten(SkReadBuffer& buffer) {
Mike Reed70bc94f2017-06-08 12:45:52 -040075 // New gradient format. Includes floating point color, color space, densely packed flags
76 uint32_t flags = buffer.readUInt();
reed9fa60da2014-08-21 07:59:51 -070077
Mike Reed70bc94f2017-06-08 12:45:52 -040078 fTileMode = (SkShader::TileMode)((flags >> kTileModeShift_GSF) & kTileModeMask_GSF);
79 fGradFlags = (flags >> kGradFlagsShift_GSF) & kGradFlagsMask_GSF;
reed9fa60da2014-08-21 07:59:51 -070080
Mike Reed70bc94f2017-06-08 12:45:52 -040081 fCount = buffer.getArrayCount();
82 if (fCount > kStorageCount) {
83 size_t allocSize = (sizeof(SkColor4f) + sizeof(SkScalar)) * fCount;
84 fDynamicStorage.reset(allocSize);
85 fColors = (SkColor4f*)fDynamicStorage.get();
86 fPos = (SkScalar*)(fColors + fCount);
87 } else {
88 fColors = fColorStorage;
89 fPos = fPosStorage;
90 }
91 if (!buffer.readColor4fArray(mutableColors(), fCount)) {
92 return false;
93 }
94 if (SkToBool(flags & kHasColorSpace_GSF)) {
95 sk_sp<SkData> data = buffer.readByteArrayAsData();
96 fColorSpace = SkColorSpace::Deserialize(data->data(), data->size());
97 } else {
brianosmane25d71c2016-09-28 11:27:28 -070098 fColorSpace = nullptr;
Mike Reed70bc94f2017-06-08 12:45:52 -040099 }
100 if (SkToBool(flags & kHasPosition_GSF)) {
101 if (!buffer.readScalarArray(mutablePos(), fCount)) {
102 return false;
brianosmane25d71c2016-09-28 11:27:28 -0700103 }
reed9fa60da2014-08-21 07:59:51 -0700104 } else {
Mike Reed70bc94f2017-06-08 12:45:52 -0400105 fPos = nullptr;
106 }
107 if (SkToBool(flags & kHasLocalMatrix_GSF)) {
108 fLocalMatrix = &fLocalMatrixStorage;
109 buffer.readMatrix(&fLocalMatrixStorage);
110 } else {
111 fLocalMatrix = nullptr;
reed9fa60da2014-08-21 07:59:51 -0700112 }
113 return buffer.isValid();
114}
115
116////////////////////////////////////////////////////////////////////////////////////////////
117
mtkleincc695fe2014-12-10 10:29:19 -0800118SkGradientShaderBase::SkGradientShaderBase(const Descriptor& desc, const SkMatrix& ptsToUnit)
reedaddf2ed2014-08-11 08:28:24 -0700119 : INHERITED(desc.fLocalMatrix)
mtkleincc695fe2014-12-10 10:29:19 -0800120 , fPtsToUnit(ptsToUnit)
Florin Malitaabc85752018-04-25 22:18:37 -0400121 , fColorSpace(desc.fColorSpace ? desc.fColorSpace : SkColorSpace::MakeSRGBLinear())
Florin Malita39d71de2017-10-31 11:33:49 -0400122 , fColorsAreOpaque(true)
commit-bot@chromium.org9c9005a2014-04-28 14:55:39 +0000123{
mtkleincc695fe2014-12-10 10:29:19 -0800124 fPtsToUnit.getType(); // Precache so reads are threadsafe.
reed@google.com437d6eb2013-05-23 19:03:05 +0000125 SkASSERT(desc.fCount > 1);
rileya@google.com589708b2012-07-26 20:04:23 +0000126
fmalita6d7e4e82016-09-20 06:55:16 -0700127 fGradFlags = static_cast<uint8_t>(desc.fGradFlags);
rileya@google.com589708b2012-07-26 20:04:23 +0000128
reed@google.com437d6eb2013-05-23 19:03:05 +0000129 SkASSERT((unsigned)desc.fTileMode < SkShader::kTileModeCount);
reed@google.com437d6eb2013-05-23 19:03:05 +0000130 fTileMode = desc.fTileMode;
rileya@google.com589708b2012-07-26 20:04:23 +0000131
rileya@google.com589708b2012-07-26 20:04:23 +0000132 /* Note: we let the caller skip the first and/or last position.
133 i.e. pos[0] = 0.3, pos[1] = 0.7
134 In these cases, we insert dummy entries to ensure that the final data
135 will be bracketed by [0, 1].
136 i.e. our_pos[0] = 0, our_pos[1] = 0.3, our_pos[2] = 0.7, our_pos[3] = 1
137
138 Thus colorCount (the caller's value, and fColorCount (our value) may
139 differ by up to 2. In the above example:
140 colorCount = 2
141 fColorCount = 4
142 */
reed@google.com437d6eb2013-05-23 19:03:05 +0000143 fColorCount = desc.fCount;
rileya@google.com589708b2012-07-26 20:04:23 +0000144 // check if we need to add in dummy start and/or end position/colors
145 bool dummyFirst = false;
146 bool dummyLast = false;
reed@google.com437d6eb2013-05-23 19:03:05 +0000147 if (desc.fPos) {
148 dummyFirst = desc.fPos[0] != 0;
149 dummyLast = desc.fPos[desc.fCount - 1] != SK_Scalar1;
rileya@google.com589708b2012-07-26 20:04:23 +0000150 fColorCount += dummyFirst + dummyLast;
151 }
152
Mike Reed62ce2ca2018-02-19 14:20:15 -0500153 size_t storageSize = fColorCount * (sizeof(SkColor4f) + (desc.fPos ? sizeof(SkScalar) : 0));
Florin Malita89ab2402017-11-01 10:14:57 -0400154 fOrigColors4f = reinterpret_cast<SkColor4f*>(fStorage.reset(storageSize));
Mike Reed62ce2ca2018-02-19 14:20:15 -0500155 fOrigPos = desc.fPos ? reinterpret_cast<SkScalar*>(fOrigColors4f + fColorCount)
156 : nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +0000157
brianosmane25d71c2016-09-28 11:27:28 -0700158 // Now copy over the colors, adding the dummies as needed
159 SkColor4f* origColors = fOrigColors4f;
160 if (dummyFirst) {
161 *origColors++ = desc.fColors[0];
162 }
Florin Malita39d71de2017-10-31 11:33:49 -0400163 for (int i = 0; i < desc.fCount; ++i) {
Mike Reed62ce2ca2018-02-19 14:20:15 -0500164 origColors[i] = desc.fColors[i];
Florin Malita39d71de2017-10-31 11:33:49 -0400165 fColorsAreOpaque = fColorsAreOpaque && (desc.fColors[i].fA == 1);
166 }
brianosmane25d71c2016-09-28 11:27:28 -0700167 if (dummyLast) {
Mike Reed62ce2ca2018-02-19 14:20:15 -0500168 origColors += desc.fCount;
169 *origColors = desc.fColors[desc.fCount - 1];
brianosmane25d71c2016-09-28 11:27:28 -0700170 }
brianosmanb9c51372016-09-15 11:09:45 -0700171
Florin Malita89ab2402017-11-01 10:14:57 -0400172 if (desc.fPos) {
Florin Malita64bb78e2017-11-03 12:54:07 -0400173 SkScalar prev = 0;
Mike Reed62ce2ca2018-02-19 14:20:15 -0500174 SkScalar* origPosPtr = fOrigPos;
Florin Malita64bb78e2017-11-03 12:54:07 -0400175 *origPosPtr++ = prev; // force the first pos to 0
reed9fa60da2014-08-21 07:59:51 -0700176
Florin Malita89ab2402017-11-01 10:14:57 -0400177 int startIndex = dummyFirst ? 0 : 1;
178 int count = desc.fCount + dummyLast;
Florin Malita64bb78e2017-11-03 12:54:07 -0400179
180 bool uniformStops = true;
181 const SkScalar uniformStep = desc.fPos[startIndex] - prev;
Florin Malita89ab2402017-11-01 10:14:57 -0400182 for (int i = startIndex; i < count; i++) {
Florin Malita3e20d022017-11-03 12:11:38 -0400183 // Pin the last value to 1.0, and make sure pos is monotonic.
Florin Malita64bb78e2017-11-03 12:54:07 -0400184 auto curr = (i == desc.fCount) ? 1 : SkScalarPin(desc.fPos[i], prev, 1);
185 uniformStops &= SkScalarNearlyEqual(uniformStep, curr - prev);
186
187 *origPosPtr++ = prev = curr;
reed9fa60da2014-08-21 07:59:51 -0700188 }
Florin Malita64bb78e2017-11-03 12:54:07 -0400189
Florin Malita64bb78e2017-11-03 12:54:07 -0400190 // If the stops are uniform, treat them as implicit.
Mike Reed62ce2ca2018-02-19 14:20:15 -0500191 if (uniformStops) {
Florin Malita64bb78e2017-11-03 12:54:07 -0400192 fOrigPos = nullptr;
193 }
rileya@google.com589708b2012-07-26 20:04:23 +0000194 }
rileya@google.com589708b2012-07-26 20:04:23 +0000195}
196
Florin Malita89ab2402017-11-01 10:14:57 -0400197SkGradientShaderBase::~SkGradientShaderBase() {}
rileya@google.com589708b2012-07-26 20:04:23 +0000198
commit-bot@chromium.org8b0e8ac2014-01-30 18:58:24 +0000199void SkGradientShaderBase::flatten(SkWriteBuffer& buffer) const {
reed9fa60da2014-08-21 07:59:51 -0700200 Descriptor desc;
brianosmane25d71c2016-09-28 11:27:28 -0700201 desc.fColors = fOrigColors4f;
brianosmanb9c51372016-09-15 11:09:45 -0700202 desc.fColorSpace = fColorSpace;
reed9fa60da2014-08-21 07:59:51 -0700203 desc.fPos = fOrigPos;
204 desc.fCount = fColorCount;
205 desc.fTileMode = fTileMode;
206 desc.fGradFlags = fGradFlags;
207
208 const SkMatrix& m = this->getLocalMatrix();
halcanary96fcdcc2015-08-27 07:41:13 -0700209 desc.fLocalMatrix = m.isIdentity() ? nullptr : &m;
reed9fa60da2014-08-21 07:59:51 -0700210 desc.flatten(buffer);
rileya@google.com589708b2012-07-26 20:04:23 +0000211}
212
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400213static void add_stop_color(SkJumper_GradientCtx* ctx, size_t stop, SkPM4f Fs, SkPM4f Bs) {
214 (ctx->fs[0])[stop] = Fs.r();
215 (ctx->fs[1])[stop] = Fs.g();
216 (ctx->fs[2])[stop] = Fs.b();
217 (ctx->fs[3])[stop] = Fs.a();
218 (ctx->bs[0])[stop] = Bs.r();
219 (ctx->bs[1])[stop] = Bs.g();
220 (ctx->bs[2])[stop] = Bs.b();
221 (ctx->bs[3])[stop] = Bs.a();
Mike Kleinf945cbb2017-05-17 09:30:58 -0400222}
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400223
224static void add_const_color(SkJumper_GradientCtx* ctx, size_t stop, SkPM4f color) {
225 add_stop_color(ctx, stop, SkPM4f::FromPremulRGBA(0,0,0,0), color);
Mike Kleinf945cbb2017-05-17 09:30:58 -0400226}
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400227
228// Calculate a factor F and a bias B so that color = F*t + B when t is in range of
229// the stop. Assume that the distance between stops is 1/gapCount.
230static void init_stop_evenly(
231 SkJumper_GradientCtx* ctx, float gapCount, size_t stop, SkPM4f c_l, SkPM4f c_r) {
Mike Klein68768172017-05-17 09:54:36 -0400232 // Clankium's GCC 4.9 targeting ARMv7 is barfing when we use Sk4f math here, so go scalar...
233 SkPM4f Fs = {{
234 (c_r.r() - c_l.r()) * gapCount,
235 (c_r.g() - c_l.g()) * gapCount,
236 (c_r.b() - c_l.b()) * gapCount,
237 (c_r.a() - c_l.a()) * gapCount,
238 }};
239 SkPM4f Bs = {{
240 c_l.r() - Fs.r()*(stop/gapCount),
241 c_l.g() - Fs.g()*(stop/gapCount),
242 c_l.b() - Fs.b()*(stop/gapCount),
243 c_l.a() - Fs.a()*(stop/gapCount),
244 }};
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400245 add_stop_color(ctx, stop, Fs, Bs);
Mike Kleinf945cbb2017-05-17 09:30:58 -0400246}
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400247
248// For each stop we calculate a bias B and a scale factor F, such that
249// for any t between stops n and n+1, the color we want is B[n] + F[n]*t.
250static void init_stop_pos(
251 SkJumper_GradientCtx* ctx, size_t stop, float t_l, float t_r, SkPM4f c_l, SkPM4f c_r) {
Mike Klein68768172017-05-17 09:54:36 -0400252 // See note about Clankium's old compiler in init_stop_evenly().
253 SkPM4f Fs = {{
254 (c_r.r() - c_l.r()) / (t_r - t_l),
255 (c_r.g() - c_l.g()) / (t_r - t_l),
256 (c_r.b() - c_l.b()) / (t_r - t_l),
257 (c_r.a() - c_l.a()) / (t_r - t_l),
258 }};
259 SkPM4f Bs = {{
260 c_l.r() - Fs.r()*t_l,
261 c_l.g() - Fs.g()*t_l,
262 c_l.b() - Fs.b()*t_l,
263 c_l.a() - Fs.a()*t_l,
264 }};
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400265 ctx->ts[stop] = t_l;
266 add_stop_color(ctx, stop, Fs, Bs);
Mike Kleinf945cbb2017-05-17 09:30:58 -0400267}
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400268
Mike Reed1d8c42e2017-08-29 14:58:19 -0400269bool SkGradientShaderBase::onAppendStages(const StageRec& rec) const {
270 SkRasterPipeline* p = rec.fPipeline;
271 SkArenaAlloc* alloc = rec.fAlloc;
272 SkColorSpace* dstCS = rec.fDstCS;
Mike Reed62ce2ca2018-02-19 14:20:15 -0500273 SkJumper_DecalTileCtx* decal_ctx = nullptr;
Mike Reed1d8c42e2017-08-29 14:58:19 -0400274
Mike Kleina3771842017-05-04 19:38:48 -0400275 SkMatrix matrix;
Mike Reed1d8c42e2017-08-29 14:58:19 -0400276 if (!this->computeTotalInverse(rec.fCTM, rec.fLocalM, &matrix)) {
Mike Kleina3771842017-05-04 19:38:48 -0400277 return false;
278 }
Florin Malita50b20842017-07-29 19:08:28 -0400279 matrix.postConcat(fPtsToUnit);
Mike Kleina3771842017-05-04 19:38:48 -0400280
Florin Malita2e409002017-06-28 14:46:54 -0400281 SkRasterPipeline_<256> postPipeline;
Mike Kleina3771842017-05-04 19:38:48 -0400282
Mike Kleine8de0242018-03-10 12:37:11 -0500283 p->append(SkRasterPipeline::seed_shader);
Mike Reed6b59bf42017-07-03 21:26:44 -0400284 p->append_matrix(alloc, matrix);
Florin Malita50b20842017-07-29 19:08:28 -0400285 this->appendGradientStages(alloc, p, &postPipeline);
Mike Kleine7598532017-05-11 11:29:29 -0400286
Mike Reed62ce2ca2018-02-19 14:20:15 -0500287 switch(fTileMode) {
Mike Klein9f85d682017-05-23 07:52:01 -0400288 case kMirror_TileMode: p->append(SkRasterPipeline::mirror_x_1); break;
289 case kRepeat_TileMode: p->append(SkRasterPipeline::repeat_x_1); break;
Mike Reeddfc0e912018-02-16 12:40:18 -0500290 case kDecal_TileMode:
Mike Reed62ce2ca2018-02-19 14:20:15 -0500291 decal_ctx = alloc->make<SkJumper_DecalTileCtx>();
292 decal_ctx->limit_x = SkBits2Float(SkFloat2Bits(1.0f) + 1);
293 // reuse mask + limit_x stage, or create a custom decal_1 that just stores the mask
294 p->append(SkRasterPipeline::decal_x, decal_ctx);
295 // fall-through to clamp
Mike Kleine7598532017-05-11 11:29:29 -0400296 case kClamp_TileMode:
297 if (!fOrigPos) {
298 // We clamp only when the stops are evenly spaced.
299 // If not, there may be hard stops, and clamping ruins hard stops at 0 and/or 1.
Mike Klein5c7960b2017-05-11 10:59:22 -0400300 // In that case, we must make sure we're using the general "gradient" stage,
Mike Kleine7598532017-05-11 11:29:29 -0400301 // which is the only stage that will correctly handle unclamped t.
Mike Klein9f85d682017-05-23 07:52:01 -0400302 p->append(SkRasterPipeline::clamp_x_1);
Mike Kleine7598532017-05-11 11:29:29 -0400303 }
Mike Reed62ce2ca2018-02-19 14:20:15 -0500304 break;
Mike Kleine7598532017-05-11 11:29:29 -0400305 }
Mike Kleina3771842017-05-04 19:38:48 -0400306
307 const bool premulGrad = fGradFlags & SkGradientShader::kInterpolateColorsInPremul_Flag;
308 auto prepareColor = [premulGrad, dstCS, this](int i) {
Florin Malita0e36b3f2017-06-05 23:33:45 -0400309 SkColor4f c = this->getXformedColor(i, dstCS);
Mike Kleina3771842017-05-04 19:38:48 -0400310 return premulGrad ? c.premul()
311 : SkPM4f::From4f(Sk4f::Load(&c));
312 };
313
314 // The two-stop case with stops at 0 and 1.
315 if (fColorCount == 2 && fOrigPos == nullptr) {
316 const SkPM4f c_l = prepareColor(0),
Mike Reed1d8c42e2017-08-29 14:58:19 -0400317 c_r = prepareColor(1);
Mike Kleina3771842017-05-04 19:38:48 -0400318
319 // See F and B below.
320 auto* f_and_b = alloc->makeArrayDefault<SkPM4f>(2);
321 f_and_b[0] = SkPM4f::From4f(c_r.to4f() - c_l.to4f());
322 f_and_b[1] = c_l;
323
Mike Klein5c7960b2017-05-11 10:59:22 -0400324 p->append(SkRasterPipeline::evenly_spaced_2_stop_gradient, f_and_b);
Mike Kleina3771842017-05-04 19:38:48 -0400325 } else {
Herb Derby4de13042017-05-15 10:49:39 -0400326 auto* ctx = alloc->make<SkJumper_GradientCtx>();
Herb Derby4de13042017-05-15 10:49:39 -0400327
328 // Note: In order to handle clamps in search, the search assumes a stop conceptully placed
329 // at -inf. Therefore, the max number of stops is fColorCount+1.
330 for (int i = 0; i < 4; i++) {
331 // Allocate at least at for the AVX2 gather from a YMM register.
332 ctx->fs[i] = alloc->makeArray<float>(std::max(fColorCount+1, 8));
333 ctx->bs[i] = alloc->makeArray<float>(std::max(fColorCount+1, 8));
334 }
335
Mike Kleina3771842017-05-04 19:38:48 -0400336 if (fOrigPos == nullptr) {
337 // Handle evenly distributed stops.
338
Herb Derby4de13042017-05-15 10:49:39 -0400339 size_t stopCount = fColorCount;
340 float gapCount = stopCount - 1;
Mike Kleina3771842017-05-04 19:38:48 -0400341
Herb Derby4de13042017-05-15 10:49:39 -0400342 SkPM4f c_l = prepareColor(0);
343 for (size_t i = 0; i < stopCount - 1; i++) {
Mike Kleina3771842017-05-04 19:38:48 -0400344 SkPM4f c_r = prepareColor(i + 1);
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400345 init_stop_evenly(ctx, gapCount, i, c_l, c_r);
Mike Kleina3771842017-05-04 19:38:48 -0400346 c_l = c_r;
347 }
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400348 add_const_color(ctx, stopCount - 1, c_l);
Mike Kleina3771842017-05-04 19:38:48 -0400349
Herb Derby4de13042017-05-15 10:49:39 -0400350 ctx->stopCount = stopCount;
351 p->append(SkRasterPipeline::evenly_spaced_gradient, ctx);
Mike Kleina3771842017-05-04 19:38:48 -0400352 } else {
353 // Handle arbitrary stops.
354
Herb Derby4de13042017-05-15 10:49:39 -0400355 ctx->ts = alloc->makeArray<float>(fColorCount+1);
356
Mike Kleina3771842017-05-04 19:38:48 -0400357 // Remove the dummy stops inserted by SkGradientShaderBase::SkGradientShaderBase
358 // because they are naturally handled by the search method.
359 int firstStop;
360 int lastStop;
361 if (fColorCount > 2) {
362 firstStop = fOrigColors4f[0] != fOrigColors4f[1] ? 0 : 1;
363 lastStop = fOrigColors4f[fColorCount - 2] != fOrigColors4f[fColorCount - 1]
364 ? fColorCount - 1 : fColorCount - 2;
365 } else {
366 firstStop = 0;
367 lastStop = 1;
368 }
Mike Kleina3771842017-05-04 19:38:48 -0400369
Mike Kleina3771842017-05-04 19:38:48 -0400370 size_t stopCount = 0;
371 float t_l = fOrigPos[firstStop];
372 SkPM4f c_l = prepareColor(firstStop);
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400373 add_const_color(ctx, stopCount++, c_l);
Mike Kleina3771842017-05-04 19:38:48 -0400374 // N.B. lastStop is the index of the last stop, not one after.
375 for (int i = firstStop; i < lastStop; i++) {
376 float t_r = fOrigPos[i + 1];
377 SkPM4f c_r = prepareColor(i + 1);
Florin Malita3e20d022017-11-03 12:11:38 -0400378 SkASSERT(t_l <= t_r);
Mike Kleina3771842017-05-04 19:38:48 -0400379 if (t_l < t_r) {
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400380 init_stop_pos(ctx, stopCount, t_l, t_r, c_l, c_r);
Mike Kleina3771842017-05-04 19:38:48 -0400381 stopCount += 1;
382 }
383 t_l = t_r;
384 c_l = c_r;
385 }
386
Herb Derby4de13042017-05-15 10:49:39 -0400387 ctx->ts[stopCount] = t_l;
Herb Derbyeb99bfd2017-05-16 10:51:26 -0400388 add_const_color(ctx, stopCount++, c_l);
Mike Kleina3771842017-05-04 19:38:48 -0400389
Herb Derby4de13042017-05-15 10:49:39 -0400390 ctx->stopCount = stopCount;
391 p->append(SkRasterPipeline::gradient, ctx);
Mike Kleina3771842017-05-04 19:38:48 -0400392 }
Mike Kleina3771842017-05-04 19:38:48 -0400393 }
394
Mike Reed62ce2ca2018-02-19 14:20:15 -0500395 if (decal_ctx) {
396 p->append(SkRasterPipeline::check_decal_mask, decal_ctx);
397 }
398
Mike Kleina3771842017-05-04 19:38:48 -0400399 if (!premulGrad && !this->colorsAreOpaque()) {
Mike Kleine7598532017-05-11 11:29:29 -0400400 p->append(SkRasterPipeline::premul);
Mike Kleina3771842017-05-04 19:38:48 -0400401 }
402
Florin Malita2e409002017-06-28 14:46:54 -0400403 p->extend(postPipeline);
404
Mike Kleina3771842017-05-04 19:38:48 -0400405 return true;
406}
407
408
rileya@google.com589708b2012-07-26 20:04:23 +0000409bool SkGradientShaderBase::isOpaque() const {
Mike Reed62ce2ca2018-02-19 14:20:15 -0500410 return fColorsAreOpaque && (this->getTileMode() != SkShader::kDecal_TileMode);
411}
412
reed8367b8c2014-08-22 08:30:20 -0700413static unsigned rounded_divide(unsigned numer, unsigned denom) {
414 return (numer + (denom >> 1)) / denom;
415}
416
417bool SkGradientShaderBase::onAsLuminanceColor(SkColor* lum) const {
418 // we just compute an average color.
419 // possibly we could weight this based on the proportional width for each color
420 // assuming they are not evenly distributed in the fPos array.
421 int r = 0;
422 int g = 0;
423 int b = 0;
424 const int n = fColorCount;
Florin Malita39d71de2017-10-31 11:33:49 -0400425 // TODO: use linear colors?
reed8367b8c2014-08-22 08:30:20 -0700426 for (int i = 0; i < n; ++i) {
Florin Malita39d71de2017-10-31 11:33:49 -0400427 SkColor c = this->getLegacyColor(i);
reed8367b8c2014-08-22 08:30:20 -0700428 r += SkColorGetR(c);
429 g += SkColorGetG(c);
430 b += SkColorGetB(c);
431 }
432 *lum = SkColorSetRGB(rounded_divide(r, n), rounded_divide(g, n), rounded_divide(b, n));
433 return true;
434}
435
Florin Malita39d71de2017-10-31 11:33:49 -0400436SkGradientShaderBase::AutoXformColors::AutoXformColors(const SkGradientShaderBase& grad,
437 SkColorSpaceXformer* xformer)
438 : fColors(grad.fColorCount) {
439 // TODO: stay in 4f to preserve precision?
440
441 SkAutoSTMalloc<8, SkColor> origColors(grad.fColorCount);
442 for (int i = 0; i < grad.fColorCount; ++i) {
443 origColors[i] = grad.getLegacyColor(i);
444 }
445
446 xformer->apply(fColors.get(), origColors.get(), grad.fColorCount);
447}
448
Florin Malitad4e9ec82017-10-25 18:00:26 -0400449static constexpr int kGradientTextureSize = 256;
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000450
Florin Malita84d7cf92017-10-25 15:31:54 -0400451void SkGradientShaderBase::initLinearBitmap(SkBitmap* bitmap, GradientBitmapType bitmapType) const {
brianosmand4546092016-09-22 12:31:58 -0700452 const bool interpInPremul = SkToBool(fGradFlags &
453 SkGradientShader::kInterpolateColorsInPremul_Flag);
brianosmand4546092016-09-22 12:31:58 -0700454 SkHalf* pixelsF16 = reinterpret_cast<SkHalf*>(bitmap->getPixels());
Florin Malita84d7cf92017-10-25 15:31:54 -0400455 uint32_t* pixels32 = reinterpret_cast<uint32_t*>(bitmap->getPixels());
brianosmand4546092016-09-22 12:31:58 -0700456
457 typedef std::function<void(const Sk4f&, int)> pixelWriteFn_t;
458
459 pixelWriteFn_t writeF16Pixel = [&](const Sk4f& x, int index) {
460 Sk4h c = SkFloatToHalf_finite_ftz(x);
461 pixelsF16[4*index+0] = c[0];
462 pixelsF16[4*index+1] = c[1];
463 pixelsF16[4*index+2] = c[2];
464 pixelsF16[4*index+3] = c[3];
465 };
466 pixelWriteFn_t writeS32Pixel = [&](const Sk4f& c, int index) {
Florin Malita84d7cf92017-10-25 15:31:54 -0400467 pixels32[index] = Sk4f_toS32(c);
468 };
469 pixelWriteFn_t writeL32Pixel = [&](const Sk4f& c, int index) {
470 pixels32[index] = Sk4f_toL32(c);
brianosmand4546092016-09-22 12:31:58 -0700471 };
472
473 pixelWriteFn_t writeSizedPixel =
Florin Malita84d7cf92017-10-25 15:31:54 -0400474 (bitmapType == GradientBitmapType::kHalfFloat) ? writeF16Pixel :
475 (bitmapType == GradientBitmapType::kSRGB ) ? writeS32Pixel : writeL32Pixel;
brianosmand4546092016-09-22 12:31:58 -0700476 pixelWriteFn_t writeUnpremulPixel = [&](const Sk4f& c, int index) {
477 writeSizedPixel(c * Sk4f(c[3], c[3], c[3], 1.0f), index);
478 };
479
480 pixelWriteFn_t writePixel = interpInPremul ? writeSizedPixel : writeUnpremulPixel;
481
Florin Malita84d7cf92017-10-25 15:31:54 -0400482 // When not in legacy mode, we just want the original 4f colors - so we pass in
483 // our own CS for identity/no transform.
484 auto* cs = bitmapType != GradientBitmapType::kLegacy ? fColorSpace.get() : nullptr;
485
brianosmand4546092016-09-22 12:31:58 -0700486 int prevIndex = 0;
487 for (int i = 1; i < fColorCount; i++) {
Florin Malitaed6ae562017-10-28 11:06:48 -0400488 // Historically, stops have been mapped to [0, 256], with 256 then nudged to the
489 // next smaller value, then truncate for the texture index. This seems to produce
490 // the best results for some common distributions, so we preserve the behavior.
491 int nextIndex = SkTMin(this->getPos(i) * kGradientTextureSize,
492 SkIntToScalar(kGradientTextureSize - 1));
brianosmand4546092016-09-22 12:31:58 -0700493
494 if (nextIndex > prevIndex) {
Florin Malita84d7cf92017-10-25 15:31:54 -0400495 SkColor4f color0 = this->getXformedColor(i - 1, cs),
496 color1 = this->getXformedColor(i , cs);
497 Sk4f c0 = Sk4f::Load(color0.vec()),
498 c1 = Sk4f::Load(color1.vec());
499
brianosmand4546092016-09-22 12:31:58 -0700500 if (interpInPremul) {
501 c0 = c0 * Sk4f(c0[3], c0[3], c0[3], 1.0f);
502 c1 = c1 * Sk4f(c1[3], c1[3], c1[3], 1.0f);
503 }
504
505 Sk4f step = Sk4f(1.0f / static_cast<float>(nextIndex - prevIndex));
506 Sk4f delta = (c1 - c0) * step;
507
508 for (int curIndex = prevIndex; curIndex <= nextIndex; ++curIndex) {
509 writePixel(c0, curIndex);
510 c0 += delta;
511 }
512 }
513 prevIndex = nextIndex;
514 }
Florin Malitad4e9ec82017-10-25 18:00:26 -0400515 SkASSERT(prevIndex == kGradientTextureSize - 1);
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000516}
517
Florin Malita0e36b3f2017-06-05 23:33:45 -0400518SkColor4f SkGradientShaderBase::getXformedColor(size_t i, SkColorSpace* dstCS) const {
Florin Malita79363b62017-11-01 15:43:52 -0400519 if (dstCS) {
520 return to_colorspace(fOrigColors4f[i], fColorSpace.get(), dstCS);
521 }
522
523 // Legacy/srgb color.
Florin Malita79363b62017-11-01 15:43:52 -0400524 // We quantize upfront to ensure stable SkColor round-trips.
525 auto rgb255 = sk_linear_to_srgb(Sk4f::Load(fOrigColors4f[i].vec()));
526 auto rgb = SkNx_cast<float>(rgb255) * (1/255.0f);
527 return { rgb[0], rgb[1], rgb[2], fOrigColors4f[i].fA };
Florin Malita0e36b3f2017-06-05 23:33:45 -0400528}
529
reed086eea92016-05-04 17:12:46 -0700530SK_DECLARE_STATIC_MUTEX(gGradientCacheMutex);
rileya@google.com589708b2012-07-26 20:04:23 +0000531/*
532 * Because our caller might rebuild the same (logically the same) gradient
533 * over and over, we'd like to return exactly the same "bitmap" if possible,
534 * allowing the client to utilize a cache of our bitmap (e.g. with a GPU).
535 * To do that, we maintain a private cache of built-bitmaps, based on our
Brian Osmanfe3e8582017-10-20 11:27:49 -0400536 * colors and positions.
rileya@google.com589708b2012-07-26 20:04:23 +0000537 */
brianosmand4546092016-09-22 12:31:58 -0700538void SkGradientShaderBase::getGradientTableBitmap(SkBitmap* bitmap,
539 GradientBitmapType bitmapType) const {
brianosmand4546092016-09-22 12:31:58 -0700540 // build our key: [numColors + colors[] + {positions[]} + flags + colorType ]
Florin Malita39d71de2017-10-31 11:33:49 -0400541 static_assert(sizeof(SkColor4f) % sizeof(int32_t) == 0, "");
542 const int colorsAsIntCount = fColorCount * sizeof(SkColor4f) / sizeof(int32_t);
543 int count = 1 + colorsAsIntCount + 1 + 1;
rileya@google.com589708b2012-07-26 20:04:23 +0000544 if (fColorCount > 2) {
Florin Malitacad3b8c2017-10-28 21:42:50 -0400545 count += fColorCount - 1;
rileya@google.com589708b2012-07-26 20:04:23 +0000546 }
547
Florin Malita39d71de2017-10-31 11:33:49 -0400548 SkAutoSTMalloc<64, int32_t> storage(count);
rileya@google.com589708b2012-07-26 20:04:23 +0000549 int32_t* buffer = storage.get();
550
551 *buffer++ = fColorCount;
Florin Malita39d71de2017-10-31 11:33:49 -0400552 memcpy(buffer, fOrigColors4f, fColorCount * sizeof(SkColor4f));
553 buffer += colorsAsIntCount;
rileya@google.com589708b2012-07-26 20:04:23 +0000554 if (fColorCount > 2) {
555 for (int i = 1; i < fColorCount; i++) {
Florin Malitacad3b8c2017-10-28 21:42:50 -0400556 *buffer++ = SkFloat2Bits(this->getPos(i));
rileya@google.com589708b2012-07-26 20:04:23 +0000557 }
558 }
reed@google.com3d3a8602013-05-24 14:58:44 +0000559 *buffer++ = fGradFlags;
brianosmand4546092016-09-22 12:31:58 -0700560 *buffer++ = static_cast<int32_t>(bitmapType);
rileya@google.com589708b2012-07-26 20:04:23 +0000561 SkASSERT(buffer - storage.get() == count);
562
563 ///////////////////////////////////
564
reeda6cac4c2014-08-21 10:50:25 -0700565 static SkGradientBitmapCache* gCache;
brianosmand4546092016-09-22 12:31:58 -0700566 // each cache cost 1K or 2K of RAM, since each bitmap will be 1x256 at either 32bpp or 64bpp
rileya@google.com589708b2012-07-26 20:04:23 +0000567 static const int MAX_NUM_CACHED_GRADIENT_BITMAPS = 32;
bungemand6aeb6d2014-07-25 11:52:47 -0700568 SkAutoMutexAcquire ama(gGradientCacheMutex);
rileya@google.com589708b2012-07-26 20:04:23 +0000569
halcanary96fcdcc2015-08-27 07:41:13 -0700570 if (nullptr == gCache) {
halcanary385fe4d2015-08-26 13:07:48 -0700571 gCache = new SkGradientBitmapCache(MAX_NUM_CACHED_GRADIENT_BITMAPS);
rileya@google.com589708b2012-07-26 20:04:23 +0000572 }
573 size_t size = count * sizeof(int32_t);
574
575 if (!gCache->find(storage.get(), size, bitmap)) {
Florin Malitad4e9ec82017-10-25 18:00:26 -0400576 // For these cases we use the bitmap cache, but not the GradientShaderCache. So just
577 // allocate and populate the bitmap's data directly.
Florin Malita63376532017-10-24 10:56:52 -0400578
Florin Malitad4e9ec82017-10-25 18:00:26 -0400579 SkImageInfo info;
580 switch (bitmapType) {
581 case GradientBitmapType::kLegacy:
582 info = SkImageInfo::Make(kGradientTextureSize, 1, kRGBA_8888_SkColorType,
583 kPremul_SkAlphaType);
584 break;
585 case GradientBitmapType::kSRGB:
586 info = SkImageInfo::Make(kGradientTextureSize, 1, kRGBA_8888_SkColorType,
587 kPremul_SkAlphaType, SkColorSpace::MakeSRGB());
588 break;
589 case GradientBitmapType::kHalfFloat:
590 info = SkImageInfo::Make(kGradientTextureSize, 1, kRGBA_F16_SkColorType,
591 kPremul_SkAlphaType, SkColorSpace::MakeSRGBLinear());
592 break;
brianosmand4546092016-09-22 12:31:58 -0700593 }
Florin Malitad4e9ec82017-10-25 18:00:26 -0400594
595 bitmap->allocPixels(info);
596 this->initLinearBitmap(bitmap, bitmapType);
Robert Phillips7a926392018-02-01 15:49:54 -0500597 bitmap->setImmutable();
rileya@google.com589708b2012-07-26 20:04:23 +0000598 gCache->add(storage.get(), size, *bitmap);
599 }
600}
601
Florin Malita5f379a82017-10-18 16:22:35 -0400602void SkGradientShaderBase::commonAsAGradient(GradientInfo* info) const {
rileya@google.com589708b2012-07-26 20:04:23 +0000603 if (info) {
604 if (info->fColorCount >= fColorCount) {
605 if (info->fColors) {
Florin Malita39d71de2017-10-31 11:33:49 -0400606 for (int i = 0; i < fColorCount; ++i) {
607 info->fColors[i] = this->getLegacyColor(i);
608 }
rileya@google.com589708b2012-07-26 20:04:23 +0000609 }
610 if (info->fColorOffsets) {
Florin Malitaed6ae562017-10-28 11:06:48 -0400611 for (int i = 0; i < fColorCount; ++i) {
612 info->fColorOffsets[i] = this->getPos(i);
rileya@google.com589708b2012-07-26 20:04:23 +0000613 }
614 }
615 }
616 info->fColorCount = fColorCount;
617 info->fTileMode = fTileMode;
reed@google.com3d3a8602013-05-24 14:58:44 +0000618 info->fGradientFlags = fGradFlags;
rileya@google.com589708b2012-07-26 20:04:23 +0000619 }
620}
621
robertphillips@google.com76f9e932013-01-15 20:17:47 +0000622void SkGradientShaderBase::toString(SkString* str) const {
623
624 str->appendf("%d colors: ", fColorCount);
625
626 for (int i = 0; i < fColorCount; ++i) {
Florin Malita39d71de2017-10-31 11:33:49 -0400627 str->appendHex(this->getLegacyColor(i), 8);
robertphillips@google.com76f9e932013-01-15 20:17:47 +0000628 if (i < fColorCount-1) {
629 str->append(", ");
630 }
631 }
632
633 if (fColorCount > 2) {
634 str->append(" points: (");
635 for (int i = 0; i < fColorCount; ++i) {
Florin Malitaed6ae562017-10-28 11:06:48 -0400636 str->appendScalar(this->getPos(i));
robertphillips@google.com76f9e932013-01-15 20:17:47 +0000637 if (i < fColorCount-1) {
638 str->append(", ");
639 }
640 }
641 str->append(")");
642 }
643
644 static const char* gTileModeName[SkShader::kTileModeCount] = {
Mike Reeddfc0e912018-02-16 12:40:18 -0500645 "clamp", "repeat", "mirror", "decal",
robertphillips@google.com76f9e932013-01-15 20:17:47 +0000646 };
647
648 str->append(" ");
649 str->append(gTileModeName[fTileMode]);
650
robertphillips@google.com76f9e932013-01-15 20:17:47 +0000651 this->INHERITED::toString(str);
652}
robertphillips@google.com76f9e932013-01-15 20:17:47 +0000653
rileya@google.com589708b2012-07-26 20:04:23 +0000654///////////////////////////////////////////////////////////////////////////////
655///////////////////////////////////////////////////////////////////////////////
656
reed1b747302015-01-06 07:13:19 -0800657// Return true if these parameters are valid/legal/safe to construct a gradient
658//
brianosmane25d71c2016-09-28 11:27:28 -0700659static bool valid_grad(const SkColor4f colors[], const SkScalar pos[], int count,
660 unsigned tileMode) {
halcanary96fcdcc2015-08-27 07:41:13 -0700661 return nullptr != colors && count >= 1 && tileMode < (unsigned)SkShader::kTileModeCount;
reed1b747302015-01-06 07:13:19 -0800662}
663
reed@google.com437d6eb2013-05-23 19:03:05 +0000664static void desc_init(SkGradientShaderBase::Descriptor* desc,
brianosmane25d71c2016-09-28 11:27:28 -0700665 const SkColor4f colors[], sk_sp<SkColorSpace> colorSpace,
666 const SkScalar pos[], int colorCount,
reedaddf2ed2014-08-11 08:28:24 -0700667 SkShader::TileMode mode, uint32_t flags, const SkMatrix* localMatrix) {
fmalita748d6202016-05-11 11:39:58 -0700668 SkASSERT(colorCount > 1);
669
commit-bot@chromium.org6c5aea22014-04-22 16:25:15 +0000670 desc->fColors = colors;
brianosmane25d71c2016-09-28 11:27:28 -0700671 desc->fColorSpace = std::move(colorSpace);
commit-bot@chromium.org6c5aea22014-04-22 16:25:15 +0000672 desc->fPos = pos;
673 desc->fCount = colorCount;
674 desc->fTileMode = mode;
commit-bot@chromium.org6c5aea22014-04-22 16:25:15 +0000675 desc->fGradFlags = flags;
reedaddf2ed2014-08-11 08:28:24 -0700676 desc->fLocalMatrix = localMatrix;
reed@google.com437d6eb2013-05-23 19:03:05 +0000677}
678
brianosmane25d71c2016-09-28 11:27:28 -0700679// assumes colors is SkColor4f* and pos is SkScalar*
fmenozzie9fd0f82016-08-19 07:50:57 -0700680#define EXPAND_1_COLOR(count) \
brianosmane25d71c2016-09-28 11:27:28 -0700681 SkColor4f tmp[2]; \
fmenozzie9fd0f82016-08-19 07:50:57 -0700682 do { \
683 if (1 == count) { \
684 tmp[0] = tmp[1] = colors[0]; \
685 colors = tmp; \
686 pos = nullptr; \
687 count = 2; \
688 } \
689 } while (0)
690
fmenozzi68d952c2016-08-19 08:56:56 -0700691struct ColorStopOptimizer {
brianosmane25d71c2016-09-28 11:27:28 -0700692 ColorStopOptimizer(const SkColor4f* colors, const SkScalar* pos,
fmenozzi68d952c2016-08-19 08:56:56 -0700693 int count, SkShader::TileMode mode)
694 : fColors(colors)
695 , fPos(pos)
696 , fCount(count) {
697
698 if (!pos || count != 3) {
699 return;
700 }
701
702 if (SkScalarNearlyEqual(pos[0], 0.0f) &&
703 SkScalarNearlyEqual(pos[1], 0.0f) &&
704 SkScalarNearlyEqual(pos[2], 1.0f)) {
705
706 if (SkShader::kRepeat_TileMode == mode ||
707 SkShader::kMirror_TileMode == mode ||
708 colors[0] == colors[1]) {
709
fmalita582a6562016-08-22 06:28:57 -0700710 // Ignore the leftmost color/pos.
711 fColors += 1;
712 fPos += 1;
713 fCount = 2;
fmenozzi68d952c2016-08-19 08:56:56 -0700714 }
715 } else if (SkScalarNearlyEqual(pos[0], 0.0f) &&
716 SkScalarNearlyEqual(pos[1], 1.0f) &&
717 SkScalarNearlyEqual(pos[2], 1.0f)) {
718
719 if (SkShader::kRepeat_TileMode == mode ||
720 SkShader::kMirror_TileMode == mode ||
721 colors[1] == colors[2]) {
722
fmalita582a6562016-08-22 06:28:57 -0700723 // Ignore the rightmost color/pos.
fmenozzi68d952c2016-08-19 08:56:56 -0700724 fCount = 2;
725 }
726 }
727 }
728
brianosmane25d71c2016-09-28 11:27:28 -0700729 const SkColor4f* fColors;
730 const SkScalar* fPos;
731 int fCount;
732};
733
734struct ColorConverter {
735 ColorConverter(const SkColor* colors, int count) {
736 for (int i = 0; i < count; ++i) {
737 fColors4f.push_back(SkColor4f::FromColor(colors[i]));
738 }
739 }
740
741 SkSTArray<2, SkColor4f, true> fColors4f;
fmenozzi68d952c2016-08-19 08:56:56 -0700742};
743
reed8a21c9f2016-03-08 18:50:00 -0800744sk_sp<SkShader> SkGradientShader::MakeLinear(const SkPoint pts[2],
fmenozzi68d952c2016-08-19 08:56:56 -0700745 const SkColor colors[],
746 const SkScalar pos[], int colorCount,
747 SkShader::TileMode mode,
748 uint32_t flags,
749 const SkMatrix* localMatrix) {
brianosmane25d71c2016-09-28 11:27:28 -0700750 ColorConverter converter(colors, colorCount);
751 return MakeLinear(pts, converter.fColors4f.begin(), nullptr, pos, colorCount, mode, flags,
752 localMatrix);
753}
754
755sk_sp<SkShader> SkGradientShader::MakeLinear(const SkPoint pts[2],
756 const SkColor4f colors[],
757 sk_sp<SkColorSpace> colorSpace,
758 const SkScalar pos[], int colorCount,
759 SkShader::TileMode mode,
760 uint32_t flags,
761 const SkMatrix* localMatrix) {
fmalitac5231042016-08-10 05:45:50 -0700762 if (!pts || !SkScalarIsFinite((pts[1] - pts[0]).length())) {
halcanary96fcdcc2015-08-27 07:41:13 -0700763 return nullptr;
reed1b747302015-01-06 07:13:19 -0800764 }
765 if (!valid_grad(colors, pos, colorCount, mode)) {
halcanary96fcdcc2015-08-27 07:41:13 -0700766 return nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +0000767 }
fmenozzie9fd0f82016-08-19 07:50:57 -0700768 if (1 == colorCount) {
brianosmane25d71c2016-09-28 11:27:28 -0700769 return SkShader::MakeColorShader(colors[0], std::move(colorSpace));
fmenozzie9fd0f82016-08-19 07:50:57 -0700770 }
Florin Malita8d3ffad2017-02-03 18:21:17 +0000771 if (localMatrix && !localMatrix->invert(nullptr)) {
772 return nullptr;
773 }
rileya@google.com589708b2012-07-26 20:04:23 +0000774
fmenozzi68d952c2016-08-19 08:56:56 -0700775 ColorStopOptimizer opt(colors, pos, colorCount, mode);
776
reed@google.com437d6eb2013-05-23 19:03:05 +0000777 SkGradientShaderBase::Descriptor desc;
brianosmane25d71c2016-09-28 11:27:28 -0700778 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
779 localMatrix);
reed8a21c9f2016-03-08 18:50:00 -0800780 return sk_make_sp<SkLinearGradient>(pts, desc);
rileya@google.com589708b2012-07-26 20:04:23 +0000781}
782
reed8a21c9f2016-03-08 18:50:00 -0800783sk_sp<SkShader> SkGradientShader::MakeRadial(const SkPoint& center, SkScalar radius,
brianosmane25d71c2016-09-28 11:27:28 -0700784 const SkColor colors[],
785 const SkScalar pos[], int colorCount,
786 SkShader::TileMode mode,
787 uint32_t flags,
788 const SkMatrix* localMatrix) {
789 ColorConverter converter(colors, colorCount);
790 return MakeRadial(center, radius, converter.fColors4f.begin(), nullptr, pos, colorCount, mode,
791 flags, localMatrix);
792}
793
794sk_sp<SkShader> SkGradientShader::MakeRadial(const SkPoint& center, SkScalar radius,
795 const SkColor4f colors[],
796 sk_sp<SkColorSpace> colorSpace,
797 const SkScalar pos[], int colorCount,
798 SkShader::TileMode mode,
799 uint32_t flags,
800 const SkMatrix* localMatrix) {
reed1b747302015-01-06 07:13:19 -0800801 if (radius <= 0) {
halcanary96fcdcc2015-08-27 07:41:13 -0700802 return nullptr;
reed1b747302015-01-06 07:13:19 -0800803 }
804 if (!valid_grad(colors, pos, colorCount, mode)) {
halcanary96fcdcc2015-08-27 07:41:13 -0700805 return nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +0000806 }
fmenozzie9fd0f82016-08-19 07:50:57 -0700807 if (1 == colorCount) {
brianosmane25d71c2016-09-28 11:27:28 -0700808 return SkShader::MakeColorShader(colors[0], std::move(colorSpace));
fmenozzie9fd0f82016-08-19 07:50:57 -0700809 }
Florin Malita8d3ffad2017-02-03 18:21:17 +0000810 if (localMatrix && !localMatrix->invert(nullptr)) {
811 return nullptr;
812 }
rileya@google.com589708b2012-07-26 20:04:23 +0000813
fmenozzi68d952c2016-08-19 08:56:56 -0700814 ColorStopOptimizer opt(colors, pos, colorCount, mode);
815
reed@google.com437d6eb2013-05-23 19:03:05 +0000816 SkGradientShaderBase::Descriptor desc;
brianosmane25d71c2016-09-28 11:27:28 -0700817 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
818 localMatrix);
reed8a21c9f2016-03-08 18:50:00 -0800819 return sk_make_sp<SkRadialGradient>(center, radius, desc);
rileya@google.com589708b2012-07-26 20:04:23 +0000820}
821
reed8a21c9f2016-03-08 18:50:00 -0800822sk_sp<SkShader> SkGradientShader::MakeTwoPointConical(const SkPoint& start,
brianosmane25d71c2016-09-28 11:27:28 -0700823 SkScalar startRadius,
824 const SkPoint& end,
825 SkScalar endRadius,
826 const SkColor colors[],
827 const SkScalar pos[],
828 int colorCount,
829 SkShader::TileMode mode,
830 uint32_t flags,
831 const SkMatrix* localMatrix) {
832 ColorConverter converter(colors, colorCount);
833 return MakeTwoPointConical(start, startRadius, end, endRadius, converter.fColors4f.begin(),
834 nullptr, pos, colorCount, mode, flags, localMatrix);
835}
836
837sk_sp<SkShader> SkGradientShader::MakeTwoPointConical(const SkPoint& start,
838 SkScalar startRadius,
839 const SkPoint& end,
840 SkScalar endRadius,
841 const SkColor4f colors[],
842 sk_sp<SkColorSpace> colorSpace,
843 const SkScalar pos[],
844 int colorCount,
845 SkShader::TileMode mode,
846 uint32_t flags,
847 const SkMatrix* localMatrix) {
reed1b747302015-01-06 07:13:19 -0800848 if (startRadius < 0 || endRadius < 0) {
halcanary96fcdcc2015-08-27 07:41:13 -0700849 return nullptr;
reed1b747302015-01-06 07:13:19 -0800850 }
Florin Malita327290f2017-07-07 09:23:16 -0400851 if (SkScalarNearlyZero((start - end).length()) && SkScalarNearlyZero(startRadius)) {
852 // We can treat this gradient as radial, which is faster.
853 return MakeRadial(start, endRadius, colors, std::move(colorSpace), pos, colorCount,
854 mode, flags, localMatrix);
855 }
reed1b747302015-01-06 07:13:19 -0800856 if (!valid_grad(colors, pos, colorCount, mode)) {
halcanary96fcdcc2015-08-27 07:41:13 -0700857 return nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +0000858 }
fmalita5edf82e2016-03-03 06:41:54 -0800859 if (startRadius == endRadius) {
860 if (start == end || startRadius == 0) {
reed8a21c9f2016-03-08 18:50:00 -0800861 return SkShader::MakeEmptyShader();
fmalita5edf82e2016-03-03 06:41:54 -0800862 }
rileya@google.com589708b2012-07-26 20:04:23 +0000863 }
Florin Malita8d3ffad2017-02-03 18:21:17 +0000864 if (localMatrix && !localMatrix->invert(nullptr)) {
865 return nullptr;
866 }
reed6b7a6c72016-08-18 16:13:50 -0700867 EXPAND_1_COLOR(colorCount);
rileya@google.com589708b2012-07-26 20:04:23 +0000868
fmenozzi68d952c2016-08-19 08:56:56 -0700869 ColorStopOptimizer opt(colors, pos, colorCount, mode);
870
reed@google.com437d6eb2013-05-23 19:03:05 +0000871 SkGradientShaderBase::Descriptor desc;
Florin Malita5f379a82017-10-18 16:22:35 -0400872 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
873 localMatrix);
874 return SkTwoPointConicalGradient::Create(start, startRadius, end, endRadius, desc);
rileya@google.com589708b2012-07-26 20:04:23 +0000875}
876
reed8a21c9f2016-03-08 18:50:00 -0800877sk_sp<SkShader> SkGradientShader::MakeSweep(SkScalar cx, SkScalar cy,
brianosmane25d71c2016-09-28 11:27:28 -0700878 const SkColor colors[],
879 const SkScalar pos[],
880 int colorCount,
Florin Malita5a9a9812017-08-01 16:38:08 -0400881 SkShader::TileMode mode,
882 SkScalar startAngle,
883 SkScalar endAngle,
brianosmane25d71c2016-09-28 11:27:28 -0700884 uint32_t flags,
885 const SkMatrix* localMatrix) {
886 ColorConverter converter(colors, colorCount);
Florin Malita5a9a9812017-08-01 16:38:08 -0400887 return MakeSweep(cx, cy, converter.fColors4f.begin(), nullptr, pos, colorCount,
888 mode, startAngle, endAngle, flags, localMatrix);
brianosmane25d71c2016-09-28 11:27:28 -0700889}
890
891sk_sp<SkShader> SkGradientShader::MakeSweep(SkScalar cx, SkScalar cy,
892 const SkColor4f colors[],
893 sk_sp<SkColorSpace> colorSpace,
894 const SkScalar pos[],
895 int colorCount,
Florin Malita5a9a9812017-08-01 16:38:08 -0400896 SkShader::TileMode mode,
897 SkScalar startAngle,
898 SkScalar endAngle,
brianosmane25d71c2016-09-28 11:27:28 -0700899 uint32_t flags,
900 const SkMatrix* localMatrix) {
Florin Malita5a9a9812017-08-01 16:38:08 -0400901 if (!valid_grad(colors, pos, colorCount, mode)) {
halcanary96fcdcc2015-08-27 07:41:13 -0700902 return nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +0000903 }
fmenozzie9fd0f82016-08-19 07:50:57 -0700904 if (1 == colorCount) {
brianosmane25d71c2016-09-28 11:27:28 -0700905 return SkShader::MakeColorShader(colors[0], std::move(colorSpace));
fmenozzie9fd0f82016-08-19 07:50:57 -0700906 }
Florin Malita5a9a9812017-08-01 16:38:08 -0400907 if (startAngle >= endAngle) {
908 return nullptr;
909 }
Florin Malita8d3ffad2017-02-03 18:21:17 +0000910 if (localMatrix && !localMatrix->invert(nullptr)) {
911 return nullptr;
912 }
rileya@google.com589708b2012-07-26 20:04:23 +0000913
Florin Malita5a9a9812017-08-01 16:38:08 -0400914 if (startAngle <= 0 && endAngle >= 360) {
915 // If the t-range includes [0,1], then we can always use clamping (presumably faster).
916 mode = SkShader::kClamp_TileMode;
917 }
fmenozzi68d952c2016-08-19 08:56:56 -0700918
919 ColorStopOptimizer opt(colors, pos, colorCount, mode);
920
reed@google.com437d6eb2013-05-23 19:03:05 +0000921 SkGradientShaderBase::Descriptor desc;
brianosmane25d71c2016-09-28 11:27:28 -0700922 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
923 localMatrix);
Florin Malita5a9a9812017-08-01 16:38:08 -0400924
925 const SkScalar t0 = startAngle / 360,
926 t1 = endAngle / 360;
927
928 return sk_make_sp<SkSweepGradient>(SkPoint::Make(cx, cy), t0, t1, desc);
rileya@google.com589708b2012-07-26 20:04:23 +0000929}
930
931SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_START(SkGradientShader)
932 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkLinearGradient)
933 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkRadialGradient)
934 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkSweepGradient)
rileya@google.com589708b2012-07-26 20:04:23 +0000935 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkTwoPointConicalGradient)
936SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_END
rileya@google.comd7cc6512012-07-27 14:00:39 +0000937
938///////////////////////////////////////////////////////////////////////////////
939
bsalomon@google.comcf8fb1f2012-08-02 14:03:32 +0000940#if SK_SUPPORT_GPU
941
Brian Osman5911a7c2017-10-25 12:52:31 -0400942#include "GrColorSpaceXform.h"
brianosmana6359362016-03-21 06:55:37 -0700943#include "GrContext.h"
Robert Phillips1afd4cd2018-01-08 13:40:32 -0500944#include "GrContextPriv.h"
Brian Salomon94efbf52016-11-29 13:43:05 -0500945#include "GrShaderCaps.h"
ajuma95243eb2016-08-24 08:19:02 -0700946#include "GrTextureStripAtlas.h"
egdanielf5294392015-10-21 07:14:17 -0700947#include "gl/GrGLContext.h"
egdaniel2d721d32015-11-11 13:06:05 -0800948#include "glsl/GrGLSLFragmentShaderBuilder.h"
egdaniel018fb622015-10-28 07:26:40 -0700949#include "glsl/GrGLSLProgramDataManager.h"
egdaniel7ea439b2015-12-03 09:20:44 -0800950#include "glsl/GrGLSLUniformHandler.h"
bsalomon@google.comcf8fb1f2012-08-02 14:03:32 +0000951#include "SkGr.h"
952
fmenozzi55d318d2016-08-09 08:05:57 -0700953void GrGradientEffect::GLSLProcessor::emitUniforms(GrGLSLUniformHandler* uniformHandler,
954 const GrGradientEffect& ge) {
Florin Malita14a8dd72017-11-08 15:46:42 -0500955 switch (ge.fStrategy) {
956 case GrGradientEffect::InterpolationStrategy::kThreshold:
957 case GrGradientEffect::InterpolationStrategy::kThresholdClamp0:
958 case GrGradientEffect::InterpolationStrategy::kThresholdClamp1:
959 fThresholdUni = uniformHandler->addUniform(kFragment_GrShaderFlag,
960 kFloat_GrSLType,
961 kHigh_GrSLPrecision,
962 "Threshold");
963 // fall through
964 case GrGradientEffect::InterpolationStrategy::kSingle:
965 fIntervalsUni = uniformHandler->addUniformArray(kFragment_GrShaderFlag,
966 kHalf4_GrSLType,
967 "Intervals",
968 ge.fIntervals.count());
969 break;
970 case GrGradientEffect::InterpolationStrategy::kTexture:
971 fFSYUni = uniformHandler->addUniform(kFragment_GrShaderFlag, kHalf_GrSLType,
972 "GradientYCoordFS");
973 break;
bsalomon@google.com82d12232013-09-09 15:36:26 +0000974 }
975}
976
fmenozzi55d318d2016-08-09 08:05:57 -0700977void GrGradientEffect::GLSLProcessor::onSetData(const GrGLSLProgramDataManager& pdman,
Brian Salomonab015ef2017-04-04 10:15:51 -0400978 const GrFragmentProcessor& processor) {
joshualittb0a8a372014-09-23 09:50:21 -0700979 const GrGradientEffect& e = processor.cast<GrGradientEffect>();
bsalomon@google.com82d12232013-09-09 15:36:26 +0000980
Florin Malita14a8dd72017-11-08 15:46:42 -0500981 switch (e.fStrategy) {
982 case GrGradientEffect::InterpolationStrategy::kThreshold:
983 case GrGradientEffect::InterpolationStrategy::kThresholdClamp0:
984 case GrGradientEffect::InterpolationStrategy::kThresholdClamp1:
985 pdman.set1f(fThresholdUni, e.fThreshold);
Brian Salomon466ad992016-10-13 16:08:36 -0400986 // fall through
Florin Malita14a8dd72017-11-08 15:46:42 -0500987 case GrGradientEffect::InterpolationStrategy::kSingle:
988 pdman.set4fv(fIntervalsUni, e.fIntervals.count(),
989 reinterpret_cast<const float*>(e.fIntervals.begin()));
fmenozzicd9a1d02016-08-15 07:03:47 -0700990 break;
Florin Malita14a8dd72017-11-08 15:46:42 -0500991 case GrGradientEffect::InterpolationStrategy::kTexture:
992 if (e.fYCoord != fCachedYCoord) {
993 pdman.set1f(fFSYUni, e.fYCoord);
994 fCachedYCoord = e.fYCoord;
fmenozzicd9a1d02016-08-15 07:03:47 -0700995 }
996 break;
rileya@google.comb3e50f22012-08-20 17:43:08 +0000997 }
998}
999
Florin Malitae657dc82017-11-03 08:46:18 -04001000void GrGradientEffect::onGetGLSLProcessorKey(const GrShaderCaps&, GrProcessorKeyBuilder* b) const {
1001 b->add32(GLSLProcessor::GenBaseGradientKey(*this));
1002}
1003
fmenozzi55d318d2016-08-09 08:05:57 -07001004uint32_t GrGradientEffect::GLSLProcessor::GenBaseGradientKey(const GrProcessor& processor) {
joshualittb0a8a372014-09-23 09:50:21 -07001005 const GrGradientEffect& e = processor.cast<GrGradientEffect>();
skia.committer@gmail.com9a070f22013-09-10 07:01:44 +00001006
Florin Malita14a8dd72017-11-08 15:46:42 -05001007 // Build a key using the following bit allocation:
1008 static constexpr uint32_t kStrategyBits = 3;
1009 static constexpr uint32_t kPremulBits = 1;
1010 SkDEBUGCODE(static constexpr uint32_t kWrapModeBits = 2;)
bsalomon@google.com82d12232013-09-09 15:36:26 +00001011
Florin Malita14a8dd72017-11-08 15:46:42 -05001012 uint32_t key = static_cast<uint32_t>(e.fStrategy);
1013 SkASSERT(key < (1 << kStrategyBits));
1014
1015 // This is already baked into the table for texture gradients,
1016 // and only changes behavior for analytical gradients.
1017 if (e.fStrategy != InterpolationStrategy::kTexture &&
1018 e.fPremulType == GrGradientEffect::kBeforeInterp_PremulType) {
1019 key |= 1 << kStrategyBits;
1020 SkASSERT(key < (1 << (kStrategyBits + kPremulBits)));
bsalomon@google.com82d12232013-09-09 15:36:26 +00001021 }
1022
Florin Malita14a8dd72017-11-08 15:46:42 -05001023 key |= static_cast<uint32_t>(e.fWrapMode) << (kStrategyBits + kPremulBits);
1024 SkASSERT(key < (1 << (kStrategyBits + kPremulBits + kWrapModeBits)));
fmenozzicd9a1d02016-08-15 07:03:47 -07001025
bsalomon@google.com82d12232013-09-09 15:36:26 +00001026 return key;
bsalomon@google.comd8b5fac2012-11-01 17:02:46 +00001027}
1028
Florin Malitab81a8b92017-08-08 12:14:17 -04001029void GrGradientEffect::GLSLProcessor::emitAnalyticalColor(GrGLSLFPFragmentBuilder* fragBuilder,
1030 GrGLSLUniformHandler* uniformHandler,
1031 const GrShaderCaps* shaderCaps,
1032 const GrGradientEffect& ge,
1033 const char* t,
1034 const char* outputColor,
1035 const char* inputColor) {
1036 // First, apply tiling rules.
Brian Salomon2bbdcc42017-09-07 12:36:34 -04001037 switch (ge.fWrapMode) {
1038 case GrSamplerState::WrapMode::kClamp:
Florin Malita14a8dd72017-11-08 15:46:42 -05001039 switch (ge.fStrategy) {
1040 case GrGradientEffect::InterpolationStrategy::kThresholdClamp0:
1041 // allow t > 1, in order to hit the clamp interval (1, inf)
1042 fragBuilder->codeAppendf("half tiled_t = max(%s, 0.0);", t);
1043 break;
1044 case GrGradientEffect::InterpolationStrategy::kThresholdClamp1:
1045 // allow t < 0, in order to hit the clamp interval (-inf, 0)
1046 fragBuilder->codeAppendf("half tiled_t = min(%s, 1.0);", t);
1047 break;
1048 default:
1049 // regular [0, 1] clamping
1050 fragBuilder->codeAppendf("half tiled_t = clamp(%s, 0.0, 1.0);", t);
1051 }
Brian Salomon2bbdcc42017-09-07 12:36:34 -04001052 break;
1053 case GrSamplerState::WrapMode::kRepeat:
Florin Malita14a8dd72017-11-08 15:46:42 -05001054 fragBuilder->codeAppendf("half tiled_t = fract(%s);", t);
Brian Salomon2bbdcc42017-09-07 12:36:34 -04001055 break;
1056 case GrSamplerState::WrapMode::kMirrorRepeat:
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001057 fragBuilder->codeAppendf("half t_1 = %s - 1.0;", t);
Greg Daniel10ed2432017-12-01 16:19:43 -05001058 fragBuilder->codeAppendf("half tiled_t = t_1 - 2.0 * floor(t_1 * 0.5) - 1.0;");
1059 if (shaderCaps->mustDoOpBetweenFloorAndAbs()) {
1060 // At this point the expected value of tiled_t should between -1 and 1, so this
1061 // clamp has no effect other than to break up the floor and abs calls and make sure
1062 // the compiler doesn't merge them back together.
1063 fragBuilder->codeAppendf("tiled_t = clamp(tiled_t, -1.0, 1.0);");
1064 }
1065 fragBuilder->codeAppendf("tiled_t = abs(tiled_t);");
Brian Salomon2bbdcc42017-09-07 12:36:34 -04001066 break;
Florin Malita8a0044f2017-08-07 14:38:22 -04001067 }
Florin Malita8a0044f2017-08-07 14:38:22 -04001068
Florin Malitab81a8b92017-08-08 12:14:17 -04001069 // Calculate the color.
Florin Malita14a8dd72017-11-08 15:46:42 -05001070 const char* intervals = uniformHandler->getUniformCStr(fIntervalsUni);
fmenozzicd9a1d02016-08-15 07:03:47 -07001071
Florin Malita14a8dd72017-11-08 15:46:42 -05001072 switch (ge.fStrategy) {
1073 case GrGradientEffect::InterpolationStrategy::kSingle:
1074 SkASSERT(ge.fIntervals.count() == 2);
1075 fragBuilder->codeAppendf(
1076 "half4 color_scale = %s[0],"
1077 " color_bias = %s[1];"
1078 , intervals, intervals
1079 );
fmenozzicd9a1d02016-08-15 07:03:47 -07001080 break;
Florin Malita14a8dd72017-11-08 15:46:42 -05001081 case GrGradientEffect::InterpolationStrategy::kThreshold:
1082 case GrGradientEffect::InterpolationStrategy::kThresholdClamp0:
1083 case GrGradientEffect::InterpolationStrategy::kThresholdClamp1:
1084 {
1085 SkASSERT(ge.fIntervals.count() == 4);
1086 const char* threshold = uniformHandler->getUniformCStr(fThresholdUni);
1087 fragBuilder->codeAppendf(
1088 "half4 color_scale, color_bias;"
1089 "if (tiled_t < %s) {"
1090 " color_scale = %s[0];"
1091 " color_bias = %s[1];"
1092 "} else {"
1093 " color_scale = %s[2];"
1094 " color_bias = %s[3];"
1095 "}"
1096 , threshold, intervals, intervals, intervals, intervals
1097 );
1098 } break;
Florin Malitab81a8b92017-08-08 12:14:17 -04001099 default:
1100 SkASSERT(false);
fmenozzicd9a1d02016-08-15 07:03:47 -07001101 break;
bsalomon@google.com82d12232013-09-09 15:36:26 +00001102 }
Florin Malitab81a8b92017-08-08 12:14:17 -04001103
Florin Malita14a8dd72017-11-08 15:46:42 -05001104 fragBuilder->codeAppend("half4 colorTemp = tiled_t * color_scale + color_bias;");
1105
Brian Osmanfe3e8582017-10-20 11:27:49 -04001106 // We could skip this step if all colors are known to be opaque. Two considerations:
Florin Malitab81a8b92017-08-08 12:14:17 -04001107 // The gradient SkShader reporting opaque is more restrictive than necessary in the two
1108 // pt case. Make sure the key reflects this optimization (and note that it can use the
Brian Osmanfe3e8582017-10-20 11:27:49 -04001109 // same shader as the kBeforeInterp case).
Florin Malita14a8dd72017-11-08 15:46:42 -05001110 if (ge.fPremulType == GrGradientEffect::kAfterInterp_PremulType) {
Florin Malitab81a8b92017-08-08 12:14:17 -04001111 fragBuilder->codeAppend("colorTemp.rgb *= colorTemp.a;");
1112 }
Brian Osman5911a7c2017-10-25 12:52:31 -04001113
1114 // If the input colors were floats, or there was a color space xform, we may end up out of
Brian Osman8f912d52017-10-26 12:10:11 -04001115 // range. The simplest solution is to always clamp our (premul) value here. We only need to
1116 // clamp RGB, but that causes hangs on the Tegra3 Nexus7. Clamping RGBA avoids the problem.
1117 fragBuilder->codeAppend("colorTemp = clamp(colorTemp, 0, colorTemp.a);");
Florin Malitab81a8b92017-08-08 12:14:17 -04001118
1119 fragBuilder->codeAppendf("%s = %s * colorTemp;", outputColor, inputColor);
1120}
1121
1122void GrGradientEffect::GLSLProcessor::emitColor(GrGLSLFPFragmentBuilder* fragBuilder,
1123 GrGLSLUniformHandler* uniformHandler,
1124 const GrShaderCaps* shaderCaps,
1125 const GrGradientEffect& ge,
1126 const char* gradientTValue,
1127 const char* outputColor,
1128 const char* inputColor,
1129 const TextureSamplers& texSamplers) {
Florin Malita14a8dd72017-11-08 15:46:42 -05001130 if (ge.fStrategy != InterpolationStrategy::kTexture) {
Florin Malitab81a8b92017-08-08 12:14:17 -04001131 this->emitAnalyticalColor(fragBuilder, uniformHandler, shaderCaps, ge, gradientTValue,
1132 outputColor, inputColor);
1133 return;
1134 }
1135
Florin Malitab81a8b92017-08-08 12:14:17 -04001136 const char* fsyuni = uniformHandler->getUniformCStr(fFSYUni);
1137
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001138 fragBuilder->codeAppendf("half2 coord = half2(%s, %s);", gradientTValue, fsyuni);
Florin Malitab81a8b92017-08-08 12:14:17 -04001139 fragBuilder->codeAppendf("%s = ", outputColor);
1140 fragBuilder->appendTextureLookupAndModulate(inputColor, texSamplers[0], "coord",
Brian Osman5911a7c2017-10-25 12:52:31 -04001141 kFloat2_GrSLType);
Florin Malitab81a8b92017-08-08 12:14:17 -04001142 fragBuilder->codeAppend(";");
rileya@google.comd7cc6512012-07-27 14:00:39 +00001143}
1144
1145/////////////////////////////////////////////////////////////////////
1146
Brian Salomon587e08f2017-01-27 10:59:27 -05001147inline GrFragmentProcessor::OptimizationFlags GrGradientEffect::OptFlags(bool isOpaque) {
Brian Salomonf3b995b2017-02-15 10:22:23 -05001148 return isOpaque
1149 ? kPreservesOpaqueInput_OptimizationFlag |
1150 kCompatibleWithCoverageAsAlpha_OptimizationFlag
1151 : kCompatibleWithCoverageAsAlpha_OptimizationFlag;
Brian Salomon587e08f2017-01-27 10:59:27 -05001152}
1153
Florin Malita14a8dd72017-11-08 15:46:42 -05001154void GrGradientEffect::addInterval(const SkGradientShaderBase& shader, size_t idx0, size_t idx1,
1155 SkColorSpace* dstCS) {
1156 SkASSERT(idx0 <= idx1);
1157 const auto c4f0 = shader.getXformedColor(idx0, dstCS),
1158 c4f1 = shader.getXformedColor(idx1, dstCS);
1159 const auto c0 = (fPremulType == kBeforeInterp_PremulType)
1160 ? c4f0.premul().to4f() : Sk4f::Load(c4f0.vec()),
1161 c1 = (fPremulType == kBeforeInterp_PremulType)
1162 ? c4f1.premul().to4f() : Sk4f::Load(c4f1.vec());
1163 const auto t0 = shader.getPos(idx0),
1164 t1 = shader.getPos(idx1),
1165 dt = t1 - t0;
1166 SkASSERT(dt >= 0);
1167 // dt can be 0 for clamp intervals => in this case we want a scale == 0
1168 const auto scale = SkScalarNearlyZero(dt) ? 0 : (c1 - c0) / dt,
1169 bias = c0 - t0 * scale;
1170
1171 // Intervals are stored as (scale, bias) tuples.
1172 SkASSERT(!(fIntervals.count() & 1));
1173 fIntervals.emplace_back(scale[0], scale[1], scale[2], scale[3]);
1174 fIntervals.emplace_back( bias[0], bias[1], bias[2], bias[3]);
1175}
1176
Ethan Nicholasabff9562017-10-09 10:54:08 -04001177GrGradientEffect::GrGradientEffect(ClassID classID, const CreateArgs& args, bool isOpaque)
Florin Malita14a8dd72017-11-08 15:46:42 -05001178 : INHERITED(classID, OptFlags(isOpaque))
1179 , fWrapMode(args.fWrapMode)
1180 , fRow(-1)
1181 , fIsOpaque(args.fShader->isOpaque())
1182 , fStrategy(InterpolationStrategy::kTexture)
1183 , fThreshold(0) {
1184
brianosman9557c272016-09-15 06:59:15 -07001185 const SkGradientShaderBase& shader(*args.fShader);
bsalomon@google.com82d12232013-09-09 15:36:26 +00001186
Florin Malita14a8dd72017-11-08 15:46:42 -05001187 fPremulType = (args.fShader->getGradFlags() & SkGradientShader::kInterpolateColorsInPremul_Flag)
1188 ? kBeforeInterp_PremulType : kAfterInterp_PremulType;
bsalomon@google.com371e1052013-01-11 21:08:55 +00001189
Florin Malita14a8dd72017-11-08 15:46:42 -05001190 // First, determine the interpolation strategy and params.
1191 switch (shader.fColorCount) {
1192 case 2:
1193 SkASSERT(!shader.fOrigPos);
1194 fStrategy = InterpolationStrategy::kSingle;
1195 this->addInterval(shader, 0, 1, args.fDstColorSpace);
1196 break;
1197 case 3:
1198 fThreshold = shader.getPos(1);
bsalomon@google.com1ce49fc2012-09-18 14:14:49 +00001199
Florin Malita14a8dd72017-11-08 15:46:42 -05001200 if (shader.fOrigPos) {
1201 SkASSERT(SkScalarNearlyEqual(shader.fOrigPos[0], 0));
1202 SkASSERT(SkScalarNearlyEqual(shader.fOrigPos[2], 1));
1203 if (SkScalarNearlyEqual(shader.fOrigPos[1], 0)) {
1204 // hard stop on the left edge.
1205 if (fWrapMode == GrSamplerState::WrapMode::kClamp) {
1206 fStrategy = InterpolationStrategy::kThresholdClamp1;
1207 // Clamp interval (scale == 0, bias == colors[0]).
1208 this->addInterval(shader, 0, 0, args.fDstColorSpace);
1209 } else {
1210 // We can ignore the hard stop when not clamping.
1211 fStrategy = InterpolationStrategy::kSingle;
1212 }
1213 this->addInterval(shader, 1, 2, args.fDstColorSpace);
1214 break;
1215 }
Brian Osmand43f7b62017-10-19 15:42:01 -04001216
Florin Malita14a8dd72017-11-08 15:46:42 -05001217 if (SkScalarNearlyEqual(shader.fOrigPos[1], 1)) {
1218 // hard stop on the right edge.
1219 this->addInterval(shader, 0, 1, args.fDstColorSpace);
1220 if (fWrapMode == GrSamplerState::WrapMode::kClamp) {
1221 fStrategy = InterpolationStrategy::kThresholdClamp0;
1222 // Clamp interval (scale == 0, bias == colors[2]).
1223 this->addInterval(shader, 2, 2, args.fDstColorSpace);
1224 } else {
1225 // We can ignore the hard stop when not clamping.
1226 fStrategy = InterpolationStrategy::kSingle;
1227 }
1228 break;
1229 }
Brian Osmand43f7b62017-10-19 15:42:01 -04001230 }
1231
Florin Malita14a8dd72017-11-08 15:46:42 -05001232 // Two arbitrary interpolation intervals.
1233 fStrategy = InterpolationStrategy::kThreshold;
1234 this->addInterval(shader, 0, 1, args.fDstColorSpace);
1235 this->addInterval(shader, 1, 2, args.fDstColorSpace);
1236 break;
1237 case 4:
1238 if (shader.fOrigPos && SkScalarNearlyEqual(shader.fOrigPos[1], shader.fOrigPos[2])) {
1239 SkASSERT(SkScalarNearlyEqual(shader.fOrigPos[0], 0));
1240 SkASSERT(SkScalarNearlyEqual(shader.fOrigPos[3], 1));
fmenozzi2a495912016-08-12 06:33:52 -07001241
Florin Malita14a8dd72017-11-08 15:46:42 -05001242 // Single hard stop => two arbitrary interpolation intervals.
1243 fStrategy = InterpolationStrategy::kThreshold;
1244 fThreshold = shader.getPos(1);
1245 this->addInterval(shader, 0, 1, args.fDstColorSpace);
1246 this->addInterval(shader, 2, 3, args.fDstColorSpace);
1247 }
1248 break;
1249 default:
1250 break;
fmenozzi2a495912016-08-12 06:33:52 -07001251 }
fmenozzicd9a1d02016-08-15 07:03:47 -07001252
Florin Malita14a8dd72017-11-08 15:46:42 -05001253 // Now that we've locked down a strategy, adjust any dependent params.
1254 if (fStrategy != InterpolationStrategy::kTexture) {
1255 // Analytical cases.
1256 fCoordTransform.reset(*args.fMatrix);
1257 } else {
1258 SkGradientShaderBase::GradientBitmapType bitmapType =
1259 SkGradientShaderBase::GradientBitmapType::kLegacy;
1260 if (args.fDstColorSpace) {
1261 // Try to use F16 if we can
1262 if (args.fContext->caps()->isConfigTexturable(kRGBA_half_GrPixelConfig)) {
1263 bitmapType = SkGradientShaderBase::GradientBitmapType::kHalfFloat;
1264 } else if (args.fContext->caps()->isConfigTexturable(kSRGBA_8888_GrPixelConfig)) {
1265 bitmapType = SkGradientShaderBase::GradientBitmapType::kSRGB;
fmenozzicd9a1d02016-08-15 07:03:47 -07001266 } else {
Florin Malita14a8dd72017-11-08 15:46:42 -05001267 // This can happen, but only if someone explicitly creates an unsupported
1268 // (eg sRGB) surface. Just fall back to legacy behavior.
fmenozzicd9a1d02016-08-15 07:03:47 -07001269 }
Florin Malita14a8dd72017-11-08 15:46:42 -05001270 }
fmenozzicd9a1d02016-08-15 07:03:47 -07001271
Florin Malita14a8dd72017-11-08 15:46:42 -05001272 SkBitmap bitmap;
1273 shader.getGradientTableBitmap(&bitmap, bitmapType);
1274 SkASSERT(1 == bitmap.height() && SkIsPow2(bitmap.width()));
fmenozzicd9a1d02016-08-15 07:03:47 -07001275
Robert Phillips41a3b872018-03-09 12:00:34 -05001276 auto atlasManager = args.fContext->contextPriv().textureStripAtlasManager();
Florin Malita14a8dd72017-11-08 15:46:42 -05001277
1278 GrTextureStripAtlas::Desc desc;
1279 desc.fWidth = bitmap.width();
1280 desc.fHeight = 32;
Robert Phillips7a926392018-02-01 15:49:54 -05001281 desc.fRowHeight = bitmap.height(); // always 1 here
Florin Malita14a8dd72017-11-08 15:46:42 -05001282 desc.fConfig = SkImageInfo2GrPixelConfig(bitmap.info(), *args.fContext->caps());
Robert Phillips96b6d532018-03-19 10:57:42 -04001283 fAtlas = atlasManager->refAtlas(desc);
Florin Malita14a8dd72017-11-08 15:46:42 -05001284 SkASSERT(fAtlas);
1285
1286 // We always filter the gradient table. Each table is one row of a texture, always
1287 // y-clamp.
1288 GrSamplerState samplerState(args.fWrapMode, GrSamplerState::Filter::kBilerp);
1289
Robert Phillips41a3b872018-03-09 12:00:34 -05001290 fRow = fAtlas->lockRow(args.fContext, bitmap);
Florin Malita14a8dd72017-11-08 15:46:42 -05001291 if (-1 != fRow) {
1292 fYCoord = fAtlas->getYOffset(fRow)+SK_ScalarHalf*fAtlas->getNormalizedTexelHeight();
1293 // This is 1/2 places where auto-normalization is disabled
1294 fCoordTransform.reset(*args.fMatrix, fAtlas->asTextureProxyRef().get(), false);
1295 fTextureSampler.reset(fAtlas->asTextureProxyRef(), samplerState);
1296 } else {
1297 // In this instance we know the samplerState state is:
1298 // clampY, bilerp
1299 // and the proxy is:
1300 // exact fit, power of two in both dimensions
1301 // Only the x-tileMode is unknown. However, given all the other knowns we know
Robert Phillips7a926392018-02-01 15:49:54 -05001302 // that GrMakeCachedImageProxy is sufficient (i.e., it won't need to be
Florin Malita14a8dd72017-11-08 15:46:42 -05001303 // extracted to a subset or mipmapped).
Robert Phillips7a926392018-02-01 15:49:54 -05001304
1305 SkASSERT(bitmap.isImmutable());
1306 sk_sp<SkImage> srcImage = SkImage::MakeFromBitmap(bitmap);
1307 if (!srcImage) {
1308 return;
1309 }
1310
1311 sk_sp<GrTextureProxy> proxy = GrMakeCachedImageProxy(
Robert Phillips1afd4cd2018-01-08 13:40:32 -05001312 args.fContext->contextPriv().proxyProvider(),
Robert Phillips7a926392018-02-01 15:49:54 -05001313 std::move(srcImage));
Florin Malita14a8dd72017-11-08 15:46:42 -05001314 if (!proxy) {
1315 SkDebugf("Gradient won't draw. Could not create texture.");
1316 return;
1317 }
1318 // This is 2/2 places where auto-normalization is disabled
1319 fCoordTransform.reset(*args.fMatrix, proxy.get(), false);
1320 fTextureSampler.reset(std::move(proxy), samplerState);
1321 fYCoord = SK_ScalarHalf;
1322 }
1323
1324 this->addTextureSampler(&fTextureSampler);
fmenozzicd9a1d02016-08-15 07:03:47 -07001325 }
1326
bsalomon@google.com77af6802013-10-02 13:04:56 +00001327 this->addCoordTransform(&fCoordTransform);
rileya@google.comd7cc6512012-07-27 14:00:39 +00001328}
1329
Brian Salomonf8480b92017-07-27 15:45:59 -04001330GrGradientEffect::GrGradientEffect(const GrGradientEffect& that)
Ethan Nicholasabff9562017-10-09 10:54:08 -04001331 : INHERITED(that.classID(), OptFlags(that.fIsOpaque))
Florin Malita14a8dd72017-11-08 15:46:42 -05001332 , fIntervals(that.fIntervals)
Brian Salomon2bbdcc42017-09-07 12:36:34 -04001333 , fWrapMode(that.fWrapMode)
Brian Salomonf8480b92017-07-27 15:45:59 -04001334 , fCoordTransform(that.fCoordTransform)
1335 , fTextureSampler(that.fTextureSampler)
1336 , fYCoord(that.fYCoord)
1337 , fAtlas(that.fAtlas)
1338 , fRow(that.fRow)
1339 , fIsOpaque(that.fIsOpaque)
Florin Malita14a8dd72017-11-08 15:46:42 -05001340 , fStrategy(that.fStrategy)
1341 , fThreshold(that.fThreshold)
Brian Salomonf8480b92017-07-27 15:45:59 -04001342 , fPremulType(that.fPremulType) {
1343 this->addCoordTransform(&fCoordTransform);
Florin Malita14a8dd72017-11-08 15:46:42 -05001344 if (fStrategy == InterpolationStrategy::kTexture) {
Brian Salomonf8480b92017-07-27 15:45:59 -04001345 this->addTextureSampler(&fTextureSampler);
1346 }
1347 if (this->useAtlas()) {
1348 fAtlas->lockRow(fRow);
1349 }
1350}
1351
rileya@google.comd7cc6512012-07-27 14:00:39 +00001352GrGradientEffect::~GrGradientEffect() {
rileya@google.comb3e50f22012-08-20 17:43:08 +00001353 if (this->useAtlas()) {
1354 fAtlas->unlockRow(fRow);
rileya@google.comb3e50f22012-08-20 17:43:08 +00001355 }
rileya@google.comd7cc6512012-07-27 14:00:39 +00001356}
1357
bsalomon0e08fc12014-10-15 08:19:04 -07001358bool GrGradientEffect::onIsEqual(const GrFragmentProcessor& processor) const {
fmenozzicd9a1d02016-08-15 07:03:47 -07001359 const GrGradientEffect& ge = processor.cast<GrGradientEffect>();
bsalomon@google.com82d12232013-09-09 15:36:26 +00001360
Florin Malita14a8dd72017-11-08 15:46:42 -05001361 if (fWrapMode != ge.fWrapMode || fStrategy != ge.fStrategy) {
Brian Salomon466ad992016-10-13 16:08:36 -04001362 return false;
1363 }
Florin Malita14a8dd72017-11-08 15:46:42 -05001364
Brian Salomon466ad992016-10-13 16:08:36 -04001365 SkASSERT(this->useAtlas() == ge.useAtlas());
Florin Malita14a8dd72017-11-08 15:46:42 -05001366 if (fStrategy == InterpolationStrategy::kTexture) {
1367 if (fYCoord != ge.fYCoord) {
Brian Salomon466ad992016-10-13 16:08:36 -04001368 return false;
1369 }
1370 } else {
Florin Malita14a8dd72017-11-08 15:46:42 -05001371 if (fThreshold != ge.fThreshold ||
1372 fIntervals != ge.fIntervals ||
1373 fPremulType != ge.fPremulType) {
Brian Salomon466ad992016-10-13 16:08:36 -04001374 return false;
1375 }
bsalomon@google.com82d12232013-09-09 15:36:26 +00001376 }
Brian Osman5911a7c2017-10-25 12:52:31 -04001377 return true;
bsalomon@google.com68b58c92013-01-17 16:50:08 +00001378}
1379
Hal Canary6f6961e2017-01-31 13:50:44 -05001380#if GR_TEST_UTILS
Brian Osman3f748602016-10-03 18:29:03 -04001381GrGradientEffect::RandomGradientParams::RandomGradientParams(SkRandom* random) {
Brian Salomon5d4cd9e2017-02-09 11:16:46 -05001382 // Set color count to min of 2 so that we don't trigger the const color optimization and make
1383 // a non-gradient processor.
1384 fColorCount = random->nextRangeU(2, kMaxRandomGradientColors);
Brian Osmana2196532016-10-17 12:48:13 -04001385 fUseColors4f = random->nextBool();
bsalomon@google.comd4726202012-08-03 14:34:46 +00001386
1387 // if one color, omit stops, otherwise randomly decide whether or not to
Brian Osman3f748602016-10-03 18:29:03 -04001388 if (fColorCount == 1 || (fColorCount >= 2 && random->nextBool())) {
1389 fStops = nullptr;
1390 } else {
1391 fStops = fStopStorage;
bsalomon@google.comd4726202012-08-03 14:34:46 +00001392 }
1393
Brian Osmana2196532016-10-17 12:48:13 -04001394 // if using SkColor4f, attach a random (possibly null) color space (with linear gamma)
1395 if (fUseColors4f) {
1396 fColorSpace = GrTest::TestColorSpace(random);
1397 if (fColorSpace) {
Brian Osman36703d92017-12-12 14:09:31 -05001398 fColorSpace = fColorSpace->makeLinearGamma();
Brian Osmana2196532016-10-17 12:48:13 -04001399 }
1400 }
1401
bsalomon@google.com81712882012-11-01 17:12:34 +00001402 SkScalar stop = 0.f;
Brian Osman3f748602016-10-03 18:29:03 -04001403 for (int i = 0; i < fColorCount; ++i) {
Brian Osmana2196532016-10-17 12:48:13 -04001404 if (fUseColors4f) {
1405 fColors4f[i].fR = random->nextUScalar1();
1406 fColors4f[i].fG = random->nextUScalar1();
1407 fColors4f[i].fB = random->nextUScalar1();
1408 fColors4f[i].fA = random->nextUScalar1();
1409 } else {
1410 fColors[i] = random->nextU();
1411 }
Brian Osman3f748602016-10-03 18:29:03 -04001412 if (fStops) {
1413 fStops[i] = stop;
1414 stop = i < fColorCount - 1 ? stop + random->nextUScalar1() * (1.f - stop) : 1.f;
bsalomon@google.comd4726202012-08-03 14:34:46 +00001415 }
1416 }
Brian Osman3f748602016-10-03 18:29:03 -04001417 fTileMode = static_cast<SkShader::TileMode>(random->nextULessThan(SkShader::kTileModeCount));
bsalomon@google.comd4726202012-08-03 14:34:46 +00001418}
Hal Canary6f6961e2017-01-31 13:50:44 -05001419#endif
bsalomon@google.comd4726202012-08-03 14:34:46 +00001420
bsalomon@google.comcf8fb1f2012-08-02 14:03:32 +00001421#endif