freeglutをカプセル化できる。glutSetWindowDataにthisポインタを渡し、コールバック関数内でglutGetWindowDataでthisを取得しそのメンバを呼び出す。
#include <Windows.h> #include <gl/GL.h> #include <gl/freeglut.h> #include <cstdio> #pragma comment(lib,"opengl32.lib") #pragma comment(lib,"freeglut.lib") class CfreeglutWindow {
// コールバック関数から呼ばれるメンバ関数群 ////////////////////////// static void mouse_callback(int button, int state, int x, int y) { CfreeglutWindow* pwin = (CfreeglutWindow*)glutGetWindowData(); pwin->mouse(button, state, x, y); } static void motion_callback(int x, int y) { CfreeglutWindow* pwin = (CfreeglutWindow*)glutGetWindowData(); pwin->motion(x, y); } static void mouseWheel_callback(int button, int dir, int x, int y) { CfreeglutWindow* pwin = (CfreeglutWindow*)glutGetWindowData(); pwin->mouse(button, dir, x, y); } static void disp_callback() { CfreeglutWindow* pwin = (CfreeglutWindow*)glutGetWindowData(); pwin->disp(); } static void key_callback(unsigned char key, int x, int y) { CfreeglutWindow* pwin = (CfreeglutWindow*)glutGetWindowData(); pwin->key(key,x,y); }
//普通のメンバ変数 int width; int height; float xpos,ypos; public: CfreeglutWindow() { xpos = 0.0; ypos = 0.0; } void init(int argc, char** argv, const char* title) { glutInit(&argc, argv); glutInitWindowPosition(100, 50); glutInitWindowSize(400, 300); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA); width = 400; height = 300; glutCreateWindow(title); glutDisplayFunc(disp_callback); glutMouseFunc(mouse_callback); glutMotionFunc(motion_callback); glutMouseWheelFunc(mouseWheel_callback); glutKeyboardFunc(key_callback); glutSetWindowData(this); } void loop() { glutMainLoop(); }
// 描画 void disp(void) { glClearColor(0, 0, 0, 0); glClear(GL_COLOR_BUFFER_BIT); glViewport(0, 0, width, height); float v = 0.7; glPushMatrix(); glLoadIdentity(); glTranslatef(xpos, ypos, 0.0); glBegin(GL_TRIANGLES); glColor3d(1, 1, 1); glVertex2f(-v, -v); glColor3d(0, 1, 1); glVertex2f( v, -v); glColor3d(0, 0, 1); glVertex2f( v, v); glEnd(); glPopMatrix(); glFlush(); glutSwapBuffers(); }
// 普通キーの入力 void key(unsigned char key, int x, int y) { if (key == 'a') { xpos -= 0.2; } if (key == 's') { xpos += 0.2; } glutPostRedisplay(); }
// クリック void mouse(int button, int state, int x, int y) { if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) { ypos += 0.2; } if (button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN) { ypos -= 0.2; } glutPostRedisplay(); }
//ドラッグ void motion(int x, int y){}
// ホイール void mouseWheel(int button, int dir, int x, int y) { if (dir > 0){} else{} return; }
}; int main(int argc, char** argv) { CfreeglutWindow cfw; cfw.init(argc, argv, "freeglut"); cfw.loop(); return 0; }