aboutsummaryrefslogtreecommitdiff
path: root/src/RenderBackend/OpenGL/Texture2D.cpp
blob: dcb9cef944c75737a7908db0325c9c6b1a385852 (plain)
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
#include "../../../include/RenderBackend/OpenGL/Texture2D.hpp"
#include "../../../include/RenderBackend/OpenGL/opengl.hpp"
#include "../../../include/Image.hpp"
#include <stack>
#include <cassert>

namespace amalgine {
    struct TextureIdAllocator {
        TextureIdAllocator(){
            glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &max_texture_units);
            if(max_texture_units < 1)
                max_texture_units = 1;
            fprintf(stderr, "max texture units: %d\n", max_texture_units);
        }

        u32 get_free_texture_id() {
            if(!free_spots.empty()) {
                u32 texture_id = free_spots.top();
                free_spots.pop();
                return texture_id;
            }

            if(texture_id_counter + 1 == max_texture_units) {
                fprintf(stderr, "Error: No free spot left for textures, resetting counter\n");
                texture_id_counter = 0;
            }

            return texture_id_counter++;
        }

        void free_texture_id(i32 texture_id) {
            free_spots.push(texture_id);
        }
        
        std::stack<u32> free_spots;
        i32 texture_id_counter = 0;
        i32 max_texture_units = 0;
    };

    static TextureIdAllocator *texture_id_allocator = nullptr;

    Texture2D::Texture2D(Image *image)
    {
        assert(image);
        if(!texture_id_allocator)
            texture_id_allocator = new TextureIdAllocator();

        texture_id = texture_id_allocator->get_free_texture_id();
        glGenTextures(1, &texture_ref);
        glActiveTexture(GL_TEXTURE0 + texture_id);
        glBindTexture(GL_TEXTURE_2D, texture_ref);
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image->getWidth(), image->getHeight(), 0, GL_RGB, GL_UNSIGNED_BYTE, image->getData());
        
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
        glGenerateMipmap(GL_TEXTURE_2D);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    }

    Texture2D::~Texture2D()
    {
        texture_id_allocator->free_texture_id(texture_id);
        glDeleteTextures(1, &texture_ref);
    }
}