为什么不在openGL中显示?

时间:2011-09-02 00:32:31

标签: opengl

int main(int argc,char * argv[]){
    srand(time(NULL));
    glutInit(&argc,argv);

    // Setup GLUT
    glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB     | GLUT_DEPTH | GLUT_STENCIL);
    glutInitWindowSize (window_width,window_height);
    glutCreateWindow (window_title);
    graphics_init ();

    // Initialize Runtime variables
    initialize();

    // callbacks
    glutReshapeFunc(&reshape);
    glutDisplayFunc(&display);
    glutMouseFunc(&mouse);
    glutMainLoop();
    return 0;
}


void mouse(int button, int state, int x, int y ){
    if(state == GLUT_DOWN){
         draw_method_two(); // draw objects here using method 2
            glFlush();

    }else{
        current_point_i = -1;
    }
}

void display(){
    // Clear Viewport
    glClearColor(0.0f,0.0f,0.0f,1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    draw_method_one(); ///// using method 1 to draw objects

    glFlush();
    glutSwapBuffers();

}

绘制对象有两种方法。在mouse()中,draw_objects_two用于在单击鼠标时绘制对象。但是,窗口中显示的对象仍由draw_method_one创建。我在glFlush函数中使用了mouse()。但为什么它不会显示在屏幕上?

更新

来自此link,它说:

The function you pass to glutDisplayFunc is only called it is needed: that means when the window is resized, or when an another window has hidden it. If you use glutMouseFunc, for instance, you perhaps want to update (redraw) your window content according to that clic. Also, if you draw animations, you need to call glutPostRedisplay from your idle function.

那么为什么在这种情况下会调用glutDisplayFunc()

2 个答案:

答案 0 :(得分:4)

在鼠标功能中没有绘制任何内容,因为您只调用glFlush但不交换缓冲区(glutSwapBuffers)。因此,您只能绘制到未显示的后台缓冲区。下次GLUT调用显示时,后面的缓冲区会被覆盖,最后通过调用glutSwapBuffers来显示。

但是你不应该用另一种方法绘制任何东西而不是glutDisplayFunc回调。只需在鼠标功能中设置一些标志(如建议的ssell)并调用glutPostRedisplay。您更新的问题是正确的,只有在需要时才会调用显示,因此每当您更改内容时都需要调用glutPostRedisplay并希望此更新屏幕。

顺便说一句,你通常不需要调用glFlush,这应该已经由缓冲交换完成了。

答案 1 :(得分:1)

正在发生的事情是,无论如何,每个循环draw_method_one( )都被调用。单击鼠标时,draw_method_two( )仅被调用一次,因此在下一个循环中,使用方法一重新绘制屏幕。

要获得理想的结果,请执行以下操作:

bool drawFirstMethod = true;

...

void mouse(int button, int state, int x, int y )
{
    //toggle draw modes
    if( state == GLUT_DOWN )
    {
        if( drawFirstMethod )
            drawFirstMethod = false;
        else
            drawFirstMethod = true;
    }

    ...
}

display( )
{
    ...

    if( drawFirstMethod )
        draw_method_one( );
    else
        draw_method_two( );

    ...
}