OpenGL中的光线追踪通过计算着色器实现。

10

我正在通过计算着色器在OpenGL中尝试进行一些光线追踪,并遇到了一个奇怪的问题。目前,我只想显示一个没有任何阴影的球体。我的计算着色器为每个像素启动一条射线,看起来像这样:

#version 430
struct Sphere{
    vec4    position;
    float   radius;
};

struct Ray{
    vec3    origin;
    vec3    dir;
};

uniform image2D outputTexture;
uniform uint        width;
uniform uint        height;

float hitSphere(Ray r, Sphere s){

    float s_vv = dot(r.dir, r.dir);
    float s_ov = dot(r.origin, r.dir);
    float s_mv = dot(s.position.xyz, r.dir);
    float s_mm = dot(s.position.xyz, s.position.xyz);
    float s_mo = dot(s.position.xyz, r.origin);
    float s_oo = dot(r.origin, r.origin);

    float d = s_ov*s_ov-2*s_ov*s_mv+s_mv*s_mv-s_vv*(s_mm-2*s_mo*s_oo-s.radius*s.radius);

    if(d < 0){
        return -1.0f;
    } else if(d == 0){
        return (s_mv-s_ov)/s_vv;
    } else {
        float t1 = 0, t2 = 0;
        t1 = s_mv-s_ov;

        t2 = (t1-sqrt(d))/s_vv;
        t1 = (t1+sqrt(d))/s_vv;

        return t1>t2? t2 : t1 ; 
    }
}

layout (local_size_x = 16, local_size_y = 16, local_size_z = 1) in;
void main(){
    uint x = gl_GlobalInvocationID.x;
    uint y = gl_GlobalInvocationID.y;

    if(x < 1024 && y < 768){
        float t = 0.0f;
        Ray r = {vec3(0,0,0), vec3(width/2-x, height/2-y, 1000)};
        Sphere sp ={vec4(0, 0, 35, 1), 5.0f};

        t = hitSphere(r, sp);

        if(t <= -0.001f){
            imageStore(outputTexture, ivec2(x, y), vec4(0.0, 0.0, 0.0, 1.0));
        } else {
            imageStore(outputTexture, ivec2(x, y), vec4(0.0, 1.0, 0.0, 1.0));
        }

        if(x == 550 && y == 390){
            imageStore(outputTexture, ivec2(x, y), vec4(1.0, 0.0, 0.0, 1.0));
        }
    } 
}

当我运行应用程序时,我会得到以下图片: 输入图像描述 但是,当我在CPU上运行相同的算法时,我会得到以下更有说服力的图片: 输入图像描述 起初,我以为我没有分派足够的工作组,以至于不是每个像素都有自己的计算着色器调用,但事实并非如此。正如您可以在GPU渲染的图像中看到的那样,中间有一个红色像素,这是由计算着色器中的最后一行引起的。这可以重现为每个其他像素。
目前,我使用1024x768的分辨率,这是我分派计算着色器的方式:
#define WORK_GROUP_SIZE 16
void OpenGLRaytracer::renderScene(int width, int height){
    glUseProgram(_progID);

    glDispatchCompute(width/WORK_GROUP_SIZE, height/WORK_GROUP_SIZE,1);

    glMemoryBarrier(GL_TEXTURE_FETCH_BARRIER_BIT);
}

哪里出了问题?浮点数计算的精度可能存在问题吗?


这个应用看起来很奇怪,它和我上周六做的东西一模一样。 - Justin Meiners
你是否遇到过这样奇怪的行为? - Stan
你的#version指令在哪里? - genpfault
忘记复制了,我会编辑的。 - Stan
"WORK_GROUP_SIZE"是什么? - Nicol Bolas
工作组大小为16,分辨率为1024x768。 - Stan
1个回答

5
错误出现在这一行中:
Ray r = {vec3(0,0,0), vec3(width/2-x, height/2-y, 1000)};

由于宽度、高度、x和y是无符号变量,当width/2-x这个术语变为负数时,您将遇到问题。

这解决了这个问题:

Ray r = {vec3(0,0,0), vec3(float(width)/2.0f-float(x), float(height)/2.0f-float(y), 1000)};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接