通过计算着色器在OpenGL中进行光线跟踪

Sta*_*tan 9 opengl raytracing gpgpu compute-shader

我试图通过计算着色器在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));
        }
    } 
}
Run Code Online (Sandbox Code Playgroud)

当我运行应用程序时,我得到以下图像: 在此输入图像描述

但是当我在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);
}
Run Code Online (Sandbox Code Playgroud)

哪里出错了?浮点计算的准确性可能存在问题吗?

Sta*_*tan 5

错误在这一行:

Ray r = {vec3(0,0,0), vec3(width/2-x, height/2-y, 1000)};
Run Code Online (Sandbox Code Playgroud)

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

这解决了这个问题:

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