#include "tex_loader.h" #include "hid_handler.h" TexLoader tex_loader; bool TexLoader::LoadPng(const std::string& path) { // Already loaded? if (tex_loader.loadedTextures.contains(path)) { return true; } hid_handler.log << "Loading image: " << path.c_str() << std::endl; // Read file into buffer std::ifstream file(path, std::ios::binary | std::ios::ate); if (!file) { hid_handler.log << "Failed to load image: not found." << std::endl; tex_loader.loadedTextures[path] = LoadedTexture{}; return false; } std::streamsize size = file.tellg(); file.seekg(0, std::ios::beg); std::vector buffer(size); if (!file.read((char*)buffer.data(), size)) { hid_handler.log << "Failed to load image: unable to read file." << std::endl; tex_loader.loadedTextures[path] = LoadedTexture{}; return false; } // Decode PNG std::vector decoded; unsigned long w, h; if (decodePNG(decoded, w, h, buffer.data(), buffer.size(), true) != 0) { hid_handler.log << "Failed to load image: unable to decode." << std::endl; tex_loader.loadedTextures[path] = LoadedTexture{}; return false; } // Create OpenGL texture GLuint texID; glGenTextures(1, &texID); glBindTexture(GL_TEXTURE_2D, texID); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); 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_RGBA8, (GLsizei)w, (GLsizei)h, 0, GL_RGBA, GL_UNSIGNED_BYTE, decoded.data()); LoadedTexture tex; tex.texID = texID; tex.width = (int)w; tex.height = (int)h; tex_loader.loadedTextures[path] = tex; return true; } std::tuple TexLoader::GetPng(const std::string& path) { auto it = tex_loader.loadedTextures.find(path); if (it != tex_loader.loadedTextures.end()) { return { it->second.texID, it->second.width, it->second.height }; } return { 0, 0, 0 }; } void TexLoader::Cleanup() { for (auto& [_, tex] : tex_loader.loadedTextures) { if (tex.texID) glDeleteTextures(1, &tex.texID); } tex_loader.loadedTextures.clear(); }