For efficient 3D object selection in my OpenGL world, I decided to implement a version of Kd-tree that meets my requirements.
Selection was more than 10 times faster than before (brute force). Specially when the number of selectable 3D objects increased 😉
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 |
//kdtree.h #pragma once #include <set> #include <map> #include <string> #include <sstream> #include <vector> #include <memory> #include <glm\glm.hpp> #include <scene\Object.h> #include "Ray.h" class World3d; class KdTree { public: enum KdAxis { X_Axis = 0, Y_Axis = 1, Z_Axis = 2, None = 3 }; struct KdTreeBoundingBox { public: KdTreeBoundingBox() { bottomLeft.x = std::numeric_limits<float>::infinity(); bottomLeft.y = std::numeric_limits<float>::infinity(); bottomLeft.z = std::numeric_limits<float>::infinity(); topRight.x = -std::numeric_limits<float>::infinity(); topRight.y = -std::numeric_limits<float>::infinity(); topRight.z = -std::numeric_limits<float>::infinity(); } ~KdTreeBoundingBox() { } glm::vec3 topRight; glm::vec3 bottomLeft; bool intersects(Ray& ray); }; struct KdTreeNode { public: KdTreeNode() : leftChild(nullptr), rightChild(nullptr) { objects = nullptr; boundingBox = nullptr; } ~KdTreeNode() { delete leftChild; leftChild = nullptr; delete rightChild; rightChild = nullptr; delete boundingBox; boundingBox = nullptr; } KdTreeBoundingBox* boundingBox; bool isLeaf; KdAxis splitAxis; float splitPlane; // the coordinate value of the axis (x, y or z) std::set<Object*>* objects; KdTreeNode* leftChild; // always elements < (less) KdTreeNode* rightChild; // always elements >= (greater or equal) bool intersects(Ray& ray); }; public: KdTree(); ~KdTree(); std::set<Object*>* getIntersectableObjects(Ray& ray); // returns the leaf node's 3d objects that are intersection candidates void build(std::set<Object*>* objects); std::set<KdTreeNode*>* getLeafNodes(); private: std::set<Object*>* getIntersectableObjects(Ray& ray, KdTreeNode* kdNode, int recursionDepth); void build(std::set<Object*>* objects, KdTreeNode* kdNode); void getMedian(std::set<Object*>* objects, KdAxis axis, glm::vec3& out); KdAxis getNextSplitAxis(KdTreeNode* kdNode); KdTreeBoundingBox* calculateBoundingBox(std::set<Object*>* objects); float splitObjects(std::set<Object*>* objects, glm::vec3* median, KdAxis axis, std::set<Object*>* smallerObjects, std::set<Object*>* greaterObjects); private: KdTreeNode* m_Root; std::set<Object*>* m_Objects; const unsigned int m_MaxLeafObjects; std::set<KdTreeNode*> m_LeafNodes; int m_Height; // TBD }; // kdtree.cpp #include "KdTree.h" #include <scene\BoundingBox.h> #include <fibonacciheap\FibonacciHeap.h> #include <utils\DebugHelper.h> #include <scene\Object.h> #include "Ray.h" #include <limits> #include <cassert> #include <string> #include <sstream> #include <algorithm> bool KdTree::KdTreeBoundingBox::intersects(Ray& ray) { glm::vec3 dirfrac; // r.dir is unit direction vector of ray dirfrac.x = 1.0f / ray.getDirection().x; dirfrac.y = 1.0f / ray.getDirection().y; dirfrac.z = 1.0f / ray.getDirection().z; // lb is the corner of AABB with minimal coordinates - left bottom, rt is maximal corner // r.org is origin of ray float t1 = (this->bottomLeft.x - ray.getOrigin().x) * dirfrac.x; float t2 = (this->topRight.x - ray.getOrigin().x) * dirfrac.x; float t3 = (this->bottomLeft.y - ray.getOrigin().y) * dirfrac.y; float t4 = (this->topRight.y - ray.getOrigin().y) * dirfrac.y; float t5 = (this->bottomLeft.z - ray.getOrigin().z) * dirfrac.z; float t6 = (this->topRight.z - ray.getOrigin().z) * dirfrac.z; float tmin = std::max(std::max(std::min(t1, t2), std::min(t3, t4)), std::min(t5, t6)); float tmax = std::min(std::min(std::max(t1, t2), std::max(t3, t4)), std::max(t5, t6)); float t = 0; // if tmax < 0, ray (line) is intersecting AABB, but whole AABB is behing us if (tmax < 0) { t = tmax; return false; } // if tmin > tmax, ray doesn't intersect AABB if (tmin > tmax) { t = tmax; return false; } t = tmin; return true; } bool KdTree::KdTreeNode::intersects(Ray& ray) { return this->boundingBox->intersects(ray); } KdTree::KdTree() : m_MaxLeafObjects(100), m_Root(new KdTreeNode) { m_Root->splitAxis = KdAxis::Z_Axis; m_Root->isLeaf = false; m_Root->splitPlane = 0; m_Objects = nullptr; } KdTree::~KdTree() { for (auto obj : this->m_LeafNodes){ delete obj; obj = nullptr; } this->m_LeafNodes.clear(); delete m_Root; // this should initiate a recursive deletion on right and left child... m_Root = nullptr; } std::set<Object*>* KdTree::getIntersectableObjects(Ray& ray) { return this->getIntersectableObjects(ray, this->m_Root, 0); } void KdTree::build(std::set<Object*>* objects) { this->m_Objects = objects; KdTreeBoundingBox* bb = this->calculateBoundingBox(objects); m_Root->boundingBox = bb; m_Root->objects = objects; this->build(objects, this->m_Root); } std::set<KdTree::KdTreeNode*>* KdTree::getLeafNodes() { return &this->m_LeafNodes; } // this method will be called recursively on the left and right child of the node to build the tree void KdTree::build(std::set<Object*>* objects, KdTreeNode* kdNode) { // first check if the number of Object is smaller or equal than the maximum number of Object per leaf // if yes, then stop here and add the Object to the leaf node. if (objects->size() <= m_MaxLeafObjects) { // don't need to create another leaf node - it has already been created in the last recursive step (see below) KdTreeBoundingBox* bb = this->calculateBoundingBox(objects); kdNode->boundingBox = bb; kdNode->isLeaf = true; kdNode->splitAxis = KdAxis::None; kdNode->objects = objects; m_LeafNodes.insert(kdNode); } else { // then split the Object and recursively build the tree // get the bounding box for the Object KdTreeBoundingBox* bb = this->calculateBoundingBox(objects); kdNode->boundingBox = bb; kdNode->isLeaf = false; kdNode->objects = objects; KdAxis axis = getNextSplitAxis(kdNode); // get next split axis with respect to the parent node // get the median glm::vec3 median; this->getMedian(objects, axis, median); // split the Object and add them to the left and right child node (and those which bounding box lies in both parts). std::set<Object*>* smallerObjects = new std::set<Object*>(); std::set<Object*>* greaterObjects = new std::set<Object*>(); float splitPlane = this->splitObjects(objects, &median, axis, smallerObjects, greaterObjects);// , sharedObject); if (smallerObjects->size() > 0) { KdTreeNode* leftChildNode(new KdTreeNode); leftChildNode->splitAxis = axis; leftChildNode->splitPlane = splitPlane; kdNode->leftChild = leftChildNode; // recursion this->build(smallerObjects, leftChildNode); } if (greaterObjects->size() > 0) { KdTreeNode* rightChildNode(new KdTreeNode); rightChildNode->splitAxis = axis; rightChildNode->splitPlane = splitPlane; kdNode->rightChild = rightChildNode; // recursion this->build(greaterObjects, rightChildNode); } } } std::set<Object*>* KdTree::getIntersectableObjects(Ray& ray, KdTreeNode* kdNode, int recursionDepth) { std::stringstream blanks; for (int i = 0; i < recursionDepth; i++) blanks << " "; bool intersects = kdNode->intersects(ray); std::set<Object*>* resultSetLeft = nullptr; std::set<Object*>* resultSetRight = nullptr; std::set<Object*>* resultSetCombined = new std::set<Object*>(); if (intersects && !kdNode->isLeaf) { if (kdNode->leftChild != nullptr) { resultSetLeft = this->getIntersectableObjects(ray, kdNode->leftChild, recursionDepth + 1); } if (kdNode->rightChild != nullptr) { resultSetRight = this->getIntersectableObjects(ray, kdNode->rightChild, recursionDepth + 1); } if (resultSetLeft != nullptr && !resultSetLeft->empty()) std::copy(resultSetLeft->begin(), resultSetLeft->end(), std::inserter(*resultSetCombined, resultSetCombined->end())); if (resultSetRight != nullptr && !resultSetRight->empty()) std::copy(resultSetRight->begin(), resultSetRight->end(), std::inserter(*resultSetCombined, resultSetCombined->end())); // ok, the data is copied. And resultSetLeft is now the resultSetCombined from the last recursion step which can now be deleted. if (resultSetLeft != nullptr) { resultSetLeft->clear(); delete resultSetLeft; resultSetLeft = nullptr; } // the same applies for resultSetRight if (resultSetRight != nullptr) { resultSetRight->clear(); delete resultSetRight; resultSetRight = nullptr; } return resultSetCombined; } else if (intersects && kdNode->isLeaf) { if (kdNode->objects != nullptr && !kdNode->objects->empty()) std::copy(kdNode->objects->begin(), kdNode->objects->end(), std::inserter(*resultSetCombined, resultSetCombined->end())); return resultSetCombined; } return nullptr; } void KdTree::getMedian(std::set<Object*>* objects, KdAxis axis, glm::vec3& out) { Fibonacci::FibonacciHeap<Object> heap; // first build up the heap for sorting double key; for (Object* object : *objects) { if (axis == KdAxis::X_Axis) { key = object->getCenter().x; } else if (axis == KdAxis::Y_Axis) { key = object->getCenter().y; } else if (axis == KdAxis::Z_Axis) { key = object->getCenter().z; } heap.insert(new Fibonacci::Node<Object>(key, object)); } int pivot = static_cast<int>(objects->size() / 2.0f); // now extract the pivot element Object* median = nullptr; for (int i = 0; i < pivot; i++) { median = heap.extractMin()->getValue(); } if (median != nullptr) { out.x = median->getCenter().x; out.y = median->getCenter().y; out.z = median->getCenter().z; } else { out.x = 0; out.y = 0; out.z = 0; } } KdTree::KdAxis KdTree::getNextSplitAxis(KdTreeNode* kdNode) { if (kdNode->splitAxis == KdTree::KdAxis::X_Axis) return KdTree::KdAxis::Y_Axis; else if (kdNode->splitAxis == KdTree::KdAxis::Y_Axis) return KdTree::KdAxis::Z_Axis; else if (kdNode->splitAxis == KdTree::KdAxis::Z_Axis) return KdTree::KdAxis::X_Axis; return KdTree::KdAxis::None; } KdTree::KdTreeBoundingBox* KdTree::calculateBoundingBox(std::set<Object*>* objects) { KdTreeBoundingBox* kdbb(new KdTreeBoundingBox); float minX, minY, minZ, maxX, maxY, maxZ; minX = minY = minZ = std::numeric_limits<float>::infinity(); maxX = maxY = maxZ = -std::numeric_limits<float>::infinity(); for (Object* object : *objects) { BoundingBox* bb = object->getBoundingBox(); if (bb->getBottomLeft().x < minX) minX = bb->getBottomLeft().x; if (bb->getBottomLeft().y < minY) minY = bb->getBottomLeft().y; if (bb->getBottomLeft().z < minZ) minZ = bb->getBottomLeft().z; if (bb->getTopRight().x >= maxX) maxX = bb->getTopRight().x; if (bb->getTopRight().y >= maxY) maxY = bb->getTopRight().y; if (bb->getTopRight().z >= maxZ) maxZ = bb->getTopRight().z; } kdbb->bottomLeft.x = minX; kdbb->bottomLeft.y = minY; kdbb->bottomLeft.z = minZ; kdbb->topRight.x = maxX; kdbb->topRight.y = maxY; kdbb->topRight.z = maxZ; return kdbb; } float KdTree::splitObjects(std::set<Object*>* objects, glm::vec3* median, KdTree::KdAxis axis, std::set<Object*>* smallerObjects, std::set<Object*>* greaterObjects) { assert(axis != KdAxis::None); assert(greaterObjects != nullptr); assert(smallerObjects != nullptr); greaterObjects->clear(); smallerObjects->clear(); float splitPlane; // ITS FATAL TO JUDGE ON THE CENTER OF THE LINE, BECAUSE THEN INTERSECTION TEST WOULD FAIL FOR THIS BOUNDING BOX. // INSTEAD THE INTERSECTION ALGO WOULD THINK THE OBJECT BELONGS TO ANOTHER BBOX --> INTERSECTION IN THIS BBOX WOULD RESULT IN <EMPTY> // THEREFORE BOTH MIN X,Y,Z AND MAX X,Y,Z MUST BE USED FOR SPLITTING // IF ONE OBJECT IS NOT CLEARLY ON ONE SIDE --> SPLIT THE OBJECT... if (axis == KdAxis::X_Axis) { for (Object* object : *objects) { // first handle smaller values if (object->getBoundingBox()->getBottomLeft().x < median->x && object->getBoundingBox()->getTopRight().x < median->x) smallerObjects->insert(object); // then handle greater or equal Object else if (object->getBoundingBox()->getBottomLeft().x >= median->x && object->getBoundingBox()->getTopRight().x >= median->x) greaterObjects->insert(object); else { // add it to both sets since it is straddling the splitting axis greaterObjects->insert(object); smallerObjects->insert(object); } } splitPlane = median->x; } else if (axis == KdAxis::Y_Axis) { for (Object* object : *objects) { // first handle smaller values if (object->getBoundingBox()->getBottomLeft().y < median->y && object->getBoundingBox()->getTopRight().y < median->y) smallerObjects->insert(object); // then handle greater or equal Object else if (object->getBoundingBox()->getBottomLeft().y >= median->y && object->getBoundingBox()->getTopRight().y >= median->y) greaterObjects->insert(object); else { // add it to both sets since it is straddling the splitting axis smallerObjects->insert(object); greaterObjects->insert(object); } } splitPlane = median->y; } else if (axis == KdAxis::Z_Axis) { for (Object* object : *objects) { // first handle smaller values if (object->getBoundingBox()->getBottomLeft().z < median->z && object->getBoundingBox()->getTopRight().z < median->z) smallerObjects->insert(object); // then handle greater or equal Object else if (object->getBoundingBox()->getBottomLeft().z >= median->z && object->getBoundingBox()->getTopRight().z >= median->z) greaterObjects->insert(object); else { // add it to both sets since it is straddling the splitting axis greaterObjects->insert(object); smallerObjects->insert(object); } } splitPlane = median->z; } return splitPlane; } |