views:

111

answers:

1

Hello:

I have the following recursive code and it doesn't behave as expected (see details below):

R3Intersection ComputeIntersectionNode(R3Ray *ray, R3Node *node)
{
  R3Intersection closest_inter;
  R3Intersection child_inter;
  R3Intersection shape_inter;

  double least_t = DBL_MAX;

  // check for intersection with shape
  if(node->shape != NULL)
  {
    shape_inter = ComputeIntersectionShape(ray, node->shape);
    if(shape_inter.hit == 1)
      closest_inter = shape_inter;
  }

  // go through all the children and for each child, compute
  // the closest intersection with ray
  for(int i = 0; i < node->children.size(); i++)
  {
    // compute intersection with children[i] and ray
    child_inter = ComputeIntersectionNode(ray, node->children[i]);

    // if there's an intersection with the child node and
    // it is the closest intersection, set closest intersection
    if(child_inter.hit == 1 && fabs(child_inter.t) < fabs(least_t))
      closest_inter = child_inter;
  }

  return closest_inter;
}

This ComputeIntersectionNode(...), in addition to the recursive calls, is also being called for multiple rays in the program. To test this function, I run it for 4 rays and 4 nodes (or more precisely, one root of type node, which doesn't have a shape, but has 4 children, each of which have one shape). For testing, each ray intersects exactly one node/shape.

When I run the code in GDB for the first ray, it first passes the root through the code, which doesn't have a shape, so then it goes directly to the children. It computes the first child's intersection correctly and sets the closest_inter variable correctly as well, which gets returned to the highest level of recursion and child_inter as well as closest_inter are set here with child_inter.hit = 1;

Then, the second child is processed. ComputeIntersectionShape(...) returns no intersection with the second child (shape_inter.hit == 0;) - this is expected behavior. However, when the function returns to the highest level of recursion, for some reason child_inter.hit is set to 1 (but should be set to 0).

Any suggestions?

Thank you in advance.

+1  A: 

I think your problem is caused by the fact you are returning a default-initialized R3Intersection (ie. you don't return the shape_inter when it doesn't intersect). Depending on its default constructor, you might get what you see.

jpalecek