【问题标题】:GLSL - Trying to add multiple lights?GLSL - 尝试添加多个灯?
【发布时间】:2013-10-09 03:12:25
【问题描述】:

我有一个模拟 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 看到这不起作用。但我很困惑?如何累积特定像素上的灯光强度?

【问题讨论】:

    标签: c++ opengl glsl shader fragment-shader


    【解决方案1】:
    Light light1;
    light0.pos = iMouse.xy;
    light0.spread = 500.0;
    light0.size = 200.0;
    

    您没有在此处初始化 light1。也许价差为零,除以它时会产生 NaN。

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

    【讨论】:

    • 除此之外,OP 甚至没有使用数组,而是声明了两个额外的灯。
    • 这里有一个更好的开始(只需将 Marius 和 derhass 的 cmets 转换为代码):灯光 [2];灯[0].pos = iMouse.xy;灯[0].spread = 400.0;灯[0].size = 50.0;灯[1].pos = iMouse.xy+vec2(100,100);灯[1].spread = 100.0;灯[1].size = 100.0;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-08
    • 1970-01-01
    相关资源
    最近更新 更多