Coding update: 2D Text Rendering

Making things a lot simpler

I’ve reworked the code for bitmap fonts that I had before. What I had previously was working but in the end was very complicated for no reason.

The new font library has the following (limited) features:

  • request any TrueType font installed on the system, with some options (size, italic, bold, anti-aliased)
  • using GDI, draw a bitmap of each character in a grid fashion and save in memory
    • draw white characters on black background (choosing white for recoloring text just by multiplying the color)
    • drawing with 24-bit RGB colors, another step is required to transform to 32-bit RGBA, filtering black pixels to become transparent pixels
  • save each glyph metrics (limited to space of each character, before / after spacing) and UV coords
  • bundle data in a Font C struct
typedef struct {
	uint  width;
	int   spacing_before;
	int   glyph_width;
	int   spacing_after;
	float uv_x;
	float uv_y;
	float uv_width;
	float uv_height;
} Glyph;

typedef struct {
	char      name[64];
	uint      size;
	bool      italic;
	bool      bold;
	bool      anti_aliased;
	Image    *image;
	Glyph     data[256];
} Font;

There, it’s very basic, but it actually has everything needed to render text.

It wasn’t too difficult to use that in an openGL sample

  • import the font image to create the texture
  • use a textured quad for each character
    • the font libary has a function to get UV coords of each glyph
  • enable blending

And voila!

Sadly this obviously only works on Windows, I might have a hard time porting it on other platforms, though I’ll always have the option of pre-baking my bitmap fonts on Windows and embed those in libraries.

Why do all this while something like freetype exists? Well I don’t want to add any more dependencies. I feel like I have too many already.

What’s next?

I will work on completing unit tests for base libraries (math, core, image). That will certainly take quite a bit of time, but it’s been nagging at me for a while now.

I won’t write unit tests for higher level libraries, but I think those three are basic enough to warrant to be checked thoroughly, and that a bug in those functions could cause me a lot of headaches later on.

Unfortunately I don’t expect to have cool results to showcase in the near future… actually a fully fledged unit test suite is kind of cool in itself, it’s bug-proofing the code!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: