使用索引缓冲区对象时出现奇怪的段落错误

时间:2012-07-22 08:04:45

标签: c++ opengl sfml

我的代码在使用glDrawArrays时工作正常,但每当我创建索引缓冲区并将其更改为使用glDrawElements时,它就会出现段错误。

(奇怪的是,不是在绘图之前或之后......但是当主循环退出时!)

这是简单的代码。我在其中声明了4个顶点,并为它们绘制了一个三角形的3个索引。

int main()
{
    sf::Window win(sf::VideoMode(400,400,32),"Manasij");
    GlewInit();
    mm::Program program
    (
        {
            mm::Shader(GL_VERTEX_SHADER,"vshader.vert"),
            mm::Shader(GL_FRAGMENT_SHADER,"fshader.frag")
        }
    );
    float vdata[]=
    {
        0.0f,0.0f,
        0.5f,0.0f,
        0.5f,0.5f,
        0.0f,0.5f
    };
    GLubyte indices[]={0,1,3};

    GLuint vao,vbo,ebo;
    glGenVertexArrays(1,&vao);
    glBindVertexArray(vao);

    glGenBuffers(1,&vbo);
    glBindBuffer(GL_ARRAY_BUFFER,vbo);
    glBufferData(GL_ARRAY_BUFFER,8*sizeof(float),vdata,GL_STATIC_DRAW);

    glGenBuffers(1,&ebo);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,ebo);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER,3*sizeof(GLubyte),indices,GL_STATIC_DRAW);

    glVertexAttribPointer(0,2,GL_FLOAT,GL_FALSE,0,0);
    glEnableVertexAttribArray(0);
    glBindAttribLocation(program.getHandle(),0,"pos");
    //glBindVertexArray(0);

    glUseProgram(program.getHandle());
    //glBindVertexArray(vao);
    glClearColor(1.0f,1.0f,1.0f,1.0f);

    while(win.isOpen())
    {
        sf::Event eve;
        while(win.pollEvent(eve))
            if(eve.type==sf::Event::Closed)
                win.close();
        glClear(GL_COLOR_BUFFER_BIT);

//      glDrawArrays(GL_TRIANGLES,0,3);
        glDrawElements(GL_TRIANGLES,3,GL_UNSIGNED_BYTE,(GLvoid*)0);
        win.display();  
    }
    return 0;
}

着色器就像它们一样简单:

#version 330
in vec2 pos;
void main()
{
    gl_Position = vec4(pos,0.0f,1.0f);
}

#version 330
void main()
{
    gl_FragColor = vec4(1.0f,0.3f,0.8f,1.0f);
}

gdb显示:

Breakpoint 1, main () at test.cpp:57
57                      win.display();
(gdb) continue 
Continuing. //<- At this point I try to close the window, thus triggeing the main loop to break

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff557d164 in ?? () from /lib/libnvidia-glcore.so.302.17

知道我在搞砸什么吗?

P.S:如果有人想要测试,这里有一个带有makefile的archive..complete!

https://docs.google.com/file/d/0B0oubbp-MVYOeGFuX0owXzhRTEU/edit

2 个答案:

答案 0 :(得分:2)

问题是在循环的最后一次迭代中,当检测到'close'事件时,窗口发出了关闭信号,但即使在那之后我最后一次调用了glDrawElements。 由于一切都已经消失,这导致了一个段错误。

解决方法是在调用win.close()之后放置一个break语句,或者将事件处理代码放到循环的末尾。

(感谢来自archlinux论坛for catching this的cmtptr,我几乎确信这是一个驱动程序问题)

答案 1 :(得分:0)

在绘制循环结束时尝试删除VertexArraysBuffers

while(win.isOpen())
{
    sf::Event eve;
    while(win.pollEvent(eve))
        if(eve.type==sf::Event::Closed)
            win.close();
    glClear(GL_COLOR_BUFFER_BIT);

    // glDrawArrays(GL_TRIANGLES,0,3);
    glDrawElements(GL_TRIANGLES,3,GL_UNSIGNED_BYTE,(GLvoid*)0);
    win.display();  
}
glDeleteBuffer(1, &ebo);
glDeleteVertexArrays(1, &vbo);    
return 0;

这只是一个猜测,请告诉我它是否有所作为。