0

I'm trying to draw a 2 dimensional line the has a smooth gradient between two colors. My application allows me to click and drag, the first point of the line segment is the first click point, the second point of the line follows the mouse cursor position.

I have the line drawing using glDrawArrays(GL_LINES, 0, points.size());, points is a 2 index array of points.

The line draws fine, clicking and dragging to move the line around works, but I'm having explainable behavior with my fragment shader:

uniform vec4 color1; //Color at p1
uniform vec4 color2; //Color at p2

out vec4 fragColor;      
void main() 
{
    //Average the fragment positions
    float weight = (gl_PointCoord.s + gl_PointCoord.t) * 0.5f; 

    //Weight the first and second color
    fragColor = (color1 * weight) + (color2 * (1.0f - weight));
}

color1 is red, color2 is green.

As I drag my line around it bounces between entirely red, entirely green, the gradient I desire, or some solid mixture of red and green on every screen redraw.

I suspect I'm using gl_PointCoord incorrectly, but I can't inspect the values as they're in the shader.I tried the following in my shader:

fragColor = (color1 + color2) * 0.5f;

And it gives a stable yellow color, so I have some confidence that the colors are stable between redraws.

Any tips?

user2278457
  • 315
  • 2
  • 9

1 Answers1

3

gl_PointCoord is only defined for point primitves. Using it with GL_LINES is just undefined behavior and never going to work.

If you want a smooth gradient, you should add a weight attribute to your line vertices and set it to 0 or 1 for start and end points, respectively.

derhass
  • 43,833
  • 2
  • 57
  • 78
  • Well now I feel silly. There is no way to get the information I need short of passing in the 2 points that define the line as uniforms(or one point and the length)? – user2278457 Oct 05 '14 at 23:07
  • I don't know why you want to use uniforms for that. As I said, an attribute is fine. You can even generate the data on the fly on the GPU in a geometry shader. – derhass Oct 05 '14 at 23:12
  • I don't see the harm in letting the GPU recalculate the color on redraw. Probably still better than transferring the data from the cpu. – user2278457 Oct 05 '14 at 23:17
  • Oh, I did some more research and now I understand. If you pass in a color per vertex to your vertex shader and output as a varying color to your fragment shader, OpenGL automatically interpolates those colors per fragment(giving the smooth gradient). Thanks, this is what I ultimately ended up doing. – user2278457 Oct 06 '14 at 00:06