Switching between 2D <> 3D in OpenGL
Source code that simplifies switching from 3D to 2D (if you, like me, drawing eg. all UI using simple 2d coordinates):
void begin2DGL ( int w, int h )
{
glDisable (GL_DEPTH_TEST);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glOrtho(0, w, 0, h, -1, 1);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
glTranslatef (0.375, 0.375, 0);
}
void end2DGL ( void )
{
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glEnable (GL_DEPTH_TEST);
}
Or you might be interested in a block version:
#define glBegin2D(_w,_h) \
glMatrixMode(GL_PROJECTION); \
glPushMatrix(); \
glLoadIdentity(); \
glOrthof(0, _w, 0, _h, -1, 1); \
glMatrixMode(GL_MODELVIEW); \
glPushMatrix(); \
glLoadIdentity(); \
glTranslatef (0.375, 0.375, 0); \
for(int __c=1; __c>0; __c--, glPopMatrix(), glMatrixMode(GL_PROJECTION), glPopMatrix(), glMatrixMode(GL_MODELVIEW))
and use it like this:
glBegin2D(320, 480) {
// drawing code ...
}
Comments