30472beb3e638ff04eb6222f865ca7eeda9a0d31
[blender.git] / source / blender / blenlib / intern / BLI_kdopbvh.c
1 /**
2  *
3  * ***** BEGIN GPL LICENSE BLOCK *****
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software Foundation,
17  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18  *
19  * The Original Code is Copyright (C) 2006 by NaN Holding BV.
20  * All rights reserved.
21  *
22  * The Original Code is: all of this file.
23  *
24  * Contributor(s): Daniel Genrich, Andre Pinto
25  *
26  * ***** END GPL LICENSE BLOCK *****
27  */
28
29 #include "math.h"
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <assert.h>
34
35 #include "MEM_guardedalloc.h"
36
37 #include "BKE_utildefines.h"
38
39 #include "BLI_kdopbvh.h"
40 #include "BLI_arithb.h"
41
42 #ifdef _OPENMP
43 #include <omp.h>
44 #endif
45
46
47
48 #define MAX_TREETYPE 32
49 #define DEFAULT_FIND_NEAREST_HEAP_SIZE 1024
50
51 typedef struct BVHNode
52 {
53         struct BVHNode **children;
54         struct BVHNode *parent; // some user defined traversed need that
55         float *bv;              // Bounding volume of all nodes, max 13 axis
56         int index;              // face, edge, vertex index
57         char totnode;   // how many nodes are used, used for speedup
58         char main_axis; // Axis used to split this node
59 } BVHNode;
60
61 struct BVHTree
62 {
63         BVHNode **nodes;
64         BVHNode *nodearray; /* pre-alloc branch nodes */
65         BVHNode **nodechild;    // pre-alloc childs for nodes
66         float   *nodebv;                // pre-alloc bounding-volumes for nodes
67         float   epsilon; /* epslion is used for inflation of the k-dop     */
68         int     totleaf; // leafs
69         int     totbranch;
70         char    tree_type; // type of tree (4 => quadtree)
71         char    axis; // kdop type (6 => OBB, 7 => AABB, ...)
72         char    start_axis, stop_axis; // KDOP_AXES array indices according to axis
73 };
74
75 typedef struct BVHOverlapData 
76 {  
77         BVHTree *tree1, *tree2; 
78         BVHTreeOverlap *overlap; 
79         int i, max_overlap; /* i is number of overlaps */
80         int start_axis, stop_axis;
81 } BVHOverlapData;
82
83 typedef struct BVHNearestData
84 {
85         BVHTree *tree;
86         const float     *co;
87         BVHTree_NearestPointCallback callback;
88         void    *userdata;
89         float proj[13];                 //coordinates projection over axis
90         BVHTreeNearest nearest;
91
92 } BVHNearestData;
93
94 typedef struct BVHRayCastData
95 {
96         BVHTree *tree;
97
98         BVHTree_RayCastCallback callback;
99         void    *userdata;
100
101
102         BVHTreeRay    ray;
103         float ray_dot_axis[13];
104
105         BVHTreeRayHit hit;
106 } BVHRayCastData;
107 ////////////////////////////////////////m
108
109
110 ////////////////////////////////////////////////////////////////////////
111 // Bounding Volume Hierarchy Definition
112 // 
113 // Notes: From OBB until 26-DOP --> all bounding volumes possible, just choose type below
114 // Notes: You have to choose the type at compile time ITM
115 // Notes: You can choose the tree type --> binary, quad, octree, choose below
116 ////////////////////////////////////////////////////////////////////////
117
118 static float KDOP_AXES[13][3] =
119 { {1.0, 0, 0}, {0, 1.0, 0}, {0, 0, 1.0}, {1.0, 1.0, 1.0}, {1.0, -1.0, 1.0}, {1.0, 1.0, -1.0},
120 {1.0, -1.0, -1.0}, {1.0, 1.0, 0}, {1.0, 0, 1.0}, {0, 1.0, 1.0}, {1.0, -1.0, 0}, {1.0, 0, -1.0},
121 {0, 1.0, -1.0}
122 };
123
124 /*
125  * Generic push and pop heap
126  */
127 #define PUSH_HEAP_BODY(HEAP_TYPE,PRIORITY,heap,heap_size)       \
128 {                                                                                                       \
129         HEAP_TYPE element = heap[heap_size-1];                  \
130         int child = heap_size-1;                                                \
131         while(child != 0)                                                               \
132         {                                                                                               \
133                 int parent = (child-1) / 2;                                     \
134                 if(PRIORITY(element, heap[parent]))                     \
135                 {                                                                                       \
136                         heap[child] = heap[parent];                             \
137                         child = parent;                                                 \
138                 }                                                                                       \
139                 else break;                                                                     \
140         }                                                                                               \
141         heap[child] = element;                                                  \
142 }
143
144 #define POP_HEAP_BODY(HEAP_TYPE, PRIORITY,heap,heap_size)       \
145 {                                                                                                       \
146         HEAP_TYPE element = heap[heap_size-1];                  \
147         int parent = 0;                                                                 \
148         while(parent < (heap_size-1)/2 )                                \
149         {                                                                                               \
150                 int child2 = (parent+1)*2;                                      \
151                 if(PRIORITY(heap[child2-1], heap[child2]))      \
152                         --child2;                                                               \
153                                                                                                         \
154                 if(PRIORITY(element, heap[child2]))                     \
155                         break;                                                                  \
156                                                                                                         \
157                 heap[parent] = heap[child2];                            \
158                 parent = child2;                                                        \
159         }                                                                                               \
160         heap[parent] = element;                                                 \
161 }
162
163 int ADJUST_MEMORY(void *local_memblock, void **memblock, int new_size, int *max_size, int size_per_item)
164 {
165         int   new_max_size = *max_size * 2;
166         void *new_memblock = NULL;
167
168         if(new_size <= *max_size)
169                 return TRUE;
170
171         if(*memblock == local_memblock)
172         {
173                 new_memblock = malloc( size_per_item * new_max_size );
174                 memcpy( new_memblock, *memblock, size_per_item * *max_size );
175         }
176         else
177                 new_memblock = realloc(*memblock, size_per_item * new_max_size );
178
179         if(new_memblock)
180         {
181                 *memblock = new_memblock;
182                 *max_size = new_max_size;
183                 return TRUE;
184         }
185         else
186                 return FALSE;
187 }
188
189
190 //////////////////////////////////////////////////////////////////////////////////////////////////////
191 // Introsort 
192 // with permission deriven from the following Java code:
193 // http://ralphunden.net/content/tutorials/a-guide-to-introsort/
194 // and he derived it from the SUN STL 
195 //////////////////////////////////////////////////////////////////////////////////////////////////////
196 static int size_threshold = 16;
197 /*
198 * Common methods for all algorithms
199 */
200 static int floor_lg(int a)
201 {
202         return (int)(floor(log(a)/log(2)));
203 }
204
205 /*
206 * Insertion sort algorithm
207 */
208 static void bvh_insertionsort(BVHNode **a, int lo, int hi, int axis)
209 {
210         int i,j;
211         BVHNode *t;
212         for (i=lo; i < hi; i++)
213         {
214                 j=i;
215                 t = a[i];
216                 while((j!=lo) && (t->bv[axis] < (a[j-1])->bv[axis]))
217                 {
218                         a[j] = a[j-1];
219                         j--;
220                 }
221                 a[j] = t;
222         }
223 }
224
225 static int bvh_partition(BVHNode **a, int lo, int hi, BVHNode * x, int axis)
226 {
227         int i=lo, j=hi;
228         while (1)
229         {
230                 while ((a[i])->bv[axis] < x->bv[axis]) i++;
231                 j--;
232                 while (x->bv[axis] < (a[j])->bv[axis]) j--;
233                 if(!(i < j))
234                         return i;
235                 SWAP( BVHNode* , a[i], a[j]);
236                 i++;
237         }
238 }
239
240 /*
241 * Heapsort algorithm
242 */
243 static void bvh_downheap(BVHNode **a, int i, int n, int lo, int axis)
244 {
245         BVHNode * d = a[lo+i-1];
246         int child;
247         while (i<=n/2)
248         {
249                 child = 2*i;
250                 if ((child < n) && ((a[lo+child-1])->bv[axis] < (a[lo+child])->bv[axis]))
251                 {
252                         child++;
253                 }
254                 if (!(d->bv[axis] < (a[lo+child-1])->bv[axis])) break;
255                 a[lo+i-1] = a[lo+child-1];
256                 i = child;
257         }
258         a[lo+i-1] = d;
259 }
260
261 static void bvh_heapsort(BVHNode **a, int lo, int hi, int axis)
262 {
263         int n = hi-lo, i;
264         for (i=n/2; i>=1; i=i-1)
265         {
266                 bvh_downheap(a, i,n,lo, axis);
267         }
268         for (i=n; i>1; i=i-1)
269         {
270                 SWAP(BVHNode*, a[lo],a[lo+i-1]);
271                 bvh_downheap(a, 1,i-1,lo, axis);
272         }
273 }
274
275 static BVHNode *bvh_medianof3(BVHNode **a, int lo, int mid, int hi, int axis) // returns Sortable
276 {
277         if ((a[mid])->bv[axis] < (a[lo])->bv[axis])
278         {
279                 if ((a[hi])->bv[axis] < (a[mid])->bv[axis])
280                         return a[mid];
281                 else
282                 {
283                         if ((a[hi])->bv[axis] < (a[lo])->bv[axis])
284                                 return a[hi];
285                         else
286                                 return a[lo];
287                 }
288         }
289         else
290         {
291                 if ((a[hi])->bv[axis] < (a[mid])->bv[axis])
292                 {
293                         if ((a[hi])->bv[axis] < (a[lo])->bv[axis])
294                                 return a[lo];
295                         else
296                                 return a[hi];
297                 }
298                 else
299                         return a[mid];
300         }
301 }
302 /*
303 * Quicksort algorithm modified for Introsort
304 */
305 static void bvh_introsort_loop (BVHNode **a, int lo, int hi, int depth_limit, int axis)
306 {
307         int p;
308
309         while (hi-lo > size_threshold)
310         {
311                 if (depth_limit == 0)
312                 {
313                         bvh_heapsort(a, lo, hi, axis);
314                         return;
315                 }
316                 depth_limit=depth_limit-1;
317                 p=bvh_partition(a, lo, hi, bvh_medianof3(a, lo, lo+((hi-lo)/2)+1, hi-1, axis), axis);
318                 bvh_introsort_loop(a, p, hi, depth_limit, axis);
319                 hi=p;
320         }
321 }
322
323 static void sort(BVHNode **a0, int begin, int end, int axis)
324 {
325         if (begin < end)
326         {
327                 BVHNode **a=a0;
328                 bvh_introsort_loop(a, begin, end, 2*floor_lg(end-begin), axis);
329                 bvh_insertionsort(a, begin, end, axis);
330         }
331 }
332 void sort_along_axis(BVHTree *tree, int start, int end, int axis)
333 {
334         sort(tree->nodes, start, end, axis);
335 }
336
337 //after a call to this function you can expect one of:
338 //      every node to left of a[n] are smaller or equal to it
339 //      every node to the right of a[n] are greater or equal to it
340 int partition_nth_element(BVHNode **a, int _begin, int _end, int n, int axis){
341         int begin = _begin, end = _end, cut;
342         while(end-begin > 3)
343         {
344                 cut = bvh_partition(a, begin, end, bvh_medianof3(a, begin, (begin+end)/2, end-1, axis), axis );
345                 if(cut <= n)
346                         begin = cut;
347                 else
348                         end = cut;
349         }
350         bvh_insertionsort(a, begin, end, axis);
351
352         return n;
353 }
354
355 //////////////////////////////////////////////////////////////////////////////////////////////////////
356
357 /*
358  * BVHTree bounding volumes functions
359  */
360 static void create_kdop_hull(BVHTree *tree, BVHNode *node, float *co, int numpoints, int moving)
361 {
362         float newminmax;
363         float *bv = node->bv;
364         int i, k;
365         
366         // don't init boudings for the moving case
367         if(!moving)
368         {
369                 for (i = tree->start_axis; i < tree->stop_axis; i++)
370                 {
371                         bv[2*i] = FLT_MAX;
372                         bv[2*i + 1] = -FLT_MAX;
373                 }
374         }
375         
376         for(k = 0; k < numpoints; k++)
377         {
378                 // for all Axes.
379                 for (i = tree->start_axis; i < tree->stop_axis; i++)
380                 {
381                         newminmax = INPR(&co[k * 3], KDOP_AXES[i]);
382                         if (newminmax < bv[2 * i])
383                                 bv[2 * i] = newminmax;
384                         if (newminmax > bv[(2 * i) + 1])
385                                 bv[(2 * i) + 1] = newminmax;
386                 }
387         }
388 }
389
390 // depends on the fact that the BVH's for each face is already build
391 static void refit_kdop_hull(BVHTree *tree, BVHNode *node, int start, int end)
392 {
393         float newmin,newmax;
394         int i, j;
395         float *bv = node->bv;
396
397         
398         for (i = tree->start_axis; i < tree->stop_axis; i++)
399         {
400                 bv[2*i] = FLT_MAX;
401                 bv[2*i + 1] = -FLT_MAX;
402         }
403
404         for (j = start; j < end; j++)
405         {
406 // for all Axes.
407                 for (i = tree->start_axis; i < tree->stop_axis; i++)
408                 {
409                         newmin = tree->nodes[j]->bv[(2 * i)];   
410                         if ((newmin < bv[(2 * i)]))
411                                 bv[(2 * i)] = newmin;
412  
413                         newmax = tree->nodes[j]->bv[(2 * i) + 1];
414                         if ((newmax > bv[(2 * i) + 1]))
415                                 bv[(2 * i) + 1] = newmax;
416                 }
417         }
418
419 }
420
421 // only supports x,y,z axis in the moment
422 // but we should use a plain and simple function here for speed sake
423 static char get_largest_axis(float *bv)
424 {
425         float middle_point[3];
426
427         middle_point[0] = (bv[1]) - (bv[0]); // x axis
428         middle_point[1] = (bv[3]) - (bv[2]); // y axis
429         middle_point[2] = (bv[5]) - (bv[4]); // z axis
430         if (middle_point[0] > middle_point[1]) 
431         {
432                 if (middle_point[0] > middle_point[2])
433                         return 1; // max x axis
434                 else
435                         return 5; // max z axis
436         }
437         else 
438         {
439                 if (middle_point[1] > middle_point[2])
440                         return 3; // max y axis
441                 else
442                         return 5; // max z axis
443         }
444 }
445
446 // bottom-up update of bvh node BV
447 // join the children on the parent BV
448 static void node_join(BVHTree *tree, BVHNode *node)
449 {
450         int i, j;
451         
452         for (i = tree->start_axis; i < tree->stop_axis; i++)
453         {
454                 node->bv[2*i] = FLT_MAX;
455                 node->bv[2*i + 1] = -FLT_MAX;
456         }
457         
458         for (i = 0; i < tree->tree_type; i++)
459         {
460                 if (node->children[i]) 
461                 {
462                         for (j = tree->start_axis; j < tree->stop_axis; j++)
463                         {
464                                 // update minimum 
465                                 if (node->children[i]->bv[(2 * j)] < node->bv[(2 * j)]) 
466                                         node->bv[(2 * j)] = node->children[i]->bv[(2 * j)];
467                                 
468                                 // update maximum 
469                                 if (node->children[i]->bv[(2 * j) + 1] > node->bv[(2 * j) + 1])
470                                         node->bv[(2 * j) + 1] = node->children[i]->bv[(2 * j) + 1];
471                         }
472                 }
473                 else
474                         break;
475         }
476 }
477
478 /*
479  * Debug and information functions
480  */
481 static void bvhtree_print_tree(BVHTree *tree, BVHNode *node, int depth)
482 {
483         int i;
484         for(i=0; i<depth; i++) printf(" ");
485         printf(" - %d (%ld): ", node->index, node - tree->nodearray);
486         for(i=2*tree->start_axis; i<2*tree->stop_axis; i++)
487                 printf("%.3f ", node->bv[i]);
488         printf("\n");
489
490         for(i=0; i<tree->tree_type; i++)
491                 if(node->children[i])
492                         bvhtree_print_tree(tree, node->children[i], depth+1);
493 }
494
495 static void bvhtree_info(BVHTree *tree)
496 {
497         printf("BVHTree info\n");
498         printf("tree_type = %d, axis = %d, epsilon = %f\n", tree->tree_type, tree->axis, tree->epsilon);
499         printf("nodes = %d, branches = %d, leafs = %d\n", tree->totbranch + tree->totleaf,  tree->totbranch, tree->totleaf);
500         printf("Memory per node = %ldbytes\n", sizeof(BVHNode) + sizeof(BVHNode*)*tree->tree_type + sizeof(float)*tree->axis);
501         printf("BV memory = %dbytes\n", MEM_allocN_len(tree->nodebv));
502
503         printf("Total memory = %ldbytes\n", sizeof(BVHTree)
504                 + MEM_allocN_len(tree->nodes)
505                 + MEM_allocN_len(tree->nodearray)
506                 + MEM_allocN_len(tree->nodechild)
507                 + MEM_allocN_len(tree->nodebv)
508                 );
509
510 //      bvhtree_print_tree(tree, tree->nodes[tree->totleaf], 0);
511 }
512
513 #if 0
514
515
516 static void verify_tree(BVHTree *tree)
517 {
518         int i, j, check = 0;
519         
520         // check the pointer list
521         for(i = 0; i < tree->totleaf; i++)
522         {
523                 if(tree->nodes[i]->parent == NULL)
524                         printf("Leaf has no parent: %d\n", i);
525                 else
526                 {
527                         for(j = 0; j < tree->tree_type; j++)
528                         {
529                                 if(tree->nodes[i]->parent->children[j] == tree->nodes[i])
530                                         check = 1;
531                         }
532                         if(!check)
533                         {
534                                 printf("Parent child relationship doesn't match: %d\n", i);
535                         }
536                         check = 0;
537                 }
538         }
539         
540         // check the leaf list
541         for(i = 0; i < tree->totleaf; i++)
542         {
543                 if(tree->nodearray[i].parent == NULL)
544                         printf("Leaf has no parent: %d\n", i);
545                 else
546                 {
547                         for(j = 0; j < tree->tree_type; j++)
548                         {
549                                 if(tree->nodearray[i].parent->children[j] == &tree->nodearray[i])
550                                         check = 1;
551                         }
552                         if(!check)
553                         {
554                                 printf("Parent child relationship doesn't match: %d\n", i);
555                         }
556                         check = 0;
557                 }
558         }
559         
560         printf("branches: %d, leafs: %d, total: %d\n", tree->totbranch, tree->totleaf, tree->totbranch + tree->totleaf);
561 }
562 #endif
563
564 //Helper data and structures to build a min-leaf generalized implicit tree
565 //This code can be easily reduced (basicly this is only method to calculate pow(k, n) in O(1).. and stuff like that)
566 typedef struct BVHBuildHelper
567 {
568         int tree_type;                          //
569         int totleafs;                           //
570
571         int leafs_per_child  [32];      //Min number of leafs that are archievable from a node at depth N
572         int branches_on_level[32];      //Number of nodes at depth N (tree_type^N)
573
574         int remain_leafs;                       //Number of leafs that are placed on the level that is not 100% filled
575
576 } BVHBuildHelper;
577
578 static void build_implicit_tree_helper(BVHTree *tree, BVHBuildHelper *data)
579 {
580         int depth = 0;
581         int remain;
582         int nnodes;
583
584         data->totleafs = tree->totleaf;
585         data->tree_type= tree->tree_type;
586
587         //Calculate the smallest tree_type^n such that tree_type^n >= num_leafs
588         for(
589                 data->leafs_per_child[0] = 1;
590                 data->leafs_per_child[0] <  data->totleafs;
591                 data->leafs_per_child[0] *= data->tree_type
592         );
593
594         data->branches_on_level[0] = 1;
595
596         //We could stop the loop first (but I am lazy to find out when)
597         for(depth = 1; depth < 32; depth++)
598         {
599                 data->branches_on_level[depth] = data->branches_on_level[depth-1] * data->tree_type;
600                 data->leafs_per_child  [depth] = data->leafs_per_child  [depth-1] / data->tree_type;
601         }
602
603         remain = data->totleafs - data->leafs_per_child[1];
604         nnodes = (remain + data->tree_type - 2) / (data->tree_type - 1);
605         data->remain_leafs = remain + nnodes;
606 }
607
608 // return the min index of all the leafs archivable with the given branch
609 static int implicit_leafs_index(BVHBuildHelper *data, int depth, int child_index)
610 {
611         int min_leaf_index = child_index * data->leafs_per_child[depth-1];
612         if(min_leaf_index <= data->remain_leafs)
613                 return min_leaf_index;
614         else if(data->leafs_per_child[depth])
615                 return data->totleafs - (data->branches_on_level[depth-1] - child_index) * data->leafs_per_child[depth];
616         else
617                 return data->remain_leafs;
618 }
619
620 /**
621  * Generalized implicit tree build
622  *
623  * An implicit tree is a tree where its structure is implied, thus there is no need to store child pointers or indexs.
624  * Its possible to find the position of the child or the parent with simple maths (multiplication and adittion). This type
625  * of tree is for example used on heaps.. where node N has its childs at indexs N*2 and N*2+1.
626  *
627  * Altought in this case the tree type is general.. and not know until runtime.
628  * tree_type stands for the maximum number of childs that a tree node can have.
629  * All tree types >= 2 are supported.
630  *
631  * Advantages of the used trees include:
632  *  - No need to store child/parent relations (they are implicit);
633  *  - Any node child always has an index greater than the parent;
634  *  - Brother nodes are sequencial in memory;
635  *
636  *
637  * Some math relations derived for general implicit trees:
638  *
639  *   K = tree_type, ( 2 <= K )
640  *   ROOT = 1
641  *   N child of node A = A * K + (2 - K) + N, (0 <= N < K)
642  *
643  * Util methods:
644  *   TODO...
645  *    (looping elements, knowing if its a leaf or not.. etc...)
646  */
647
648 // This functions returns the number of branches needed to have the requested number of leafs.
649 static int implicit_needed_branches(int tree_type, int leafs)
650 {
651         return MAX2(1, (leafs + tree_type - 3) / (tree_type-1) );
652 }
653
654 /*
655  * This function handles the problem of "sorting" the leafs (along the split_axis).
656  *
657  * It arranges the elements in the given partitions such that:
658  *  - any element in partition N is less or equal to any element in partition N+1.
659  *  - if all elements are diferent all partition will get the same subset of elements
660  *    as if the array was sorted.
661  *
662  * partition P is described as the elements in the range ( nth[P] , nth[P+1] ]
663  *
664  * TODO: This can be optimized a bit by doing a specialized nth_element instead of K nth_elements
665  */
666 static void split_leafs(BVHNode **leafs_array, int *nth, int partitions, int split_axis)
667 {
668         int i;
669         for(i=0; i < partitions-1; i++)
670         {
671                 if(nth[i] >= nth[partitions])
672                         break;
673
674                 partition_nth_element(leafs_array, nth[i], nth[partitions], nth[i+1], split_axis);
675         }
676 }
677
678 /*
679  * This functions builds an optimal implicit tree from the given leafs.
680  * Where optimal stands for:
681  *  - The resulting tree will have the smallest number of branches;
682  *  - At most only one branch will have NULL childs;
683  *  - All leafs will be stored at level N or N+1.
684  *
685  * This function creates an implicit tree on branches_array, the leafs are given on the leafs_array.
686  *
687  * The tree is built per depth levels. First branchs at depth 1.. then branches at depth 2.. etc..
688  * The reason is that we can build level N+1 from level N witouth any data dependencies.. thus it allows
689  * to use multithread building.
690  *
691  * To archieve this is necessary to find how much leafs are accessible from a certain branch, BVHBuildHelper
692  * implicit_needed_branches and implicit_leafs_index are auxiliar functions to solve that "optimal-split".
693  */
694 static void non_recursive_bvh_div_nodes(BVHTree *tree, BVHNode *branches_array, BVHNode **leafs_array, int num_leafs)
695 {
696         int i;
697
698         const int tree_type   = tree->tree_type;
699         const int tree_offset = 2 - tree->tree_type; //this value is 0 (on binary trees) and negative on the others
700         const int num_branches= implicit_needed_branches(tree_type, num_leafs);
701
702         BVHBuildHelper data;
703         int depth;
704         
705         // set parent from root node to NULL
706         BVHNode *tmp = branches_array+0;
707         tmp->parent = NULL;
708
709         //Most of bvhtree code relies on 1-leaf trees having at least one branch
710         //We handle that special case here
711         if(num_leafs == 1)
712         {
713                 BVHNode *root = branches_array+0;
714                 refit_kdop_hull(tree, root, 0, num_leafs);
715                 root->main_axis = get_largest_axis(root->bv) / 2;
716                 root->totnode = 1;
717                 root->children[0] = leafs_array[0];
718                 root->children[0]->parent = root;
719                 return;
720         }
721
722         branches_array--;       //Implicit trees use 1-based indexs
723         
724         build_implicit_tree_helper(tree, &data);
725
726         //Loop tree levels (log N) loops
727         for(i=1, depth = 1; i <= num_branches; i = i*tree_type + tree_offset, depth++)
728         {
729                 const int first_of_next_level = i*tree_type + tree_offset;
730                 const int  end_j = MIN2(first_of_next_level, num_branches + 1); //index of last branch on this level
731                 int j;
732
733                 //Loop all branches on this level
734 #pragma omp parallel for private(j) schedule(static)
735                 for(j = i; j < end_j; j++)
736                 {
737                         int k;
738                         const int parent_level_index= j-i;
739                         BVHNode* parent = branches_array + j;
740                         int nth_positions[ MAX_TREETYPE + 1];
741                         char split_axis;
742
743                         int parent_leafs_begin = implicit_leafs_index(&data, depth, parent_level_index);
744                         int parent_leafs_end   = implicit_leafs_index(&data, depth, parent_level_index+1);
745
746                         //This calculates the bounding box of this branch
747                         //and chooses the largest axis as the axis to divide leafs
748                         refit_kdop_hull(tree, parent, parent_leafs_begin, parent_leafs_end);
749                         split_axis = get_largest_axis(parent->bv);
750
751                         //Save split axis (this can be used on raytracing to speedup the query time)
752                         parent->main_axis = split_axis / 2;
753
754                         //Split the childs along the split_axis, note: its not needed to sort the whole leafs array
755                         //Only to assure that the elements are partioned on a way that each child takes the elements
756                         //it would take in case the whole array was sorted.
757                         //Split_leafs takes care of that "sort" problem.
758                         nth_positions[        0] = parent_leafs_begin;
759                         nth_positions[tree_type] = parent_leafs_end;
760                         for(k = 1; k < tree_type; k++)
761                         {
762                                 int child_index = j * tree_type + tree_offset + k;
763                                 int child_level_index = child_index - first_of_next_level; //child level index
764                                 nth_positions[k] = implicit_leafs_index(&data, depth+1, child_level_index);
765                         }
766
767                         split_leafs(leafs_array, nth_positions, tree_type, split_axis);
768
769
770                         //Setup children and totnode counters
771                         //Not really needed but currently most of BVH code relies on having an explicit children structure
772                         for(k = 0; k < tree_type; k++)
773                         {
774                                 int child_index = j * tree_type + tree_offset + k;
775                                 int child_level_index = child_index - first_of_next_level; //child level index
776
777                                 int child_leafs_begin = implicit_leafs_index(&data, depth+1, child_level_index);
778                                 int child_leafs_end   = implicit_leafs_index(&data, depth+1, child_level_index+1);
779
780                                 if(child_leafs_end - child_leafs_begin > 1)
781                                 {
782                                         parent->children[k] = branches_array + child_index;
783                                         parent->children[k]->parent = parent;
784                                 }
785                                 else if(child_leafs_end - child_leafs_begin == 1)
786                                 {
787                                         parent->children[k] = leafs_array[ child_leafs_begin ];
788                                         parent->children[k]->parent = parent;
789                                 }
790                                 else
791                                         break;
792
793                                 parent->totnode = k+1;
794                         }
795                 }
796         }
797 }
798
799
800 /*
801  * BLI_bvhtree api
802  */
803 BVHTree *BLI_bvhtree_new(int maxsize, float epsilon, char tree_type, char axis)
804 {
805         BVHTree *tree;
806         int numnodes, i;
807         
808         // theres not support for trees below binary-trees :P
809         if(tree_type < 2)
810                 return NULL;
811         
812         if(tree_type > MAX_TREETYPE)
813                 return NULL;
814
815         tree = (BVHTree *)MEM_callocN(sizeof(BVHTree), "BVHTree");
816
817         //tree epsilon must be >= FLT_EPSILON
818         //so that tangent rays can still hit a bounding volume..
819         //this bug would show up when casting a ray aligned with a kdop-axis and with an edge of 2 faces
820         epsilon = MAX2(FLT_EPSILON, epsilon);
821         
822         if(tree)
823         {
824                 tree->epsilon = epsilon;
825                 tree->tree_type = tree_type; 
826                 tree->axis = axis;
827                 
828                 if(axis == 26)
829                 {
830                         tree->start_axis = 0;
831                         tree->stop_axis = 13;
832                 }
833                 else if(axis == 18)
834                 {
835                         tree->start_axis = 7;
836                         tree->stop_axis = 13;
837                 }
838                 else if(axis == 14)
839                 {
840                         tree->start_axis = 0;
841                         tree->stop_axis = 7;
842                 }
843                 else if(axis == 8) // AABB
844                 {
845                         tree->start_axis = 0;
846                         tree->stop_axis = 4;
847                 }
848                 else if(axis == 6) // OBB
849                 {
850                         tree->start_axis = 0;
851                         tree->stop_axis = 3;
852                 }
853                 else
854                 {
855                         MEM_freeN(tree);
856                         return NULL;
857                 }
858
859
860                 //Allocate arrays
861                 numnodes = maxsize + implicit_needed_branches(tree_type, maxsize) + tree_type;
862
863                 tree->nodes = (BVHNode **)MEM_callocN(sizeof(BVHNode *)*numnodes, "BVHNodes");
864                 
865                 if(!tree->nodes)
866                 {
867                         MEM_freeN(tree);
868                         return NULL;
869                 }
870                 
871                 tree->nodebv = (float*)MEM_callocN(sizeof(float)* axis * numnodes, "BVHNodeBV");
872                 if(!tree->nodebv)
873                 {
874                         MEM_freeN(tree->nodes);
875                         MEM_freeN(tree);
876                 }
877
878                 tree->nodechild = (BVHNode**)MEM_callocN(sizeof(BVHNode*) * tree_type * numnodes, "BVHNodeBV");
879                 if(!tree->nodechild)
880                 {
881                         MEM_freeN(tree->nodebv);
882                         MEM_freeN(tree->nodes);
883                         MEM_freeN(tree);
884                 }
885
886                 tree->nodearray = (BVHNode *)MEM_callocN(sizeof(BVHNode)* numnodes, "BVHNodeArray");
887                 
888                 if(!tree->nodearray)
889                 {
890                         MEM_freeN(tree->nodechild);
891                         MEM_freeN(tree->nodebv);
892                         MEM_freeN(tree->nodes);
893                         MEM_freeN(tree);
894                         return NULL;
895                 }
896
897                 //link the dynamic bv and child links
898                 for(i=0; i< numnodes; i++)
899                 {
900                         tree->nodearray[i].bv = tree->nodebv + i * axis;
901                         tree->nodearray[i].children = tree->nodechild + i * tree_type;
902                 }
903                 
904         }
905
906         return tree;
907 }
908
909 void BLI_bvhtree_free(BVHTree *tree)
910 {       
911         if(tree)
912         {
913                 MEM_freeN(tree->nodes);
914                 MEM_freeN(tree->nodearray);
915                 MEM_freeN(tree->nodebv);
916                 MEM_freeN(tree->nodechild);
917                 MEM_freeN(tree);
918         }
919 }
920
921 void BLI_bvhtree_balance(BVHTree *tree)
922 {
923         int i;
924
925         BVHNode*  branches_array = tree->nodearray + tree->totleaf;
926         BVHNode** leafs_array    = tree->nodes;
927
928         //This function should only be called once (some big bug goes here if its being called more than once per tree)
929         assert(tree->totbranch == 0);
930
931         //Build the implicit tree
932         non_recursive_bvh_div_nodes(tree, branches_array, leafs_array, tree->totleaf);
933
934         //current code expects the branches to be linked to the nodes array
935         //we perform that linkage here
936         tree->totbranch = implicit_needed_branches(tree->tree_type, tree->totleaf);
937         for(i = 0; i < tree->totbranch; i++)
938                 tree->nodes[tree->totleaf + i] = branches_array + i;
939
940         //bvhtree_info(tree);
941 }
942
943 int BLI_bvhtree_insert(BVHTree *tree, int index, float *co, int numpoints)
944 {
945         int i;
946         BVHNode *node = NULL;
947         
948         // insert should only possible as long as tree->totbranch is 0
949         if(tree->totbranch > 0)
950                 return 0;
951         
952         if(tree->totleaf+1 >= MEM_allocN_len(tree->nodes)/sizeof(*(tree->nodes)))
953                 return 0;
954         
955         // TODO check if have enough nodes in array
956         
957         node = tree->nodes[tree->totleaf] = &(tree->nodearray[tree->totleaf]);
958         tree->totleaf++;
959         
960         create_kdop_hull(tree, node, co, numpoints, 0);
961         node->index= index;
962         
963         // inflate the bv with some epsilon
964         for (i = tree->start_axis; i < tree->stop_axis; i++)
965         {
966                 node->bv[(2 * i)] -= tree->epsilon; // minimum 
967                 node->bv[(2 * i) + 1] += tree->epsilon; // maximum 
968         }
969
970         return 1;
971 }
972
973
974 // call before BLI_bvhtree_update_tree()
975 int BLI_bvhtree_update_node(BVHTree *tree, int index, float *co, float *co_moving, int numpoints)
976 {
977         int i;
978         BVHNode *node= NULL;
979         
980         // check if index exists
981         if(index > tree->totleaf)
982                 return 0;
983         
984         node = tree->nodearray + index;
985         
986         create_kdop_hull(tree, node, co, numpoints, 0);
987         
988         if(co_moving)
989                 create_kdop_hull(tree, node, co_moving, numpoints, 1);
990         
991         // inflate the bv with some epsilon
992         for (i = tree->start_axis; i < tree->stop_axis; i++)
993         {
994                 node->bv[(2 * i)] -= tree->epsilon; // minimum 
995                 node->bv[(2 * i) + 1] += tree->epsilon; // maximum 
996         }
997
998         return 1;
999 }
1000
1001 // call BLI_bvhtree_update_node() first for every node/point/triangle
1002 void BLI_bvhtree_update_tree(BVHTree *tree)
1003 {
1004         //Update bottom=>top
1005         //TRICKY: the way we build the tree all the childs have an index greater than the parent
1006         //This allows us todo a bottom up update by starting on the biger numbered branch
1007
1008         BVHNode** root  = tree->nodes + tree->totleaf;
1009         BVHNode** index = tree->nodes + tree->totleaf + tree->totbranch-1;
1010
1011         for (; index >= root; index--)
1012                 node_join(tree, *index);
1013 }
1014
1015 float BLI_bvhtree_getepsilon(BVHTree *tree)
1016 {
1017         return tree->epsilon;
1018 }
1019
1020
1021 /*
1022  * BLI_bvhtree_overlap
1023  */
1024 // overlap - is it possbile for 2 bv's to collide ?
1025 static int tree_overlap(BVHNode *node1, BVHNode *node2, int start_axis, int stop_axis)
1026 {
1027         float *bv1 = node1->bv;
1028         float *bv2 = node2->bv;
1029
1030         float *bv1_end = bv1 + (stop_axis<<1);
1031                 
1032         bv1 += start_axis<<1;
1033         bv2 += start_axis<<1;
1034         
1035         // test all axis if min + max overlap
1036         for (; bv1 != bv1_end; bv1+=2, bv2+=2)
1037         {
1038                 if ((*(bv1) > *(bv2 + 1)) || (*(bv2) > *(bv1 + 1))) 
1039                         return 0;
1040         }
1041         
1042         return 1;
1043 }
1044
1045 static void traverse(BVHOverlapData *data, BVHNode *node1, BVHNode *node2)
1046 {
1047         int j;
1048         
1049         if(tree_overlap(node1, node2, data->start_axis, data->stop_axis))
1050         {
1051                 // check if node1 is a leaf
1052                 if(!node1->totnode)
1053                 {
1054                         // check if node2 is a leaf
1055                         if(!node2->totnode)
1056                         {
1057                                 
1058                                 if(node1 == node2)
1059                                 {
1060                                         return;
1061                                 }
1062                                         
1063                                 if(data->i >= data->max_overlap)
1064                                 {       
1065                                         // try to make alloc'ed memory bigger
1066                                         data->overlap = realloc(data->overlap, sizeof(BVHTreeOverlap)*data->max_overlap*2);
1067                                         
1068                                         if(!data->overlap)
1069                                         {
1070                                                 printf("Out of Memory in traverse\n");
1071                                                 return;
1072                                         }
1073                                         data->max_overlap *= 2;
1074                                 }
1075                                 
1076                                 // both leafs, insert overlap!
1077                                 data->overlap[data->i].indexA = node1->index;
1078                                 data->overlap[data->i].indexB = node2->index;
1079
1080                                 data->i++;
1081                         }
1082                         else
1083                         {
1084                                 for(j = 0; j < data->tree2->tree_type; j++)
1085                                 {
1086                                         if(node2->children[j])
1087                                                 traverse(data, node1, node2->children[j]);
1088                                 }
1089                         }
1090                 }
1091                 else
1092                 {
1093                         
1094                         for(j = 0; j < data->tree2->tree_type; j++)
1095                         {
1096                                 if(node1->children[j])
1097                                         traverse(data, node1->children[j], node2);
1098                         }
1099                 }
1100         }
1101         return;
1102 }
1103
1104 BVHTreeOverlap *BLI_bvhtree_overlap(BVHTree *tree1, BVHTree *tree2, int *result)
1105 {
1106         int j, total = 0;
1107         BVHTreeOverlap *overlap = NULL, *to = NULL;
1108         BVHOverlapData **data;
1109         
1110         // check for compatibility of both trees (can't compare 14-DOP with 18-DOP)
1111         if((tree1->axis != tree2->axis) && (tree1->axis == 14 || tree2->axis == 14) && (tree1->axis == 18 || tree2->axis == 18))
1112                 return 0;
1113         
1114         // fast check root nodes for collision before doing big splitting + traversal
1115         if(!tree_overlap(tree1->nodes[tree1->totleaf], tree2->nodes[tree2->totleaf], MIN2(tree1->start_axis, tree2->start_axis), MIN2(tree1->stop_axis, tree2->stop_axis)))
1116                 return 0;
1117
1118         data = MEM_callocN(sizeof(BVHOverlapData *)* tree1->tree_type, "BVHOverlapData_star");
1119         
1120         for(j = 0; j < tree1->tree_type; j++)
1121         {
1122                 data[j] = (BVHOverlapData *)MEM_callocN(sizeof(BVHOverlapData), "BVHOverlapData");
1123                 
1124                 // init BVHOverlapData
1125                 data[j]->overlap = (BVHTreeOverlap *)malloc(sizeof(BVHTreeOverlap)*MAX2(tree1->totleaf, tree2->totleaf));
1126                 data[j]->tree1 = tree1;
1127                 data[j]->tree2 = tree2;
1128                 data[j]->max_overlap = MAX2(tree1->totleaf, tree2->totleaf);
1129                 data[j]->i = 0;
1130                 data[j]->start_axis = MIN2(tree1->start_axis, tree2->start_axis);
1131                 data[j]->stop_axis  = MIN2(tree1->stop_axis,  tree2->stop_axis );
1132         }
1133
1134 #pragma omp parallel for private(j) schedule(static)
1135         for(j = 0; j < MIN2(tree1->tree_type, tree1->nodes[tree1->totleaf]->totnode); j++)
1136         {
1137                 traverse(data[j], tree1->nodes[tree1->totleaf]->children[j], tree2->nodes[tree2->totleaf]);
1138         }
1139         
1140         for(j = 0; j < tree1->tree_type; j++)
1141                 total += data[j]->i;
1142         
1143         to = overlap = (BVHTreeOverlap *)MEM_callocN(sizeof(BVHTreeOverlap)*total, "BVHTreeOverlap");
1144         
1145         for(j = 0; j < tree1->tree_type; j++)
1146         {
1147                 memcpy(to, data[j]->overlap, data[j]->i*sizeof(BVHTreeOverlap));
1148                 to+=data[j]->i;
1149         }
1150         
1151         for(j = 0; j < tree1->tree_type; j++)
1152         {
1153                 free(data[j]->overlap);
1154                 MEM_freeN(data[j]);
1155         }
1156         MEM_freeN(data);
1157         
1158         (*result) = total;
1159         return overlap;
1160 }
1161
1162
1163 /*
1164  * Nearest neighbour - BLI_bvhtree_find_nearest
1165  */
1166 static float squared_dist(const float *a, const float *b)
1167 {
1168         float tmp[3];
1169         VECSUB(tmp, a, b);
1170         return INPR(tmp, tmp);
1171 }
1172
1173 //Determines the nearest point of the given node BV. Returns the squared distance to that point.
1174 static float calc_nearest_point(BVHNearestData *data, BVHNode *node, float *nearest)
1175 {
1176         int i;
1177         const float *bv = node->bv;
1178
1179         //nearest on AABB hull
1180         for(i=0; i != 3; i++, bv += 2)
1181         {
1182                 if(bv[0] > data->proj[i])
1183                         nearest[i] = bv[0];
1184                 else if(bv[1] < data->proj[i])
1185                         nearest[i] = bv[1];
1186                 else
1187                         nearest[i] = data->proj[i];
1188         }
1189
1190 /*
1191         //nearest on a general hull
1192         VECCOPY(nearest, data->co);
1193         for(i = data->tree->start_axis; i != data->tree->stop_axis; i++, bv+=2)
1194         {
1195                 float proj = INPR( nearest, KDOP_AXES[i]);
1196                 float dl = bv[0] - proj;
1197                 float du = bv[1] - proj;
1198
1199                 if(dl > 0)
1200                 {
1201                         VECADDFAC(nearest, nearest, KDOP_AXES[i], dl);
1202                 }
1203                 else if(du < 0)
1204                 {
1205                         VECADDFAC(nearest, nearest, KDOP_AXES[i], du);
1206                 }
1207         }
1208 */
1209         return squared_dist(data->co, nearest);
1210 }
1211
1212
1213 typedef struct NodeDistance
1214 {
1215         BVHNode *node;
1216         float dist;
1217
1218 } NodeDistance;
1219
1220 #define NodeDistance_priority(a,b)      ( (a).dist < (b).dist )
1221
1222 // TODO: use a priority queue to reduce the number of nodes looked on
1223 static void dfs_find_nearest_dfs(BVHNearestData *data, BVHNode *node)
1224 {
1225         if(node->totnode == 0)
1226         {
1227                 if(data->callback)
1228                         data->callback(data->userdata , node->index, data->co, &data->nearest);
1229                 else
1230                 {
1231                         data->nearest.index     = node->index;
1232                         data->nearest.dist      = calc_nearest_point(data, node, data->nearest.co);
1233                 }
1234         }
1235         else
1236         {
1237                 //Better heuristic to pick the closest node to dive on
1238                 int i;
1239                 float nearest[3];
1240
1241                 if(data->proj[ node->main_axis ] <= node->children[0]->bv[node->main_axis*2+1])
1242                 {
1243
1244                         for(i=0; i != node->totnode; i++)
1245                         {
1246                                 if( calc_nearest_point(data, node->children[i], nearest) >= data->nearest.dist) continue;
1247                                 dfs_find_nearest_dfs(data, node->children[i]);
1248                         }
1249                 }
1250                 else
1251                 {
1252                         for(i=node->totnode-1; i >= 0 ; i--)
1253                         {
1254                                 if( calc_nearest_point(data, node->children[i], nearest) >= data->nearest.dist) continue;
1255                                 dfs_find_nearest_dfs(data, node->children[i]);
1256                         }
1257                 }
1258         }
1259 }
1260
1261 static void dfs_find_nearest_begin(BVHNearestData *data, BVHNode *node)
1262 {
1263         float nearest[3], sdist;
1264         sdist = calc_nearest_point(data, node, nearest);
1265         if(sdist >= data->nearest.dist) return;
1266         dfs_find_nearest_dfs(data, node);
1267 }
1268
1269
1270 static void NodeDistance_push_heap(NodeDistance *heap, int heap_size)
1271 PUSH_HEAP_BODY(NodeDistance, NodeDistance_priority, heap, heap_size)
1272
1273 static void NodeDistance_pop_heap(NodeDistance *heap, int heap_size)
1274 POP_HEAP_BODY(NodeDistance, NodeDistance_priority, heap, heap_size)
1275
1276 //NN function that uses an heap.. this functions leads to an optimal number of min-distance
1277 //but for normal tri-faces and BV 6-dop.. a simple dfs with local heuristics (as implemented
1278 //in source/blender/blenkernel/intern/shrinkwrap.c) works faster.
1279 //
1280 //It may make sense to use this function if the callback queries are very slow.. or if its impossible
1281 //to get a nice heuristic
1282 //
1283 //this function uses "malloc/free" instead of the MEM_* because it intends to be openmp safe
1284 static void bfs_find_nearest(BVHNearestData *data, BVHNode *node)
1285 {
1286         int i;
1287         NodeDistance default_heap[DEFAULT_FIND_NEAREST_HEAP_SIZE];
1288         NodeDistance *heap=default_heap, current;
1289         int heap_size = 0, max_heap_size = sizeof(default_heap)/sizeof(default_heap[0]);
1290         float nearest[3];
1291
1292         int callbacks = 0, push_heaps = 0;
1293
1294         if(node->totnode == 0)
1295         {
1296                 dfs_find_nearest_dfs(data, node);
1297                 return;
1298         }
1299
1300         current.node = node;
1301         current.dist = calc_nearest_point(data, node, nearest);
1302
1303         while(current.dist < data->nearest.dist)
1304         {
1305 //              printf("%f : %f\n", current.dist, data->nearest.dist);
1306                 for(i=0; i< current.node->totnode; i++)
1307                 {
1308                         BVHNode *child = current.node->children[i];
1309                         if(child->totnode == 0)
1310                         {
1311                                 callbacks++;
1312                                 dfs_find_nearest_dfs(data, child);
1313                         }
1314                         else
1315                         {
1316                                 //adjust heap size
1317                                 if(heap_size >= max_heap_size
1318                                 && ADJUST_MEMORY(default_heap, (void**)&heap, heap_size+1, &max_heap_size, sizeof(heap[0])) == FALSE)
1319                                 {
1320                                         printf("WARNING: bvh_find_nearest got out of memory\n");
1321
1322                                         if(heap != default_heap)
1323                                                 free(heap);
1324
1325                                         return;
1326                                 }
1327
1328                                 heap[heap_size].node = current.node->children[i];
1329                                 heap[heap_size].dist = calc_nearest_point(data, current.node->children[i], nearest);
1330
1331                                 if(heap[heap_size].dist >= data->nearest.dist) continue;
1332                                 heap_size++;
1333
1334                                 NodeDistance_push_heap(heap, heap_size);
1335         //                      PUSH_HEAP_BODY(NodeDistance, NodeDistance_priority, heap, heap_size);
1336                                 push_heaps++;
1337                         }
1338                 }
1339                 
1340                 if(heap_size == 0) break;
1341
1342                 current = heap[0];
1343                 NodeDistance_pop_heap(heap, heap_size);
1344 //              POP_HEAP_BODY(NodeDistance, NodeDistance_priority, heap, heap_size);
1345                 heap_size--;
1346         }
1347
1348 //      printf("hsize=%d, callbacks=%d, pushs=%d\n", heap_size, callbacks, push_heaps);
1349
1350         if(heap != default_heap)
1351                 free(heap);
1352 }
1353
1354
1355 int BLI_bvhtree_find_nearest(BVHTree *tree, const float *co, BVHTreeNearest *nearest, BVHTree_NearestPointCallback callback, void *userdata)
1356 {
1357         int i;
1358
1359         BVHNearestData data;
1360         BVHNode* root = tree->nodes[tree->totleaf];
1361
1362         //init data to search
1363         data.tree = tree;
1364         data.co = co;
1365
1366         data.callback = callback;
1367         data.userdata = userdata;
1368
1369         for(i = data.tree->start_axis; i != data.tree->stop_axis; i++)
1370         {
1371                 data.proj[i] = INPR(data.co, KDOP_AXES[i]);
1372         }
1373
1374         if(nearest)
1375         {
1376                 memcpy( &data.nearest , nearest, sizeof(*nearest) );
1377         }
1378         else
1379         {
1380                 data.nearest.index = -1;
1381                 data.nearest.dist = FLT_MAX;
1382         }
1383
1384         //dfs search
1385         if(root)
1386                 dfs_find_nearest_begin(&data, root);
1387
1388         //copy back results
1389         if(nearest)
1390         {
1391                 memcpy(nearest, &data.nearest, sizeof(*nearest));
1392         }
1393
1394         return data.nearest.index;
1395 }
1396
1397
1398 /*
1399  * Raycast - BLI_bvhtree_ray_cast
1400  *
1401  * raycast is done by performing a DFS on the BVHTree and saving the closest hit
1402  */
1403
1404 //Determines the distance that the ray must travel to hit the bounding volume of the given node
1405 static float ray_nearest_hit(BVHRayCastData *data, BVHNode *node)
1406 {
1407         int i;
1408         const float *bv = node->bv;
1409
1410         float low = 0, upper = data->hit.dist;
1411
1412         for(i=0; i != 3; i++, bv += 2)
1413         {
1414                 if(data->ray_dot_axis[i] == 0.0f)
1415                 {
1416                         //axis aligned ray
1417                         if(data->ray.origin[i] < bv[0] - data->ray.radius
1418                         || data->ray.origin[i] > bv[1] + data->ray.radius)
1419                                 return FLT_MAX;
1420                 }
1421                 else
1422                 {
1423                         float ll = (bv[0] - data->ray.radius - data->ray.origin[i]) / data->ray_dot_axis[i];
1424                         float lu = (bv[1] + data->ray.radius - data->ray.origin[i]) / data->ray_dot_axis[i];
1425
1426                         if(data->ray_dot_axis[i] > 0.0f)
1427                         {
1428                                 if(ll > low)   low = ll;
1429                                 if(lu < upper) upper = lu;
1430                         }
1431                         else
1432                         {
1433                                 if(lu > low)   low = lu;
1434                                 if(ll < upper) upper = ll;
1435                         }
1436         
1437                         if(low > upper) return FLT_MAX;
1438                 }
1439         }
1440         return low;
1441 }
1442
1443 static void dfs_raycast(BVHRayCastData *data, BVHNode *node)
1444 {
1445         int i;
1446
1447         //ray-bv is really fast.. and simple tests revealed its worth to test it
1448         //before calling the ray-primitive functions
1449         float dist = ray_nearest_hit(data, node);
1450         if(dist >= data->hit.dist) return;
1451
1452         if(node->totnode == 0)
1453         {
1454                 if(data->callback)
1455                         data->callback(data->userdata, node->index, &data->ray, &data->hit);
1456                 else
1457                 {
1458                         data->hit.index = node->index;
1459                         data->hit.dist  = dist;
1460                         VECADDFAC(data->hit.co, data->ray.origin, data->ray.direction, dist);
1461                 }
1462         }
1463         else
1464         {
1465                 //pick loop direction to dive into the tree (based on ray direction and split axis)
1466                 if(data->ray_dot_axis[ node->main_axis ] > 0.0f)
1467                 {
1468                         for(i=0; i != node->totnode; i++)
1469                         {
1470                                 dfs_raycast(data, node->children[i]);
1471                         }
1472                 }
1473                 else
1474                 {
1475                         for(i=node->totnode-1; i >= 0; i--)
1476                         {
1477                                 dfs_raycast(data, node->children[i]);
1478                         }
1479                 }
1480         }
1481 }
1482
1483 int BLI_bvhtree_ray_cast(BVHTree *tree, const float *co, const float *dir, float radius, BVHTreeRayHit *hit, BVHTree_RayCastCallback callback, void *userdata)
1484 {
1485         int i;
1486         BVHRayCastData data;
1487         BVHNode * root = tree->nodes[tree->totleaf];
1488
1489         data.tree = tree;
1490
1491         data.callback = callback;
1492         data.userdata = userdata;
1493
1494         VECCOPY(data.ray.origin,    co);
1495         VECCOPY(data.ray.direction, dir);
1496         data.ray.radius = radius;
1497
1498         Normalize(data.ray.direction);
1499
1500         for(i=0; i<3; i++)
1501         {
1502                 data.ray_dot_axis[i] = INPR( data.ray.direction, KDOP_AXES[i]);
1503
1504                 if(fabs(data.ray_dot_axis[i]) < FLT_EPSILON)
1505                         data.ray_dot_axis[i] = 0.0;
1506         }
1507
1508
1509         if(hit)
1510                 memcpy( &data.hit, hit, sizeof(*hit) );
1511         else
1512         {
1513                 data.hit.index = -1;
1514                 data.hit.dist = FLT_MAX;
1515         }
1516
1517         if(root)
1518                 dfs_raycast(&data, root);
1519
1520
1521         if(hit)
1522                 memcpy( hit, &data.hit, sizeof(*hit) );
1523
1524         return data.hit.index;
1525 }
1526