1 /*
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 
8 #include "SkGradientShaderPriv.h"
9 #include "SkLinearGradient.h"
10 #include "SkRadialGradient.h"
11 #include "SkTwoPointConicalGradient.h"
12 #include "SkSweepGradient.h"
13 
flatten(SkWriteBuffer & buffer) const14 void SkGradientShaderBase::Descriptor::flatten(SkWriteBuffer& buffer) const {
15     buffer.writeColorArray(fColors, fCount);
16     if (fPos) {
17         buffer.writeBool(true);
18         buffer.writeScalarArray(fPos, fCount);
19     } else {
20         buffer.writeBool(false);
21     }
22     buffer.write32(fTileMode);
23     buffer.write32(fGradFlags);
24     if (fLocalMatrix) {
25         buffer.writeBool(true);
26         buffer.writeMatrix(*fLocalMatrix);
27     } else {
28         buffer.writeBool(false);
29     }
30 }
31 
unflatten(SkReadBuffer & buffer)32 bool SkGradientShaderBase::DescriptorScope::unflatten(SkReadBuffer& buffer) {
33     fCount = buffer.getArrayCount();
34     if (fCount > kStorageCount) {
35         size_t allocSize = (sizeof(SkColor) + sizeof(SkScalar)) * fCount;
36         fDynamicStorage.reset(allocSize);
37         fColors = (SkColor*)fDynamicStorage.get();
38         fPos = (SkScalar*)(fColors + fCount);
39     } else {
40         fColors = fColorStorage;
41         fPos = fPosStorage;
42     }
43 
44     if (!buffer.readColorArray(const_cast<SkColor*>(fColors), fCount)) {
45         return false;
46     }
47     if (buffer.readBool()) {
48         if (!buffer.readScalarArray(const_cast<SkScalar*>(fPos), fCount)) {
49             return false;
50         }
51     } else {
52         fPos = NULL;
53     }
54 
55     fTileMode = (SkShader::TileMode)buffer.read32();
56     fGradFlags = buffer.read32();
57 
58     if (buffer.readBool()) {
59         fLocalMatrix = &fLocalMatrixStorage;
60         buffer.readMatrix(&fLocalMatrixStorage);
61     } else {
62         fLocalMatrix = NULL;
63     }
64     return buffer.isValid();
65 }
66 
67 ////////////////////////////////////////////////////////////////////////////////////////////
68 
SkGradientShaderBase(const Descriptor & desc,const SkMatrix & ptsToUnit)69 SkGradientShaderBase::SkGradientShaderBase(const Descriptor& desc, const SkMatrix& ptsToUnit)
70     : INHERITED(desc.fLocalMatrix)
71     , fPtsToUnit(ptsToUnit)
72 {
73     fPtsToUnit.getType();  // Precache so reads are threadsafe.
74     SkASSERT(desc.fCount > 1);
75 
76     fGradFlags = SkToU8(desc.fGradFlags);
77 
78     SkASSERT((unsigned)desc.fTileMode < SkShader::kTileModeCount);
79     SkASSERT(SkShader::kTileModeCount == SK_ARRAY_COUNT(gTileProcs));
80     fTileMode = desc.fTileMode;
81     fTileProc = gTileProcs[desc.fTileMode];
82 
83     /*  Note: we let the caller skip the first and/or last position.
84         i.e. pos[0] = 0.3, pos[1] = 0.7
85         In these cases, we insert dummy entries to ensure that the final data
86         will be bracketed by [0, 1].
87         i.e. our_pos[0] = 0, our_pos[1] = 0.3, our_pos[2] = 0.7, our_pos[3] = 1
88 
89         Thus colorCount (the caller's value, and fColorCount (our value) may
90         differ by up to 2. In the above example:
91             colorCount = 2
92             fColorCount = 4
93      */
94     fColorCount = desc.fCount;
95     // check if we need to add in dummy start and/or end position/colors
96     bool dummyFirst = false;
97     bool dummyLast = false;
98     if (desc.fPos) {
99         dummyFirst = desc.fPos[0] != 0;
100         dummyLast = desc.fPos[desc.fCount - 1] != SK_Scalar1;
101         fColorCount += dummyFirst + dummyLast;
102     }
103 
104     if (fColorCount > kColorStorageCount) {
105         size_t size = sizeof(SkColor) + sizeof(Rec);
106         if (desc.fPos) {
107             size += sizeof(SkScalar);
108         }
109         fOrigColors = reinterpret_cast<SkColor*>(
110                                         sk_malloc_throw(size * fColorCount));
111     }
112     else {
113         fOrigColors = fStorage;
114     }
115 
116     // Now copy over the colors, adding the dummies as needed
117     {
118         SkColor* origColors = fOrigColors;
119         if (dummyFirst) {
120             *origColors++ = desc.fColors[0];
121         }
122         memcpy(origColors, desc.fColors, desc.fCount * sizeof(SkColor));
123         if (dummyLast) {
124             origColors += desc.fCount;
125             *origColors = desc.fColors[desc.fCount - 1];
126         }
127     }
128 
129     if (desc.fPos && fColorCount) {
130         fOrigPos = (SkScalar*)(fOrigColors + fColorCount);
131         fRecs = (Rec*)(fOrigPos + fColorCount);
132     } else {
133         fOrigPos = NULL;
134         fRecs = (Rec*)(fOrigColors + fColorCount);
135     }
136 
137     if (fColorCount > 2) {
138         Rec* recs = fRecs;
139         recs->fPos = 0;
140         //  recs->fScale = 0; // unused;
141         recs += 1;
142         if (desc.fPos) {
143             SkScalar* origPosPtr = fOrigPos;
144             *origPosPtr++ = 0;
145 
146             /*  We need to convert the user's array of relative positions into
147                 fixed-point positions and scale factors. We need these results
148                 to be strictly monotonic (no two values equal or out of order).
149                 Hence this complex loop that just jams a zero for the scale
150                 value if it sees a segment out of order, and it assures that
151                 we start at 0 and end at 1.0
152             */
153             SkScalar prev = 0;
154             int startIndex = dummyFirst ? 0 : 1;
155             int count = desc.fCount + dummyLast;
156             for (int i = startIndex; i < count; i++) {
157                 // force the last value to be 1.0
158                 SkScalar curr;
159                 if (i == desc.fCount) {  // we're really at the dummyLast
160                     curr = 1;
161                 } else {
162                     curr = SkScalarPin(desc.fPos[i], 0, 1);
163                 }
164                 *origPosPtr++ = curr;
165 
166                 recs->fPos = SkScalarToFixed(curr);
167                 SkFixed diff = SkScalarToFixed(curr - prev);
168                 if (diff > 0) {
169                     recs->fScale = (1 << 24) / diff;
170                 } else {
171                     recs->fScale = 0; // ignore this segment
172                 }
173                 // get ready for the next value
174                 prev = curr;
175                 recs += 1;
176             }
177         } else {    // assume even distribution
178             fOrigPos = NULL;
179 
180             SkFixed dp = SK_Fixed1 / (desc.fCount - 1);
181             SkFixed p = dp;
182             SkFixed scale = (desc.fCount - 1) << 8;  // (1 << 24) / dp
183             for (int i = 1; i < desc.fCount - 1; i++) {
184                 recs->fPos   = p;
185                 recs->fScale = scale;
186                 recs += 1;
187                 p += dp;
188             }
189             recs->fPos = SK_Fixed1;
190             recs->fScale = scale;
191         }
192     } else if (desc.fPos) {
193         SkASSERT(2 == fColorCount);
194         fOrigPos[0] = SkScalarPin(desc.fPos[0], 0, 1);
195         fOrigPos[1] = SkScalarPin(desc.fPos[1], fOrigPos[0], 1);
196         if (0 == fOrigPos[0] && 1 == fOrigPos[1]) {
197             fOrigPos = NULL;
198         }
199     }
200     this->initCommon();
201 }
202 
~SkGradientShaderBase()203 SkGradientShaderBase::~SkGradientShaderBase() {
204     if (fOrigColors != fStorage) {
205         sk_free(fOrigColors);
206     }
207 }
208 
initCommon()209 void SkGradientShaderBase::initCommon() {
210     unsigned colorAlpha = 0xFF;
211     for (int i = 0; i < fColorCount; i++) {
212         colorAlpha &= SkColorGetA(fOrigColors[i]);
213     }
214     fColorsAreOpaque = colorAlpha == 0xFF;
215 }
216 
flatten(SkWriteBuffer & buffer) const217 void SkGradientShaderBase::flatten(SkWriteBuffer& buffer) const {
218     Descriptor desc;
219     desc.fColors = fOrigColors;
220     desc.fPos = fOrigPos;
221     desc.fCount = fColorCount;
222     desc.fTileMode = fTileMode;
223     desc.fGradFlags = fGradFlags;
224 
225     const SkMatrix& m = this->getLocalMatrix();
226     desc.fLocalMatrix = m.isIdentity() ? NULL : &m;
227     desc.flatten(buffer);
228 }
229 
getGpuColorType(SkColor colors[3]) const230 SkGradientShaderBase::GpuColorType SkGradientShaderBase::getGpuColorType(SkColor colors[3]) const {
231     if (fColorCount <= 3) {
232         memcpy(colors, fOrigColors, fColorCount * sizeof(SkColor));
233     }
234 
235     if (SkShader::kClamp_TileMode == fTileMode) {
236         if (2 == fColorCount) {
237             return kTwo_GpuColorType;
238         } else if (3 == fColorCount &&
239                    (SkScalarAbs(
240                     SkFixedToScalar(fRecs[1].fPos) - SK_ScalarHalf) < SK_Scalar1 / 1000)) {
241             return kThree_GpuColorType;
242         }
243     }
244     return kTexture_GpuColorType;
245 }
246 
FlipGradientColors(SkColor * colorDst,Rec * recDst,SkColor * colorSrc,Rec * recSrc,int count)247 void SkGradientShaderBase::FlipGradientColors(SkColor* colorDst, Rec* recDst,
248                                               SkColor* colorSrc, Rec* recSrc,
249                                               int count) {
250     SkAutoSTArray<8, SkColor> colorsTemp(count);
251     for (int i = 0; i < count; ++i) {
252         int offset = count - i - 1;
253         colorsTemp[i] = colorSrc[offset];
254     }
255     if (count > 2) {
256         SkAutoSTArray<8, Rec> recsTemp(count);
257         for (int i = 0; i < count; ++i) {
258             int offset = count - i - 1;
259             recsTemp[i].fPos = SK_Fixed1 - recSrc[offset].fPos;
260             recsTemp[i].fScale = recSrc[offset].fScale;
261         }
262         memcpy(recDst, recsTemp.get(), count * sizeof(Rec));
263     }
264     memcpy(colorDst, colorsTemp.get(), count * sizeof(SkColor));
265 }
266 
isOpaque() const267 bool SkGradientShaderBase::isOpaque() const {
268     return fColorsAreOpaque;
269 }
270 
rounded_divide(unsigned numer,unsigned denom)271 static unsigned rounded_divide(unsigned numer, unsigned denom) {
272     return (numer + (denom >> 1)) / denom;
273 }
274 
onAsLuminanceColor(SkColor * lum) const275 bool SkGradientShaderBase::onAsLuminanceColor(SkColor* lum) const {
276     // we just compute an average color.
277     // possibly we could weight this based on the proportional width for each color
278     //   assuming they are not evenly distributed in the fPos array.
279     int r = 0;
280     int g = 0;
281     int b = 0;
282     const int n = fColorCount;
283     for (int i = 0; i < n; ++i) {
284         SkColor c = fOrigColors[i];
285         r += SkColorGetR(c);
286         g += SkColorGetG(c);
287         b += SkColorGetB(c);
288     }
289     *lum = SkColorSetRGB(rounded_divide(r, n), rounded_divide(g, n), rounded_divide(b, n));
290     return true;
291 }
292 
GradientShaderBaseContext(const SkGradientShaderBase & shader,const ContextRec & rec)293 SkGradientShaderBase::GradientShaderBaseContext::GradientShaderBaseContext(
294         const SkGradientShaderBase& shader, const ContextRec& rec)
295     : INHERITED(shader, rec)
296     , fCache(shader.refCache(getPaintAlpha()))
297 {
298     const SkMatrix& inverse = this->getTotalInverse();
299 
300     fDstToIndex.setConcat(shader.fPtsToUnit, inverse);
301 
302     fDstToIndexProc = fDstToIndex.getMapXYProc();
303     fDstToIndexClass = (uint8_t)SkShader::Context::ComputeMatrixClass(fDstToIndex);
304 
305     // now convert our colors in to PMColors
306     unsigned paintAlpha = this->getPaintAlpha();
307 
308     fFlags = this->INHERITED::getFlags();
309     if (shader.fColorsAreOpaque && paintAlpha == 0xFF) {
310         fFlags |= kOpaqueAlpha_Flag;
311     }
312     // we can do span16 as long as our individual colors are opaque,
313     // regardless of the paint's alpha
314     if (shader.fColorsAreOpaque) {
315         fFlags |= kHasSpan16_Flag;
316     }
317 }
318 
GradientShaderCache(U8CPU alpha,const SkGradientShaderBase & shader)319 SkGradientShaderBase::GradientShaderCache::GradientShaderCache(
320         U8CPU alpha, const SkGradientShaderBase& shader)
321     : fCacheAlpha(alpha)
322     , fShader(shader)
323     , fCache16Inited(false)
324     , fCache32Inited(false)
325 {
326     // Only initialize the cache in getCache16/32.
327     fCache16 = NULL;
328     fCache32 = NULL;
329     fCache16Storage = NULL;
330     fCache32PixelRef = NULL;
331 }
332 
~GradientShaderCache()333 SkGradientShaderBase::GradientShaderCache::~GradientShaderCache() {
334     sk_free(fCache16Storage);
335     SkSafeUnref(fCache32PixelRef);
336 }
337 
338 #define Fixed_To_Dot8(x)        (((x) + 0x80) >> 8)
339 
340 /** We take the original colors, not our premultiplied PMColors, since we can
341     build a 16bit table as long as the original colors are opaque, even if the
342     paint specifies a non-opaque alpha.
343 */
Build16bitCache(uint16_t cache[],SkColor c0,SkColor c1,int count)344 void SkGradientShaderBase::GradientShaderCache::Build16bitCache(
345         uint16_t cache[], SkColor c0, SkColor c1, int count) {
346     SkASSERT(count > 1);
347     SkASSERT(SkColorGetA(c0) == 0xFF);
348     SkASSERT(SkColorGetA(c1) == 0xFF);
349 
350     SkFixed r = SkColorGetR(c0);
351     SkFixed g = SkColorGetG(c0);
352     SkFixed b = SkColorGetB(c0);
353 
354     SkFixed dr = SkIntToFixed(SkColorGetR(c1) - r) / (count - 1);
355     SkFixed dg = SkIntToFixed(SkColorGetG(c1) - g) / (count - 1);
356     SkFixed db = SkIntToFixed(SkColorGetB(c1) - b) / (count - 1);
357 
358     r = SkIntToFixed(r) + 0x8000;
359     g = SkIntToFixed(g) + 0x8000;
360     b = SkIntToFixed(b) + 0x8000;
361 
362     do {
363         unsigned rr = r >> 16;
364         unsigned gg = g >> 16;
365         unsigned bb = b >> 16;
366         cache[0] = SkPackRGB16(SkR32ToR16(rr), SkG32ToG16(gg), SkB32ToB16(bb));
367         cache[kCache16Count] = SkDitherPack888ToRGB16(rr, gg, bb);
368         cache += 1;
369         r += dr;
370         g += dg;
371         b += db;
372     } while (--count != 0);
373 }
374 
375 /*
376  *  r,g,b used to be SkFixed, but on gcc (4.2.1 mac and 4.6.3 goobuntu) in
377  *  release builds, we saw a compiler error where the 0xFF parameter in
378  *  SkPackARGB32() was being totally ignored whenever it was called with
379  *  a non-zero add (e.g. 0x8000).
380  *
381  *  We found two work-arounds:
382  *      1. change r,g,b to unsigned (or just one of them)
383  *      2. change SkPackARGB32 to + its (a << SK_A32_SHIFT) value instead
384  *         of using |
385  *
386  *  We chose #1 just because it was more localized.
387  *  See http://code.google.com/p/skia/issues/detail?id=1113
388  *
389  *  The type SkUFixed encapsulate this need for unsigned, but logically Fixed.
390  */
391 typedef uint32_t SkUFixed;
392 
Build32bitCache(SkPMColor cache[],SkColor c0,SkColor c1,int count,U8CPU paintAlpha,uint32_t gradFlags)393 void SkGradientShaderBase::GradientShaderCache::Build32bitCache(
394         SkPMColor cache[], SkColor c0, SkColor c1,
395         int count, U8CPU paintAlpha, uint32_t gradFlags) {
396     SkASSERT(count > 1);
397 
398     // need to apply paintAlpha to our two endpoints
399     uint32_t a0 = SkMulDiv255Round(SkColorGetA(c0), paintAlpha);
400     uint32_t a1 = SkMulDiv255Round(SkColorGetA(c1), paintAlpha);
401 
402 
403     const bool interpInPremul = SkToBool(gradFlags &
404                            SkGradientShader::kInterpolateColorsInPremul_Flag);
405 
406     uint32_t r0 = SkColorGetR(c0);
407     uint32_t g0 = SkColorGetG(c0);
408     uint32_t b0 = SkColorGetB(c0);
409 
410     uint32_t r1 = SkColorGetR(c1);
411     uint32_t g1 = SkColorGetG(c1);
412     uint32_t b1 = SkColorGetB(c1);
413 
414     if (interpInPremul) {
415         r0 = SkMulDiv255Round(r0, a0);
416         g0 = SkMulDiv255Round(g0, a0);
417         b0 = SkMulDiv255Round(b0, a0);
418 
419         r1 = SkMulDiv255Round(r1, a1);
420         g1 = SkMulDiv255Round(g1, a1);
421         b1 = SkMulDiv255Round(b1, a1);
422     }
423 
424     SkFixed da = SkIntToFixed(a1 - a0) / (count - 1);
425     SkFixed dr = SkIntToFixed(r1 - r0) / (count - 1);
426     SkFixed dg = SkIntToFixed(g1 - g0) / (count - 1);
427     SkFixed db = SkIntToFixed(b1 - b0) / (count - 1);
428 
429     /*  We pre-add 1/8 to avoid having to add this to our [0] value each time
430         in the loop. Without this, the bias for each would be
431             0x2000  0xA000  0xE000  0x6000
432         With this trick, we can add 0 for the first (no-op) and just adjust the
433         others.
434      */
435     SkUFixed a = SkIntToFixed(a0) + 0x2000;
436     SkUFixed r = SkIntToFixed(r0) + 0x2000;
437     SkUFixed g = SkIntToFixed(g0) + 0x2000;
438     SkUFixed b = SkIntToFixed(b0) + 0x2000;
439 
440     /*
441      *  Our dither-cell (spatially) is
442      *      0 2
443      *      3 1
444      *  Where
445      *      [0] -> [-1/8 ... 1/8 ) values near 0
446      *      [1] -> [ 1/8 ... 3/8 ) values near 1/4
447      *      [2] -> [ 3/8 ... 5/8 ) values near 1/2
448      *      [3] -> [ 5/8 ... 7/8 ) values near 3/4
449      */
450 
451     if (0xFF == a0 && 0 == da) {
452         do {
453             cache[kCache32Count*0] = SkPackARGB32(0xFF, (r + 0     ) >> 16,
454                                                         (g + 0     ) >> 16,
455                                                         (b + 0     ) >> 16);
456             cache[kCache32Count*1] = SkPackARGB32(0xFF, (r + 0x8000) >> 16,
457                                                         (g + 0x8000) >> 16,
458                                                         (b + 0x8000) >> 16);
459             cache[kCache32Count*2] = SkPackARGB32(0xFF, (r + 0xC000) >> 16,
460                                                         (g + 0xC000) >> 16,
461                                                         (b + 0xC000) >> 16);
462             cache[kCache32Count*3] = SkPackARGB32(0xFF, (r + 0x4000) >> 16,
463                                                         (g + 0x4000) >> 16,
464                                                         (b + 0x4000) >> 16);
465             cache += 1;
466             r += dr;
467             g += dg;
468             b += db;
469         } while (--count != 0);
470     } else if (interpInPremul) {
471         do {
472             cache[kCache32Count*0] = SkPackARGB32((a + 0     ) >> 16,
473                                                   (r + 0     ) >> 16,
474                                                   (g + 0     ) >> 16,
475                                                   (b + 0     ) >> 16);
476             cache[kCache32Count*1] = SkPackARGB32((a + 0x8000) >> 16,
477                                                   (r + 0x8000) >> 16,
478                                                   (g + 0x8000) >> 16,
479                                                   (b + 0x8000) >> 16);
480             cache[kCache32Count*2] = SkPackARGB32((a + 0xC000) >> 16,
481                                                   (r + 0xC000) >> 16,
482                                                   (g + 0xC000) >> 16,
483                                                   (b + 0xC000) >> 16);
484             cache[kCache32Count*3] = SkPackARGB32((a + 0x4000) >> 16,
485                                                   (r + 0x4000) >> 16,
486                                                   (g + 0x4000) >> 16,
487                                                   (b + 0x4000) >> 16);
488             cache += 1;
489             a += da;
490             r += dr;
491             g += dg;
492             b += db;
493         } while (--count != 0);
494     } else {    // interpolate in unpreml space
495         do {
496             cache[kCache32Count*0] = SkPremultiplyARGBInline((a + 0     ) >> 16,
497                                                              (r + 0     ) >> 16,
498                                                              (g + 0     ) >> 16,
499                                                              (b + 0     ) >> 16);
500             cache[kCache32Count*1] = SkPremultiplyARGBInline((a + 0x8000) >> 16,
501                                                              (r + 0x8000) >> 16,
502                                                              (g + 0x8000) >> 16,
503                                                              (b + 0x8000) >> 16);
504             cache[kCache32Count*2] = SkPremultiplyARGBInline((a + 0xC000) >> 16,
505                                                              (r + 0xC000) >> 16,
506                                                              (g + 0xC000) >> 16,
507                                                              (b + 0xC000) >> 16);
508             cache[kCache32Count*3] = SkPremultiplyARGBInline((a + 0x4000) >> 16,
509                                                              (r + 0x4000) >> 16,
510                                                              (g + 0x4000) >> 16,
511                                                              (b + 0x4000) >> 16);
512             cache += 1;
513             a += da;
514             r += dr;
515             g += dg;
516             b += db;
517         } while (--count != 0);
518     }
519 }
520 
SkFixedToFFFF(SkFixed x)521 static inline int SkFixedToFFFF(SkFixed x) {
522     SkASSERT((unsigned)x <= SK_Fixed1);
523     return x - (x >> 16);
524 }
525 
getCache16()526 const uint16_t* SkGradientShaderBase::GradientShaderCache::getCache16() {
527     SkOnce(&fCache16Inited, &fCache16Mutex, SkGradientShaderBase::GradientShaderCache::initCache16,
528            this);
529     SkASSERT(fCache16);
530     return fCache16;
531 }
532 
initCache16(GradientShaderCache * cache)533 void SkGradientShaderBase::GradientShaderCache::initCache16(GradientShaderCache* cache) {
534     // double the count for dither entries
535     const int entryCount = kCache16Count * 2;
536     const size_t allocSize = sizeof(uint16_t) * entryCount;
537 
538     SkASSERT(NULL == cache->fCache16Storage);
539     cache->fCache16Storage = (uint16_t*)sk_malloc_throw(allocSize);
540     cache->fCache16 = cache->fCache16Storage;
541     if (cache->fShader.fColorCount == 2) {
542         Build16bitCache(cache->fCache16, cache->fShader.fOrigColors[0],
543                         cache->fShader.fOrigColors[1], kCache16Count);
544     } else {
545         Rec* rec = cache->fShader.fRecs;
546         int prevIndex = 0;
547         for (int i = 1; i < cache->fShader.fColorCount; i++) {
548             int nextIndex = SkFixedToFFFF(rec[i].fPos) >> kCache16Shift;
549             SkASSERT(nextIndex < kCache16Count);
550 
551             if (nextIndex > prevIndex)
552                 Build16bitCache(cache->fCache16 + prevIndex, cache->fShader.fOrigColors[i-1],
553                                 cache->fShader.fOrigColors[i], nextIndex - prevIndex + 1);
554             prevIndex = nextIndex;
555         }
556     }
557 }
558 
getCache32()559 const SkPMColor* SkGradientShaderBase::GradientShaderCache::getCache32() {
560     SkOnce(&fCache32Inited, &fCache32Mutex, SkGradientShaderBase::GradientShaderCache::initCache32,
561            this);
562     SkASSERT(fCache32);
563     return fCache32;
564 }
565 
initCache32(GradientShaderCache * cache)566 void SkGradientShaderBase::GradientShaderCache::initCache32(GradientShaderCache* cache) {
567     const int kNumberOfDitherRows = 4;
568     const SkImageInfo info = SkImageInfo::MakeN32Premul(kCache32Count, kNumberOfDitherRows);
569 
570     SkASSERT(NULL == cache->fCache32PixelRef);
571     cache->fCache32PixelRef = SkMallocPixelRef::NewAllocate(info, 0, NULL);
572     cache->fCache32 = (SkPMColor*)cache->fCache32PixelRef->getAddr();
573     if (cache->fShader.fColorCount == 2) {
574         Build32bitCache(cache->fCache32, cache->fShader.fOrigColors[0],
575                         cache->fShader.fOrigColors[1], kCache32Count, cache->fCacheAlpha,
576                         cache->fShader.fGradFlags);
577     } else {
578         Rec* rec = cache->fShader.fRecs;
579         int prevIndex = 0;
580         for (int i = 1; i < cache->fShader.fColorCount; i++) {
581             int nextIndex = SkFixedToFFFF(rec[i].fPos) >> kCache32Shift;
582             SkASSERT(nextIndex < kCache32Count);
583 
584             if (nextIndex > prevIndex)
585                 Build32bitCache(cache->fCache32 + prevIndex, cache->fShader.fOrigColors[i-1],
586                                 cache->fShader.fOrigColors[i], nextIndex - prevIndex + 1,
587                                 cache->fCacheAlpha, cache->fShader.fGradFlags);
588             prevIndex = nextIndex;
589         }
590     }
591 }
592 
593 /*
594  *  The gradient holds a cache for the most recent value of alpha. Successive
595  *  callers with the same alpha value will share the same cache.
596  */
refCache(U8CPU alpha) const597 SkGradientShaderBase::GradientShaderCache* SkGradientShaderBase::refCache(U8CPU alpha) const {
598     SkAutoMutexAcquire ama(fCacheMutex);
599     if (!fCache || fCache->getAlpha() != alpha) {
600         fCache.reset(SkNEW_ARGS(GradientShaderCache, (alpha, *this)));
601     }
602     // Increment the ref counter inside the mutex to ensure the returned pointer is still valid.
603     // Otherwise, the pointer may have been overwritten on a different thread before the object's
604     // ref count was incremented.
605     fCache.get()->ref();
606     return fCache;
607 }
608 
609 SK_DECLARE_STATIC_MUTEX(gGradientCacheMutex);
610 /*
611  *  Because our caller might rebuild the same (logically the same) gradient
612  *  over and over, we'd like to return exactly the same "bitmap" if possible,
613  *  allowing the client to utilize a cache of our bitmap (e.g. with a GPU).
614  *  To do that, we maintain a private cache of built-bitmaps, based on our
615  *  colors and positions. Note: we don't try to flatten the fMapper, so if one
616  *  is present, we skip the cache for now.
617  */
getGradientTableBitmap(SkBitmap * bitmap) const618 void SkGradientShaderBase::getGradientTableBitmap(SkBitmap* bitmap) const {
619     // our caller assumes no external alpha, so we ensure that our cache is
620     // built with 0xFF
621     SkAutoTUnref<GradientShaderCache> cache(this->refCache(0xFF));
622 
623     // build our key: [numColors + colors[] + {positions[]} + flags ]
624     int count = 1 + fColorCount + 1;
625     if (fColorCount > 2) {
626         count += fColorCount - 1;    // fRecs[].fPos
627     }
628 
629     SkAutoSTMalloc<16, int32_t> storage(count);
630     int32_t* buffer = storage.get();
631 
632     *buffer++ = fColorCount;
633     memcpy(buffer, fOrigColors, fColorCount * sizeof(SkColor));
634     buffer += fColorCount;
635     if (fColorCount > 2) {
636         for (int i = 1; i < fColorCount; i++) {
637             *buffer++ = fRecs[i].fPos;
638         }
639     }
640     *buffer++ = fGradFlags;
641     SkASSERT(buffer - storage.get() == count);
642 
643     ///////////////////////////////////
644 
645     static SkGradientBitmapCache* gCache;
646     // each cache cost 1K of RAM, since each bitmap will be 1x256 at 32bpp
647     static const int MAX_NUM_CACHED_GRADIENT_BITMAPS = 32;
648     SkAutoMutexAcquire ama(gGradientCacheMutex);
649 
650     if (NULL == gCache) {
651         gCache = SkNEW_ARGS(SkGradientBitmapCache, (MAX_NUM_CACHED_GRADIENT_BITMAPS));
652     }
653     size_t size = count * sizeof(int32_t);
654 
655     if (!gCache->find(storage.get(), size, bitmap)) {
656         // force our cahce32pixelref to be built
657         (void)cache->getCache32();
658         bitmap->setInfo(SkImageInfo::MakeN32Premul(kCache32Count, 1));
659         bitmap->setPixelRef(cache->getCache32PixelRef());
660 
661         gCache->add(storage.get(), size, *bitmap);
662     }
663 }
664 
commonAsAGradient(GradientInfo * info,bool flipGrad) const665 void SkGradientShaderBase::commonAsAGradient(GradientInfo* info, bool flipGrad) const {
666     if (info) {
667         if (info->fColorCount >= fColorCount) {
668             SkColor* colorLoc;
669             Rec*     recLoc;
670             if (flipGrad && (info->fColors || info->fColorOffsets)) {
671                 SkAutoSTArray<8, SkColor> colorStorage(fColorCount);
672                 SkAutoSTArray<8, Rec> recStorage(fColorCount);
673                 colorLoc = colorStorage.get();
674                 recLoc = recStorage.get();
675                 FlipGradientColors(colorLoc, recLoc, fOrigColors, fRecs, fColorCount);
676             } else {
677                 colorLoc = fOrigColors;
678                 recLoc = fRecs;
679             }
680             if (info->fColors) {
681                 memcpy(info->fColors, colorLoc, fColorCount * sizeof(SkColor));
682             }
683             if (info->fColorOffsets) {
684                 if (fColorCount == 2) {
685                     info->fColorOffsets[0] = 0;
686                     info->fColorOffsets[1] = SK_Scalar1;
687                 } else if (fColorCount > 2) {
688                     for (int i = 0; i < fColorCount; ++i) {
689                         info->fColorOffsets[i] = SkFixedToScalar(recLoc[i].fPos);
690                     }
691                 }
692             }
693         }
694         info->fColorCount = fColorCount;
695         info->fTileMode = fTileMode;
696         info->fGradientFlags = fGradFlags;
697     }
698 }
699 
700 #ifndef SK_IGNORE_TO_STRING
toString(SkString * str) const701 void SkGradientShaderBase::toString(SkString* str) const {
702 
703     str->appendf("%d colors: ", fColorCount);
704 
705     for (int i = 0; i < fColorCount; ++i) {
706         str->appendHex(fOrigColors[i], 8);
707         if (i < fColorCount-1) {
708             str->append(", ");
709         }
710     }
711 
712     if (fColorCount > 2) {
713         str->append(" points: (");
714         for (int i = 0; i < fColorCount; ++i) {
715             str->appendScalar(SkFixedToScalar(fRecs[i].fPos));
716             if (i < fColorCount-1) {
717                 str->append(", ");
718             }
719         }
720         str->append(")");
721     }
722 
723     static const char* gTileModeName[SkShader::kTileModeCount] = {
724         "clamp", "repeat", "mirror"
725     };
726 
727     str->append(" ");
728     str->append(gTileModeName[fTileMode]);
729 
730     this->INHERITED::toString(str);
731 }
732 #endif
733 
734 ///////////////////////////////////////////////////////////////////////////////
735 ///////////////////////////////////////////////////////////////////////////////
736 
737 // Return true if these parameters are valid/legal/safe to construct a gradient
738 //
valid_grad(const SkColor colors[],const SkScalar pos[],int count,unsigned tileMode)739 static bool valid_grad(const SkColor colors[], const SkScalar pos[], int count, unsigned tileMode) {
740     return NULL != colors && count >= 1 && tileMode < (unsigned)SkShader::kTileModeCount;
741 }
742 
743 // assumes colors is SkColor* and pos is SkScalar*
744 #define EXPAND_1_COLOR(count)               \
745     SkColor tmp[2];                         \
746     do {                                    \
747         if (1 == count) {                   \
748             tmp[0] = tmp[1] = colors[0];    \
749             colors = tmp;                   \
750             pos = NULL;                     \
751             count = 2;                      \
752         }                                   \
753     } while (0)
754 
desc_init(SkGradientShaderBase::Descriptor * desc,const SkColor colors[],const SkScalar pos[],int colorCount,SkShader::TileMode mode,uint32_t flags,const SkMatrix * localMatrix)755 static void desc_init(SkGradientShaderBase::Descriptor* desc,
756                       const SkColor colors[], const SkScalar pos[], int colorCount,
757                       SkShader::TileMode mode, uint32_t flags, const SkMatrix* localMatrix) {
758     desc->fColors       = colors;
759     desc->fPos          = pos;
760     desc->fCount        = colorCount;
761     desc->fTileMode     = mode;
762     desc->fGradFlags    = flags;
763     desc->fLocalMatrix  = localMatrix;
764 }
765 
CreateLinear(const SkPoint pts[2],const SkColor colors[],const SkScalar pos[],int colorCount,SkShader::TileMode mode,uint32_t flags,const SkMatrix * localMatrix)766 SkShader* SkGradientShader::CreateLinear(const SkPoint pts[2],
767                                          const SkColor colors[],
768                                          const SkScalar pos[], int colorCount,
769                                          SkShader::TileMode mode,
770                                          uint32_t flags,
771                                          const SkMatrix* localMatrix) {
772     if (!pts) {
773         return NULL;
774     }
775     if (!valid_grad(colors, pos, colorCount, mode)) {
776         return NULL;
777     }
778     EXPAND_1_COLOR(colorCount);
779 
780     SkGradientShaderBase::Descriptor desc;
781     desc_init(&desc, colors, pos, colorCount, mode, flags, localMatrix);
782     return SkNEW_ARGS(SkLinearGradient, (pts, desc));
783 }
784 
CreateRadial(const SkPoint & center,SkScalar radius,const SkColor colors[],const SkScalar pos[],int colorCount,SkShader::TileMode mode,uint32_t flags,const SkMatrix * localMatrix)785 SkShader* SkGradientShader::CreateRadial(const SkPoint& center, SkScalar radius,
786                                          const SkColor colors[],
787                                          const SkScalar pos[], int colorCount,
788                                          SkShader::TileMode mode,
789                                          uint32_t flags,
790                                          const SkMatrix* localMatrix) {
791     if (radius <= 0) {
792         return NULL;
793     }
794     if (!valid_grad(colors, pos, colorCount, mode)) {
795         return NULL;
796     }
797     EXPAND_1_COLOR(colorCount);
798 
799     SkGradientShaderBase::Descriptor desc;
800     desc_init(&desc, colors, pos, colorCount, mode, flags, localMatrix);
801     return SkNEW_ARGS(SkRadialGradient, (center, radius, desc));
802 }
803 
CreateTwoPointConical(const SkPoint & start,SkScalar startRadius,const SkPoint & end,SkScalar endRadius,const SkColor colors[],const SkScalar pos[],int colorCount,SkShader::TileMode mode,uint32_t flags,const SkMatrix * localMatrix)804 SkShader* SkGradientShader::CreateTwoPointConical(const SkPoint& start,
805                                                   SkScalar startRadius,
806                                                   const SkPoint& end,
807                                                   SkScalar endRadius,
808                                                   const SkColor colors[],
809                                                   const SkScalar pos[],
810                                                   int colorCount,
811                                                   SkShader::TileMode mode,
812                                                   uint32_t flags,
813                                                   const SkMatrix* localMatrix) {
814     if (startRadius < 0 || endRadius < 0) {
815         return NULL;
816     }
817     if (!valid_grad(colors, pos, colorCount, mode)) {
818         return NULL;
819     }
820     if (start == end && startRadius == endRadius) {
821         return SkShader::CreateEmptyShader();
822     }
823 
824     EXPAND_1_COLOR(colorCount);
825 
826     bool flipGradient = startRadius > endRadius;
827 
828     SkGradientShaderBase::Descriptor desc;
829 
830     if (!flipGradient) {
831         desc_init(&desc, colors, pos, colorCount, mode, flags, localMatrix);
832         return SkNEW_ARGS(SkTwoPointConicalGradient,
833                           (start, startRadius, end, endRadius, flipGradient, desc));
834     } else {
835         SkAutoSTArray<8, SkColor> colorsNew(colorCount);
836         SkAutoSTArray<8, SkScalar> posNew(colorCount);
837         for (int i = 0; i < colorCount; ++i) {
838             colorsNew[i] = colors[colorCount - i - 1];
839         }
840 
841         if (pos) {
842             for (int i = 0; i < colorCount; ++i) {
843                 posNew[i] = 1 - pos[colorCount - i - 1];
844             }
845             desc_init(&desc, colorsNew.get(), posNew.get(), colorCount, mode, flags, localMatrix);
846         } else {
847             desc_init(&desc, colorsNew.get(), NULL, colorCount, mode, flags, localMatrix);
848         }
849 
850         return SkNEW_ARGS(SkTwoPointConicalGradient,
851                           (end, endRadius, start, startRadius, flipGradient, desc));
852     }
853 }
854 
CreateSweep(SkScalar cx,SkScalar cy,const SkColor colors[],const SkScalar pos[],int colorCount,uint32_t flags,const SkMatrix * localMatrix)855 SkShader* SkGradientShader::CreateSweep(SkScalar cx, SkScalar cy,
856                                         const SkColor colors[],
857                                         const SkScalar pos[],
858                                         int colorCount,
859                                         uint32_t flags,
860                                         const SkMatrix* localMatrix) {
861     if (!valid_grad(colors, pos, colorCount, SkShader::kClamp_TileMode)) {
862         return NULL;
863     }
864     EXPAND_1_COLOR(colorCount);
865 
866     SkGradientShaderBase::Descriptor desc;
867     desc_init(&desc, colors, pos, colorCount, SkShader::kClamp_TileMode, flags, localMatrix);
868     return SkNEW_ARGS(SkSweepGradient, (cx, cy, desc));
869 }
870 
871 SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_START(SkGradientShader)
SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkLinearGradient)872     SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkLinearGradient)
873     SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkRadialGradient)
874     SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkSweepGradient)
875     SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkTwoPointConicalGradient)
876 SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_END
877 
878 ///////////////////////////////////////////////////////////////////////////////
879 
880 #if SK_SUPPORT_GPU
881 
882 #include "effects/GrTextureStripAtlas.h"
883 #include "GrInvariantOutput.h"
884 #include "gl/builders/GrGLProgramBuilder.h"
885 #include "SkGr.h"
886 
887 GrGLGradientEffect::GrGLGradientEffect()
888     : fCachedYCoord(SK_ScalarMax) {
889 }
890 
~GrGLGradientEffect()891 GrGLGradientEffect::~GrGLGradientEffect() { }
892 
emitUniforms(GrGLFPBuilder * builder,const GrGradientEffect & ge)893 void GrGLGradientEffect::emitUniforms(GrGLFPBuilder* builder, const GrGradientEffect& ge) {
894 
895     if (SkGradientShaderBase::kTwo_GpuColorType == ge.getColorType()) { // 2 Color case
896         fColorStartUni = builder->addUniform(GrGLProgramBuilder::kFragment_Visibility,
897                                              kVec4f_GrSLType, kDefault_GrSLPrecision,
898                                             "GradientStartColor");
899         fColorEndUni = builder->addUniform(GrGLProgramBuilder::kFragment_Visibility,
900                                            kVec4f_GrSLType, kDefault_GrSLPrecision,
901                                            "GradientEndColor");
902 
903     } else if (SkGradientShaderBase::kThree_GpuColorType == ge.getColorType()) { // 3 Color Case
904         fColorStartUni = builder->addUniform(GrGLProgramBuilder::kFragment_Visibility,
905                                              kVec4f_GrSLType,  kDefault_GrSLPrecision,
906                                              "GradientStartColor");
907         fColorMidUni = builder->addUniform(GrGLProgramBuilder::kFragment_Visibility,
908                                            kVec4f_GrSLType, kDefault_GrSLPrecision,
909                                            "GradientMidColor");
910         fColorEndUni = builder->addUniform(GrGLProgramBuilder::kFragment_Visibility,
911                                            kVec4f_GrSLType, kDefault_GrSLPrecision,
912                                            "GradientEndColor");
913 
914     } else { // if not a fast case
915         fFSYUni = builder->addUniform(GrGLProgramBuilder::kFragment_Visibility,
916                                       kFloat_GrSLType, kDefault_GrSLPrecision,
917                                       "GradientYCoordFS");
918     }
919 }
920 
set_color_uni(const GrGLProgramDataManager & pdman,const GrGLProgramDataManager::UniformHandle uni,const SkColor * color)921 static inline void set_color_uni(const GrGLProgramDataManager& pdman,
922                                  const GrGLProgramDataManager::UniformHandle uni,
923                                  const SkColor* color) {
924        pdman.set4f(uni,
925                    SkColorGetR(*color) / 255.f,
926                    SkColorGetG(*color) / 255.f,
927                    SkColorGetB(*color) / 255.f,
928                    SkColorGetA(*color) / 255.f);
929 }
930 
set_mul_color_uni(const GrGLProgramDataManager & pdman,const GrGLProgramDataManager::UniformHandle uni,const SkColor * color)931 static inline void set_mul_color_uni(const GrGLProgramDataManager& pdman,
932                                      const GrGLProgramDataManager::UniformHandle uni,
933                                      const SkColor* color){
934        float a = SkColorGetA(*color) / 255.f;
935        float aDiv255 = a / 255.f;
936        pdman.set4f(uni,
937                    SkColorGetR(*color) * aDiv255,
938                    SkColorGetG(*color) * aDiv255,
939                    SkColorGetB(*color) * aDiv255,
940                    a);
941 }
942 
setData(const GrGLProgramDataManager & pdman,const GrProcessor & processor)943 void GrGLGradientEffect::setData(const GrGLProgramDataManager& pdman,
944                                  const GrProcessor& processor) {
945 
946     const GrGradientEffect& e = processor.cast<GrGradientEffect>();
947 
948 
949     if (SkGradientShaderBase::kTwo_GpuColorType == e.getColorType()){
950 
951         if (GrGradientEffect::kBeforeInterp_PremulType == e.getPremulType()) {
952             set_mul_color_uni(pdman, fColorStartUni, e.getColors(0));
953             set_mul_color_uni(pdman, fColorEndUni,   e.getColors(1));
954         } else {
955             set_color_uni(pdman, fColorStartUni, e.getColors(0));
956             set_color_uni(pdman, fColorEndUni,   e.getColors(1));
957         }
958 
959     } else if (SkGradientShaderBase::kThree_GpuColorType == e.getColorType()){
960 
961         if (GrGradientEffect::kBeforeInterp_PremulType == e.getPremulType()) {
962             set_mul_color_uni(pdman, fColorStartUni, e.getColors(0));
963             set_mul_color_uni(pdman, fColorMidUni,   e.getColors(1));
964             set_mul_color_uni(pdman, fColorEndUni,   e.getColors(2));
965         } else {
966             set_color_uni(pdman, fColorStartUni, e.getColors(0));
967             set_color_uni(pdman, fColorMidUni,   e.getColors(1));
968             set_color_uni(pdman, fColorEndUni,   e.getColors(2));
969         }
970     } else {
971 
972         SkScalar yCoord = e.getYCoord();
973         if (yCoord != fCachedYCoord) {
974             pdman.set1f(fFSYUni, yCoord);
975             fCachedYCoord = yCoord;
976         }
977     }
978 }
979 
980 
GenBaseGradientKey(const GrProcessor & processor)981 uint32_t GrGLGradientEffect::GenBaseGradientKey(const GrProcessor& processor) {
982     const GrGradientEffect& e = processor.cast<GrGradientEffect>();
983 
984     uint32_t key = 0;
985 
986     if (SkGradientShaderBase::kTwo_GpuColorType == e.getColorType()) {
987         key |= kTwoColorKey;
988     } else if (SkGradientShaderBase::kThree_GpuColorType == e.getColorType()) {
989         key |= kThreeColorKey;
990     }
991 
992     if (GrGradientEffect::kBeforeInterp_PremulType == e.getPremulType()) {
993         key |= kPremulBeforeInterpKey;
994     }
995 
996     return key;
997 }
998 
emitColor(GrGLFPBuilder * builder,const GrGradientEffect & ge,const char * gradientTValue,const char * outputColor,const char * inputColor,const TextureSamplerArray & samplers)999 void GrGLGradientEffect::emitColor(GrGLFPBuilder* builder,
1000                                    const GrGradientEffect& ge,
1001                                    const char* gradientTValue,
1002                                    const char* outputColor,
1003                                    const char* inputColor,
1004                                    const TextureSamplerArray& samplers) {
1005     GrGLFragmentBuilder* fsBuilder = builder->getFragmentShaderBuilder();
1006     if (SkGradientShaderBase::kTwo_GpuColorType == ge.getColorType()){
1007         fsBuilder->codeAppendf("\tvec4 colorTemp = mix(%s, %s, clamp(%s, 0.0, 1.0));\n",
1008                                builder->getUniformVariable(fColorStartUni).c_str(),
1009                                builder->getUniformVariable(fColorEndUni).c_str(),
1010                                gradientTValue);
1011         // Note that we could skip this step if both colors are known to be opaque. Two
1012         // considerations:
1013         // The gradient SkShader reporting opaque is more restrictive than necessary in the two pt
1014         // case. Make sure the key reflects this optimization (and note that it can use the same
1015         // shader as thekBeforeIterp case). This same optimization applies to the 3 color case below.
1016         if (GrGradientEffect::kAfterInterp_PremulType == ge.getPremulType()) {
1017             fsBuilder->codeAppend("\tcolorTemp.rgb *= colorTemp.a;\n");
1018         }
1019 
1020         fsBuilder->codeAppendf("\t%s = %s;\n", outputColor,
1021                                (GrGLSLExpr4(inputColor) * GrGLSLExpr4("colorTemp")).c_str());
1022     } else if (SkGradientShaderBase::kThree_GpuColorType == ge.getColorType()) {
1023         fsBuilder->codeAppendf("\tfloat oneMinus2t = 1.0 - (2.0 * (%s));\n",
1024                                gradientTValue);
1025         fsBuilder->codeAppendf("\tvec4 colorTemp = clamp(oneMinus2t, 0.0, 1.0) * %s;\n",
1026                                builder->getUniformVariable(fColorStartUni).c_str());
1027         if (kTegra3_GrGLRenderer == builder->ctxInfo().renderer()) {
1028             // The Tegra3 compiler will sometimes never return if we have
1029             // min(abs(oneMinus2t), 1.0), or do the abs first in a separate expression.
1030             fsBuilder->codeAppend("\tfloat minAbs = abs(oneMinus2t);\n");
1031             fsBuilder->codeAppend("\tminAbs = minAbs > 1.0 ? 1.0 : minAbs;\n");
1032             fsBuilder->codeAppendf("\tcolorTemp += (1.0 - minAbs) * %s;\n",
1033                                    builder->getUniformVariable(fColorMidUni).c_str());
1034         } else {
1035             fsBuilder->codeAppendf("\tcolorTemp += (1.0 - min(abs(oneMinus2t), 1.0)) * %s;\n",
1036                                    builder->getUniformVariable(fColorMidUni).c_str());
1037         }
1038         fsBuilder->codeAppendf("\tcolorTemp += clamp(-oneMinus2t, 0.0, 1.0) * %s;\n",
1039                                builder->getUniformVariable(fColorEndUni).c_str());
1040         if (GrGradientEffect::kAfterInterp_PremulType == ge.getPremulType()) {
1041             fsBuilder->codeAppend("\tcolorTemp.rgb *= colorTemp.a;\n");
1042         }
1043 
1044         fsBuilder->codeAppendf("\t%s = %s;\n", outputColor,
1045                                (GrGLSLExpr4(inputColor) * GrGLSLExpr4("colorTemp")).c_str());
1046     } else {
1047         fsBuilder->codeAppendf("\tvec2 coord = vec2(%s, %s);\n",
1048                                gradientTValue,
1049                                builder->getUniformVariable(fFSYUni).c_str());
1050         fsBuilder->codeAppendf("\t%s = ", outputColor);
1051         fsBuilder->appendTextureLookupAndModulate(inputColor,
1052                                                   samplers[0],
1053                                                   "coord");
1054         fsBuilder->codeAppend(";\n");
1055     }
1056 }
1057 
1058 /////////////////////////////////////////////////////////////////////
1059 
GrGradientEffect(GrContext * ctx,const SkGradientShaderBase & shader,const SkMatrix & matrix,SkShader::TileMode tileMode)1060 GrGradientEffect::GrGradientEffect(GrContext* ctx,
1061                                    const SkGradientShaderBase& shader,
1062                                    const SkMatrix& matrix,
1063                                    SkShader::TileMode tileMode) {
1064 
1065     fIsOpaque = shader.isOpaque();
1066 
1067     fColorType = shader.getGpuColorType(&fColors[0]);
1068 
1069     // The two and three color specializations do not currently support tiling.
1070     if (SkGradientShaderBase::kTwo_GpuColorType == fColorType ||
1071         SkGradientShaderBase::kThree_GpuColorType == fColorType) {
1072         fRow = -1;
1073 
1074         if (SkGradientShader::kInterpolateColorsInPremul_Flag & shader.getGradFlags()) {
1075             fPremulType = kBeforeInterp_PremulType;
1076         } else {
1077             fPremulType = kAfterInterp_PremulType;
1078         }
1079         fCoordTransform.reset(kCoordSet, matrix);
1080     } else {
1081         // doesn't matter how this is set, just be consistent because it is part of the effect key.
1082         fPremulType = kBeforeInterp_PremulType;
1083         SkBitmap bitmap;
1084         shader.getGradientTableBitmap(&bitmap);
1085 
1086         GrTextureStripAtlas::Desc desc;
1087         desc.fWidth  = bitmap.width();
1088         desc.fHeight = 32;
1089         desc.fRowHeight = bitmap.height();
1090         desc.fContext = ctx;
1091         desc.fConfig = SkImageInfo2GrPixelConfig(bitmap.info());
1092         fAtlas = GrTextureStripAtlas::GetAtlas(desc);
1093         SkASSERT(fAtlas);
1094 
1095         // We always filter the gradient table. Each table is one row of a texture, always y-clamp.
1096         GrTextureParams params;
1097         params.setFilterMode(GrTextureParams::kBilerp_FilterMode);
1098         params.setTileModeX(tileMode);
1099 
1100         fRow = fAtlas->lockRow(bitmap);
1101         if (-1 != fRow) {
1102             fYCoord = fAtlas->getYOffset(fRow) + SK_ScalarHalf * fAtlas->getNormalizedTexelHeight();
1103             fCoordTransform.reset(kCoordSet, matrix, fAtlas->getTexture(), params.filterMode());
1104             fTextureAccess.reset(fAtlas->getTexture(), params);
1105         } else {
1106             SkAutoTUnref<GrTexture> texture(GrRefCachedBitmapTexture(ctx, bitmap, &params));
1107             if (!texture) {
1108                 return;
1109             }
1110             fCoordTransform.reset(kCoordSet, matrix, texture, params.filterMode());
1111             fTextureAccess.reset(texture, params);
1112             fYCoord = SK_ScalarHalf;
1113         }
1114         this->addTextureAccess(&fTextureAccess);
1115     }
1116     this->addCoordTransform(&fCoordTransform);
1117 }
1118 
~GrGradientEffect()1119 GrGradientEffect::~GrGradientEffect() {
1120     if (this->useAtlas()) {
1121         fAtlas->unlockRow(fRow);
1122     }
1123 }
1124 
onIsEqual(const GrFragmentProcessor & processor) const1125 bool GrGradientEffect::onIsEqual(const GrFragmentProcessor& processor) const {
1126     const GrGradientEffect& s = processor.cast<GrGradientEffect>();
1127 
1128     if (this->fColorType == s.getColorType()){
1129 
1130         if (SkGradientShaderBase::kTwo_GpuColorType == fColorType) {
1131             if (*this->getColors(0) != *s.getColors(0) ||
1132                 *this->getColors(1) != *s.getColors(1)) {
1133                 return false;
1134             }
1135         } else if (SkGradientShaderBase::kThree_GpuColorType == fColorType) {
1136             if (*this->getColors(0) != *s.getColors(0) ||
1137                 *this->getColors(1) != *s.getColors(1) ||
1138                 *this->getColors(2) != *s.getColors(2)) {
1139                 return false;
1140             }
1141         } else {
1142             if (fYCoord != s.getYCoord()) {
1143                 return false;
1144             }
1145         }
1146 
1147         SkASSERT(this->useAtlas() == s.useAtlas());
1148         return true;
1149     }
1150 
1151     return false;
1152 }
1153 
onComputeInvariantOutput(GrInvariantOutput * inout) const1154 void GrGradientEffect::onComputeInvariantOutput(GrInvariantOutput* inout) const {
1155     if (fIsOpaque) {
1156         inout->mulByUnknownOpaqueFourComponents();
1157     } else {
1158         inout->mulByUnknownFourComponents();
1159     }
1160 }
1161 
RandomGradientParams(SkRandom * random,SkColor colors[],SkScalar ** stops,SkShader::TileMode * tm)1162 int GrGradientEffect::RandomGradientParams(SkRandom* random,
1163                                            SkColor colors[],
1164                                            SkScalar** stops,
1165                                            SkShader::TileMode* tm) {
1166     int outColors = random->nextRangeU(1, kMaxRandomGradientColors);
1167 
1168     // if one color, omit stops, otherwise randomly decide whether or not to
1169     if (outColors == 1 || (outColors >= 2 && random->nextBool())) {
1170         *stops = NULL;
1171     }
1172 
1173     SkScalar stop = 0.f;
1174     for (int i = 0; i < outColors; ++i) {
1175         colors[i] = random->nextU();
1176         if (*stops) {
1177             (*stops)[i] = stop;
1178             stop = i < outColors - 1 ? stop + random->nextUScalar1() * (1.f - stop) : 1.f;
1179         }
1180     }
1181     *tm = static_cast<SkShader::TileMode>(random->nextULessThan(SkShader::kTileModeCount));
1182 
1183     return outColors;
1184 }
1185 
1186 #endif
1187