Jump to content
  • Advertisement
Sign in to follow this  
deadstar

OpenGL Using SDL_TTF with OpenGL - halves my framerate

This topic is 3790 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, I'm using a modified version of C-Junkie's code (from here: http://www.gamedev.net/community/forums/topic.asp?topic_id=284259) to render text from SDL_TTF to an OpenGl quad.
void SDL_GL_RenderText(string Text, TTF_Font *Font, SDL_Color Colour, SDL_Rect *Position)
{
	SDL_Surface *Initial;
	SDL_Surface *Intermediary;
	SDL_Rect Rect;
	int Width, Height;
	GLuint Texture;

	//Cast the string as a non-const char*
	char *Text_NonConst = const_cast<char*>(Text.c_str());

	//Enable blending
	glEnable(GL_BLEND);
	
	//Render text to SDL surface
	Initial = TTF_RenderText_Blended(Font, Text_NonConst, Colour);
	
	//Get the width and height of the SDL surface containing the text
	Width = nextpoweroftwo(Initial->w);
	Height = nextpoweroftwo(Initial->h);
	
	//Create a surface with useable format for OpenGL
	Intermediary = SDL_CreateRGBSurface(0, Width, Height, 32, 0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000);

	//Blit the text surface onto the OpenGL compliant one
	SDL_BlitSurface(Initial, 0, Intermediary, 0);
	
	//Setup the texture
	glGenTextures(1, &Texture);
	glBindTexture(GL_TEXTURE_2D, Texture);

	//Copy SDL surface to the OpenGL texture
	glTexImage2D(GL_TEXTURE_2D, 0, 4, Width, Height, 0, GL_BGRA, GL_UNSIGNED_BYTE, Intermediary->pixels );
	
	//Setup texture filter
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

	//Enable textures
	glEnable(GL_TEXTURE_2D);

	//Set the colour to white (for correct blending)
	glColor3f(1.0f, 1.0f, 1.0f);
	
	//Draw texture using a quad
	glBegin(GL_QUADS);

		glTexCoord2f(0.0f, 0.0f); glVertex2f(Position->x, Position->y);
		glTexCoord2f(1.0f, 0.0f); glVertex2f(Position->x + Width, Position->y);
		glTexCoord2f(1.0f, 1.0f); glVertex2f(Position->x + Width, Position->y + Height);
		glTexCoord2f(0.0f, 1.0f); glVertex2f(Position->x, Position->y + Height);

	glEnd();

	//Disable blending
	glDisable(GL_BLEND);
	
	//Clean up
	SDL_FreeSurface(Initial);
	SDL_FreeSurface(Intermediary);
	glDeleteTextures(1, &Texture);
}



Simply rendering a single word halves my framerate. Is there a way to reduce the amount of code used? Or a simpler way to copy an SDL surface to an OpenGL texture? I don't want to change my font library to something else, I like SDL_TTF for its simplicity and cross-platform capability. Thanks

Share this post


Link to post
Share on other sites
Advertisement
When you say it halves your framerate, are you comparing doing nothing at all versus just rendering text? Because if so, that would not be a good comparison.

One big way to speed the code up would be to save the OpenGL textures you create and simply reuse them. This of course would require you to use static text though.

If you want to use dynamic text, you could render the entire alphabet to a texture in the manner you have, and using texture coordinates, write a message one letter at a time. That would be harder to code though.

Share this post


Link to post
Share on other sites
As the poster before me pointed out dont compare to rendering nothing at all because that's not a good baseline.

With regards performance .. This is the slowest performing code you could possibly write and I dont mean that in a bad way, just as constructive criticism. It is by understanding why the code is slow that you can speed it up.

#1. You are rendering using immediate mode gl draw calls. Very slow, so read up on how to use vertex arrays or even better vertex buffer objects if you want the ultimate performance.

#2. You are rendering using quads. Although the gl vendor will convert the quads to triangles somewhere down the pipeline, the fastest data to send is indexed triangles to take advantage of the vertex cache on the gpu. Make your quads 2 indexed triangles each (tip: your triangle indices will ALWAYS be the same).

#3. You are generating a fresh texture every single frame. Big nono. Uploading data to the gpu is SLOW, so where possible generate the texture once and reuse. You should pack all your font characters (glyphs) into a single texture and bind it for the draw call, then use texture coordinates to map a characters onto a quad.

#4. Try to avoid memory allocations in your rendering loop. Memory allocation / deallocation is very slow.

Hope these tips help, and good luck with your code!

Share this post


Link to post
Share on other sites
Quote:
Original post by Simian Man
When you say it halves your framerate, are you comparing doing nothing at all versus just rendering text? Because if so, that would not be a good comparison.


Well, it's rendering a grid and a few 3D models. Maybe I'm jumping the gun a bit then.

Quote:
Original post by Simian Man
One big way to speed the code up would be to save the OpenGL textures you create and simply reuse them. This of course would require you to use static text though.


I'm using the text to show the FPS and some debug info, as well as putting it into good use on a quake-style console, so I wouldn't find use for static text.

Quote:
Original post by Simian Man
If you want to use dynamic text, you could render the entire alphabet to a texture in the manner you have, and using texture coordinates, write a message one letter at a time. That would be harder to code though.


I can't see much benefits over using bitmapped fonts in this instance.


Thanks for your response, I think I'm rendering too few things on the screen to give an accurate result.

Share this post


Link to post
Share on other sites
Quote:
Original post by TheGilb
As the poster before me pointed out dont compare to rendering nothing at all because that's not a good baseline.

With regards performance .. This is the slowest performing code you could possibly write and I dont mean that in a bad way, just as constructive criticism. It is by understanding why the code is slow that you can speed it up.

#1. You are rendering using immediate mode gl draw calls. Very slow, so read up on how to use vertex arrays or even better vertex buffer objects if you want the ultimate performance.

#2. You are rendering using quads. Although the gl vendor will convert the quads to triangles somewhere down the pipeline, the fastest data to send is indexed triangles to take advantage of the vertex cache on the gpu. Make your quads 2 indexed triangles each (tip: your triangle indices will ALWAYS be the same).

#3. You are generating a fresh texture every single frame. Big nono. Uploading data to the gpu is SLOW, so where possible generate the texture once and reuse. You should pack all your font characters (glyphs) into a single texture and bind it for the draw call, then use texture coordinates to map a characters onto a quad.

#4. Try to avoid memory allocations in your rendering loop. Memory allocation / deallocation is very slow.

Hope these tips help, and good luck with your code!


Thanks for the reply.

The code isn't mine, it was taken from the above thread and slightly modified to include STL::String support.

I thought about using a vertex array, but I thought a single quad wouldn't be THAT much of a slow-down, and a vertex array wouldn't be worth the hassle. Am I wrong?

I'll try and remove as much memory allocation I can from the code (maybe make a class, and call glGenTextures once), and use a bitmapped font solution only as a last resort, since I am fond of this method dispite these drawbacks.

Share this post


Link to post
Share on other sites
That code is horrible.

Take a good hard look at what it's doing and you'll throw it away without a thought.

For single frame, it takes a font and renders it.
Then it creates a texture. Every frame!
And finally renders the texture to a quad. and deletes the texture.

EVERY FRAME! :)

