Sign in to follow this  
nitro404

OpenGL Issues with OpenGL / SDL / SDL_TTF

Recommended Posts

Okay, so I'm attempting to create dynamic font loading from TTF files using SDL_TTF / SDL / OpenGL. (Also note I am using the QtCore library as well.) The general idea of what my code is doing is as follows:

Loading:
1) Generate font path and attempt to load the font using SDL_TTF
2) Render 128 characters to individual SDL_Surfaces, from character 32 to 160
3) Keep track of the size of the largest characters
4) Create a new surface to render all 128 characters onto based on the largest width and height (also make sure it is a power of 2 to prevent scaling)
5) Iterate over all 128 of the characters, rendering to them to the full surface (16x8)
6) Create an OpenGL texture from the data contained in the full surface
7) Create an OpenGL list of all of the characters for ease of use when rendering text later

Rendering:
1) Generate output text data based on format string and arguments passed in
2) Use glCallLists to render the string using the previously generated font data

It's been somewhat successful so far, but I have hit two major snags:

1) SDL_Surfaces store pixel data upside down. I've read about this issue online, but have not found any simple solutions to this. I ultimately did find some code to flip the texture upside-down, but it seemed like an unnecessary amount of code to do so - and it still didn't fix the problem. In short, if I blit to an SDL_Surface, then attempt to make an OpenGL texture out of it, the image is upside-down when rendered. And since I'm generating the image on runtime, having an upside-down input file is not an option.

2) The text shows up yellow instead of white, as specified by the SDL_Color struct. I also found others online who had this same issue, but have not managed to find a solution. When the temp SDL_Surface is allocated, I had to change the RGBA masks to BGRA instead of the usual RGBA / ABGR depending on what endian SDL is using in order to have anything show up at all. I'm not sure if I horribly messed this up or not, but it's the only thing that produces any results thus far. I also tried SDL_DisplayFormat on the surface I was generating, but no matter what I change the RGBA masks to after that, there is no output.

I have attached a quad displaying the full image output at the bottom as well as relevant source code. If anyone has any advice / tips / hints / suggestions / solutions / etc. to this problem, they would be tremendously appreciated. I'll gladly surf around the forums and help other people out as well afterwards, seeing as how this is my first post. Thanks so much!

Edit: I just realized the texture co-ordinates are semi wrong when generating the lists, they're for a 16x16 grid, but the one I'm using is 16x8. They also don't account for non-perfect fit textures (ie. whitespace on the "top" and "right" to make the texture a power of 2, to prevent automatic scaling).

Font Loading:
[code]
bool Font::load() {
if(m_loaded) { return true; }

QString fontPath = QString(Game::settings->dataDirectory);
fontPath.append("/Fonts/");
fontPath.append(m_filename);

QFileInfo fontFile(fontPath);
if(!fontFile.exists()) { return false; }

QByteArray bytes = fontPath.toLocal8Bit();

TTF_Font * fontData;
if(!(fontData = TTF_OpenFont(bytes.data(), m_size))) {
return false;
}

SDL_Color colour = {255, 255, 255, 255};

SDL_Surface * character;
QVector<SDL_Surface *> characters;
int maxWidth = -1;
int maxHeight = -1;
char data[2];
data[1] = '\0';
for(int i=0;i<128;i++ ) {
data[0] = (char) (i + 32);
character = TTF_RenderText_Blended(fontData, data, colour);
characters.push_back(character);
if(maxWidth < 0 || maxWidth < character->w) { maxWidth = character->w; }
if(maxHeight < 0 || maxHeight < character->h) { maxHeight = character->h; }
}

int width = 1, tempWidth = maxWidth * 16;
int height = 1, tempHeight = maxHeight * 8;
while(width < tempWidth) { width *= 2; }
while(height < tempHeight) { height *= 2; }

SDL_Surface * temp = SDL_CreateRGBSurface(0, width, height, 32, 0x0000ff00, 0x00ff0000, 0xff000000, 0x000000ff);

SDL_Rect sourceArea, destArea;
int x = 0;
int y = 0;
for(int i=0;i<128;i++) {
sourceArea.x = 0;
sourceArea.y = 0;
sourceArea.w = characters[i]->w;
sourceArea.h = characters[i]->h;

destArea.x = maxWidth * x;
destArea.y = maxHeight * y;
destArea.w = characters[i]->w;
destArea.h = characters[i]->h;

SDL_BlitSurface(characters[i], &sourceArea, temp, &destArea);

x++;
if(x == 16) {
x = 0;
y++;
}
}

glGenTextures(1, &m_texture);
glBindTexture(GL_TEXTURE_2D, m_texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, temp->w, temp->h, 0, GL_BGRA, GL_UNSIGNED_BYTE, temp->pixels);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE);

