texturemanager.cpp 8.42 KB
Newer Older
Jakob Weiss's avatar
Jakob Weiss committed
1
2
3
#include "texturemanager.h"
#include "texture.h"
#include "singleton.h"
Jakob Weiss's avatar
Jakob Weiss committed
4
#include "gltextureformattraits.h"
Jakob Weiss's avatar
Jakob Weiss committed
5
6


Jakob Weiss's avatar
Jakob Weiss committed
7
8
9
10
11
12
13
14
15
16
17
18
19
20
namespace {
    /// private class to format iostream to use points as a thousands separator
    class PointSeparator : public std::numpunct<char>
    {
    public:
        PointSeparator(std::size_t refs) : std::numpunct<char>(refs) {}
    protected:
        char do_thousands_sep() const { return '.'; }
        std::string do_grouping() const { return "\03"; }
    };
}

const std::string cgt::TextureManager::loggerCat_("cgt.TextureManager");

Jakob Weiss's avatar
Jakob Weiss committed
21
cgt::TextureManager::TextureManager()
Jakob Weiss's avatar
Jakob Weiss committed
22
23
24
    : RunnableWithConditionalWait("Texture Manager")
    , activeAllocatedMemory_(0)
    , texturePoolMemory_(0)
Jakob Weiss's avatar
Jakob Weiss committed
25
{
Jakob Weiss's avatar
Jakob Weiss committed
26
27
28
29
#ifdef ENABLE_TEXTURE_POOL
    // start the garbage collection thread
    start();
#endif ENABLE_TEXTURE_POOl
Jakob Weiss's avatar
Jakob Weiss committed
30
31
32
33
}

cgt::TextureManager::~TextureManager()
{
Jakob Weiss's avatar
Jakob Weiss committed
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#ifdef ENABLE_TEXTURE_POOL
    // stop the GC thread and clear the pool
    stop();
    forceClearPool();
#endif ENABLE_TEXTURE_POOL

    cgtAssert(texturePool_.empty(), "Texture pool not empty at the end of texture manager's life!");
    cgtAssert(activeAllocatedMemory_ == 0, "There are still Textures in use after the Texture Manager is destroyed! This most likely means you are leaking cgt::Texture instances!");
}

void cgt::TextureManager::clearPool()
{
    std::stringstream dbgOut;
    dbgOut.imbue(std::locale(std::cout.getloc(), new PointSeparator(1)));

    dbgOut << texturePoolMemory_ << " Bytes of in texture pool, additionally " << activeAllocatedMemory_ << " Bytes still in use.";
    LDEBUG(dbgOut.str());
    LDEBUG("releasing texture pool with " << texturePool_.size() << " textures...");
    size_t totalBytes = 0;

    std::stringstream ss;
    for (auto& it : texturePool_)
    {
        auto tft = GLTextureFormatTraits::get(std::get<INTERNAL_FORMAT>(it.first));
        cgt::svec3 size(std::get<SIZE_X>(it.first), std::get<SIZE_Y>(it.first), std::get<SIZE_Z>(it.first));
        GLenum textureType = std::get<TEX_TYPE>(it.first);
        ss << "\t * [" << size.x << "," << size.y << "," << size.z
            << "] " << textureTypeToStr(textureType) << " " << tft.internalFormatName() << std::endl;

        glDeleteTextures(1, &it.second);

        totalBytes += textureByteSize(it.first);
        texturePoolMemory_ -= textureByteSize(it.first);
    }
    texturePool_.clear();

    std::stringstream ss3;
    ss3 << "Released " << totalBytes << " Bytes of texture data:" << std::endl << ss.str();
    LDEBUG(ss3.str());
}

void cgt::TextureManager::performGarbageCollection()
{
    std::stringstream dbgOut;
    dbgOut.imbue(std::locale(std::cout.getloc(), new PointSeparator(1)));

    dbgOut << texturePoolMemory_ << " Bytes of in texture pool, additionally " << activeAllocatedMemory_ << " Bytes still in use.";
    LDEBUG(dbgOut.str());
    LDEBUG("releasing texture pool with " << texturePool_.size() << " textures...");
    size_t totalBytes = 0;

    std::stringstream ss;
    for (auto& it : texturePool_)
    {
        auto tft = GLTextureFormatTraits::get(std::get<INTERNAL_FORMAT>(it.first));
        cgt::svec3 size(std::get<SIZE_X>(it.first), std::get<SIZE_Y>(it.first), std::get<SIZE_Z>(it.first));
        GLenum textureType = std::get<TEX_TYPE>(it.first);
        ss << "\t * [" << size.x << "," << size.y << "," << size.z
            << "] " << textureTypeToStr(textureType) << " " << tft.internalFormatName() << std::endl;

Jakob Weiss's avatar
Jakob Weiss committed
94
        glDeleteTextures(1, &it.second);
Jakob Weiss's avatar
Jakob Weiss committed
95
96
97

        totalBytes += textureByteSize(it.first);
        texturePoolMemory_ -= textureByteSize(it.first);
Jakob Weiss's avatar
Jakob Weiss committed
98
    }
Jakob Weiss's avatar
Jakob Weiss committed
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
    texturePool_.clear();

    std::stringstream ss3;
    ss3 << "Released " << totalBytes << " Bytes of texture data:" << std::endl << ss.str();
    LDEBUG(ss3.str());
}

