我正在尝试创建一个 OpenGL ES 2.0 片段着色器,它沿一个轴输出多个停止渐变。它应该在以百分比定义的点处的多种颜色之间进行插值。
我通过使用 if
实现了这一点s 片段着色器,如下所示:
float y = gl_FragCoord.y;
float step1 = resolution.y * 0.20;
float step2 = resolution.y * 0.50;
if (y < step1) {
color = white;
} else if (y < step2) {
float x = smoothstep(step1, step2, y);
color = mix(white, red, x);
} else {
float x = smoothstep(step2, resolution.y, y);
color = mix(red, green, x);
}
他们说片段着色器中的分支会降低性能。是否有一些巧妙的技巧可用于在不使用
if
的情况下在许多值之间进行插值? ?它真的值得吗(我知道这是非常主观的,但作为经验法则)?为了说明我的问题,此 GLSL 沙箱链接中的完整源代码(尽管仍然很短):http://glsl.heroku.com/e#8035.0
最佳答案
如果您想消除分支,您可以执行以下操作(取自 Heroku);
color = mix(white, red, smoothstep(step1, step2, y));
color = mix(color, blue, smoothstep(step2, step3, y));
color = mix(color, green, smoothstep(step3, resolution.y, y));
但我完全不确定这是否比 if/elses 更快。
关于opengl-es - 如何创建多停止渐变片段着色器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15935117/