文本未正确呈现-使用FreeType2的OpenGL

4
几乎是相同的重复问题: OpenGL字体渲染使用Freetype2
我正在尝试��用FreeType2(2.5.3)在我的OpenGL程序中呈现文本,基于这个教程:http://en.wikibooks.org/wiki/OpenGL_Programming/Modern_OpenGL_Tutorial_Text_Rendering_02,使用与Bentebent在他的问题中相同的结构体。 我遇到了他遇到的相同问题,矩形显示而非可读字符(即使使用正确的GL_TEXTURE0参数调用glActiveTexture())。
例如,呈现下面的绿色字符串"Hello""World":

Rendering 'Hello' and 'World'

与Bentebent一样,使用gDebugger我可以看到我的纹理生成得很好。 我已经搜遍了Google/StackOverflow,尝试了不同的glTexImage2D参数、不同的片段着色器中color公式等等,但是没有运气。 已经卡住了一段时间。 感谢您的任何帮助。

创建纹理图集的结构体:
//DrawTestOpenGLWnd.h
struct FontCharacter
{
    float advanceX;
    float advanceY;

    float bitmapWidth;
    float bitmapHeight;

    float bitmapLeft;
    float bitmapTop;

    float uvOffsetX;
    float uvOffsetY;
};

struct FontTextureAtlas
{
    GLuint texture;
    GLint textureUniform;

    int width;
    int height;

    FontCharacter characters[128];

    FontTextureAtlas(FT_Face face, int h, GLint tUniform)
    {
        FT_Set_Pixel_Sizes(face, 0, h);
        FT_GlyphSlot glyphSlot = face->glyph;

        int roww = 0;
        int rowh = 0;
        width = 0;
        height = 0;

        memset(characters, 0, sizeof(FontCharacter));

        for (int i = 32; i < 128; i++)
        {
            if (FT_Load_Char(face, i, FT_LOAD_RENDER))
            {
                TRACE("Loading character %c failed\n", i);
                continue;
            }

            if (roww + glyphSlot->bitmap.width + 1 >= MAX_WIDTH)
            {
                width = std::max(width, roww);
                height += rowh;
                roww = 0;
                rowh = 0;
            }

            roww += glyphSlot->bitmap.width + 1;
            rowh = std::max(rowh, glyphSlot->bitmap.rows);
        }

        width = std::max(width, roww);
        height += rowh;

        glGenTextures(1, &texture);

        if (glGetError() != GL_NO_ERROR){
            TRACE("glGenTextures failed\n");
        }

        glActiveTexture(GL_TEXTURE0);

        if (glGetError() != GL_NO_ERROR){
            TRACE("glActiveTexture failed\n");
        }

        glBindTexture(GL_TEXTURE_2D, texture);

        if (glGetError() != GL_NO_ERROR){
            TRACE("glBindTexture failed\n");
        }

        glUniform1i(tUniform, 0);
        textureUniform = tUniform;

        glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, width, height, 0, GL_RED, GL_UNSIGNED_BYTE, 0);

        if (glGetError() != GL_NO_ERROR){
            TRACE("glTexImage2D failed\n");
        }

        glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

        if (glGetError() != GL_NO_ERROR){
            TRACE("glPixelStorei failed\n");
        }

        glPixelStorei(GL_PACK_ALIGNMENT, 1);

        if (glGetError() != GL_NO_ERROR){
            TRACE("glPixelStorei failed\n");
        }

        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);

        if (glGetError() != GL_NO_ERROR){
            TRACE("glTexParameteri failed\n");
        }

        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

        if (glGetError() != GL_NO_ERROR){
            TRACE("glTexParameteri failed\n");
        }

        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

        if (glGetError() != GL_NO_ERROR){
            TRACE("glTexParameteri failed\n");
        }

        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

        if (glGetError() != GL_NO_ERROR){
            TRACE("glTexParameteri failed\n");
        }


        int ox = 0;
        int oy = 0;

        rowh = 0;

        for (int i = 32; i < 128; i++)
        {
            if (FT_Load_Char(face, i, FT_LOAD_RENDER)) {
                TRACE("Loading character %c failed\n", i);
                continue;
            }

            if (ox + glyphSlot->bitmap.width + 1 >= MAX_WIDTH) {
                oy += rowh;
                rowh = 0;
                ox = 0;
            }

            glTexSubImage2D(GL_TEXTURE_2D, 0, ox, oy, glyphSlot->bitmap.width, glyphSlot->bitmap.rows, GL_RED, GL_UNSIGNED_BYTE, glyphSlot->bitmap.buffer);

            if (glGetError() != GL_NO_ERROR) {
                TRACE("BORKED AGAIN\n");
            }

            characters[i].advanceX = glyphSlot->advance.x >> 6;
            characters[i].advanceY = glyphSlot->advance.y >> 6;

            characters[i].bitmapWidth = glyphSlot->bitmap.width;
            characters[i].bitmapHeight = glyphSlot->bitmap.rows;

            characters[i].bitmapLeft = glyphSlot->bitmap_left;
            characters[i].bitmapTop = glyphSlot->bitmap_top;

            characters[i].uvOffsetX = ox / (float)width;
            characters[i].uvOffsetY = oy / (float)height;

            rowh = std::max(rowh, glyphSlot->bitmap.rows);
            ox += glyphSlot->bitmap.width + 1;
        }

        TRACE("Generated a %d x %d (%d kb) texture atlas.\n", width, height, width * height / 1024);
    }

    ~FontTextureAtlas()
    {
        glDeleteTextures(1, &texture);
    }
};

