Search code examples
openglfreetype2

FreeType2 Multiple characters and random colors


I'm using FreeType2 library for Text rendering in my OpenGL program. I have a buffer array for rgb values for screen. For text rendering first i initialize FreeType2 library, then load a font, set pixel size and get A char then get bitmap of that glyph, merge glyph bitmap and my buffer array then use glTexSubImage2D function and render. And i got this result.

Render result

My FreeType2 code is:

assert(FT_Init_FreeType(&console->library) == 0);
assert(FT_New_Face(console->library, "data/pixelize.ttf", 0, &console->face) == 0);

assert(FT_Set_Pixel_Sizes(console->face, 0, 32) == 0);

FT_UInt glyphIndex;
glyphIndex = FT_Get_Char_Index(console->face, 'A');

assert(FT_Load_Glyph(console->face, glyphIndex, FT_LOAD_DEFAULT) == 0);
assert(FT_Render_Glyph(console->face->glyph, FT_RENDER_MODE_NORMAL) == 0);

FT_Bitmap bmp = console->face->glyph->bitmap;
_tpCopyTextToConsoleBuffer(console, bmp, 10, 10);

And _tpCopyTextToConsoleBuffer method is

int bitmapWidth = bmp.width;
int bitmapHeight = bmp.rows;

int cbx = x; // x
int cby = y;

for(int yy = 0; yy < bitmapHeight; yy++) {
    for(int xx = 0; xx < bitmapWidth; xx++) {
        int cbIndex = _tpGetIndex(console, cbx, cby);
        int bmpIndex = (yy * bitmapWidth + xx) * 3;

        console->buffer[cbIndex] = bmp.buffer[bmpIndex];
        console->buffer[cbIndex + 1] = bmp.buffer[bmpIndex + 1];
        console->buffer[cbIndex + 2] = bmp.buffer[bmpIndex + 2];

        cbx++;
    }
    cbx = x;
    cby++;
}

_tpUpdateTexture(console);

What is wrong with my code?


Solution

  • The FT_RENDER_MODE_NORMAL mode rasterizes an 8-bit grayscale image. Therefore if you convert it to RGB use:

    for(int yy = 0; yy < bmp.rows; yy++) {
        for(int xx = 0; xx < bmp.width; xx++) {
            uint8_t *p = console->buffer + _tpGetIndex(console, x + xx, y + yy);
            const uint8_t *q = bmp.buffer + yy * bmp.pitch + xx;
            p[0] = p[1] = p[2] = *q;
        }
    }
    

    Also avoid using the assert(f() == 0) construct, because if you turn off the asserts with the NDEBUG switch then the functions won't be called at all.