Search code examples
c++glut

How to create a class to wrap GLUT?


I'm writing a game for school in OpenGL. Since there will be several more similar assignments I want to make a small framework for doing common things in OpenGL. I have made a few simple games before and I usually break it down into an IO class to handle input and drawing to the screen, Game class for the main game loop/logic, and classes for whatever objects there are in the game.

Before I was using SDL, so my question is, is this the right way of going about this in OpenGL? I've already ran into some trouble. I want my IO class to handle initializing the window, drawing the scene, and mouse clicks. So the constructor looked like this:

IO::IO()
{
    currWindowSize[0] = DEF_WIDTH;
    currWindowSize[1] = DEF_HEIGHT;

    glutInitDisplayMode( GLUT_DOUBLE | GLUT_RGBA );
    glutInitWindowPosition( INIT_WINDOW_POSITION[0], INIT_WINDOW_POSITION[1] );
    glutInitWindowSize( currWindowSize[0], currWindowSize[1] );
    glutCreateWindow( "TEST" );

    setUp();

    glutDisplayFunc(drawScene);
    glutMainLoop();
}

However, drawScene is a class method. Is there a way to pass a class method to glutDisplayFunc() without making it static?


Solution

  • Unfortunately the glutDisplayFunc() doesn't take a void* pointer so you could've fake an object context. You will have to make a static function that can call into the correct IO instance using a static variable.

    I see some slight trouble with your pattern also, though. As far as I know, glutMainLoop() never returns until you terminate the GLUT context, therefore you have a constructor that practically never returns, so your program flow is unreasonable. You should move that call into a separate run() method in your class.

    (Personally I would use GLFW, which avoids the entire callback mess with GLUT, although you have to write your mainloop.)