diff --git a/README.md b/README.md index 5566291..fd0c194 100644 --- a/README.md +++ b/README.md @@ -3,9 +3,9 @@ ## TODO Fix known issues: -- [ ] Use cached textures when loading meshes instead of always loading the textures again for each mesh - [ ] Fix apparently incorrect light radius of lights visible through scaled portals - [x] Fix GL_LINEAR_MIPMAP_LINEAR error +- [x] Use cached textures when loading meshes instead of always loading the textures again for each mesh Add new features: - [ ] Text and UI rendering diff --git a/src/assets/mesh.cpp b/src/assets/mesh.cpp index 509e61a..1764928 100644 --- a/src/assets/mesh.cpp +++ b/src/assets/mesh.cpp @@ -5,6 +5,8 @@ #include #include +std::map> assets::Mesh::s_texture_cache; + assets::Mesh::Mesh(std::span verts, std::span tris, std::span materials) : va_(gfx::VA_POSITION | gfx::VA_NORMAL | gfx::VA_UV | gfx::VA_LIGHTMAP_UV, gfx::VF_CREATE_EBO) { @@ -110,7 +112,7 @@ std::shared_ptr assets::Mesh::LoadFromFile(const std::string& file if (!material.name.empty()) { try { - material.texture = gfx::Texture::LoadFromFile("data/" + material.name + ".png"); + material.texture = LoadTexture("data/" + material.name + ".png"); } catch (const std::exception& e) { throw std::runtime_error("Failed to load texture for material '" + material.name + "': " + e.what()); } @@ -127,3 +129,20 @@ std::shared_ptr assets::Mesh::LoadFromFile(const std::string& file } return mesh; } + +std::shared_ptr assets::Mesh::LoadTexture(const std::string& filename) +{ + auto it = s_texture_cache.find(filename); + if (it != s_texture_cache.end()) + { + if (auto texture = it->second.lock()) + { + return texture; // Return cached texture + } + } + + auto texture = gfx::Texture::LoadFromFile(filename); + s_texture_cache[filename] = texture; // Cache the texture + + return texture; +} diff --git a/src/assets/mesh.hpp b/src/assets/mesh.hpp index 3801c8c..116dd88 100644 --- a/src/assets/mesh.hpp +++ b/src/assets/mesh.hpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include "gfx/vertex_array.hpp" @@ -59,5 +60,9 @@ namespace assets std::span GetMaterials() const { return materials_; } static std::shared_ptr LoadFromFile(const std::string& filename, bool load_collision); + + private: + static std::map> s_texture_cache; + static std::shared_ptr LoadTexture(const std::string& filename); }; } diff --git a/src/gfx/texture.cpp b/src/gfx/texture.cpp index 0893daa..20f93fb 100644 --- a/src/gfx/texture.cpp +++ b/src/gfx/texture.cpp @@ -60,6 +60,8 @@ gfx::Texture::~Texture() { std::shared_ptr gfx::Texture::LoadFromFile(const std::string& filename) { + printf("Loading texture from file: %s\n", filename.c_str()); + int width, height, channels; unsigned char* data = stbi_load(filename.c_str(), &width, &height, &channels, 4);