Posts
Search
Contact
Cookies
About
RSS

OpenGL string printer

Added 2 Jan 2015, 9:40 p.m. edited 19 Jun 2023, 3:22 a.m.

glprint

Well... I meant to do this a lot earlier and indeed having this would have saved me flooding the console with junk - not an ideal way to debug! I wanted a few things from my string printer, first of all I wanted it to scale with the screen (regardless of screen ratio) I decided to have characters nominally 16x16 (but the textures are larger than this, at a nominal resolution of 640x480 this gives 40x30 characters on the screen. Because my codebase can be easily "ported" to GLES I decided to keep my texture size to a power of 2 size (512x256) A texture of this size allows a character cell of 32x42 pixels for each characters texture, remember on a desktop the screen resolution could be large enough to need a decent sized texture. A character cell of 42 pixels high actually only uses 252 lines of the texture but we can live with 4 wasted lines. Of course if you have a more modest target you can always have a 256x128 texture with 16x22 characters... Although I'm using a boring white font, there is no reason at all that you can't use a multi coloured texture or even with some easy modification an animated texture. In the example code I've included below and as you can see in the above screenshot, I'm using two sizes of fonts, to use my routines first you must set up the string printer

        Print printer =  new Print("data/font.png",24,32);
        Print smlPrint = new Print("data/font.png",16,16);
16x16 is our nominal font size, so simply supply a larger size when you create the string printing object if you want a BIG FONT!. Two things need to be done before actually printing
glEnable (GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
printer.preRender(width,height);
first set up your blending - this is separate as you may well already be using this blending mode, leading to unnecessary state changes. Next we tell the printer we're just about to render, this gives the printer the opportunity to set up OpenGL the way it needs to - selecting the buffers and shaders etc. The width and height we supply is the current size of our window (not our nominal 640x480) Now we can actually print
printer.render(20,20,"Hello");
printer.render(60,40,"World!");
The x & y coordinate are using our nominal 640x480 resolution thats scaled to the current screen resolution. finally allow the printer to tidy up
printer.postRender();
and thats all there is to it... here's the code Enjoy!