#define AA 2
#define COUNT_PETALS 	5.
#define TIME_SPEED 		0.5
#define BUMP_FACTOR     0.05
#define MOVE_SPEED		0.0

vec3 sdf(vec2 p, float t)
{
    p = vec2(atan(p.x+sin(t * MOVE_SPEED)*0.5,p.y), length(p * 3.5)); 	// cart to polar
    for (int i=0; i<3; i++)
	{
		p.y += cos(p.x * COUNT_PETALS - t)/3.; 	// l warping 
		p.x += sin(p.y * 4. - t*2.)/3.;			// a warping
    }
	p = vec2(cos(p.x), sin(p.x)) * p.y; 		// polar to cart
	p = abs(fract(p)-0.5);						// domain repeat
	return vec3(length(p), p);
}

vec4 render(in vec2 v, in vec2 o)
{
    float t = iTime * TIME_SPEED; 
	
    vec2 uv = (v + o - iResolution.xy*0.5)/iResolution.y;
    vec3 rd = normalize(vec3(uv, 1.));

	// light point
    vec3 lp = vec3(cos(iTime)*0.5, sin(iTime)*0.2, -1.);
	
	// bump mapping
	vec2 eps = vec2(5./iResolution.y, 0.);
    vec3 f = sdf(uv, t);
    float fx = (sdf(uv-eps.xy, t).x-f.x)/eps.x;
    float fy = (sdf(uv-eps.yx, t).x-f.x)/eps.x;
	vec3 n = normalize( vec3(0., 0., -1) + vec3(fx, fy, -1.) * BUMP_FACTOR );           
	
	// distance to light point
	vec3 ld = lp - vec3(uv,0);
	float lDist = max(length(ld), 0.001);
	ld /= lDist;
    float atten = (f.x*0.9+0.1)/(1.0 + lDist*lDist*0.15);
	
	// diffuse
	float diff = max(dot(n, ld), 0.);  
    diff = pow(diff, 4.)*0.7 + pow(diff, 8.)*0.3; 
	
	// specular
    float spec = pow(max(dot( reflect(-ld, n), -rd), 0.), 12.); 
    
	// texture
	vec3 col = texture(iChannel0, uv + f.yz).xyz; 
    col = smoothstep(0.05, .75, pow(col*col, vec3(.75, .8, .85)));    
    
	// final light
	col = (col * (diff*vec3(0.496, 0.853, 1.0)*2. + 0.5) + vec3(1)*spec*2.)*atten;
	return vec4(sqrt(clamp(col, 0., 1.)), 1.);
}

void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
    fragColor = vec4(0);
    
    int _AA = max(AA,1); // avoid div by 0 at line 69
    
	for(int i=0;i<_AA;i++)
    for(int j=0;j<_AA;j++)
        fragColor += render(fragCoord, vec2(i,j) / float(_AA));
    
    fragColor /= float(_AA * _AA);
}
