#version 330 core

layout(location = 0) in vec2 inCorner;
layout(location = 1) in vec3 inPos;
layout(location = 2) in float inSize;
layout(location = 3) in float inRotation;
layout(location = 4) in float inFade;

uniform mat4 viewMatrix;
uniform mat4 projectionMatrix;
uniform vec3 cameraPosition;

smooth out vec3 camspace_position; // position for per fragment lighting
smooth out vec3 camspace_normal;   // normal for per fragment lighting
smooth out vec3 frag_3D_position;

out vec2 vTex;
out float vFade;

void main()
{
    
    if (inFade <= 0.0 || inSize <= 0.0) {
        gl_Position = vec4(2.0, 2.0, 2.0, 1.0); 
        vTex = vec2(0.0);
        vFade = 0.0;
        return;
    }

    float s = sin(inRotation);
    float c = cos(inRotation);
    vec2 rotated = vec2(
        inCorner.x * c - inCorner.y * s,
        inCorner.x * s + inCorner.y * c
    ) * inSize;

    vec3 right = vec3(viewMatrix[0][0], viewMatrix[1][0], viewMatrix[2][0]);
    vec3 up    = vec3(viewMatrix[0][1], viewMatrix[1][1], viewMatrix[2][1]);

    vec3 worldPos = inPos + rotated.x * right + rotated.y * up;

    gl_Position = projectionMatrix * viewMatrix * vec4(worldPos, 1.0);
    vTex  = inCorner + vec2(0.5);
    vFade = inFade;
    
    mat4 ModelMatrix = mat4(inSize);
    ModelMatrix[3] = vec4(inPos, inSize);
    // Normal matrix (M^-1)T
    mat4 NormalMatrix = transpose(inverse(ModelMatrix));

    camspace_position = ((viewMatrix * ModelMatrix) * vec4(inPos.xyz, 1.0f)).xyz;
    camspace_normal = ((viewMatrix * NormalMatrix) * vec4(cross(right, up), 0)).xyz;
    frag_3D_position = worldPos;
    // V^-1 * M * V * position
}