-1

I have written a geo shader which gets a line (2 vertices) and should add width (length) along the line normal. Without the geo shader everything gets displayed correctly. I have also calculated the formula with pencil and paper (worked). I am calculating them with the formula:

N1 = (-(x2 - x1),y2-y1) N2 = (x2 - x1 , -(y2 - y1))

My code:

#version 330 core
layout(lines) in;
layout(triangle_strip, max_vertices = 4) out;
uniform float length;

void main()
{
            //A -(x2 - x1) |   y2 - y1
            //B   x2 - x1  | -(y2 - y1)
            vec2 normal = normalize(vec2(gl_in[1].gl_Position.x - gl_in[0].gl_Position.x, gl_in[1].gl_Position.y - gl_in[0].gl_Position.y));
            vec3 normalA = vec3(-normal.x, normal.y, 0);
            vec3 normalB = vec3(normal.x, -normal.y, 0);
            gl_Position = gl_in[0].gl_Position + (vec4(normalB, 0) * length);
            EmitVertex();
            gl_Position = gl_in[0].gl_Position + (vec4(normalA, 0) * length);
            EmitVertex();
            gl_Position = gl_in[1].gl_Position + (vec4(normalA, 0) * length);
            EmitVertex();
            gl_Position = gl_in[1].gl_Position + (vec4(normalB, 0) * length);
            EmitVertex();
            EndPrimitive();
}

P0 [0.3, 0.3] P1 [0.4, 0.3]

Sens4
  • 605
  • 1
  • 11
  • 29

1 Answers1

0

Your formula is clearly wrong. You create a traingle strips with zero area for these particular input points.

If you have a 2D vector (x,y), the two perpendicular vectos to this are (-y, x) and (y, -x), not (-x,y) and (x,-y) as you currently use.

For your input points P0 and P1 and your original formula, you'll get both normalA and normalB with an y component of 0, so in the end , all 4 points will end up in a line on y=0.3, which results in a triangle strip consisting of two zero-area triangles which never get rasterized.

I'll suggest the follwowing code (also simplifying the syntax a bit):

        vec2 direction = normalize(gl_in[1].gl_Position.xy - gl_in[0].gl_Position.xy);
        vec4 offset =v ec4(-direction.y, direction.x, 0, 0) * length;
        gl_Position = gl_in[0].gl_Position - offset;
        EmitVertex();
        gl_Position = gl_in[0].gl_Position + offset;
        EmitVertex();
        gl_Position = gl_in[1].gl_Position + offset;
        EmitVertex();
        gl_Position = gl_in[1].gl_Position - offset;
        EmitVertex();
        EndPrimitive();
derhass
  • 43,833
  • 2
  • 57
  • 78