#version 450

layout(location = 0) in vec3 tang_norm;
layout(location = 1) in vec3 tang_U;
layout(location = 2) in vec3 tang_V;
layout(location = 3) in vec2 tex;
layout(location = 4) in vec3 pos;

/* Right now all in set 0 */
layout(location = 0) out vec4 fin_color;
/* Yes, even these guys */
layout(binding = 1) uniform sampler2D color_tex;
layout(binding = 2) uniform sampler2D normal_map;
layout(binding = 3) uniform sampler2D specular_map;

layout(push_constant, std430) uniform pc {
    layout(offset = 64) vec3 camera_pos;
};

struct Pipeline0PointLight {
    vec3 pos;
    vec3 color;
};

struct Pipeline0Spotlight {
    vec3 pos;
    vec3 dir;
    vec3 color;
    float range;
};

layout(std140, binding = 0) uniform Pipeline0UBO {
    int point_light_count;
    int spotlight_count;
    Pipeline0PointLight point_light_arr[120];
    Pipeline0Spotlight spotlight_arr [20];
};

float get_intensity(float dist){
    return 1 / (dist * dist * 1.8 + dist * 0.7 + 1);
}

void main(){
    vec3 compressed_normal = texture(normal_map, tex).xyz;
    vec3 correct_norm_on_tang = compressed_normal * 2 - 1;
    vec3 norm = normalize(mat3(tang_U, tang_norm, tang_V) * correct_norm_on_tang);
    vec3 diffuse_illumination = vec3(0);
    vec3 specular_illumination = vec3(0);
    for (int i = 0; i < point_light_count; i++) {
        Pipeline0PointLight lamp = point_light_arr[i];
        vec3 to_light = -pos + lamp.pos;
        float dist = length(to_light);
        vec3 U = to_light / dist;
        diffuse_illumination += get_intensity(dist) * max(0, dot(U, norm)) * lamp.color;
        vec3 A = reflect(-U, norm);
        vec3 to_cam = -pos+camera_pos;
        float dist_to_cam = length(to_cam);
        vec3 B = to_cam / dist_to_cam;
        specular_illumination += get_intensity(dist) * pow(max(0, dot(A, B)), 32) * lamp.color;
    }
    for (int i = 0; i < spotlight_count; i++) {
        Pipeline0Spotlight lamp = spotlight_arr[i];
    }
    vec3 natural_color = texture(color_tex, tex).xyz;
    float specular_c = texture(specular_map, tex).x;
    vec3 color = natural_color * diffuse_illumination + specular_c * specular_illumination;
    fin_color = vec4(color, 1);
}
