Search code examples
iosopengl-esglslopengl-es-2.0shader

How can I colour things in OpenGL ES 2.0 based on their depth?


I'm writing an OpenGL ES 2.0 game (on iOS). How can I create a shader (since I assume this would be simpler to do in a shader) so that geometry further from the origin (on the Z axis) appears darker?

The water in this image illustrates the effect I have in mind

Zarch
(source: bytecellar.com)


Solution

  • This is fairly simple to do if you just want to use the Z position of your geometry. You could have a vertex shader like the following:

    attribute vec4 position;
    
    varying float zDepth;
    
    uniform mat4 modelViewProjMatrix;
    
    void main()
    {
        vec4 newPosition = modelViewProjMatrix * position;
        gl_Position = newPosition;
        zDepth = (2.0 - (1.0 + newPosition.z))/2.0;
    }
    

    and a fragment shader like

    varying highp float zDepth;
    
    void main()
    {
        gl_FragColor = vec4(zDepth, zDepth, 0.0, 1.0);
    }
    

    which would produce the following look:

    Depth-shaded OpenGL teapot

    I have an example of this within this iPad sample code I assembled for my OpenGL ES 2.0 class.