#define R iResolution
#define PI 3.14159265359
float max_iter = 512.0;
int AA = 6;

//#define iTime iGlobalTime


vec3 randCol(float i) {
    float f = i/max_iter * 2.0;
    f=f*f*2.;
    float t = iTime+1.;
    return vec3((sin(f*2.0)), (sin(f*4.)), abs(sin(f*8.0)));
}


vec3 julia(vec2 p, vec2 comp)
{
    float th = iTime*2.*PI/180.;
    mat2 rot = mat2(cos(th), -sin(th), sin(th), cos(th));
    vec3 col = vec3(0.0);
    vec2 z = (2.0*p - R.xy)/R.y;
    z *= rot;
    z *= pow(1.1, -iTime*2.);//(fract(-iTime*0.05+0.99));
    z += vec2(0.0566,0.279);
    vec2 c = comp; 
    float r = 20.;
    float iter = 0.0;
    vec3 jCol = vec3(0.0);
    vec2 zP;
    for (; iter<max_iter && dot(z,zP)<r*r; iter++)
    {
        zP = z;
        z = vec2(z.x*z.x - z.y*z.y, 2.0*z.x*z.y) + c;
    }
    if (iter>max_iter) return vec3(0.0);
    
    float d = length(z);
    float fIter = log2(log(d)/log(r));
    col = vec3( smoothstep(6.,.0,fIter) )*randCol(iter*6.);
    return col + vec3(0.2);
}

void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
    // Normalized pixel coordinates (from 0 to 1)    
    vec3 accCol = vec3(0.);
    
    //vec2 c1 =  vec2(-0.8 , 0.156);//vec2( -0.79, 0.141 );
    //vec2 c2 =  vec2( -0.79, 0.141 );
    //vec2 c4 =  vec2( -0.75, 0.16 );
    //float a = 0.2*PI+sin(iTime*0.05)*0.5+0.5+3.;
    vec2 c3 = vec2(0.285,0.01);
    //vec2 c = mix(c1,c2,sin(iTime*0.02+0.33));
    
    
    for (int i=0; i<AA; i++)
    for (int j=0; j<AA; j++)
    {
        vec2 dx = -0.5 + vec2(float(i), float(j))/float(AA);
        accCol += julia(fragCoord + dx, c3);
    }
    accCol /= float(AA*AA);
    
    vec3 col = vec3(accCol);

    // Output to screen
    col = pow(col, vec3(2.2));
    fragColor = vec4(col,1.0);
}
