SDL_TTF和OPENGL协同工作时出现问题

Trouble having SDL_TTF and OPENGL work together

本文关键字:问题 协同工作 OPENGL TTF SDL      更新时间:2023-10-16

对于我正在开发的游戏,我希望在很多图形中使用OpenGL,在文本中使用SDL_TTF。我可以让两个人同时上班,但不能同时上班。这是我的代码(基于Lazy Foo):

#include "SDL/SDL.h"
#include "SDL/SDL_ttf.h"
#include "GL/gl.h"
const bool useOpenGl = true;
//The surfaces
SDL_Surface *message = NULL;
SDL_Surface *screen = NULL;
//The event structure
SDL_Event event;
//The font that's going to be used
TTF_Font *font = NULL;
//The color of the font
SDL_Color textColor = {255, 255, 255};
void apply_surface(int x, int y, SDL_Surface* source, SDL_Surface* destination, SDL_Rect* clip = NULL)
{
    //Holds offsets
    SDL_Rect offset;
    //Get offsets
    offset.x = x;
    offset.y = y;
    //Blit
    SDL_BlitSurface(source, clip, destination, &offset);
}
bool init()
{
    SDL_Init (SDL_INIT_EVERYTHING);
    if (useOpenGl)
    {
        screen = SDL_SetVideoMode (1280, 720, 32, SDL_SWSURFACE | SDL_OPENGL); //With SDL_OPENGL flag only opengl is sceen, without only text is
    } else {
        screen = SDL_SetVideoMode (1280, 720, 32, SDL_SWSURFACE);
    }
    TTF_Init();
    SDL_WM_SetCaption ("TTF Not Working With OpenGL", NULL);
    if (useOpenGl)
    {
        glClearColor(1.0, 0.0, 0.0, 0.0);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glOrtho(0.0, screen->w, screen->h, 1.0, -1.0, 1.0);
        glEnable(GL_BLEND);
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    }
    return true;
}
bool load_files()
{
    font = TTF_OpenFont ("arial.ttf", 28);
    return true;
}
void clean_up()
{
    SDL_FreeSurface (message);
    TTF_CloseFont (font);
    TTF_Quit();
    SDL_Quit();
}
int main(int argc, char* args[])
{
    //Quit flag
    bool quit = false;
    init();
    load_files();
    if (useOpenGl)
    {
        glClear(GL_COLOR_BUFFER_BIT); //clearing the screen
        glPushMatrix();

        glBegin(GL_QUADS);
        glColor3f(1.0, 0.0, 0.0);
        glVertex2f(0, 0);
        glColor3f(0.0, 1.0, 0.0);
        glVertex2f(1280, 0);
        glColor3f(0.0, 0.0, 1.0);
        glVertex2f(1280, 720);
        glColor4f(0.5, 0.5, 1.0, 0.1);
        glVertex2f(0, 720);
        glEnd();
        glPopMatrix();
        glFlush();
    }
    //Render the text
    message = TTF_RenderText_Solid (font, "The quick brown fox jumps over the lazy dog", textColor);
    //Apply the images to the screen
    apply_surface (0, 150, message, screen);
    //I'm guessing this is where the problem is coming from
    SDL_GL_SwapBuffers();
    SDL_Flip (screen);

    while (quit == false)
    {
        while (SDL_PollEvent (&event))
        {
            if (event.type == SDL_QUIT)
            {
                quit = true;
            }
        }
    }
    clean_up();
    return 0;
}

如果变量useOpenGl设置为false,程序将仅使用SDL_TTF,如果设置为true,则将同时使用SDL_TTF和OpenGL。从玩它的角度来看,问题似乎在于我在创建窗口时是否使用"SDL_OPENGL"标志。

SDL_TTF使用软件渲染,与OpenGL模式不兼容。

您可能需要查找另一个库,如FTGL或freetypegl。