#include "texture.h" #include #include "stb_image.h" Texture::Texture(const char* filename) : path(filename) { int nrComponents; stbi_set_flip_vertically_on_load(true); unsigned char* bytes = stbi_load(filename, &width, &height, &nrComponents, 4); if (not bytes) throw std::runtime_error("Failed to load texture: " + path); pixels.assign(bytes, bytes + (size_t)width * height * 4); stbi_image_free(bytes); CreateGLTexture(); } Texture::Texture(const unsigned char* encoded, int size, const std::string& name) : path(name) { int nrComponents; stbi_set_flip_vertically_on_load(true); unsigned char* bytes = stbi_load_from_memory(encoded, size, &width, &height, &nrComponents, 4); if (not bytes) throw std::runtime_error("Failed to load texture: " + path); pixels.assign(bytes, bytes + (size_t)width * height * 4); stbi_image_free(bytes); CreateGLTexture(); } Texture::Texture(int newWidth, int newHeight) : width(newWidth), height(newHeight) { pixels.assign((size_t)width * height * 4, 255); CreateGLTexture(); } Texture::Texture(const Texture& source) : path(source.path), width(source.width), height(source.height), pixels(source.pixels) { CreateGLTexture(); } void Texture::CreateGLTexture() { glGenTextures(1, &ID); glBindTexture(GL_TEXTURE_2D, ID); // Mipmaps when shrunk, otherwise tiled textures shimmer in the distance glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels.data()); glGenerateMipmap(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, 0); } void Texture::Upload() { glBindTexture(GL_TEXTURE_2D, ID); glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pixels.data()); glGenerateMipmap(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, 0); } void Texture::Delete() { glDeleteTextures(1, &ID); }