Announcing GLUT CPP

Have you ever written anything using GLUT and C++? If you did you probably wrote proper OOP code and thus at one point or another tried to pass a non-static member function to the GLUT callbacks – and failed. Unfortunately the GLUT API is broken in this respect as it does not allow passing user-data to the callback functions. You either have to make all of your members static or use wrapper functions.

Well the situation bugged me enough, to dig inside GLUT and write a class-based C++ wrapper around its API – it uses the wrapper function approach but hides it behind the class interface, so you dont have to mess around it yourself.

Here is an example what you can do with it:

#include "glut.hpp"
#include <iostream>

class MyWindow: public glut::Window {
public:
 GLfloat color[3];

 MyWindow(const char* title) : glut::Window(title, 300, 200), color( { 1, 0, 0 }) {
 }

 void displayFunc() {

   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

   glColor3fv(color);

   glBegin(GL_TRIANGLES);
   glVertex3f(-0.5, -0.5, 0.0);
   glVertex3f(0.5, 0.0, 0.0);
   glVertex3f(0.0, 0.5, 0.0);
   glEnd();

   swapBuffers();
 }

 void keyboardFunc(unsigned char key, int x, int y) {
   cout << key << endl;
 }
};

class MyMenu: public glut::Menu {
public:
 MyMenu(glut::Window& w) : glut::Menu(w) {
   addEntry("Hello", 1);
   addEntry("World", 2);
   attach(GLUT_RIGHT_BUTTON);
 }

 void selected(int value) {
   cout << value << endl;
 }
};

int main(int argc, char* argv[]) {
 glut::Init(argc, argv);
 glut::InitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);

 MyWindow w("Window 1");
 w.show();

 MyMenu m(w);

 MyWindow w2("Window 2");
 w2.color[1] = 1;
 w2.show();

 glut::MainLoop();

 return 0;
}

the API coverage is far from complete, but it suits my own needs very well. So I hope it can also help others. You can download the header here. And in case you want to help me out with the API coverage or fix some bugs, there is a bazaar branch here.