2014-05-15 115 views
2

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

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

我对OpenGL本人相当陌生,但看起来像需要着色器的“新”OpenGL。对于一个非常好的教程,我推荐[这一个](http://arcsynthesis.org/gltut/index.html),你可能想阅读[“你好三角形”](http://arcsynthesis.org/gltut /Basics/Tutorial%2001.html)一章。 –

+0

也许尝试改变整个屏幕的颜色使用'glClearColor()'并在glClear'glLoadIdentity'后调用这个函数' – mr5

+0

@ReetoKoradi - 谢谢....这工作! – SINGULARITY

回答

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

注意,我写了,从我的头顶上,万一有一些错误,请评论。

+0

由于这被认为是重复的,也许最好是将答案添加到原始问题中?我将代码区分到旧问题中的代码,并且完全相同。 –

+0

@ReetoKoradi你是对的,我没有注意到重复,在我写回答之后,问题被标记。我在那里扩展我的答案http://stackoverflow.com/questions/23097007/how-can-i-make-opengl-draw-something-using-vbos-in-xcode/23696380#23696380。 –