Advertisement
Geometrian

Traversal Simplified

Oct 12th, 2017
249
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.77 KB | None | 0 0
  1. void traverse(const Vec8f& query, const BinaryTree& tree, const Result* result) {
  2.     const Node* stack[BIG_ENOUGH];
  3.     stack[0] = tree.root;
  4.     int stack_ptr = 0;
  5.  
  6.     do {
  7.         //Try to convince the compiler to load 64-byte node.
  8.         Node node = stack[stack_ptr];
  9.  
  10.         if (node.type.is_interior) {
  11.             //We can compute our child pointers (simple unpacking operations).
  12.             const Node* child0 = node.calculate_child0();
  13.             const Node* child1 = node.calculate_child1();
  14.  
  15.             //Calculate whether we need to traverse our children.  Functions are math-heavy.  Note:
  16.             //  they do not depend on dereferencing `child0` or `child1`.
  17.             Temp temp;
  18.             calculate_should_traverse0(node,query,result,&temp);
  19.             calculate_should_traverse1(node,query,result,&temp);
  20.  
  21.             //"Recurse".  The tests involve very simple logic.
  22.             if        (should_traverse_0_only(result,temp)) {
  23.                 //Replace the current node on the stack with child 0 and loop (tail recursion)
  24.                 stack[stack_ptr] = child0;
  25.                 continue;
  26.             } else if (should_traverse_1_only(result,temp)) {
  27.                 //Replace the current node on the stack with child 1 and loop (tail recursion)
  28.                 stack[stack_ptr] = child1;
  29.                 continue;
  30.             } else if (should_traverse_0_and_1(result,temp)) {
  31.                 if (should_traverse_0_first(result,temp)) {
  32.                     //Push child 1 onto the stack and recurse with child 0
  33.                     stack[stack_ptr++] = child1;
  34.                     stack[stack_ptr  ] = child0;
  35.                 } else {
  36.                     //Push child 0 onto the stack and recurse with child 1
  37.                     stack[stack_ptr++] = child0;
  38.                     stack[stack_ptr  ] = child1;
  39.                 }
  40.                 continue;
  41.             } else {
  42.                 //We don't need to traverse either node.  Fall out, decrementing `stack_ptr`.
  43.             }
  44.         } else { //is leaf
  45.             calculate_math_and_memory_intensive_functions(node,result);
  46.         }
  47.         --stack_ptr;
  48.     } while(stack_ptr>0)
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement