SDL_TTF渲染垃圾到纹理

时间:2016-11-15 11:56:37

标签: c++ opengl sdl-ttf

我正在尝试使用OpenGL和SDL,使用SDL_ttf将文本渲染到纹理,但代码呈现垃圾。

我的“渲染到纹理代码”:

GLuint textToTexture(std::string & text, TTF_Font* font, glm::vec4 textColour, glm::vec4 bgColour)
{
    if (!TTF_WasInit())
    {
        if (TTF_Init() == -1)
            exit(6);
    }
    SDL_Color colour = { (Uint8)(textColour.r*255), (Uint8)(textColour.g*255), (Uint8)(textColour.b*255), (Uint8)(textColour.a*255) };
    SDL_Color bg = { (Uint8)(bgColour.r*255), (Uint8)(bgColour.g*255), (Uint8)(bgColour.b*255), (Uint8)(bgColour.a*255) };

    SDL_Surface *stringImage = NULL;
    stringImage = TTF_RenderText_Blended(font, text.c_str(), colour);

    if (stringImage == NULL)
    {
        exit(5);
    }

    GLuint trueH = powerofTwo(stringImage->h);
    GLuint trueW = powerofTwo(stringImage->w);
    unsigned char* pixels = NULL;
    GLuint w = stringImage->w;
    GLuint h = stringImage->h;
    GLuint colours = stringImage->format->BytesPerPixel;
    pixels = padTexture((unsigned char*)stringImage->pixels, w, h, pixels, trueW, trueH, colours);
    GLuint format, internalFormat;
    if (colours == 4) {  

        if (stringImage->format->Rmask == 0x000000ff)
            format = GL_RGBA;
        else
            format = GL_BGRA;
    }
    else {      

        // no alpha
        if (stringImage->format->Rmask == 0x000000ff)
            format = GL_RGB;
        else
            format = GL_BGR;
    }
    internalFormat = (colours == 4) ? GL_RGBA : GL_RGB;


    GLuint texId = 0;
    //GLuint texture;

    glGenTextures(1, &texId);

    glBindTexture(GL_TEXTURE_2D, texId);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, trueW, trueH, 0,format, GL_UNSIGNED_BYTE, pixels);

    // SDL surface was used to generate the texture but is no longer
    // required. Release it to free memory
    SDL_FreeSurface(stringImage);
    free(pixels)
    return texId;
}

用于计算填充的正确尺寸的代码:

int powerofTwo(int num)
{
    if (num != 0)
    {
        num--;
        num |= num >> 1;   // Divide by 2^k for consecutive doublings of k up to 32,
        num |= num >> 2;   // and then or the results.
        num |= num >> 4;
        num |= num >> 8;
        num |= num >> 16;
        num++;
    }
    return num;
}

最后,将字节复制到正确尺寸的纹理的代码:

unsigned char* padTexture(unsigned char * src, int srcW, int srcH, unsigned char * dest, int width, int height, int bpp)
{
    dest = (unsigned char*)calloc(1, width*height*bpp);
    for (int i = 0; i < srcH; i++)
    {
        memcpy(dest + (width*i*bpp),src + (srcW*i*bpp), srcW*bpp);
    }
    return dest;
}

此代码的结果如下:[![乱码纹理] [1]] [1]

我已确认并检查错误,SDL_TTF已在代码库中的其他位置正确初始化,并且字体也正在加载。 我已经测试了三种不同的ttf字体,结果相同。

此外,如果我使用任何其他TTF_rendering函数(阴影,实体等),渲染一个实心四边形,textToTexture函数中的“colors”变量也最终为1。

其他:

正如我之前所说,我测试了三种ttf字体: MavenPro-Regular,

HelveticaNeueLTStd-Th

另一个我在互联网上找到了。 我试图渲染字符串“Select Scenario”。

预填充图像尺寸为138x25像素。

填充后的图片尺寸为256x32像素。

更新1:

修复bpp问题后,新纹理如下:

New garbled

每次运行程序时,此图像都会更改。

更新2: 通过填充图像来修复附加的斑点错误,并将像素数据设置为纹理本身,当我使用TTF_RenderText_Blended时,我得到的是一个黑色四边形,当我使用TTF_RenderText_Shaded时,我得到:< / p>

enter image description here

更新3:

