#version 450
#extension GL_ARB_separate_shader_objects : enable

layout(set = 1, binding = 0) uniform CameraData
{
    mat4 viewProjection;
    mat4 view;
    mat4 projection;
    vec4 camPos;
} cam;

layout(location = 0) out vec3 nearPoint;
layout(location = 1) out vec3 farPoint;

// Grid position are in clipped space
vec3 gridPlane[4] = vec3[] (
    vec3(1, 1, 0), vec3(-1, 1, 0), vec3(1, -1, 0), vec3(-1, -1, 0)
);

vec3 UnprojectPoint(float x, float y, float z, mat4 view, mat4 projection) {
    vec4 unprojectedPoint = inverse(cam.viewProjection) * vec4(x, y, z, 1.0);
    return unprojectedPoint.xyz / unprojectedPoint.w;
}

void main() {
    vec3 p = gridPlane[gl_VertexIndex].xyz;
    nearPoint = UnprojectPoint(p.x, p.y, 0.0, cam.view, cam.projection).xyz; // unprojecting on the near plane
    farPoint = UnprojectPoint(p.x, p.y, 1.0, cam.view, cam.projection).xyz; // unprojecting on the far plane
    gl_Position = vec4(p, 1.0); // using directly the clipped coordinates
}
