/*
Mouse X Left  左 : 低速 Slow 
Mouse X Right 右 : 最高速度 Maximum Speed
*/
precision highp float;
uniform vec2 resolution;
uniform vec2 mouse;
uniform float time;
uniform sampler2D backbuffer;
out vec4 outColor;float crossDist( in vec3 p ) {
    vec3 absp = abs(p);
    float d =0.;
    for(float i=0.,m;i++<3.;){
        d+=step(m=max(absp.y,absp.z),absp.x)*m;
        absp.xyz=absp.yzx;
    }
    float cr = 1.0-d;
    float cu = max(max(absp.x,absp.z), absp.y) - 3.0;
    return max(cr, cu);
}


// menger sponge fractal
float fractal( in vec3 p ) {
    vec3 pp = p;
    float scale = 1.0;
    float dist = 0.0;
    for (int i = 0 ; i < 4 ; i++) {
    
        dist = max(dist, crossDist(p)*scale);
        
        p = fract((p-1.0)*0.5) * 6.0 - 3.0;
        scale /= 3.;
        //p.yz*=rot(.785);
        
    }

    return dist;
}
mat2 rot(float a){float c=cos(a),s=sin(a);return mat2(c,-s,s,c);}
vec3 pal(float t){return .5+.5*cos(6.28*(1.*t+vec3(.0,.3,.7)));}
void main(){
  vec2 r=resolution,uv=(gl_FragCoord.xy*2.-r)/min(r.x,r.y);
    bool speedup = mouse.x*mouse.x >.5 ;
    vec3 col = vec3(0.);
    float rnd = fract(758.7*sin(dot(uv,vec2(486.426,751.953))));
    vec3 p,d=normalize(vec3(uv,.8-.05*sqrt(max(.1,length(uv)-.3))*rnd));
    float t = time*.2;
    t*=2.;
    t=floor(t)+pow(fract(t),.05);
    t+=time*.2;
    t=speedup?time:t;
    for(float i,e,g;i++<50.;){
           p = d*g;
           vec3 op = p;
          
           if(mod(t,(speedup ? 12.:6.))<2.){p.x +=20.+10.*((t*.5));p.yz*=rot(t);}
           else if(mod(t,(speedup ? 12.:6.))<4.){ p.y +=20.+10.*((t*.5)); p.xz *=rot(t);}
           else { p.xy *=rot(t+p.z*.1+rnd*.025*sqrt(length(uv))); p.z +=20.+10.*((t*.5));  p.x += sin(t);}
           p.zxy = asin(sin(p.zxy/1.8))*1.8;
          
         
           float h= max(abs(p.z)-3.,fractal(p));
          
           g+=e=max(.0001,abs(h));
           float tt=tanh(sin(length(p)+rnd*.01)*5.);
           
           
        col +=mix(pal(.9+rnd*.1+tt+t*2.+length(p))*(.05),vec3(.0015)*fract(105.*dot(floor(p*5.)/10.,vec3(225.35,355.35,953.35))),clamp(tt,0.,1.))/exp((1.-fract(-op.z*.1+t*2.))*e*i*i);
}
  outColor=vec4(sqrt(col),1);
  
  
}