我在调用GL代码之前立即使用SDL_SaveBMP,在调用SDL_RenderText_Blended之后,结果是一个完全白色的图像(给定哪种文本颜色)。

当我使用TTF_RenderText_Solid执行相同操作时,保存的图像应该是这样,但是由opengl呈现,就像上面看到的图像一样。

SDL_TTF初始化正常,字体加载没有错误,文本渲染没有返回错误,所以我想不出下一步该做什么。

更新4:

我已经将所有ttf代码重构为单个函数并删除了填充代码(因为现代opengl似乎并不关心它)。但是,尽管所有项目设置和代码现在都与已知在同一硬件上工作的测试项目相同,但问题仍然存在。

GLuint textToTexture(const char * text, const char * font, glm::vec4 textColour, glm::vec4 bgColour, unsigned int & texID)
{
    if (!TTF_WasInit()) {
        if (TTF_Init() == -1)
            exit(6);
    }
    SDL_Color colour = { (Uint8)(textColour.r * 255), (Uint8)(textColour.g * 255), (Uint8)(textColour.b * 255),(Uint8)(textColour.a * 255) };
    SDL_Color bg = { (Uint8)(bgColour.r * 255), (Uint8)(bgColour.g * 255), (Uint8)(bgColour.b * 255),255 };
    TTF_Font* fontObj = TTF_OpenFont(font, 24);
    if (!fontObj)
    {
        SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR,
            "Texture Error",
            "Cannot load font to create texture.",
            NULL);
        return 0;
    }
    SDL_Surface *image = NULL;
    image = TTF_RenderText_Blended(fontObj, text, colour);
    if (image == NULL)
    {
        exit(5);
        //exitFatalError("String surface not created.");
        std::cout << "String surface not created." << std::endl;

    }
    unsigned char* pixels = NULL;
    GLuint w = image->w;
    GLuint h = image->h;
    GLuint colours = image->format->BytesPerPixel;
    GLuint externalFormat, internalFormat;
    SDL_PixelFormat *format = image->format;
    if (colours == 4) {

        if (image->format->Rmask == 0x000000ff)
            externalFormat = GL_RGBA;
        else
            externalFormat = GL_BGRA;
    }
    else {

        // no alpha
        if (image->format->Rmask == 0x000000ff)
            externalFormat = GL_RGB;
        else
            externalFormat = GL_BGR;
    }
    internalFormat = (colours == 4) ? GL_RGBA : GL_RGB;


    GLuint texId = 0;
    //GLuint texture;

    glGenTextures(1, &texID);

    glBindTexture(GL_TEXTURE_2D, texID);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, w, h, 0, externalFormat, GL_UNSIGNED_BYTE, image->pixels);
    //glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, trueW, trueH, 0, externalFormat, GL_UNSIGNED_BYTE, pixels);
    glGenerateMipmap(GL_TEXTURE_2D);

    //// SDL surface was used to generate the texture but is no longer
    //// required. Release it to free memory
    SDL_FreeSurface(image);
    TTF_CloseFont(fontObj);
    return texID;
}

我有一个解决方法,可以将图像保存到bmp,然后重新加载并创建纹理,但只有在我使用TTF_RenderText_Shaded时。如果我使用TTF_RenderText_Blended,我会得到一个与文字颜色相对应的单色图像。

1 个答案:

答案 0 :(得分:2)

glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, trueH, trueW, 0,format, GL_UNSIGNED_BYTE, pixels);

trueHtrueW订单相反

memcpy(src + (srcW*i*bpp), dest + (width*i*bpp), srcW*bpp);

来源和目的地顺序相反。

dest = (unsigned char*)calloc(0, width*height*bpp);

分配了大小为width*height*bpp的0个元素,即0个字节。应为1而不是0。

这是一个完整的例子:

#include <SDL2/SDL.h>
#include <GL/gl.h>
#include <SDL2/SDL_ttf.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

static unsigned char* padTexture(unsigned char * src, int srcW, int srcH, unsigned char * dest, int width, int height, int bpp, const SDL_Palette *palette)
{
    int dst_bpp = (bpp == 1) ? 4 : bpp;
    dest = (unsigned char*)calloc(1, width*height*dst_bpp);
    if(bpp != 1) {
        for (int i = 0; i < srcH; i++)
        {
            memcpy(dest + (width*i*bpp), src + (srcW*i*bpp), srcW*bpp);
        }
    } else {
        /* indexed - read colours from palette */
        for(int i = 0; i < srcH; i++) {
            for(int j = 0; j < srcW; j++) {
                memcpy(dest + (width*i+j)*dst_bpp,
                        &palette->colors[src[srcW*i+j]], sizeof(SDL_Color));
            }
        }
    }
    return dest;
}

