mathgraphicsgeometryvulkangeometry-shader

Vulkan 2D geometry shader generated geometry lines exhibiting parralellogram shape


I am trying to add support for geometry shaders for a Vulkan project, so I am just starting with something simple for now.

The goal is, given a list of vertices, generate a perfect rectangle encompassing that line.

For that effect I made this geometry shader:

#version 450
#extension GL_ARB_separate_shader_objects : enable

layout(lines) in;
layout(triangle_strip, max_vertices = 6) out;

layout(location = 0) in vec2 fragCoord[];

layout(location = 0) out vec2 fragTexCoord;

void main() {
    vec2 p1 = gl_in[0].gl_Position.xy;
    vec2 p2 = gl_in[1].gl_Position.xy;
    vec2 tangent = normalize(p2 - p1);
    vec2 normal = vec2(tangent.y, -tangent.x) * 0.05;

    vec2 quad[4] = vec2[](p1 + normal, p1 - normal, p2 + normal, p2 - normal);

    // Create first triangle
    gl_Position = vec4(quad[0], 0, 1);
    EmitVertex();
    gl_Position = vec4(quad[1], 0, 1);
    EmitVertex();
    gl_Position = vec4(quad[2], 0, 1);
    EmitVertex();
    EndPrimitive();

    // Create second triangle
    gl_Position = vec4(quad[1], 0, 1);
    EmitVertex();
    gl_Position = vec4(quad[2], 0, 1);
    EmitVertex();
    gl_Position = vec4(quad[3], 0, 1);
    EmitVertex();
    EndPrimitive();
}

Which outputs: enter image description here

The vertex shader is:

#version 450
#extension GL_ARB_separate_shader_objects : enable

layout(location = 0) in vec3 inPosition;
layout(location = 1) in vec2 inTexCoord;

layout(location = 0) out vec2 fragTexCoord;

void main() {

    gl_Position = vec4(inPosition, 1.0);
    fragTexCoord = inTexCoord;
}

I am not sure why the lines are parallelograms instead of rectangles. Adding the normal to the line (the orthogonal direction) to both vertices in the line should make a rectangle, by definition.

Edit:

Even hard coding the vertices in the vertex shader seems to produce the same result:

vec4 verts[2] = vec4[](vec4(-0.5,-0.5,0,1), vec4(0.5,0.5,0,1));
void main() {
    gl_Position = verts[gl_VertexID];//vec4(inPosition, 1.0);
    fragTexCoord = inTexCoord;
}

Solution

  • I made a silly mistake, since coordinates are calculated on the NORMALIZED GL space, but the window is not a square, my space is stretched, defroming the topology. This is the result in a perfectly squared image:

    enter image description here

    To correct this error I must pass the aspect ratio information to the shader and correct the vertex positions accordingly.