
in vec2 uv;
in vec2 uvn;
out vec4 C;

uniform int tex_a;
uniform int tex_b;
uniform int tex_input;
uniform int pass;

uniform float dog_k;
uniform float dog_thresh;
uniform float dog_phi;


void main() {
    vec2 u = uvn;
    
    if(pass == 0){

        vec3 b = texture(textures[tex_a], u).rgb;
        vec3 a = texture(textures[tex_b], u).rgb;
        vec3 inp = texture(textures[tex_input], u).rgb;
        //    C.rgb = -b + a;
        //    C.rgb = -a+b*1.05;

        float ss = -0.01;
//        ss = 1.;
        ss = dog_k;
        ss *= 0.001;
        //    a *= 0.94;
        C.rgb = -a*(1.0 + ss)+b*(1-ss);
        float l = luma(C.rgb*1);

        //    C -= C;
        //    C = texture(textures[tex_input], u);
        //    C -= C;
        //    C = vec4(1.0);
        float thresh = dog_thresh;
        thresh *= 0.001;
        //    vec3 thr = vec3(1,3.4,-1)*thresh;
        vec3 thr = vec3(1)*thresh;

        //    thresh = 0.001;
        //    C += step(thresh,l);
        C.rgb = step(thr,C.rgb);
        C.rgb = inp*0.;
        //    C.r -= 1.0*step(thresh,l);
        //    C.rgb -= step(thr,C.rgb);
        //    C = 1-C;
        if(l < thresh){
            float phi = dog_phi * 20000.01;
            
            //        C += +tanh(-(l - thresh)*phi);
//            C += 1.+tanh((l - thresh)*phi);
//            C.rgb += 1.+tanh((l - thresh)*phi*vec3(0.2,0.4,.1));
            C.rgb += 1.+tanh((l - thresh)*phi);
            //          C -= 1;
            //        C -= tanh(abs(l - thresh)*phi);
            //        C -= 1.-tanh(-(l - thresh)*phi);
        } else {
            C += 2.0;
        }
        
//        C = 1.-step(C,vec4(0));
        //    C = 1-C;
        //    C -= smoothstep(fwidth(l),0,abs(l))*0.9;
        //    C -= smoothstep(fwidth(l),0,abs(l));

        //    l = smoothstep(fwidth(l),0.,abs(l));

        //    C.rgb = a;
        //    C.rgb = l.xxx;
        //    C = (C)*10;
        //    C.rgb *= step(0.004,l);
        C *= 1.;
        C = max(C,0);
        C.w = 1.0;
    } else {
        float W = 0.;
        
        C = vec4(0);
        for(int i = 0; i <2; i++){
            vec2 q = u;
            for(int k = 0; k < 40; k++){
                vec2 eig = texture(textures[tex_a], q).zw*1.0;
                if(i == 1){
                    eig = -eig;
                }
//                eig = normalize(eig)*0.04;
                if(pass == 1){
                    eig *= 0.001;
                } else {
                    eig *= 0.003;
                }
                q += eig;
                float w = 1.-smoothstep(0.,0.1,length(q-u));
                C += texture(textures[tex_input], q)*w;
                W += w;
            }
            
        }
        C /= W;
    }
}
