View Single Post
Old 2008-01-24, 13:26   #1
kuratkull
 
kuratkull's Avatar
 
Mar 2007
Estonia

23·17 Posts
Default Intersection with cubic

Hey, this topic could have been made under Programming, but I decided that this is more math centered.

Ok, I'm writing my own raytracer and it's basically finished. It's ~300 lines of C code. As you may guess/know, the most important step is to calculate the intersections with the ray and object(in this situation, cube).
The way I solved this now, is the most robust way:
1. I have calculated the vector(vec.x, vec.y, vec.z), I have the starting point(ray.x, ray.y, ray.z).
2. Add unit vector to current location and loop through every object to see if it is currently in the boundries of any cube(repeat #2 for x times):

SIZE is handeled by the C preprocessor and is replaced by an integer, let's say '40' in my case. This is in units.
It checks if all three coordinates are currently all within a single object and then returns the number of the object it hit, else it returns '-1'. This is rather impractical, but that's why I'm here, asking for your help :)

Code:
int collide(double ray.x, double ray.y, double ray.z)
{
    int i;
    for (i = 0; i < num_of_obj; i++)
    {
        if (ray.x >= objects[i][0] && ray.x <= objects[i][0]+SIZE)
        {
            if (ray.y >= objects[i][1] && ray.y <= objects[i][1]+SIZE)
            {
                if (ray.z >= objects[i][2] && ray.z <= objects[i][2]+SIZE)
                {
                    return (i);
                }
            }
        }
    }
    return(-1);
}
I read from an online tutorial, that the best way would be to use polynomial functions to detect the intersection.
The biggest negative side of my current solution is the inaccuracy: let's say the ray is very near to a corner of a cube, the ray might "jump" through the corner, if the vector is a bit too large.

Can anyone help me to figure out a (polynomial)function to get an intersection point? I guess the needed inputs would be:
*(vec.x, vec.y, vec.z) - current (unit)vector
*(ray.x, ray.y, ray.z) - current location of ray
and
*the locations of cubes are global variables, so they don't need to be an input, they could be accessed from objects[o][0..3].
*Size is also available as global.

I would be very grateful to anyone who feels like helping me out :)
PS! I have tried using google for this, but failed to get a straightforward answer :(
kuratkull is offline   Reply With Quote