void testRayIntersect() { KDTree<Triangle> tree; Array<int> index; Array<Point3> vertex; printf(" (load model, "); fflush(stdout); ArticulatedModel::Ref model = ArticulatedModel::fromFile(System::findDataFile("cow.ifs")); extractTriangles(model, vertex, index); for (int i = 0; i < index.size(); i += 3) { int i0 = index[i]; int i1 = index[i + 1]; int i2 = index[i + 2]; tree.insert(Triangle(vertex[i0], vertex[i1], vertex[i2])); } printf("balance tree, "); fflush(stdout); tree.balance(); Vector3 origin = Vector3(0, 5, 0); IntersectCallback intersectCallback; printf("raytrace, "); fflush(stdout); for (int i = 0; i < 4000; ++i) { // Cast towards a random point near the cow surface Vector3 target = vertex.randomElement() + Vector3::random() * 0.0001f; Ray ray = Ray::fromOriginAndDirection(origin, (target - origin).direction()); // Exhaustively test against each triangle float exhaustiveDistance = inf(); { const KDTree<Triangle>::Iterator& end = tree.end(); KDTree<Triangle>::Iterator it = tree.begin(); while (it != end) { const Triangle& tri = *it; float d = ray.intersectionTime(tri); if (d > 0 && d < exhaustiveDistance) { exhaustiveDistance = d; } ++it; } } // Test using the ray iterator float treeDistance = inf(); tree.intersectRay(ray, intersectCallback, treeDistance, true); float treeDistance2 = inf(); tree.intersectRay(ray, intersectCallback, treeDistance2, false); debugAssertM(fuzzyEq(treeDistance, exhaustiveDistance), format("KDTree::intersectRay found a point at %f, " "exhaustive ray intersection found %f.", treeDistance, exhaustiveDistance)); debugAssertM(fuzzyEq(treeDistance2, exhaustiveDistance), format("KDTree::intersectRay found a point at %f, " "exhaustive ray intersection found %f.", treeDistance2, exhaustiveDistance)); } printf("done) "); }