#include "../../../include/RenderBackend/OpenGL/Texture2D.hpp" #include "../../../include/RenderBackend/OpenGL/opengl.hpp" #include "../../../include/Image.hpp" #include #include 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 free_spots; i32 texture_id_counter = 0; i32 max_texture_units = 0; }; static TextureIdAllocator *texture_id_allocator = nullptr; Texture2D::Texture2D() : texture_id(-1), texture_ref(-1) { } static void output_gl_error(const char *description) { GLenum error = glGetError(); if(error != GL_NO_ERROR) { fprintf(stderr, "Error: failed to %s, reason: %s (%u)\n", description, glewGetErrorString(error), error); } } Texture2D::Texture2D(Image *image) { assert(image); if(!texture_id_allocator) texture_id_allocator = new TextureIdAllocator(); texture_id = texture_id_allocator->get_free_texture_id(); printf("texture id: %d\n", texture_id); texture_ref = -1; //output_gl_error("start"); glGenTextures(1, &texture_ref); //output_gl_error("gen textures"); glActiveTexture(GL_TEXTURE0 + texture_id); //output_gl_error("set active texture"); glBindTexture(GL_TEXTURE_2D, texture_ref); //output_gl_error("bind texture"); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image->getWidth(), image->getHeight(), 0, GL_RGB, GL_UNSIGNED_BYTE, image->getData()); //output_gl_error("set texture"); 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() { if(texture_ref != -1) { texture_id_allocator->free_texture_id(texture_id); glDeleteTextures(1, &texture_ref); } } Texture2D::Texture2D(Texture2D &&other) { this->operator=(std::move(other)); } Texture2D& Texture2D::operator=(Texture2D &&other) { texture_id = other.texture_id; texture_ref = other.texture_ref; other.texture_id = -1; other.texture_ref = -1; return *this; } }