#version 450
#extension GL_ARB_separate_shader_objects : enable

layout(set = 1, binding = 0) uniform CameraData
{
    mat4 viewProjection;
    mat4 view;
    mat4 projection;
    vec4 camPos;
    float nearPlane;
    float farPlane;
    float width;
    float height;
    float fov;
    float aspect;
    float scaleFactor;
    float pixelScaleFactor;
} cam;

layout(set = 2, binding = 0) uniform RealCameraData
{
    mat3 intrinsic;
    int width;
    int height;
} realCam;

layout(location = 0) out vec2 textureCoordinates;
layout(location = 1) out float scaleOut;

// Background plane positions are in clipped space
const vec4 PLANE[4] = vec4[](
        vec4(1, -1, 1, 1), vec4(-1, -1, 1, 1), vec4(1, 1, 1, 1), vec4(-1, 1, 1, 1)
    );
const vec2 TEX_COORDS[4] = vec2[](
        vec2(1, 0), vec2(0, 0), vec2(1, 1), vec2(0, 1)
    );

void main() {
    vec4 position = PLANE[gl_VertexIndex];

    // Calculate the scaling factors for width and height
    float height = realCam.height;
    float realScale = height / realCam.intrinsic[1][1];
    float realAspect = height / realCam.width;
    float scaleY = realScale / cam.scaleFactor;
    float scaleX = scaleY / (cam.aspect * realAspect);

    // Handle center
    vec2 centerOffset = realCam.intrinsic[2].xy / vec2(realCam.width, realCam.height);
    centerOffset -= 0.5;
    position.xy -= centerOffset * vec2(2, 2);

    // Scale the quad's position
    position.xy *= vec2(scaleX, scaleY);

    scaleOut = 1 / scaleY;
    gl_Position = position;
    textureCoordinates = TEX_COORDS[gl_VertexIndex];
}
