三角形不渲染

Triangle doesn't render

本文关键字:三角形      更新时间:2023-10-16

我在渲染一个简单的三角形时遇到了麻烦。下面的代码编译并运行,除了没有任何三角形;只有黑色的背景。

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;
}

因为你没有着色器,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);

请注意,我写的是我的头脑,如果有什么错误,请评论