Refraction in C++ RayTracer giving artifacts

406 views Asked by At

I am currently working on the refract function for my RayTracer. For some reason, i can't get it to work. It definitely renders a different image then usual, but it has a lot of artifacts in it, and it's not "transparent". My refract function is:

void computeRefractedLight( const Vec3Df & origin, const Vec3Df & dest, int & level, Vec3Df & hit, Vec3Df & color, int & triangleIndex, Vec3Df & hitnormal)
{
    //Calculate normal of triangle
    Triangle triangle3d = MyMesh.triangles[triangleIndex];
    Vec3Df normal = hitnormal;

    // Normalize the direction of the ray hitting the triangle
    Vec3Df viewDir = hit - origin;
    viewDir.normalize();

    // Breaking index (hardcoded for now)
    float n = 1.5f;

    float dotNV = n * (Vec3Df::dotProduct(normal, viewDir));
    float sqrtNV = (1 - ((Vec3Df::dotProduct(normal, viewDir))*(Vec3Df::dotProduct(normal, viewDir))));
    if(sqrtNV < EPSILON)
        return;
    else
    {
        Vec3Df result = ((dotNV - sqrtf(1 - (n * n) * sqrtNV)) * normal) - (n * viewDir);
        std::cout << "Calculating refraction" << std::endl;
        performRayTracing(hit, result, level, color);
    }
}

If I ue this code to render my image (a sphere on a plane), I get the following result:

enter image description here

The artifacts are probably caused by the floating point precision. However, I have used an Epsilon (0.0000f), but I could have implemented this the wrong way. Anyone who knows how to help me?

0

There are 0 answers