这个在GPU上运行的光线追踪功能,GPU安全吗?

问题描述

我尝试在片段着色器中编写一个简单的光线追踪器。 我有这个函数应该创建一个漫射球体,如下所示:

enter image description here

这是函数

vec3 GetRayColor(Ray ray)
{
Ray new_ray = ray;
vec3 FinalColor = vec3(1.0f);

bool IntersectionFound = false;
int hit_times = 0;

for (int i = 0; i < RAY_BOUNCE_LIMIT; i++)
{
    RayHitRecord ClosestSphere = IntersectScenespheres(new_ray,0.001f,MAX_RAY_HIT_disTANCE);

    if (ClosestSphere.Hit == true)
    {
        // Get the final ray direction

        vec3 R;
        R.x = nextFloat(RNG_SEED,-1.0f,1.0f); 
        R.y = nextFloat(RNG_SEED,1.0f);
        R.z = nextFloat(RNG_SEED,1.0f);

        vec3 S = normalize(ClosestSphere.normal) + normalize(R);
        S = normalize(S);

        new_ray.Origin = ClosestSphere.Point;
        new_ray.Direction = S;

        hit_times += 1;
        IntersectionFound = true;
    }

    else
    {
        FinalColor = GetGradientColorAtRay(new_ray);
        break;
    }
}

if (IntersectionFound)
{
    FinalColor /= 2.0f; // LAmbertian diffuse only absorbs half the light
    FinalColor = FinalColor / float(hit_times);
}

return FinalColor;
}

出于某种原因,hit_times 似乎是常数。 这个完全相同的代码cpu 上运行并生成了附加的屏幕截图。

我不确定这是否与 GPU 有关。但我已经测试了所有其他功能,它们按预期工作。

  1. 法线很好且完全相同
  2. 随机生成器工作正常并且已经可视化

这是可视化的 normal + RandomVecS

enter image description here

cpu 上完成时完全相同。

这是在 cpu

上可视化的 hit_times

enter image description here

但在 GPU 上,三个球体都是白色的。 这是完整的片段着色器:https://pastebin.com/3xeA6LtT 这是在 cpu 上运行的代码https://pastebin.com/eyLnHYzr

解决方法

所有球体很可能都是白色的,因为 ClosestSphere.Hit 函数中的 GetRayColor 始终为真。

我认为问题出在您的 IntersectSceneSpheres 函数中。

在 CPU 代码中,您返回默认为 false 的 HitAnything。同时,在片段着色器中,如果没有命中,则返回结构体 ClosestRecord,该结构体保持未初始化状态。

ClosestRecord.Hit = HitAnything; 函数的末尾显式添加 IntersectSceneSpheres 应该可以修复它