使用glDrawElements绘制std :: vector

时间:2018-09-03 07:15:16

标签: c++ opengl vao gl-triangle-strip

我正在尝试使用已有的高度图绘制地形。通过使用std :: vector,我现在有了一个位置数组和一个位置索引数组,以便在绘制地形时使用glDrawElements(GL_TRIANGLE_STRIP,...)。但是,由于某种原因,我的简单代码无法正常工作。请注意,我正在将glm用于数学库。

以下是VAO,VBO和EBO的配置。我仔细检查了顶点数据和索引数据,它们都是正确的。

// positions and indices
    vector<glm::vec3> positions;
    vector<int> indices;
    for (int z = 0; z < gridZNum; z++) {
        for (int x = 0; x < gridXNum; x++) {
            positions.push_back(glm::vec3(x, _terrain->getHeight(x,z),z));
            //normals.push_back(_terrain->getNormal(x, z));
            indices.push_back(z*gridXNum + (x+1));
            indices.push_back(z*gridXNum + (x+1) + gridXNum);
            if (x == gridXNum-1 && z != gridZNum-1) {
                indices.push_back(z*gridXNum + 2*gridXNum);
                indices.push_back((z+1)*gridXNum+1);
            }
        }
    }

// VAO, VBO configuration
    unsigned int VAO, VBO, EBO;
    glGenVertexArrays(1, &VAO);
    glGenBuffers(1, &VBO);
    glGenBuffers(1, &EBO);

    glBindBuffer(GL_ARRAY_BUFFER, VAO);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
    glBufferData(GL_ARRAY_BUFFER, positions.size() * sizeof(glm::vec3), &positions[0] , GL_STATIC_DRAW);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(int), &indices[0], GL_STATIC_DRAW);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3* sizeof(float), 0);

最后,这是我的绘图功能

//Inside the render loop I call
drawScene(shader, VAO, indices.size());
//......

void drawScene(Shader &shader, unsigned int VAO, unsigned int numIndices)   //draw the scene with the parameter data.
{
    glm::mat4 model;
    //model = glm::translate(model, glm::vec3(-(_terrain->width())/2, 0.0f, -(_terrain->length())/2));
    glm::mat4 view = camera.GetViewMatrix();
    glm::mat4 projection = glm::perspective(glm::radians(camera.Zoom), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f);

    shader.use();
    shader.setMat4("model", model);
    shader.setMat4("view", view);
    shader.setMat4("projection", projection);

    glBindVertexArray(VAO);
    glDrawElements(GL_TRIANGLE_STRIP, numIndices, GL_UNSIGNED_INT, 0);
    glBindVertexArray(0);
}

我假设像size参数之类的参数有问题,但是目前我找不到任何错误。

1 个答案:

答案 0 :(得分:0)

在定义通用顶点属性数据的数组之前,必须绑定顶点数组对象。参见Vertex Array Object

glBindVertexArray(VAO);

顶点缓冲区对象的名称为VBO而不是VAO

glBindBuffer(GL_ARRAY_BUFFER, VBO);

以某种方式更改代码:

unsigned int VAO, VBO, EBO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glGenBuffers(1, &EBO);

glBindVertexArray(VAO);

glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, positions.size() * sizeof(glm::vec3), &positions[0] , GL_STATIC_DRAW);

glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(int), &indices[0], GL_STATIC_DRAW);

glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3* sizeof(float), 0);