为什么用纯GLSL片段着色器绘制时GLSL线内部有瑕疵

Why GLSL line has flaws inside when drawing with a pure GLSL fragment shader

我正在尝试使用纯 GLSL(仅片段着色器)绘制一条线。 但是线里面有一些瑕疵,很奇怪! 来看代码:

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);
}

结果行在这里,点击查看: Line with flaw inside

有人知道画线算法有什么问题吗?

smoothstep 的结果仅为 edge0 < edge1 定义。如果edge0 >= edge1,结果未定义。
edge0edge1 交换并反转结果:

col.rg += vec2(smoothstep(0.01, 0.01-0.006, d));

col.rg += vec2(1.0 - smoothstep(0.01-0.006, 0.01, d));