Search code examples
javascriptraytracingrenderer

JS Ray Tracer object infinitely long


I have written a very primitive ray tracer in JS, it renders only one cube by shooting one ray from each pixel and checking if it intersects with the cube. If it intersects then that pixel is set to white and if not, black.

However the object starts in the correct place but is not the correct dimensions. This is best explained with a picture:

raytracing attempt with one cube

I have posted the code here However if you run it, it will take a very long time if you want to speed it up then reduce the number of iterations in

function main_v

I think the problem is with the ray intersection test (intersect_b function) however I have been unable to track down the problem. The intersection function is directly adapted from here


Solution

  • One issue is this:

    function c2p_p(r) {
        return r.type == vType.Cartesian ? {
            r: Math.sqrt(r.x ^ 2 + r.y ^ 2 + r.z ^ 2),
            theta: Math.acos(r.z / Math.sqrt(r.x ^ 2 + r.y ^ 2 + r.z ^ 2)),
            phi: Math.atan2(r.y / r.x),
            type: vType.Polar
        } : r
    }
    

    In JavaScript, the ^ operator is bitwise XOR, not exponentiation. Just write r.x*r.x + r.y*r.y + r.z*r.z instead.