m_font = glGenLists(128);

float cx, cy;
for(int i=0;i<128;i++) {
cx = (float) (i % 16) / 16.0f;
cy = (float) (i / 16) / 16.0f;

glNewList(m_font + i, GL_COMPILE);

glBegin(GL_QUADS);
glTexCoord2f(cx, 1 - cy - 0.0625f); glVertex2i(0, m_size);
glTexCoord2f(cx + 0.0625f, 1 - cy - 0.0625f); glVertex2i(m_size, m_size);
glTexCoord2f(cx + 0.0625f, 1 - cy ); glVertex2i(m_size, 0 );
glTexCoord2f(cx, 1 - cy ); glVertex2i(0, 0 );

glEnd();

glTranslated(10, 0, 0);

glEndList();
}

for(int i=0;i<128;i++) {
SDL_FreeSurface(characters[i]);
}
SDL_FreeSurface(temp);

m_loaded = true;

return true;
}
[/code]

Text Drawing:
[code]
void Font::drawText(int x, int y, const char * format, ...) const {
if(!m_loaded) { return; }

char text[256];
va_list args;
va_start(args, format);
vsprintf_s(text, 256, format, args);
va_end(args);

glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE);

glBindTexture(GL_TEXTURE_2D, m_texture);

glMatrixMode(GL_MODELVIEW);
glPushMatrix();

glLoadIdentity();

glTranslated(x, y, 0);
glListBase(m_font - 32);
glCallLists(strlen(text), GL_BYTE, text);

glPopMatrix();
}
[/code]

Output:
[attachment=4116:font_texture.png]

Share this post


Link to post
Share on other sites
Finally solved all of the problems I was having after much frustration. Here's my solution code to anyone who has run into the same problems I have - hopefully it is helpful:

Font.h
[code]
#ifndef FONT_H
#define FONT_H

#include "SDL/SDL.h"
#include "SDL/SDL_OpenGL.h"
#include "SDL/SDL_TTF.h"
#include "Utilities.h"

class Font {
public:
Font(const char * id, const char * filename, int size);
Font(const Font & f);
Font & operator = (const Font & f);
virtual ~Font();

const char * getID() const;
const char * getFilename() const;
int getSize() const;
int getHorizontalSpacing();
int getVerticalSpacing();

void drawText(int x, int y, const char * format, ...) const;

bool load();
bool unload();
bool isLoaded() const;

bool operator == (const Font & f) const;
bool operator != (const Font & f) const;

protected:
char * m_id;
char * m_filename;
int m_size;
int m_horizontalSpacing;
int m_verticalSpacing;
GLuint m_texture;
GLuint m_font;
bool m_loaded;
};

#endif // FONT_H
[/code]

Font.cpp
[code]
#include "Game.h"
#include "Font.h"

Font::Font(const char * id, const char * filename, int size) : m_loaded(false) {
if(id == NULL) {
m_id = new char[1];
m_id[0] = '\0';
}
else {
m_id = strtrimcpy(id);
}

if(filename == NULL) {
m_filename = new char[1];
m_filename[0] = '\0';
}
else {
m_filename = strtrimcpy(filename);
}

m_size = (size < 1) ? 1 : size;
}

Font::Font(const Font & f) {
m_id = new char[strlen(f.m_id) + 1];
strcpy_s(m_id, strlen(f.m_id) + 1, f.m_id);

m_filename = new char[strlen(f.m_filename) + 1];
strcpy_s(m_filename, strlen(f.m_filename) + 1, f.m_filename);

m_size = f.m_size;
}

Font & Font::operator = (const Font & f) {
unload();
delete [] m_id;
delete [] m_filename;

m_id = new char[strlen(f.m_id) + 1];
strcpy_s(m_id, strlen(f.m_id) + 1, f.m_id);

m_filename = new char[strlen(f.m_filename) + 1];
strcpy_s(m_filename, strlen(f.m_filename) + 1, f.m_filename);

m_size = f.m_size;

return *this;
}

Font::~Font() {
unload();
delete [] m_id;
delete [] m_filename;
}

const char * Font::getID() const {
return m_id;
}

const char * Font::getFilename() const {
return m_filename;
}

int Font::getSize() const {
return m_size;
}

