title: Drawing a border on a 2d polygon with a fragment shader
body: <p>I have some simple polygons (fewer than 20 vertices) rendering flat on a simple xy plane, using GL_TRIANGLES and a flat color, a 2d simulation.</p>
  
  <p>I would like to add a border of variable thickness and a different color to these polygons. I have something implemented using the same vertices and glLineWidth/GL_LINE_LOOP, which works, but is another rendering pass and repeats all the vertex transforms.</p>
  
  <p>I think I should be able to do this in the fragment shader using gl_FragCoord and the vertex data and/or texture coordinates, but I'm not sure, and my naive attempts have been obviously incorrect.</p>
  
  <p>I imagine something like the following.</p>
  
  <pre><code>uniform vec2 scale;  // viewport h/w
  uniform float line_width;
  uniform vec4 fill_color;
  uniform vec4 border_color;
  
  varying vec4 vertex; // in world coords
  
  void main()
  {
      if (distance_from_edge(gl_FragCoord, vertex, scale) &lt; line_width)
      {
          // we're close to the edge the polygon, so we're the border.
          gl_FragColor = border_color;
      }
      else
      {
          gl_FragColor = fill_color;
      }
  }
  </code></pre>
  
  <p>The part I'm trying to figure out is the distance_from_edge function - how can that be calculated? Is using gl_FragCoord the wrong approach - should I be using some kind of texture mapping?</p>
  
  <p>As an experiment I tried converting the vertex to pixel space with the scale, and then calculate the distance between that and gl_FragCoord in pixels, but that give strange results that I didn't really understand. Plus I need the distance to the <em>edge</em>, not the vertex, but I'm not sure how to get that. </p>
  
  <p>Any ideas?</p>
  
  <p>EDIT: based on Nicol's response, my question becomes:</p>
  
  <p>Assuming I have a triangle with 3 corner vertices marked as edge vertices, and one vertex in the middle marked as not edge (so rendered with 3 triangles in total), then how do I interpolate in the fragment shader to draw a border of a given thickness? I am assuming I pass the edge flag to the fragment shader, as well as the desired line thickness, and it does some interpolation calculation to figure out the distance between the edge and not edge vertices, and thresholds the color as border/fill as appropriate?</p>