GradientCache.cpp revision 6183c97e5f317ad52ad16fe50e40129e2c7b2150
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        , mHasLinearBlending(extensions.hasLinearBlending()) {
72    glGetIntegerv(GL_MAX_TEXTURE_SIZE, &mMaxTextureSize);
73
74    mCache.setOnEntryRemovedListener(this);
75}
76
77GradientCache::~GradientCache() {
78    mCache.clear();
79}
80
81///////////////////////////////////////////////////////////////////////////////
82// Size management
83///////////////////////////////////////////////////////////////////////////////
84
85uint32_t GradientCache::getSize() {
86    return mSize;
87}
88
89uint32_t GradientCache::getMaxSize() {
90    return mMaxSize;
91}
92
93///////////////////////////////////////////////////////////////////////////////
94// Callbacks
95///////////////////////////////////////////////////////////////////////////////
96
97void GradientCache::operator()(GradientCacheEntry&, Texture*& texture) {
98    if (texture) {
99        mSize -= texture->objectSize();
100        texture->deleteTexture();
101        delete texture;
102    }
103}
104
105///////////////////////////////////////////////////////////////////////////////
106// Caching
107///////////////////////////////////////////////////////////////////////////////
108
109Texture* GradientCache::get(uint32_t* colors, float* positions, int count) {
110    GradientCacheEntry gradient(colors, positions, count);
111    Texture* texture = mCache.get(gradient);
112
113    if (!texture) {
114        texture = addLinearGradient(gradient, colors, positions, count);
115    }
116
117    return texture;
118}
119
120void GradientCache::clear() {
121    mCache.clear();
122}
123
124void GradientCache::getGradientInfo(const uint32_t* colors, const int count,
125        GradientInfo& info) {
126    uint32_t width = 256 * (count - 1);
127
128    // If the npot extension is not supported we cannot use non-clamp
129    // wrap modes. We therefore find the nearest largest power of 2
130    // unless width is already a power of 2
131    if (!mHasNpot && (width & (width - 1)) != 0) {
132        width = 1 << (32 - __builtin_clz(width));
133    }
134
135    bool hasAlpha = false;
136    for (int i = 0; i < count; i++) {
137        if (((colors[i] >> 24) & 0xff) < 255) {
138            hasAlpha = true;
139            break;
140        }
141    }
142
143    info.width = min(width, uint32_t(mMaxTextureSize));
144    info.hasAlpha = hasAlpha;
145}
146
147Texture* GradientCache::addLinearGradient(GradientCacheEntry& gradient,
148        uint32_t* colors, float* positions, int count) {
149
150    GradientInfo info;
151    getGradientInfo(colors, count, info);
152
153    Texture* texture = new Texture(Caches::getInstance());
154    texture->blend = info.hasAlpha;
155    texture->generation = 1;
156
157    // Assume the cache is always big enough
158    const uint32_t size = info.width * 2 * bytesPerPixel();
159    while (getSize() + size > mMaxSize) {
160        LOG_ALWAYS_FATAL_IF(!mCache.removeOldest(),
161                "Ran out of things to remove from the cache? getSize() = %" PRIu32
162                ", size = %" PRIu32 ", mMaxSize = %" PRIu32 ", width = %" PRIu32,
163                getSize(), size, mMaxSize, info.width);
164    }
165
166    generateTexture(colors, positions, info.width, 2, texture);
167
168    mSize += size;
169    LOG_ALWAYS_FATAL_IF((int)size != texture->objectSize(),
170            "size != texture->objectSize(), size %" PRIu32 ", objectSize %d"
171            " width = %" PRIu32 " bytesPerPixel() = %zu",
172            size, texture->objectSize(), info.width, bytesPerPixel());
173    mCache.put(gradient, texture);
174
175    return texture;
176}
177
178size_t GradientCache::bytesPerPixel() const {
179    // We use 4 channels (RGBA)
180    return 4 * (mUseFloatTexture ? /* fp16 */ 2 : sizeof(uint8_t));
181}
182
183size_t GradientCache::sourceBytesPerPixel() const {
184    // We use 4 channels (RGBA) and upload from floats (not half floats)
185    return 4 * (mUseFloatTexture ? sizeof(float) : sizeof(uint8_t));
186}
187
188void GradientCache::mixBytes(const FloatColor& start, const FloatColor& end,
189        float amount, uint8_t*& dst) const {
190    float oppAmount = 1.0f - amount;
191    float a = start.a * oppAmount + end.a * amount;
192    *dst++ = uint8_t(a * OECF(start.r * oppAmount + end.r * amount) * 255.0f);
193    *dst++ = uint8_t(a * OECF(start.g * oppAmount + end.g * amount) * 255.0f);
194    *dst++ = uint8_t(a * OECF(start.b * oppAmount + end.b * amount) * 255.0f);
195    *dst++ = uint8_t(a * 255.0f);
196}
197
198void GradientCache::mixFloats(const FloatColor& start, const FloatColor& end,
199        float amount, uint8_t*& dst) const {
200    float oppAmount = 1.0f - amount;
201    float a = start.a * oppAmount + end.a * amount;
202    float* d = (float*) dst;
203#ifdef ANDROID_ENABLE_LINEAR_BLENDING
204    // We want to stay linear
205    *d++ = a * (start.r * oppAmount + end.r * amount);
206    *d++ = a * (start.g * oppAmount + end.g * amount);
207    *d++ = a * (start.b * oppAmount + end.b * amount);
208#else
209    *d++ = a * OECF(start.r * oppAmount + end.r * amount);
210    *d++ = a * OECF(start.g * oppAmount + end.g * amount);
211    *d++ = a * OECF(start.b * oppAmount + end.b * amount);
212#endif
213    *d++ = a;
214    dst += 4 * sizeof(float);
215}
216
217void GradientCache::generateTexture(uint32_t* colors, float* positions,
218        const uint32_t width, const uint32_t height, Texture* texture) {
219    const GLsizei rowBytes = width * sourceBytesPerPixel();
220    uint8_t pixels[rowBytes * height];
221
222    static ChannelMixer gMixers[] = {
223            // colors are stored gamma-encoded
224            &android::uirenderer::GradientCache::mixBytes,
225            // colors are stored in linear (linear blending on)
226            // or gamma-encoded (linear blending off)
227            &android::uirenderer::GradientCache::mixFloats,
228    };
229    ChannelMixer mix = gMixers[mUseFloatTexture];
230
231    FloatColor start;
232    start.setUnPreMultiplied(colors[0]);
233
234    FloatColor end;
235    end.setUnPreMultiplied(colors[1]);
236
237    int currentPos = 1;
238    float startPos = positions[0];
239    float distance = positions[1] - startPos;
240
241    uint8_t* dst = pixels;
242    for (uint32_t x = 0; x < width; x++) {
243        float pos = x / float(width - 1);
244        if (pos > positions[currentPos]) {
245            start = end;
246            startPos = positions[currentPos];
247
248            currentPos++;
249
250            end.setUnPreMultiplied(colors[currentPos]);
251            distance = positions[currentPos] - startPos;
252        }
253
254        float amount = (pos - startPos) / distance;
255        (this->*mix)(start, end, amount, dst);
256    }
257
258    memcpy(pixels + rowBytes, pixels, rowBytes);
259
260    if (mUseFloatTexture) {
261        texture->upload(GL_RGBA16F, width, height, GL_RGBA, GL_FLOAT, pixels);
262    } else {
263        GLint internalFormat = mHasLinearBlending ? GL_SRGB8_ALPHA8 : GL_RGBA;
264        texture->upload(internalFormat, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
265    }
266
267    texture->setFilter(GL_LINEAR);
268    texture->setWrap(GL_CLAMP_TO_EDGE);
269}
270
271}; // namespace uirenderer
272}; // namespace android
273