Continue program even after openGL window closed

1.3k views Asked by At

I keep calling glutMainLoopEvent to process the graphics. However, after someone closed the window, I would like to exit the loop and show Code reached here. . it seems when a window is closed, an exit function is called and the entire application stops. While I need the application to continue. How should I fix the code?

#include <stdio.h>
#include <GL/freeglut.h>

//display function - draws a triangle rotating about the origin
void cback_render()
{
    //keeps track of rotations
    static float rotations = 0;

    //OpenGL stuff for triangle
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glLoadIdentity();
    glRotatef(rotations, 0, 0, 1);

    glBegin(GL_TRIANGLES);
        glVertex3f(0,0,0);
        glVertex3f(1,0,0);
        glVertex3f(0,1,0);
    glEnd();

    //display on screen
    glutSwapBuffers();

    //rotate triangle a little bit, wrapping around at 360°
    if (++rotations > 360) rotations -= 360;
}

void timer(int value )
{
    glutPostRedisplay();
    glutMainLoopEvent();
    glutTimerFunc(30, timer, 1);
}

int main(int argc, char **argv)
{
    //initialisations
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH);
    glutInitWindowPosition(100, 100);
    glutInitWindowSize(512, 512);

    //create window and register display callback
    glutCreateWindow("freegluttest");
    glutDisplayFunc (cback_render);
    glutTimerFunc(30, timer, 1);

    //loop forever
    long i=0;
    while(1)
    {
        printf("[%ld]\n",i);
        i++;
        glutMainLoopEvent();
    }
    printf("Code reached here.");

    return 0;
}
1

There are 1 answers

3
Schomes On BEST ANSWER

Use GLUT_ACTION_ON_WINDOW_CLOSE to allow your program to continue when a window is closed.

glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE,
              GLUT_ACTION_GLUTMAINLOOP_RETURNS);

Sources:

http://www.lighthouse3d.com/cg-topics/glut-and-freeglut/ http://freeglut.sourceforge.net/docs/api.php