I'd suggest taking a look at Nehe's font tutorial, it's about 10000 times faster than this. Granted, his example is windows specific, but it's possible to make it multiplatform if you need to.

http://nehe.gamedev.net/data/lessons/lesson.asp?lesson=13
I think it's this one. It actually does load fonts from normal font files, not textures.

Share this post


Link to post
Share on other sites
Quote:
Original post by TheGilb
#1. You are rendering using immediate mode gl draw calls. Very slow, so read up on how to use vertex arrays or even better vertex buffer objects if you want the ultimate performance.

#2. You are rendering using quads. Although the gl vendor will convert the quads to triangles somewhere down the pipeline, the fastest data to send is indexed triangles to take advantage of the vertex cache on the gpu. Make your quads 2 indexed triangles each (tip: your triangle indices will ALWAYS be the same).

#4. Try to avoid memory allocations in your rendering loop. Memory allocation / deallocation is very slow.


These three are *nothing* compared with your #3 (sending a new texture the video card each frame). Until that is optimized, using triangles or vertex arrays would be meaningless.

Share this post


Link to post
Share on other sites
Quote:
Original post by deadstar
I'm using the text to show the FPS and some debug info, as well as putting it into good use on a quake-style console, so I wouldn't find use for static text.

Well, unless you're updating all of the text every single frame, then you can still take advantage of the static text concept. I started out with similar horribly inefficient code and it would drop my framerate to the teens or lower when I had my console on screen (maybe a dozen or two lines of text). I updated the code to cache text textures that don't change from frame to frame and now it runs much more acceptably.

