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