The spica renderer
kdtree.h
1 #ifndef _SPICA_KDTREE_H_
2 #define _SPICA_KDTREE_H_
3 
4 #include <vector>
5 #include <queue>
6 #include <functional>
7 
8 namespace spica {
9 
10  enum KnnSearchType {
11  EPSILON_BALL = 0x01,
12  K_NEAREST = 0x02
13  };
14 
15  struct KnnQuery {
16  KnnSearchType type;
17  double epsilon;
18  int k;
19  KnnQuery(int type_, double epsilon_, int k_)
20  : type(static_cast<KnnSearchType>(type_))
21  , epsilon(epsilon_)
22  , k(k_)
23  {
24  }
25  };
26 
27  template <class Ty>
28  class KdTree {
29  public:
30  KdTree();
31  KdTree(const KdTree<Ty>& kdtree);
32  ~KdTree();
33 
34  KdTree& operator=(const KdTree<Ty>& kdtree);
35 
36  void add(const Ty& point);
37  void construct(const std::vector<Ty>& points);
38  void knnSearch(const Ty& point, const KnnQuery& query, std::vector<Ty>* results) const;
39 
40  void release();
41 
42  private:
43  // Private internal classes
44  struct OrderedType {
45  double dist;
46  Ty t;
47  OrderedType(const double dist_, const Ty& t_)
48  : dist(dist_)
49  , t(t_)
50  {
51  }
52 
53  bool operator<(const OrderedType& t) const {
54  return this->dist < t.dist;
55  }
56  bool operator>(const OrderedType& t) const {
57  return this->dist > t.dist;
58  }
59  };
60 
61  typedef std::priority_queue<OrderedType, std::vector<OrderedType>, std::less<OrderedType> > PriorityQueue;
62 
63  struct KdTreeNode {
64  Ty point;
65  KdTreeNode* left;
66  KdTreeNode* right;
67  int axis;
68 
69  KdTreeNode()
70  : point()
71  , left(NULL)
72  , right(NULL)
73  , axis(0)
74  {
75  }
76  };
77 
78  struct AxisComparator {
79  int dim;
80  explicit AxisComparator(int d) : dim(d) {}
81  bool operator()(const Ty* t1, const Ty* t2) {
82  return (*t1)[dim] < (*t2)[dim];
83  }
84  };
85 
86  // Private methods
87  KdTreeNode* constructRec(std::vector<const Ty*>& points, const int nodeID, const int startID, const int endID, const int dim);
88  KdTreeNode* addRec(KdTreeNode* node, const Ty& point, int dim);
89  void knnSearchRec(KdTreeNode* node, const Ty& point, KnnQuery& query, PriorityQueue* results) const;
90 
91  static double distance(const Ty& p1, const Ty& p2);
92 
93  // Private fields
94  KdTreeNode* _nodes;
95  int* _numCopies;
96  };
97 }
98 
99 #include "kdtree_detail.h"
100 
101 #endif // _SPICA_KDTREE_H_
Definition: kdtree.h:28
Definition: kdtree.h:15