Cogs and Levers A blog full of technical stuff

2D in OpenGL

Whilst OpenGL enjoys a lot of fame as a 3D graphics package, it’s also a fully featured 2D graphics library as well. In this short tutorial, I’ll walk you through the code required to put OpenGL into 2D mode. This tutorial does assume that you’re ready to run some OpenGL code. It won’t be a primer in how to use SDL or GLUT, etc. Here’s the code.

/* first of all, we need to read the dimensions of the 
   display viewport. */
int viewport[4];
glGetIntegerv(GL_VIEWPORT, viewport);

/* setup an orthographic matrix using the viewport 
   dimensions on the projection matrix */
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, viewport[2], viewport[3], 0, -1, 1);

/* clear out the modelview matrix */
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();

/* disable depth testing (as we're not using z) */
glDisable(GL_DEPTH_TEST);

First off, we use glGetIntegerv to read the dimensions of the viewport. You will probably already have these values on hand anyway, but getting the viewport this way just generalises the code and it’s not expensive to do so. We generate an orthographic matrix next using glOrtho and the viewport information we retrieved in the first step. The model view matrix is then kept clean - out of habbit, i’d say and finally `glDisable is used to turn off depth testing.

We’re in 2D. No Z-Axis, no depth testing! That’s it! You can draw what you need to as simply as this:

/* note that we're not clearing the depth buffer */
glClear(GL_COLOR_BUFFER_BIT);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();

/* draw a triangle */
glBegin(GL_TRIANGLES);

glColor3ub(255, 0, 0);
glVertex2d(0, 0);

glColor3ub(0, 255, 0);
glVertex2d(100,0);

glColor3ub(0, 0, 255);
glVertex2d(50, 50);

glEnd();

Quick update to this one - I switched the parameters around in the call to glOrtho so that it’s a much more natural drawing experience (putting 0,0 in the top left hand corner of the screen). It’s not perfect mathematically but it sure does help any of your existing code that assumes your screen goes positive to the right and positive to the bottom!