title: Fragment Shader - Drawing Curved Lines
body: <p>How do I draw a line, or a curved line using a fragment shader?</p>
  
  <p>I have a program that calculates a bezier curve given a set of vertices specified by the user. Early on, it was pretty straightforward where I simply process each vertex on the application side to generate a set of interpolated points based on this cubic Bezier curve equation: </p>
  
  <p><a href="https://i.stack.imgur.com/vIgco.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vIgco.png" alt="Cubic Bezier curve"></a></p>
  
  <p>... and then store all the processed vertices into a GL_VERTEX_ARRAY for drawing with glDrawArrays(GL_LINE_STRIP, 0, myArraySize). While the solution is simple, the time complexity for this implementation is <strong>O(n^2)</strong>. The issue arises where I start increasing my step count, such as incrementing t by 0.01 each iteration of my loop, compounded by the user generating as many vertices they want.</p>
  
  <p>So that's when I started looking into shaders, especially the fragment shader. As far as I understand, our fragment shader program assigns a color to the current fragment being processed by the GPU. I haven't gotten serious into shader programming, but my current line shader implementation is as follows:</p>
  
  <pre><code>#version 120
  
  uniform vec2 resolution;
  uniform vec2 ptA;
  uniform vec2 ptB;
  uniform vec2 ptC;
  uniform vec2 ptD;
  uniform float stepTotal;
  
  void main()
  {
      vec2 uv = gl_FragCoord.xy / resolution.xy;
      vec2 curvePts[int(stepTotal)];
  
      float t = stepTotal;
  
      for(float i = 0.; i &lt; 1.0; i += 1./t)
      {
          # Courtesy to: https://yalantis.com/blog/how-we-created-visualization-for-horizon-our-open-source-library-for-sound-visualization/
          vec2 q0 = mix(ptA, ptB, i);
          vec2 q1 = mix(ptB, ptC, i);
          vec2 q2 = mix(ptC, ptD, i);
  
          vec2 r0 = mix(q0, q1, i);
          vec2 r1 = mix(q1, q2, i);
  
          vec2 p_int = mix(r0, r1, i);
          curvePts[int(i) * int(stepTotal)] = p_int;
      }
  
      // TO DO:
      // Check if current fragment is within the curve. Not sure how
      // to proceed from here...
  }
  </code></pre>
  
  <p>As you can see, I am currently stuck on how to check if the current fragment is within the curve, as well as how do I assign a color to that specific fragment that eventually becomes a curved line when displayed. </p>