在OS / X上使用glDrawElements(OpenGL 3.2核心配置文件)

时间:2012-09-27 09:53:17

标签: macos opengl glfw

我正在尝试将一些OpenGL 3.2代码从Windows移植到OS / X 10.8(使用GLFW核心配置文件),但在调用glDrawElements时获取INVALID_OPERATION(glError())。 glDrawArrays函数工作正常,因此我的着色器初始化正常。

以下代码段解释了我在做什么。知道我做错了什么?

struct Vertex {
 vec2 position;
 vec3 color;
};

void display() {
    glClearColor(0.0, 0.0, 0.0, 1.0);
    glClear(GL_COLOR_BUFFER_BIT);

    glUseProgram(shaderProgram);

    mat4 projection = Ortho2D(-15.0f, 15.0f, -15.0f, 15.0f);
    glUniformMatrix4fv(projectionUniform, 1, GL_TRUE, projection);

    glBindVertexArray(shapeVertexArrayBuffer);

    mat4 modelView;

    // upper left
    modelView = Translate(-7,+7,0);
    glUniformMatrix4fv(modelViewUniform, 1, GL_TRUE, modelView);
    glDrawArrays(GL_TRIANGLE_FAN, 0, rectangleSize); // renders correctly

    // upper right
    modelView = Translate(+7,+7,0);
    glUniformMatrix4fv(modelViewUniform, 1, GL_TRUE, modelView);
    GLuint indices[6] = {0,1,2,3,4,0};
    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, indices); //INVALID_OPERATION

    glfwSwapBuffers();
}

void loadGeometry() {
    vec3 color(1.0f, 1.0f, 0.0f);
    Vertex rectangleData[rectangleSize] = {
        { vec2( 0.0,  0.0 ), color },
        { vec2( 5.0, -5.0 ), color },
        { vec2( 5.0,  0.0 ), color },
        { vec2( 0.0,  5.0 ), color },
        { vec2(-5.0,  0.0 ), color },
        { vec2(-5.0, -5.0 ), color }
    };
    shapeVertexArrayBuffer = loadBufferData(rectangleData, rectangleSize);
}

GLuint loadBufferData(Vertex* vertices, int vertexCount) {
    GLuint vertexArrayObject;

    glGenVertexArrays(1, &vertexArrayObject);
    glBindVertexArray(vertexArrayObject);

    GLuint vertexBuffer;
    glGenBuffers(1, &vertexBuffer);
    glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
    glBufferData(GL_ARRAY_BUFFER, vertexCount * sizeof(Vertex), vertices, GL_STATIC_DRAW);

    glEnableVertexAttribArray(positionAttribute);
    glEnableVertexAttribArray(colorAttribute);
    glVertexAttribPointer(positionAttribute, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid *)0);
    glVertexAttribPointer(colorAttribute  , 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid *)sizeof(vec2));

    return vertexArrayObject;
}

1 个答案:

答案 0 :(得分:5)

您可以在顶点缓冲区后创建索引缓冲区。

GLuint elementBuffer;
glGenBuffers(1, &elementBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

然后你可以拨打glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);