如何正确跟踪VBO和VAO进行清理?

问题描述

不好意思,但我是一位。我目前正在尝试找到一种跟踪VAO和VBO ID的方法,以便可以使用for循环遍历它们并告诉OpenGL删除它们。我当前的方法是将它们推入向量,并在终止时向后遍历它们,这导致了段错误。在编译时使用向量已向我发出此警告:

lou@debian:~/Development/GamEngine$ make
src/model.cpp: In static member function ‘static void Model::_cleanup()’:
src/model.cpp:39:27: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
   39 |   glDeleteVertexArrays(1,(unsigned int*)_vaos[i]);
src/model.cpp:43:22: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
   43 |   glDeleteBuffers(1,(unsigned int*)_vbos[i]);

我想我可以对模型类使用析构函数,并使每个模型删除自己的VAO和VBO,因为每个模型都可以跟踪它们。这是Model :: _ cleanup():

void Model::_cleanup()
{
    // Clean VAOs
    for(int i = _vaos.size(); i > 0; i--) {
        glDeleteVertexArrays(1,(unsigned int*)_vaos[i]);
    }
    // Clean VBOs
    for(int i = _vbos.size(); i > 0; i--) {
        glDeleteBuffers(1,(unsigned int*)_vbos[i]);
    }
}

这是model.hpp:

#ifndef __MODEL_HPP__
#define __MODEL_HPP__

#include <glad/glad.h> 
#include <vector>

using std::vector;

class Model
{

public:
    Model(float* p_pos);
    unsigned int getVaoID() { return m_vaoID; }
    unsigned int getVboID() { return m_vboID; }
    unsigned int getVertexCount() { return m_vertexCount; }

    static void _cleanup();

private:
    unsigned int m_vaoID;
    unsigned int m_vboID;
    unsigned int m_vertexCount;

    void m_createVAO(int p_attribNum,float* p_data);
    void m_unbindVAO();

    void m_createVBO();
    void m_unbindVBO();

    static vector<unsigned int> _vaos;
    static vector<unsigned int> _vbos;

};

#endif // __MODEL_HPP__

解决方法

缺少(&)运算符的地址

glDeleteVertexArrays(1,(unsigned int*)_vaos[i]);

glDeleteVertexArrays(1,&_vaos[i]);

或者,您可以执行以下操作:

glDeleteVertexArrays(1,_vaos.data()+i);

无论如何,您根本不需要for循环(请参见std::vector):

void Model::_cleanup()
{
    glDeleteVertexArrays(_vaos.size(),_vaos.data());
    glDeleteBuffers(_vbos.size(),_vbos.data());
}