GLSL issue with smoothstep function where edge0 is bigger than edge1

40 views Asked by At

I'm learning GLSL language in the book of shaders site. And at page 5, I see the following code.

#ifdef GL_ES
precision mediump float;
#endif

uniform vec2 u_resolution;
uniform vec2 u_mouse;
uniform float u_time;

// Plot a line on Y using a value between 0.0-1.0
float plot(vec2 st) {    
    return smoothstep(0.02, 0.0, abs(st.y - st.x));
}

void main() {
    vec2 st = gl_FragCoord.xy/u_resolution;

    float y = st.x;

    vec3 color = vec3(y);

    // Plot a line
    float pct = plot(st);
    color = (1.0-pct)*color+pct*vec3(0.0,1.0,0.0);

    gl_FragColor = vec4(color,1.0);
}

Basically the code result is a gradient from white to black and a green line from bottom left to top right. I understand where the black gradient come from. But I don't understand something about the smoothstep function where the edge0 is bigger than the edge1. I tried to change the value of abs(st.y - st.x) to any float positive number example 0.01. It's supposed to return a value around 0.5 if I understand it correctly. But somehow the returned value is always 0.0, because the green line is gone. Can anyone help me understand how the smoothstep function work?

1

There are 1 answers

0
Thomas On

This code is broken. In GLSL 4.40 for example, the result is undefined (spec):

genType smoothstep (genType edge0, genType edge1, genType x)

Returns 0.0 if x <= edge0 and 1.0 if x >= edge1 and performs smooth Hermite interpolation between 0 and 1 when edge0 < x < edge1. This is useful in cases where you would want a threshold function with a smooth transition. This is equivalent to:

genType t;
t = clamp ((x – edge0) / (edge1 – edge0), 0, 1);
return t * t * (3 – 2 * t);

(And similarly for doubles.)

Results are undefined if edge0 >= edge1.

In GLSL 1.10, the result wasn't explicitly undefined, so presumably this last sentence was added in some later revision.