00001
00002 #include "KDTree.h"
00003 #include "Node.h"
00004 #include "Primitive.h"
00005
00006
00009 KDTree::~KDTree()
00010 {
00011 delete mRootNode;
00012 }
00013
00014
00021 bool KDTree::intersect(Ray & ray) const
00022 {
00023
00024 std::pair<float, float> tmm = mBoundingBox.intersect(ray);
00025
00026
00027 if (tmm.first >= INFINITY - EPSILON)
00028 return false;
00029
00030
00031
00032
00033
00034 return intersect(mRootNode, ray, tmm.first, tmm.second);
00035 }
00036
00037
00046 bool KDTree::intersect( const Node * node,
00047 Ray & ray,
00048 float min,
00049 float max ) const
00050 {
00051
00052 if (!node)
00053 return false;
00054
00055
00056 if (node->isLeafNode())
00057 {
00058 return node->leafIntersect(ray, min, max);
00059 }
00060
00061
00062 Node * near = NULL;
00063 Node * far = NULL;
00064 node->nearFar(ray, near, far);
00065
00066
00067 float dist = node->distanceToSplitPlane(ray);
00068
00069
00070 if (dist <= 0 || dist > max)
00071 {
00072 return intersect(near, ray, min, max);
00073 }
00074
00075 else if (dist <= min)
00076 {
00077 return intersect(far, ray, min, max);
00078 }
00079
00080 else
00081 {
00082
00083 if (intersect(near, ray, min, dist))
00084 return true;
00085
00086
00087 return intersect(far, ray, dist, max);
00088 }
00089 }
00090
00091
00097 void KDTree::buildTree( const PrimitiveList & list,
00098 const Box & bbox )
00099 {
00100
00101 delete mRootNode;
00102
00103 LOG("Started building kd-tree");
00104
00105
00106 mRootNode = new Node(list);
00107
00108
00109 mBoundingBox = bbox;
00110 }
00111
00112
00122 bool KDTree::terminate( const Node * current,
00123 float ,
00124 unsigned int depth ) const
00125 {
00126 return (current->primitives_count() <= mMinPrimitives || depth >= mMaxDepth);
00127 }
00128
00129