//https://www.shadertoy.com/view/dtsyR4

#define TAU 6.2831853

float p_area(in vec2 a, in vec2 b, in vec2 c)
{
    vec3 ab = vec3(b-a,0.);
    vec3 ac = vec3(c-a,0.);
    return cross(ab,ac).z;
}




vec3 bary(in vec2 a, in vec2 b, in vec2 c, in vec2 p)
{
    float abc = p_area(a,b,c);
    return vec3(p_area(a,b,p),p_area(b,c,p),p_area(c,a,p))/abc;
}

//requires:
//AB is the short side.
//ABC is a right angle.
//P is within the triangle.
float subtri(inout vec2 az, inout vec2 bz, inout vec2 cz, in vec2 p)
{
    vec2 a = az;
    vec2 b = bz;
    vec2 c = cz;
    vec3 res = bary(a,b,c,p);
    vec2 d = (4.*a+c)/5.;
    if(res.x*4. < res.y){
        //ADB is subtri.
        cz = b;
        bz = d;
        return 0.;
    }
    //working on DBC.
    vec2 e = (b+c)/2.;
    res = bary(d,b,c,p);
    if(res.x > res.z){
        //DEC is subtri
        vec2 f = (c+d)/2.;
        res = bary(d,e,c,p);
        az = e;
        bz = f;
        if(res.x > res.y){
            return 4.;
        }else{
            cz = d;
            return 3.;
        }
    }else{
        //DEB is subtri
        vec2 g = (b+d)/2.;
        res = bary(d,e,b,p);
        bz = g;
        cz = e;
        if(res.x > res.y){
            az = b;
            return 2.;
        }else{
            az = d;
            return 1.;
        }
    }
    
    
    return 5.;
}




void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
    // Normalized pixel coordinates (from 0 to 1)
    vec2 uv = (fragCoord-iResolution.xy*0.5) / min(iResolution.x,iResolution.y);
    if(abs(uv.x) > 1.){
        fragColor = vec4(0.);
        return;
    }
    if(abs(uv.y) > .5){
        fragColor = vec4(0.);
        return;
    }
    

    
    if(uv.x/2.+uv.y > 0.){
        uv *= -1.;
    }
    vec2 a = vec2(-1.,.5);
    vec2 b = vec2(-1.,-.5);
    vec2 c = vec2(1.,-.5);
    //vec3 col = bary(vec2(-1.,-.5),vec2(-1.,.5),vec2(1.,-.5),uv);
    vec3 col = vec3(0.5);
    float r = 0.;
    for(int i=0;i<5;i++){
        float z = subtri(a,b,c,uv);
        r = r/5.+z;
        vec3 q = bary(a,b,c,uv);
        float p = smoothstep(min(min(q.x,q.y),q.z)*3.,0.,0.1);
        col = (col+p)/2.;
    r = r * 7.5 * sin(iTime*TAU/120.);
    float offset = iTime * TAU / 180.;
    col = col * (vec3(sin(r+offset),sin(r+TAU/3.+offset),sin(r-TAU/3.+offset))+1.)/2.;
        
        
        //col = (col.yzx+*vec3(0.7,0.7,1.))/2.;
        
    }
    //col = ((col*6.)-0.5)/5.;
    //col = (bary(a,b,c,uv)+((p_area(a,b,c)>0.)?0.25:0.75))/1.25;
    
    /*
    for(int i=0;i<3;i++){
        col = (col+subtri(a,b,c,uv))/5.;
    }
    col = (sin(col*4.)+1.+bary(a,b,c,uv))/3.;
    */

    // Time varying pixel color
    //vec3 col = 0.5 + 0.5*cos(iTime+uv.xyx+vec3(0,2,4));

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