GLSL - 尝试添加多个光源

GLSL - Trying to add multiple lights?

本文关键字:光源 添加 GLSL      更新时间:2023-10-16

我有一个简单的片段着色器来模拟2D照明,如下所示:

struct Light
{
    vec2 pos;     // Light position
    float spread;    // Light spread
    float size;   // Light bulb size
};
void main(void)
{
    Light light0;    // Define the light
    light0.pos = iMouse.xy;    // Set the position to mouse coords
    light0.spread = 500.0;
    light0.size = 200.0;
    float x_dis = light0.pos.x - gl_FragCoord.x;   
    float y_dis = light0.pos.y - gl_FragCoord.y;
    float intensity = sqrt(pow(x_dis, 2.0) + pow(y_dis, 2.0))-light0.size;  // Pythagorean Theorem - size
    if(intensity < 0.0)
        intensity = 0.0;
    else
        intensity /= light0.spread;    // Divide the intensity by the spread
    gl_FragColor = vec4(1.0-intensity, 1.0-intensity, 1.0-intensity, 1.0);
}

这在屏幕上放了一盏灯。(您可以在此处查看 https://www.shadertoy.com/view/XsX3Wl(

我想,"嘿,这很容易!我就做一个 for 循环,把光的强度结合起来!

这就是我所做的:

struct Light
{
    vec2 pos;     // Light position
    float spread;    // Light spread
    float size;   // Light bulb size
};
void main(void)
{
    Light lights[2];
    Light light0;
    light0.pos = iMouse.xy;
    light0.spread = 500.0;
    light0.size = 200.0;
    Light light1;
    light0.pos = iMouse.xy;
    light0.spread = 500.0;
    light0.size = 200.0;
    float intensity = 0.0;
    for(int i = 0; i < 2; i++)
    {
        float x_dis = lights[i].pos.x - gl_FragCoord.x;   
        float y_dis = lights[i].pos.y - gl_FragCoord.y;
        float sub_ints = sqrt(pow(x_dis, 2.0) + pow(y_dis, 2.0))-lights[i].size;  // Intensity relative to this light
        if(sub_ints < 0.0)
            sub_ints = 0.0;
        sub_ints /= lights[i].spread;    // Divide the intensity by the spread
        intensity += sub_ints;
    }
    gl_FragColor = vec4(1.0-intensity, 1.0-intensity, 1.0-intensity, 1.0);
}

您可以通过 https://www.shadertoy.com/view/4dX3Wl 看到这不起作用。但是我很困惑?如何累积特定像素上的灯光强度?

Light light1;
light0.pos = iMouse.xy;
light0.spread = 500.0;
light0.size = 200.0;

您在此处不是在初始化 light1。也许点差为零,除以它时会产生一个 NaN。

我知道会发生复制和粘贴错误,但很容易发现。在将代码发布到 SO 上之前,您应该对其进行认真的审查。