void cgt::TextureManager::forceGarbageCollection()
{
#ifdef ENABLE_TEXTURE_POOL
    std::lock_guard<std::mutex> scope_lock(accessMutex_);

    performGarbageCollection();
#endif ENABLE_TEXTURE_POOL
}

void cgt::TextureManager::forceClearPool()
{
#ifdef ENABLE_TEXTURE_POOL
    std::lock_guard<std::mutex> scope_lock(accessMutex_);

    clearPool();
#endif ENABLE_TEXTURE_POOL
Jakob Weiss's avatar
Jakob Weiss committed
122
123
124
125
}

GLuint cgt::TextureManager::generateId(GLenum type, const cgt::svec3 & dimensions, GLenum internalFormat)
{
Jakob Weiss's avatar
Jakob Weiss committed
126
127
    cache_key_t cacheKey(type, dimensions.x, dimensions.y, dimensions.z, internalFormat);

Jakob Weiss's avatar
Jakob Weiss committed
128
129
130
131
#ifdef ENABLE_TEXTURE_POOL
    std::lock_guard<std::mutex> scope_lock(accessMutex_);

    GLuint id;
Jakob Weiss's avatar
Jakob Weiss committed
132
    auto it = texturePool_.find(cacheKey);
Jakob Weiss's avatar
Jakob Weiss committed
133
134
135
    if (it != texturePool_.end()) {
        id = it->second;
        texturePool_.erase(it);
Jakob Weiss's avatar
Jakob Weiss committed
136
137
138

        activeAllocatedMemory_ += textureByteSize(cacheKey);
        texturePoolMemory_ -= textureByteSize(cacheKey);
Jakob Weiss's avatar
Jakob Weiss committed
139
140
141
142
143
144
145
146
    }
    else {
        glGenTextures(1, &id);

        glBindTexture(type, id);

        switch (type) {
        case GL_TEXTURE_1D:
Jakob Weiss's avatar
Jakob Weiss committed
147
148
            glTexImage1D(type, 0, internalFormat, static_cast<GLsizei>(dimensions.x), 0, 
                Texture::calcMatchingPixelFormat(internalFormat), Texture::calcMatchingPixelDataType(internalFormat), nullptr);
Jakob Weiss's avatar
Jakob Weiss committed
149
150
151
152
            break;

        case GL_TEXTURE_1D_ARRAY: // fallthrough
        case GL_TEXTURE_2D:
Jakob Weiss's avatar
Jakob Weiss committed
153
154
            glTexImage2D(type, 0, internalFormat, static_cast<GLsizei>(dimensions.x), static_cast<GLsizei>(dimensions.y), 0, 
                Texture::calcMatchingPixelFormat(internalFormat), Texture::calcMatchingPixelDataType(internalFormat), nullptr);
Jakob Weiss's avatar
Jakob Weiss committed
155
156
157
158
            break;

        case GL_TEXTURE_2D_ARRAY: // fallthrough
        case GL_TEXTURE_3D:
Jakob Weiss's avatar
Jakob Weiss committed
159
160
            glTexImage3D(type, 0, internalFormat, static_cast<GLsizei>(dimensions.x), static_cast<GLsizei>(dimensions.y), static_cast<GLsizei>(dimensions.z), 0, 
                Texture::calcMatchingPixelFormat(internalFormat), Texture::calcMatchingPixelDataType(internalFormat), nullptr);
Jakob Weiss's avatar
Jakob Weiss committed
161
162
163
            break;
        }
        LGL_ERROR;
Jakob Weiss's avatar
Jakob Weiss committed
164
165

        activeAllocatedMemory_ += textureByteSize(cacheKey);
Jakob Weiss's avatar
Jakob Weiss committed
166
167
168
169
170
171
172
173
174
    }
#else
    GLuint id;
    glGenTextures(1, &id);

    glBindTexture(type, id);

    switch (type) {
    case GL_TEXTURE_1D:
Jakob Weiss's avatar
Jakob Weiss committed
175
        glTexImage1D(type, 0, internalFormat, static_cast<GLsizei>(dimensions.x), 0,
Jakob Weiss's avatar
Jakob Weiss committed
176
            Texture::calcMatchingPixelFormat(internalFormat), Texture::calcMatchingPixelDataType(internalFormat), nullptr);
Jakob Weiss's avatar
Jakob Weiss committed
177
178
179
180
        break;

    case GL_TEXTURE_1D_ARRAY: // fallthrough
    case GL_TEXTURE_2D:
Jakob Weiss's avatar
Jakob Weiss committed
181
        glTexImage2D(type, 0, internalFormat, static_cast<GLsizei>(dimensions.x), static_cast<GLsizei>(dimensions.y), 0,
Jakob Weiss's avatar
Jakob Weiss committed
182
            Texture::calcMatchingPixelFormat(internalFormat), Texture::calcMatchingPixelDataType(internalFormat), nullptr);
Jakob Weiss's avatar
Jakob Weiss committed
183
184
185
186
        break;

    case GL_TEXTURE_2D_ARRAY: // fallthrough
    case GL_TEXTURE_3D:
Jakob Weiss's avatar
Jakob Weiss committed
187
        glTexImage3D(type, 0, internalFormat, static_cast<GLsizei>(dimensions.x), static_cast<GLsizei>(dimensions.y), static_cast<GLsizei>(dimensions.z), 0,
Jakob Weiss's avatar
Jakob Weiss committed
188
            Texture::calcMatchingPixelFormat(internalFormat), Texture::calcMatchingPixelDataType(internalFormat), nullptr);
Jakob Weiss's avatar
Jakob Weiss committed
189
190
191
        break;
    }
    LGL_ERROR;
Jakob Weiss's avatar
Jakob Weiss committed
192
193
194

    activeAllocatedMemory_ += textureByteSize(cacheKey);

Jakob Weiss's avatar
Jakob Weiss committed
195
196
197
198
199
200
#endif
    return id;
}