static int powerofTwo(int num) {
    if (num != 0)
    {
        num--;
        num |= num >> 1;   // Divide by 2^k for consecutive doublings of k up to 32,
        num |= num >> 2;   // and then or the results.
        num |= num >> 4;
        num |= num >> 8;
        num |= num >> 16;
        num++;
    }
    return num;
}

static GLuint textToTexture(const char *text, TTF_Font* font) {
    if (!TTF_WasInit()) {
        if (TTF_Init() == -1)
            exit(6);
    }
    SDL_Color colour = { 255, 255, 255, 255 };
    SDL_Color bg = { 0, 0, 0, 255 };

    SDL_Surface *stringImage = NULL;
//    stringImage = TTF_RenderText_Blended(font, text, colour);
    stringImage = TTF_RenderText_Shaded(font, text, colour, bg);

    if (stringImage == NULL) {
        exit(5);
    }

    GLuint trueH = powerofTwo(stringImage->h);
    GLuint trueW = powerofTwo(stringImage->w);
    unsigned char* pixels = NULL;
    GLuint w = stringImage->w;
    GLuint h = stringImage->h;
    GLuint colours = stringImage->format->BytesPerPixel;
    pixels = padTexture((unsigned char*)stringImage->pixels, w, h, pixels, trueW, trueH,
            colours, stringImage->format->palette);
    GLuint format, internalFormat;

    /* If indexed, want resulting image to be 32bit */
    if(colours == 1) {
        colours = 4;
    }

    if (colours == 4) {  

        if (stringImage->format->Rmask == 0x000000ff)
            format = GL_RGBA;
        else
            format = GL_BGRA;
    }
    else {      

        // no alpha
        if (stringImage->format->Rmask == 0x000000ff)
            format = GL_RGB;
        else
            format = GL_BGR;
    }
    internalFormat = (colours == 4) ? GL_RGBA : GL_RGB;


    GLuint texId = 0;
    //GLuint texture;

    glGenTextures(1, &texId);

    glBindTexture(GL_TEXTURE_2D, texId);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, trueW, trueH, 0,format, GL_UNSIGNED_BYTE, pixels);

    // SDL surface was used to generate the texture but is no longer
    // required. Release it to free memory
    SDL_FreeSurface(stringImage);
    free(pixels);
    return texId;
}

int main(int argc, char* argv[])
{
    SDL_Init(SDL_INIT_VIDEO);
    TTF_Init();

    SDL_Window *window = SDL_CreateWindow("SDL2 Example", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 600, 400, SDL_WINDOW_OPENGL);
    SDL_GLContext gl_ctx = SDL_GL_CreateContext(window);

    TTF_Font *font = TTF_OpenFont(".fonts/tahoma.ttf", 16);
    if(font) {
        printf("font loaded\n");
        textToTexture("Select Scenario", font);
        TTF_CloseFont(font);
    }

    int quit = 0;
    while(!quit) {
        SDL_Event ev;
        while(SDL_PollEvent(&ev)) {
            if(ev.type == SDL_QUIT || ev.type == SDL_KEYUP) {
                quit = 1;
            }
        }

        glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        glLoadIdentity();
        glEnable(GL_BLEND);
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
        glEnable(GL_TEXTURE_2D);
        glColor3f(1.0f, 1.0f, 1.0f);
        glBegin(GL_QUADS);
            glTexCoord2f(0, 1);
            glVertex2f(-0.5, -0.5);
            glTexCoord2f(0, 0);
            glVertex2f(-0.5, 0.5);
            glTexCoord2f(1, 0);
            glVertex2f(0.5, 0.5);
            glTexCoord2f(1, 1);
            glVertex2f(0.5, -0.5);
        glEnd();

        glFlush();
        SDL_GL_SwapWindow(window);
    }

    SDL_GL_DeleteContext(gl_ctx);
    SDL_DestroyWindow(window);

    TTF_Quit();
    SDL_Quit();

    return 0;
}