GradientCache.cpp revision 2de7771740ee08fcaff638ec6b2e460bb72fff04
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(MB(DEFAULT_GRADIENT_CACHE_SIZE))
69        , mUseFloatTexture(extensions.hasFloatTextures())
70        , mHasNpot(extensions.hasNPot()){
71    char property[PROPERTY_VALUE_MAX];
72    if (property_get(PROPERTY_GRADIENT_CACHE_SIZE, property, nullptr) > 0) {
73        INIT_LOGD("  Setting gradient cache size to %sMB", property);
74        setMaxSize(MB(atof(property)));
75    } else {
76        INIT_LOGD("  Using default gradient cache size of %.2fMB", DEFAULT_GRADIENT_CACHE_SIZE);
77    }
78
79    glGetIntegerv(GL_MAX_TEXTURE_SIZE, &mMaxTextureSize);
80
81    mCache.setOnEntryRemovedListener(this);
82}
83
84GradientCache::~GradientCache() {
85    mCache.clear();
86}
87
88///////////////////////////////////////////////////////////////////////////////
89// Size management
90///////////////////////////////////////////////////////////////////////////////
91
92uint32_t GradientCache::getSize() {
93    return mSize;
94}
95
96uint32_t GradientCache::getMaxSize() {
97    return mMaxSize;
98}
99
100void GradientCache::setMaxSize(uint32_t maxSize) {
101    mMaxSize = maxSize;
102    while (mSize > mMaxSize) {
103        mCache.removeOldest();
104    }
105}
106
107///////////////////////////////////////////////////////////////////////////////
108// Callbacks
109///////////////////////////////////////////////////////////////////////////////
110
111void GradientCache::operator()(GradientCacheEntry&, Texture*& texture) {
112    if (texture) {
113        mSize -= texture->objectSize();
114        texture->deleteTexture();
115        delete texture;
116    }
117}
118
119///////////////////////////////////////////////////////////////////////////////
120// Caching
121///////////////////////////////////////////////////////////////////////////////
122
123Texture* GradientCache::get(uint32_t* colors, float* positions, int count) {
124    GradientCacheEntry gradient(colors, positions, count);
125    Texture* texture = mCache.get(gradient);
126
127    if (!texture) {
128        texture = addLinearGradient(gradient, colors, positions, count);
129    }
130
131    return texture;
132}
133
134void GradientCache::clear() {
135    mCache.clear();
136}
137
138void GradientCache::getGradientInfo(const uint32_t* colors, const int count,
139        GradientInfo& info) {
140    uint32_t width = 256 * (count - 1);
141
142    // If the npot extension is not supported we cannot use non-clamp
143    // wrap modes. We therefore find the nearest largest power of 2
144    // unless width is already a power of 2
145    if (!mHasNpot && (width & (width - 1)) != 0) {
146        width = 1 << (32 - __builtin_clz(width));
147    }
148
149    bool hasAlpha = false;
150    for (int i = 0; i < count; i++) {
151        if (((colors[i] >> 24) & 0xff) < 255) {
152            hasAlpha = true;
153            break;
154        }
155    }
156
157    info.width = min(width, uint32_t(mMaxTextureSize));
158    info.hasAlpha = hasAlpha;
159}
160
161Texture* GradientCache::addLinearGradient(GradientCacheEntry& gradient,
162        uint32_t* colors, float* positions, int count) {
163
164    GradientInfo info;
165    getGradientInfo(colors, count, info);
166
167    Texture* texture = new Texture(Caches::getInstance());
168    texture->blend = info.hasAlpha;
169    texture->generation = 1;
170
171    // Asume the cache is always big enough
172    const uint32_t size = info.width * 2 * bytesPerPixel();
173    while (getSize() + size > mMaxSize) {
174        mCache.removeOldest();
175    }
176
177    generateTexture(colors, positions, info.width, 2, texture);
178
179    mSize += size;
180    mCache.put(gradient, texture);
181
182    return texture;
183}
184
185size_t GradientCache::bytesPerPixel() const {
186    // We use 4 channels (RGBA)
187    return 4 * (mUseFloatTexture ? sizeof(float) : sizeof(uint8_t));
188}
189
190void GradientCache::splitToBytes(uint32_t inColor, GradientColor& outColor) const {
191    outColor.r = (inColor >> 16) & 0xff;
192    outColor.g = (inColor >>  8) & 0xff;
193    outColor.b = (inColor >>  0) & 0xff;
194    outColor.a = (inColor >> 24) & 0xff;
195}
196
197void GradientCache::splitToFloats(uint32_t inColor, GradientColor& outColor) const {
198    outColor.r = ((inColor >> 16) & 0xff) / 255.0f;
199    outColor.g = ((inColor >>  8) & 0xff) / 255.0f;
200    outColor.b = ((inColor >>  0) & 0xff) / 255.0f;
201    outColor.a = ((inColor >> 24) & 0xff) / 255.0f;
202}
203
204void GradientCache::mixBytes(GradientColor& start, GradientColor& end, float amount,
205        uint8_t*& dst) const {
206    float oppAmount = 1.0f - amount;
207    const float alpha = start.a * oppAmount + end.a * amount;
208    const float a = alpha / 255.0f;
209
210    *dst++ = uint8_t(a * (start.r * oppAmount + end.r * amount));
211    *dst++ = uint8_t(a * (start.g * oppAmount + end.g * amount));
212    *dst++ = uint8_t(a * (start.b * oppAmount + end.b * amount));
213    *dst++ = uint8_t(alpha);
214}
215
216void GradientCache::mixFloats(GradientColor& start, GradientColor& end, float amount,
217        uint8_t*& dst) const {
218    float oppAmount = 1.0f - amount;
219    const float a = start.a * oppAmount + end.a * amount;
220
221    float* d = (float*) dst;
222    *d++ = a * (start.r * oppAmount + end.r * amount);
223    *d++ = a * (start.g * oppAmount + end.g * amount);
224    *d++ = a * (start.b * oppAmount + end.b * amount);
225    *d++ = a;
226
227    dst += 4 * sizeof(float);
228}
229
230void GradientCache::generateTexture(uint32_t* colors, float* positions,
231        const uint32_t width, const uint32_t height, Texture* texture) {
232    const GLsizei rowBytes = width * bytesPerPixel();
233    uint8_t pixels[rowBytes * height];
234
235    static ChannelSplitter gSplitters[] = {
236            &android::uirenderer::GradientCache::splitToBytes,
237            &android::uirenderer::GradientCache::splitToFloats,
238    };
239    ChannelSplitter split = gSplitters[mUseFloatTexture];
240
241    static ChannelMixer gMixers[] = {
242            &android::uirenderer::GradientCache::mixBytes,
243            &android::uirenderer::GradientCache::mixFloats,
244    };
245    ChannelMixer mix = gMixers[mUseFloatTexture];
246
247    GradientColor start;
248    (this->*split)(colors[0], start);
249
250    GradientColor end;
251    (this->*split)(colors[1], end);
252
253    int currentPos = 1;
254    float startPos = positions[0];
255    float distance = positions[1] - startPos;
256
257    uint8_t* dst = pixels;
258    for (uint32_t x = 0; x < width; x++) {
259        float pos = x / float(width - 1);
260        if (pos > positions[currentPos]) {
261            start = end;
262            startPos = positions[currentPos];
263
264            currentPos++;
265
266            (this->*split)(colors[currentPos], end);
267            distance = positions[currentPos] - startPos;
268        }
269
270        float amount = (pos - startPos) / distance;
271        (this->*mix)(start, end, amount, dst);
272    }
273
274    memcpy(pixels + rowBytes, pixels, rowBytes);
275
276    if (mUseFloatTexture) {
277        // We have to use GL_RGBA16F because GL_RGBA32F does not support filtering
278        texture->upload(GL_RGBA16F, width, height, GL_RGBA, GL_FLOAT, pixels);
279    } else {
280        texture->upload(GL_RGBA, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
281    }
282
283    texture->setFilter(GL_LINEAR);
284    texture->setWrap(GL_CLAMP_TO_EDGE);
285}
286
287}; // namespace uirenderer
288}; // namespace android
289