参考:smoothstep
用来生成0-1的平滑过渡值
smoothstep函数源码实现:
float smoothstep(float t1, float t2, float x) {
// Scale, bias and saturate x to 0..1 range
x = clamp((x - t1) / (t2 - t1), 0.0, 1.0);
// Evaluate polynomial
return x * x * (3 - 2 * x);
}
先理解clamp函数:
用于将一个值限制在给定的范围之内。其语法为clamp(x, minVal, maxVal)
,它接受三个参数:
x
:要被限制的值。minVal
:范围的最小值。maxVal
:范围的最大值。
#ifdef GL_ES
precision mediump float;
#endif
uniform vec2 u_resolution;
uniform float u_time;
void main(){
vec2 st = gl_FragCoord.xy/u_resolution.xy;
st.x *= u_resolution.x/u_resolution.y;
float maxValue = abs(sin(u_time)) * 0.5;
float f = clamp(st.y, 0.0, maxValue);
gl_FragColor = vec4(f,f,f, 1.0);
}
- float maxValue = abs(sin(u_time));
- sin(u_time)返回[-1,1]的值,abs(sin(u_time)) 取绝对值将该值限制在了[0,1],再乘以0.5返回[0,0.5]
-
float f = clamp(st.y, 0.0, maxValue);
-
maxValue的区间为[0,0.5]
-
clamp(st.y, 0.0, maxValue)将屏幕的Y值限制在[0,0.5]之间
-
x = clamp((x - t1) / (t2 - t1), 0.0, 1.0);
- x的值被限制在0-1之间。
绘制圆环:
#ifdef GL_ES
precision mediump float;
#endif
uniform vec2 u_resolution;
void main(){
vec2 st = gl_FragCoord.xy/u_resolution.xy;
st -=0.5;
st.x *= u_resolution.x/u_resolution.y;
float r = length(st);
float r1 = smoothstep(0.2,0.3 ,r );
float r2 = smoothstep(0.3,0.4 ,r );
float color = r1- r2;
gl_FragColor = vec4(vec3(color),1.0);
}
r1-r2的函数图像
绘制结果