Cleaning up when exiting an OpenGL app
I have an an OSX OpenGL app I'm trying to modify. When I create the app a whole bunch of initialisation functions are called -- including methods where I can specify my own mouse and keyboard handlers etc. For example:
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
glutInitWindowPosition(100, 100);
glutInitWindowSize(700, 700);
glutCreateWindow("Map Abstraction");
glutReshapeFunc(resizeWindow);
glutDisplayFunc(renderScene);
glutIdleFunc(renderScene);
glutMouseFunc(mousePressedButton);
glutMotionFunc(mouseMovedButton);
glutKeyboardFunc(keyPressed);
At some point I pass control to glutMainLoop and my application runs. In the process of running I create a whole bunch of objects. I'd like to clean these up. Is there any way I can tell GLUT to call a cleanup method before it quits?
In freeglut if you call this:
glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_CONTINUE_EXECUTION)
Prior to entering the main loop, then when the window closes the main loop function will return and you can do your cleanup.
It's worth noting that at that stage the GL context has already been destroyed so you can't perform any GL operations.
I fell for this once in a while, trying to play with GLUT. I tried everything I could thing of, including IIRC exiting glutMainLoop
through an exception catched in the main function but...
When using glutMainLoop
My solution was the following : Create a global Context
object, who will be owner of all your resources, and free those resources in the destructor.
This global Context
object destructor will be called immediately after exiting the main.
It is important Context
is a global variable, and not a variable declared in the main function, because for a reason that still escapes me (I still fail to see the interest of this implementation choice), glutMainLoop won't return.
In my Linux box (Ubuntu), the destructor is called correctly. I guess it should work the same way on Windows and MacOS, too.
Note that this is the C++ version of Francisco Soto's atexit()
solution, without the possible limitations.
Using glutMainLoopEvent
Apparently, some implementations have a glutMainLoopEvent which can be used instead of calling glutMainLoop.
http://openglut.sourceforge.net/group__mainloop.html#ga1
glutMainLoopEvent
will only resolve the pending events, and then return. Thus, you must provide the event loop (the for(;;)
construct) around the call to glutMainLoopEvent
, but this way, you can work with a GLUT and still have control on the event loop, and free your resources when needed.
如果你使用C / C ++,也许你可以使用atexit()调用?
链接地址: http://www.djcxy.com/p/38432.html下一篇: 退出OpenGL应用程序时进行清理