Tutorial 8 – Text

Drawing text on screen may not be the most exciting thing that you can do with OpenGL, but it can be a very useful tool. Whether displaying a user’s HUD in a game or simply getting some information out for simple debugging, drawing text becomes essential!

Decisions, Decisions…

In OpenGL there are multiple ways to draw text to the screen. For this tutorial we are going to use some of the Windows OpenGL (“wgl”) functions to achieve our goals. The main reason for this is that I’ve found this method the most flexible for choosing different fonts and styles on the windows platform.

Getting Started

To use this functionality we need to add a couple of variables to our OpenGL class.

HFONT m_font;
GLuint m_textList;

These will contain the font used to render our text and a list of glyphs used to represent our text.

In our initialise function we first want to create the font that we’ll be writing our text with using a call to CreateFont. This function allows us to define a font with a specific height, width, rotation and many more characteristics. One the font is created we tell our device context to us it when drawing text with a call to SelectObject. Now using this newly created font we generate a list of glyphs. Firstly we create a display list to store the glyphs in using glGenLists and then we populate that list with the glyphs using wglUseFontBitmaps.

The most sensible way to draw text for this tutorial is in 2D, right against the screen (as opposed to in 3D, rotated or off in the distance). The 2D primitives tutorial on this site shows how to set up the camera to render in this fashion. After the camera is set up we tell OpenGL where we want to draw our text onscreen with a call to glRasterPos. With all this set up we can now draw text from any string we want with the following call:

glCallLists(strlen(pTextBuffer), GL_UNSIGNED_BYTE, pTextBuffer);

There are one or two extra little caveats that you can find in the demo code below. But that’s about all you need to know to draw text to your OpenGL window