Cleanup: edbm_do_smooth_laplacian_vertex_exec
[blender.git] / source / blender / blenkernel / intern / pbvh.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * ***** END GPL LICENSE BLOCK *****
19  */
20
21 /** \file blender/blenkernel/intern/pbvh.c
22  *  \ingroup bli
23  */
24
25 #include "DNA_meshdata_types.h"
26
27 #include "MEM_guardedalloc.h"
28
29 #include "BLI_bitmap.h"
30 #include "BLI_math.h"
31 #include "BLI_utildefines.h"
32 #include "BLI_ghash.h"
33 #include "BLI_task.h"
34
35 #include "BKE_pbvh.h"
36 #include "BKE_ccg.h"
37 #include "BKE_subsurf.h"
38 #include "BKE_DerivedMesh.h"
39 #include "BKE_global.h"
40 #include "BKE_mesh.h" /* for BKE_mesh_calc_normals */
41 #include "BKE_paint.h"
42
43 #include "GPU_buffers.h"
44 #include "GPU_immediate.h"
45
46 #include "bmesh.h"
47
48 #include "atomic_ops.h"
49
50 #include "pbvh_intern.h"
51
52 #include <limits.h>
53
54 #define LEAF_LIMIT 10000
55
56 //#define PERFCNTRS
57
58 #define STACK_FIXED_DEPTH   100
59
60 #define PBVH_THREADED_LIMIT 4
61
62 typedef struct PBVHStack {
63         PBVHNode *node;
64         bool revisiting;
65 } PBVHStack;
66
67 typedef struct PBVHIter {
68         PBVH *bvh;
69         BKE_pbvh_SearchCallback scb;
70         void *search_data;
71
72         PBVHStack *stack;
73         int stacksize;
74
75         PBVHStack stackfixed[STACK_FIXED_DEPTH];
76         int stackspace;
77 } PBVHIter;
78
79 void BB_reset(BB *bb)
80 {
81         bb->bmin[0] = bb->bmin[1] = bb->bmin[2] = FLT_MAX;
82         bb->bmax[0] = bb->bmax[1] = bb->bmax[2] = -FLT_MAX;
83 }
84
85 /* Expand the bounding box to include a new coordinate */
86 void BB_expand(BB *bb, const float co[3])
87 {
88         for (int i = 0; i < 3; ++i) {
89                 bb->bmin[i] = min_ff(bb->bmin[i], co[i]);
90                 bb->bmax[i] = max_ff(bb->bmax[i], co[i]);
91         }
92 }
93
94 /* Expand the bounding box to include another bounding box */
95 void BB_expand_with_bb(BB *bb, BB *bb2)
96 {
97         for (int i = 0; i < 3; ++i) {
98                 bb->bmin[i] = min_ff(bb->bmin[i], bb2->bmin[i]);
99                 bb->bmax[i] = max_ff(bb->bmax[i], bb2->bmax[i]);
100         }
101 }
102
103 /* Return 0, 1, or 2 to indicate the widest axis of the bounding box */
104 int BB_widest_axis(const BB *bb)
105 {
106         float dim[3];
107
108         for (int i = 0; i < 3; ++i)
109                 dim[i] = bb->bmax[i] - bb->bmin[i];
110
111         if (dim[0] > dim[1]) {
112                 if (dim[0] > dim[2])
113                         return 0;
114                 else
115                         return 2;
116         }
117         else {
118                 if (dim[1] > dim[2])
119                         return 1;
120                 else
121                         return 2;
122         }
123 }
124
125 void BBC_update_centroid(BBC *bbc)
126 {
127         for (int i = 0; i < 3; ++i)
128                 bbc->bcentroid[i] = (bbc->bmin[i] + bbc->bmax[i]) * 0.5f;
129 }
130
131 /* Not recursive */
132 static void update_node_vb(PBVH *bvh, PBVHNode *node)
133 {
134         BB vb;
135
136         BB_reset(&vb);
137
138         if (node->flag & PBVH_Leaf) {
139                 PBVHVertexIter vd;
140
141                 BKE_pbvh_vertex_iter_begin(bvh, node, vd, PBVH_ITER_ALL)
142                 {
143                         BB_expand(&vb, vd.co);
144                 }
145                 BKE_pbvh_vertex_iter_end;
146         }
147         else {
148                 BB_expand_with_bb(&vb,
149                                   &bvh->nodes[node->children_offset].vb);
150                 BB_expand_with_bb(&vb,
151                                   &bvh->nodes[node->children_offset + 1].vb);
152         }
153
154         node->vb = vb;
155 }
156
157 //void BKE_pbvh_node_BB_reset(PBVHNode *node)
158 //{
159 //      BB_reset(&node->vb);
160 //}
161 //
162 //void BKE_pbvh_node_BB_expand(PBVHNode *node, float co[3])
163 //{
164 //      BB_expand(&node->vb, co);
165 //}
166
167 static bool face_materials_match(const MPoly *f1, const MPoly *f2)
168 {
169         return ((f1->flag & ME_SMOOTH) == (f2->flag & ME_SMOOTH) &&
170                 (f1->mat_nr == f2->mat_nr));
171 }
172
173 static bool grid_materials_match(const DMFlagMat *f1, const DMFlagMat *f2)
174 {
175         return ((f1->flag & ME_SMOOTH) == (f2->flag & ME_SMOOTH) &&
176                 (f1->mat_nr == f2->mat_nr));
177 }
178
179 /* Adapted from BLI_kdopbvh.c */
180 /* Returns the index of the first element on the right of the partition */
181 static int partition_indices(int *prim_indices, int lo, int hi, int axis,
182                              float mid, BBC *prim_bbc)
183 {
184         int i = lo, j = hi;
185         for (;; ) {
186                 for (; prim_bbc[prim_indices[i]].bcentroid[axis] < mid; i++) ;
187                 for (; mid < prim_bbc[prim_indices[j]].bcentroid[axis]; j--) ;
188
189                 if (!(i < j))
190                         return i;
191
192                 SWAP(int, prim_indices[i], prim_indices[j]);
193                 i++;
194         }
195 }
196
197 /* Returns the index of the first element on the right of the partition */
198 static int partition_indices_material(PBVH *bvh, int lo, int hi)
199 {
200         const MPoly *mpoly = bvh->mpoly;
201         const MLoopTri *looptri = bvh->looptri;
202         const DMFlagMat *flagmats = bvh->grid_flag_mats;
203         const int *indices = bvh->prim_indices;
204         const void *first;
205         int i = lo, j = hi;
206
207         if (bvh->looptri)
208                 first = &mpoly[looptri[bvh->prim_indices[lo]].poly];
209         else
210                 first = &flagmats[bvh->prim_indices[lo]];
211
212         for (;; ) {
213                 if (bvh->looptri) {
214                         for (; face_materials_match(first, &mpoly[looptri[indices[i]].poly]); i++) ;
215                         for (; !face_materials_match(first, &mpoly[looptri[indices[j]].poly]); j--) ;
216                 }
217                 else {
218                         for (; grid_materials_match(first, &flagmats[indices[i]]); i++) ;
219                         for (; !grid_materials_match(first, &flagmats[indices[j]]); j--) ;
220                 }
221
222                 if (!(i < j))
223                         return i;
224
225                 SWAP(int, bvh->prim_indices[i], bvh->prim_indices[j]);
226                 i++;
227         }
228 }
229
230 void pbvh_grow_nodes(PBVH *bvh, int totnode)
231 {
232         if (UNLIKELY(totnode > bvh->node_mem_count)) {
233                 bvh->node_mem_count = bvh->node_mem_count + (bvh->node_mem_count / 3);
234                 if (bvh->node_mem_count < totnode)
235                         bvh->node_mem_count = totnode;
236                 bvh->nodes = MEM_recallocN(bvh->nodes, sizeof(PBVHNode) * bvh->node_mem_count);
237         }
238
239         bvh->totnode = totnode;
240 }
241
242 /* Add a vertex to the map, with a positive value for unique vertices and
243  * a negative value for additional vertices */
244 static int map_insert_vert(PBVH *bvh, GHash *map,
245                            unsigned int *face_verts,
246                            unsigned int *uniq_verts, int vertex)
247 {
248         void *key, **value_p;
249
250         key = SET_INT_IN_POINTER(vertex);
251         if (!BLI_ghash_ensure_p(map, key, &value_p)) {
252                 int value_i;
253                 if (BLI_BITMAP_TEST(bvh->vert_bitmap, vertex) == 0) {
254                         BLI_BITMAP_ENABLE(bvh->vert_bitmap, vertex);
255                         value_i = *uniq_verts;
256                         (*uniq_verts)++;
257                 }
258                 else {
259                         value_i = ~(*face_verts);
260                         (*face_verts)++;
261                 }
262                 *value_p = SET_INT_IN_POINTER(value_i);
263                 return value_i;
264         }
265         else {
266                 return GET_INT_FROM_POINTER(*value_p);
267         }
268 }
269
270 /* Find vertices used by the faces in this node and update the draw buffers */
271 static void build_mesh_leaf_node(PBVH *bvh, PBVHNode *node)
272 {
273         bool has_visible = false;
274
275         node->uniq_verts = node->face_verts = 0;
276         const int totface = node->totprim;
277
278         /* reserve size is rough guess */
279         GHash *map = BLI_ghash_int_new_ex("build_mesh_leaf_node gh", 2 * totface);
280
281         int (*face_vert_indices)[3] = MEM_mallocN(sizeof(int[3]) * totface,
282                                                   "bvh node face vert indices");
283
284         node->face_vert_indices = (const int (*)[3])face_vert_indices;
285
286         for (int i = 0; i < totface; ++i) {
287                 const MLoopTri *lt = &bvh->looptri[node->prim_indices[i]];
288                 for (int j = 0; j < 3; ++j) {
289                         face_vert_indices[i][j] =
290                                 map_insert_vert(bvh, map, &node->face_verts,
291                                                 &node->uniq_verts, bvh->mloop[lt->tri[j]].v);
292                 }
293
294                 if (!paint_is_face_hidden(lt, bvh->verts, bvh->mloop)) {
295                         has_visible = true;
296                 }
297         }
298
299         int *vert_indices = MEM_callocN(sizeof(int) * (node->uniq_verts + node->face_verts),
300                                         "bvh node vert indices");
301         node->vert_indices = vert_indices;
302
303         /* Build the vertex list, unique verts first */
304         GHashIterator gh_iter;
305         GHASH_ITER (gh_iter, map) {
306                 void *value = BLI_ghashIterator_getValue(&gh_iter);
307                 int ndx = GET_INT_FROM_POINTER(value);
308
309                 if (ndx < 0)
310                         ndx = -ndx + node->uniq_verts - 1;
311
312                 vert_indices[ndx] =
313                         GET_INT_FROM_POINTER(BLI_ghashIterator_getKey(&gh_iter));
314         }
315
316         for (int i = 0; i < totface; ++i) {
317                 const int sides = 3;
318
319                 for (int j = 0; j < sides; ++j) {
320                         if (face_vert_indices[i][j] < 0)
321                                 face_vert_indices[i][j] =
322                                         -face_vert_indices[i][j] +
323                                         node->uniq_verts - 1;
324                 }
325         }
326
327         BKE_pbvh_node_mark_rebuild_draw(node);
328
329         BKE_pbvh_node_fully_hidden_set(node, !has_visible);
330
331         BLI_ghash_free(map, NULL, NULL);
332 }
333
334 static void update_vb(PBVH *bvh, PBVHNode *node, BBC *prim_bbc,
335                       int offset, int count)
336 {
337         BB_reset(&node->vb);
338         for (int i = offset + count - 1; i >= offset; --i) {
339                 BB_expand_with_bb(&node->vb, (BB *)(&prim_bbc[bvh->prim_indices[i]]));
340         }
341         node->orig_vb = node->vb;
342 }
343
344 /* Returns the number of visible quads in the nodes' grids. */
345 int BKE_pbvh_count_grid_quads(BLI_bitmap **grid_hidden,
346                               int *grid_indices, int totgrid,
347                               int gridsize)
348 {
349         const int gridarea = (gridsize - 1) * (gridsize - 1);
350         int totquad = 0;
351
352         /* grid hidden layer is present, so have to check each grid for
353          * visibility */
354
355         for (int i = 0; i < totgrid; i++) {
356                 const BLI_bitmap *gh = grid_hidden[grid_indices[i]];
357
358                 if (gh) {
359                         /* grid hidden are present, have to check each element */
360                         for (int y = 0; y < gridsize - 1; y++) {
361                                 for (int x = 0; x < gridsize - 1; x++) {
362                                         if (!paint_is_grid_face_hidden(gh, gridsize, x, y))
363                                                 totquad++;
364                                 }
365                         }
366                 }
367                 else
368                         totquad += gridarea;
369         }
370
371         return totquad;
372 }
373
374 static void build_grid_leaf_node(PBVH *bvh, PBVHNode *node)
375 {
376         int totquads = BKE_pbvh_count_grid_quads(bvh->grid_hidden, node->prim_indices,
377                                                  node->totprim, bvh->gridkey.grid_size);
378         BKE_pbvh_node_fully_hidden_set(node, (totquads == 0));
379         BKE_pbvh_node_mark_rebuild_draw(node);
380 }
381
382
383 static void build_leaf(PBVH *bvh, int node_index, BBC *prim_bbc,
384                        int offset, int count)
385 {
386         bvh->nodes[node_index].flag |= PBVH_Leaf;
387
388         bvh->nodes[node_index].prim_indices = bvh->prim_indices + offset;
389         bvh->nodes[node_index].totprim = count;
390
391         /* Still need vb for searches */
392         update_vb(bvh, &bvh->nodes[node_index], prim_bbc, offset, count);
393
394         if (bvh->looptri)
395                 build_mesh_leaf_node(bvh, bvh->nodes + node_index);
396         else {
397                 build_grid_leaf_node(bvh, bvh->nodes + node_index);
398         }
399 }
400
401 /* Return zero if all primitives in the node can be drawn with the
402  * same material (including flat/smooth shading), non-zero otherwise */
403 static bool leaf_needs_material_split(PBVH *bvh, int offset, int count)
404 {
405         if (count <= 1)
406                 return false;
407
408         if (bvh->looptri) {
409                 const MLoopTri *first = &bvh->looptri[bvh->prim_indices[offset]];
410                 const MPoly *mp = &bvh->mpoly[first->poly];
411
412                 for (int i = offset + count - 1; i > offset; --i) {
413                         int prim = bvh->prim_indices[i];
414                         const MPoly *mp_other = &bvh->mpoly[bvh->looptri[prim].poly];
415                         if (!face_materials_match(mp, mp_other)) {
416                                 return true;
417                         }
418                 }
419         }
420         else {
421                 const DMFlagMat *first = &bvh->grid_flag_mats[bvh->prim_indices[offset]];
422
423                 for (int i = offset + count - 1; i > offset; --i) {
424                         int prim = bvh->prim_indices[i];
425                         if (!grid_materials_match(first, &bvh->grid_flag_mats[prim]))
426                                 return true;
427                 }
428         }
429
430         return false;
431 }
432
433
434 /* Recursively build a node in the tree
435  *
436  * vb is the voxel box around all of the primitives contained in
437  * this node.
438  *
439  * cb is the bounding box around all the centroids of the primitives
440  * contained in this node
441  *
442  * offset and start indicate a range in the array of primitive indices
443  */
444
445 static void build_sub(PBVH *bvh, int node_index, BB *cb, BBC *prim_bbc,
446                       int offset, int count)
447 {
448         int end;
449         BB cb_backing;
450
451         /* Decide whether this is a leaf or not */
452         const bool below_leaf_limit = count <= bvh->leaf_limit;
453         if (below_leaf_limit) {
454                 if (!leaf_needs_material_split(bvh, offset, count)) {
455                         build_leaf(bvh, node_index, prim_bbc, offset, count);
456                         return;
457                 }
458         }
459
460         /* Add two child nodes */
461         bvh->nodes[node_index].children_offset = bvh->totnode;
462         pbvh_grow_nodes(bvh, bvh->totnode + 2);
463
464         /* Update parent node bounding box */
465         update_vb(bvh, &bvh->nodes[node_index], prim_bbc, offset, count);
466
467         if (!below_leaf_limit) {
468                 /* Find axis with widest range of primitive centroids */
469                 if (!cb) {
470                         cb = &cb_backing;
471                         BB_reset(cb);
472                         for (int i = offset + count - 1; i >= offset; --i)
473                                 BB_expand(cb, prim_bbc[bvh->prim_indices[i]].bcentroid);
474                 }
475                 const int axis = BB_widest_axis(cb);
476
477                 /* Partition primitives along that axis */
478                 end = partition_indices(bvh->prim_indices,
479                                         offset, offset + count - 1,
480                                         axis,
481                                         (cb->bmax[axis] + cb->bmin[axis]) * 0.5f,
482                                         prim_bbc);
483         }
484         else {
485                 /* Partition primitives by material */
486                 end = partition_indices_material(bvh, offset, offset + count - 1);
487         }
488
489         /* Build children */
490         build_sub(bvh, bvh->nodes[node_index].children_offset, NULL,
491                   prim_bbc, offset, end - offset);
492         build_sub(bvh, bvh->nodes[node_index].children_offset + 1, NULL,
493                   prim_bbc, end, offset + count - end);
494 }
495
496 static void pbvh_build(PBVH *bvh, BB *cb, BBC *prim_bbc, int totprim)
497 {
498         if (totprim != bvh->totprim) {
499                 bvh->totprim = totprim;
500                 if (bvh->nodes) MEM_freeN(bvh->nodes);
501                 if (bvh->prim_indices) MEM_freeN(bvh->prim_indices);
502                 bvh->prim_indices = MEM_mallocN(sizeof(int) * totprim,
503                                                 "bvh prim indices");
504                 for (int i = 0; i < totprim; ++i)
505                         bvh->prim_indices[i] = i;
506                 bvh->totnode = 0;
507                 if (bvh->node_mem_count < 100) {
508                         bvh->node_mem_count = 100;
509                         bvh->nodes = MEM_callocN(sizeof(PBVHNode) *
510                                                  bvh->node_mem_count,
511                                                  "bvh initial nodes");
512                 }
513         }
514
515         bvh->totnode = 1;
516         build_sub(bvh, 0, cb, prim_bbc, 0, totprim);
517 }
518
519 /**
520  * Do a full rebuild with on Mesh data structure.
521  *
522  * \note Unlike mpoly/mloop/verts, looptri is **totally owned** by PBVH (which means it may rewrite it if needed,
523  *       see BKE_pbvh_apply_vertCos().
524  */
525 void BKE_pbvh_build_mesh(
526         PBVH *bvh, const MPoly *mpoly, const MLoop *mloop, MVert *verts,
527         int totvert, struct CustomData *vdata,
528         const MLoopTri *looptri, int looptri_num)
529 {
530         BBC *prim_bbc = NULL;
531         BB cb;
532
533         bvh->type = PBVH_FACES;
534         bvh->mpoly = mpoly;
535         bvh->mloop = mloop;
536         bvh->looptri = looptri;
537         bvh->verts = verts;
538         bvh->vert_bitmap = BLI_BITMAP_NEW(totvert, "bvh->vert_bitmap");
539         bvh->totvert = totvert;
540         bvh->leaf_limit = LEAF_LIMIT;
541         bvh->vdata = vdata;
542
543         BB_reset(&cb);
544
545         /* For each face, store the AABB and the AABB centroid */
546         prim_bbc = MEM_mallocN(sizeof(BBC) * looptri_num, "prim_bbc");
547
548         for (int i = 0; i < looptri_num; ++i) {
549                 const MLoopTri *lt = &looptri[i];
550                 const int sides = 3;
551                 BBC *bbc = prim_bbc + i;
552
553                 BB_reset((BB *)bbc);
554
555                 for (int j = 0; j < sides; ++j)
556                         BB_expand((BB *)bbc, verts[bvh->mloop[lt->tri[j]].v].co);
557
558                 BBC_update_centroid(bbc);
559
560                 BB_expand(&cb, bbc->bcentroid);
561         }
562
563         if (looptri_num)
564                 pbvh_build(bvh, &cb, prim_bbc, looptri_num);
565
566         MEM_freeN(prim_bbc);
567         MEM_freeN(bvh->vert_bitmap);
568 }
569
570 /* Do a full rebuild with on Grids data structure */
571 void BKE_pbvh_build_grids(PBVH *bvh, CCGElem **grids,
572                           int totgrid, CCGKey *key, void **gridfaces, DMFlagMat *flagmats, BLI_bitmap **grid_hidden)
573 {
574         const int gridsize = key->grid_size;
575
576         bvh->type = PBVH_GRIDS;
577         bvh->grids = grids;
578         bvh->gridfaces = gridfaces;
579         bvh->grid_flag_mats = flagmats;
580         bvh->totgrid = totgrid;
581         bvh->gridkey = *key;
582         bvh->grid_hidden = grid_hidden;
583         bvh->leaf_limit = max_ii(LEAF_LIMIT / ((gridsize - 1) * (gridsize - 1)), 1);
584
585         BB cb;
586         BB_reset(&cb);
587
588         /* For each grid, store the AABB and the AABB centroid */
589         BBC *prim_bbc = MEM_mallocN(sizeof(BBC) * totgrid, "prim_bbc");
590
591         for (int i = 0; i < totgrid; ++i) {
592                 CCGElem *grid = grids[i];
593                 BBC *bbc = prim_bbc + i;
594
595                 BB_reset((BB *)bbc);
596
597                 for (int j = 0; j < gridsize * gridsize; ++j)
598                         BB_expand((BB *)bbc, CCG_elem_offset_co(key, grid, j));
599
600                 BBC_update_centroid(bbc);
601
602                 BB_expand(&cb, bbc->bcentroid);
603         }
604
605         if (totgrid)
606                 pbvh_build(bvh, &cb, prim_bbc, totgrid);
607
608         MEM_freeN(prim_bbc);
609 }
610
611 void BKE_pbvh_set_ccgdm(PBVH *bvh, CCGDerivedMesh *ccgdm)
612 {
613         bvh->ccgdm = ccgdm;
614 }
615
616 PBVH *BKE_pbvh_new(void)
617 {
618         PBVH *bvh = MEM_callocN(sizeof(PBVH), "pbvh");
619
620         return bvh;
621 }
622
623 void BKE_pbvh_free(PBVH *bvh)
624 {
625         for (int i = 0; i < bvh->totnode; ++i) {
626                 PBVHNode *node = &bvh->nodes[i];
627
628                 if (node->flag & PBVH_Leaf) {
629                         if (node->draw_buffers)
630                                 GPU_pbvh_buffers_free(node->draw_buffers);
631                         if (node->vert_indices)
632                                 MEM_freeN((void *)node->vert_indices);
633                         if (node->face_vert_indices)
634                                 MEM_freeN((void *)node->face_vert_indices);
635                         BKE_pbvh_node_layer_disp_free(node);
636
637                         if (node->bm_faces)
638                                 BLI_gset_free(node->bm_faces, NULL);
639                         if (node->bm_unique_verts)
640                                 BLI_gset_free(node->bm_unique_verts, NULL);
641                         if (node->bm_other_verts)
642                                 BLI_gset_free(node->bm_other_verts, NULL);
643                 }
644         }
645         GPU_pbvh_multires_buffers_free(&bvh->grid_common_gpu_buffer);
646
647         if (bvh->deformed) {
648                 if (bvh->verts) {
649                         /* if pbvh was deformed, new memory was allocated for verts/faces -- free it */
650
651                         MEM_freeN((void *)bvh->verts);
652                 }
653         }
654
655         if (bvh->looptri) {
656                 MEM_freeN((void *)bvh->looptri);
657         }
658
659         if (bvh->nodes)
660                 MEM_freeN(bvh->nodes);
661
662         if (bvh->prim_indices)
663                 MEM_freeN(bvh->prim_indices);
664
665         MEM_freeN(bvh);
666 }
667
668 void BKE_pbvh_free_layer_disp(PBVH *bvh)
669 {
670         for (int i = 0; i < bvh->totnode; ++i)
671                 BKE_pbvh_node_layer_disp_free(&bvh->nodes[i]);
672 }
673
674 static void pbvh_iter_begin(PBVHIter *iter, PBVH *bvh, BKE_pbvh_SearchCallback scb, void *search_data)
675 {
676         iter->bvh = bvh;
677         iter->scb = scb;
678         iter->search_data = search_data;
679
680         iter->stack = iter->stackfixed;
681         iter->stackspace = STACK_FIXED_DEPTH;
682
683         iter->stack[0].node = bvh->nodes;
684         iter->stack[0].revisiting = false;
685         iter->stacksize = 1;
686 }
687
688 static void pbvh_iter_end(PBVHIter *iter)
689 {
690         if (iter->stackspace > STACK_FIXED_DEPTH)
691                 MEM_freeN(iter->stack);
692 }
693
694 static void pbvh_stack_push(PBVHIter *iter, PBVHNode *node, bool revisiting)
695 {
696         if (UNLIKELY(iter->stacksize == iter->stackspace)) {
697                 iter->stackspace *= 2;
698                 if (iter->stackspace != (STACK_FIXED_DEPTH * 2)) {
699                         iter->stack = MEM_reallocN(iter->stack, sizeof(PBVHStack) * iter->stackspace);
700                 }
701                 else {
702                         iter->stack = MEM_mallocN(sizeof(PBVHStack) * iter->stackspace, "PBVHStack");
703                         memcpy(iter->stack, iter->stackfixed, sizeof(PBVHStack) * iter->stacksize);
704                 }
705         }
706
707         iter->stack[iter->stacksize].node = node;
708         iter->stack[iter->stacksize].revisiting = revisiting;
709         iter->stacksize++;
710 }
711
712 static PBVHNode *pbvh_iter_next(PBVHIter *iter)
713 {
714         /* purpose here is to traverse tree, visiting child nodes before their
715          * parents, this order is necessary for e.g. computing bounding boxes */
716
717         while (iter->stacksize) {
718                 /* pop node */
719                 iter->stacksize--;
720                 PBVHNode *node = iter->stack[iter->stacksize].node;
721
722                 /* on a mesh with no faces this can happen
723                  * can remove this check if we know meshes have at least 1 face */
724                 if (node == NULL)
725                         return NULL;
726
727                 bool revisiting = iter->stack[iter->stacksize].revisiting;
728
729                 /* revisiting node already checked */
730                 if (revisiting)
731                         return node;
732
733                 if (iter->scb && !iter->scb(node, iter->search_data))
734                         continue;  /* don't traverse, outside of search zone */
735
736                 if (node->flag & PBVH_Leaf) {
737                         /* immediately hit leaf node */
738                         return node;
739                 }
740                 else {
741                         /* come back later when children are done */
742                         pbvh_stack_push(iter, node, true);
743
744                         /* push two child nodes on the stack */
745                         pbvh_stack_push(iter, iter->bvh->nodes + node->children_offset + 1, false);
746                         pbvh_stack_push(iter, iter->bvh->nodes + node->children_offset, false);
747                 }
748         }
749
750         return NULL;
751 }
752
753 static PBVHNode *pbvh_iter_next_occluded(PBVHIter *iter)
754 {
755         while (iter->stacksize) {
756                 /* pop node */
757                 iter->stacksize--;
758                 PBVHNode *node = iter->stack[iter->stacksize].node;
759
760                 /* on a mesh with no faces this can happen
761                  * can remove this check if we know meshes have at least 1 face */
762                 if (node == NULL) return NULL;
763
764                 if (iter->scb && !iter->scb(node, iter->search_data)) continue;  /* don't traverse, outside of search zone */
765
766                 if (node->flag & PBVH_Leaf) {
767                         /* immediately hit leaf node */
768                         return node;
769                 }
770                 else {
771                         pbvh_stack_push(iter, iter->bvh->nodes + node->children_offset + 1, false);
772                         pbvh_stack_push(iter, iter->bvh->nodes + node->children_offset, false);
773                 }
774         }
775
776         return NULL;
777 }
778
779 void BKE_pbvh_search_gather(PBVH *bvh,
780                             BKE_pbvh_SearchCallback scb, void *search_data,
781                             PBVHNode ***r_array, int *r_tot)
782 {
783         PBVHIter iter;
784         PBVHNode **array = NULL, *node;
785         int tot = 0, space = 0;
786
787         pbvh_iter_begin(&iter, bvh, scb, search_data);
788
789         while ((node = pbvh_iter_next(&iter))) {
790                 if (node->flag & PBVH_Leaf) {
791                         if (UNLIKELY(tot == space)) {
792                                 /* resize array if needed */
793                                 space = (tot == 0) ? 32 : space * 2;
794                                 array = MEM_recallocN_id(array, sizeof(PBVHNode *) * space, __func__);
795                         }
796
797                         array[tot] = node;
798                         tot++;
799                 }
800         }
801
802         pbvh_iter_end(&iter);
803
804         if (tot == 0 && array) {
805                 MEM_freeN(array);
806                 array = NULL;
807         }
808
809         *r_array = array;
810         *r_tot = tot;
811 }
812
813 void BKE_pbvh_search_callback(PBVH *bvh,
814                               BKE_pbvh_SearchCallback scb, void *search_data,
815                               BKE_pbvh_HitCallback hcb, void *hit_data)
816 {
817         PBVHIter iter;
818         PBVHNode *node;
819
820         pbvh_iter_begin(&iter, bvh, scb, search_data);
821
822         while ((node = pbvh_iter_next(&iter)))
823                 if (node->flag & PBVH_Leaf)
824                         hcb(node, hit_data);
825
826         pbvh_iter_end(&iter);
827 }
828
829 typedef struct node_tree {
830         PBVHNode *data;
831
832         struct node_tree *left;
833         struct node_tree *right;
834 } node_tree;
835
836 static void node_tree_insert(node_tree *tree, node_tree *new_node)
837 {
838         if (new_node->data->tmin < tree->data->tmin) {
839                 if (tree->left) {
840                         node_tree_insert(tree->left, new_node);
841                 }
842                 else {
843                         tree->left = new_node;
844                 }
845         }
846         else {
847                 if (tree->right) {
848                         node_tree_insert(tree->right, new_node);
849                 }
850                 else {
851                         tree->right = new_node;
852                 }
853         }
854 }
855
856 static void traverse_tree(node_tree *tree, BKE_pbvh_HitOccludedCallback hcb, void *hit_data, float *tmin)
857 {
858         if (tree->left) traverse_tree(tree->left, hcb, hit_data, tmin);
859
860         hcb(tree->data, hit_data, tmin);
861
862         if (tree->right) traverse_tree(tree->right, hcb, hit_data, tmin);
863 }
864
865 static void free_tree(node_tree *tree)
866 {
867         if (tree->left) {
868                 free_tree(tree->left);
869                 tree->left = NULL;
870         }
871
872         if (tree->right) {
873                 free_tree(tree->right);
874                 tree->right = NULL;
875         }
876
877         free(tree);
878 }
879
880 float BKE_pbvh_node_get_tmin(PBVHNode *node)
881 {
882         return node->tmin;
883 }
884
885 static void BKE_pbvh_search_callback_occluded(PBVH *bvh,
886                                               BKE_pbvh_SearchCallback scb, void *search_data,
887                                               BKE_pbvh_HitOccludedCallback hcb, void *hit_data)
888 {
889         PBVHIter iter;
890         PBVHNode *node;
891         node_tree *tree = NULL;
892
893         pbvh_iter_begin(&iter, bvh, scb, search_data);
894
895         while ((node = pbvh_iter_next_occluded(&iter))) {
896                 if (node->flag & PBVH_Leaf) {
897                         node_tree *new_node = malloc(sizeof(node_tree));
898
899                         new_node->data = node;
900
901                         new_node->left  = NULL;
902                         new_node->right = NULL;
903
904                         if (tree) {
905                                 node_tree_insert(tree, new_node);
906                         }
907                         else {
908                                 tree = new_node;
909                         }
910                 }
911         }
912
913         pbvh_iter_end(&iter);
914
915         if (tree) {
916                 float tmin = FLT_MAX;
917                 traverse_tree(tree, hcb, hit_data, &tmin);
918                 free_tree(tree);
919         }
920 }
921
922 static bool update_search_cb(PBVHNode *node, void *data_v)
923 {
924         int flag = GET_INT_FROM_POINTER(data_v);
925
926         if (node->flag & PBVH_Leaf)
927                 return (node->flag & flag) != 0;
928
929         return true;
930 }
931
932 typedef struct PBVHUpdateData {
933         PBVH *bvh;
934         PBVHNode **nodes;
935         int totnode;
936
937         float (*fnors)[3];
938         float (*vnors)[3];
939         int flag;
940 } PBVHUpdateData;
941
942 static void pbvh_update_normals_accum_task_cb(
943         void *__restrict userdata,
944         const int n,
945         const ParallelRangeTLS *__restrict UNUSED(tls))
946 {
947         PBVHUpdateData *data = userdata;
948
949         PBVH *bvh = data->bvh;
950         PBVHNode *node = data->nodes[n];
951         float (*fnors)[3] = data->fnors;
952         float (*vnors)[3] = data->vnors;
953
954         if ((node->flag & PBVH_UpdateNormals)) {
955                 unsigned int mpoly_prev = UINT_MAX;
956                 float fn[3];
957
958                 const int *faces = node->prim_indices;
959                 const int totface = node->totprim;
960
961                 for (int i = 0; i < totface; ++i) {
962                         const MLoopTri *lt = &bvh->looptri[faces[i]];
963                         const unsigned int vtri[3] = {
964                                 bvh->mloop[lt->tri[0]].v,
965                                 bvh->mloop[lt->tri[1]].v,
966                                 bvh->mloop[lt->tri[2]].v,
967                         };
968                         const int sides = 3;
969
970                         /* Face normal and mask */
971                         if (lt->poly != mpoly_prev) {
972                                 const MPoly *mp = &bvh->mpoly[lt->poly];
973                                 BKE_mesh_calc_poly_normal(mp, &bvh->mloop[mp->loopstart], bvh->verts, fn);
974                                 mpoly_prev = lt->poly;
975
976                                 if (fnors) {
977                                         /* We can assume a face is only present in one node ever. */
978                                         copy_v3_v3(fnors[lt->poly], fn);
979                                 }
980                         }
981
982                         for (int j = sides; j--; ) {
983                                 const int v = vtri[j];
984
985                                 if (bvh->verts[v].flag & ME_VERT_PBVH_UPDATE) {
986                                         /* Note: This avoids `lock, add_v3_v3, unlock` and is five to ten times quicker than a spinlock.
987                                          *       Not exact equivalent though, since atomicity is only ensured for one component
988                                          *       of the vector at a time, but here it shall not make any sensible difference. */
989                                         for (int k = 3; k--; ) {
990                                                 atomic_add_and_fetch_fl(&vnors[v][k], fn[k]);
991                                         }
992                                 }
993                         }
994                 }
995         }
996 }
997
998 static void pbvh_update_normals_store_task_cb(
999         void *__restrict userdata,
1000         const int n,
1001         const ParallelRangeTLS *__restrict UNUSED(tls))
1002 {
1003         PBVHUpdateData *data = userdata;
1004         PBVH *bvh = data->bvh;
1005         PBVHNode *node = data->nodes[n];
1006         float (*vnors)[3] = data->vnors;
1007
1008         if (node->flag & PBVH_UpdateNormals) {
1009                 const int *verts = node->vert_indices;
1010                 const int totvert = node->uniq_verts;
1011
1012                 for (int i = 0; i < totvert; ++i) {
1013                         const int v = verts[i];
1014                         MVert *mvert = &bvh->verts[v];
1015
1016                         /* mvert is shared between nodes, hence between threads. */
1017                         if (atomic_fetch_and_and_char(&mvert->flag, (char)~ME_VERT_PBVH_UPDATE) & ME_VERT_PBVH_UPDATE) {
1018                                 normalize_v3(vnors[v]);
1019                                 normal_float_to_short_v3(mvert->no, vnors[v]);
1020                         }
1021                 }
1022
1023                 node->flag &= ~PBVH_UpdateNormals;
1024         }
1025 }
1026
1027 static void pbvh_update_normals(PBVH *bvh, PBVHNode **nodes,
1028                                 int totnode, float (*fnors)[3])
1029 {
1030         float (*vnors)[3];
1031
1032         if (bvh->type == PBVH_BMESH) {
1033                 BLI_assert(fnors == NULL);
1034                 pbvh_bmesh_normals_update(nodes, totnode);
1035                 return;
1036         }
1037
1038         if (bvh->type != PBVH_FACES)
1039                 return;
1040
1041         /* could be per node to save some memory, but also means
1042          * we have to store for each vertex which node it is in */
1043         vnors = MEM_callocN(sizeof(*vnors) * bvh->totvert, __func__);
1044
1045         /* subtle assumptions:
1046          * - We know that for all edited vertices, the nodes with faces
1047          *   adjacent to these vertices have been marked with PBVH_UpdateNormals.
1048          *   This is true because if the vertex is inside the brush radius, the
1049          *   bounding box of it's adjacent faces will be as well.
1050          * - However this is only true for the vertices that have actually been
1051          *   edited, not for all vertices in the nodes marked for update, so we
1052          *   can only update vertices marked with ME_VERT_PBVH_UPDATE.
1053          */
1054
1055         PBVHUpdateData data = {
1056             .bvh = bvh, .nodes = nodes,
1057             .fnors = fnors, .vnors = vnors,
1058         };
1059
1060         ParallelRangeSettings settings;
1061         BLI_parallel_range_settings_defaults(&settings);
1062         settings.use_threading = (totnode > PBVH_THREADED_LIMIT);
1063
1064         BLI_task_parallel_range(0, totnode, &data, pbvh_update_normals_accum_task_cb, &settings);
1065
1066         BLI_task_parallel_range(0, totnode, &data, pbvh_update_normals_store_task_cb, &settings);
1067
1068         MEM_freeN(vnors);
1069 }
1070
1071 static void pbvh_update_BB_redraw_task_cb(
1072         void *__restrict userdata,
1073         const int n,
1074         const ParallelRangeTLS *__restrict UNUSED(tls))
1075 {
1076         PBVHUpdateData *data = userdata;
1077         PBVH *bvh = data->bvh;
1078         PBVHNode *node = data->nodes[n];
1079         const int flag = data->flag;
1080
1081         if ((flag & PBVH_UpdateBB) && (node->flag & PBVH_UpdateBB))
1082                 /* don't clear flag yet, leave it for flushing later */
1083                 /* Note that bvh usage is read-only here, so no need to thread-protect it. */
1084                 update_node_vb(bvh, node);
1085
1086         if ((flag & PBVH_UpdateOriginalBB) && (node->flag & PBVH_UpdateOriginalBB))
1087                 node->orig_vb = node->vb;
1088
1089         if ((flag & PBVH_UpdateRedraw) && (node->flag & PBVH_UpdateRedraw))
1090                 node->flag &= ~PBVH_UpdateRedraw;
1091 }
1092
1093 void pbvh_update_BB_redraw(PBVH *bvh, PBVHNode **nodes, int totnode, int flag)
1094 {
1095         /* update BB, redraw flag */
1096         PBVHUpdateData data = {
1097             .bvh = bvh, .nodes = nodes,
1098             .flag = flag,
1099         };
1100
1101         ParallelRangeSettings settings;
1102         BLI_parallel_range_settings_defaults(&settings);
1103         settings.use_threading = (totnode > PBVH_THREADED_LIMIT);
1104         BLI_task_parallel_range(0, totnode, &data, pbvh_update_BB_redraw_task_cb, &settings);
1105 }
1106
1107 static int pbvh_get_buffers_update_flags(PBVH *bvh)
1108 {
1109         int update_flags = 0;
1110         update_flags |= bvh->show_mask ? GPU_PBVH_BUFFERS_SHOW_MASK : 0;
1111         return update_flags;
1112 }
1113
1114 static void pbvh_update_draw_buffers(PBVH *bvh, PBVHNode **nodes, int totnode)
1115 {
1116         /* can't be done in parallel with OpenGL */
1117         for (int n = 0; n < totnode; n++) {
1118                 PBVHNode *node = nodes[n];
1119
1120                 if (node->flag & PBVH_RebuildDrawBuffers) {
1121                         GPU_pbvh_buffers_free(node->draw_buffers);
1122                         switch (bvh->type) {
1123                                 case PBVH_GRIDS:
1124                                         node->draw_buffers =
1125                                                 GPU_pbvh_grid_buffers_build(node->prim_indices,
1126                                                                    node->totprim,
1127                                                                    bvh->grid_hidden,
1128                                                                    bvh->gridkey.grid_size,
1129                                                                    &bvh->gridkey, &bvh->grid_common_gpu_buffer);
1130                                         break;
1131                                 case PBVH_FACES:
1132                                         node->draw_buffers =
1133                                                 GPU_pbvh_mesh_buffers_build(node->face_vert_indices,
1134                                                                    bvh->mpoly, bvh->mloop, bvh->looptri,
1135                                                                    bvh->verts,
1136                                                                    node->prim_indices,
1137                                                                    node->totprim);
1138                                         break;
1139                                 case PBVH_BMESH:
1140                                         node->draw_buffers =
1141                                                 GPU_pbvh_bmesh_buffers_build(bvh->flags & PBVH_DYNTOPO_SMOOTH_SHADING);
1142                                         break;
1143                         }
1144
1145                         node->flag &= ~PBVH_RebuildDrawBuffers;
1146                 }
1147
1148                 if (node->flag & PBVH_UpdateDrawBuffers) {
1149                         const int update_flags = pbvh_get_buffers_update_flags(bvh);
1150                         switch (bvh->type) {
1151                                 case PBVH_GRIDS:
1152                                         GPU_pbvh_grid_buffers_update(
1153                                                 node->draw_buffers,
1154                                                 bvh->grids,
1155                                                 bvh->grid_flag_mats,
1156                                                 node->prim_indices,
1157                                                 node->totprim,
1158                                                 &bvh->gridkey,
1159                                                 update_flags);
1160                                         break;
1161                                 case PBVH_FACES:
1162                                         GPU_pbvh_mesh_buffers_update(
1163                                                 node->draw_buffers,
1164                                                 bvh->verts,
1165                                                 node->vert_indices,
1166                                                 node->uniq_verts +
1167                                                 node->face_verts,
1168                                                 CustomData_get_layer(bvh->vdata, CD_PAINT_MASK),
1169                                                 node->face_vert_indices,
1170                                                 update_flags);
1171                                         break;
1172                                 case PBVH_BMESH:
1173                                         GPU_pbvh_bmesh_buffers_update(
1174                                                 node->draw_buffers,
1175                                                 bvh->bm,
1176                                                 node->bm_faces,
1177                                                 node->bm_unique_verts,
1178                                                 node->bm_other_verts,
1179                                                 update_flags);
1180                                         break;
1181                         }
1182
1183                         node->flag &= ~PBVH_UpdateDrawBuffers;
1184                 }
1185         }
1186 }
1187
1188 static int pbvh_flush_bb(PBVH *bvh, PBVHNode *node, int flag)
1189 {
1190         int update = 0;
1191
1192         /* difficult to multithread well, we just do single threaded recursive */
1193         if (node->flag & PBVH_Leaf) {
1194                 if (flag & PBVH_UpdateBB) {
1195                         update |= (node->flag & PBVH_UpdateBB);
1196                         node->flag &= ~PBVH_UpdateBB;
1197                 }
1198
1199                 if (flag & PBVH_UpdateOriginalBB) {
1200                         update |= (node->flag & PBVH_UpdateOriginalBB);
1201                         node->flag &= ~PBVH_UpdateOriginalBB;
1202                 }
1203
1204                 return update;
1205         }
1206         else {
1207                 update |= pbvh_flush_bb(bvh, bvh->nodes + node->children_offset, flag);
1208                 update |= pbvh_flush_bb(bvh, bvh->nodes + node->children_offset + 1, flag);
1209
1210                 if (update & PBVH_UpdateBB)
1211                         update_node_vb(bvh, node);
1212                 if (update & PBVH_UpdateOriginalBB)
1213                         node->orig_vb = node->vb;
1214         }
1215
1216         return update;
1217 }
1218
1219 void BKE_pbvh_update(PBVH *bvh, int flag, float (*fnors)[3])
1220 {
1221         if (!bvh->nodes)
1222                 return;
1223
1224         PBVHNode **nodes;
1225         int totnode;
1226
1227         BKE_pbvh_search_gather(bvh, update_search_cb, SET_INT_IN_POINTER(flag),
1228                                &nodes, &totnode);
1229
1230         if (flag & PBVH_UpdateNormals)
1231                 pbvh_update_normals(bvh, nodes, totnode, fnors);
1232
1233         if (flag & (PBVH_UpdateBB | PBVH_UpdateOriginalBB | PBVH_UpdateRedraw))
1234                 pbvh_update_BB_redraw(bvh, nodes, totnode, flag);
1235
1236         if (flag & (PBVH_UpdateBB | PBVH_UpdateOriginalBB))
1237                 pbvh_flush_bb(bvh, bvh->nodes, flag);
1238
1239         if (nodes) MEM_freeN(nodes);
1240 }
1241
1242 void BKE_pbvh_redraw_BB(PBVH *bvh, float bb_min[3], float bb_max[3])
1243 {
1244         PBVHIter iter;
1245         PBVHNode *node;
1246         BB bb;
1247
1248         BB_reset(&bb);
1249
1250         pbvh_iter_begin(&iter, bvh, NULL, NULL);
1251
1252         while ((node = pbvh_iter_next(&iter)))
1253                 if (node->flag & PBVH_UpdateRedraw)
1254                         BB_expand_with_bb(&bb, &node->vb);
1255
1256         pbvh_iter_end(&iter);
1257
1258         copy_v3_v3(bb_min, bb.bmin);
1259         copy_v3_v3(bb_max, bb.bmax);
1260 }
1261
1262 void BKE_pbvh_get_grid_updates(PBVH *bvh, bool clear, void ***r_gridfaces, int *r_totface)
1263 {
1264         GSet *face_set = BLI_gset_ptr_new(__func__);
1265         PBVHNode *node;
1266         PBVHIter iter;
1267
1268         pbvh_iter_begin(&iter, bvh, NULL, NULL);
1269
1270         while ((node = pbvh_iter_next(&iter))) {
1271                 if (node->flag & PBVH_UpdateNormals) {
1272                         for (unsigned i = 0; i < node->totprim; ++i) {
1273                                 void *face = bvh->gridfaces[node->prim_indices[i]];
1274                                 BLI_gset_add(face_set, face);
1275                         }
1276
1277                         if (clear)
1278                                 node->flag &= ~PBVH_UpdateNormals;
1279                 }
1280         }
1281
1282         pbvh_iter_end(&iter);
1283
1284         const int tot = BLI_gset_len(face_set);
1285         if (tot == 0) {
1286                 *r_totface = 0;
1287                 *r_gridfaces = NULL;
1288                 BLI_gset_free(face_set, NULL);
1289                 return;
1290         }
1291
1292         void **faces = MEM_mallocN(sizeof(*faces) * tot, "PBVH Grid Faces");
1293
1294         GSetIterator gs_iter;
1295         int i;
1296         GSET_ITER_INDEX (gs_iter, face_set, i) {
1297                 faces[i] = BLI_gsetIterator_getKey(&gs_iter);
1298         }
1299
1300         BLI_gset_free(face_set, NULL);
1301
1302         *r_totface = tot;
1303         *r_gridfaces = faces;
1304 }
1305
1306 /***************************** PBVH Access ***********************************/
1307
1308 PBVHType BKE_pbvh_type(const PBVH *bvh)
1309 {
1310         return bvh->type;
1311 }
1312
1313 bool BKE_pbvh_has_faces(const PBVH *bvh)
1314 {
1315         if (bvh->type == PBVH_BMESH) {
1316                 return (bvh->bm->totface != 0);
1317         }
1318         else {
1319                 return (bvh->totprim != 0);
1320         }
1321 }
1322
1323 void BKE_pbvh_bounding_box(const PBVH *bvh, float min[3], float max[3])
1324 {
1325         if (bvh->totnode) {
1326                 const BB *bb = &bvh->nodes[0].vb;
1327                 copy_v3_v3(min, bb->bmin);
1328                 copy_v3_v3(max, bb->bmax);
1329         }
1330         else {
1331                 zero_v3(min);
1332                 zero_v3(max);
1333         }
1334 }
1335
1336 BLI_bitmap **BKE_pbvh_grid_hidden(const PBVH *bvh)
1337 {
1338         BLI_assert(bvh->type == PBVH_GRIDS);
1339         return bvh->grid_hidden;
1340 }
1341
1342 void BKE_pbvh_get_grid_key(const PBVH *bvh, CCGKey *key)
1343 {
1344         BLI_assert(bvh->type == PBVH_GRIDS);
1345         *key = bvh->gridkey;
1346 }
1347
1348 CCGDerivedMesh *BKE_pbvh_get_ccgdm(const PBVH *bvh)
1349 {
1350         return bvh->ccgdm;
1351 }
1352
1353
1354 BMesh *BKE_pbvh_get_bmesh(PBVH *bvh)
1355 {
1356         BLI_assert(bvh->type == PBVH_BMESH);
1357         return bvh->bm;
1358 }
1359
1360 /***************************** Node Access ***********************************/
1361
1362 void BKE_pbvh_node_mark_update(PBVHNode *node)
1363 {
1364         node->flag |= PBVH_UpdateNormals | PBVH_UpdateBB | PBVH_UpdateOriginalBB | PBVH_UpdateDrawBuffers | PBVH_UpdateRedraw;
1365 }
1366
1367 void BKE_pbvh_node_mark_rebuild_draw(PBVHNode *node)
1368 {
1369         node->flag |= PBVH_RebuildDrawBuffers | PBVH_UpdateDrawBuffers | PBVH_UpdateRedraw;
1370 }
1371
1372 void BKE_pbvh_node_mark_redraw(PBVHNode *node)
1373 {
1374         node->flag |= PBVH_UpdateDrawBuffers | PBVH_UpdateRedraw;
1375 }
1376
1377 void BKE_pbvh_node_mark_normals_update(PBVHNode *node)
1378 {
1379         node->flag |= PBVH_UpdateNormals;
1380 }
1381
1382
1383 void BKE_pbvh_node_fully_hidden_set(PBVHNode *node, int fully_hidden)
1384 {
1385         BLI_assert(node->flag & PBVH_Leaf);
1386
1387         if (fully_hidden)
1388                 node->flag |= PBVH_FullyHidden;
1389         else
1390                 node->flag &= ~PBVH_FullyHidden;
1391 }
1392
1393 void BKE_pbvh_node_get_verts(
1394         PBVH *bvh, PBVHNode *node,
1395         const int **r_vert_indices, MVert **r_verts)
1396 {
1397         if (r_vert_indices) {
1398                 *r_vert_indices = node->vert_indices;
1399         }
1400
1401         if (r_verts) {
1402                 *r_verts = bvh->verts;
1403         }
1404 }
1405
1406 void BKE_pbvh_node_num_verts(
1407         PBVH *bvh, PBVHNode *node,
1408         int *r_uniquevert, int *r_totvert)
1409 {
1410         int tot;
1411
1412         switch (bvh->type) {
1413                 case PBVH_GRIDS:
1414                         tot = node->totprim * bvh->gridkey.grid_area;
1415                         if (r_totvert) *r_totvert = tot;
1416                         if (r_uniquevert) *r_uniquevert = tot;
1417                         break;
1418                 case PBVH_FACES:
1419                         if (r_totvert) *r_totvert = node->uniq_verts + node->face_verts;
1420                         if (r_uniquevert) *r_uniquevert = node->uniq_verts;
1421                         break;
1422                 case PBVH_BMESH:
1423                         tot = BLI_gset_len(node->bm_unique_verts);
1424                         if (r_totvert) *r_totvert = tot + BLI_gset_len(node->bm_other_verts);
1425                         if (r_uniquevert) *r_uniquevert = tot;
1426                         break;
1427         }
1428 }
1429
1430 void BKE_pbvh_node_get_grids(
1431         PBVH *bvh, PBVHNode *node,
1432         int **r_grid_indices, int *r_totgrid, int *r_maxgrid, int *r_gridsize, CCGElem ***r_griddata)
1433 {
1434         switch (bvh->type) {
1435                 case PBVH_GRIDS:
1436                         if (r_grid_indices) *r_grid_indices = node->prim_indices;
1437                         if (r_totgrid) *r_totgrid = node->totprim;
1438                         if (r_maxgrid) *r_maxgrid = bvh->totgrid;
1439                         if (r_gridsize) *r_gridsize = bvh->gridkey.grid_size;
1440                         if (r_griddata) *r_griddata = bvh->grids;
1441                         break;
1442                 case PBVH_FACES:
1443                 case PBVH_BMESH:
1444                         if (r_grid_indices) *r_grid_indices = NULL;
1445                         if (r_totgrid) *r_totgrid = 0;
1446                         if (r_maxgrid) *r_maxgrid = 0;
1447                         if (r_gridsize) *r_gridsize = 0;
1448                         if (r_griddata) *r_griddata = NULL;
1449                         break;
1450         }
1451 }
1452
1453 void BKE_pbvh_node_get_BB(PBVHNode *node, float bb_min[3], float bb_max[3])
1454 {
1455         copy_v3_v3(bb_min, node->vb.bmin);
1456         copy_v3_v3(bb_max, node->vb.bmax);
1457 }
1458
1459 void BKE_pbvh_node_get_original_BB(PBVHNode *node, float bb_min[3], float bb_max[3])
1460 {
1461         copy_v3_v3(bb_min, node->orig_vb.bmin);
1462         copy_v3_v3(bb_max, node->orig_vb.bmax);
1463 }
1464
1465 void BKE_pbvh_node_get_proxies(PBVHNode *node, PBVHProxyNode **proxies, int *proxy_count)
1466 {
1467         if (node->proxy_count > 0) {
1468                 if (proxies) *proxies = node->proxies;
1469                 if (proxy_count) *proxy_count = node->proxy_count;
1470         }
1471         else {
1472                 if (proxies) *proxies = NULL;
1473                 if (proxy_count) *proxy_count = 0;
1474         }
1475 }
1476
1477 void BKE_pbvh_node_get_bm_orco_data(
1478         PBVHNode *node,
1479         int (**r_orco_tris)[3], int *r_orco_tris_num, float (**r_orco_coords)[3])
1480 {
1481         *r_orco_tris = node->bm_ortri;
1482         *r_orco_tris_num = node->bm_tot_ortri;
1483         *r_orco_coords = node->bm_orco;
1484 }
1485
1486 /**
1487  * \note doing a full search on all vertices here seems expensive,
1488  * however this is important to avoid having to recalculate boundbox & sync the buffers to the GPU
1489  * (which is far more expensive!) See: T47232.
1490  */
1491 bool BKE_pbvh_node_vert_update_check_any(PBVH *bvh, PBVHNode *node)
1492 {
1493         BLI_assert(bvh->type == PBVH_FACES);
1494         const int *verts = node->vert_indices;
1495         const int totvert = node->uniq_verts + node->face_verts;
1496
1497         for (int i = 0; i < totvert; ++i) {
1498                 const int v = verts[i];
1499                 const MVert *mvert = &bvh->verts[v];
1500
1501                 if (mvert->flag & ME_VERT_PBVH_UPDATE) {
1502                         return true;
1503                 }
1504         }
1505
1506         return false;
1507 }
1508
1509
1510 /********************************* Raycast ***********************************/
1511
1512 typedef struct {
1513         struct IsectRayAABB_Precalc ray;
1514         bool original;
1515 } RaycastData;
1516
1517 static bool ray_aabb_intersect(PBVHNode *node, void *data_v)
1518 {
1519         RaycastData *rcd = data_v;
1520         const float *bb_min, *bb_max;
1521
1522         if (rcd->original) {
1523                 /* BKE_pbvh_node_get_original_BB */
1524                 bb_min = node->orig_vb.bmin;
1525                 bb_max = node->orig_vb.bmax;
1526         }
1527         else {
1528                 /* BKE_pbvh_node_get_BB */
1529                 bb_min = node->vb.bmin;
1530                 bb_max = node->vb.bmax;
1531         }
1532
1533         return isect_ray_aabb_v3(&rcd->ray, bb_min, bb_max, &node->tmin);
1534 }
1535
1536 void BKE_pbvh_raycast(
1537         PBVH *bvh, BKE_pbvh_HitOccludedCallback cb, void *data,
1538         const float ray_start[3], const float ray_normal[3],
1539         bool original)
1540 {
1541         RaycastData rcd;
1542
1543         isect_ray_aabb_v3_precalc(&rcd.ray, ray_start, ray_normal);
1544         rcd.original = original;
1545
1546         BKE_pbvh_search_callback_occluded(bvh, ray_aabb_intersect, &rcd, cb, data);
1547 }
1548
1549 bool ray_face_intersection_quad(
1550         const float ray_start[3], const float ray_normal[3],
1551         const float t0[3], const float t1[3], const float t2[3], const float t3[3],
1552         float *depth)
1553 {
1554         float depth_test;
1555
1556         if ((isect_ray_tri_epsilon_v3(
1557                  ray_start, ray_normal, t0, t1, t2, &depth_test, NULL, 0.1f) && (depth_test < *depth)) ||
1558             (isect_ray_tri_epsilon_v3(
1559                  ray_start, ray_normal, t0, t2, t3, &depth_test, NULL, 0.1f) && (depth_test < *depth)))
1560         {
1561                 *depth = depth_test;
1562                 return true;
1563         }
1564         else {
1565                 return false;
1566         }
1567 }
1568
1569 bool ray_face_intersection_tri(
1570         const float ray_start[3], const float ray_normal[3],
1571         const float t0[3], const float t1[3], const float t2[3],
1572         float *depth)
1573 {
1574         float depth_test;
1575
1576         if ((isect_ray_tri_epsilon_v3(
1577                  ray_start, ray_normal, t0, t1, t2, &depth_test, NULL, 0.1f) && (depth_test < *depth)))
1578         {
1579                 *depth = depth_test;
1580                 return true;
1581         }
1582         else {
1583                 return false;
1584         }
1585 }
1586
1587 /* Take advantage of the fact we know this wont be an intersection.
1588  * Just handle ray-tri edges. */
1589 static float dist_squared_ray_to_tri_v3_fast(
1590         const float ray_origin[3], const float ray_direction[3],
1591         const float v0[3], const float v1[3], const float v2[3],
1592         float r_point[3], float *r_depth)
1593 {
1594         const float *tri[3] = {v0, v1, v2};
1595         float dist_sq_best = FLT_MAX;
1596         for (int i = 0, j = 2; i < 3; j = i++) {
1597                 float point_test[3], depth_test = FLT_MAX;
1598                 const float dist_sq_test = dist_squared_ray_to_seg_v3(
1599                         ray_origin, ray_direction, tri[i], tri[j], point_test, &depth_test);
1600                 if (dist_sq_test < dist_sq_best || i == 0) {
1601                         copy_v3_v3(r_point, point_test);
1602                         *r_depth = depth_test;
1603                         dist_sq_best = dist_sq_test;
1604                 }
1605         }
1606         return dist_sq_best;
1607 }
1608
1609 bool ray_face_nearest_quad(
1610         const float ray_start[3], const float ray_normal[3],
1611         const float t0[3], const float t1[3], const float t2[3], const float t3[3],
1612         float *depth, float *dist_sq)
1613 {
1614         float dist_sq_test;
1615         float co[3], depth_test;
1616
1617         if (((dist_sq_test = dist_squared_ray_to_tri_v3_fast(
1618                  ray_start, ray_normal, t0, t1, t2, co, &depth_test)) < *dist_sq))
1619         {
1620                 *dist_sq = dist_sq_test;
1621                 *depth = depth_test;
1622                 if (((dist_sq_test = dist_squared_ray_to_tri_v3_fast(
1623                          ray_start, ray_normal, t0, t2, t3, co, &depth_test)) < *dist_sq))
1624                 {
1625                         *dist_sq = dist_sq_test;
1626                         *depth = depth_test;
1627                 }
1628                 return true;
1629         }
1630         else {
1631                 return false;
1632         }
1633 }
1634
1635 bool ray_face_nearest_tri(
1636         const float ray_start[3], const float ray_normal[3],
1637         const float t0[3], const float t1[3], const float t2[3],
1638         float *depth, float *dist_sq)
1639 {
1640         float dist_sq_test;
1641         float co[3], depth_test;
1642
1643         if (((dist_sq_test = dist_squared_ray_to_tri_v3_fast(
1644                  ray_start, ray_normal, t0, t1, t2, co, &depth_test)) < *dist_sq))
1645         {
1646                 *dist_sq = dist_sq_test;
1647                 *depth = depth_test;
1648                 return true;
1649         }
1650         else {
1651                 return false;
1652         }
1653 }
1654
1655 static bool pbvh_faces_node_raycast(
1656         PBVH *bvh, const PBVHNode *node,
1657         float (*origco)[3],
1658         const float ray_start[3], const float ray_normal[3],
1659         float *depth)
1660 {
1661         const MVert *vert = bvh->verts;
1662         const MLoop *mloop = bvh->mloop;
1663         const int *faces = node->prim_indices;
1664         int i, totface = node->totprim;
1665         bool hit = false;
1666
1667         for (i = 0; i < totface; ++i) {
1668                 const MLoopTri *lt = &bvh->looptri[faces[i]];
1669                 const int *face_verts = node->face_vert_indices[i];
1670
1671                 if (paint_is_face_hidden(lt, vert, mloop))
1672                         continue;
1673
1674                 if (origco) {
1675                         /* intersect with backuped original coordinates */
1676                         hit |= ray_face_intersection_tri(
1677                                 ray_start, ray_normal,
1678                                 origco[face_verts[0]],
1679                                 origco[face_verts[1]],
1680                                 origco[face_verts[2]],
1681                                 depth);
1682                 }
1683                 else {
1684                         /* intersect with current coordinates */
1685                         hit |= ray_face_intersection_tri(
1686                                 ray_start, ray_normal,
1687                                 vert[mloop[lt->tri[0]].v].co,
1688                                 vert[mloop[lt->tri[1]].v].co,
1689                                 vert[mloop[lt->tri[2]].v].co,
1690                                 depth);
1691                 }
1692         }
1693
1694         return hit;
1695 }
1696
1697 static bool pbvh_grids_node_raycast(
1698         PBVH *bvh, PBVHNode *node,
1699         float (*origco)[3],
1700         const float ray_start[3], const float ray_normal[3],
1701         float *depth)
1702 {
1703         const int totgrid = node->totprim;
1704         const int gridsize = bvh->gridkey.grid_size;
1705         bool hit = false;
1706
1707         for (int i = 0; i < totgrid; ++i) {
1708                 CCGElem *grid = bvh->grids[node->prim_indices[i]];
1709                 BLI_bitmap *gh;
1710
1711                 if (!grid)
1712                         continue;
1713
1714                 gh = bvh->grid_hidden[node->prim_indices[i]];
1715
1716                 for (int y = 0; y < gridsize - 1; ++y) {
1717                         for (int x = 0; x < gridsize - 1; ++x) {
1718                                 /* check if grid face is hidden */
1719                                 if (gh) {
1720                                         if (paint_is_grid_face_hidden(gh, gridsize, x, y))
1721                                                 continue;
1722                                 }
1723
1724                                 if (origco) {
1725                                         hit |= ray_face_intersection_quad(
1726                                                 ray_start, ray_normal,
1727                                                 origco[y * gridsize + x],
1728                                                 origco[y * gridsize + x + 1],
1729                                                 origco[(y + 1) * gridsize + x + 1],
1730                                                 origco[(y + 1) * gridsize + x],
1731                                                 depth);
1732                                 }
1733                                 else {
1734                                         hit |= ray_face_intersection_quad(
1735                                                 ray_start, ray_normal,
1736                                                 CCG_grid_elem_co(&bvh->gridkey, grid, x, y),
1737                                                 CCG_grid_elem_co(&bvh->gridkey, grid, x + 1, y),
1738                                                 CCG_grid_elem_co(&bvh->gridkey, grid, x + 1, y + 1),
1739                                                 CCG_grid_elem_co(&bvh->gridkey, grid, x, y + 1),
1740                                                 depth);
1741                                 }
1742                         }
1743                 }
1744
1745                 if (origco)
1746                         origco += gridsize * gridsize;
1747         }
1748
1749         return hit;
1750 }
1751
1752 bool BKE_pbvh_node_raycast(
1753         PBVH *bvh, PBVHNode *node, float (*origco)[3], bool use_origco,
1754         const float ray_start[3], const float ray_normal[3],
1755         float *depth)
1756 {
1757         bool hit = false;
1758
1759         if (node->flag & PBVH_FullyHidden)
1760                 return false;
1761
1762         switch (bvh->type) {
1763                 case PBVH_FACES:
1764                         hit |= pbvh_faces_node_raycast(
1765                                 bvh, node, origco,
1766                                 ray_start, ray_normal, depth);
1767                         break;
1768                 case PBVH_GRIDS:
1769                         hit |= pbvh_grids_node_raycast(
1770                                 bvh, node, origco,
1771                                 ray_start, ray_normal, depth);
1772                         break;
1773                 case PBVH_BMESH:
1774                         hit = pbvh_bmesh_node_raycast(
1775                                 node, ray_start, ray_normal, depth, use_origco);
1776                         break;
1777         }
1778
1779         return hit;
1780 }
1781
1782 void BKE_pbvh_raycast_project_ray_root(
1783         PBVH *bvh, bool original,
1784         float ray_start[3], float ray_end[3], float ray_normal[3])
1785 {
1786         if (bvh->nodes) {
1787                 float rootmin_start, rootmin_end;
1788                 float bb_min_root[3], bb_max_root[3], bb_center[3], bb_diff[3];
1789                 struct IsectRayAABB_Precalc ray;
1790                 float ray_normal_inv[3];
1791                 float offset = 1.0f + 1e-3f;
1792                 float offset_vec[3] = {1e-3f, 1e-3f, 1e-3f};
1793
1794                 if (original)
1795                         BKE_pbvh_node_get_original_BB(bvh->nodes, bb_min_root, bb_max_root);
1796                 else
1797                         BKE_pbvh_node_get_BB(bvh->nodes, bb_min_root, bb_max_root);
1798
1799                 /* slightly offset min and max in case we have a zero width node (due to a plane mesh for instance),
1800                  * or faces very close to the bounding box boundary. */
1801                 mid_v3_v3v3(bb_center, bb_max_root, bb_min_root);
1802                 /* diff should be same for both min/max since it's calculated from center */
1803                 sub_v3_v3v3(bb_diff, bb_max_root, bb_center);
1804                 /* handles case of zero width bb */
1805                 add_v3_v3(bb_diff, offset_vec);
1806                 madd_v3_v3v3fl(bb_max_root, bb_center, bb_diff, offset);
1807                 madd_v3_v3v3fl(bb_min_root, bb_center, bb_diff, -offset);
1808
1809                 /* first project start ray */
1810                 isect_ray_aabb_v3_precalc(&ray, ray_start, ray_normal);
1811                 if (!isect_ray_aabb_v3(&ray, bb_min_root, bb_max_root, &rootmin_start))
1812                         return;
1813
1814                 /* then the end ray */
1815                 mul_v3_v3fl(ray_normal_inv, ray_normal, -1.0);
1816                 isect_ray_aabb_v3_precalc(&ray, ray_end, ray_normal_inv);
1817                 /* unlikely to fail exiting if entering succeeded, still keep this here */
1818                 if (!isect_ray_aabb_v3(&ray, bb_min_root, bb_max_root, &rootmin_end))
1819                         return;
1820
1821                 madd_v3_v3v3fl(ray_start, ray_start, ray_normal, rootmin_start);
1822                 madd_v3_v3v3fl(ray_end, ray_end, ray_normal_inv, rootmin_end);
1823         }
1824 }
1825
1826 /* -------------------------------------------------------------------- */
1827
1828 typedef struct {
1829         struct DistRayAABB_Precalc dist_ray_to_aabb_precalc;
1830         bool original;
1831 } FindNearestRayData;
1832
1833 static bool nearest_to_ray_aabb_dist_sq(PBVHNode *node, void *data_v)
1834 {
1835         FindNearestRayData *rcd = data_v;
1836         const float *bb_min, *bb_max;
1837
1838         if (rcd->original) {
1839                 /* BKE_pbvh_node_get_original_BB */
1840                 bb_min = node->orig_vb.bmin;
1841                 bb_max = node->orig_vb.bmax;
1842         }
1843         else {
1844                 /* BKE_pbvh_node_get_BB */
1845                 bb_min = node->vb.bmin;
1846                 bb_max = node->vb.bmax;
1847         }
1848
1849         float co_dummy[3], depth;
1850         node->tmin = dist_squared_ray_to_aabb_v3(&rcd->dist_ray_to_aabb_precalc, bb_min, bb_max, co_dummy, &depth);
1851         /* Ideally we would skip distances outside the range. */
1852         return depth > 0.0f;
1853 }
1854
1855 void BKE_pbvh_find_nearest_to_ray(
1856         PBVH *bvh, BKE_pbvh_SearchNearestCallback cb, void *data,
1857         const float ray_start[3], const float ray_normal[3],
1858         bool original)
1859 {
1860         FindNearestRayData ncd;
1861
1862         dist_squared_ray_to_aabb_v3_precalc(&ncd.dist_ray_to_aabb_precalc, ray_start, ray_normal);
1863         ncd.original = original;
1864
1865         BKE_pbvh_search_callback_occluded(bvh, nearest_to_ray_aabb_dist_sq, &ncd, cb, data);
1866 }
1867
1868
1869 static bool pbvh_faces_node_nearest_to_ray(
1870         PBVH *bvh, const PBVHNode *node,
1871         float (*origco)[3],
1872         const float ray_start[3], const float ray_normal[3],
1873         float *depth, float *dist_sq)
1874 {
1875         const MVert *vert = bvh->verts;
1876         const MLoop *mloop = bvh->mloop;
1877         const int *faces = node->prim_indices;
1878         int i, totface = node->totprim;
1879         bool hit = false;
1880
1881         for (i = 0; i < totface; ++i) {
1882                 const MLoopTri *lt = &bvh->looptri[faces[i]];
1883                 const int *face_verts = node->face_vert_indices[i];
1884
1885                 if (paint_is_face_hidden(lt, vert, mloop))
1886                         continue;
1887
1888                 if (origco) {
1889                         /* intersect with backuped original coordinates */
1890                         hit |= ray_face_nearest_tri(
1891                                 ray_start, ray_normal,
1892                                 origco[face_verts[0]],
1893                                 origco[face_verts[1]],
1894                                 origco[face_verts[2]],
1895                                 depth, dist_sq);
1896                 }
1897                 else {
1898                         /* intersect with current coordinates */
1899                         hit |= ray_face_nearest_tri(
1900                                 ray_start, ray_normal,
1901                                 vert[mloop[lt->tri[0]].v].co,
1902                                 vert[mloop[lt->tri[1]].v].co,
1903                                 vert[mloop[lt->tri[2]].v].co,
1904                                 depth, dist_sq);
1905                 }
1906         }
1907
1908         return hit;
1909 }
1910
1911 static bool pbvh_grids_node_nearest_to_ray(
1912         PBVH *bvh, PBVHNode *node,
1913         float (*origco)[3],
1914         const float ray_start[3], const float ray_normal[3],
1915         float *depth, float *dist_sq)
1916 {
1917         const int totgrid = node->totprim;
1918         const int gridsize = bvh->gridkey.grid_size;
1919         bool hit = false;
1920
1921         for (int i = 0; i < totgrid; ++i) {
1922                 CCGElem *grid = bvh->grids[node->prim_indices[i]];
1923                 BLI_bitmap *gh;
1924
1925                 if (!grid)
1926                         continue;
1927
1928                 gh = bvh->grid_hidden[node->prim_indices[i]];
1929
1930                 for (int y = 0; y < gridsize - 1; ++y) {
1931                         for (int x = 0; x < gridsize - 1; ++x) {
1932                                 /* check if grid face is hidden */
1933                                 if (gh) {
1934                                         if (paint_is_grid_face_hidden(gh, gridsize, x, y))
1935                                                 continue;
1936                                 }
1937
1938                                 if (origco) {
1939                                         hit |= ray_face_nearest_quad(
1940                                                 ray_start, ray_normal,
1941                                                 origco[y * gridsize + x],
1942                                                 origco[y * gridsize + x + 1],
1943                                                 origco[(y + 1) * gridsize + x + 1],
1944                                                 origco[(y + 1) * gridsize + x],
1945                                                 depth, dist_sq);
1946                                 }
1947                                 else {
1948                                         hit |= ray_face_nearest_quad(
1949                                                 ray_start, ray_normal,
1950                                                 CCG_grid_elem_co(&bvh->gridkey, grid, x, y),
1951                                                 CCG_grid_elem_co(&bvh->gridkey, grid, x + 1, y),
1952                                                 CCG_grid_elem_co(&bvh->gridkey, grid, x + 1, y + 1),
1953                                                 CCG_grid_elem_co(&bvh->gridkey, grid, x, y + 1),
1954                                                 depth, dist_sq);
1955                                 }
1956                         }
1957                 }
1958
1959                 if (origco)
1960                         origco += gridsize * gridsize;
1961         }
1962
1963         return hit;
1964 }
1965
1966 bool BKE_pbvh_node_find_nearest_to_ray(
1967         PBVH *bvh, PBVHNode *node, float (*origco)[3], bool use_origco,
1968         const float ray_start[3], const float ray_normal[3],
1969         float *depth, float *dist_sq)
1970 {
1971         bool hit = false;
1972
1973         if (node->flag & PBVH_FullyHidden)
1974                 return false;
1975
1976         switch (bvh->type) {
1977                 case PBVH_FACES:
1978                         hit |= pbvh_faces_node_nearest_to_ray(
1979                                 bvh, node, origco,
1980                                 ray_start, ray_normal, depth, dist_sq);
1981                         break;
1982                 case PBVH_GRIDS:
1983                         hit |= pbvh_grids_node_nearest_to_ray(
1984                                 bvh, node, origco,
1985                                 ray_start, ray_normal, depth, dist_sq);
1986                         break;
1987                 case PBVH_BMESH:
1988                         hit = pbvh_bmesh_node_nearest_to_ray(
1989                                 node, ray_start, ray_normal, depth, dist_sq, use_origco);
1990                         break;
1991         }
1992
1993         return hit;
1994 }
1995
1996 typedef enum {
1997         ISECT_INSIDE,
1998         ISECT_OUTSIDE,
1999         ISECT_INTERSECT
2000 } PlaneAABBIsect;
2001
2002 /* Adapted from:
2003  * http://www.gamedev.net/community/forums/topic.asp?topic_id=512123
2004  * Returns true if the AABB is at least partially within the frustum
2005  * (ok, not a real frustum), false otherwise.
2006  */
2007 static PlaneAABBIsect test_planes_aabb(const float bb_min[3],
2008                                        const float bb_max[3],
2009                                        const float (*planes)[4])
2010 {
2011         float vmin[3], vmax[3];
2012         PlaneAABBIsect ret = ISECT_INSIDE;
2013
2014         for (int i = 0; i < 4; ++i) {
2015                 for (int axis = 0; axis < 3; ++axis) {
2016                         if (planes[i][axis] > 0) {
2017                                 vmin[axis] = bb_min[axis];
2018                                 vmax[axis] = bb_max[axis];
2019                         }
2020                         else {
2021                                 vmin[axis] = bb_max[axis];
2022                                 vmax[axis] = bb_min[axis];
2023                         }
2024                 }
2025
2026                 if (dot_v3v3(planes[i], vmin) + planes[i][3] > 0)
2027                         return ISECT_OUTSIDE;
2028                 else if (dot_v3v3(planes[i], vmax) + planes[i][3] >= 0)
2029                         ret = ISECT_INTERSECT;
2030         }
2031
2032         return ret;
2033 }
2034
2035 bool BKE_pbvh_node_planes_contain_AABB(PBVHNode *node, void *data)
2036 {
2037         const float *bb_min, *bb_max;
2038         /* BKE_pbvh_node_get_BB */
2039         bb_min = node->vb.bmin;
2040         bb_max = node->vb.bmax;
2041
2042         return test_planes_aabb(bb_min, bb_max, data) != ISECT_OUTSIDE;
2043 }
2044
2045 bool BKE_pbvh_node_planes_exclude_AABB(PBVHNode *node, void *data)
2046 {
2047         const float *bb_min, *bb_max;
2048         /* BKE_pbvh_node_get_BB */
2049         bb_min = node->vb.bmin;
2050         bb_max = node->vb.bmax;
2051
2052         return test_planes_aabb(bb_min, bb_max, data) != ISECT_INSIDE;
2053 }
2054
2055 struct PBVHNodeDrawCallbackData {
2056         void (*draw_fn)(void *user_data, GPUBatch *batch);
2057         void *user_data;
2058         bool fast;
2059         bool only_mask; /* Only draw nodes that have mask data. */
2060 };
2061
2062 static void pbvh_node_draw_cb(PBVHNode *node, void *data_v)
2063 {
2064         struct PBVHNodeDrawCallbackData *data = data_v;
2065
2066         if (!(node->flag & PBVH_FullyHidden)) {
2067                 GPUBatch *triangles = GPU_pbvh_buffers_batch_get(node->draw_buffers, data->fast);
2068                 bool show_mask = GPU_pbvh_buffers_has_mask(node->draw_buffers);
2069                 if (!data->only_mask || show_mask) {
2070                         if (triangles != NULL) {
2071                                 data->draw_fn(data->user_data, triangles);
2072                         }
2073                 }
2074         }
2075 }
2076
2077 /**
2078  * Version of #BKE_pbvh_draw that runs a callback.
2079  */
2080 void BKE_pbvh_draw_cb(
2081         PBVH *bvh, float (*planes)[4], float (*fnors)[3], bool fast, bool only_mask,
2082         void (*draw_fn)(void *user_data, GPUBatch *batch), void *user_data)
2083 {
2084         struct PBVHNodeDrawCallbackData draw_data = {
2085                 .only_mask = only_mask,
2086                 .fast = fast,
2087                 .draw_fn = draw_fn,
2088                 .user_data = user_data,
2089         };
2090         PBVHNode **nodes;
2091         int totnode;
2092
2093         BKE_pbvh_search_gather(bvh, update_search_cb, SET_INT_IN_POINTER(PBVH_UpdateNormals | PBVH_UpdateDrawBuffers),
2094                                &nodes, &totnode);
2095
2096         pbvh_update_normals(bvh, nodes, totnode, fnors);
2097         pbvh_update_draw_buffers(bvh, nodes, totnode);
2098
2099         if (nodes) MEM_freeN(nodes);
2100
2101         if (planes) {
2102                 BKE_pbvh_search_callback(
2103                         bvh, BKE_pbvh_node_planes_contain_AABB,
2104                         planes, pbvh_node_draw_cb, &draw_data);
2105         }
2106         else {
2107                 BKE_pbvh_search_callback(
2108                         bvh, NULL,
2109                         NULL, pbvh_node_draw_cb, &draw_data);
2110         }
2111 #if 0
2112         if (G.debug_value == 14)
2113                 pbvh_draw_BB(bvh);
2114 #endif
2115 }
2116
2117 void BKE_pbvh_grids_update(PBVH *bvh, CCGElem **grids, void **gridfaces,
2118                            DMFlagMat *flagmats, BLI_bitmap **grid_hidden)
2119 {
2120         bvh->grids = grids;
2121         bvh->gridfaces = gridfaces;
2122
2123         if (flagmats != bvh->grid_flag_mats || bvh->grid_hidden != grid_hidden) {
2124                 bvh->grid_flag_mats = flagmats;
2125                 bvh->grid_hidden = grid_hidden;
2126
2127                 for (int a = 0; a < bvh->totnode; ++a)
2128                         BKE_pbvh_node_mark_rebuild_draw(&bvh->nodes[a]);
2129         }
2130 }
2131
2132 /* Get the node's displacement layer, creating it if necessary */
2133 float *BKE_pbvh_node_layer_disp_get(PBVH *bvh, PBVHNode *node)
2134 {
2135         if (!node->layer_disp) {
2136                 int totvert = 0;
2137                 BKE_pbvh_node_num_verts(bvh, node, &totvert, NULL);
2138                 node->layer_disp = MEM_callocN(sizeof(float) * totvert, "layer disp");
2139         }
2140         return node->layer_disp;
2141 }
2142
2143 /* If the node has a displacement layer, free it and set to null */
2144 void BKE_pbvh_node_layer_disp_free(PBVHNode *node)
2145 {
2146         if (node->layer_disp) {
2147                 MEM_freeN(node->layer_disp);
2148                 node->layer_disp = NULL;
2149         }
2150 }
2151
2152 float (*BKE_pbvh_get_vertCos(PBVH *pbvh))[3]
2153 {
2154         float (*vertCos)[3] = NULL;
2155
2156         if (pbvh->verts) {
2157                 MVert *mvert = pbvh->verts;
2158
2159                 vertCos = MEM_callocN(3 * pbvh->totvert * sizeof(float), "BKE_pbvh_get_vertCoords");
2160                 float *co = (float *)vertCos;
2161
2162                 for (int a = 0; a < pbvh->totvert; a++, mvert++, co += 3) {
2163                         copy_v3_v3(co, mvert->co);
2164                 }
2165         }
2166
2167         return vertCos;
2168 }
2169
2170 void BKE_pbvh_apply_vertCos(PBVH *pbvh, float (*vertCos)[3], const int totvert)
2171 {
2172         if (totvert != pbvh->totvert) {
2173                 BLI_assert(!"PBVH: Given deforming vcos number does not natch PBVH vertex number!");
2174                 return;
2175         }
2176
2177         if (!pbvh->deformed) {
2178                 if (pbvh->verts) {
2179                         /* if pbvh is not already deformed, verts/faces points to the */
2180                         /* original data and applying new coords to this arrays would lead to */
2181                         /* unneeded deformation -- duplicate verts/faces to avoid this */
2182
2183                         pbvh->verts   = MEM_dupallocN(pbvh->verts);
2184                         /* No need to dupalloc pbvh->looptri, this one is 'totally owned' by pbvh, it's never some mesh data. */
2185
2186                         pbvh->deformed = true;
2187                 }
2188         }
2189
2190         if (pbvh->verts) {
2191                 MVert *mvert = pbvh->verts;
2192                 /* copy new verts coords */
2193                 for (int a = 0; a < pbvh->totvert; ++a, ++mvert) {
2194                         /* no need for float comparison here (memory is exactly equal or not) */
2195                         if (memcmp(mvert->co, vertCos[a], sizeof(float[3])) != 0) {
2196                                 copy_v3_v3(mvert->co, vertCos[a]);
2197                                 mvert->flag |= ME_VERT_PBVH_UPDATE;
2198                         }
2199                 }
2200
2201                 /* coordinates are new -- normals should also be updated */
2202                 BKE_mesh_calc_normals_looptri(
2203                         pbvh->verts, pbvh->totvert,
2204                         pbvh->mloop,
2205                         pbvh->looptri, pbvh->totprim,
2206                         NULL);
2207
2208                 for (int a = 0; a < pbvh->totnode; ++a)
2209                         BKE_pbvh_node_mark_update(&pbvh->nodes[a]);
2210
2211                 BKE_pbvh_update(pbvh, PBVH_UpdateBB, NULL);
2212                 BKE_pbvh_update(pbvh, PBVH_UpdateOriginalBB, NULL);
2213
2214         }
2215 }
2216
2217 bool BKE_pbvh_isDeformed(PBVH *pbvh)
2218 {
2219         return pbvh->deformed;
2220 }
2221 /* Proxies */
2222
2223 PBVHProxyNode *BKE_pbvh_node_add_proxy(PBVH *bvh, PBVHNode *node)
2224 {
2225         int index, totverts;
2226
2227         index = node->proxy_count;
2228
2229         node->proxy_count++;
2230
2231         if (node->proxies)
2232                 node->proxies = MEM_reallocN(node->proxies, node->proxy_count * sizeof(PBVHProxyNode));
2233         else
2234                 node->proxies = MEM_mallocN(sizeof(PBVHProxyNode), "PBVHNodeProxy");
2235
2236         BKE_pbvh_node_num_verts(bvh, node, &totverts, NULL);
2237         node->proxies[index].co = MEM_callocN(sizeof(float[3]) * totverts, "PBVHNodeProxy.co");
2238
2239         return node->proxies + index;
2240 }
2241
2242 void BKE_pbvh_node_free_proxies(PBVHNode *node)
2243 {
2244         for (int p = 0; p < node->proxy_count; p++) {
2245                 MEM_freeN(node->proxies[p].co);
2246                 node->proxies[p].co = NULL;
2247         }
2248
2249         MEM_freeN(node->proxies);
2250         node->proxies = NULL;
2251
2252         node->proxy_count = 0;
2253 }
2254
2255 void BKE_pbvh_gather_proxies(PBVH *pbvh, PBVHNode ***r_array,  int *r_tot)
2256 {
2257         PBVHNode **array = NULL;
2258         int tot = 0, space = 0;
2259
2260         for (int n = 0; n < pbvh->totnode; n++) {
2261                 PBVHNode *node = pbvh->nodes + n;
2262
2263                 if (node->proxy_count > 0) {
2264                         if (tot == space) {
2265                                 /* resize array if needed */
2266                                 space = (tot == 0) ? 32 : space * 2;
2267                                 array = MEM_recallocN_id(array, sizeof(PBVHNode *) * space, __func__);
2268                         }
2269
2270                         array[tot] = node;
2271                         tot++;
2272                 }
2273         }
2274
2275         if (tot == 0 && array) {
2276                 MEM_freeN(array);
2277                 array = NULL;
2278         }
2279
2280         *r_array = array;
2281         *r_tot = tot;
2282 }
2283
2284 void pbvh_vertex_iter_init(PBVH *bvh, PBVHNode *node,
2285                            PBVHVertexIter *vi, int mode)
2286 {
2287         struct CCGElem **grids;
2288         struct MVert *verts;
2289         const int *vert_indices;
2290         int *grid_indices;
2291         int totgrid, gridsize, uniq_verts, totvert;
2292
2293         vi->grid = NULL;
2294         vi->no = NULL;
2295         vi->fno = NULL;
2296         vi->mvert = NULL;
2297
2298         BKE_pbvh_node_get_grids(bvh, node, &grid_indices, &totgrid, NULL, &gridsize, &grids);
2299         BKE_pbvh_node_num_verts(bvh, node, &uniq_verts, &totvert);
2300         BKE_pbvh_node_get_verts(bvh, node, &vert_indices, &verts);
2301         vi->key = &bvh->gridkey;
2302
2303         vi->grids = grids;
2304         vi->grid_indices = grid_indices;
2305         vi->totgrid = (grids) ? totgrid : 1;
2306         vi->gridsize = gridsize;
2307
2308         if (mode == PBVH_ITER_ALL)
2309                 vi->totvert = totvert;
2310         else
2311                 vi->totvert = uniq_verts;
2312         vi->vert_indices = vert_indices;
2313         vi->mverts = verts;
2314
2315         if (bvh->type == PBVH_BMESH) {
2316                 BLI_gsetIterator_init(&vi->bm_unique_verts, node->bm_unique_verts);
2317                 BLI_gsetIterator_init(&vi->bm_other_verts, node->bm_other_verts);
2318                 vi->bm_vdata = &bvh->bm->vdata;
2319                 vi->cd_vert_mask_offset = CustomData_get_offset(vi->bm_vdata, CD_PAINT_MASK);
2320         }
2321
2322         vi->gh = NULL;
2323         if (vi->grids && mode == PBVH_ITER_UNIQUE)
2324                 vi->grid_hidden = bvh->grid_hidden;
2325
2326         vi->mask = NULL;
2327         if (bvh->type == PBVH_FACES)
2328                 vi->vmask = CustomData_get_layer(bvh->vdata, CD_PAINT_MASK);
2329 }
2330
2331 bool pbvh_has_mask(PBVH *bvh)
2332 {
2333         switch (bvh->type) {
2334                 case PBVH_GRIDS:
2335                         return (bvh->gridkey.has_mask != 0);
2336                 case PBVH_FACES:
2337                         return (bvh->vdata && CustomData_get_layer(bvh->vdata,
2338                                               CD_PAINT_MASK));
2339                 case PBVH_BMESH:
2340                         return (bvh->bm && (CustomData_get_offset(&bvh->bm->vdata, CD_PAINT_MASK) != -1));
2341         }
2342
2343         return false;
2344 }
2345
2346 void pbvh_show_diffuse_color_set(PBVH *bvh, bool show_diffuse_color)
2347 {
2348         bvh->show_diffuse_color = !pbvh_has_mask(bvh) || show_diffuse_color;
2349 }
2350
2351 void pbvh_show_mask_set(PBVH *bvh, bool show_mask)
2352 {
2353         bvh->show_mask = show_mask;
2354 }