BVH_Example.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. #include <Eigen/StdVector>
  2. #include <unsupported/Eigen/BVH>
  3. #include <iostream>
  4. using namespace Eigen;
  5. typedef AlignedBox<double, 2> Box2d;
  6. namespace Eigen {
  7. Box2d bounding_box(const Vector2d &v) { return Box2d(v, v); } //compute the bounding box of a single point
  8. }
  9. struct PointPointMinimizer //how to compute squared distances between points and rectangles
  10. {
  11. PointPointMinimizer() : calls(0) {}
  12. typedef double Scalar;
  13. double minimumOnVolumeVolume(const Box2d &r1, const Box2d &r2) { ++calls; return r1.squaredExteriorDistance(r2); }
  14. double minimumOnVolumeObject(const Box2d &r, const Vector2d &v) { ++calls; return r.squaredExteriorDistance(v); }
  15. double minimumOnObjectVolume(const Vector2d &v, const Box2d &r) { ++calls; return r.squaredExteriorDistance(v); }
  16. double minimumOnObjectObject(const Vector2d &v1, const Vector2d &v2) { ++calls; return (v1 - v2).squaredNorm(); }
  17. int calls;
  18. };
  19. int main()
  20. {
  21. typedef std::vector<Vector2d, aligned_allocator<Vector2d> > StdVectorOfVector2d;
  22. StdVectorOfVector2d redPoints, bluePoints;
  23. for(int i = 0; i < 100; ++i) { //initialize random set of red points and blue points
  24. redPoints.push_back(Vector2d::Random());
  25. bluePoints.push_back(Vector2d::Random());
  26. }
  27. PointPointMinimizer minimizer;
  28. double minDistSq = std::numeric_limits<double>::max();
  29. //brute force to find closest red-blue pair
  30. for(int i = 0; i < (int)redPoints.size(); ++i)
  31. for(int j = 0; j < (int)bluePoints.size(); ++j)
  32. minDistSq = std::min(minDistSq, minimizer.minimumOnObjectObject(redPoints[i], bluePoints[j]));
  33. std::cout << "Brute force distance = " << sqrt(minDistSq) << ", calls = " << minimizer.calls << std::endl;
  34. //using BVH to find closest red-blue pair
  35. minimizer.calls = 0;
  36. KdBVH<double, 2, Vector2d> redTree(redPoints.begin(), redPoints.end()), blueTree(bluePoints.begin(), bluePoints.end()); //construct the trees
  37. minDistSq = BVMinimize(redTree, blueTree, minimizer); //actual BVH minimization call
  38. std::cout << "BVH distance = " << sqrt(minDistSq) << ", calls = " << minimizer.calls << std::endl;
  39. return 0;
  40. }