Robin92
Robin92

Reputation: 561

Keeping original colors

I'm trying to place a texture (with alpha) on another texture in OpenGL. I do it without any problems, but it's not as I wanted: my nearest image's color is strongly affected by background image (furthest texture) resulting in appearing orange in spite of red.

Anyone knows a way of blending (or getting rid of alpha) that will resolve this issue?

Blending initialization:

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

Drawing scene:

glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();

//furthest image (background)
glBindTexture(GL_TEXTURE_2D, texture[1]);
glBegin(GL_QUADS);
    glTexCoord2f(0, 0); glVertex2f(0, 0);
    glTexCoord2f(1, 0); glVertex2f(500, 0);
    glTexCoord2f(1, 1); glVertex2f(500, 500);
    glTexCoord2f(0, 1); glVertex2f(0, 500);
glEnd();

//nearest image (appears orange, should be red) 
glBindTexture(GL_TEXTURE_2D, texture[0]);
glBegin(GL_QUADS);
    glTexCoord2f(0, 0); glVertex2f(100, 100);
    glTexCoord2f(1, 0); glVertex2f(300, 100);
    glTexCoord2f(1, 1); glVertex2f(300, 300);
    glTexCoord2f(0, 1); glVertex2f(100, 300);
glEnd();

glutSwapBuffers();

EDIT. Here's an image depicting how it looks: issue

Here's an image of how it should look: target

Upvotes: 1

Views: 568

Answers (3)

Robin92
Robin92

Reputation: 561

With help of you all, I managed to resolve the issue by:

  • resaving my texture as PNG (in spite of BMP)
  • changing blending function to glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

Thanks to all contributtors :)

Upvotes: 0

datenwolf
datenwolf

Reputation: 162164

This blend func

glBlendFunc(GL_SRC_ALPHA, GL_ONE);

is the cause of your problems. The GL_ONE for destination means, that whatever is present already in the framebuffer will be added to the incoming colour regardles of the alpha value.

In your case your red texture gets added with the greenish background. And since red + greenish = orange this is what you get.

What you want is mask the previous content in the destination framebuffer with your alpha channel, which is done using

glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

Also remember that OpenGL state is meant to be set and reset on demand, so when drawing other textures then you might need other setting for blending and blend func.

Upvotes: 2

Tim
Tim

Reputation: 35923

I believe what you want is 'alpha testing', not blending. See

glEnable(GL_ALPHA_TEST)
glAlphaFunc()

If you want to leave blending enabled, you should use

glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); 

This will only use the source color in places where the source alpha is 1. Currently your function adds the source color to the background color.

If you don't want any mixing of colors, then using alpha test is the better way to go, as it uses less resources then blending.

Upvotes: 2

Related Questions