出于某种原因,OpenGL VAO指向0

OpenGL VAO is pointing to address 0 for some reason

本文关键字:VAO 指向 OpenGL 某种原因      更新时间:2023-10-16

我的vao遇到了一些麻烦(至少这是我认为正在发生的事情)。

所以,我正在做的是,我有一个正在从某些原始数据中创建VBO和VAO的类

RawModel* Loader::loadToVao(float* positions, int sizeOfPositions) {
    unsigned int vaoID = this->createVao();
    this->storeDataInAttributeList(vaoID, positions, sizeOfPositions);
    this->unbindVao();
    return new RawModel(vaoID, sizeOfPositions / 3);
}
unsigned int Loader::createVao() {
    unsigned int vaoID;
    glGenVertexArrays(1, &vaoID);
    glBindVertexArray(vaoID);
    unsigned int copyOfVaoID = vaoID;
    vaos.push_back(copyOfVaoID);
    return vaoID;
}
void Loader::storeDataInAttributeList(unsigned int attributeNumber, float* data, int dataSize) {
    unsigned int vboID;
    glGenBuffers(1, &vboID);
    glBindBuffer(GL_ARRAY_BUFFER, vboID);
    glBufferData(GL_ARRAY_BUFFER, dataSize * sizeof(float), data, GL_STATIC_DRAW);
    glVertexAttribPointer(attributeNumber, 3, GL_FLOAT, false, 0, 0);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
    unsigned int copyOfVboID = vboID;
    vbos.push_back(copyOfVboID);
}
void Loader::unbindVao() {
    glBindVertexArray(0);
}

Rawmodel只是一个应该吸入浮子并创建VBO和VAO的类。我正在使用的向量vbosvaos只是为了跟踪所有ID,因此使用所有数据完成后,我可以将它们删除。

我90%的人相信这都应该正常工作。但是,当我尝试运行一些绘制它的代码时,OpenGL即将退出,因为它正在尝试从地址0x0000000读取,并且不喜欢那样。我将我从代码创建的原始模型传递到看起来像这样的渲染器中的函数中:

void Renderer::render(RawModel* model) {
    glBindVertexArray(model->getVaoID());
    glEnableVertexAttribArray(0);   
    glDrawArrays(GL_TRIANGLES, 0, model->getVertexCount());
    glDisableVertexAttribArray(0);
    glBindVertexArray(0);
}

我已经检查以确保当我创建VAO时,以及试图检索VAO时的vaoid相同。实际上是一样的。

我不知道如何读取当前在OpenGL当前以Vertex Attrab阵列绑定的任何地址存储的地址,因此我无法测试它是否指向顶点数据。我很确定它是由于某种原因指向0的指向。

编辑:

事实证明,不是硬编码0是一个问题。它删除了Visual Studio和OpenGL给我的错误,但实际错误在其他地方。我意识到我在上面的某些代码中将vaoID作为attributeNumber传递,当时我应该通过硬编码0。我在此处编辑了我的代码:

RawModel* Loader::loadToVao(float* positions, int sizeOfPositions) {
    unsigned int vaoID = this->createVao();
    this->storeDataInAttributeList(0, positions, sizeOfPositions);
    this->unbindVao();
    return new RawModel(vaoID, sizeOfPositions / 3);
}

我将行this->storeDataInAttributeList(vaoID, positions, sizeOfPositions);更改为您在上面看到的。但是,在更改后效果很好。

您应该使用glVertexAttribPointerglEnableVertexAttribArrayglDisableVertexAttribArray使用顶点属性索引,但是您所拥有的是:

  • glVertexAttribPointer使用的VAO ID
  • glEnableVertexAttribArrayglDisableVertexAttribArray使用的硬编码0(如果您确定该值,这不一定是错误)

如果您不确定索引值(例如,如果您不指定着色器中的布局),则可以使用glGetAttribLocation调用:

获得它
// The code assumes `program` is created with glCreateProgram
// and `position` is the attribute name in your vertex shader
const auto index = glGetAttribLocation(program, "position");

然后,您可以将index与上述呼叫一起使用。