KdBVH.h
00001 // This file is part of Eigen, a lightweight C++ template library
00002 // for linear algebra.
00003 //
00004 // Copyright (C) 2009 Ilya Baran <ibaran@mit.edu>
00005 //
00006 // Eigen is free software; you can redistribute it and/or
00007 // modify it under the terms of the GNU Lesser General Public
00008 // License as published by the Free Software Foundation; either
00009 // version 3 of the License, or (at your option) any later version.
00010 //
00011 // Alternatively, you can redistribute it and/or
00012 // modify it under the terms of the GNU General Public License as
00013 // published by the Free Software Foundation; either version 2 of
00014 // the License, or (at your option) any later version.
00015 //
00016 // Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
00017 // WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
00018 // FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
00019 // GNU General Public License for more details.
00020 //
00021 // You should have received a copy of the GNU Lesser General Public
00022 // License and a copy of the GNU General Public License along with
00023 // Eigen. If not, see <http://www.gnu.org/licenses/>.
00024 
00025 #ifndef KDBVH_H_INCLUDED
00026 #define KDBVH_H_INCLUDED
00027 
00028 namespace Eigen { 
00029 
00030 namespace internal {
00031 
00032 //internal pair class for the BVH--used instead of std::pair because of alignment
00033 template<typename Scalar, int Dim>
00034 struct vector_int_pair
00035 {
00036 EIGEN_MAKE_ALIGNED_OPERATOR_NEW_IF_VECTORIZABLE_FIXED_SIZE(Scalar, Dim)
00037   typedef Matrix<Scalar, Dim, 1> VectorType;
00038 
00039   vector_int_pair(const VectorType &v, int i) : first(v), second(i) {}
00040 
00041   VectorType first;
00042   int second;
00043 };
00044 
00045 //these templates help the tree initializer get the bounding boxes either from a provided
00046 //iterator range or using bounding_box in a unified way
00047 template<typename ObjectList, typename VolumeList, typename BoxIter>
00048 struct get_boxes_helper {
00049   void operator()(const ObjectList &objects, BoxIter boxBegin, BoxIter boxEnd, VolumeList &outBoxes)
00050   {
00051     outBoxes.insert(outBoxes.end(), boxBegin, boxEnd);
00052     eigen_assert(outBoxes.size() == objects.size());
00053   }
00054 };
00055 
00056 template<typename ObjectList, typename VolumeList>
00057 struct get_boxes_helper<ObjectList, VolumeList, int> {
00058   void operator()(const ObjectList &objects, int, int, VolumeList &outBoxes)
00059   {
00060     outBoxes.reserve(objects.size());
00061     for(int i = 0; i < (int)objects.size(); ++i)
00062       outBoxes.push_back(bounding_box(objects[i]));
00063   }
00064 };
00065 
00066 } // end namespace internal
00067 
00068 
00082 template<typename _Scalar, int _Dim, typename _Object> class KdBVH
00083 {
00084 public:
00085   enum { Dim = _Dim };
00086   typedef _Object Object;
00087   typedef std::vector<Object, aligned_allocator<Object> > ObjectList;
00088   typedef _Scalar Scalar;
00089   typedef AlignedBox<Scalar, Dim> Volume;
00090   typedef std::vector<Volume, aligned_allocator<Volume> > VolumeList;
00091   typedef int Index;
00092   typedef const int *VolumeIterator; //the iterators are just pointers into the tree's vectors
00093   typedef const Object *ObjectIterator;
00094 
00095   KdBVH() {}
00096 
00098   template<typename Iter> KdBVH(Iter begin, Iter end) { init(begin, end, 0, 0); } //int is recognized by init as not being an iterator type
00099 
00101   template<typename OIter, typename BIter> KdBVH(OIter begin, OIter end, BIter boxBegin, BIter boxEnd) { init(begin, end, boxBegin, boxEnd); }
00102 
00105   template<typename Iter> void init(Iter begin, Iter end) { init(begin, end, 0, 0); }
00106 
00109   template<typename OIter, typename BIter> void init(OIter begin, OIter end, BIter boxBegin, BIter boxEnd)
00110   {
00111     objects.clear();
00112     boxes.clear();
00113     children.clear();
00114 
00115     objects.insert(objects.end(), begin, end);
00116     int n = static_cast<int>(objects.size());
00117 
00118     if(n < 2)
00119       return; //if we have at most one object, we don't need any internal nodes
00120 
00121     VolumeList objBoxes;
00122     VIPairList objCenters;
00123 
00124     //compute the bounding boxes depending on BIter type
00125     internal::get_boxes_helper<ObjectList, VolumeList, BIter>()(objects, boxBegin, boxEnd, objBoxes);
00126 
00127     objCenters.reserve(n);
00128     boxes.reserve(n - 1);
00129     children.reserve(2 * n - 2);
00130 
00131     for(int i = 0; i < n; ++i)
00132       objCenters.push_back(VIPair(objBoxes[i].center(), i));
00133 
00134     build(objCenters, 0, n, objBoxes, 0); //the recursive part of the algorithm
00135 
00136     ObjectList tmp(n);
00137     tmp.swap(objects);
00138     for(int i = 0; i < n; ++i)
00139       objects[i] = tmp[objCenters[i].second];
00140   }
00141 
00143   inline Index getRootIndex() const { return (int)boxes.size() - 1; }
00144 
00147   EIGEN_STRONG_INLINE void getChildren(Index index, VolumeIterator &outVBegin, VolumeIterator &outVEnd,
00148                                        ObjectIterator &outOBegin, ObjectIterator &outOEnd) const
00149   { //inlining this function should open lots of optimization opportunities to the compiler
00150     if(index < 0) {
00151       outVBegin = outVEnd;
00152       if(!objects.empty())
00153         outOBegin = &(objects[0]);
00154       outOEnd = outOBegin + objects.size(); //output all objects--necessary when the tree has only one object
00155       return;
00156     }
00157 
00158     int numBoxes = static_cast<int>(boxes.size());
00159 
00160     int idx = index * 2;
00161     if(children[idx + 1] < numBoxes) { //second index is always bigger
00162       outVBegin = &(children[idx]);
00163       outVEnd = outVBegin + 2;
00164       outOBegin = outOEnd;
00165     }
00166     else if(children[idx] >= numBoxes) { //if both children are objects
00167       outVBegin = outVEnd;
00168       outOBegin = &(objects[children[idx] - numBoxes]);
00169       outOEnd = outOBegin + 2;
00170     } else { //if the first child is a volume and the second is an object
00171       outVBegin = &(children[idx]);
00172       outVEnd = outVBegin + 1;
00173       outOBegin = &(objects[children[idx + 1] - numBoxes]);
00174       outOEnd = outOBegin + 1;
00175     }
00176   }
00177 
00179   inline const Volume &getVolume(Index index) const
00180   {
00181     return boxes[index];
00182   }
00183 
00184 private:
00185   typedef internal::vector_int_pair<Scalar, Dim> VIPair;
00186   typedef std::vector<VIPair, aligned_allocator<VIPair> > VIPairList;
00187   typedef Matrix<Scalar, Dim, 1> VectorType;
00188   struct VectorComparator //compares vectors, or, more specificall, VIPairs along a particular dimension
00189   {
00190     VectorComparator(int inDim) : dim(inDim) {}
00191     inline bool operator()(const VIPair &v1, const VIPair &v2) const { return v1.first[dim] < v2.first[dim]; }
00192     int dim;
00193   };
00194 
00195   //Build the part of the tree between objects[from] and objects[to] (not including objects[to]).
00196   //This routine partitions the objCenters in [from, to) along the dimension dim, recursively constructs
00197   //the two halves, and adds their parent node.  TODO: a cache-friendlier layout
00198   void build(VIPairList &objCenters, int from, int to, const VolumeList &objBoxes, int dim)
00199   {
00200     eigen_assert(to - from > 1);
00201     if(to - from == 2) {
00202       boxes.push_back(objBoxes[objCenters[from].second].merged(objBoxes[objCenters[from + 1].second]));
00203       children.push_back(from + (int)objects.size() - 1); //there are objects.size() - 1 tree nodes
00204       children.push_back(from + (int)objects.size());
00205     }
00206     else if(to - from == 3) {
00207       int mid = from + 2;
00208       std::nth_element(objCenters.begin() + from, objCenters.begin() + mid,
00209                         objCenters.begin() + to, VectorComparator(dim)); //partition
00210       build(objCenters, from, mid, objBoxes, (dim + 1) % Dim);
00211       int idx1 = (int)boxes.size() - 1;
00212       boxes.push_back(boxes[idx1].merged(objBoxes[objCenters[mid].second]));
00213       children.push_back(idx1);
00214       children.push_back(mid + (int)objects.size() - 1);
00215     }
00216     else {
00217       int mid = from + (to - from) / 2;
00218       nth_element(objCenters.begin() + from, objCenters.begin() + mid,
00219                   objCenters.begin() + to, VectorComparator(dim)); //partition
00220       build(objCenters, from, mid, objBoxes, (dim + 1) % Dim);
00221       int idx1 = (int)boxes.size() - 1;
00222       build(objCenters, mid, to, objBoxes, (dim + 1) % Dim);
00223       int idx2 = (int)boxes.size() - 1;
00224       boxes.push_back(boxes[idx1].merged(boxes[idx2]));
00225       children.push_back(idx1);
00226       children.push_back(idx2);
00227     }
00228   }
00229 
00230   std::vector<int> children; //children of x are children[2x] and children[2x+1], indices bigger than boxes.size() index into objects.
00231   VolumeList boxes;
00232   ObjectList objects;
00233 };
00234 
00235 } // end namespace Eigen
00236 
00237 #endif //KDBVH_H_INCLUDED