I am trying to draw a line using pure GLSL ( only fragment shader ). But there are some flaws inside the line, very strange! Let's see the code:
vec2 A = vec2(-0.3, -0.3);
vec2 B = vec2(0.3, 0.3);
vec2 P = vec2(0.0, 0.3);
float drawCircle(vec2 uvPos, vec2 center, float r)
{
float d = smoothstep(r+0.01, r, length(uvPos - center));
return d;
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
//// initializions
// screen size ratio
float ratio = (iResolution.x/iResolution.y);
// Normalized pixel coordinates (from 0 to 1) with ratio (y is 1.0)
vec2 uv = vec2(ratio * fragCoord.x/iResolution.x, fragCoord.y/iResolution.y);
// screen center
vec2 center = vec2(0.5 * ratio, 0.5);
uv -= center;
uv *= 1.0;
//// drawings:
// pixel position relative to center
float d = length(uv);
// color of fragment
vec3 col = vec3(0.0, 0.0, 0.0);
//col.r = step(0.7, uv.x);
//col.g = step(0.3, d);
col.r += drawCircle(uv, A, 0.02);
col.g += drawCircle(uv, B, 0.02);
col.b += drawCircle(uv, P, 0.02);
// draw line, by using the distance of uv to line.
d = sqrt(length(uv-A)*length(uv-A)-dot(B-A, uv-A)*dot(B-A, uv-A)/length(B-A)/length(B-A));
col.rg += vec2(smoothstep(0.01, 0.01-0.006, d));
//// Output to screen
fragColor = vec4(col,1.0);
}
The result line here, click to see: Line with flaw inside
Anybody knows what is the problem with the line drawing algorithm?
The result of smoothstep
is only defined for edge0 < edge1
. If edge0 >= edge1
, the result is undefined.
Swap edge0
with edge1
and invert the result:
col.rg += vec2(smoothstep(0.01, 0.01-0.006, d));
col.rg += vec2(1.0 - smoothstep(0.01-0.006, 0.01, d));