Here's my new version of the function (there's plenty of room for improvement, but it didn't require any huge changes and it works well enough for me). Note that it's integrated into my GUI class so each widget automatically keeps track of the previous string it rendered and the current string, which are the first two parameters (if they match then it just reuses the texture), and it also requires that you manage the OpenGL texture outside of the function. There's some other classes referenced in there too but you can probably figure out what's going on.

void GUI::RenderText(string str, string oldstr, int x, int y, int justify, TTF_Font *font, GLuint tex, float scale, bool shadow)
{
SDL_Surface *text;

if (str.length() == 0 || !TTF_WasInit())
return;
SDL_Color col;
col.r = 255;
col.g = 255;
col.b = 255;

SDL_Surface *t = TTF_RenderText_Solid(font, str.c_str(), col);
if (!t) // Had some problems with sdl-ttf at one point
{ // At least this way it won't segfault
cout << "Error rendering text: " << str << endl;
exit(-1);
}
int neww = PowerOf2(t->w);
int newh = PowerOf2(t->h);

texman->texhand->BindTexture(tex);

if (oldstr != str)
{
Uint32 rmask, gmask, bmask, amask;
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
rmask = 0xff000000;
gmask = 0x00ff0000;
bmask = 0x0000ff00;
amask = 0x000000ff;
#else
rmask = 0x000000ff;
gmask = 0x0000ff00;
bmask = 0x00ff0000;
amask = 0xff000000;
#endif
text = SDL_CreateRGBSurface(SDL_SWSURFACE, neww, newh, 32,
rmask, gmask, bmask, amask);


SDL_BlitSurface(t, NULL, text, NULL);

SDL_LockSurface(text);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, text->w, text->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, text->pixels);
}

float texwidth = (float)t->w / (float)neww;
float texheight = (float)t->h / (float)newh;

int offset = 2;
int shadowpass = shadow ? 1 : 0;
while (shadowpass >= 0)
{
if (shadow)
{
if (shadowpass)
{
glColor4f(0, 0, 0, 1);
x += offset;
y += offset;
}
else
{
glColor4f(1, 1, 1, 1);
x -= offset;
y -= offset;
}
}
glBegin(GL_TRIANGLE_STRIP);
if (justify == 0)
{
glTexCoord2f(0, 0);
glVertex2f(x, y);
glTexCoord2f(0, texheight);
glVertex2f(x, y + t->h * scale);
glTexCoord2f(texwidth, 0);
glVertex2f(x + t->w * scale, y);
glTexCoord2f(texwidth, texheight);
glVertex2f(x + t->w * scale, y + t->h * scale);
}
else if (justify == 1)
{
glTexCoord2f(0, 0);
glVertex2f(x - t->w, y);
glTexCoord2f(0, texheight);
glVertex2f(x - t->w, y + t->h);
glTexCoord2f(texwidth, 0);
glVertex2f(x, y);
glTexCoord2f(texwidth, texheight);
glVertex2f(x, y + t->h);
}
glEnd();
--shadowpass;
}
glColor4f(1, 1, 1, 1);

SDL_FreeSurface(t);
if (oldstr != str)
SDL_FreeSurface(text);
}

Share this post


Link to post
Share on other sites
What I would do if you want to use SDL for font rendering, is use the same method nehe uses. It creates a quad for every character and stores every quad in a display list. It then uses a really clever way of calling these display lists. This way you can have text that updates every frame and still not really affect your framerate. I think it's by far the best solution.

Share this post


Link to post
Share on other sites
The easiest way to increase the speed of your code is to:
1. Create the openGL texture just once (pick the maximum size you need/can afford)
2. Use glTexSubImage2D instead of glTexImage2D to update the texture when the text changes

If you have multiple text targets (like a Quake-style console plus a HUD), use multiple target textures.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!