void cgt::TextureManager::releaseId(GLuint id, GLenum type, const cgt::svec3 & dimensions, GLenum internalFormat)
{
201
    cache_key_t cacheKey(type, dimensions.x, dimensions.y, dimensions.z, internalFormat);
Jakob Weiss's avatar
Jakob Weiss committed
202
203
#ifdef ENABLE_TEXTURE_POOL
    std::lock_guard<std::mutex> scope_lock(accessMutex_);
Jakob Weiss's avatar
Jakob Weiss committed
204
205
206
    texturePool_.insert(std::make_pair(cacheKey, id));
    activeAllocatedMemory_ -= textureByteSize(cacheKey);
    texturePoolMemory_ += textureByteSize(cacheKey);
Jakob Weiss's avatar
Jakob Weiss committed
207
208
#else
    glDeleteTextures(1, &id);
Jakob Weiss's avatar
Jakob Weiss committed
209
    activeAllocatedMemory_ -= textureByteSize(cacheKey);
Jakob Weiss's avatar
Jakob Weiss committed
210
211
#endif
}
Jakob Weiss's avatar
Jakob Weiss committed
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247

void cgt::TextureManager::run()
{
    std::unique_lock<std::mutex> scope_lock(accessMutex_);

    while (!_stopExecution) {
        _evaluationCondition.wait_for(scope_lock, std::chrono::milliseconds(garbageCollectionDelayMs));

        // could have changed in the meantime
        if(!_stopExecution)
            performGarbageCollection();
    }
}

constexpr size_t cgt::TextureManager::textureByteSize(const cache_key_t & key)
{
     return std::get<SIZE_X>(key) * std::get<SIZE_Y>(key) * std::get<SIZE_Z>(key) * GLTextureFormatTraits::get(std::get<INTERNAL_FORMAT>(key)).bpp();
}

std::string cgt::TextureManager::textureTypeToStr(GLenum tt)
{
    switch (tt) {
    case GL_TEXTURE_1D:
        return "GL_TEXTURE_1D";
    case GL_TEXTURE_1D_ARRAY:
        return "GL_TEXTURE_1D_ARRAY";
    case GL_TEXTURE_2D:
        return "GL_TEXTURE_2D";
    case GL_TEXTURE_2D_ARRAY:
        return "GL_TEXTURE_2D_ARRAY";
    case GL_TEXTURE_3D:
        return "GL_TEXTURE_3D";
    default:
        return "Unknown";
    }
}