openGL ES textures from PNGs with transparency are being rendered with weird artifacts and driving me nuts!

I am beginning to work on my first OpenGL iPhone app, but I've hit an early snag.

I have a VERY SIMPLE little texture that I want to use as a sprite in a 2D game, but it renders with weird 'randomly' colored pixels up top.

http://i40.tinypic.com/2s7c9ro.png <-- Screenshot here

I sort of get the feeling that this is Photoshop's fault, so if anybody something about that please let me know.

If it's not photoshop then it's gotta be my code... So here is the code in question...

- (void)loadTexture {

CGImageRef textureImage = [UIImage imageNamed:@"zombie0.png"].CGImage;

if (textureImage == nil) {
    NSLog(@"Failed to load texture image");
    return;
}

NSInteger texWidth = CGImageGetWidth(textureImage);
NSInteger texHeight = CGImageGetHeight(textureImage);

GLubyte *textureData = (GLubyte *)malloc(texWidth * texHeight * 4);

CGContextRef textureContext = CGBitmapContextCreate(textureData, texWidth, texHeight, 8, texWidth * 4, CGImageGetColorSpace(textureImage), kCGImageAlphaPremultipliedLast);

CGContextDrawImage(textureContext, CGRectMake(0.0, 0.0, (float)texWidth, (float)texHeight), textureImage);

CGContextRelease(textureContext);

glGenTextures(1, &textures[0]);

glBindTexture(GL_TEXTURE_2D, textures[0]);

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texWidth, texHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, textureData);

free(textureData);

glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

glEnable(GL_TEXTURE_2D);

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

}

This blend function yielded the best results.

Please, let me know what you think is wrong.

Thank you very much, this problem has been driving me nuts.

Upvotes: 12

Views: 6306

Answers (3)

Marco Mustapic
Marco Mustapic

Reputation: 3859

Most probably your image has some colored pixels with an zero alpha value, but because of the blending function you are showing them. Try

glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

Upvotes: 0

Gordon Childs
Gordon Childs

Reputation: 36072

Try erasing your CGContextRef first:

CGContextSetRGBFillColor(ctxt, 1, 1, 1, 0);
CGContextFillRect(ctxt, CGRectMake(0, 0, w, h));

Upvotes: 1

Nikolai Ruhe
Nikolai Ruhe

Reputation: 81848

One problem I can see from the code is that you do not clear your context before drawing the image. Since your image contains transparent areas and is composed on the background, you just see what's in the memory allocated by malloc. Try setting you Quartz Blend mode to copy before drawing the image:

CGContextSetBlendMode(textureContext, kCGBlendModeCopy);

You could also use calloc instead of malloc, since calloc gives you zeroed memory.

Your OpenGL blending is correct:

glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);

gives you Porter-Duff "OVER", which is what you usually want.

Upvotes: 19

Related Questions