in vec2 uv;
in vec2 uvn;

out vec4 C;


uniform int input_tex;
uniform int prev_grad_tex;
uniform int prev_lum_tex;
uniform int curr_lum_tex;

const float vertical_weights[25] = float[25](
    -5., -8., -10., -8., -5.,
    -4.,-10.,-20.,-10.,-4.,
    0.,0.,0.,0.,0.,
    4.,10.,20.,10.,4.,
    5.,8.,10.,8.,5.
);

// horizontal gradient
const float horizontal_weights[25] = float[25](
    -5., -4., 0., 4., 5.,
    -8., -10.,0.,10.,8.,
    -10.,-20.,0.,20.,10.,
    -8.,-10.,0.,10.,8.,
    -5.,-4.,0.,4.,5.
);

void main() {
    vec2 image_res = vec2(textureSize(textures[curr_lum_tex], 0).xy);
    
    vec2 u = gl_FragCoord.xy/vec2(image_res);
    //    C.rgb = 
    C = texture(textures[input_tex], u);


    float horiz_sum = 0.;
    float vert_sum = 0.;

    for (int i = 0; i < 5; i++) {
        for (int j = 0; j < 5; j++) {
            vec2 uv = u+vec2(j,i)*1./image_res;
            vec4 c = texture(textures[input_tex], uv);
            horiz_sum += horizontal_weights[i*5+j]*luma(c.rgb);
            vert_sum +=   vertical_weights[i*5+j]*luma(c.rgb);
        }
    }
    C.x = horiz_sum/240.;
    C.y = vert_sum/240.;

    
    float lum = luma(texture(textures[input_tex], u).rgb);
    float prev_lum = texture(textures[prev_lum_tex], u).x;
    
    float dt = lum - prev_lum;
    
    float dd = sqrt(C.x*C.x + C.y*C.y + 1.);
    
    
//    imageStore(f16r_images[curr_lum_tex], uvec2(U), lum.xxxx);
    imageStore(f32r_images[curr_lum_tex], ivec2(U), lum.xxxx);
    

    vec4 prev_grad = texture(textures[prev_grad_tex], u);
//    
    
    vec2 delta_grad = C.xy - prev_grad.xy;
    C.zw = delta_grad;

    vec2 flow = 1. * dt * vec2(C.x,C.y) / dd;

//    C.zw = flow;
    
    
//    horizontal_pass = vec4(horz_sum.xyz/240., 1.);
//    vertical_pass = vec4(vert_sum.xyz/240., 1.);
//    C.w = 1.0;
}

