TextureCache.cc 1.63 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
#include "TextureCache.h"

TextureCache::TextureCache(uint32_t _cacheSize)
    : cacheSize(_cacheSize)
    , imageCache(new WebImageCache(0, cacheSize))
{
    textures.resize(cacheSize);
    TexturePtr t;
    foreach(t, textures)
    {
        GLuint id;
        glGenTextures(1, &id);
        t->setID(id);
        glBindTexture(GL_TEXTURE_2D, id);
        glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    }
}

TexturePtr
TextureCache::get(const QString& tileURL)
{
    QPair<TexturePtr, int32_t> p1 = lookup(tileURL);
    if (!p1.first.isNull())
    {
        return p1.first;
    }

    QPair<WebImagePtr, int32_t> p2 = imageCache->lookup(tileURL);
    if (!p2.first.isNull())
    {
        textures[p2.second]->sync(p2.first);
        p1 = lookup(tileURL);

        return p1.first;
    }

    return TexturePtr();
}

void
TextureCache::sync(void)
{
    if (requireSync())
    {
        for (int32_t i = 0; i < textures.size(); ++i)
        {
            textures[i]->sync(imageCache->at(i));
        }
    }
}

QPair<TexturePtr, int32_t>
TextureCache::lookup(const QString& tileURL)
{
    for (int32_t i = 0; i < textures.size(); ++i)
    {
        if (textures[i]->getSourceURL() == tileURL)
        {
            return qMakePair(textures[i], i);
        }
    }

    return qMakePair(TexturePtr(), -1);
}

bool
TextureCache::requireSync(void) const
{
    for (uint32_t i = 0; i < cacheSize; ++i)
    {
        if (imageCache->at(i)->getSyncFlag())
        {
            return true;
        }
    }
    return false;
}