InitFreeType函数:

void DrawTestOpenGLWnd::InitFreeType(char * strFontFilePath)
{

    m_error = FT_Init_FreeType(&m_library);
    if (m_error) {
        TRACE("An error occurred during library initialization");
    }

    m_error = FT_New_Face(m_library, strFontFilePath, 0, &m_face);
    if (m_error == FT_Err_Unknown_File_Format) {
        TRACE("Font file could be opened and read, but it appears that its font format is unsupported");
    }
    else if (m_error) {
        TRACE("Font file could not be opened or read. Or it's broken.");
    }

    m_program_text = LoadShaders("TextVertexShader.vertexshader", "TextFragmentShader.fragmentshader");
    glUseProgram(m_program_text);

    m_uniform_texture = glGetUniformLocation(m_program_text, "texture");
    m_uniform_textColor = glGetUniformLocation(m_program_text, "textColor");

    glGenVertexArrays(1, &vao_text);
    glBindVertexArray(vao_text);

    glGenBuffers(1, &vbo_text);
    //glBindBuffer(GL_ARRAY_BUFFER, vbo_text);

    a48 = new FontTextureAtlas(m_face, 48, m_uniform_texture);
    a24 = new FontTextureAtlas(m_face, 24, m_uniform_texture);
    a12 = new FontTextureAtlas(m_face, 12, m_uniform_texture);
}

RenderText函数:

void DrawTestOpenGLWnd::RenderText(char * text, FontTextureAtlas * atlas, float x, float y, float sx, float sy)
{
    glUseProgram(m_program_text);
    const unsigned char* p;

    std::vector<glm::vec4> coords;

    int c = 0;

    for (p = (const unsigned char*)text; *p; p++)
    {
        float x2 = x + atlas->characters[*p].bitmapLeft * sx;
        float y2 = -y - atlas->characters[*p].bitmapTop * sy;
        float w = atlas->characters[*p].bitmapWidth * sx;
        float h = atlas->characters[*p].bitmapHeight * sy;

        x += atlas->characters[*p].advanceX * sx;
        y += atlas->characters[*p].advanceY * sy;

        if (!w || !h)
            continue;

        coords.push_back(
            glm::vec4(
            x2,
            -y2,
            atlas->characters[*p].uvOffsetX,
            atlas->characters[*p].uvOffsetY)
            );


        coords.push_back(
            glm::vec4(
            x2 + w,
            -y2,
            atlas->characters[*p].uvOffsetX + atlas->characters[*p].bitmapWidth / atlas->width,
            atlas->characters[*p].uvOffsetY)
            );



        coords.push_back(
            glm::vec4(
            x2,
            -y2 - h,
            atlas->characters[*p].uvOffsetX,
            atlas->characters[*p].uvOffsetY + atlas->characters[*p].bitmapHeight / atlas->height)
            );



        coords.push_back(
            glm::vec4(
            x2 + w,
            -y2,
            atlas->characters[*p].uvOffsetX + atlas->characters[*p].bitmapWidth / atlas->width,
            atlas->characters[*p].uvOffsetY)
            );


        coords.push_back(
            glm::vec4(
            x2,
            -y2 - h,
            atlas->characters[*p].uvOffsetX,
            atlas->characters[*p].uvOffsetY + atlas->characters[*p].bitmapHeight / atlas->height)
            );


        coords.push_back(
            glm::vec4(
            x2 + w,
            -y2 - h,
            atlas->characters[*p].uvOffsetX + atlas->characters[*p].bitmapWidth / atlas->width,
            atlas->characters[*p].uvOffsetY + atlas->characters[*p].bitmapHeight / atlas->height)
            );
    }

    glBindVertexArray(vao_text);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    glActiveTexture(GL_TEXTURE0);
    glUniform1i(atlas->textureUniform, 0);
    glBindTexture(GL_TEXTURE_2D, atlas->texture);

    GLfloat textColor[4] = {0.0, 1.0, 0.0, 0.}; //green
    glUniform4fv(m_uniform_textColor, 1, textColor);

    glBindBuffer(GL_ARRAY_BUFFER, vbo_text);
    glBufferData(GL_ARRAY_BUFFER, coords.size() * sizeof(glm::vec4), coords.data(), GL_DYNAMIC_DRAW);

    //Position
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(glm::vec4), (void*)0);

    glDrawArrays(GL_TRIANGLES, 0, coords.size());

    glDisableVertexAttribArray(0);

    glBindVertexArray(0);
    glUseProgram(0);
}