int Font::getHorizontalSpacing() {
return m_horizontalSpacing;
}

int Font::getVerticalSpacing() {
return m_verticalSpacing;
}

void Font::drawText(int x, int y, const char * format, ...) const {
if(!m_loaded) { return; }

char text[256];
va_list args;
va_start(args, format);
vsprintf_s(text, 256, format, args);
va_end(args);

glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE);

glBindTexture(GL_TEXTURE_2D, m_texture);

glMatrixMode(GL_MODELVIEW);
glPushMatrix();

glLoadIdentity();

glTranslated(x, y, 0);
glListBase(m_font - 32);
glCallLists(strlen(text), GL_BYTE, text);

glPopMatrix();
}

bool Font::load() {
if(m_loaded) { return true; }

QString fontPath = QString(Game::settings->dataDirectory);
fontPath.append("/Fonts/");
fontPath.append(m_filename);

QFileInfo fontFile(fontPath);
if(!fontFile.exists()) { return false; }

QByteArray bytes = fontPath.toLocal8Bit();

TTF_Font * fontData;
if(!(fontData = TTF_OpenFont(bytes.data(), m_size))) {
return false;
}

SDL_Color colour = {255, 255, 255, 255};

SDL_Surface * character;
QVector<SDL_Surface *> characters;
int maxWidth = -1;
int maxHeight = -1;
char data[2];
data[1] = '\0';
for(int i=0;i<128;i++ ) {
data[0] = (char) (i + 32);
character = TTF_RenderText_Blended(fontData, data, colour);
characters.push_back(character);
if(maxWidth < 0 || maxWidth < character->w) { maxWidth = character->w; }
if(maxHeight < 0 || maxHeight < character->h) { maxHeight = character->h; }
}

m_horizontalSpacing = maxWidth;
m_verticalSpacing = maxHeight;

int width = 1, tempWidth = maxWidth * 16;
int height = 1, tempHeight = maxHeight * 8;
while(width < tempWidth) { width *= 2; }
while(height < tempHeight) { height *= 2; }

SDL_Surface * temp = SDL_CreateRGBSurface(0, width, height, 32,
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
0xff000000, 0x00ff0000, 0x0000ff00, 0x000000ff
#else
0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000
#endif
);

SDL_Rect sourceArea, destArea;
int x = 0;
int y = 0;
for(int i=0;i<128;i++) {
sourceArea.x = 0;
sourceArea.y = 0;
sourceArea.w = characters[i]->w;
sourceArea.h = characters[i]->h;

destArea.x = maxWidth * x;
destArea.y = maxHeight * y;
destArea.w = characters[i]->w;
destArea.h = characters[i]->h;

SDL_SetAlpha(characters[i], 0, 0);
SDL_BlitSurface(characters[i], &sourceArea, temp, &destArea);

x++;
if(x == 16) {
x = 0;
y++;
}
}

glGenTextures(1, &m_texture);
glBindTexture(GL_TEXTURE_2D, m_texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, temp->w, temp->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, temp->pixels);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE);

m_font = glGenLists(128);

x = 0;
y = 0;
float w = (float) maxWidth / (float) (temp->w);
float h = (float) maxHeight / (float) (temp->h);
for(int i=0;i<128;i++) {

glNewList(m_font + i, GL_COMPILE);

glBegin(GL_QUADS);
glTexCoord2f((w * x), ((h * y))); glVertex2i(0, 0);
glTexCoord2f((w * x) + w, ((h * y))); glVertex2i(maxWidth, 0);
glTexCoord2f((w * x) + w, ((h * y) + h)); glVertex2i(maxWidth, maxHeight);
glTexCoord2f((w * x), ((h * y) + h)); glVertex2i(0, maxHeight);
glEnd();

glTranslated(maxWidth, 0, 0);

glEndList();

x++;
if(x == 16) {
x = 0;
y++;
}
}

for(int i=0;i<128;i++) {
SDL_FreeSurface(characters[i]);
}
SDL_FreeSurface(temp);

m_loaded = true;

return true;
}

bool Font::unload() {
if(!m_loaded) { return true; }

glDeleteLists(m_font, 128);
glDeleteTextures(1, &m_texture);

m_loaded = false;

return true;
}

bool Font::isLoaded() const {
return m_loaded;
}

bool Font::operator == (const Font & f) const {
return _stricmp(m_id, f.m_id) == 0 &&
_stricmp(m_filename, f.m_filename) == 0 &&
m_size == f.m_size;
}

