Sign in to follow this  

OpenGL Text in openGL

Recommended Posts

At the minute I'm using bitmap fonts and print_bitmap_string() to display text on screen. The problem I have is that it only allows me to use 7 different fonts. These fonts are all too 'skinny' which is quite hard to see on screen, I need bold text really. The trouble is that this print_bitmap_string() function is absolutely perfect for what I need -apart from the limited fonts- it is easy to place on screen, it stays the same size and always rotates to face the camera etc. However I think I need to use another method to display my text. Is there any other method which is similar but has a wider range of fonts? Ideally what I need to do is draw the character in white and have a black outline round each letter. However, if that is quite hard then I should be able to cope with a simple "chunky" font. Any ideas? Thanks.

Share this post

Link to post
Share on other sites
Well I've just looked for the function and I cant find it anywhere, I must of got it from some sample code or a tutorial somewhere. But anyhow, with the print_bitmap_string() function I can only use the following fonts:


The code I've got to print something is:

char string[0][256];
string[0][0] = 'H'; string[0][1] = 'e'; string[0][2] = 'l'; string[0][3] = 'p';

glRasterPos3f(42000, 75000, -3000);
print_bitmap_string( GLUT_BITMAP_9_BY_15 , string[0]);

That's all I do, I've not included any fancy libraries or anything.
I'll have to look through some tutorials, maybe I'm using the wrong type of function to use bitmap fonts.

***edit*** Sorry, just realised that the print_bitmap_string function actually makes a call to glutBitmapCharacter() function. No wonder I couldn't find it anywhere... :-S

[Edited by - mpledge52 on February 22, 2008 2:18:56 PM]

Share this post

Link to post
Share on other sites
Yeah, the GLUT has only few fonts hardcoded as (small) bitmaps. You can use font libraries like freetype or SDL_TTF to load and render any truetype font you want to image(s), then use it as texture. There is also a Nehe tutorial on bitmap fonts although it uses some os-specific functions.

Share this post

Link to post
Share on other sites
Thanks snoutmate, do you know if the bitmap fonts used in the Nehe tutorial (or any other fonts for that matter) behave in the same way as the bitmap fonts I have used so far? i.e. the stay the same size no matter where the camera is positioned, and (more importantly) the text rotates to face the camera at all times.

Thanks again.

Share this post

