如何创建多个停止渐变片段着色器?

时间:2013-04-10 19:51:01

标签: opengl-es opengl-es-2.0 glsl gradient interpolation

我正在尝试创建一个OpenGL ES 2.0片段着色器,它沿一个轴输出多个停止渐变。它应该在百分比定义的点之间插入多种颜色。

我通过使用if片段着色器实现了这一点,如下所示:

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 s的情况下在多个值之间进行插值?它真的值得(这是非常主观的,我知道,但作为经验法则)?

为了说明我的问题,请参阅此GLSL沙盒链接中的完整来源(尽管仍然很短):http://glsl.heroku.com/e#8035.0

1 个答案:

答案 0 :(得分:9)

如果您想消除分支,您可以执行以下操作(取自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更快。