三角形无法渲染

时间:2014-05-15 05:48:09

标签: c++ opengl geometry

我无法渲染简单的三角形。下面的代码编译并运行,除了没有任何三角形;只有黑色背景。

GLuint VBO;

static void RenderSceneCB()
{
    //glClear sets the bitplane area of the window to values previously selected by glClearColor, glClearDepth, and glClearStencil. 
    glClear(GL_COLOR_BUFFER_BIT);

    glEnableVertexAttribArray(0);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);

    glDrawArrays(GL_TRIANGLES, 0, 3);

    glDisableVertexAttribArray(0);

    //swaps the buffers of the current window if double buffered.
    glutSwapBuffers();
}

static void InitializeGlutCallbacks()
{
    glutDisplayFunc(RenderSceneCB);
}

static void CreateVertexBuffer()
{
    Vector3f Vertices[3];
    Vertices[0] = Vector3f(-1.0f, -1.0f, 0.0f);
    Vertices[1] = Vector3f(1.0f, -1.0f, 0.0f);
    Vertices[2] = Vector3f(0.0f, 1.0f, 0.0f);

    glGenBuffers(1, &VBO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(Vertices), Vertices, GL_STATIC_DRAW);
}

int main(int argc, char** argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGBA);
    glutInitWindowSize(1024, 768);
    glutInitWindowPosition(100, 100);
    glutCreateWindow("Tutorial 02");

    InitializeGlutCallbacks();

    // Must be done after glut is initialized!
    GLenum res = glewInit();
    if (res != GLEW_OK) {
      fprintf(stderr, "Error: '%s'\n", glewGetErrorString(res));
      return 1;
    }
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

    CreateVertexBuffer();

    glutMainLoop();

    return 0;
}

1 个答案:

答案 0 :(得分:3)

由于你没有着色器,OpenGL不知道如何解释你的顶点属性0,因为它只知道位置,颜色等,而不是通用属性。请注意,这可能适用于某些GPU,因为它们会将通用属性映射到相同的"插槽",然后将零解释为位置(对于这些问题,通常NVidia不那么严格)。

您可以使用MiniShader,只需在CreateVertexBuffer();之后添加以下代码:

minish::InitializeGLExts(); // initialize shading extensions
const char *vs =
    "layout(location = 0) in vec3 pos;\n"
    // the layout specifier binds this variable to vertex attribute 0
    "void main()\n"
    "{\n"
    "    gl_Position = gl_ModelViewProjectionMatrix * vec4(pos, 1.0);\n"
    "}\n";
const char *fs = "void main() { gl_FragColor=vec4(.0, 1.0, .0, 1.0); }"; // green
minish::CompileShader(vs, fs);

请注意,我是从头脑中写的,如果有错误,请发表评论。