#version 460 core

layout(location = 0) in vec3 pos;
layout(location = 1) in vec3 norm;
layout(location = 2) in vec3 tangent;
layout(location = 3) in vec2 uv;
layout(location = 4) in uint draw_id;
layout(location = 5) in mat4 model_mat; // also occupies location 5, 6, 7 & 8
layout(location = 9) in mat3 normal_mat;

out VS_OUT {
    vec3      pos;
    vec3      tan_pos;
    vec2      uv;
    flat uint draw_id;
    mat3      TBN;
}
vs_out;

// Uniforms
uniform mat4 view_proj_mat; // View-projection matrix

void main() {
    // Tangent-space matrix
    vec3 T   = normalize(normal_mat * tangent);
    vec3 N   = normalize(normal_mat * norm);
    T        = normalize(T - dot(T, N) * N); // Re-orthogonalisation
    vec3 B   = cross(N, T);
    mat3 TBN = transpose(mat3(T, B, N));

    vec4 world_pos = model_mat * vec4(pos, 1.0);

    vs_out.pos     = vec3(world_pos) / world_pos.w; // World-space position
    vs_out.tan_pos = TBN * vs_out.pos;              // Tangent-space position
    vs_out.uv      = uv;                            // Texture coordinates
    vs_out.draw_id = draw_id;                       // MDI draw ID
    vs_out.TBN     = TBN;                           // World-space -> tangent-space matrix

    gl_Position = view_proj_mat * world_pos;
}
