c ++递归错误

时间:2010-03-31 20:27:28

标签: c++ recursion raytracing

我有以下递归代码,它的行为不符合预期(详见下文):

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;
}

除了递归调用之外,还会在程序中为多个光线调用此ComputeIntersectionNode(...)。为了测试此功能,我运行了4 rays和4 nodes(或者更确切地说,rootnode,它没有{{1} },但有4 shape,每个都有一个children)。对于测试,每个shape只与一个ray / node相交。

当我在GDB中为第一个shape运行代码时,它首先通过ray通过代码,该代码没有root,因此它直接转到shape。它正确计算第一个孩子的交集,并正确设置children变量,返回到最高递归级别,closest_inter以及child_inter设置为{{1} }}

然后,处理第二个孩子。 closest_inter不返回与第二个子项(child_inter.hit = 1;;)的交集 - 这是预期的行为。但是,当函数返回到最高递归级别时,由于某种原因,child_inter.hit设置为1(但应设置为0)。

有什么建议吗?

提前谢谢。

1 个答案:

答案 0 :(得分:1)

我认为您的问题是由您返回默认初始化R3Intersection引起的(即,当它不相交时您不返回shape_inter)。根据其默认构造函数,您可能会得到您所看到的内容。