TextVertexShader.vertexshader:

#version 330 core

layout(location = 0) in vec4 pos_uv;
out vec2 uv;

void main(void) {
  gl_Position = vec4(pos_uv.xy, 0, 1);
  uv = pos_uv.zw;
}

TextFragmentShader.fragmentshader:

#version 330 core

in vec2 uv;
uniform sampler2D texture;
uniform vec4 textColor;

out vec4 color;

void main(void) {
  color = vec4(textColor.rgb, texture2D(texture, uv).a);
}

这个例子看起来很有前途:https://github.com/rougier/freetype-gl 更一般的问题:https://dev59.com/wWox5IYBdhLWcg3w_JLd - Ciro Santilli OurBigBook.com
你在说什么?这个字体渲染看起来很好啊! - Andrew
2个回答

4

您的纹理格式为R8,因此仅包含R通道。您的着色器似乎使用A通道。 比较这两行代码:

glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, width, height, 0, GL_RED, 
             GL_UNSIGNED_BYTE, 0);
 ...
glTexSubImage2D(GL_TEXTURE_2D, 0, ox, oy, glyphSlot->bitmap.width,
                glyphSlot->bitmap.rows, GL_RED, ...

vs

color = vec4(textColor.rgb, texture2D(texture, uv).a);

如果您的OpenGL版本小于3.0,我建议将GL_R8GL_RED更改为GL_ALPHA8GL_ALPHA,否则请将texture2D(texture, uv).a更改为texture2D(texture, uv).r


好的!非常感谢!这是我自己的愚蠢错误。教程使用了GL_ALPHA,但这在我的OpenGL 3.3版本中是无效的,所以当我将glTexImage2DglTexSubImage2D更改为使用GL_RED时,我忘记了我的着色器。我将我的着色器更改为texture2D(texture, uv).r,现在文本可以正确地渲染了。 - Tur1ng
@Tur1ng,您说的“GL_ALPHA无效”的意思是什么? - UB-
1
@UB- GL_ALPHA是有效的,但从不包含alpha通道的纹理中采样这个通道会返回0.0。 - Anonymous

3
这是我的工作代码,根据匿名建议:
在 FontCharacterAtlas 结构中:
glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, width, height, 0, GL_RED, 
             GL_UNSIGNED_BYTE, 0);
 ...
glTexSubImage2D(GL_TEXTURE_2D, 0, ox, oy, glyphSlot->bitmap.width, glyphSlot->bitmap.rows, 
                GL_RED, GL_UNSIGNED_BYTE, glyphSlot->bitmap.buffer);

在TextFragmentShader.fragmentshader文件中:
color = vec4(textColor.rgb, texture2D(texture, uv).r);

文本可以呈现,尽管不太美观(一些字符的边缘稍微被切掉了,当使用a24或a12图集时,字体会很混乱),但这是另一回事。

由于您的纹理过滤器为GL_LINEAR,所以您应该确保在所有边缘上为字形添加1像素的边框,以避免与相邻字形产生溢出(GL_LINEAR过滤器会对4个最近的纹素进行采样并使用加权平均值)。这将解决大多数仅在使用GL_LINEAR过滤而不是GL_NEAREST时出现的问题。根据您所参考的教程判断,它试图紧密打包字形,而这对于GL_LINEAR过滤来说是不适当的。 - Andon M. Coleman
@AndonM.Coleman 感谢您的建议。我该如何在字形周围添加1个像素边框? - Tur1ng

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接