// Mandelbrot shader using GPGPU techniques
// Author: Gabriel Zachmann, June 2007
//
// Modified and extended for Tcl3D by Paul Obermeier 2009/01/04
// See www.tcl3d.org for the Tcl3D extension.
//
// This shader implements the body of the loop that computes the z_i

#version 110

uniform sampler2D zi_minus_1;   // from last iteration
uniform float curIteration;     // iteration count
// we use a float here because in the end, it will be stored 
// in gl_FragColor.z, which is a float, too

varying vec2 c;

vec2 csquare( vec2 z )
{
    return vec2( z.x*z.x - z.y*z.y , 2.0*z.x*z.y );
}

void main ()
{
    // Lookup value from last iteration
    vec4 inputValue = texture2D( zi_minus_1, gl_TexCoord[0].xy );
    vec2 z = inputValue.xy;

    // Only process if still within radius-2 boundary
    if ( dot(z,z) > 4.0 ) {
        // Leave pixel unchanged (but copy through to dest. buffer)
        gl_FragColor = inputValue;
    } else {
        gl_FragColor.xy = csquare( z ) + c;
        gl_FragColor.z = curIteration;
        gl_FragColor.w = 0.0;
    }
}
