سؤال
لدي الرمز المتكرر التالي ولا يتصرف كما هو متوقع (انظر التفاصيل أدناه):
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
(أو بدقة واحدة ، واحدة root
من النوع node
, ، التي لا تحتوي على ملف shape
, ، ولكن لديه 4 children
, ، كل منها لديه واحد shape
). للاختبار ، كل ray
يتقاطع بالضبط واحد node
/shape
.
عندما أقوم بتشغيل الرمز في GDB لأول مرة ray
, ، يمر أولاً root
من خلال الكود ، الذي لا يحتوي على ملف shape
, ، إذن يذهب مباشرة إلى children
. يحسب تقاطع الطفل الأول بشكل صحيح ويضع closest_inter
متغير بشكل صحيح أيضًا ، والذي يتم إرجاعه إلى أعلى مستوى من العودية و child_inter
إلى جانب closest_inter
تم تعيينها هنا مع child_inter.hit = 1;
ثم ، تتم معالجة الطفل الثاني. ComputeIntersectionShape(...)
لا يعيد أي تقاطع مع الطفل الثاني (shape_inter.hit == 0
؛) - هذا هو السلوك المتوقع. ومع ذلك ، عندما تعود الوظيفة إلى أعلى مستوى من العودية ، لسبب ما يتم ضبط child_inter.hit على 1 (ولكن يجب ضبطها على 0).
أي اقتراحات؟
شكرا لكم مقدما.
المحلول
أعتقد أن مشكلتك ناتجة عن حقيقة أنك تعيد تقصيرًا افتراضيًا R3Intersection
(أي أنك لا تعيد shape_inter
عندما لا يتقاطع). اعتمادًا على مُنشئه الافتراضي ، قد تحصل على ما تراه.