bool Font::operator != (const Font & f) const {
return !operator == (f);
}
[/code]

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Forum Statistics

    • Total Topics
      627719
    • Total Posts
      2978790
  • Similar Content

    • By DelicateTreeFrog
      Hello! As an exercise for delving into modern OpenGL, I'm creating a simple .obj renderer. I want to support things like varying degrees of specularity, geometry opacity, things like that, on a per-material basis. Different materials can also have different textures. Basic .obj necessities. I've done this in old school OpenGL, but modern OpenGL has its own thing going on, and I'd like to conform as closely to the standards as possible so as to keep the program running correctly, and I'm hoping to avoid picking up bad habits this early on.
      Reading around on the OpenGL Wiki, one tip in particular really stands out to me on this page:
      For something like a renderer for .obj files, this sort of thing seems almost ideal, but according to the wiki, it's a bad idea. Interesting to note!
      So, here's what the plan is so far as far as loading goes:
      Set up a type for materials so that materials can be created and destroyed. They will contain things like diffuse color, diffuse texture, geometry opacity, and so on, for each material in the .mtl file. Since .obj files are conveniently split up by material, I can load different groups of vertices/normals/UVs and triangles into different blocks of data for different models. When it comes to the rendering, I get a bit lost. I can either:
      Between drawing triangle groups, call glUseProgram to use a different shader for that particular geometry (so a unique shader just for the material that is shared by this triangle group). or
      Between drawing triangle groups, call glUniform a few times to adjust different parameters within the "master shader", such as specularity, diffuse color, and geometry opacity. In both cases, I still have to call glBindTexture between drawing triangle groups in order to bind the diffuse texture used by the material, so there doesn't seem to be a way around having the CPU do *something* during the rendering process instead of letting the GPU do everything all at once.
      The second option here seems less cluttered, however. There are less shaders to keep up with while one "master shader" handles it all. I don't have to duplicate any code or compile multiple shaders. Arguably, I could always have the shader program for each material be embedded in the material itself, and be auto-generated upon loading the material from the .mtl file. But this still leads to constantly calling glUseProgram, much more than is probably necessary in order to properly render the .obj. There seem to be a number of differing opinions on if it's okay to use hundreds of shaders or if it's best to just use tens of shaders.
      So, ultimately, what is the "right" way to do this? Does using a "master shader" (or a few variants of one) bog down the system compared to using hundreds of shader programs each dedicated to their own corresponding materials? Keeping in mind that the "master shaders" would have to track these additional uniforms and potentially have numerous branches of ifs, it may be possible that the ifs will lead to additional and unnecessary processing. But would that more expensive than constantly calling glUseProgram to switch shaders, or storing the shaders to begin with?
      With all these angles to consider, it's difficult to come to a conclusion. Both possible methods work, and both seem rather convenient for their own reasons, but which is the most performant? Please help this beginner/dummy understand. Thank you!
    • By JJCDeveloper
      I want to make professional java 3d game with server program and database,packet handling for multiplayer and client-server communicating,maps rendering,models,and stuffs Which aspect of java can I learn and where can I learn java Lwjgl OpenGL rendering Like minecraft and world of tanks
    • By AyeRonTarpas
      A friend of mine and I are making a 2D game engine as a learning experience and to hopefully build upon the experience in the long run.

      -What I'm using:
          C++;. Since im learning this language while in college and its one of the popular language to make games with why not.     Visual Studios; Im using a windows so yea.     SDL or GLFW; was thinking about SDL since i do some research on it where it is catching my interest but i hear SDL is a huge package compared to GLFW, so i may do GLFW to start with as learning since i may get overwhelmed with SDL.  
      -Questions
      Knowing what we want in the engine what should our main focus be in terms of learning. File managements, with headers, functions ect. How can i properly manage files with out confusing myself and my friend when sharing code. Alternative to Visual studios: My friend has a mac and cant properly use Vis studios, is there another alternative to it?  
    • By ferreiradaselva
      Both functions are available since 3.0, and I'm currently using `glMapBuffer()`, which works fine.
      But, I was wondering if anyone has experienced advantage in using `glMapBufferRange()`, which allows to specify the range of the mapped buffer. Could this be only a safety measure or does it improve performance?
      Note: I'm not asking about glBufferSubData()/glBufferData. Those two are irrelevant in this case.
    • By xhcao
      Before using void glBindImageTexture(    GLuint unit, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLenum format), does need to make sure that texture is completeness. 
  • Popular Now