渲染FreeType字体

时间:2014-04-04 16:23:12

标签: c++ opengl opengl-3 freetype2

我一直在尝试在OpenGL 3中渲染FreeType2字体。我使用了NeHe的教程http://nehe.gamedev.net/tutorial/freetype_fonts_in_opengl/24001/。但是,我对现代OpenGL 3+进行了一些修改。实际上,我使用glBufferData(...,GL_DYNAMIC_DRAW)来更新每个字符的顶点缓冲区。顶点数组是在字形加载期间创建的,因为NeHe使用显示列表:

    int width = next_p2(bitmap.width);
    int height = next_p2(bitmap.rows);

    float   x=(float)bitmap.width / (float)width,
        y= (float)bitmap.rows / (float)height;


    using namespace glm;
    glyphsVertices[c] = new pxgVertex2dT[4];
    glyphsVertices[c][0] = {  vec2(0,bitmap.rows), vec2(0,y) };
    glyphsVertices[c][1] = {  vec2(0,0), vec2(0,0) };
    glyphsVertices[c][2] = {  vec2(bitmap.width,0), vec2(x,0) };
    glyphsVertices[c][3] = {  vec2(bitmap.width,bitmap.rows), vec2(x,y) };

glyphVertices是这种结构的二维数组:

   struct Vertex2dT
   {
       glm::vec2 pos;
       glm::vec2 texCoord;
   };

不幸的是,我得到以下结果:

Code Result

那么,我做错了什么?

2 个答案:

答案 0 :(得分:2)

发生了两件事:你的代码假定左上角是视口的原点,而实际上它位于左下角,这意味着你的图像是垂直翻转的。

FreeType也会在左上角渲染带有原点的字形图像,这会对齐几何体的y-flip,因此字符看起来是直立的。

答案 1 :(得分:2)

正如SAKrisT正确指出的那样,问题是由Y轴的错误偏移引起的。玩了一下代码,我想出了解决方案:

   if(FT_Load_Char(face, c, FT_LOAD_RENDER))
     return;

    FT_GlyphSlot g = face->glyph;

    int width = next_p2(g->bitmap.width);
    int height = next_p2(g->bitmap.rows);

    ...

    float   x=(float)g->bitmap.width / (float)width,
            y= (float)g->bitmap.rows / (float)height;



    float x2 = g->bitmap_left;
    float y2 = g->bitmap_top;
    float w = g->bitmap.width;
    float h = g->bitmap.rows;


    using namespace glm;
    glyphsVertices[c] = new pxgVertex2dT[4];
    glyphsVertices[c][0] = {  vec2(0,h-y2), vec2(0,y) };
    glyphsVertices[c][1] = {  vec2(0,-y2), vec2(0,0) };
    glyphsVertices[c][2] = {  vec2(w,-y2), vec2(x,0) };
    glyphsVertices[c][3] = {  vec2(w,h-y2), vec2(x,y) };

现在它完美无缺!

相关问题