How can I render a semi transparent model with OpenGL correctly?

Posted by phobitor on Game Development See other posts from Game Development or by phobitor
Published on 2012-07-03T08:36:57Z Indexed on 2012/07/03 9:23 UTC
Read the original article Hit count: 194

Filed under:
|

I'm using OpenGL ES 2 and I want to render a simple model with some level of transparency. I'm just starting out with shaders, and I wrote a simple diffuse shader for the model without any issues but I don't know how to add transparency to it. I tried to set my fragment shader's output (gl_FragColor) to a non opaque alpha value but the results weren't too great. It sort of works, but it looks like certain model triangles are only rendered based on the camera position... It's really hard to describe what's wrong so please watch this short video I recorded:

http://www.youtube.com/watch?v=s0JqA0rZabE

I thought this was a depth testing issue so I tried playing around with enabling/disabling depth testing and back face culling. Enabling back face culling changes the output slightly but the problem in the video is still there. Enabling/disabling depth testing doesn't seem to do anything.

Could anyone explain what I'm seeing and how I can add some simple transparency to my model with the shader? I'm not looking for advanced order independent transparency implementations.

edit:

Vertex Shader:
// color varying for fragment shader
varying mediump vec3 LightIntensity;
varying highp vec3 VertexInModelSpace;

void main()
{
    //
    vec4 LightPosition = vec4(0.0, 0.0, 0.0, 1.0);
    vec3 LightColor = vec3(1.0, 1.0, 1.0);
    vec3 DiffuseColor = vec3(1.0, 0.25, 0.0);

    // find the vector from the given vertex to the light source
    vec4 vertexInWorldSpace = gl_ModelViewMatrix * vec4(gl_Vertex);
    vec3 normalInWorldSpace = normalize(gl_NormalMatrix * gl_Normal);
    vec3 lightDirn = normalize(vec3(LightPosition-vertexInWorldSpace));

    // save vertexInWorldSpace
    VertexInModelSpace = vec3(gl_Vertex);

    // calculate light intensity
    LightIntensity = LightColor * DiffuseColor * max(dot(lightDirn,normalInWorldSpace),0.0);

    // calculate projected vertex position
    gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;

}

Fragment Shader:
// varying to define color
varying vec3 LightIntensity;
varying vec3 VertexInModelSpace;

void main()
{
    gl_FragColor = vec4(LightIntensity,0.5);
}

© Game Development or respective owner

Related posts about opengl

Related posts about transparency