Search code examples
c++openglglslfreetypefreetype2

OpenGL, FreeType2: italic characters overlay each other


I am trying to use FreeType (v2) library for 2D drawing in my OpenGL (v4.1) scene using C++. The text is rendered, but not correctly: one glyph hides another. How to prevent this behavior? My drawing code is below:

void CFreeTypeFont::Print(string sText, int x, int y, int iPXSize) {
    glBindVertexArray(uiVAO);
    glUniform1i(shp->uniform("gSampler"), 0);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    int iCurX = x, iCurY = y;
    if(iPXSize == -1)iPXSize = iLoadedPixelSize;
    float fScale = float(iPXSize)/float(iLoadedPixelSize);
    FOR(i, ESZ(sText)) {
        if(sText[i] == '\n') {
            iCurX = x;
            iCurY -= iNewLine*iPXSize/iLoadedPixelSize;
            continue;
        }
        int iIndex = int(sText[i]);
        iCurX += iBearingX[iIndex]*iPXSize/iLoadedPixelSize;
        if(sText[i] != ' ') {
            tCharTextures[iIndex].BindTexture(0);
            glm::mat4 mModelView = glm::translate(glm::mat4(1.0f), glm::vec3(float(iCurX), float(iCurY), 0.0f));
            mModelView = glm::scale(mModelView, glm::vec3(fScale));

            glUniformMatrix4fv(shp->uniform("matrices.modelViewMatrix"),
                               1, GL_FALSE, glm::value_ptr(mModelView));

            // Draw character
            glDrawArrays(GL_TRIANGLE_STRIP, iIndex*4, 4);
        }

        iCurX += (iAdvX[iIndex]-iBearingX[iIndex])*iPXSize/iLoadedPixelSize;
    }
    glDisable(GL_BLEND);
}

The output is like this:

Must be "Hellow, World!"

If I disable blend mode, then picture clearly shows characters overlaying:

The same text without opacity

My vertex shader:

#version 410

uniform struct Matrices {
    mat4 modelViewMatrix;
} matrices;

uniform float screenWidth;
uniform float screenHeight;

layout (location = 0) in vec2 inPosition;
layout (location = 1) in vec2 inCoord;

out vec2 texCoord;

void main() {
    texCoord = inCoord;
    vec4 pre = matrices.modelViewMatrix*vec4(inPosition, 0.0, 1.0);
    pre.x = pre.x / screenWidth - 1;
    pre.y = pre.y / screenHeight - 1;
    gl_Position = pre;
}

The fragment shader:

#version 410

in vec2 texCoord;
out vec4 outputColor;

uniform sampler2D gSampler;
uniform vec4 vColor;

void main() {
    vec4 vTexColor = texture(gSampler, texCoord);
    outputColor = vTexColor*vColor;
}

Solution

  • The results look as if you haven't disabled depth testing when rendering the fonts. The depth-test prevents other glyphs from being drawn at the same position as previous ones.

    To disable depth-testing call

    glDisable(GL_DEPTH_TEST);