Link to post
Share on other sites
That is different thing alltogether - if you want something drawn this way (text, HUD in games, etc.), you simply draw your scene, then set orthogonal projection matrix (glOrtho) and render the text (you'd also want to disable things like depth buffer and lighting usually for this pass).

Share this post

Link to post
Share on other sites
You could always use freetype. Here's my simple wrapper I use for loading and drawing text.

#ifndef _FT_WRAPPER_H
#define _FT_WRAPPER_H

#include <string>
#include <vector>
#include <ft2build.h>
#include FT_FREETYPE_H
#include FT_GLYPH_H

namespace freetype
// Glyph entry structure
// stores data for a single ascii character
struct GlyphEntry
unsigned char ascii, width, height;
unsigned short x, y;

// Font data structure
// stores all infomration pertaining to a loaded font
struct FontData
std::string fontFile;
float fontSize;
int pixelSize;
bool antiAlias;
unsigned char* imagePixels;
size_t imageWidth;
size_t imageHeight;

std::vector<GlyphEntry> glyphEntries;
unsigned char glyphBase;

// Frees any memory associated with FontData object
void FreeFont(FontData* font)
delete[] font->imagePixels;
delete font;

// Creates a truetype font from specified fontfile
FontData* LoadFont(const std::string& fontfile, float font_size, bool antialias)
// Create new FontData object
FontData* fontData = new FontData;
fontData->fontFile = fontfile;
fontData->fontSize = font_size;
fontData->antiAlias = antialias;

// Compute pixel size
size_t y_resolution = 96;
size_t pixel_size = font_size * y_resolution / 72;

// Margins around characters to prevent them from 'bleeding' into each other
const size_t margin = 3;
size_t image_height = 0;
size_t image_width = 256;

// Initialize FreeType
FT_Library library;
if (FT_Init_FreeType(&library) != 0)
throw "Could not initialize FreeType2 library.";

// Load the font
FT_Face face;
if (FT_New_Face(library, fontfile.c_str(), 0, &face) != 0)
throw "Could not load font file.";

// Abort if this is not a 'true type', scalable font
if (!(face->face_flags & FT_FACE_FLAG_SCALABLE) || !(face->face_flags && FT_FACE_FLAG_HORIZONTAL))
throw "Error setting font size.";

// Set the font size
FT_Set_Pixel_Sizes(face, pixel_size, 0);

// First we go over all the characters to find the max descent
// and ascent (space required above and below the base of a
// line of text) and needed image size. There are simpler methods
// to obtain these with FreeType but they are unreliable.
int max_descent = 0, max_ascent = 0;
size_t space_on_line = image_width - margin, lines = 1;

unsigned int startChar = 32;
unsigned int endChar = 126;
for (unsigned int i = startChar; i <= endChar; i++) {

// Look up the character in the font file
size_t char_index = FT_Get_Char_Index(face, i);

// Render the current glyph
FT_Load_Glyph(face, char_index, FT_LOAD_DEFAULT);
FT_Render_Glyph(face->glyph, FT_RENDER_MODE_NORMAL);

size_t advance = (face->glyph->metrics.horiAdvance >> 6) + margin;

// If the line is full, go to the next line
if (advance > space_on_line) {
space_on_line = image_width - margin;

space_on_line -= advance;

max_ascent = max(face->glyph->bitmap_top, max_ascent);
max_descent = max(face->glyph->bitmap.rows - face->glyph->bitmap_top, max_descent);

// Compute how high the texture has to be
size_t needed_image_height = (max_ascent + max_descent + margin) * lines + margin;

// Get the first power of two in which it fits
image_height = 16;
while (image_height < needed_image_height)
image_height *= 2;

// Allocate memory for the texture
unsigned char* image = new unsigned char[image_width * image_height];
for (unsigned int i = 0; i < image_width * image_height; i++)
image[i] = 0;

// Allocate space for the glyph entries
fontData->glyphEntries.resize(endChar - startChar + 1);
fontData->glyphBase = startChar;

// These are the positions at which to draw the next glyph
unsigned int x = margin, y = margin + max_ascent;

// Drawing loop
for (unsigned int i = startChar; i <= endChar; i++) {

unsigned int char_index = FT_Get_Char_Index(face, i);

// Handle antialias text
if (antialias == true) {

// Render the glyph
FT_Load_Glyph(face, char_index, FT_LOAD_DEFAULT);
FT_Render_Glyph(face->glyph, FT_RENDER_MODE_NORMAL);

// See whether the character fits on the current line
unsigned int advance = (face->glyph->metrics.horiAdvance >> 6) + margin;
if (advance > image_width - x) {
x = margin;
y += (max_ascent + max_descent + margin);

// Fill in the glyph entries
fontData->glyphEntries[i - startChar].ascii = (unsigned char)i;
fontData->glyphEntries[i - startChar].width = advance - margin;
fontData->glyphEntries[i - startChar].height = pixel_size;
fontData->glyphEntries[i - startChar].x = x;
fontData->glyphEntries[i - startChar].y = y - max_ascent;

// Copy the image gotten from FreeType onto the texture at the correct position
for (unsigned int row = 0; row < face->glyph->bitmap.rows; row++) {
for (unsigned int pixel = 0; pixel < face->glyph->bitmap.width; pixel++) {

image[(x + face->glyph->bitmap_left + pixel) + (y - face->glyph->bitmap_top + row) * image_width] =
face->glyph->bitmap.buffer[pixel + row * face->glyph->bitmap.pitch];

x += advance;
// Handle monochrome text
else {

// Render the glyph
FT_Bitmap* ft_bmp;
FT_Glyph glyph;
FT_BitmapGlyph bmp_glyph;

FT_Load_Glyph(face, char_index, FT_LOAD_DEFAULT);
FT_Render_Glyph(face->glyph, FT_RENDER_MODE_MONO);
FT_Get_Glyph(face->glyph, &glyph);

FT_Glyph_To_Bitmap(&glyph, FT_RENDER_MODE_MONO, 0, 1);

bmp_glyph = (FT_BitmapGlyph)glyph;
ft_bmp = &bmp_glyph->bitmap;

// See whether the character fits on the current line
unsigned int advance = (face->glyph->metrics.horiAdvance >> 6) + margin;
if (advance > image_width - x) {
x = margin;
y += (max_ascent + max_descent + margin);

// Fill in the glyph entries
fontData->glyphEntries[i - startChar].ascii = (unsigned char)i;
fontData->glyphEntries[i - startChar].width = advance - margin;
fontData->glyphEntries[i - startChar].height = pixel_size;
fontData->glyphEntries[i - startChar].x = x;
fontData->glyphEntries[i - startChar].y = y - max_ascent;

// Copy the image onto the texture at the correct position
unsigned char* monochromeData = ft_bmp->buffer;
int bit;

for (size_t row = 0; row < ft_bmp->rows; row++) {

unsigned char* nextPtr = monochromeData + ft_bmp->pitch;
bit = 7;

for (size_t pixel = 0; pixel < ft_bmp->width; pixel++) {

unsigned char value = (*monochromeData & (1 << bit)) >> bit;

image[(x + bmp_glyph->left + pixel) + (y - bmp_glyph->top + row) * image_width] = value;

if (bit == -1) {
bit = 7;

bit = 7;
monochromeData = nextPtr;

x += advance;


// Return FT_FontData object
fontData->pixelSize = pixel_size;
fontData->imagePixels = image;
fontData->imageWidth = image_width;
fontData->imageHeight = image_height;
return fontData;


freetype::FontData* font;
GLuint texID;

void init()
font = freetype::LoadFont("c:\\windows\\fonts\\arial.ttf", 9.0f, false);
CreateTextureFromFont(&fontTexID, *font);

void CreateTextureFromFont(GLuint* texID, const freetype::FontData& font)
glGenTextures(1, texID);
glBindTexture(GL_TEXTURE_2D, *texID);
glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, font.imageWidth, font.imageHeight, 0, GL_ALPHA, GL_UNSIGNED_BYTE, font.imagePixels);

void drawString(freetype::FontData* f, GLuint texID, std::string str)
if (f->antiAlias) {
else {
glAlphaFunc(GL_GREATER, 0);

glBindTexture(GL_TEXTURE_2D, texID);

glColor4f(0, 0, 1, 1);

float x = 0, y = 0;

for (int i = 0; i < str.size(); i++) {

freetype::GlyphEntry g = f->glyphEntries[str[i] - f->glyphBase];

float tx1 = g.x / (float)f->imageWidth;
float ty1 = g.y / (float)f->imageHeight;
float tx2 = (g.x + g.width) / (float)f->imageWidth;
float ty2 = (g.y + g.height) / (float)f->imageHeight;

glTexCoord2f(tx1, ty1); glVertex2i(x, y);
glTexCoord2f(tx2, ty1); glVertex2i(x + g.width, y);
glTexCoord2f(tx2, ty2); glVertex2i(x + g.width, y + g.height);
glTexCoord2f(tx1, ty2); glVertex2i(x, y + g.height);

x += g.width;


if (f->antiAlias) {
else {

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Announcements

  • Forum Statistics

    • Total Topics
    • Total Posts
  • Similar Content

    • By DejayHextrix
      Hi, New here. 
      I need some help. My fiance and I like to play this mobile game online that goes by real time. Her and I are always working but when we have free time we like to play this game. We don't always got time throughout the day to Queue Buildings, troops, Upgrades....etc.... 
      I was told to look into DLL Injection and OpenGL/DirectX Hooking. Is this true? Is this what I need to learn? 
      How do I read the Android files, or modify the files, or get the in-game tags/variables for the game I want? 
      Any assistance on this would be most appreciated. I been everywhere and seems no one knows or is to lazy to help me out. It would be nice to have assistance for once. I don't know what I need to learn. 
      So links of topics I need to learn within the comment section would be SOOOOO.....Helpful. Anything to just get me started. 
      Dejay Hextrix 
    • By mellinoe
      Hi all,
      First time poster here, although I've been reading posts here for quite a while. This place has been invaluable for learning graphics programming -- thanks for a great resource!
      Right now, I'm working on a graphics abstraction layer for .NET which supports D3D11, Vulkan, and OpenGL at the moment. I have implemented most of my planned features already, and things are working well. Some remaining features that I am planning are Compute Shaders, and some flavor of read-write shader resources. At the moment, my shaders can just get simple read-only access to a uniform (or constant) buffer, a texture, or a sampler. Unfortunately, I'm having a tough time grasping the distinctions between all of the different kinds of read-write resources that are available. In D3D alone, there seem to be 5 or 6 different kinds of resources with similar but different characteristics. On top of that, I get the impression that some of them are more or less "obsoleted" by the newer kinds, and don't have much of a place in modern code. There seem to be a few pivots:
      The data source/destination (buffer or texture) Read-write or read-only Structured or unstructured (?) Ordered vs unordered (?) These are just my observations based on a lot of MSDN and OpenGL doc reading. For my library, I'm not interested in exposing every possibility to the user -- just trying to find a good "middle-ground" that can be represented cleanly across API's which is good enough for common scenarios.
      Can anyone give a sort of "overview" of the different options, and perhaps compare/contrast the concepts between Direct3D, OpenGL, and Vulkan? I'd also be very interested in hearing how other folks have abstracted these concepts in their libraries.
    • By aejt
      I recently started getting into graphics programming (2nd try, first try was many years ago) and I'm working on a 3d rendering engine which I hope to be able to make a 3D game with sooner or later. I have plenty of C++ experience, but not a lot when it comes to graphics, and while it's definitely going much better this time, I'm having trouble figuring out how assets are usually handled by engines.
      I'm not having trouble with handling the GPU resources, but more so with how the resources should be defined and used in the system (materials, models, etc).
      This is my plan now, I've implemented most of it except for the XML parts and factories and those are the ones I'm not sure of at all:
      I have these classes:
      For GPU resources:
      Geometry: holds and manages everything needed to render a geometry: VAO, VBO, EBO. Texture: holds and manages a texture which is loaded into the GPU. Shader: holds and manages a shader which is loaded into the GPU. For assets relying on GPU resources:
      Material: holds a shader resource, multiple texture resources, as well as uniform settings. Mesh: holds a geometry and a material. Model: holds multiple meshes, possibly in a tree structure to more easily support skinning later on? For handling GPU resources:
      ResourceCache<T>: T can be any resource loaded into the GPU. It owns these resources and only hands out handles to them on request (currently string identifiers are used when requesting handles, but all resources are stored in a vector and each handle only contains resource's index in that vector) Resource<T>: The handles given out from ResourceCache. The handles are reference counted and to get the underlying resource you simply deference like with pointers (*handle).  
      And my plan is to define everything into these XML documents to abstract away files:
      Resources.xml for ref-counted GPU resources (geometry, shaders, textures) Resources are assigned names/ids and resource files, and possibly some attributes (what vertex attributes does this geometry have? what vertex attributes does this shader expect? what uniforms does this shader use? and so on) Are reference counted using ResourceCache<T> Assets.xml for assets using the GPU resources (materials, meshes, models) Assets are not reference counted, but they hold handles to ref-counted resources. References the resources defined in Resources.xml by names/ids. The XMLs are loaded into some structure in memory which is then used for loading the resources/assets using factory classes:
      Factory classes for resources:
      For example, a texture factory could contain the texture definitions from the XML containing data about textures in the game, as well as a cache containing all loaded textures. This means it has mappings from each name/id to a file and when asked to load a texture with a name/id, it can look up its path and use a "BinaryLoader" to either load the file and create the resource directly, or asynchronously load the file's data into a queue which then can be read from later to create the resources synchronously in the GL context. These factories only return handles.
      Factory classes for assets:
      Much like for resources, these classes contain the definitions for the assets they can load. For example, with the definition the MaterialFactory will know which shader, textures and possibly uniform a certain material has, and with the help of TextureFactory and ShaderFactory, it can retrieve handles to the resources it needs (Shader + Textures), setup itself from XML data (uniform values), and return a created instance of requested material. These factories return actual instances, not handles (but the instances contain handles).
      Is this a good or commonly used approach? Is this going to bite me in the ass later on? Are there other more preferable approaches? Is this outside of the scope of a 3d renderer and should be on the engine side? I'd love to receive and kind of advice or suggestions!
    • By nedondev
      I 'm learning how to create game by using opengl with c/c++ coding, so here is my fist game. In video description also have game contain in Dropbox. May be I will make it better in future.
    • By Abecederia
      So I've recently started learning some GLSL and now I'm toying with a POM shader. I'm trying to optimize it and notice that it starts having issues at high texture sizes, especially with self-shadowing.
      Now I know POM is expensive either way, but would pulling the heightmap out of the normalmap alpha channel and in it's own 8bit texture make doing all those dozens of texture fetches more cheap? Or is everything in the cache aligned to 32bit anyway? I haven't implemented texture compression yet, I think that would help? But regardless, should there be a performance boost from decoupling the heightmap? I could also keep it in a lower resolution than the normalmap if that would improve performance.
      Any help is much appreciated, please keep in mind I'm somewhat of a newbie. Thanks!
  • Popular Now