#version 450
#extension GL_ARB_separate_shader_objects : enable

layout(push_constant) uniform PushConstants {
    mat4 model;
    bool is_selected;
} push;

layout(binding = 0) uniform ObjectUniformData {
    mat4 view;
    mat4 projection;
    float time;
    vec3 light_position;
    vec3 light_directional_rotation;
    vec3 camera_position;
} ubo;

layout(binding = 1) uniform sampler2D diffuse_tex;
layout(binding = 2) uniform sampler2D normal_tex;

layout(location = 0) in vec2 tex_coords;
layout(location = 1) in vec3 normal_wld;
layout(location = 2) in vec3 position_wld;
layout(location = 3) in mat3 tbn;

layout(location = 0) out vec4 out_color;

void main() {
    vec3 normal_cam_u = vec3(texture(normal_tex, tex_coords).rg, 1.0);
    normal_cam_u = normal_cam_u * 2.0 - 1.0;
    normal_cam_u = normalize(tbn * normal_cam_u);

    vec3 light_direction_cam_u = normalize(ubo.light_position - position_wld);

    float ambient_strength = 0.1;
    vec3 light_color = vec3(1.0, 1.0, 1.0);
    vec3 ambient_color = ambient_strength * light_color;

    float diffuse_strength = max(0.0, dot(normal_cam_u, light_direction_cam_u));
    vec3 diffuse_color = diffuse_strength * light_color;

    float specular_value = 1.0;

    vec3 view_direction = normalize(vec3(inverse(ubo.view) * vec4(0.0, 0.0, 0.0, 1.0)) - position_wld);
    vec3 halfway_direction = normalize(light_direction_cam_u + view_direction);
    float specular_strength = pow(max(dot(normal_cam_u, halfway_direction), 0.0), 2);
    vec3 specular_color = specular_value * specular_strength * light_color;

    out_color = vec4(ambient_color + diffuse_color + specular_color, 1.0) * texture(diffuse_tex, tex_coords);
    if (push.is_selected) {
        out_color = mix(out_color, vec4(0.5, 0.5, 0.0, 1.0), 0.1);
    }
}