blob: afb4f8b95a5055a128b6c4c6494e4ef41471b481 [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
fmalitabc590c02016-02-22 09:12:33 -08008#include "Sk4fLinearGradient.h"
raftias94888332016-10-18 10:02:51 -07009#include "SkColorSpace_XYZ.h"
rileya@google.com589708b2012-07-26 20:04:23 +000010#include "SkGradientShaderPriv.h"
brianosmand4546092016-09-22 12:31:58 -070011#include "SkHalf.h"
rileya@google.com589708b2012-07-26 20:04:23 +000012#include "SkLinearGradient.h"
13#include "SkRadialGradient.h"
rileya@google.com589708b2012-07-26 20:04:23 +000014#include "SkTwoPointConicalGradient.h"
15#include "SkSweepGradient.h"
16
brianosmane25d71c2016-09-28 11:27:28 -070017enum GradientSerializationFlags {
18 // Bits 29:31 used for various boolean flags
19 kHasPosition_GSF = 0x80000000,
20 kHasLocalMatrix_GSF = 0x40000000,
21 kHasColorSpace_GSF = 0x20000000,
22
23 // Bits 12:28 unused
24
25 // Bits 8:11 for fTileMode
26 kTileModeShift_GSF = 8,
27 kTileModeMask_GSF = 0xF,
28
29 // Bits 0:7 for fGradFlags (note that kForce4fContext_PrivateFlag is 0x80)
30 kGradFlagsShift_GSF = 0,
31 kGradFlagsMask_GSF = 0xFF,
32};
33
reed9fa60da2014-08-21 07:59:51 -070034void SkGradientShaderBase::Descriptor::flatten(SkWriteBuffer& buffer) const {
brianosmane25d71c2016-09-28 11:27:28 -070035 uint32_t flags = 0;
reed9fa60da2014-08-21 07:59:51 -070036 if (fPos) {
brianosmane25d71c2016-09-28 11:27:28 -070037 flags |= kHasPosition_GSF;
reed9fa60da2014-08-21 07:59:51 -070038 }
reed9fa60da2014-08-21 07:59:51 -070039 if (fLocalMatrix) {
brianosmane25d71c2016-09-28 11:27:28 -070040 flags |= kHasLocalMatrix_GSF;
41 }
42 sk_sp<SkData> colorSpaceData = fColorSpace ? fColorSpace->serialize() : nullptr;
43 if (colorSpaceData) {
44 flags |= kHasColorSpace_GSF;
45 }
46 SkASSERT(static_cast<uint32_t>(fTileMode) <= kTileModeMask_GSF);
47 flags |= (fTileMode << kTileModeShift_GSF);
48 SkASSERT(fGradFlags <= kGradFlagsMask_GSF);
49 flags |= (fGradFlags << kGradFlagsShift_GSF);
50
51 buffer.writeUInt(flags);
52
53 buffer.writeColor4fArray(fColors, fCount);
54 if (colorSpaceData) {
55 buffer.writeDataAsByteArray(colorSpaceData.get());
56 }
57 if (fPos) {
58 buffer.writeScalarArray(fPos, fCount);
59 }
60 if (fLocalMatrix) {
reed9fa60da2014-08-21 07:59:51 -070061 buffer.writeMatrix(*fLocalMatrix);
reed9fa60da2014-08-21 07:59:51 -070062 }
63}
64
65bool SkGradientShaderBase::DescriptorScope::unflatten(SkReadBuffer& buffer) {
brianosmane25d71c2016-09-28 11:27:28 -070066 if (buffer.isVersionLT(SkReadBuffer::kGradientShaderFloatColor_Version)) {
67 fCount = buffer.getArrayCount();
68 if (fCount > kStorageCount) {
69 size_t allocSize = (sizeof(SkColor4f) + sizeof(SkScalar)) * fCount;
70 fDynamicStorage.reset(allocSize);
71 fColors = (SkColor4f*)fDynamicStorage.get();
72 fPos = (SkScalar*)(fColors + fCount);
73 } else {
74 fColors = fColorStorage;
75 fPos = fPosStorage;
76 }
reed9fa60da2014-08-21 07:59:51 -070077
brianosmane25d71c2016-09-28 11:27:28 -070078 // Old gradients serialized SkColor. Read that to a temporary location, then convert.
79 SkSTArray<2, SkColor, true> colors;
80 colors.resize_back(fCount);
81 if (!buffer.readColorArray(colors.begin(), fCount)) {
reed9fa60da2014-08-21 07:59:51 -070082 return false;
83 }
brianosmane25d71c2016-09-28 11:27:28 -070084 for (int i = 0; i < fCount; ++i) {
85 mutableColors()[i] = SkColor4f::FromColor(colors[i]);
86 }
reed9fa60da2014-08-21 07:59:51 -070087
brianosmane25d71c2016-09-28 11:27:28 -070088 if (buffer.readBool()) {
89 if (!buffer.readScalarArray(const_cast<SkScalar*>(fPos), fCount)) {
90 return false;
91 }
92 } else {
93 fPos = nullptr;
94 }
reed9fa60da2014-08-21 07:59:51 -070095
brianosmane25d71c2016-09-28 11:27:28 -070096 fColorSpace = nullptr;
97 fTileMode = (SkShader::TileMode)buffer.read32();
98 fGradFlags = buffer.read32();
99
100 if (buffer.readBool()) {
101 fLocalMatrix = &fLocalMatrixStorage;
102 buffer.readMatrix(&fLocalMatrixStorage);
103 } else {
104 fLocalMatrix = nullptr;
105 }
reed9fa60da2014-08-21 07:59:51 -0700106 } else {
brianosmane25d71c2016-09-28 11:27:28 -0700107 // New gradient format. Includes floating point color, color space, densely packed flags
108 uint32_t flags = buffer.readUInt();
109
110 fTileMode = (SkShader::TileMode)((flags >> kTileModeShift_GSF) & kTileModeMask_GSF);
111 fGradFlags = (flags >> kGradFlagsShift_GSF) & kGradFlagsMask_GSF;
112
113 fCount = buffer.getArrayCount();
114 if (fCount > kStorageCount) {
115 size_t allocSize = (sizeof(SkColor4f) + sizeof(SkScalar)) * fCount;
116 fDynamicStorage.reset(allocSize);
117 fColors = (SkColor4f*)fDynamicStorage.get();
118 fPos = (SkScalar*)(fColors + fCount);
119 } else {
120 fColors = fColorStorage;
121 fPos = fPosStorage;
122 }
123 if (!buffer.readColor4fArray(mutableColors(), fCount)) {
124 return false;
125 }
126 if (SkToBool(flags & kHasColorSpace_GSF)) {
127 sk_sp<SkData> data = buffer.readByteArrayAsData();
128 fColorSpace = SkColorSpace::Deserialize(data->data(), data->size());
129 } else {
130 fColorSpace = nullptr;
131 }
132 if (SkToBool(flags & kHasPosition_GSF)) {
133 if (!buffer.readScalarArray(mutablePos(), fCount)) {
134 return false;
135 }
136 } else {
137 fPos = nullptr;
138 }
139 if (SkToBool(flags & kHasLocalMatrix_GSF)) {
140 fLocalMatrix = &fLocalMatrixStorage;
141 buffer.readMatrix(&fLocalMatrixStorage);
142 } else {
143 fLocalMatrix = nullptr;
144 }
reed9fa60da2014-08-21 07:59:51 -0700145 }
146 return buffer.isValid();
147}
148
149////////////////////////////////////////////////////////////////////////////////////////////
150
mtkleincc695fe2014-12-10 10:29:19 -0800151SkGradientShaderBase::SkGradientShaderBase(const Descriptor& desc, const SkMatrix& ptsToUnit)
reedaddf2ed2014-08-11 08:28:24 -0700152 : INHERITED(desc.fLocalMatrix)
mtkleincc695fe2014-12-10 10:29:19 -0800153 , fPtsToUnit(ptsToUnit)
commit-bot@chromium.org9c9005a2014-04-28 14:55:39 +0000154{
mtkleincc695fe2014-12-10 10:29:19 -0800155 fPtsToUnit.getType(); // Precache so reads are threadsafe.
reed@google.com437d6eb2013-05-23 19:03:05 +0000156 SkASSERT(desc.fCount > 1);
rileya@google.com589708b2012-07-26 20:04:23 +0000157
fmalita6d7e4e82016-09-20 06:55:16 -0700158 fGradFlags = static_cast<uint8_t>(desc.fGradFlags);
rileya@google.com589708b2012-07-26 20:04:23 +0000159
reed@google.com437d6eb2013-05-23 19:03:05 +0000160 SkASSERT((unsigned)desc.fTileMode < SkShader::kTileModeCount);
rileya@google.com589708b2012-07-26 20:04:23 +0000161 SkASSERT(SkShader::kTileModeCount == SK_ARRAY_COUNT(gTileProcs));
reed@google.com437d6eb2013-05-23 19:03:05 +0000162 fTileMode = desc.fTileMode;
163 fTileProc = gTileProcs[desc.fTileMode];
rileya@google.com589708b2012-07-26 20:04:23 +0000164
rileya@google.com589708b2012-07-26 20:04:23 +0000165 /* Note: we let the caller skip the first and/or last position.
166 i.e. pos[0] = 0.3, pos[1] = 0.7
167 In these cases, we insert dummy entries to ensure that the final data
168 will be bracketed by [0, 1].
169 i.e. our_pos[0] = 0, our_pos[1] = 0.3, our_pos[2] = 0.7, our_pos[3] = 1
170
171 Thus colorCount (the caller's value, and fColorCount (our value) may
172 differ by up to 2. In the above example:
173 colorCount = 2
174 fColorCount = 4
175 */
reed@google.com437d6eb2013-05-23 19:03:05 +0000176 fColorCount = desc.fCount;
rileya@google.com589708b2012-07-26 20:04:23 +0000177 // check if we need to add in dummy start and/or end position/colors
178 bool dummyFirst = false;
179 bool dummyLast = false;
reed@google.com437d6eb2013-05-23 19:03:05 +0000180 if (desc.fPos) {
181 dummyFirst = desc.fPos[0] != 0;
182 dummyLast = desc.fPos[desc.fCount - 1] != SK_Scalar1;
rileya@google.com589708b2012-07-26 20:04:23 +0000183 fColorCount += dummyFirst + dummyLast;
184 }
185
186 if (fColorCount > kColorStorageCount) {
brianosmanb9c51372016-09-15 11:09:45 -0700187 size_t size = sizeof(SkColor) + sizeof(SkColor4f) + sizeof(Rec);
reed9fa60da2014-08-21 07:59:51 -0700188 if (desc.fPos) {
189 size += sizeof(SkScalar);
190 }
brianosmane25d71c2016-09-28 11:27:28 -0700191 fOrigColors = reinterpret_cast<SkColor*>(sk_malloc_throw(size * fColorCount));
rileya@google.com589708b2012-07-26 20:04:23 +0000192 }
193 else {
194 fOrigColors = fStorage;
195 }
196
brianosmanb9c51372016-09-15 11:09:45 -0700197 fOrigColors4f = (SkColor4f*)(fOrigColors + fColorCount);
198
brianosmane25d71c2016-09-28 11:27:28 -0700199 // Now copy over the colors, adding the dummies as needed
200 SkColor4f* origColors = fOrigColors4f;
201 if (dummyFirst) {
202 *origColors++ = desc.fColors[0];
203 }
204 memcpy(origColors, desc.fColors, desc.fCount * sizeof(SkColor4f));
205 if (dummyLast) {
206 origColors += desc.fCount;
207 *origColors = desc.fColors[desc.fCount - 1];
208 }
brianosmanb9c51372016-09-15 11:09:45 -0700209
brianosmane25d71c2016-09-28 11:27:28 -0700210 // Convert our SkColor4f colors to SkColor as well. Note that this is incorrect if the
211 // source colors are not in sRGB gamut. We would need to do a gamut transformation, but
212 // SkColorSpaceXform can't do that (yet). GrColorSpaceXform can, but we may not have GPU
213 // support compiled in here. For the common case (sRGB colors), this does the right thing.
214 for (int i = 0; i < fColorCount; ++i) {
215 fOrigColors[i] = fOrigColors4f[i].toSkColor();
216 }
brianosmanb9c51372016-09-15 11:09:45 -0700217
brianosmane25d71c2016-09-28 11:27:28 -0700218 if (!desc.fColorSpace) {
219 // This happens if we were constructed from SkColors, so our colors are really sRGB
Matt Sarett77a7a1b2017-02-07 13:56:11 -0500220 fColorSpace = SkColorSpace::MakeSRGBLinear();
brianosmanb9c51372016-09-15 11:09:45 -0700221 } else {
brianosmane25d71c2016-09-28 11:27:28 -0700222 // The color space refers to the float colors, so it must be linear gamma
223 SkASSERT(desc.fColorSpace->gammaIsLinear());
brianosmanb9c51372016-09-15 11:09:45 -0700224 fColorSpace = desc.fColorSpace;
rileya@google.com589708b2012-07-26 20:04:23 +0000225 }
226
reed9fa60da2014-08-21 07:59:51 -0700227 if (desc.fPos && fColorCount) {
brianosmanb9c51372016-09-15 11:09:45 -0700228 fOrigPos = (SkScalar*)(fOrigColors4f + fColorCount);
reed9fa60da2014-08-21 07:59:51 -0700229 fRecs = (Rec*)(fOrigPos + fColorCount);
230 } else {
halcanary96fcdcc2015-08-27 07:41:13 -0700231 fOrigPos = nullptr;
brianosmanb9c51372016-09-15 11:09:45 -0700232 fRecs = (Rec*)(fOrigColors4f + fColorCount);
reed9fa60da2014-08-21 07:59:51 -0700233 }
234
rileya@google.com589708b2012-07-26 20:04:23 +0000235 if (fColorCount > 2) {
236 Rec* recs = fRecs;
237 recs->fPos = 0;
238 // recs->fScale = 0; // unused;
239 recs += 1;
reed@google.com437d6eb2013-05-23 19:03:05 +0000240 if (desc.fPos) {
reed9fa60da2014-08-21 07:59:51 -0700241 SkScalar* origPosPtr = fOrigPos;
242 *origPosPtr++ = 0;
243
rileya@google.com589708b2012-07-26 20:04:23 +0000244 /* We need to convert the user's array of relative positions into
245 fixed-point positions and scale factors. We need these results
246 to be strictly monotonic (no two values equal or out of order).
247 Hence this complex loop that just jams a zero for the scale
248 value if it sees a segment out of order, and it assures that
249 we start at 0 and end at 1.0
250 */
reed9fa60da2014-08-21 07:59:51 -0700251 SkScalar prev = 0;
rileya@google.com589708b2012-07-26 20:04:23 +0000252 int startIndex = dummyFirst ? 0 : 1;
reed@google.com437d6eb2013-05-23 19:03:05 +0000253 int count = desc.fCount + dummyLast;
rileya@google.com589708b2012-07-26 20:04:23 +0000254 for (int i = startIndex; i < count; i++) {
255 // force the last value to be 1.0
reed9fa60da2014-08-21 07:59:51 -0700256 SkScalar curr;
reed@google.com437d6eb2013-05-23 19:03:05 +0000257 if (i == desc.fCount) { // we're really at the dummyLast
reed9fa60da2014-08-21 07:59:51 -0700258 curr = 1;
rileya@google.com589708b2012-07-26 20:04:23 +0000259 } else {
reed9fa60da2014-08-21 07:59:51 -0700260 curr = SkScalarPin(desc.fPos[i], 0, 1);
rileya@google.com589708b2012-07-26 20:04:23 +0000261 }
reed9fa60da2014-08-21 07:59:51 -0700262 *origPosPtr++ = curr;
mtklein55de40b2014-08-21 11:52:36 -0700263
reed9fa60da2014-08-21 07:59:51 -0700264 recs->fPos = SkScalarToFixed(curr);
mtklein55de40b2014-08-21 11:52:36 -0700265 SkFixed diff = SkScalarToFixed(curr - prev);
266 if (diff > 0) {
267 recs->fScale = (1 << 24) / diff;
rileya@google.com589708b2012-07-26 20:04:23 +0000268 } else {
269 recs->fScale = 0; // ignore this segment
270 }
271 // get ready for the next value
272 prev = curr;
273 recs += 1;
274 }
275 } else { // assume even distribution
halcanary96fcdcc2015-08-27 07:41:13 -0700276 fOrigPos = nullptr;
reed9fa60da2014-08-21 07:59:51 -0700277
reed@google.com437d6eb2013-05-23 19:03:05 +0000278 SkFixed dp = SK_Fixed1 / (desc.fCount - 1);
rileya@google.com589708b2012-07-26 20:04:23 +0000279 SkFixed p = dp;
reed@google.com437d6eb2013-05-23 19:03:05 +0000280 SkFixed scale = (desc.fCount - 1) << 8; // (1 << 24) / dp
commit-bot@chromium.org44d83c12014-04-21 13:10:25 +0000281 for (int i = 1; i < desc.fCount - 1; i++) {
rileya@google.com589708b2012-07-26 20:04:23 +0000282 recs->fPos = p;
283 recs->fScale = scale;
284 recs += 1;
285 p += dp;
286 }
commit-bot@chromium.org44d83c12014-04-21 13:10:25 +0000287 recs->fPos = SK_Fixed1;
commit-bot@chromium.org811f20d2014-04-21 21:09:49 +0000288 recs->fScale = scale;
rileya@google.com589708b2012-07-26 20:04:23 +0000289 }
reed9fa60da2014-08-21 07:59:51 -0700290 } else if (desc.fPos) {
291 SkASSERT(2 == fColorCount);
292 fOrigPos[0] = SkScalarPin(desc.fPos[0], 0, 1);
293 fOrigPos[1] = SkScalarPin(desc.fPos[1], fOrigPos[0], 1);
294 if (0 == fOrigPos[0] && 1 == fOrigPos[1]) {
halcanary96fcdcc2015-08-27 07:41:13 -0700295 fOrigPos = nullptr;
reed9fa60da2014-08-21 07:59:51 -0700296 }
rileya@google.com589708b2012-07-26 20:04:23 +0000297 }
298 this->initCommon();
299}
300
rileya@google.com589708b2012-07-26 20:04:23 +0000301SkGradientShaderBase::~SkGradientShaderBase() {
rileya@google.com589708b2012-07-26 20:04:23 +0000302 if (fOrigColors != fStorage) {
303 sk_free(fOrigColors);
304 }
rileya@google.com589708b2012-07-26 20:04:23 +0000305}
306
307void SkGradientShaderBase::initCommon() {
rileya@google.com589708b2012-07-26 20:04:23 +0000308 unsigned colorAlpha = 0xFF;
309 for (int i = 0; i < fColorCount; i++) {
310 colorAlpha &= SkColorGetA(fOrigColors[i]);
311 }
312 fColorsAreOpaque = colorAlpha == 0xFF;
313}
314
commit-bot@chromium.org8b0e8ac2014-01-30 18:58:24 +0000315void SkGradientShaderBase::flatten(SkWriteBuffer& buffer) const {
reed9fa60da2014-08-21 07:59:51 -0700316 Descriptor desc;
brianosmane25d71c2016-09-28 11:27:28 -0700317 desc.fColors = fOrigColors4f;
brianosmanb9c51372016-09-15 11:09:45 -0700318 desc.fColorSpace = fColorSpace;
reed9fa60da2014-08-21 07:59:51 -0700319 desc.fPos = fOrigPos;
320 desc.fCount = fColorCount;
321 desc.fTileMode = fTileMode;
322 desc.fGradFlags = fGradFlags;
323
324 const SkMatrix& m = this->getLocalMatrix();
halcanary96fcdcc2015-08-27 07:41:13 -0700325 desc.fLocalMatrix = m.isIdentity() ? nullptr : &m;
reed9fa60da2014-08-21 07:59:51 -0700326 desc.flatten(buffer);
rileya@google.com589708b2012-07-26 20:04:23 +0000327}
328
commit-bot@chromium.org44d83c12014-04-21 13:10:25 +0000329void SkGradientShaderBase::FlipGradientColors(SkColor* colorDst, Rec* recDst,
330 SkColor* colorSrc, Rec* recSrc,
331 int count) {
332 SkAutoSTArray<8, SkColor> colorsTemp(count);
333 for (int i = 0; i < count; ++i) {
334 int offset = count - i - 1;
335 colorsTemp[i] = colorSrc[offset];
336 }
337 if (count > 2) {
338 SkAutoSTArray<8, Rec> recsTemp(count);
339 for (int i = 0; i < count; ++i) {
340 int offset = count - i - 1;
341 recsTemp[i].fPos = SK_Fixed1 - recSrc[offset].fPos;
342 recsTemp[i].fScale = recSrc[offset].fScale;
343 }
344 memcpy(recDst, recsTemp.get(), count * sizeof(Rec));
345 }
346 memcpy(colorDst, colorsTemp.get(), count * sizeof(SkColor));
347}
348
rileya@google.com589708b2012-07-26 20:04:23 +0000349bool SkGradientShaderBase::isOpaque() const {
350 return fColorsAreOpaque;
351}
352
reed8367b8c2014-08-22 08:30:20 -0700353static unsigned rounded_divide(unsigned numer, unsigned denom) {
354 return (numer + (denom >> 1)) / denom;
355}
356
357bool SkGradientShaderBase::onAsLuminanceColor(SkColor* lum) const {
358 // we just compute an average color.
359 // possibly we could weight this based on the proportional width for each color
360 // assuming they are not evenly distributed in the fPos array.
361 int r = 0;
362 int g = 0;
363 int b = 0;
364 const int n = fColorCount;
365 for (int i = 0; i < n; ++i) {
366 SkColor c = fOrigColors[i];
367 r += SkColorGetR(c);
368 g += SkColorGetG(c);
369 b += SkColorGetB(c);
370 }
371 *lum = SkColorSetRGB(rounded_divide(r, n), rounded_divide(g, n), rounded_divide(b, n));
372 return true;
373}
374
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000375SkGradientShaderBase::GradientShaderBaseContext::GradientShaderBaseContext(
commit-bot@chromium.orge901b6d2014-05-01 19:31:31 +0000376 const SkGradientShaderBase& shader, const ContextRec& rec)
377 : INHERITED(shader, rec)
fmalita37d86882015-10-09 10:22:46 -0700378#ifdef SK_SUPPORT_LEGACY_GRADIENT_DITHERING
379 , fDither(true)
380#else
381 , fDither(rec.fPaint->isDither())
382#endif
383 , fCache(shader.refCache(getPaintAlpha(), fDither))
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000384{
rileya@google.com589708b2012-07-26 20:04:23 +0000385 const SkMatrix& inverse = this->getTotalInverse();
386
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000387 fDstToIndex.setConcat(shader.fPtsToUnit, inverse);
388
rileya@google.com589708b2012-07-26 20:04:23 +0000389 fDstToIndexProc = fDstToIndex.getMapXYProc();
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000390 fDstToIndexClass = (uint8_t)SkShader::Context::ComputeMatrixClass(fDstToIndex);
rileya@google.com589708b2012-07-26 20:04:23 +0000391
392 // now convert our colors in to PMColors
393 unsigned paintAlpha = this->getPaintAlpha();
394
395 fFlags = this->INHERITED::getFlags();
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000396 if (shader.fColorsAreOpaque && paintAlpha == 0xFF) {
rileya@google.com589708b2012-07-26 20:04:23 +0000397 fFlags |= kOpaqueAlpha_Flag;
398 }
rileya@google.com589708b2012-07-26 20:04:23 +0000399}
400
fmalita088e21b2016-10-05 09:28:42 -0700401bool SkGradientShaderBase::GradientShaderBaseContext::isValid() const {
402 return fDstToIndex.isFinite();
403}
404
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000405SkGradientShaderBase::GradientShaderCache::GradientShaderCache(
fmalita37d86882015-10-09 10:22:46 -0700406 U8CPU alpha, bool dither, const SkGradientShaderBase& shader)
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000407 : fCacheAlpha(alpha)
fmalita37d86882015-10-09 10:22:46 -0700408 , fCacheDither(dither)
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000409 , fShader(shader)
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000410{
brianosman93110a82016-09-15 08:40:21 -0700411 // Only initialize the cache in getCache32.
halcanary96fcdcc2015-08-27 07:41:13 -0700412 fCache32 = nullptr;
halcanary96fcdcc2015-08-27 07:41:13 -0700413 fCache32PixelRef = nullptr;
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000414}
415
416SkGradientShaderBase::GradientShaderCache::~GradientShaderCache() {
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000417 SkSafeUnref(fCache32PixelRef);
rileya@google.com589708b2012-07-26 20:04:23 +0000418}
419
reed@google.com3d3a8602013-05-24 14:58:44 +0000420/*
421 * r,g,b used to be SkFixed, but on gcc (4.2.1 mac and 4.6.3 goobuntu) in
422 * release builds, we saw a compiler error where the 0xFF parameter in
423 * SkPackARGB32() was being totally ignored whenever it was called with
424 * a non-zero add (e.g. 0x8000).
425 *
426 * We found two work-arounds:
427 * 1. change r,g,b to unsigned (or just one of them)
428 * 2. change SkPackARGB32 to + its (a << SK_A32_SHIFT) value instead
429 * of using |
430 *
431 * We chose #1 just because it was more localized.
432 * See http://code.google.com/p/skia/issues/detail?id=1113
433 *
434 * The type SkUFixed encapsulate this need for unsigned, but logically Fixed.
435 */
436typedef uint32_t SkUFixed;
437
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000438void SkGradientShaderBase::GradientShaderCache::Build32bitCache(
439 SkPMColor cache[], SkColor c0, SkColor c1,
fmalita37d86882015-10-09 10:22:46 -0700440 int count, U8CPU paintAlpha, uint32_t gradFlags, bool dither) {
rileya@google.com589708b2012-07-26 20:04:23 +0000441 SkASSERT(count > 1);
442
443 // need to apply paintAlpha to our two endpoints
reed@google.com3d3a8602013-05-24 14:58:44 +0000444 uint32_t a0 = SkMulDiv255Round(SkColorGetA(c0), paintAlpha);
445 uint32_t a1 = SkMulDiv255Round(SkColorGetA(c1), paintAlpha);
446
447
448 const bool interpInPremul = SkToBool(gradFlags &
449 SkGradientShader::kInterpolateColorsInPremul_Flag);
450
451 uint32_t r0 = SkColorGetR(c0);
452 uint32_t g0 = SkColorGetG(c0);
453 uint32_t b0 = SkColorGetB(c0);
454
455 uint32_t r1 = SkColorGetR(c1);
456 uint32_t g1 = SkColorGetG(c1);
457 uint32_t b1 = SkColorGetB(c1);
458
459 if (interpInPremul) {
460 r0 = SkMulDiv255Round(r0, a0);
461 g0 = SkMulDiv255Round(g0, a0);
462 b0 = SkMulDiv255Round(b0, a0);
463
464 r1 = SkMulDiv255Round(r1, a1);
465 g1 = SkMulDiv255Round(g1, a1);
466 b1 = SkMulDiv255Round(b1, a1);
rileya@google.com589708b2012-07-26 20:04:23 +0000467 }
468
reed@google.com3d3a8602013-05-24 14:58:44 +0000469 SkFixed da = SkIntToFixed(a1 - a0) / (count - 1);
470 SkFixed dr = SkIntToFixed(r1 - r0) / (count - 1);
471 SkFixed dg = SkIntToFixed(g1 - g0) / (count - 1);
472 SkFixed db = SkIntToFixed(b1 - b0) / (count - 1);
rileya@google.com589708b2012-07-26 20:04:23 +0000473
reed@google.comd8e0d6a2013-02-08 19:48:12 +0000474 /* We pre-add 1/8 to avoid having to add this to our [0] value each time
475 in the loop. Without this, the bias for each would be
476 0x2000 0xA000 0xE000 0x6000
477 With this trick, we can add 0 for the first (no-op) and just adjust the
478 others.
479 */
fmalita37d86882015-10-09 10:22:46 -0700480 const SkUFixed bias0 = dither ? 0x2000 : 0x8000;
481 const SkUFixed bias1 = dither ? 0x8000 : 0;
482 const SkUFixed bias2 = dither ? 0xC000 : 0;
483 const SkUFixed bias3 = dither ? 0x4000 : 0;
484
485 SkUFixed a = SkIntToFixed(a0) + bias0;
486 SkUFixed r = SkIntToFixed(r0) + bias0;
487 SkUFixed g = SkIntToFixed(g0) + bias0;
488 SkUFixed b = SkIntToFixed(b0) + bias0;
rileya@google.com589708b2012-07-26 20:04:23 +0000489
reed@google.comd8e0d6a2013-02-08 19:48:12 +0000490 /*
491 * Our dither-cell (spatially) is
492 * 0 2
493 * 3 1
494 * Where
495 * [0] -> [-1/8 ... 1/8 ) values near 0
496 * [1] -> [ 1/8 ... 3/8 ) values near 1/4
497 * [2] -> [ 3/8 ... 5/8 ) values near 1/2
498 * [3] -> [ 5/8 ... 7/8 ) values near 3/4
499 */
500
reed@google.com3d3a8602013-05-24 14:58:44 +0000501 if (0xFF == a0 && 0 == da) {
reed@google.comd8e0d6a2013-02-08 19:48:12 +0000502 do {
fmalita37d86882015-10-09 10:22:46 -0700503 cache[kCache32Count*0] = SkPackARGB32(0xFF, (r + 0 ) >> 16,
504 (g + 0 ) >> 16,
505 (b + 0 ) >> 16);
506 cache[kCache32Count*1] = SkPackARGB32(0xFF, (r + bias1) >> 16,
507 (g + bias1) >> 16,
508 (b + bias1) >> 16);
509 cache[kCache32Count*2] = SkPackARGB32(0xFF, (r + bias2) >> 16,
510 (g + bias2) >> 16,
511 (b + bias2) >> 16);
512 cache[kCache32Count*3] = SkPackARGB32(0xFF, (r + bias3) >> 16,
513 (g + bias3) >> 16,
514 (b + bias3) >> 16);
reed@google.comd8e0d6a2013-02-08 19:48:12 +0000515 cache += 1;
516 r += dr;
517 g += dg;
518 b += db;
519 } while (--count != 0);
reed@google.com3d3a8602013-05-24 14:58:44 +0000520 } else if (interpInPremul) {
521 do {
fmalita37d86882015-10-09 10:22:46 -0700522 cache[kCache32Count*0] = SkPackARGB32((a + 0 ) >> 16,
523 (r + 0 ) >> 16,
524 (g + 0 ) >> 16,
525 (b + 0 ) >> 16);
526 cache[kCache32Count*1] = SkPackARGB32((a + bias1) >> 16,
527 (r + bias1) >> 16,
528 (g + bias1) >> 16,
529 (b + bias1) >> 16);
530 cache[kCache32Count*2] = SkPackARGB32((a + bias2) >> 16,
531 (r + bias2) >> 16,
532 (g + bias2) >> 16,
533 (b + bias2) >> 16);
534 cache[kCache32Count*3] = SkPackARGB32((a + bias3) >> 16,
535 (r + bias3) >> 16,
536 (g + bias3) >> 16,
537 (b + bias3) >> 16);
reed@google.com3d3a8602013-05-24 14:58:44 +0000538 cache += 1;
539 a += da;
540 r += dr;
541 g += dg;
542 b += db;
543 } while (--count != 0);
544 } else { // interpolate in unpreml space
reed@google.comd8e0d6a2013-02-08 19:48:12 +0000545 do {
546 cache[kCache32Count*0] = SkPremultiplyARGBInline((a + 0 ) >> 16,
547 (r + 0 ) >> 16,
548 (g + 0 ) >> 16,
549 (b + 0 ) >> 16);
fmalita37d86882015-10-09 10:22:46 -0700550 cache[kCache32Count*1] = SkPremultiplyARGBInline((a + bias1) >> 16,
551 (r + bias1) >> 16,
552 (g + bias1) >> 16,
553 (b + bias1) >> 16);
554 cache[kCache32Count*2] = SkPremultiplyARGBInline((a + bias2) >> 16,
555 (r + bias2) >> 16,
556 (g + bias2) >> 16,
557 (b + bias2) >> 16);
558 cache[kCache32Count*3] = SkPremultiplyARGBInline((a + bias3) >> 16,
559 (r + bias3) >> 16,
560 (g + bias3) >> 16,
561 (b + bias3) >> 16);
reed@google.comd8e0d6a2013-02-08 19:48:12 +0000562 cache += 1;
563 a += da;
564 r += dr;
565 g += dg;
566 b += db;
567 } while (--count != 0);
568 }
rileya@google.com589708b2012-07-26 20:04:23 +0000569}
570
571static inline int SkFixedToFFFF(SkFixed x) {
572 SkASSERT((unsigned)x <= SK_Fixed1);
573 return x - (x >> 16);
574}
575
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000576const SkPMColor* SkGradientShaderBase::GradientShaderCache::getCache32() {
mtkleind9dd4282016-04-18 08:09:11 -0700577 fCache32InitOnce(SkGradientShaderBase::GradientShaderCache::initCache32, this);
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000578 SkASSERT(fCache32);
rileya@google.com589708b2012-07-26 20:04:23 +0000579 return fCache32;
580}
581
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000582void SkGradientShaderBase::GradientShaderCache::initCache32(GradientShaderCache* cache) {
reede5ea5002014-09-03 11:54:58 -0700583 const int kNumberOfDitherRows = 4;
584 const SkImageInfo info = SkImageInfo::MakeN32Premul(kCache32Count, kNumberOfDitherRows);
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000585
halcanary96fcdcc2015-08-27 07:41:13 -0700586 SkASSERT(nullptr == cache->fCache32PixelRef);
587 cache->fCache32PixelRef = SkMallocPixelRef::NewAllocate(info, 0, nullptr);
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000588 cache->fCache32 = (SkPMColor*)cache->fCache32PixelRef->getAddr();
589 if (cache->fShader.fColorCount == 2) {
590 Build32bitCache(cache->fCache32, cache->fShader.fOrigColors[0],
591 cache->fShader.fOrigColors[1], kCache32Count, cache->fCacheAlpha,
fmalita37d86882015-10-09 10:22:46 -0700592 cache->fShader.fGradFlags, cache->fCacheDither);
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000593 } else {
594 Rec* rec = cache->fShader.fRecs;
595 int prevIndex = 0;
596 for (int i = 1; i < cache->fShader.fColorCount; i++) {
597 int nextIndex = SkFixedToFFFF(rec[i].fPos) >> kCache32Shift;
598 SkASSERT(nextIndex < kCache32Count);
599
600 if (nextIndex > prevIndex)
601 Build32bitCache(cache->fCache32 + prevIndex, cache->fShader.fOrigColors[i-1],
602 cache->fShader.fOrigColors[i], nextIndex - prevIndex + 1,
fmalita37d86882015-10-09 10:22:46 -0700603 cache->fCacheAlpha, cache->fShader.fGradFlags, cache->fCacheDither);
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000604 prevIndex = nextIndex;
605 }
606 }
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000607}
608
brianosmand4546092016-09-22 12:31:58 -0700609void SkGradientShaderBase::initLinearBitmap(SkBitmap* bitmap) const {
610 const bool interpInPremul = SkToBool(fGradFlags &
611 SkGradientShader::kInterpolateColorsInPremul_Flag);
612 bitmap->lockPixels();
613 SkHalf* pixelsF16 = reinterpret_cast<SkHalf*>(bitmap->getPixels());
614 uint32_t* pixelsS32 = reinterpret_cast<uint32_t*>(bitmap->getPixels());
615
616 typedef std::function<void(const Sk4f&, int)> pixelWriteFn_t;
617
618 pixelWriteFn_t writeF16Pixel = [&](const Sk4f& x, int index) {
619 Sk4h c = SkFloatToHalf_finite_ftz(x);
620 pixelsF16[4*index+0] = c[0];
621 pixelsF16[4*index+1] = c[1];
622 pixelsF16[4*index+2] = c[2];
623 pixelsF16[4*index+3] = c[3];
624 };
625 pixelWriteFn_t writeS32Pixel = [&](const Sk4f& c, int index) {
626 pixelsS32[index] = Sk4f_toS32(c);
627 };
628
629 pixelWriteFn_t writeSizedPixel =
630 (kRGBA_F16_SkColorType == bitmap->colorType()) ? writeF16Pixel : writeS32Pixel;
631 pixelWriteFn_t writeUnpremulPixel = [&](const Sk4f& c, int index) {
632 writeSizedPixel(c * Sk4f(c[3], c[3], c[3], 1.0f), index);
633 };
634
635 pixelWriteFn_t writePixel = interpInPremul ? writeSizedPixel : writeUnpremulPixel;
636
637 int prevIndex = 0;
638 for (int i = 1; i < fColorCount; i++) {
639 int nextIndex = (fColorCount == 2) ? (kCache32Count - 1)
640 : SkFixedToFFFF(fRecs[i].fPos) >> kCache32Shift;
641 SkASSERT(nextIndex < kCache32Count);
642
643 if (nextIndex > prevIndex) {
644 Sk4f c0 = Sk4f::Load(fOrigColors4f[i - 1].vec());
645 Sk4f c1 = Sk4f::Load(fOrigColors4f[i].vec());
646 if (interpInPremul) {
647 c0 = c0 * Sk4f(c0[3], c0[3], c0[3], 1.0f);
648 c1 = c1 * Sk4f(c1[3], c1[3], c1[3], 1.0f);
649 }
650
651 Sk4f step = Sk4f(1.0f / static_cast<float>(nextIndex - prevIndex));
652 Sk4f delta = (c1 - c0) * step;
653
654 for (int curIndex = prevIndex; curIndex <= nextIndex; ++curIndex) {
655 writePixel(c0, curIndex);
656 c0 += delta;
657 }
658 }
659 prevIndex = nextIndex;
660 }
661 SkASSERT(prevIndex == kCache32Count - 1);
662 bitmap->unlockPixels();
663}
664
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000665/*
666 * The gradient holds a cache for the most recent value of alpha. Successive
667 * callers with the same alpha value will share the same cache.
668 */
Hal Canary67b39de2016-11-07 11:47:44 -0500669sk_sp<SkGradientShaderBase::GradientShaderCache> SkGradientShaderBase::refCache(U8CPU alpha,
fmalita37d86882015-10-09 10:22:46 -0700670 bool dither) const {
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000671 SkAutoMutexAcquire ama(fCacheMutex);
fmalita37d86882015-10-09 10:22:46 -0700672 if (!fCache || fCache->getAlpha() != alpha || fCache->getDither() != dither) {
673 fCache.reset(new GradientShaderCache(alpha, dither, *this));
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000674 }
675 // Increment the ref counter inside the mutex to ensure the returned pointer is still valid.
676 // Otherwise, the pointer may have been overwritten on a different thread before the object's
677 // ref count was incremented.
commit-bot@chromium.org87fcd952014-04-23 19:10:51 +0000678 return fCache;
679}
680
reed086eea92016-05-04 17:12:46 -0700681SK_DECLARE_STATIC_MUTEX(gGradientCacheMutex);
rileya@google.com589708b2012-07-26 20:04:23 +0000682/*
683 * Because our caller might rebuild the same (logically the same) gradient
684 * over and over, we'd like to return exactly the same "bitmap" if possible,
685 * allowing the client to utilize a cache of our bitmap (e.g. with a GPU).
686 * To do that, we maintain a private cache of built-bitmaps, based on our
687 * colors and positions. Note: we don't try to flatten the fMapper, so if one
688 * is present, we skip the cache for now.
689 */
brianosmand4546092016-09-22 12:31:58 -0700690void SkGradientShaderBase::getGradientTableBitmap(SkBitmap* bitmap,
691 GradientBitmapType bitmapType) const {
692 // our caller assumes no external alpha, so we ensure that our cache is built with 0xFF
Hal Canary67b39de2016-11-07 11:47:44 -0500693 sk_sp<GradientShaderCache> cache(this->refCache(0xFF, true));
rileya@google.com589708b2012-07-26 20:04:23 +0000694
brianosmand4546092016-09-22 12:31:58 -0700695 // build our key: [numColors + colors[] + {positions[]} + flags + colorType ]
696 int count = 1 + fColorCount + 1 + 1;
rileya@google.com589708b2012-07-26 20:04:23 +0000697 if (fColorCount > 2) {
698 count += fColorCount - 1; // fRecs[].fPos
699 }
700
701 SkAutoSTMalloc<16, int32_t> storage(count);
702 int32_t* buffer = storage.get();
703
704 *buffer++ = fColorCount;
705 memcpy(buffer, fOrigColors, fColorCount * sizeof(SkColor));
706 buffer += fColorCount;
707 if (fColorCount > 2) {
708 for (int i = 1; i < fColorCount; i++) {
709 *buffer++ = fRecs[i].fPos;
710 }
711 }
reed@google.com3d3a8602013-05-24 14:58:44 +0000712 *buffer++ = fGradFlags;
brianosmand4546092016-09-22 12:31:58 -0700713 *buffer++ = static_cast<int32_t>(bitmapType);
rileya@google.com589708b2012-07-26 20:04:23 +0000714 SkASSERT(buffer - storage.get() == count);
715
716 ///////////////////////////////////
717
reeda6cac4c2014-08-21 10:50:25 -0700718 static SkGradientBitmapCache* gCache;
brianosmand4546092016-09-22 12:31:58 -0700719 // 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 +0000720 static const int MAX_NUM_CACHED_GRADIENT_BITMAPS = 32;
bungemand6aeb6d2014-07-25 11:52:47 -0700721 SkAutoMutexAcquire ama(gGradientCacheMutex);
rileya@google.com589708b2012-07-26 20:04:23 +0000722
halcanary96fcdcc2015-08-27 07:41:13 -0700723 if (nullptr == gCache) {
halcanary385fe4d2015-08-26 13:07:48 -0700724 gCache = new SkGradientBitmapCache(MAX_NUM_CACHED_GRADIENT_BITMAPS);
rileya@google.com589708b2012-07-26 20:04:23 +0000725 }
726 size_t size = count * sizeof(int32_t);
727
728 if (!gCache->find(storage.get(), size, bitmap)) {
brianosmand4546092016-09-22 12:31:58 -0700729 if (GradientBitmapType::kLegacy == bitmapType) {
730 // force our cache32pixelref to be built
731 (void)cache->getCache32();
732 bitmap->setInfo(SkImageInfo::MakeN32Premul(kCache32Count, 1));
Hal Canary1b3387b2016-12-12 13:48:12 -0500733 bitmap->setPixelRef(sk_ref_sp(cache->getCache32PixelRef()), 0, 0);
brianosmand4546092016-09-22 12:31:58 -0700734 } else {
735 // For these cases we use the bitmap cache, but not the GradientShaderCache. So just
736 // allocate and populate the bitmap's data directly.
rileya@google.com589708b2012-07-26 20:04:23 +0000737
brianosmand4546092016-09-22 12:31:58 -0700738 SkImageInfo info;
739 switch (bitmapType) {
740 case GradientBitmapType::kSRGB:
741 info = SkImageInfo::Make(kCache32Count, 1, kRGBA_8888_SkColorType,
742 kPremul_SkAlphaType,
Matt Sarett77a7a1b2017-02-07 13:56:11 -0500743 SkColorSpace::MakeSRGB());
brianosmand4546092016-09-22 12:31:58 -0700744 break;
745 case GradientBitmapType::kHalfFloat:
brianosmaneec83042016-09-27 15:11:47 -0700746 info = SkImageInfo::Make(
747 kCache32Count, 1, kRGBA_F16_SkColorType, kPremul_SkAlphaType,
Matt Sarett77a7a1b2017-02-07 13:56:11 -0500748 SkColorSpace::MakeSRGBLinear());
brianosmand4546092016-09-22 12:31:58 -0700749 break;
750 default:
751 SkFAIL("Unexpected bitmap type");
752 return;
753 }
754 bitmap->allocPixels(info);
755 this->initLinearBitmap(bitmap);
756 }
rileya@google.com589708b2012-07-26 20:04:23 +0000757 gCache->add(storage.get(), size, *bitmap);
758 }
759}
760
commit-bot@chromium.org44d83c12014-04-21 13:10:25 +0000761void SkGradientShaderBase::commonAsAGradient(GradientInfo* info, bool flipGrad) const {
rileya@google.com589708b2012-07-26 20:04:23 +0000762 if (info) {
763 if (info->fColorCount >= fColorCount) {
commit-bot@chromium.org44d83c12014-04-21 13:10:25 +0000764 SkColor* colorLoc;
765 Rec* recLoc;
Hal Canaryab8e02a2017-02-27 09:59:39 -0500766 SkAutoSTArray<8, SkColor> colorStorage;
767 SkAutoSTArray<8, Rec> recStorage;
commit-bot@chromium.org44d83c12014-04-21 13:10:25 +0000768 if (flipGrad && (info->fColors || info->fColorOffsets)) {
Hal Canaryab8e02a2017-02-27 09:59:39 -0500769 colorStorage.reset(fColorCount);
770 recStorage.reset(fColorCount);
commit-bot@chromium.org44d83c12014-04-21 13:10:25 +0000771 colorLoc = colorStorage.get();
772 recLoc = recStorage.get();
773 FlipGradientColors(colorLoc, recLoc, fOrigColors, fRecs, fColorCount);
774 } else {
775 colorLoc = fOrigColors;
776 recLoc = fRecs;
777 }
rileya@google.com589708b2012-07-26 20:04:23 +0000778 if (info->fColors) {
commit-bot@chromium.org44d83c12014-04-21 13:10:25 +0000779 memcpy(info->fColors, colorLoc, fColorCount * sizeof(SkColor));
rileya@google.com589708b2012-07-26 20:04:23 +0000780 }
781 if (info->fColorOffsets) {
782 if (fColorCount == 2) {
783 info->fColorOffsets[0] = 0;
784 info->fColorOffsets[1] = SK_Scalar1;
785 } else if (fColorCount > 2) {
robertphillips@google.com76f9e932013-01-15 20:17:47 +0000786 for (int i = 0; i < fColorCount; ++i) {
commit-bot@chromium.org44d83c12014-04-21 13:10:25 +0000787 info->fColorOffsets[i] = SkFixedToScalar(recLoc[i].fPos);
robertphillips@google.com76f9e932013-01-15 20:17:47 +0000788 }
rileya@google.com589708b2012-07-26 20:04:23 +0000789 }
790 }
791 }
792 info->fColorCount = fColorCount;
793 info->fTileMode = fTileMode;
reed@google.com3d3a8602013-05-24 14:58:44 +0000794 info->fGradientFlags = fGradFlags;
rileya@google.com589708b2012-07-26 20:04:23 +0000795 }
796}
797
commit-bot@chromium.org0f10f7b2014-03-13 18:02:17 +0000798#ifndef SK_IGNORE_TO_STRING
robertphillips@google.com76f9e932013-01-15 20:17:47 +0000799void SkGradientShaderBase::toString(SkString* str) const {
800
801 str->appendf("%d colors: ", fColorCount);
802
803 for (int i = 0; i < fColorCount; ++i) {
robertphillipsf3f5bad2014-12-19 13:49:15 -0800804 str->appendHex(fOrigColors[i], 8);
robertphillips@google.com76f9e932013-01-15 20:17:47 +0000805 if (i < fColorCount-1) {
806 str->append(", ");
807 }
808 }
809
810 if (fColorCount > 2) {
811 str->append(" points: (");
812 for (int i = 0; i < fColorCount; ++i) {
813 str->appendScalar(SkFixedToScalar(fRecs[i].fPos));
814 if (i < fColorCount-1) {
815 str->append(", ");
816 }
817 }
818 str->append(")");
819 }
820
821 static const char* gTileModeName[SkShader::kTileModeCount] = {
822 "clamp", "repeat", "mirror"
823 };
824
825 str->append(" ");
826 str->append(gTileModeName[fTileMode]);
827
robertphillips@google.com76f9e932013-01-15 20:17:47 +0000828 this->INHERITED::toString(str);
829}
830#endif
831
rileya@google.com589708b2012-07-26 20:04:23 +0000832///////////////////////////////////////////////////////////////////////////////
833///////////////////////////////////////////////////////////////////////////////
834
reed1b747302015-01-06 07:13:19 -0800835// Return true if these parameters are valid/legal/safe to construct a gradient
836//
brianosmane25d71c2016-09-28 11:27:28 -0700837static bool valid_grad(const SkColor4f colors[], const SkScalar pos[], int count,
838 unsigned tileMode) {
halcanary96fcdcc2015-08-27 07:41:13 -0700839 return nullptr != colors && count >= 1 && tileMode < (unsigned)SkShader::kTileModeCount;
reed1b747302015-01-06 07:13:19 -0800840}
841
reed@google.com437d6eb2013-05-23 19:03:05 +0000842static void desc_init(SkGradientShaderBase::Descriptor* desc,
brianosmane25d71c2016-09-28 11:27:28 -0700843 const SkColor4f colors[], sk_sp<SkColorSpace> colorSpace,
844 const SkScalar pos[], int colorCount,
reedaddf2ed2014-08-11 08:28:24 -0700845 SkShader::TileMode mode, uint32_t flags, const SkMatrix* localMatrix) {
fmalita748d6202016-05-11 11:39:58 -0700846 SkASSERT(colorCount > 1);
847
commit-bot@chromium.org6c5aea22014-04-22 16:25:15 +0000848 desc->fColors = colors;
brianosmane25d71c2016-09-28 11:27:28 -0700849 desc->fColorSpace = std::move(colorSpace);
commit-bot@chromium.org6c5aea22014-04-22 16:25:15 +0000850 desc->fPos = pos;
851 desc->fCount = colorCount;
852 desc->fTileMode = mode;
commit-bot@chromium.org6c5aea22014-04-22 16:25:15 +0000853 desc->fGradFlags = flags;
reedaddf2ed2014-08-11 08:28:24 -0700854 desc->fLocalMatrix = localMatrix;
reed@google.com437d6eb2013-05-23 19:03:05 +0000855}
856
brianosmane25d71c2016-09-28 11:27:28 -0700857// assumes colors is SkColor4f* and pos is SkScalar*
fmenozzie9fd0f82016-08-19 07:50:57 -0700858#define EXPAND_1_COLOR(count) \
brianosmane25d71c2016-09-28 11:27:28 -0700859 SkColor4f tmp[2]; \
fmenozzie9fd0f82016-08-19 07:50:57 -0700860 do { \
861 if (1 == count) { \
862 tmp[0] = tmp[1] = colors[0]; \
863 colors = tmp; \
864 pos = nullptr; \
865 count = 2; \
866 } \
867 } while (0)
868
fmenozzi68d952c2016-08-19 08:56:56 -0700869struct ColorStopOptimizer {
brianosmane25d71c2016-09-28 11:27:28 -0700870 ColorStopOptimizer(const SkColor4f* colors, const SkScalar* pos,
fmenozzi68d952c2016-08-19 08:56:56 -0700871 int count, SkShader::TileMode mode)
872 : fColors(colors)
873 , fPos(pos)
874 , fCount(count) {
875
876 if (!pos || count != 3) {
877 return;
878 }
879
880 if (SkScalarNearlyEqual(pos[0], 0.0f) &&
881 SkScalarNearlyEqual(pos[1], 0.0f) &&
882 SkScalarNearlyEqual(pos[2], 1.0f)) {
883
884 if (SkShader::kRepeat_TileMode == mode ||
885 SkShader::kMirror_TileMode == mode ||
886 colors[0] == colors[1]) {
887
fmalita582a6562016-08-22 06:28:57 -0700888 // Ignore the leftmost color/pos.
889 fColors += 1;
890 fPos += 1;
891 fCount = 2;
fmenozzi68d952c2016-08-19 08:56:56 -0700892 }
893 } else if (SkScalarNearlyEqual(pos[0], 0.0f) &&
894 SkScalarNearlyEqual(pos[1], 1.0f) &&
895 SkScalarNearlyEqual(pos[2], 1.0f)) {
896
897 if (SkShader::kRepeat_TileMode == mode ||
898 SkShader::kMirror_TileMode == mode ||
899 colors[1] == colors[2]) {
900
fmalita582a6562016-08-22 06:28:57 -0700901 // Ignore the rightmost color/pos.
fmenozzi68d952c2016-08-19 08:56:56 -0700902 fCount = 2;
903 }
904 }
905 }
906
brianosmane25d71c2016-09-28 11:27:28 -0700907 const SkColor4f* fColors;
908 const SkScalar* fPos;
909 int fCount;
910};
911
912struct ColorConverter {
913 ColorConverter(const SkColor* colors, int count) {
914 for (int i = 0; i < count; ++i) {
915 fColors4f.push_back(SkColor4f::FromColor(colors[i]));
916 }
917 }
918
919 SkSTArray<2, SkColor4f, true> fColors4f;
fmenozzi68d952c2016-08-19 08:56:56 -0700920};
921
reed8a21c9f2016-03-08 18:50:00 -0800922sk_sp<SkShader> SkGradientShader::MakeLinear(const SkPoint pts[2],
fmenozzi68d952c2016-08-19 08:56:56 -0700923 const SkColor colors[],
924 const SkScalar pos[], int colorCount,
925 SkShader::TileMode mode,
926 uint32_t flags,
927 const SkMatrix* localMatrix) {
brianosmane25d71c2016-09-28 11:27:28 -0700928 ColorConverter converter(colors, colorCount);
929 return MakeLinear(pts, converter.fColors4f.begin(), nullptr, pos, colorCount, mode, flags,
930 localMatrix);
931}
932
933sk_sp<SkShader> SkGradientShader::MakeLinear(const SkPoint pts[2],
934 const SkColor4f colors[],
935 sk_sp<SkColorSpace> colorSpace,
936 const SkScalar pos[], int colorCount,
937 SkShader::TileMode mode,
938 uint32_t flags,
939 const SkMatrix* localMatrix) {
fmalitac5231042016-08-10 05:45:50 -0700940 if (!pts || !SkScalarIsFinite((pts[1] - pts[0]).length())) {
halcanary96fcdcc2015-08-27 07:41:13 -0700941 return nullptr;
reed1b747302015-01-06 07:13:19 -0800942 }
943 if (!valid_grad(colors, pos, colorCount, mode)) {
halcanary96fcdcc2015-08-27 07:41:13 -0700944 return nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +0000945 }
fmenozzie9fd0f82016-08-19 07:50:57 -0700946 if (1 == colorCount) {
brianosmane25d71c2016-09-28 11:27:28 -0700947 return SkShader::MakeColorShader(colors[0], std::move(colorSpace));
fmenozzie9fd0f82016-08-19 07:50:57 -0700948 }
Florin Malita8d3ffad2017-02-03 18:21:17 +0000949 if (localMatrix && !localMatrix->invert(nullptr)) {
950 return nullptr;
951 }
rileya@google.com589708b2012-07-26 20:04:23 +0000952
fmenozzi68d952c2016-08-19 08:56:56 -0700953 ColorStopOptimizer opt(colors, pos, colorCount, mode);
954
reed@google.com437d6eb2013-05-23 19:03:05 +0000955 SkGradientShaderBase::Descriptor desc;
brianosmane25d71c2016-09-28 11:27:28 -0700956 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
957 localMatrix);
reed8a21c9f2016-03-08 18:50:00 -0800958 return sk_make_sp<SkLinearGradient>(pts, desc);
rileya@google.com589708b2012-07-26 20:04:23 +0000959}
960
reed8a21c9f2016-03-08 18:50:00 -0800961sk_sp<SkShader> SkGradientShader::MakeRadial(const SkPoint& center, SkScalar radius,
brianosmane25d71c2016-09-28 11:27:28 -0700962 const SkColor colors[],
963 const SkScalar pos[], int colorCount,
964 SkShader::TileMode mode,
965 uint32_t flags,
966 const SkMatrix* localMatrix) {
967 ColorConverter converter(colors, colorCount);
968 return MakeRadial(center, radius, converter.fColors4f.begin(), nullptr, pos, colorCount, mode,
969 flags, localMatrix);
970}
971
972sk_sp<SkShader> SkGradientShader::MakeRadial(const SkPoint& center, SkScalar radius,
973 const SkColor4f colors[],
974 sk_sp<SkColorSpace> colorSpace,
975 const SkScalar pos[], int colorCount,
976 SkShader::TileMode mode,
977 uint32_t flags,
978 const SkMatrix* localMatrix) {
reed1b747302015-01-06 07:13:19 -0800979 if (radius <= 0) {
halcanary96fcdcc2015-08-27 07:41:13 -0700980 return nullptr;
reed1b747302015-01-06 07:13:19 -0800981 }
982 if (!valid_grad(colors, pos, colorCount, mode)) {
halcanary96fcdcc2015-08-27 07:41:13 -0700983 return nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +0000984 }
fmenozzie9fd0f82016-08-19 07:50:57 -0700985 if (1 == colorCount) {
brianosmane25d71c2016-09-28 11:27:28 -0700986 return SkShader::MakeColorShader(colors[0], std::move(colorSpace));
fmenozzie9fd0f82016-08-19 07:50:57 -0700987 }
Florin Malita8d3ffad2017-02-03 18:21:17 +0000988 if (localMatrix && !localMatrix->invert(nullptr)) {
989 return nullptr;
990 }
rileya@google.com589708b2012-07-26 20:04:23 +0000991
fmenozzi68d952c2016-08-19 08:56:56 -0700992 ColorStopOptimizer opt(colors, pos, colorCount, mode);
993
reed@google.com437d6eb2013-05-23 19:03:05 +0000994 SkGradientShaderBase::Descriptor desc;
brianosmane25d71c2016-09-28 11:27:28 -0700995 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
996 localMatrix);
reed8a21c9f2016-03-08 18:50:00 -0800997 return sk_make_sp<SkRadialGradient>(center, radius, desc);
rileya@google.com589708b2012-07-26 20:04:23 +0000998}
999
reed8a21c9f2016-03-08 18:50:00 -08001000sk_sp<SkShader> SkGradientShader::MakeTwoPointConical(const SkPoint& start,
brianosmane25d71c2016-09-28 11:27:28 -07001001 SkScalar startRadius,
1002 const SkPoint& end,
1003 SkScalar endRadius,
1004 const SkColor colors[],
1005 const SkScalar pos[],
1006 int colorCount,
1007 SkShader::TileMode mode,
1008 uint32_t flags,
1009 const SkMatrix* localMatrix) {
1010 ColorConverter converter(colors, colorCount);
1011 return MakeTwoPointConical(start, startRadius, end, endRadius, converter.fColors4f.begin(),
1012 nullptr, pos, colorCount, mode, flags, localMatrix);
1013}
1014
1015sk_sp<SkShader> SkGradientShader::MakeTwoPointConical(const SkPoint& start,
1016 SkScalar startRadius,
1017 const SkPoint& end,
1018 SkScalar endRadius,
1019 const SkColor4f colors[],
1020 sk_sp<SkColorSpace> colorSpace,
1021 const SkScalar pos[],
1022 int colorCount,
1023 SkShader::TileMode mode,
1024 uint32_t flags,
1025 const SkMatrix* localMatrix) {
reed1b747302015-01-06 07:13:19 -08001026 if (startRadius < 0 || endRadius < 0) {
halcanary96fcdcc2015-08-27 07:41:13 -07001027 return nullptr;
reed1b747302015-01-06 07:13:19 -08001028 }
1029 if (!valid_grad(colors, pos, colorCount, mode)) {
halcanary96fcdcc2015-08-27 07:41:13 -07001030 return nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +00001031 }
fmalita5edf82e2016-03-03 06:41:54 -08001032 if (startRadius == endRadius) {
1033 if (start == end || startRadius == 0) {
reed8a21c9f2016-03-08 18:50:00 -08001034 return SkShader::MakeEmptyShader();
fmalita5edf82e2016-03-03 06:41:54 -08001035 }
rileya@google.com589708b2012-07-26 20:04:23 +00001036 }
Florin Malita8d3ffad2017-02-03 18:21:17 +00001037 if (localMatrix && !localMatrix->invert(nullptr)) {
1038 return nullptr;
1039 }
reed6b7a6c72016-08-18 16:13:50 -07001040 EXPAND_1_COLOR(colorCount);
rileya@google.com589708b2012-07-26 20:04:23 +00001041
fmenozzi68d952c2016-08-19 08:56:56 -07001042 ColorStopOptimizer opt(colors, pos, colorCount, mode);
1043
commit-bot@chromium.org44d83c12014-04-21 13:10:25 +00001044 bool flipGradient = startRadius > endRadius;
1045
reed@google.com437d6eb2013-05-23 19:03:05 +00001046 SkGradientShaderBase::Descriptor desc;
commit-bot@chromium.org44d83c12014-04-21 13:10:25 +00001047
1048 if (!flipGradient) {
brianosmane25d71c2016-09-28 11:27:28 -07001049 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
1050 localMatrix);
reed8a21c9f2016-03-08 18:50:00 -08001051 return sk_make_sp<SkTwoPointConicalGradient>(start, startRadius, end, endRadius,
1052 flipGradient, desc);
commit-bot@chromium.org44d83c12014-04-21 13:10:25 +00001053 } else {
brianosmane25d71c2016-09-28 11:27:28 -07001054 SkAutoSTArray<8, SkColor4f> colorsNew(opt.fCount);
tomhudson54d9b662016-09-16 14:22:49 -07001055 SkAutoSTArray<8, SkScalar> posNew(opt.fCount);
1056 for (int i = 0; i < opt.fCount; ++i) {
1057 colorsNew[i] = opt.fColors[opt.fCount - i - 1];
commit-bot@chromium.org44d83c12014-04-21 13:10:25 +00001058 }
1059
1060 if (pos) {
tomhudson54d9b662016-09-16 14:22:49 -07001061 for (int i = 0; i < opt.fCount; ++i) {
1062 posNew[i] = 1 - opt.fPos[opt.fCount - i - 1];
commit-bot@chromium.org44d83c12014-04-21 13:10:25 +00001063 }
brianosmane25d71c2016-09-28 11:27:28 -07001064 desc_init(&desc, colorsNew.get(), std::move(colorSpace), posNew.get(), opt.fCount, mode,
1065 flags, localMatrix);
commit-bot@chromium.org44d83c12014-04-21 13:10:25 +00001066 } else {
brianosmane25d71c2016-09-28 11:27:28 -07001067 desc_init(&desc, colorsNew.get(), std::move(colorSpace), nullptr, opt.fCount, mode,
1068 flags, localMatrix);
commit-bot@chromium.org44d83c12014-04-21 13:10:25 +00001069 }
1070
reed8a21c9f2016-03-08 18:50:00 -08001071 return sk_make_sp<SkTwoPointConicalGradient>(end, endRadius, start, startRadius,
1072 flipGradient, desc);
commit-bot@chromium.org44d83c12014-04-21 13:10:25 +00001073 }
rileya@google.com589708b2012-07-26 20:04:23 +00001074}
1075
reed8a21c9f2016-03-08 18:50:00 -08001076sk_sp<SkShader> SkGradientShader::MakeSweep(SkScalar cx, SkScalar cy,
brianosmane25d71c2016-09-28 11:27:28 -07001077 const SkColor colors[],
1078 const SkScalar pos[],
1079 int colorCount,
1080 uint32_t flags,
1081 const SkMatrix* localMatrix) {
1082 ColorConverter converter(colors, colorCount);
1083 return MakeSweep(cx, cy, converter.fColors4f.begin(), nullptr, pos, colorCount, flags,
1084 localMatrix);
1085}
1086
1087sk_sp<SkShader> SkGradientShader::MakeSweep(SkScalar cx, SkScalar cy,
1088 const SkColor4f colors[],
1089 sk_sp<SkColorSpace> colorSpace,
1090 const SkScalar pos[],
1091 int colorCount,
1092 uint32_t flags,
1093 const SkMatrix* localMatrix) {
reed1b747302015-01-06 07:13:19 -08001094 if (!valid_grad(colors, pos, colorCount, SkShader::kClamp_TileMode)) {
halcanary96fcdcc2015-08-27 07:41:13 -07001095 return nullptr;
rileya@google.com589708b2012-07-26 20:04:23 +00001096 }
fmenozzie9fd0f82016-08-19 07:50:57 -07001097 if (1 == colorCount) {
brianosmane25d71c2016-09-28 11:27:28 -07001098 return SkShader::MakeColorShader(colors[0], std::move(colorSpace));
fmenozzie9fd0f82016-08-19 07:50:57 -07001099 }
Florin Malita8d3ffad2017-02-03 18:21:17 +00001100 if (localMatrix && !localMatrix->invert(nullptr)) {
1101 return nullptr;
1102 }
rileya@google.com589708b2012-07-26 20:04:23 +00001103
fmenozzi68d952c2016-08-19 08:56:56 -07001104 auto mode = SkShader::kClamp_TileMode;
1105
1106 ColorStopOptimizer opt(colors, pos, colorCount, mode);
1107
reed@google.com437d6eb2013-05-23 19:03:05 +00001108 SkGradientShaderBase::Descriptor desc;
brianosmane25d71c2016-09-28 11:27:28 -07001109 desc_init(&desc, opt.fColors, std::move(colorSpace), opt.fPos, opt.fCount, mode, flags,
1110 localMatrix);
reed8a21c9f2016-03-08 18:50:00 -08001111 return sk_make_sp<SkSweepGradient>(cx, cy, desc);
rileya@google.com589708b2012-07-26 20:04:23 +00001112}
1113
1114SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_START(SkGradientShader)
1115 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkLinearGradient)
1116 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkRadialGradient)
1117 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkSweepGradient)
rileya@google.com589708b2012-07-26 20:04:23 +00001118 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkTwoPointConicalGradient)
1119SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_END
rileya@google.comd7cc6512012-07-27 14:00:39 +00001120
1121///////////////////////////////////////////////////////////////////////////////
1122
bsalomon@google.comcf8fb1f2012-08-02 14:03:32 +00001123#if SK_SUPPORT_GPU
1124
brianosmana6359362016-03-21 06:55:37 -07001125#include "GrContext.h"
Brian Salomon94efbf52016-11-29 13:43:05 -05001126#include "GrShaderCaps.h"
ajuma95243eb2016-08-24 08:19:02 -07001127#include "GrTextureStripAtlas.h"
egdanielf5294392015-10-21 07:14:17 -07001128#include "gl/GrGLContext.h"
brianosmand4546092016-09-22 12:31:58 -07001129#include "glsl/GrGLSLColorSpaceXformHelper.h"
egdaniel2d721d32015-11-11 13:06:05 -08001130#include "glsl/GrGLSLFragmentShaderBuilder.h"
egdaniel018fb622015-10-28 07:26:40 -07001131#include "glsl/GrGLSLProgramDataManager.h"
egdaniel7ea439b2015-12-03 09:20:44 -08001132#include "glsl/GrGLSLUniformHandler.h"
bsalomon@google.comcf8fb1f2012-08-02 14:03:32 +00001133#include "SkGr.h"
1134
fmenozzicd9a1d02016-08-15 07:03:47 -07001135static inline bool close_to_one_half(const SkFixed& val) {
1136 return SkScalarNearlyEqual(SkFixedToScalar(val), SK_ScalarHalf);
1137}
1138
1139static inline int color_type_to_color_count(GrGradientEffect::ColorType colorType) {
1140 switch (colorType) {
1141#if GR_GL_USE_ACCURATE_HARD_STOP_GRADIENTS
Brian Salomon466ad992016-10-13 16:08:36 -04001142 case GrGradientEffect::kSingleHardStop_ColorType:
fmenozzicd9a1d02016-08-15 07:03:47 -07001143 return 4;
1144 case GrGradientEffect::kHardStopLeftEdged_ColorType:
1145 case GrGradientEffect::kHardStopRightEdged_ColorType:
1146 return 3;
1147#endif
1148 case GrGradientEffect::kTwo_ColorType:
1149 return 2;
1150 case GrGradientEffect::kThree_ColorType:
1151 return 3;
1152 case GrGradientEffect::kTexture_ColorType:
1153 return 0;
1154 }
1155
1156 SkDEBUGFAIL("Unhandled ColorType in color_type_to_color_count()");
1157 return -1;
1158}
1159
1160GrGradientEffect::ColorType GrGradientEffect::determineColorType(
1161 const SkGradientShaderBase& shader) {
1162#if GR_GL_USE_ACCURATE_HARD_STOP_GRADIENTS
1163 if (shader.fOrigPos) {
1164 if (4 == shader.fColorCount) {
1165 if (SkScalarNearlyEqual(shader.fOrigPos[0], 0.0f) &&
Brian Salomon466ad992016-10-13 16:08:36 -04001166 SkScalarNearlyEqual(shader.fOrigPos[1], shader.fOrigPos[2]) &&
fmenozzicd9a1d02016-08-15 07:03:47 -07001167 SkScalarNearlyEqual(shader.fOrigPos[3], 1.0f)) {
1168
Brian Salomon466ad992016-10-13 16:08:36 -04001169 return kSingleHardStop_ColorType;
fmenozzicd9a1d02016-08-15 07:03:47 -07001170 }
1171 } else if (3 == shader.fColorCount) {
1172 if (SkScalarNearlyEqual(shader.fOrigPos[0], 0.0f) &&
1173 SkScalarNearlyEqual(shader.fOrigPos[1], 0.0f) &&
1174 SkScalarNearlyEqual(shader.fOrigPos[2], 1.0f)) {
1175
1176 return kHardStopLeftEdged_ColorType;
1177 } else if (SkScalarNearlyEqual(shader.fOrigPos[0], 0.0f) &&
1178 SkScalarNearlyEqual(shader.fOrigPos[1], 1.0f) &&
1179 SkScalarNearlyEqual(shader.fOrigPos[2], 1.0f)) {
1180
1181 return kHardStopRightEdged_ColorType;
1182 }
1183 }
1184 }
1185#endif
1186
1187 if (SkShader::kClamp_TileMode == shader.getTileMode()) {
1188 if (2 == shader.fColorCount) {
1189 return kTwo_ColorType;
1190 } else if (3 == shader.fColorCount &&
1191 close_to_one_half(shader.getRecs()[1].fPos)) {
1192 return kThree_ColorType;
1193 }
1194 }
1195
1196 return kTexture_ColorType;
bsalomon@google.comd8b5fac2012-11-01 17:02:46 +00001197}
rileya@google.comd7cc6512012-07-27 14:00:39 +00001198
fmenozzi55d318d2016-08-09 08:05:57 -07001199void GrGradientEffect::GLSLProcessor::emitUniforms(GrGLSLUniformHandler* uniformHandler,
1200 const GrGradientEffect& ge) {
fmenozzicd9a1d02016-08-15 07:03:47 -07001201 if (int colorCount = color_type_to_color_count(ge.getColorType())) {
1202 fColorsUni = uniformHandler->addUniformArray(kFragment_GrShaderFlag,
1203 kVec4f_GrSLType,
1204 kDefault_GrSLPrecision,
1205 "Colors",
1206 colorCount);
Brian Salomon466ad992016-10-13 16:08:36 -04001207 if (ge.fColorType == kSingleHardStop_ColorType) {
1208 fHardStopT = uniformHandler->addUniform(kFragment_GrShaderFlag, kFloat_GrSLType,
1209 kDefault_GrSLPrecision, "HardStopT");
1210 }
fmenozzicd9a1d02016-08-15 07:03:47 -07001211 } else {
cdalton5e58cee2016-02-11 12:49:47 -08001212 fFSYUni = uniformHandler->addUniform(kFragment_GrShaderFlag,
egdaniel7ea439b2015-12-03 09:20:44 -08001213 kFloat_GrSLType, kDefault_GrSLPrecision,
1214 "GradientYCoordFS");
bsalomon@google.com82d12232013-09-09 15:36:26 +00001215 }
1216}
1217
brianosmanb9c51372016-09-15 11:09:45 -07001218static inline void set_after_interp_color_uni_array(
1219 const GrGLSLProgramDataManager& pdman,
1220 const GrGLSLProgramDataManager::UniformHandle uni,
1221 const SkTDArray<SkColor4f>& colors,
1222 const GrColorSpaceXform* colorSpaceXform) {
1223 int count = colors.count();
1224 if (colorSpaceXform) {
1225 constexpr int kSmallCount = 10;
1226 SkAutoSTArray<4 * kSmallCount, float> vals(4 * count);
1227
1228 for (int i = 0; i < count; i++) {
1229 colorSpaceXform->srcToDst().mapScalars(colors[i].vec(), &vals[4 * i]);
1230 }
1231
1232 pdman.set4fv(uni, count, vals.get());
1233 } else {
1234 pdman.set4fv(uni, count, (float*)&colors[0]);
1235 }
1236}
1237
1238static inline void set_before_interp_color_uni_array(
1239 const GrGLSLProgramDataManager& pdman,
1240 const GrGLSLProgramDataManager::UniformHandle uni,
1241 const SkTDArray<SkColor4f>& colors,
1242 const GrColorSpaceXform* colorSpaceXform) {
1243 int count = colors.count();
1244 constexpr int kSmallCount = 10;
1245 SkAutoSTArray<4 * kSmallCount, float> vals(4 * count);
1246
1247 for (int i = 0; i < count; i++) {
1248 float a = colors[i].fA;
1249 vals[4 * i + 0] = colors[i].fR * a;
1250 vals[4 * i + 1] = colors[i].fG * a;
1251 vals[4 * i + 2] = colors[i].fB * a;
1252 vals[4 * i + 3] = a;
1253 }
1254
1255 if (colorSpaceXform) {
1256 for (int i = 0; i < count; i++) {
1257 colorSpaceXform->srcToDst().mapScalars(&vals[4 * i]);
1258 }
1259 }
1260
1261 pdman.set4fv(uni, count, vals.get());
1262}
1263
fmenozzicd9a1d02016-08-15 07:03:47 -07001264static inline void set_after_interp_color_uni_array(const GrGLSLProgramDataManager& pdman,
1265 const GrGLSLProgramDataManager::UniformHandle uni,
1266 const SkTDArray<SkColor>& colors) {
1267 int count = colors.count();
1268 constexpr int kSmallCount = 10;
1269
1270 SkAutoSTArray<4*kSmallCount, float> vals(4*count);
1271
1272 for (int i = 0; i < colors.count(); i++) {
1273 // RGBA
1274 vals[4*i + 0] = SkColorGetR(colors[i]) / 255.f;
1275 vals[4*i + 1] = SkColorGetG(colors[i]) / 255.f;
1276 vals[4*i + 2] = SkColorGetB(colors[i]) / 255.f;
1277 vals[4*i + 3] = SkColorGetA(colors[i]) / 255.f;
1278 }
1279
1280 pdman.set4fv(uni, colors.count(), vals.get());
bsalomon@google.com82d12232013-09-09 15:36:26 +00001281}
1282
fmenozzicd9a1d02016-08-15 07:03:47 -07001283static inline void set_before_interp_color_uni_array(const GrGLSLProgramDataManager& pdman,
1284 const GrGLSLProgramDataManager::UniformHandle uni,
1285 const SkTDArray<SkColor>& colors) {
1286 int count = colors.count();
1287 constexpr int kSmallCount = 10;
1288
1289 SkAutoSTArray<4*kSmallCount, float> vals(4*count);
1290
1291 for (int i = 0; i < count; i++) {
1292 float a = SkColorGetA(colors[i]) / 255.f;
1293 float aDiv255 = a / 255.f;
1294
1295 // RGBA
1296 vals[4*i + 0] = SkColorGetR(colors[i]) * aDiv255;
1297 vals[4*i + 1] = SkColorGetG(colors[i]) * aDiv255;
1298 vals[4*i + 2] = SkColorGetB(colors[i]) * aDiv255;
1299 vals[4*i + 3] = a;
1300 }
1301
1302 pdman.set4fv(uni, count, vals.get());
rileya@google.comb3e50f22012-08-20 17:43:08 +00001303}
1304
fmenozzi55d318d2016-08-09 08:05:57 -07001305void GrGradientEffect::GLSLProcessor::onSetData(const GrGLSLProgramDataManager& pdman,
1306 const GrProcessor& processor) {
joshualittb0a8a372014-09-23 09:50:21 -07001307 const GrGradientEffect& e = processor.cast<GrGradientEffect>();
bsalomon@google.com82d12232013-09-09 15:36:26 +00001308
fmenozzicd9a1d02016-08-15 07:03:47 -07001309 switch (e.getColorType()) {
1310#if GR_GL_USE_ACCURATE_HARD_STOP_GRADIENTS
Brian Salomon466ad992016-10-13 16:08:36 -04001311 case GrGradientEffect::kSingleHardStop_ColorType:
1312 pdman.set1f(fHardStopT, e.fPositions[1]);
1313 // fall through
fmenozzicd9a1d02016-08-15 07:03:47 -07001314 case GrGradientEffect::kHardStopLeftEdged_ColorType:
1315 case GrGradientEffect::kHardStopRightEdged_ColorType:
1316#endif
1317 case GrGradientEffect::kTwo_ColorType:
1318 case GrGradientEffect::kThree_ColorType: {
brianosmanb9c51372016-09-15 11:09:45 -07001319 if (e.fColors4f.count() > 0) {
1320 // Gamma-correct / color-space aware
1321 if (GrGradientEffect::kBeforeInterp_PremulType == e.getPremulType()) {
1322 set_before_interp_color_uni_array(pdman, fColorsUni, e.fColors4f,
1323 e.fColorSpaceXform.get());
1324 } else {
1325 set_after_interp_color_uni_array(pdman, fColorsUni, e.fColors4f,
1326 e.fColorSpaceXform.get());
1327 }
fmenozzicd9a1d02016-08-15 07:03:47 -07001328 } else {
brianosmanb9c51372016-09-15 11:09:45 -07001329 // Legacy mode. Would be nice if we had converted the 8-bit colors to float earlier
1330 if (GrGradientEffect::kBeforeInterp_PremulType == e.getPremulType()) {
1331 set_before_interp_color_uni_array(pdman, fColorsUni, e.fColors);
1332 } else {
1333 set_after_interp_color_uni_array(pdman, fColorsUni, e.fColors);
1334 }
fmenozzicd9a1d02016-08-15 07:03:47 -07001335 }
bsalomon@google.com82d12232013-09-09 15:36:26 +00001336
fmenozzicd9a1d02016-08-15 07:03:47 -07001337 break;
bsalomon@google.com82d12232013-09-09 15:36:26 +00001338 }
1339
fmenozzicd9a1d02016-08-15 07:03:47 -07001340 case GrGradientEffect::kTexture_ColorType: {
1341 SkScalar yCoord = e.getYCoord();
1342 if (yCoord != fCachedYCoord) {
1343 pdman.set1f(fFSYUni, yCoord);
1344 fCachedYCoord = yCoord;
1345 }
brianosmand4546092016-09-22 12:31:58 -07001346 if (SkToBool(e.fColorSpaceXform)) {
Brian Osmanc624d9d2017-03-08 11:42:02 -05001347 fColorSpaceHelper.setData(pdman, e.fColorSpaceXform.get());
brianosmand4546092016-09-22 12:31:58 -07001348 }
fmenozzicd9a1d02016-08-15 07:03:47 -07001349 break;
bsalomon@google.com82d12232013-09-09 15:36:26 +00001350 }
rileya@google.comb3e50f22012-08-20 17:43:08 +00001351 }
1352}
1353
fmenozzi55d318d2016-08-09 08:05:57 -07001354uint32_t GrGradientEffect::GLSLProcessor::GenBaseGradientKey(const GrProcessor& processor) {
joshualittb0a8a372014-09-23 09:50:21 -07001355 const GrGradientEffect& e = processor.cast<GrGradientEffect>();
skia.committer@gmail.com9a070f22013-09-10 07:01:44 +00001356
bsalomon63e99f72014-07-21 08:03:14 -07001357 uint32_t key = 0;
bsalomon@google.com82d12232013-09-09 15:36:26 +00001358
bsalomon@google.com82d12232013-09-09 15:36:26 +00001359 if (GrGradientEffect::kBeforeInterp_PremulType == e.getPremulType()) {
1360 key |= kPremulBeforeInterpKey;
1361 }
1362
fmenozzicd9a1d02016-08-15 07:03:47 -07001363 if (GrGradientEffect::kTwo_ColorType == e.getColorType()) {
1364 key |= kTwoColorKey;
1365 } else if (GrGradientEffect::kThree_ColorType == e.getColorType()) {
1366 key |= kThreeColorKey;
1367 }
1368#if GR_GL_USE_ACCURATE_HARD_STOP_GRADIENTS
Brian Salomon466ad992016-10-13 16:08:36 -04001369 else if (GrGradientEffect::kSingleHardStop_ColorType == e.getColorType()) {
fmenozzicd9a1d02016-08-15 07:03:47 -07001370 key |= kHardStopCenteredKey;
1371 } else if (GrGradientEffect::kHardStopLeftEdged_ColorType == e.getColorType()) {
1372 key |= kHardStopZeroZeroOneKey;
1373 } else if (GrGradientEffect::kHardStopRightEdged_ColorType == e.getColorType()) {
1374 key |= kHardStopZeroOneOneKey;
1375 }
1376
1377 if (SkShader::TileMode::kClamp_TileMode == e.fTileMode) {
1378 key |= kClampTileMode;
1379 } else if (SkShader::TileMode::kRepeat_TileMode == e.fTileMode) {
1380 key |= kRepeatTileMode;
1381 } else {
1382 key |= kMirrorTileMode;
1383 }
1384#endif
1385
brianosmand4546092016-09-22 12:31:58 -07001386 key |= GrColorSpaceXform::XformKey(e.fColorSpaceXform.get()) << kReservedBits;
1387
bsalomon@google.com82d12232013-09-09 15:36:26 +00001388 return key;
bsalomon@google.comd8b5fac2012-11-01 17:02:46 +00001389}
1390
fmenozzi55d318d2016-08-09 08:05:57 -07001391void GrGradientEffect::GLSLProcessor::emitColor(GrGLSLFPFragmentBuilder* fragBuilder,
1392 GrGLSLUniformHandler* uniformHandler,
Brian Salomon1edc5b92016-11-29 13:43:46 -05001393 const GrShaderCaps* shaderCaps,
fmenozzi55d318d2016-08-09 08:05:57 -07001394 const GrGradientEffect& ge,
1395 const char* gradientTValue,
1396 const char* outputColor,
1397 const char* inputColor,
bsalomonb58a2b42016-09-26 06:55:02 -07001398 const TextureSamplers& texSamplers) {
fmenozzicd9a1d02016-08-15 07:03:47 -07001399 switch (ge.getColorType()) {
1400#if GR_GL_USE_ACCURATE_HARD_STOP_GRADIENTS
Brian Salomon466ad992016-10-13 16:08:36 -04001401 case kSingleHardStop_ColorType: {
fmenozzicd9a1d02016-08-15 07:03:47 -07001402 const char* t = gradientTValue;
1403 const char* colors = uniformHandler->getUniformCStr(fColorsUni);
Brian Salomon466ad992016-10-13 16:08:36 -04001404 const char* stopT = uniformHandler->getUniformCStr(fHardStopT);
fmenozzicd9a1d02016-08-15 07:03:47 -07001405
1406 fragBuilder->codeAppendf("float clamp_t = clamp(%s, 0.0, 1.0);", t);
1407
1408 // Account for tile mode
1409 if (SkShader::kRepeat_TileMode == ge.fTileMode) {
1410 fragBuilder->codeAppendf("clamp_t = fract(%s);", t);
1411 } else if (SkShader::kMirror_TileMode == ge.fTileMode) {
1412 fragBuilder->codeAppendf("if (%s < 0.0 || %s > 1.0) {", t, t);
1413 fragBuilder->codeAppendf(" if (mod(floor(%s), 2.0) == 0.0) {", t);
1414 fragBuilder->codeAppendf(" clamp_t = fract(%s);", t);
1415 fragBuilder->codeAppendf(" } else {");
1416 fragBuilder->codeAppendf(" clamp_t = 1.0 - fract(%s);", t);
1417 fragBuilder->codeAppendf(" }");
1418 fragBuilder->codeAppendf("}");
1419 }
1420
1421 // Calculate color
Brian Salomon466ad992016-10-13 16:08:36 -04001422 fragBuilder->codeAppend ("vec4 start, end;");
1423 fragBuilder->codeAppend ("float relative_t;");
1424 fragBuilder->codeAppendf("if (clamp_t < %s) {", stopT);
1425 fragBuilder->codeAppendf(" start = %s[0];", colors);
1426 fragBuilder->codeAppendf(" end = %s[1];", colors);
1427 fragBuilder->codeAppendf(" relative_t = clamp_t / %s;", stopT);
1428 fragBuilder->codeAppend ("} else {");
fmenozziaf23ee52016-08-16 09:24:52 -07001429 fragBuilder->codeAppendf(" start = %s[2];", colors);
1430 fragBuilder->codeAppendf(" end = %s[3];", colors);
Brian Salomon466ad992016-10-13 16:08:36 -04001431 fragBuilder->codeAppendf(" relative_t = (clamp_t - %s) / (1 - %s);", stopT, stopT);
1432 fragBuilder->codeAppend ("}");
1433 fragBuilder->codeAppend ("vec4 colorTemp = mix(start, end, relative_t);");
fmenozzicd9a1d02016-08-15 07:03:47 -07001434
1435 if (GrGradientEffect::kAfterInterp_PremulType == ge.getPremulType()) {
1436 fragBuilder->codeAppend("colorTemp.rgb *= colorTemp.a;");
1437 }
Brian Salomonc5ca7f92017-02-21 14:35:11 -05001438 if (ge.fColorSpaceXform) {
1439 fragBuilder->codeAppend("colorTemp.rgb = clamp(colorTemp.rgb, 0, colorTemp.a);");
1440 }
fmenozzicd9a1d02016-08-15 07:03:47 -07001441 fragBuilder->codeAppendf("%s = %s;", outputColor,
1442 (GrGLSLExpr4(inputColor) * GrGLSLExpr4("colorTemp")).c_str());
1443
1444 break;
bsalomon@google.com82d12232013-09-09 15:36:26 +00001445 }
bsalomon@google.com34bcb9f2012-08-28 18:20:18 +00001446
fmenozzicd9a1d02016-08-15 07:03:47 -07001447 case kHardStopLeftEdged_ColorType: {
1448 const char* t = gradientTValue;
1449 const char* colors = uniformHandler->getUniformCStr(fColorsUni);
1450
1451 fragBuilder->codeAppendf("float clamp_t = clamp(%s, 0.0, 1.0);", t);
1452
1453 // Account for tile mode
1454 if (SkShader::kRepeat_TileMode == ge.fTileMode) {
1455 fragBuilder->codeAppendf("clamp_t = fract(%s);", t);
1456 } else if (SkShader::kMirror_TileMode == ge.fTileMode) {
1457 fragBuilder->codeAppendf("if (%s < 0.0 || %s > 1.0) {", t, t);
1458 fragBuilder->codeAppendf(" if (mod(floor(%s), 2.0) == 0.0) {", t);
1459 fragBuilder->codeAppendf(" clamp_t = fract(%s);", t);
1460 fragBuilder->codeAppendf(" } else {");
1461 fragBuilder->codeAppendf(" clamp_t = 1.0 - fract(%s);", t);
1462 fragBuilder->codeAppendf(" }");
1463 fragBuilder->codeAppendf("}");
1464 }
1465
1466 fragBuilder->codeAppendf("vec4 colorTemp = mix(%s[1], %s[2], clamp_t);", colors,
1467 colors);
1468 if (SkShader::kClamp_TileMode == ge.fTileMode) {
1469 fragBuilder->codeAppendf("if (%s < 0.0) {", t);
1470 fragBuilder->codeAppendf(" colorTemp = %s[0];", colors);
1471 fragBuilder->codeAppendf("}");
1472 }
1473
1474 if (GrGradientEffect::kAfterInterp_PremulType == ge.getPremulType()) {
1475 fragBuilder->codeAppend("colorTemp.rgb *= colorTemp.a;");
1476 }
Brian Salomonc5ca7f92017-02-21 14:35:11 -05001477 if (ge.fColorSpaceXform) {
1478 fragBuilder->codeAppend("colorTemp.rgb = clamp(colorTemp.rgb, 0, colorTemp.a);");
1479 }
fmenozzicd9a1d02016-08-15 07:03:47 -07001480 fragBuilder->codeAppendf("%s = %s;", outputColor,
1481 (GrGLSLExpr4(inputColor) * GrGLSLExpr4("colorTemp")).c_str());
1482
1483 break;
bsalomon@google.com82d12232013-09-09 15:36:26 +00001484 }
1485
fmenozzicd9a1d02016-08-15 07:03:47 -07001486 case kHardStopRightEdged_ColorType: {
1487 const char* t = gradientTValue;
1488 const char* colors = uniformHandler->getUniformCStr(fColorsUni);
1489
1490 fragBuilder->codeAppendf("float clamp_t = clamp(%s, 0.0, 1.0);", t);
1491
1492 // Account for tile mode
1493 if (SkShader::kRepeat_TileMode == ge.fTileMode) {
1494 fragBuilder->codeAppendf("clamp_t = fract(%s);", t);
1495 } else if (SkShader::kMirror_TileMode == ge.fTileMode) {
1496 fragBuilder->codeAppendf("if (%s < 0.0 || %s > 1.0) {", t, t);
1497 fragBuilder->codeAppendf(" if (mod(floor(%s), 2.0) == 0.0) {", t);
1498 fragBuilder->codeAppendf(" clamp_t = fract(%s);", t);
1499 fragBuilder->codeAppendf(" } else {");
1500 fragBuilder->codeAppendf(" clamp_t = 1.0 - fract(%s);", t);
1501 fragBuilder->codeAppendf(" }");
1502 fragBuilder->codeAppendf("}");
1503 }
1504
1505 fragBuilder->codeAppendf("vec4 colorTemp = mix(%s[0], %s[1], clamp_t);", colors,
1506 colors);
1507 if (SkShader::kClamp_TileMode == ge.fTileMode) {
1508 fragBuilder->codeAppendf("if (%s > 1.0) {", t);
1509 fragBuilder->codeAppendf(" colorTemp = %s[2];", colors);
1510 fragBuilder->codeAppendf("}");
1511 }
1512
1513 if (GrGradientEffect::kAfterInterp_PremulType == ge.getPremulType()) {
1514 fragBuilder->codeAppend("colorTemp.rgb *= colorTemp.a;");
1515 }
Brian Salomonc5ca7f92017-02-21 14:35:11 -05001516 if (ge.fColorSpaceXform) {
1517 fragBuilder->codeAppend("colorTemp.rgb = clamp(colorTemp.rgb, 0, colorTemp.a);");
1518 }
fmenozzicd9a1d02016-08-15 07:03:47 -07001519 fragBuilder->codeAppendf("%s = %s;", outputColor,
1520 (GrGLSLExpr4(inputColor) * GrGLSLExpr4("colorTemp")).c_str());
1521
1522 break;
1523 }
1524#endif
1525
1526 case kTwo_ColorType: {
1527 const char* t = gradientTValue;
1528 const char* colors = uniformHandler->getUniformCStr(fColorsUni);
1529
1530 fragBuilder->codeAppendf("vec4 colorTemp = mix(%s[0], %s[1], clamp(%s, 0.0, 1.0));",
1531 colors, colors, t);
1532
1533 // We could skip this step if both colors are known to be opaque. Two
1534 // considerations:
1535 // The gradient SkShader reporting opaque is more restrictive than necessary in the two
1536 // pt case. Make sure the key reflects this optimization (and note that it can use the
1537 // same shader as thekBeforeIterp case). This same optimization applies to the 3 color
1538 // case below.
1539 if (GrGradientEffect::kAfterInterp_PremulType == ge.getPremulType()) {
1540 fragBuilder->codeAppend("colorTemp.rgb *= colorTemp.a;");
1541 }
Brian Salomonc5ca7f92017-02-21 14:35:11 -05001542 if (ge.fColorSpaceXform) {
1543 fragBuilder->codeAppend("colorTemp.rgb = clamp(colorTemp.rgb, 0, colorTemp.a);");
1544 }
fmenozzicd9a1d02016-08-15 07:03:47 -07001545
1546 fragBuilder->codeAppendf("%s = %s;", outputColor,
1547 (GrGLSLExpr4(inputColor) * GrGLSLExpr4("colorTemp")).c_str());
1548
1549 break;
1550 }
1551
1552 case kThree_ColorType: {
1553 const char* t = gradientTValue;
1554 const char* colors = uniformHandler->getUniformCStr(fColorsUni);
1555
1556 fragBuilder->codeAppendf("float oneMinus2t = 1.0 - (2.0 * %s);", t);
1557 fragBuilder->codeAppendf("vec4 colorTemp = clamp(oneMinus2t, 0.0, 1.0) * %s[0];",
1558 colors);
Brian Salomon1edc5b92016-11-29 13:43:46 -05001559 if (!shaderCaps->canUseMinAndAbsTogether()) {
fmenozzicd9a1d02016-08-15 07:03:47 -07001560 // The Tegra3 compiler will sometimes never return if we have
1561 // min(abs(oneMinus2t), 1.0), or do the abs first in a separate expression.
1562 fragBuilder->codeAppendf("float minAbs = abs(oneMinus2t);");
1563 fragBuilder->codeAppendf("minAbs = minAbs > 1.0 ? 1.0 : minAbs;");
1564 fragBuilder->codeAppendf("colorTemp += (1.0 - minAbs) * %s[1];", colors);
1565 } else {
1566 fragBuilder->codeAppendf("colorTemp += (1.0 - min(abs(oneMinus2t), 1.0)) * %s[1];",
1567 colors);
1568 }
1569 fragBuilder->codeAppendf("colorTemp += clamp(-oneMinus2t, 0.0, 1.0) * %s[2];", colors);
1570
1571 if (GrGradientEffect::kAfterInterp_PremulType == ge.getPremulType()) {
1572 fragBuilder->codeAppend("colorTemp.rgb *= colorTemp.a;");
1573 }
Brian Salomonc5ca7f92017-02-21 14:35:11 -05001574 if (ge.fColorSpaceXform) {
1575 fragBuilder->codeAppend("colorTemp.rgb = clamp(colorTemp.rgb, 0, colorTemp.a);");
1576 }
fmenozzicd9a1d02016-08-15 07:03:47 -07001577
1578 fragBuilder->codeAppendf("%s = %s;", outputColor,
1579 (GrGLSLExpr4(inputColor) * GrGLSLExpr4("colorTemp")).c_str());
1580
1581 break;
1582 }
1583
1584 case kTexture_ColorType: {
Brian Osmanc624d9d2017-03-08 11:42:02 -05001585 fColorSpaceHelper.emitCode(uniformHandler, ge.fColorSpaceXform.get());
brianosmand4546092016-09-22 12:31:58 -07001586
fmenozzicd9a1d02016-08-15 07:03:47 -07001587 const char* fsyuni = uniformHandler->getUniformCStr(fFSYUni);
1588
1589 fragBuilder->codeAppendf("vec2 coord = vec2(%s, %s);", gradientTValue, fsyuni);
1590 fragBuilder->codeAppendf("%s = ", outputColor);
brianosmand4546092016-09-22 12:31:58 -07001591 fragBuilder->appendTextureLookupAndModulate(inputColor, texSamplers[0], "coord",
Brian Osmanc624d9d2017-03-08 11:42:02 -05001592 kVec2f_GrSLType, &fColorSpaceHelper);
fmenozzicd9a1d02016-08-15 07:03:47 -07001593 fragBuilder->codeAppend(";");
1594
1595 break;
1596 }
bsalomon@google.com82d12232013-09-09 15:36:26 +00001597 }
rileya@google.comd7cc6512012-07-27 14:00:39 +00001598}
1599
1600/////////////////////////////////////////////////////////////////////
1601
Brian Salomon587e08f2017-01-27 10:59:27 -05001602inline GrFragmentProcessor::OptimizationFlags GrGradientEffect::OptFlags(bool isOpaque) {
Brian Salomonf3b995b2017-02-15 10:22:23 -05001603 return isOpaque
1604 ? kPreservesOpaqueInput_OptimizationFlag |
1605 kCompatibleWithCoverageAsAlpha_OptimizationFlag
1606 : kCompatibleWithCoverageAsAlpha_OptimizationFlag;
Brian Salomon587e08f2017-01-27 10:59:27 -05001607}
1608
1609GrGradientEffect::GrGradientEffect(const CreateArgs& args, bool isOpaque)
1610 : INHERITED(OptFlags(isOpaque)) {
brianosman9557c272016-09-15 06:59:15 -07001611 const SkGradientShaderBase& shader(*args.fShader);
bsalomon@google.com82d12232013-09-09 15:36:26 +00001612
bsalomon@google.com371e1052013-01-11 21:08:55 +00001613 fIsOpaque = shader.isOpaque();
1614
fmenozzicd9a1d02016-08-15 07:03:47 -07001615 fColorType = this->determineColorType(shader);
brianosmand4546092016-09-22 12:31:58 -07001616 fColorSpaceXform = std::move(args.fColorSpaceXform);
bsalomon@google.com1ce49fc2012-09-18 14:14:49 +00001617
fmenozzicd9a1d02016-08-15 07:03:47 -07001618 if (kTexture_ColorType != fColorType) {
brianosmanb9c51372016-09-15 11:09:45 -07001619 SkASSERT(shader.fOrigColors && shader.fOrigColors4f);
1620 if (args.fGammaCorrect) {
1621 fColors4f = SkTDArray<SkColor4f>(shader.fOrigColors4f, shader.fColorCount);
brianosmanb9c51372016-09-15 11:09:45 -07001622 } else {
fmenozzicd9a1d02016-08-15 07:03:47 -07001623 fColors = SkTDArray<SkColor>(shader.fOrigColors, shader.fColorCount);
halcanary8a822ba2016-08-12 12:35:51 -07001624 }
fmenozzi2a495912016-08-12 06:33:52 -07001625
fmenozzicd9a1d02016-08-15 07:03:47 -07001626#if GR_GL_USE_ACCURATE_HARD_STOP_GRADIENTS
1627 if (shader.fOrigPos) {
1628 fPositions = SkTDArray<SkScalar>(shader.fOrigPos, shader.fColorCount);
halcanary8a822ba2016-08-12 12:35:51 -07001629 }
fmenozzicd9a1d02016-08-15 07:03:47 -07001630#endif
fmenozzi2a495912016-08-12 06:33:52 -07001631 }
fmenozzicd9a1d02016-08-15 07:03:47 -07001632
1633#if GR_GL_USE_ACCURATE_HARD_STOP_GRADIENTS
brianosman9557c272016-09-15 06:59:15 -07001634 fTileMode = args.fTileMode;
fmenozzicd9a1d02016-08-15 07:03:47 -07001635#endif
1636
1637 switch (fColorType) {
1638 // The two and three color specializations do not currently support tiling.
1639 case kTwo_ColorType:
1640 case kThree_ColorType:
1641#if GR_GL_USE_ACCURATE_HARD_STOP_GRADIENTS
1642 case kHardStopLeftEdged_ColorType:
1643 case kHardStopRightEdged_ColorType:
Brian Salomon466ad992016-10-13 16:08:36 -04001644 case kSingleHardStop_ColorType:
fmenozzicd9a1d02016-08-15 07:03:47 -07001645#endif
1646 fRow = -1;
1647
1648 if (SkGradientShader::kInterpolateColorsInPremul_Flag & shader.getGradFlags()) {
1649 fPremulType = kBeforeInterp_PremulType;
1650 } else {
1651 fPremulType = kAfterInterp_PremulType;
1652 }
1653
Brian Salomon2ebd0c82016-10-03 17:15:28 -04001654 fCoordTransform.reset(*args.fMatrix);
fmenozzicd9a1d02016-08-15 07:03:47 -07001655
1656 break;
1657 case kTexture_ColorType:
1658 // doesn't matter how this is set, just be consistent because it is part of the
1659 // effect key.
1660 fPremulType = kBeforeInterp_PremulType;
1661
brianosmand4546092016-09-22 12:31:58 -07001662 SkGradientShaderBase::GradientBitmapType bitmapType =
1663 SkGradientShaderBase::GradientBitmapType::kLegacy;
1664 if (args.fGammaCorrect) {
1665 // Try to use F16 if we can
1666 if (args.fContext->caps()->isConfigTexturable(kRGBA_half_GrPixelConfig)) {
1667 bitmapType = SkGradientShaderBase::GradientBitmapType::kHalfFloat;
1668 } else if (args.fContext->caps()->isConfigTexturable(kSRGBA_8888_GrPixelConfig)) {
1669 bitmapType = SkGradientShaderBase::GradientBitmapType::kSRGB;
1670 } else {
brianosmanc68e8922016-09-22 14:27:34 -07001671 // This can happen, but only if someone explicitly creates an unsupported
1672 // (eg sRGB) surface. Just fall back to legacy behavior.
brianosmand4546092016-09-22 12:31:58 -07001673 }
1674 }
1675
fmenozzicd9a1d02016-08-15 07:03:47 -07001676 SkBitmap bitmap;
brianosmand4546092016-09-22 12:31:58 -07001677 shader.getGradientTableBitmap(&bitmap, bitmapType);
Robert Phillips30f9bc62017-02-22 15:28:38 -05001678 SkASSERT(1 == bitmap.height() && SkIsPow2(bitmap.width()));
1679
fmenozzicd9a1d02016-08-15 07:03:47 -07001680
1681 GrTextureStripAtlas::Desc desc;
1682 desc.fWidth = bitmap.width();
1683 desc.fHeight = 32;
1684 desc.fRowHeight = bitmap.height();
brianosman9557c272016-09-15 06:59:15 -07001685 desc.fContext = args.fContext;
1686 desc.fConfig = SkImageInfo2GrPixelConfig(bitmap.info(), *args.fContext->caps());
fmenozzicd9a1d02016-08-15 07:03:47 -07001687 fAtlas = GrTextureStripAtlas::GetAtlas(desc);
1688 SkASSERT(fAtlas);
1689
1690 // We always filter the gradient table. Each table is one row of a texture, always
1691 // y-clamp.
Brian Salomon514baff2016-11-17 15:17:07 -05001692 GrSamplerParams params;
1693 params.setFilterMode(GrSamplerParams::kBilerp_FilterMode);
brianosman9557c272016-09-15 06:59:15 -07001694 params.setTileModeX(args.fTileMode);
fmenozzicd9a1d02016-08-15 07:03:47 -07001695
1696 fRow = fAtlas->lockRow(bitmap);
1697 if (-1 != fRow) {
1698 fYCoord = fAtlas->getYOffset(fRow)+SK_ScalarHalf*fAtlas->getNormalizedTexelHeight();
Robert Phillips67c18d62017-01-20 12:44:06 -05001699 // This is 1/2 places where auto-normalization is disabled
Robert Phillips30f9bc62017-02-22 15:28:38 -05001700 fCoordTransform.reset(args.fContext, *args.fMatrix,
1701 fAtlas->asTextureProxyRef().get(),
Robert Phillips67c18d62017-01-20 12:44:06 -05001702 params.filterMode(), false);
Brian Osman32342f02017-03-04 08:12:46 -05001703 fTextureSampler.reset(args.fContext->resourceProvider(),
Robert Phillips30f9bc62017-02-22 15:28:38 -05001704 fAtlas->asTextureProxyRef(), params);
fmenozzicd9a1d02016-08-15 07:03:47 -07001705 } else {
Robert Phillips30f9bc62017-02-22 15:28:38 -05001706 // In this instance we know the params are:
1707 // clampY, bilerp
1708 // and the proxy is:
1709 // exact fit, power of two in both dimensions
1710 // Only the x-tileMode is unknown. However, given all the other knowns we know
1711 // that GrMakeCachedBitmapProxy is sufficient (i.e., it won't need to be
1712 // extracted to a subset or mipmapped).
1713 sk_sp<GrTextureProxy> proxy = GrMakeCachedBitmapProxy(args.fContext, bitmap);
1714 if (!proxy) {
fmenozzicd9a1d02016-08-15 07:03:47 -07001715 return;
1716 }
Robert Phillips67c18d62017-01-20 12:44:06 -05001717 // This is 2/2 places where auto-normalization is disabled
Robert Phillips30f9bc62017-02-22 15:28:38 -05001718 fCoordTransform.reset(args.fContext, *args.fMatrix,
1719 proxy.get(), params.filterMode(), false);
Brian Osman32342f02017-03-04 08:12:46 -05001720 fTextureSampler.reset(args.fContext->resourceProvider(),
Robert Phillips30f9bc62017-02-22 15:28:38 -05001721 std::move(proxy), params);
fmenozzicd9a1d02016-08-15 07:03:47 -07001722 fYCoord = SK_ScalarHalf;
1723 }
1724
Brian Salomon0bbecb22016-11-17 11:38:22 -05001725 this->addTextureSampler(&fTextureSampler);
fmenozzicd9a1d02016-08-15 07:03:47 -07001726
1727 break;
1728 }
1729
bsalomon@google.com77af6802013-10-02 13:04:56 +00001730 this->addCoordTransform(&fCoordTransform);
rileya@google.comd7cc6512012-07-27 14:00:39 +00001731}
1732
1733GrGradientEffect::~GrGradientEffect() {
rileya@google.comb3e50f22012-08-20 17:43:08 +00001734 if (this->useAtlas()) {
1735 fAtlas->unlockRow(fRow);
rileya@google.comb3e50f22012-08-20 17:43:08 +00001736 }
rileya@google.comd7cc6512012-07-27 14:00:39 +00001737}
1738
bsalomon0e08fc12014-10-15 08:19:04 -07001739bool GrGradientEffect::onIsEqual(const GrFragmentProcessor& processor) const {
fmenozzicd9a1d02016-08-15 07:03:47 -07001740 const GrGradientEffect& ge = processor.cast<GrGradientEffect>();
bsalomon@google.com82d12232013-09-09 15:36:26 +00001741
Brian Salomon466ad992016-10-13 16:08:36 -04001742 if (this->fColorType != ge.getColorType()) {
1743 return false;
1744 }
1745 SkASSERT(this->useAtlas() == ge.useAtlas());
1746 if (kTexture_ColorType == fColorType) {
1747 if (fYCoord != ge.getYCoord()) {
1748 return false;
1749 }
1750 } else {
1751 if (kSingleHardStop_ColorType == fColorType) {
1752 if (!SkScalarNearlyEqual(ge.fPositions[1], fPositions[1])) {
bsalomon@google.com82d12232013-09-09 15:36:26 +00001753 return false;
1754 }
1755 }
Brian Salomon466ad992016-10-13 16:08:36 -04001756 if (this->getPremulType() != ge.getPremulType() ||
1757 this->fColors.count() != ge.fColors.count() ||
1758 this->fColors4f.count() != ge.fColors4f.count()) {
1759 return false;
1760 }
skia.committer@gmail.com9a070f22013-09-10 07:01:44 +00001761
Brian Salomon466ad992016-10-13 16:08:36 -04001762 for (int i = 0; i < this->fColors.count(); i++) {
1763 if (*this->getColors(i) != *ge.getColors(i)) {
1764 return false;
1765 }
1766 }
1767 for (int i = 0; i < this->fColors4f.count(); i++) {
1768 if (*this->getColors4f(i) != *ge.getColors4f(i)) {
1769 return false;
1770 }
1771 }
bsalomon@google.com82d12232013-09-09 15:36:26 +00001772 }
Brian Salomon466ad992016-10-13 16:08:36 -04001773 return GrColorSpaceXform::Equals(this->fColorSpaceXform.get(), ge.fColorSpaceXform.get());
bsalomon@google.com68b58c92013-01-17 16:50:08 +00001774}
1775
Hal Canary6f6961e2017-01-31 13:50:44 -05001776#if GR_TEST_UTILS
Brian Osman3f748602016-10-03 18:29:03 -04001777GrGradientEffect::RandomGradientParams::RandomGradientParams(SkRandom* random) {
Brian Salomon5d4cd9e2017-02-09 11:16:46 -05001778 // Set color count to min of 2 so that we don't trigger the const color optimization and make
1779 // a non-gradient processor.
1780 fColorCount = random->nextRangeU(2, kMaxRandomGradientColors);
Brian Osmana2196532016-10-17 12:48:13 -04001781 fUseColors4f = random->nextBool();
bsalomon@google.comd4726202012-08-03 14:34:46 +00001782
1783 // if one color, omit stops, otherwise randomly decide whether or not to
Brian Osman3f748602016-10-03 18:29:03 -04001784 if (fColorCount == 1 || (fColorCount >= 2 && random->nextBool())) {
1785 fStops = nullptr;
1786 } else {
1787 fStops = fStopStorage;
bsalomon@google.comd4726202012-08-03 14:34:46 +00001788 }
1789
Brian Osmana2196532016-10-17 12:48:13 -04001790 // if using SkColor4f, attach a random (possibly null) color space (with linear gamma)
1791 if (fUseColors4f) {
1792 fColorSpace = GrTest::TestColorSpace(random);
1793 if (fColorSpace) {
raftias94888332016-10-18 10:02:51 -07001794 SkASSERT(SkColorSpace_Base::Type::kXYZ == as_CSB(fColorSpace)->type());
1795 fColorSpace = static_cast<SkColorSpace_XYZ*>(fColorSpace.get())->makeLinearGamma();
Brian Osmana2196532016-10-17 12:48:13 -04001796 }
1797 }
1798
bsalomon@google.com81712882012-11-01 17:12:34 +00001799 SkScalar stop = 0.f;
Brian Osman3f748602016-10-03 18:29:03 -04001800 for (int i = 0; i < fColorCount; ++i) {
Brian Osmana2196532016-10-17 12:48:13 -04001801 if (fUseColors4f) {
1802 fColors4f[i].fR = random->nextUScalar1();
1803 fColors4f[i].fG = random->nextUScalar1();
1804 fColors4f[i].fB = random->nextUScalar1();
1805 fColors4f[i].fA = random->nextUScalar1();
1806 } else {
1807 fColors[i] = random->nextU();
1808 }
Brian Osman3f748602016-10-03 18:29:03 -04001809 if (fStops) {
1810 fStops[i] = stop;
1811 stop = i < fColorCount - 1 ? stop + random->nextUScalar1() * (1.f - stop) : 1.f;
bsalomon@google.comd4726202012-08-03 14:34:46 +00001812 }
1813 }
Brian Osman3f748602016-10-03 18:29:03 -04001814 fTileMode = static_cast<SkShader::TileMode>(random->nextULessThan(SkShader::kTileModeCount));
bsalomon@google.comd4726202012-08-03 14:34:46 +00001815}
Hal Canary6f6961e2017-01-31 13:50:44 -05001816#endif
bsalomon@google.comd4726202012-08-03 14:34:46 +00001817
bsalomon@google.comcf8fb1f2012-08-02 14:03:32 +00001818#endif