GradientCache.cpp revision 48a8f431fa52ae2ee25ffba9d20676f03bb710ff
1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <utils/JenkinsHash.h>
18
19#include "Caches.h"
20#include "Debug.h"
21#include "GradientCache.h"
22#include "Properties.h"
23
24#include <cutils/properties.h>
25
26namespace android {
27namespace uirenderer {
28
29///////////////////////////////////////////////////////////////////////////////
30// Functions
31///////////////////////////////////////////////////////////////////////////////
32
33template<typename T>
34static inline T min(T a, T b) {
35    return a < b ? a : b;
36}
37
38///////////////////////////////////////////////////////////////////////////////
39// Cache entry
40///////////////////////////////////////////////////////////////////////////////
41
42hash_t GradientCacheEntry::hash() const {
43    uint32_t hash = JenkinsHashMix(0, count);
44    for (uint32_t i = 0; i < count; i++) {
45        hash = JenkinsHashMix(hash, android::hash_type(colors[i]));
46        hash = JenkinsHashMix(hash, android::hash_type(positions[i]));
47    }
48    return JenkinsHashWhiten(hash);
49}
50
51int GradientCacheEntry::compare(const GradientCacheEntry& lhs, const GradientCacheEntry& rhs) {
52    int deltaInt = int(lhs.count) - int(rhs.count);
53    if (deltaInt != 0) return deltaInt;
54
55    deltaInt = memcmp(lhs.colors.get(), rhs.colors.get(), lhs.count * sizeof(uint32_t));
56    if (deltaInt != 0) return deltaInt;
57
58    return memcmp(lhs.positions.get(), rhs.positions.get(), lhs.count * sizeof(float));
59}
60
61///////////////////////////////////////////////////////////////////////////////
62// Constructors/destructor
63///////////////////////////////////////////////////////////////////////////////
64
65GradientCache::GradientCache(Extensions& extensions)
66        : mCache(LruCache<GradientCacheEntry, Texture*>::kUnlimitedCapacity)
67        , mSize(0)
68        , mMaxSize(Properties::gradientCacheSize)
69        , mUseFloatTexture(extensions.hasFloatTextures())
70        , mHasNpot(extensions.hasNPot()){
71    glGetIntegerv(GL_MAX_TEXTURE_SIZE, &mMaxTextureSize);
72
73    mCache.setOnEntryRemovedListener(this);
74}
75
76GradientCache::~GradientCache() {
77    mCache.clear();
78}
79
80///////////////////////////////////////////////////////////////////////////////
81// Size management
82///////////////////////////////////////////////////////////////////////////////
83
84uint32_t GradientCache::getSize() {
85    return mSize;
86}
87
88uint32_t GradientCache::getMaxSize() {
89    return mMaxSize;
90}
91
92///////////////////////////////////////////////////////////////////////////////
93// Callbacks
94///////////////////////////////////////////////////////////////////////////////
95
96void GradientCache::operator()(GradientCacheEntry&, Texture*& texture) {
97    if (texture) {
98        mSize -= texture->objectSize();
99        texture->deleteTexture();
100        delete texture;
101    }
102}
103
104///////////////////////////////////////////////////////////////////////////////
105// Caching
106///////////////////////////////////////////////////////////////////////////////
107
108Texture* GradientCache::get(uint32_t* colors, float* positions, int count) {
109    GradientCacheEntry gradient(colors, positions, count);
110    Texture* texture = mCache.get(gradient);
111
112    if (!texture) {
113        texture = addLinearGradient(gradient, colors, positions, count);
114    }
115
116    return texture;
117}
118
119void GradientCache::clear() {
120    mCache.clear();
121}
122
123void GradientCache::getGradientInfo(const uint32_t* colors, const int count,
124        GradientInfo& info) {
125    uint32_t width = 256 * (count - 1);
126
127    // If the npot extension is not supported we cannot use non-clamp
128    // wrap modes. We therefore find the nearest largest power of 2
129    // unless width is already a power of 2
130    if (!mHasNpot && (width & (width - 1)) != 0) {
131        width = 1 << (32 - __builtin_clz(width));
132    }
133
134    bool hasAlpha = false;
135    for (int i = 0; i < count; i++) {
136        if (((colors[i] >> 24) & 0xff) < 255) {
137            hasAlpha = true;
138            break;
139        }
140    }
141
142    info.width = min(width, uint32_t(mMaxTextureSize));
143    info.hasAlpha = hasAlpha;
144}
145
146Texture* GradientCache::addLinearGradient(GradientCacheEntry& gradient,
147        uint32_t* colors, float* positions, int count) {
148
149    GradientInfo info;
150    getGradientInfo(colors, count, info);
151
152    Texture* texture = new Texture(Caches::getInstance());
153    texture->blend = info.hasAlpha;
154    texture->generation = 1;
155
156    // Asume the cache is always big enough
157    const uint32_t size = info.width * 2 * bytesPerPixel();
158    while (getSize() + size > mMaxSize) {
159        mCache.removeOldest();
160    }
161
162    generateTexture(colors, positions, info.width, 2, texture);
163
164    mSize += size;
165    mCache.put(gradient, texture);
166
167    return texture;
168}
169
170size_t GradientCache::bytesPerPixel() const {
171    // We use 4 channels (RGBA)
172    return 4 * (mUseFloatTexture ? sizeof(float) : sizeof(uint8_t));
173}
174
175void GradientCache::splitToBytes(uint32_t inColor, GradientColor& outColor) const {
176    outColor.r = (inColor >> 16) & 0xff;
177    outColor.g = (inColor >>  8) & 0xff;
178    outColor.b = (inColor >>  0) & 0xff;
179    outColor.a = (inColor >> 24) & 0xff;
180}
181
182void GradientCache::splitToFloats(uint32_t inColor, GradientColor& outColor) const {
183    outColor.r = ((inColor >> 16) & 0xff) / 255.0f;
184    outColor.g = ((inColor >>  8) & 0xff) / 255.0f;
185    outColor.b = ((inColor >>  0) & 0xff) / 255.0f;
186    outColor.a = ((inColor >> 24) & 0xff) / 255.0f;
187}
188
189void GradientCache::mixBytes(GradientColor& start, GradientColor& end, float amount,
190        uint8_t*& dst) const {
191    float oppAmount = 1.0f - amount;
192    const float alpha = start.a * oppAmount + end.a * amount;
193    const float a = alpha / 255.0f;
194
195    *dst++ = uint8_t(a * (start.r * oppAmount + end.r * amount));
196    *dst++ = uint8_t(a * (start.g * oppAmount + end.g * amount));
197    *dst++ = uint8_t(a * (start.b * oppAmount + end.b * amount));
198    *dst++ = uint8_t(alpha);
199}
200
201void GradientCache::mixFloats(GradientColor& start, GradientColor& end, float amount,
202        uint8_t*& dst) const {
203    float oppAmount = 1.0f - amount;
204    const float a = start.a * oppAmount + end.a * amount;
205
206    float* d = (float*) dst;
207    *d++ = a * (start.r * oppAmount + end.r * amount);
208    *d++ = a * (start.g * oppAmount + end.g * amount);
209    *d++ = a * (start.b * oppAmount + end.b * amount);
210    *d++ = a;
211
212    dst += 4 * sizeof(float);
213}
214
215void GradientCache::generateTexture(uint32_t* colors, float* positions,
216        const uint32_t width, const uint32_t height, Texture* texture) {
217    const GLsizei rowBytes = width * bytesPerPixel();
218    uint8_t pixels[rowBytes * height];
219
220    static ChannelSplitter gSplitters[] = {
221            &android::uirenderer::GradientCache::splitToBytes,
222            &android::uirenderer::GradientCache::splitToFloats,
223    };
224    ChannelSplitter split = gSplitters[mUseFloatTexture];
225
226    static ChannelMixer gMixers[] = {
227            &android::uirenderer::GradientCache::mixBytes,
228            &android::uirenderer::GradientCache::mixFloats,
229    };
230    ChannelMixer mix = gMixers[mUseFloatTexture];
231
232    GradientColor start;
233    (this->*split)(colors[0], start);
234
235    GradientColor end;
236    (this->*split)(colors[1], end);
237
238    int currentPos = 1;
239    float startPos = positions[0];
240    float distance = positions[1] - startPos;
241
242    uint8_t* dst = pixels;
243    for (uint32_t x = 0; x < width; x++) {
244        float pos = x / float(width - 1);
245        if (pos > positions[currentPos]) {
246            start = end;
247            startPos = positions[currentPos];
248
249            currentPos++;
250
251            (this->*split)(colors[currentPos], end);
252            distance = positions[currentPos] - startPos;
253        }
254
255        float amount = (pos - startPos) / distance;
256        (this->*mix)(start, end, amount, dst);
257    }
258
259    memcpy(pixels + rowBytes, pixels, rowBytes);
260
261    if (mUseFloatTexture) {
262        // We have to use GL_RGBA16F because GL_RGBA32F does not support filtering
263        texture->upload(GL_RGBA16F, width, height, GL_RGBA, GL_FLOAT, pixels);
264    } else {
265        texture->upload(GL_RGBA, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
266    }
267
268    texture->setFilter(GL_LINEAR);
269    texture->setWrap(GL_CLAMP_TO_EDGE);
270}
271
272}; // namespace uirenderer
273}; // namespace android
274