Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my PNG texture not coming out with transparency?

The bottom right image should have a transparent background.

I load my Notch's PNG via these functions:

public void Image2D(Bitmap bmp, int mipmapReductionLevel = 0)
{
    var rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
    var data = bmp.LockBits(rect, ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

    GL.TexImage2D(TextureTarget.Texture2D, mipmapReductionLevel, PixelInternalFormat.Rgba, data.Width, data.Height, 0,
        OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0);

    bmp.UnlockBits(data);
}

public void Image2D(string filename, int mipmapReductionLevel = 0)
{
    Image2D(new Bitmap(filename), mipmapReductionLevel);
}

And my fragment shader looks like this:

#version 330

in vec2 TexCoord0;

uniform sampler2D TexSampler;

void main()
{
    gl_FragColor = texture2D(TexSampler, TexCoord0.xy);
}

I've inspected the bmp with the debugger, and used bmp.GetPixel(255,0) (just above that tree sapling, in the black area) and it comes back (0,0,0,0). The docs say 0 is fully transparent, so... I must be doing something wrong on the OpenGL side of things. But what?


Render function

protected override void OnRenderFrame(FrameEventArgs e)
{
    GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

    _blockInstanceBuffer.Bind();
    _blockIndexBuffer.Bind();
    GL.DrawElementsInstancedBaseVertex(BeginMode.TriangleStrip, Data.FaceIndices.Length, DrawElementsType.UnsignedInt, IntPtr.Zero, _blockCount, 0);

    SwapBuffers();
}
like image 716
mpen Avatar asked Feb 10 '12 02:02

mpen


People also ask

Why are my transparent PNGs not transparent?

There are a few reasons why your PNG might not be transparent in Photoshop. One reason is that you are using the wrong file format. You should be using a PNG-24 file format to ensure transparency. Another reason is that your image might have an alpha channel, but it is not set as the transparency channel.

Do all PNGs support transparency?

png-32 supports different levels of transparency. Each pixel can have an opacity between 0 and 255, with 0 as completely transparent. png-24 supports setting one color as fully transparent. Everything else will be opaque.

Why is my PNG not transparent in after effects?

Is there actually anything behind your PNG in AE? The default background is black, so your transparency will look black unless there is anything behind it or you change the background.


1 Answers

Just needed to enable blending:

GL.Enable(EnableCap.Blend);
GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);

I didn't think that was necessary in OpenGL 3 if you write your own shader, but I guess it still is.

like image 68
mpen Avatar answered Sep 18 '22 13:09

mpen