Glsl 如何创建多步径向渐变片段着色器

Glsl 如何创建多步径向渐变片段着色器,glsl,fragment-shader,Glsl,Fragment Shader,我正在使用一些着色器代码通过混合颜色创建多步线性渐变。它工作得很好。我有一个使用距离的径向着色器。工作很好,但我不知道如何适应多步骤 我该怎么做呢 线性梯度 简单径向梯度 您只需计算当前片段到视口中心的距离。为此,必须以标准化设备坐标计算碎片位置。可以采用与“条带”着色器中y坐标相同的方式使用到中心的距离: 你的着色器应该看起来像这样: void main() { vec2 pos_ndc = 2.0 * gl_FragCoord.xy / resolution.xy - 1.0;

我正在使用一些着色器代码通过混合颜色创建多步线性渐变。它工作得很好。我有一个使用距离的径向着色器。工作很好,但我不知道如何适应多步骤

我该怎么做呢

线性梯度

简单径向梯度


您只需计算当前片段到视口中心的距离。为此,必须以标准化设备坐标计算碎片位置。可以采用与“条带”着色器中y坐标相同的方式使用到中心的距离:

你的着色器应该看起来像这样:

void main()
{
    vec2 pos_ndc = 2.0 * gl_FragCoord.xy / resolution.xy - 1.0;
    float dist = length(pos_ndc);

    vec4 white = vec4(1.0, 1.0, 1.0, 1.0);
    vec4 red = vec4(1.0, 0.0, 0.0, 1.0);
    vec4 blue = vec4(0.0, 0.0, 1.0, 1.0);
    vec4 green = vec4(0.0, 1.0, 0.0, 1.0);
    float step1 = 0.0;
    float step2 = 0.33;
    float step3 = 0.66;
    float step4 = 1.0;

    vec4 color = mix(white, red, smoothstep(step1, step2, dist));
    color = mix(color, blue, smoothstep(step2, step3, dist));
    color = mix(color, green, smoothstep(step3, step4, dist));

    gl_FragColor = color;
}
预览:


请参阅代码片段:

var ShaderProgram={};
ShaderProgram.Create=函数(shaderList){
var shaderObjs=[];
for(变量i_sh=0;i_shvoid mainImage( out vec4 fragColor, in vec2 fragCoord )
{

    float d = distance(iResolution.xy*0.5,fragCoord.xy)*(sin(1.0)+1.5)*0.003;
    fragColor = mix(vec4(1.0, 1.0, 1.0, 1.0), vec4(0.0, 0.0, 0.0, 1.0), d);
}
vec2 pos_ndc = 2.0 * gl_FragCoord.xy / resolution.xy - 1.0;
float dist = length(pos_ndc);
void main()
{
    vec2 pos_ndc = 2.0 * gl_FragCoord.xy / resolution.xy - 1.0;
    float dist = length(pos_ndc);

    vec4 white = vec4(1.0, 1.0, 1.0, 1.0);
    vec4 red = vec4(1.0, 0.0, 0.0, 1.0);
    vec4 blue = vec4(0.0, 0.0, 1.0, 1.0);
    vec4 green = vec4(0.0, 1.0, 0.0, 1.0);
    float step1 = 0.0;
    float step2 = 0.33;
    float step3 = 0.66;
    float step4 = 1.0;

    vec4 color = mix(white, red, smoothstep(step1, step2, dist));
    color = mix(color, blue, smoothstep(step2, step3, dist));
    color = mix(color, green, smoothstep(step3, step4, dist));

    gl_FragColor = color;
}