[SDL] Alpha-blending with OpenGL in SDL (multiple textures)

Mikkel Gjøl s971661 at student.dtu.dk
Sun Nov 2 13:51:01 PST 2003


First of all, comp.graphics.api.opengl is great for answering questions 
like this.

Stephen Anthony wrote:
> My problem is with alpha-blending.  I want the current glyph (8x8 
> pixels) to be drawn, but only the parts that make up the foreground of 
> the glyph. So I assumed that I'd set the foreground color to 
> 0x808080FF (indicated a light grey with full opacity) and the 
> background to 0x0 (indicating full transparency).

You need to set the alpha-channel of the image to values between 0 and 
1. If you do this, you should set the blendfunc to:

glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
- which is a linear interpolation between the color of the texture you 
draw with, and the color that is already in the framebuffer.

If you don't want to mess about with blendfuncs, you might use 
glAlphaFunc(GL_GREATER, 0.5f);
- but this requires actually setting an alpha-value for the texture.


You _could_ blend according to the color of the texture though, using
glBlendFunc(GL_SRC_COLOR, GL_ONE_MINUS_SRC_COLOR);

- which would give the same result for monocrome textures.


> It doesn't seem to be working out.  The following is part of the code:
> 
>   glEnable(GL_BLEND);
>   glEnable(GL_TEXTURE_2D);
>   glBegin(GL_QUADS);
>     glTexCoord2f(0.0, 0.0); glVertex2i(xorig,   yorig  );
>     glTexCoord2f(1.0, 0.0); glVertex2i(xorig+8, yorig  );
>     glTexCoord2f(0.0, 1.0); glVertex2i(xorig+8, yorig+8);
>     glTexCoord2f(1.0, 1.0); glVertex2i(xorig,   yorig+8);
>   glEnd();

You forget to bind the texture.

glBindTexture(GL_TEXTURE_2D, texno);

- where 'texno' is an integer returned from some code looking like (if 
you don't have the following code somewhere, it should be placed before 
glBindTexture):
	GLuint texno;
	glGenTextures(1, &texno);


Another thing to remember is, that you always need to set wrap, min and 
mag filters. The following piece of code should work:

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_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);


I can't tell if you need to draw several letters on top of each other, 
but if you do, you should remember to draw them "back to front", ie. 
draw the letter you actually want to be shown on the screen, last.


Hope this helps,
\\Mikkel Gjoel





More information about the SDL mailing list