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