使用 glDrawElements 绘制 std::vector

Drawing a std::vector with glDrawElements

我正在尝试使用我拥有的高度图绘制地形。通过使用 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 参数,但目前我找不到任何问题。

在定义通用顶点属性数据数组之前,您必须绑定顶点数组对象。见 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);