Unload textures when model is deleted, and remove warnings.

This commit is contained in:
Warwick 2022-06-14 14:34:30 +01:00
parent a91fc3d57d
commit cf964bf235
5 changed files with 34 additions and 4 deletions

View file

@ -63,3 +63,15 @@ void Mesh::draw(ShaderLoader &shader) {
glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
}
void Mesh::unloadTextures() {
for (int i = 0; i < textures.size(); i++) {
glDeleteTextures(1, &textures[i].id);
}
}
// Until I have a firmer grasp on memory management, textures should only be
// managed by the Model class
Mesh::~Mesh() { // this->unloadTextures();
// error.log("Mesh destructor called");
}

View file

@ -24,6 +24,8 @@ private:
unsigned int VAO, VBO, EBO;
void setupMesh();
void unloadTextures();
public:
std::vector<Vertex> vertices;
std::vector<unsigned int> indices;
@ -33,4 +35,6 @@ public:
Mesh(std::vector<Vertex> vertices, std::vector<unsigned int> indices,
std::vector<Texture> textures);
~Mesh();
};

View file

@ -1,6 +1,6 @@
#include "Model.h"
Model::Model(char *path) { loadModel(path); }
Model::Model(std::string path) { loadModel(path); }
Model::Model(Mesh mesh) { this->meshes.push_back(mesh); }
Model::Model(std::vector<Mesh> meshes) { this->meshes = meshes; }
@ -126,6 +126,7 @@ std::vector<Texture> Model::loadMaterialTextures(aiMaterial *material,
}
return textures;
}
unsigned int Model::loadTextureFromFile(std::string file,
std::string directory) {
// Use sdl2_image to load the texture.
@ -165,3 +166,11 @@ unsigned int Model::loadTextureFromFile(std::string file,
return texture;
}
void Model::unloadTextures() {
for (int i = 0; i < textures_loaded.size(); i++) {
glDeleteTextures(1, &textures_loaded[i].id);
}
}
Model::~Model() { this->unloadTextures(); }

View file

@ -33,13 +33,15 @@ private:
aiTextureType type,
std::string typeName);
void unloadTextures();
std::string directory;
unsigned int loadTextureFromFile(std::string texture, std::string directory);
std::vector<Texture> textures_loaded;
public:
// Create a model from file
Model(char *path);
Model(std::string path);
// Used to create a mesh out of a single mesh.
Model(Mesh mesh);
// Used to create a mesh out of multiple meshes.
@ -50,4 +52,6 @@ public:
// Translate the model
void translate(glm::vec3 translation);
~Model();
};

View file

@ -75,7 +75,8 @@ int main(int argc, char **argv) {
ROOT_DIR "data/shaders/fragment.glsl");
Model backpack(ROOT_DIR "data/models/backpack/backpack.obj");
// Model cube(ROOT_DIR "data/models/cube/cube.obj");
Model cube(ROOT_DIR "data/models/cube/cube.obj");
cube.translate(glm::vec3(3.0f, 0.0f, -1.0f));
// Mess with perspective
// Projection matrix : 45° Field of View, 4:3 ratio, display range : 0.1
@ -124,7 +125,7 @@ int main(int argc, char **argv) {
shader.setMat4("MVP", camera.getMVP());
// Draw Meshes
// cube.draw(shader);
cube.draw(shader);
backpack.draw(shader);
// Finally render everything