Merge branch 'master' into blender2.8
[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 = POINTER_FROM_INT(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 = POINTER_FROM_INT(value_i);
263                 return value_i;
264         }
265         else {
266                 return POINTER_AS_INT(*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 = POINTER_AS_INT(value);
308
309                 if (ndx < 0)
310                         ndx = -ndx + node->uniq_verts - 1;
311
312                 vert_indices[ndx] =
313                         POINTER_AS_INT(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 PBVH *BKE_pbvh_new(void)
612 {
613         PBVH *bvh = MEM_callocN(sizeof(PBVH), "pbvh");
614
615         return bvh;
616 }
617
618 void BKE_pbvh_free(PBVH *bvh)
619 {
620         for (int i = 0; i < bvh->totnode; ++i) {
621                 PBVHNode *node = &bvh->nodes[i];
622
623                 if (node->flag & PBVH_Leaf) {
624                         if (node->draw_buffers)
625                                 GPU_pbvh_buffers_free(node->draw_buffers);
626                         if (node->vert_indices)
627                                 MEM_freeN((void *)node->vert_indices);
628                         if (node->face_vert_indices)
629                                 MEM_freeN((void *)node->face_vert_indices);
630                         BKE_pbvh_node_layer_disp_free(node);
631
632                         if (node->bm_faces)
633                                 BLI_gset_free(node->bm_faces, NULL);
634                         if (node->bm_unique_verts)
635                                 BLI_gset_free(node->bm_unique_verts, NULL);
636                         if (node->bm_other_verts)
637                                 BLI_gset_free(node->bm_other_verts, NULL);
638                 }
639         }
640
641         if (bvh->deformed) {
642                 if (bvh->verts) {
643                         /* if pbvh was deformed, new memory was allocated for verts/faces -- free it */
644
645                         MEM_freeN((void *)bvh->verts);
646                 }
647         }
648
649         if (bvh->looptri) {
650                 MEM_freeN((void *)bvh->looptri);
651         }
652
653         if (bvh->nodes)
654                 MEM_freeN(bvh->nodes);
655
656         if (bvh->prim_indices)
657                 MEM_freeN(bvh->prim_indices);
658
659         MEM_freeN(bvh);
660 }
661
662 void BKE_pbvh_free_layer_disp(PBVH *bvh)
663 {
664         for (int i = 0; i < bvh->totnode; ++i)
665                 BKE_pbvh_node_layer_disp_free(&bvh->nodes[i]);
666 }
667
668 static void pbvh_iter_begin(PBVHIter *iter, PBVH *bvh, BKE_pbvh_SearchCallback scb, void *search_data)
669 {
670         iter->bvh = bvh;
671         iter->scb = scb;
672         iter->search_data = search_data;
673
674         iter->stack = iter->stackfixed;
675         iter->stackspace = STACK_FIXED_DEPTH;
676
677         iter->stack[0].node = bvh->nodes;
678         iter->stack[0].revisiting = false;
679         iter->stacksize = 1;
680 }
681
682 static void pbvh_iter_end(PBVHIter *iter)
683 {
684         if (iter->stackspace > STACK_FIXED_DEPTH)
685                 MEM_freeN(iter->stack);
686 }
687
688 static void pbvh_stack_push(PBVHIter *iter, PBVHNode *node, bool revisiting)
689 {
690         if (UNLIKELY(iter->stacksize == iter->stackspace)) {
691                 iter->stackspace *= 2;
692                 if (iter->stackspace != (STACK_FIXED_DEPTH * 2)) {
693                         iter->stack = MEM_reallocN(iter->stack, sizeof(PBVHStack) * iter->stackspace);
694                 }
695                 else {
696                         iter->stack = MEM_mallocN(sizeof(PBVHStack) * iter->stackspace, "PBVHStack");
697                         memcpy(iter->stack, iter->stackfixed, sizeof(PBVHStack) * iter->stacksize);
698                 }
699         }
700
701         iter->stack[iter->stacksize].node = node;
702         iter->stack[iter->stacksize].revisiting = revisiting;
703         iter->stacksize++;
704 }
705
706 static PBVHNode *pbvh_iter_next(PBVHIter *iter)
707 {
708         /* purpose here is to traverse tree, visiting child nodes before their
709          * parents, this order is necessary for e.g. computing bounding boxes */
710
711         while (iter->stacksize) {
712                 /* pop node */
713                 iter->stacksize--;
714                 PBVHNode *node = iter->stack[iter->stacksize].node;
715
716                 /* on a mesh with no faces this can happen
717                  * can remove this check if we know meshes have at least 1 face */
718                 if (node == NULL)
719                         return NULL;
720
721                 bool revisiting = iter->stack[iter->stacksize].revisiting;
722
723                 /* revisiting node already checked */
724                 if (revisiting)
725                         return node;
726
727                 if (iter->scb && !iter->scb(node, iter->search_data))
728                         continue;  /* don't traverse, outside of search zone */
729
730                 if (node->flag & PBVH_Leaf) {
731                         /* immediately hit leaf node */
732                         return node;
733                 }
734                 else {
735                         /* come back later when children are done */
736                         pbvh_stack_push(iter, node, true);
737
738                         /* push two child nodes on the stack */
739                         pbvh_stack_push(iter, iter->bvh->nodes + node->children_offset + 1, false);
740                         pbvh_stack_push(iter, iter->bvh->nodes + node->children_offset, false);
741                 }
742         }
743
744         return NULL;
745 }
746
747 static PBVHNode *pbvh_iter_next_occluded(PBVHIter *iter)
748 {
749         while (iter->stacksize) {
750                 /* pop node */
751                 iter->stacksize--;
752                 PBVHNode *node = iter->stack[iter->stacksize].node;
753
754                 /* on a mesh with no faces this can happen
755                  * can remove this check if we know meshes have at least 1 face */
756                 if (node == NULL) return NULL;
757
758                 if (iter->scb && !iter->scb(node, iter->search_data)) continue;  /* don't traverse, outside of search zone */
759
760                 if (node->flag & PBVH_Leaf) {
761                         /* immediately hit leaf node */
762                         return node;
763                 }
764                 else {
765                         pbvh_stack_push(iter, iter->bvh->nodes + node->children_offset + 1, false);
766                         pbvh_stack_push(iter, iter->bvh->nodes + node->children_offset, false);
767                 }
768         }
769
770         return NULL;
771 }
772
773 void BKE_pbvh_search_gather(PBVH *bvh,
774                             BKE_pbvh_SearchCallback scb, void *search_data,
775                             PBVHNode ***r_array, int *r_tot)
776 {
777         PBVHIter iter;
778         PBVHNode **array = NULL, *node;
779         int tot = 0, space = 0;
780
781         pbvh_iter_begin(&iter, bvh, scb, search_data);
782
783         while ((node = pbvh_iter_next(&iter))) {
784                 if (node->flag & PBVH_Leaf) {
785                         if (UNLIKELY(tot == space)) {
786                                 /* resize array if needed */
787                                 space = (tot == 0) ? 32 : space * 2;
788                                 array = MEM_recallocN_id(array, sizeof(PBVHNode *) * space, __func__);
789                         }
790
791                         array[tot] = node;
792                         tot++;
793                 }
794         }
795
796         pbvh_iter_end(&iter);
797
798         if (tot == 0 && array) {
799                 MEM_freeN(array);
800                 array = NULL;
801         }
802
803         *r_array = array;
804         *r_tot = tot;
805 }
806
807 void BKE_pbvh_search_callback(PBVH *bvh,
808                               BKE_pbvh_SearchCallback scb, void *search_data,
809                               BKE_pbvh_HitCallback hcb, void *hit_data)
810 {
811         PBVHIter iter;
812         PBVHNode *node;
813
814         pbvh_iter_begin(&iter, bvh, scb, search_data);
815
816         while ((node = pbvh_iter_next(&iter)))
817                 if (node->flag & PBVH_Leaf)
818                         hcb(node, hit_data);
819
820         pbvh_iter_end(&iter);
821 }
822
823 typedef struct node_tree {
824         PBVHNode *data;
825
826         struct node_tree *left;
827         struct node_tree *right;
828 } node_tree;
829
830 static void node_tree_insert(node_tree *tree, node_tree *new_node)
831 {
832         if (new_node->data->tmin < tree->data->tmin) {
833                 if (tree->left) {
834                         node_tree_insert(tree->left, new_node);
835                 }
836                 else {
837                         tree->left = new_node;
838                 }
839         }
840         else {
841                 if (tree->right) {
842                         node_tree_insert(tree->right, new_node);
843                 }
844                 else {
845                         tree->right = new_node;
846                 }
847         }
848 }
849
850 static void traverse_tree(node_tree *tree, BKE_pbvh_HitOccludedCallback hcb, void *hit_data, float *tmin)
851 {
852         if (tree->left) traverse_tree(tree->left, hcb, hit_data, tmin);
853
854         hcb(tree->data, hit_data, tmin);
855
856         if (tree->right) traverse_tree(tree->right, hcb, hit_data, tmin);
857 }
858
859 static void free_tree(node_tree *tree)
860 {
861         if (tree->left) {
862                 free_tree(tree->left);
863                 tree->left = NULL;
864         }
865
866         if (tree->right) {
867                 free_tree(tree->right);
868                 tree->right = NULL;
869         }
870
871         free(tree);
872 }
873
874 float BKE_pbvh_node_get_tmin(PBVHNode *node)
875 {
876         return node->tmin;
877 }
878
879 static void BKE_pbvh_search_callback_occluded(PBVH *bvh,
880                                               BKE_pbvh_SearchCallback scb, void *search_data,
881                                               BKE_pbvh_HitOccludedCallback hcb, void *hit_data)
882 {
883         PBVHIter iter;
884         PBVHNode *node;
885         node_tree *tree = NULL;
886
887         pbvh_iter_begin(&iter, bvh, scb, search_data);
888
889         while ((node = pbvh_iter_next_occluded(&iter))) {
890                 if (node->flag & PBVH_Leaf) {
891                         node_tree *new_node = malloc(sizeof(node_tree));
892
893                         new_node->data = node;
894
895                         new_node->left  = NULL;
896                         new_node->right = NULL;
897
898                         if (tree) {
899                                 node_tree_insert(tree, new_node);
900                         }
901                         else {
902                                 tree = new_node;
903                         }
904                 }
905         }
906
907         pbvh_iter_end(&iter);
908
909         if (tree) {
910                 float tmin = FLT_MAX;
911                 traverse_tree(tree, hcb, hit_data, &tmin);
912                 free_tree(tree);
913         }
914 }
915
916 static bool update_search_cb(PBVHNode *node, void *data_v)
917 {
918         int flag = POINTER_AS_INT(data_v);
919
920         if (node->flag & PBVH_Leaf)
921                 return (node->flag & flag) != 0;
922
923         return true;
924 }
925
926 typedef struct PBVHUpdateData {
927         PBVH *bvh;
928         PBVHNode **nodes;
929         int totnode;
930
931         float (*fnors)[3];
932         float (*vnors)[3];
933         int flag;
934 } PBVHUpdateData;
935
936 static void pbvh_update_normals_accum_task_cb(
937         void *__restrict userdata,
938         const int n,
939         const ParallelRangeTLS *__restrict UNUSED(tls))
940 {
941         PBVHUpdateData *data = userdata;
942
943         PBVH *bvh = data->bvh;
944         PBVHNode *node = data->nodes[n];
945         float (*fnors)[3] = data->fnors;
946         float (*vnors)[3] = data->vnors;
947
948         if ((node->flag & PBVH_UpdateNormals)) {
949                 unsigned int mpoly_prev = UINT_MAX;
950                 float fn[3];
951
952                 const int *faces = node->prim_indices;
953                 const int totface = node->totprim;
954
955                 for (int i = 0; i < totface; ++i) {
956                         const MLoopTri *lt = &bvh->looptri[faces[i]];
957                         const unsigned int vtri[3] = {
958                                 bvh->mloop[lt->tri[0]].v,
959                                 bvh->mloop[lt->tri[1]].v,
960                                 bvh->mloop[lt->tri[2]].v,
961                         };
962                         const int sides = 3;
963
964                         /* Face normal and mask */
965                         if (lt->poly != mpoly_prev) {
966                                 const MPoly *mp = &bvh->mpoly[lt->poly];
967                                 BKE_mesh_calc_poly_normal(mp, &bvh->mloop[mp->loopstart], bvh->verts, fn);
968                                 mpoly_prev = lt->poly;
969
970                                 if (fnors) {
971                                         /* We can assume a face is only present in one node ever. */
972                                         copy_v3_v3(fnors[lt->poly], fn);
973                                 }
974                         }
975
976                         for (int j = sides; j--; ) {
977                                 const int v = vtri[j];
978
979                                 if (bvh->verts[v].flag & ME_VERT_PBVH_UPDATE) {
980                                         /* Note: This avoids `lock, add_v3_v3, unlock` and is five to ten times quicker than a spinlock.
981                                          *       Not exact equivalent though, since atomicity is only ensured for one component
982                                          *       of the vector at a time, but here it shall not make any sensible difference. */
983                                         for (int k = 3; k--; ) {
984                                                 atomic_add_and_fetch_fl(&vnors[v][k], fn[k]);
985                                         }
986                                 }
987                         }
988                 }
989         }
990 }
991
992 static void pbvh_update_normals_store_task_cb(
993         void *__restrict userdata,
994         const int n,
995         const ParallelRangeTLS *__restrict UNUSED(tls))
996 {
997         PBVHUpdateData *data = userdata;
998         PBVH *bvh = data->bvh;
999         PBVHNode *node = data->nodes[n];
1000         float (*vnors)[3] = data->vnors;
1001
1002         if (node->flag & PBVH_UpdateNormals) {
1003                 const int *verts = node->vert_indices;
1004                 const int totvert = node->uniq_verts;
1005
1006                 for (int i = 0; i < totvert; ++i) {
1007                         const int v = verts[i];
1008                         MVert *mvert = &bvh->verts[v];
1009
1010                         /* mvert is shared between nodes, hence between threads. */
1011                         if (atomic_fetch_and_and_char(&mvert->flag, (char)~ME_VERT_PBVH_UPDATE) & ME_VERT_PBVH_UPDATE) {
1012                                 normalize_v3(vnors[v]);
1013                                 normal_float_to_short_v3(mvert->no, vnors[v]);
1014                         }
1015                 }
1016
1017                 node->flag &= ~PBVH_UpdateNormals;
1018         }
1019 }
1020
1021 static void pbvh_update_normals(PBVH *bvh, PBVHNode **nodes,
1022                                 int totnode, float (*fnors)[3])
1023 {
1024         float (*vnors)[3];
1025
1026         if (bvh->type == PBVH_BMESH) {
1027                 BLI_assert(fnors == NULL);
1028                 pbvh_bmesh_normals_update(nodes, totnode);
1029                 return;
1030         }
1031
1032         if (bvh->type != PBVH_FACES)
1033                 return;
1034
1035         /* could be per node to save some memory, but also means
1036          * we have to store for each vertex which node it is in */
1037         vnors = MEM_callocN(sizeof(*vnors) * bvh->totvert, __func__);
1038
1039         /* subtle assumptions:
1040          * - We know that for all edited vertices, the nodes with faces
1041          *   adjacent to these vertices have been marked with PBVH_UpdateNormals.
1042          *   This is true because if the vertex is inside the brush radius, the
1043          *   bounding box of it's adjacent faces will be as well.
1044          * - However this is only true for the vertices that have actually been
1045          *   edited, not for all vertices in the nodes marked for update, so we
1046          *   can only update vertices marked with ME_VERT_PBVH_UPDATE.
1047          */
1048
1049         PBVHUpdateData data = {
1050             .bvh = bvh, .nodes = nodes,
1051             .fnors = fnors, .vnors = vnors,
1052         };
1053
1054         ParallelRangeSettings settings;
1055         BLI_parallel_range_settings_defaults(&settings);
1056         settings.use_threading = (totnode > PBVH_THREADED_LIMIT);
1057
1058         BLI_task_parallel_range(0, totnode, &data, pbvh_update_normals_accum_task_cb, &settings);
1059
1060         BLI_task_parallel_range(0, totnode, &data, pbvh_update_normals_store_task_cb, &settings);
1061
1062         MEM_freeN(vnors);
1063 }
1064
1065 static void pbvh_update_BB_redraw_task_cb(
1066         void *__restrict userdata,
1067         const int n,
1068         const ParallelRangeTLS *__restrict UNUSED(tls))
1069 {
1070         PBVHUpdateData *data = userdata;
1071         PBVH *bvh = data->bvh;
1072         PBVHNode *node = data->nodes[n];
1073         const int flag = data->flag;
1074
1075         if ((flag & PBVH_UpdateBB) && (node->flag & PBVH_UpdateBB))
1076                 /* don't clear flag yet, leave it for flushing later */
1077                 /* Note that bvh usage is read-only here, so no need to thread-protect it. */
1078                 update_node_vb(bvh, node);
1079
1080         if ((flag & PBVH_UpdateOriginalBB) && (node->flag & PBVH_UpdateOriginalBB))
1081                 node->orig_vb = node->vb;
1082
1083         if ((flag & PBVH_UpdateRedraw) && (node->flag & PBVH_UpdateRedraw))
1084                 node->flag &= ~PBVH_UpdateRedraw;
1085 }
1086
1087 void pbvh_update_BB_redraw(PBVH *bvh, PBVHNode **nodes, int totnode, int flag)
1088 {
1089         /* update BB, redraw flag */
1090         PBVHUpdateData data = {
1091             .bvh = bvh, .nodes = nodes,
1092             .flag = flag,
1093         };
1094
1095         ParallelRangeSettings settings;
1096         BLI_parallel_range_settings_defaults(&settings);
1097         settings.use_threading = (totnode > PBVH_THREADED_LIMIT);
1098         BLI_task_parallel_range(0, totnode, &data, pbvh_update_BB_redraw_task_cb, &settings);
1099 }
1100
1101 static int pbvh_get_buffers_update_flags(PBVH *bvh)
1102 {
1103         int update_flags = 0;
1104         update_flags |= bvh->show_mask ? GPU_PBVH_BUFFERS_SHOW_MASK : 0;
1105         return update_flags;
1106 }
1107
1108 static void pbvh_update_draw_buffers(PBVH *bvh, PBVHNode **nodes, int totnode)
1109 {
1110         /* can't be done in parallel with OpenGL */
1111         for (int n = 0; n < totnode; n++) {
1112                 PBVHNode *node = nodes[n];
1113
1114                 if (node->flag & PBVH_RebuildDrawBuffers) {
1115                         GPU_pbvh_buffers_free(node->draw_buffers);
1116                         switch (bvh->type) {
1117                                 case PBVH_GRIDS:
1118                                         node->draw_buffers =
1119                                                 GPU_pbvh_grid_buffers_build(
1120                                                         node->prim_indices,
1121                                                         node->totprim,
1122                                                         bvh->grid_hidden,
1123                                                         bvh->gridkey.grid_size,
1124                                                         &bvh->gridkey);
1125                                         break;
1126                                 case PBVH_FACES:
1127                                         node->draw_buffers =
1128                                                 GPU_pbvh_mesh_buffers_build(
1129                                                         node->face_vert_indices,
1130                                                         bvh->mpoly, bvh->mloop, bvh->looptri,
1131                                                         bvh->verts,
1132                                                         node->prim_indices,
1133                                                         node->totprim);
1134                                         break;
1135                                 case PBVH_BMESH:
1136                                         node->draw_buffers =
1137                                                 GPU_pbvh_bmesh_buffers_build(bvh->flags & PBVH_DYNTOPO_SMOOTH_SHADING);
1138                                         break;
1139                         }
1140
1141                         node->flag &= ~PBVH_RebuildDrawBuffers;
1142                 }
1143
1144                 if (node->flag & PBVH_UpdateDrawBuffers) {
1145                         const int update_flags = pbvh_get_buffers_update_flags(bvh);
1146                         switch (bvh->type) {
1147                                 case PBVH_GRIDS:
1148                                         GPU_pbvh_grid_buffers_update(
1149                                                 node->draw_buffers,
1150                                                 bvh->grids,
1151                                                 bvh->grid_flag_mats,
1152                                                 node->prim_indices,
1153                                                 node->totprim,
1154                                                 &bvh->gridkey,
1155                                                 update_flags);
1156                                         break;
1157                                 case PBVH_FACES:
1158                                         GPU_pbvh_mesh_buffers_update(
1159                                                 node->draw_buffers,
1160                                                 bvh->verts,
1161                                                 node->vert_indices,
1162                                                 node->uniq_verts +
1163                                                 node->face_verts,
1164                                                 CustomData_get_layer(bvh->vdata, CD_PAINT_MASK),
1165                                                 node->face_vert_indices,
1166                                                 update_flags);
1167                                         break;
1168                                 case PBVH_BMESH:
1169                                         GPU_pbvh_bmesh_buffers_update(
1170                                                 node->draw_buffers,
1171                                                 bvh->bm,
1172                                                 node->bm_faces,
1173                                                 node->bm_unique_verts,
1174                                                 node->bm_other_verts,
1175                                                 update_flags);
1176                                         break;
1177                         }
1178
1179                         node->flag &= ~PBVH_UpdateDrawBuffers;
1180                 }
1181         }
1182 }
1183
1184 static int pbvh_flush_bb(PBVH *bvh, PBVHNode *node, int flag)
1185 {
1186         int update = 0;
1187
1188         /* difficult to multithread well, we just do single threaded recursive */
1189         if (node->flag & PBVH_Leaf) {
1190                 if (flag & PBVH_UpdateBB) {
1191                         update |= (node->flag & PBVH_UpdateBB);
1192                         node->flag &= ~PBVH_UpdateBB;
1193                 }
1194
1195                 if (flag & PBVH_UpdateOriginalBB) {
1196                         update |= (node->flag & PBVH_UpdateOriginalBB);
1197                         node->flag &= ~PBVH_UpdateOriginalBB;
1198                 }
1199
1200                 return update;
1201         }
1202         else {
1203                 update |= pbvh_flush_bb(bvh, bvh->nodes + node->children_offset, flag);
1204                 update |= pbvh_flush_bb(bvh, bvh->nodes + node->children_offset + 1, flag);
1205
1206                 if (update & PBVH_UpdateBB)
1207                         update_node_vb(bvh, node);
1208                 if (update & PBVH_UpdateOriginalBB)
1209                         node->orig_vb = node->vb;
1210         }
1211
1212         return update;
1213 }
1214
1215 void BKE_pbvh_update(PBVH *bvh, int flag, float (*fnors)[3])
1216 {
1217         if (!bvh->nodes)
1218                 return;
1219
1220         PBVHNode **nodes;
1221         int totnode;
1222
1223         BKE_pbvh_search_gather(bvh, update_search_cb, POINTER_FROM_INT(flag),
1224                                &nodes, &totnode);
1225
1226         if (flag & PBVH_UpdateNormals)
1227                 pbvh_update_normals(bvh, nodes, totnode, fnors);
1228
1229         if (flag & (PBVH_UpdateBB | PBVH_UpdateOriginalBB | PBVH_UpdateRedraw))
1230                 pbvh_update_BB_redraw(bvh, nodes, totnode, flag);
1231
1232         if (flag & (PBVH_UpdateBB | PBVH_UpdateOriginalBB))
1233                 pbvh_flush_bb(bvh, bvh->nodes, flag);
1234
1235         if (nodes) MEM_freeN(nodes);
1236 }
1237
1238 void BKE_pbvh_redraw_BB(PBVH *bvh, float bb_min[3], float bb_max[3])
1239 {
1240         PBVHIter iter;
1241         PBVHNode *node;
1242         BB bb;
1243
1244         BB_reset(&bb);
1245
1246         pbvh_iter_begin(&iter, bvh, NULL, NULL);
1247
1248         while ((node = pbvh_iter_next(&iter)))
1249                 if (node->flag & PBVH_UpdateRedraw)
1250                         BB_expand_with_bb(&bb, &node->vb);
1251
1252         pbvh_iter_end(&iter);
1253
1254         copy_v3_v3(bb_min, bb.bmin);
1255         copy_v3_v3(bb_max, bb.bmax);
1256 }
1257
1258 void BKE_pbvh_get_grid_updates(PBVH *bvh, bool clear, void ***r_gridfaces, int *r_totface)
1259 {
1260         GSet *face_set = BLI_gset_ptr_new(__func__);
1261         PBVHNode *node;
1262         PBVHIter iter;
1263
1264         pbvh_iter_begin(&iter, bvh, NULL, NULL);
1265
1266         while ((node = pbvh_iter_next(&iter))) {
1267                 if (node->flag & PBVH_UpdateNormals) {
1268                         for (unsigned i = 0; i < node->totprim; ++i) {
1269                                 void *face = bvh->gridfaces[node->prim_indices[i]];
1270                                 BLI_gset_add(face_set, face);
1271                         }
1272
1273                         if (clear)
1274                                 node->flag &= ~PBVH_UpdateNormals;
1275                 }
1276         }
1277
1278         pbvh_iter_end(&iter);
1279
1280         const int tot = BLI_gset_len(face_set);
1281         if (tot == 0) {
1282                 *r_totface = 0;
1283                 *r_gridfaces = NULL;
1284                 BLI_gset_free(face_set, NULL);
1285                 return;
1286         }
1287
1288         void **faces = MEM_mallocN(sizeof(*faces) * tot, "PBVH Grid Faces");
1289
1290         GSetIterator gs_iter;
1291         int i;
1292         GSET_ITER_INDEX (gs_iter, face_set, i) {
1293                 faces[i] = BLI_gsetIterator_getKey(&gs_iter);
1294         }
1295
1296         BLI_gset_free(face_set, NULL);
1297
1298         *r_totface = tot;
1299         *r_gridfaces = faces;
1300 }
1301
1302 /***************************** PBVH Access ***********************************/
1303
1304 PBVHType BKE_pbvh_type(const PBVH *bvh)
1305 {
1306         return bvh->type;
1307 }
1308
1309 bool BKE_pbvh_has_faces(const PBVH *bvh)
1310 {
1311         if (bvh->type == PBVH_BMESH) {
1312                 return (bvh->bm->totface != 0);
1313         }
1314         else {
1315                 return (bvh->totprim != 0);
1316         }
1317 }
1318
1319 void BKE_pbvh_bounding_box(const PBVH *bvh, float min[3], float max[3])
1320 {
1321         if (bvh->totnode) {
1322                 const BB *bb = &bvh->nodes[0].vb;
1323                 copy_v3_v3(min, bb->bmin);
1324                 copy_v3_v3(max, bb->bmax);
1325         }
1326         else {
1327                 zero_v3(min);
1328                 zero_v3(max);
1329         }
1330 }
1331
1332 BLI_bitmap **BKE_pbvh_grid_hidden(const PBVH *bvh)
1333 {
1334         BLI_assert(bvh->type == PBVH_GRIDS);
1335         return bvh->grid_hidden;
1336 }
1337
1338 void BKE_pbvh_get_grid_key(const PBVH *bvh, CCGKey *key)
1339 {
1340         BLI_assert(bvh->type == PBVH_GRIDS);
1341         *key = bvh->gridkey;
1342 }
1343
1344 struct CCGElem **BKE_pbvh_get_grids(const PBVH *bvh, int *num_grids)
1345 {
1346         BLI_assert(bvh->type == PBVH_GRIDS);
1347         *num_grids = bvh->totgrid;
1348         return bvh->grids;
1349 }
1350
1351 BMesh *BKE_pbvh_get_bmesh(PBVH *bvh)
1352 {
1353         BLI_assert(bvh->type == PBVH_BMESH);
1354         return bvh->bm;
1355 }
1356
1357 /***************************** Node Access ***********************************/
1358
1359 void BKE_pbvh_node_mark_update(PBVHNode *node)
1360 {
1361         node->flag |= PBVH_UpdateNormals | PBVH_UpdateBB | PBVH_UpdateOriginalBB | PBVH_UpdateDrawBuffers | PBVH_UpdateRedraw;
1362 }
1363
1364 void BKE_pbvh_node_mark_rebuild_draw(PBVHNode *node)
1365 {
1366         node->flag |= PBVH_RebuildDrawBuffers | PBVH_UpdateDrawBuffers | PBVH_UpdateRedraw;
1367 }
1368
1369 void BKE_pbvh_node_mark_redraw(PBVHNode *node)
1370 {
1371         node->flag |= PBVH_UpdateDrawBuffers | PBVH_UpdateRedraw;
1372 }
1373
1374 void BKE_pbvh_node_mark_normals_update(PBVHNode *node)
1375 {
1376         node->flag |= PBVH_UpdateNormals;
1377 }
1378
1379
1380 void BKE_pbvh_node_fully_hidden_set(PBVHNode *node, int fully_hidden)
1381 {
1382         BLI_assert(node->flag & PBVH_Leaf);
1383
1384         if (fully_hidden)
1385                 node->flag |= PBVH_FullyHidden;
1386         else
1387                 node->flag &= ~PBVH_FullyHidden;
1388 }
1389
1390 void BKE_pbvh_node_get_verts(
1391         PBVH *bvh, PBVHNode *node,
1392         const int **r_vert_indices, MVert **r_verts)
1393 {
1394         if (r_vert_indices) {
1395                 *r_vert_indices = node->vert_indices;
1396         }
1397
1398         if (r_verts) {
1399                 *r_verts = bvh->verts;
1400         }
1401 }
1402
1403 void BKE_pbvh_node_num_verts(
1404         PBVH *bvh, PBVHNode *node,
1405         int *r_uniquevert, int *r_totvert)
1406 {
1407         int tot;
1408
1409         switch (bvh->type) {
1410                 case PBVH_GRIDS:
1411                         tot = node->totprim * bvh->gridkey.grid_area;
1412                         if (r_totvert) *r_totvert = tot;
1413                         if (r_uniquevert) *r_uniquevert = tot;
1414                         break;
1415                 case PBVH_FACES:
1416                         if (r_totvert) *r_totvert = node->uniq_verts + node->face_verts;
1417                         if (r_uniquevert) *r_uniquevert = node->uniq_verts;
1418                         break;
1419                 case PBVH_BMESH:
1420                         tot = BLI_gset_len(node->bm_unique_verts);
1421                         if (r_totvert) *r_totvert = tot + BLI_gset_len(node->bm_other_verts);
1422                         if (r_uniquevert) *r_uniquevert = tot;
1423                         break;
1424         }
1425 }
1426
1427 void BKE_pbvh_node_get_grids(
1428         PBVH *bvh, PBVHNode *node,
1429         int **r_grid_indices, int *r_totgrid, int *r_maxgrid, int *r_gridsize, CCGElem ***r_griddata)
1430 {
1431         switch (bvh->type) {
1432                 case PBVH_GRIDS:
1433                         if (r_grid_indices) *r_grid_indices = node->prim_indices;
1434                         if (r_totgrid) *r_totgrid = node->totprim;
1435                         if (r_maxgrid) *r_maxgrid = bvh->totgrid;
1436                         if (r_gridsize) *r_gridsize = bvh->gridkey.grid_size;
1437                         if (r_griddata) *r_griddata = bvh->grids;
1438                         break;
1439                 case PBVH_FACES:
1440                 case PBVH_BMESH:
1441                         if (r_grid_indices) *r_grid_indices = NULL;
1442                         if (r_totgrid) *r_totgrid = 0;
1443                         if (r_maxgrid) *r_maxgrid = 0;
1444                         if (r_gridsize) *r_gridsize = 0;
1445                         if (r_griddata) *r_griddata = NULL;
1446                         break;
1447         }
1448 }
1449
1450 void BKE_pbvh_node_get_BB(PBVHNode *node, float bb_min[3], float bb_max[3])
1451 {
1452         copy_v3_v3(bb_min, node->vb.bmin);
1453         copy_v3_v3(bb_max, node->vb.bmax);
1454 }
1455
1456 void BKE_pbvh_node_get_original_BB(PBVHNode *node, float bb_min[3], float bb_max[3])
1457 {
1458         copy_v3_v3(bb_min, node->orig_vb.bmin);
1459         copy_v3_v3(bb_max, node->orig_vb.bmax);
1460 }
1461
1462 void BKE_pbvh_node_get_proxies(PBVHNode *node, PBVHProxyNode **proxies, int *proxy_count)
1463 {
1464         if (node->proxy_count > 0) {
1465                 if (proxies) *proxies = node->proxies;
1466                 if (proxy_count) *proxy_count = node->proxy_count;
1467         }
1468         else {
1469                 if (proxies) *proxies = NULL;
1470                 if (proxy_count) *proxy_count = 0;
1471         }
1472 }
1473
1474 void BKE_pbvh_node_get_bm_orco_data(
1475         PBVHNode *node,
1476         int (**r_orco_tris)[3], int *r_orco_tris_num, float (**r_orco_coords)[3])
1477 {
1478         *r_orco_tris = node->bm_ortri;
1479         *r_orco_tris_num = node->bm_tot_ortri;
1480         *r_orco_coords = node->bm_orco;
1481 }
1482
1483 /**
1484  * \note doing a full search on all vertices here seems expensive,
1485  * however this is important to avoid having to recalculate boundbox & sync the buffers to the GPU
1486  * (which is far more expensive!) See: T47232.
1487  */
1488 bool BKE_pbvh_node_vert_update_check_any(PBVH *bvh, PBVHNode *node)
1489 {
1490         BLI_assert(bvh->type == PBVH_FACES);
1491         const int *verts = node->vert_indices;
1492         const int totvert = node->uniq_verts + node->face_verts;
1493
1494         for (int i = 0; i < totvert; ++i) {
1495                 const int v = verts[i];
1496                 const MVert *mvert = &bvh->verts[v];
1497
1498                 if (mvert->flag & ME_VERT_PBVH_UPDATE) {
1499                         return true;
1500                 }
1501         }
1502
1503         return false;
1504 }
1505
1506
1507 /********************************* Raycast ***********************************/
1508
1509 typedef struct {
1510         struct IsectRayAABB_Precalc ray;
1511         bool original;
1512 } RaycastData;
1513
1514 static bool ray_aabb_intersect(PBVHNode *node, void *data_v)
1515 {
1516         RaycastData *rcd = data_v;
1517         const float *bb_min, *bb_max;
1518
1519         if (rcd->original) {
1520                 /* BKE_pbvh_node_get_original_BB */
1521                 bb_min = node->orig_vb.bmin;
1522                 bb_max = node->orig_vb.bmax;
1523         }
1524         else {
1525                 /* BKE_pbvh_node_get_BB */
1526                 bb_min = node->vb.bmin;
1527                 bb_max = node->vb.bmax;
1528         }
1529
1530         return isect_ray_aabb_v3(&rcd->ray, bb_min, bb_max, &node->tmin);
1531 }
1532
1533 void BKE_pbvh_raycast(
1534         PBVH *bvh, BKE_pbvh_HitOccludedCallback cb, void *data,
1535         const float ray_start[3], const float ray_normal[3],
1536         bool original)
1537 {
1538         RaycastData rcd;
1539
1540         isect_ray_aabb_v3_precalc(&rcd.ray, ray_start, ray_normal);
1541         rcd.original = original;
1542
1543         BKE_pbvh_search_callback_occluded(bvh, ray_aabb_intersect, &rcd, cb, data);
1544 }
1545
1546 bool ray_face_intersection_quad(
1547         const float ray_start[3], const float ray_normal[3],
1548         const float t0[3], const float t1[3], const float t2[3], const float t3[3],
1549         float *depth)
1550 {
1551         float depth_test;
1552
1553         if ((isect_ray_tri_epsilon_v3(
1554                  ray_start, ray_normal, t0, t1, t2, &depth_test, NULL, 0.1f) && (depth_test < *depth)) ||
1555             (isect_ray_tri_epsilon_v3(
1556                  ray_start, ray_normal, t0, t2, t3, &depth_test, NULL, 0.1f) && (depth_test < *depth)))
1557         {
1558                 *depth = depth_test;
1559                 return true;
1560         }
1561         else {
1562                 return false;
1563         }
1564 }
1565
1566 bool ray_face_intersection_tri(
1567         const float ray_start[3], const float ray_normal[3],
1568         const float t0[3], const float t1[3], const float t2[3],
1569         float *depth)
1570 {
1571         float depth_test;
1572
1573         if ((isect_ray_tri_epsilon_v3(
1574                  ray_start, ray_normal, t0, t1, t2, &depth_test, NULL, 0.1f) && (depth_test < *depth)))
1575         {
1576                 *depth = depth_test;
1577                 return true;
1578         }
1579         else {
1580                 return false;
1581         }
1582 }
1583
1584 /* Take advantage of the fact we know this wont be an intersection.
1585  * Just handle ray-tri edges. */
1586 static float dist_squared_ray_to_tri_v3_fast(
1587         const float ray_origin[3], const float ray_direction[3],
1588         const float v0[3], const float v1[3], const float v2[3],
1589         float r_point[3], float *r_depth)
1590 {
1591         const float *tri[3] = {v0, v1, v2};
1592         float dist_sq_best = FLT_MAX;
1593         for (int i = 0, j = 2; i < 3; j = i++) {
1594                 float point_test[3], depth_test = FLT_MAX;
1595                 const float dist_sq_test = dist_squared_ray_to_seg_v3(
1596                         ray_origin, ray_direction, tri[i], tri[j], point_test, &depth_test);
1597                 if (dist_sq_test < dist_sq_best || i == 0) {
1598                         copy_v3_v3(r_point, point_test);
1599                         *r_depth = depth_test;
1600                         dist_sq_best = dist_sq_test;
1601                 }
1602         }
1603         return dist_sq_best;
1604 }
1605
1606 bool ray_face_nearest_quad(
1607         const float ray_start[3], const float ray_normal[3],
1608         const float t0[3], const float t1[3], const float t2[3], const float t3[3],
1609         float *depth, float *dist_sq)
1610 {
1611         float dist_sq_test;
1612         float co[3], depth_test;
1613
1614         if (((dist_sq_test = dist_squared_ray_to_tri_v3_fast(
1615                  ray_start, ray_normal, t0, t1, t2, co, &depth_test)) < *dist_sq))
1616         {
1617                 *dist_sq = dist_sq_test;
1618                 *depth = depth_test;
1619                 if (((dist_sq_test = dist_squared_ray_to_tri_v3_fast(
1620                          ray_start, ray_normal, t0, t2, t3, co, &depth_test)) < *dist_sq))
1621                 {
1622                         *dist_sq = dist_sq_test;
1623                         *depth = depth_test;
1624                 }
1625                 return true;
1626         }
1627         else {
1628                 return false;
1629         }
1630 }
1631
1632 bool ray_face_nearest_tri(
1633         const float ray_start[3], const float ray_normal[3],
1634         const float t0[3], const float t1[3], const float t2[3],
1635         float *depth, float *dist_sq)
1636 {
1637         float dist_sq_test;
1638         float co[3], depth_test;
1639
1640         if (((dist_sq_test = dist_squared_ray_to_tri_v3_fast(
1641                  ray_start, ray_normal, t0, t1, t2, co, &depth_test)) < *dist_sq))
1642         {
1643                 *dist_sq = dist_sq_test;
1644                 *depth = depth_test;
1645                 return true;
1646         }
1647         else {
1648                 return false;
1649         }
1650 }
1651
1652 static bool pbvh_faces_node_raycast(
1653         PBVH *bvh, const PBVHNode *node,
1654         float (*origco)[3],
1655         const float ray_start[3], const float ray_normal[3],
1656         float *depth)
1657 {
1658         const MVert *vert = bvh->verts;
1659         const MLoop *mloop = bvh->mloop;
1660         const int *faces = node->prim_indices;
1661         int i, totface = node->totprim;
1662         bool hit = false;
1663
1664         for (i = 0; i < totface; ++i) {
1665                 const MLoopTri *lt = &bvh->looptri[faces[i]];
1666                 const int *face_verts = node->face_vert_indices[i];
1667
1668                 if (paint_is_face_hidden(lt, vert, mloop))
1669                         continue;
1670
1671                 if (origco) {
1672                         /* intersect with backuped original coordinates */
1673                         hit |= ray_face_intersection_tri(
1674                                 ray_start, ray_normal,
1675                                 origco[face_verts[0]],
1676                                 origco[face_verts[1]],
1677                                 origco[face_verts[2]],
1678                                 depth);
1679                 }
1680                 else {
1681                         /* intersect with current coordinates */
1682                         hit |= ray_face_intersection_tri(
1683                                 ray_start, ray_normal,
1684                                 vert[mloop[lt->tri[0]].v].co,
1685                                 vert[mloop[lt->tri[1]].v].co,
1686                                 vert[mloop[lt->tri[2]].v].co,
1687                                 depth);
1688                 }
1689         }
1690
1691         return hit;
1692 }
1693
1694 static bool pbvh_grids_node_raycast(
1695         PBVH *bvh, PBVHNode *node,
1696         float (*origco)[3],
1697         const float ray_start[3], const float ray_normal[3],
1698         float *depth)
1699 {
1700         const int totgrid = node->totprim;
1701         const int gridsize = bvh->gridkey.grid_size;
1702         bool hit = false;
1703
1704         for (int i = 0; i < totgrid; ++i) {
1705                 CCGElem *grid = bvh->grids[node->prim_indices[i]];
1706                 BLI_bitmap *gh;
1707
1708                 if (!grid)
1709                         continue;
1710
1711                 gh = bvh->grid_hidden[node->prim_indices[i]];
1712
1713                 for (int y = 0; y < gridsize - 1; ++y) {
1714                         for (int x = 0; x < gridsize - 1; ++x) {
1715                                 /* check if grid face is hidden */
1716                                 if (gh) {
1717                                         if (paint_is_grid_face_hidden(gh, gridsize, x, y))
1718                                                 continue;
1719                                 }
1720
1721                                 if (origco) {
1722                                         hit |= ray_face_intersection_quad(
1723                                                 ray_start, ray_normal,
1724                                                 origco[y * gridsize + x],
1725                                                 origco[y * gridsize + x + 1],
1726                                                 origco[(y + 1) * gridsize + x + 1],
1727                                                 origco[(y + 1) * gridsize + x],
1728                                                 depth);
1729                                 }
1730                                 else {
1731                                         hit |= ray_face_intersection_quad(
1732                                                 ray_start, ray_normal,
1733                                                 CCG_grid_elem_co(&bvh->gridkey, grid, x, y),
1734                                                 CCG_grid_elem_co(&bvh->gridkey, grid, x + 1, y),
1735                                                 CCG_grid_elem_co(&bvh->gridkey, grid, x + 1, y + 1),
1736                                                 CCG_grid_elem_co(&bvh->gridkey, grid, x, y + 1),
1737                                                 depth);
1738                                 }
1739                         }
1740                 }
1741
1742                 if (origco)
1743                         origco += gridsize * gridsize;
1744         }
1745
1746         return hit;
1747 }
1748
1749 bool BKE_pbvh_node_raycast(
1750         PBVH *bvh, PBVHNode *node, float (*origco)[3], bool use_origco,
1751         const float ray_start[3], const float ray_normal[3],
1752         float *depth)
1753 {
1754         bool hit = false;
1755
1756         if (node->flag & PBVH_FullyHidden)
1757                 return false;
1758
1759         switch (bvh->type) {
1760                 case PBVH_FACES:
1761                         hit |= pbvh_faces_node_raycast(
1762                                 bvh, node, origco,
1763                                 ray_start, ray_normal, depth);
1764                         break;
1765                 case PBVH_GRIDS:
1766                         hit |= pbvh_grids_node_raycast(
1767                                 bvh, node, origco,
1768                                 ray_start, ray_normal, depth);
1769                         break;
1770                 case PBVH_BMESH:
1771                         hit = pbvh_bmesh_node_raycast(
1772                                 node, ray_start, ray_normal, depth, use_origco);
1773                         break;
1774         }
1775
1776         return hit;
1777 }
1778
1779 void BKE_pbvh_raycast_project_ray_root(
1780         PBVH *bvh, bool original,
1781         float ray_start[3], float ray_end[3], float ray_normal[3])
1782 {
1783         if (bvh->nodes) {
1784                 float rootmin_start, rootmin_end;
1785                 float bb_min_root[3], bb_max_root[3], bb_center[3], bb_diff[3];
1786                 struct IsectRayAABB_Precalc ray;
1787                 float ray_normal_inv[3];
1788                 float offset = 1.0f + 1e-3f;
1789                 float offset_vec[3] = {1e-3f, 1e-3f, 1e-3f};
1790
1791                 if (original)
1792                         BKE_pbvh_node_get_original_BB(bvh->nodes, bb_min_root, bb_max_root);
1793                 else
1794                         BKE_pbvh_node_get_BB(bvh->nodes, bb_min_root, bb_max_root);
1795
1796                 /* slightly offset min and max in case we have a zero width node (due to a plane mesh for instance),
1797                  * or faces very close to the bounding box boundary. */
1798                 mid_v3_v3v3(bb_center, bb_max_root, bb_min_root);
1799                 /* diff should be same for both min/max since it's calculated from center */
1800                 sub_v3_v3v3(bb_diff, bb_max_root, bb_center);
1801                 /* handles case of zero width bb */
1802                 add_v3_v3(bb_diff, offset_vec);
1803                 madd_v3_v3v3fl(bb_max_root, bb_center, bb_diff, offset);
1804                 madd_v3_v3v3fl(bb_min_root, bb_center, bb_diff, -offset);
1805
1806                 /* first project start ray */
1807                 isect_ray_aabb_v3_precalc(&ray, ray_start, ray_normal);
1808                 if (!isect_ray_aabb_v3(&ray, bb_min_root, bb_max_root, &rootmin_start))
1809                         return;
1810
1811                 /* then the end ray */
1812                 mul_v3_v3fl(ray_normal_inv, ray_normal, -1.0);
1813                 isect_ray_aabb_v3_precalc(&ray, ray_end, ray_normal_inv);
1814                 /* unlikely to fail exiting if entering succeeded, still keep this here */
1815                 if (!isect_ray_aabb_v3(&ray, bb_min_root, bb_max_root, &rootmin_end))
1816                         return;
1817
1818                 madd_v3_v3v3fl(ray_start, ray_start, ray_normal, rootmin_start);
1819                 madd_v3_v3v3fl(ray_end, ray_end, ray_normal_inv, rootmin_end);
1820         }
1821 }
1822
1823 /* -------------------------------------------------------------------- */
1824
1825 typedef struct {
1826         struct DistRayAABB_Precalc dist_ray_to_aabb_precalc;
1827         bool original;
1828 } FindNearestRayData;
1829
1830 static bool nearest_to_ray_aabb_dist_sq(PBVHNode *node, void *data_v)
1831 {
1832         FindNearestRayData *rcd = data_v;
1833         const float *bb_min, *bb_max;
1834
1835         if (rcd->original) {
1836                 /* BKE_pbvh_node_get_original_BB */
1837                 bb_min = node->orig_vb.bmin;
1838                 bb_max = node->orig_vb.bmax;
1839         }
1840         else {
1841                 /* BKE_pbvh_node_get_BB */
1842                 bb_min = node->vb.bmin;
1843                 bb_max = node->vb.bmax;
1844         }
1845
1846         float co_dummy[3], depth;
1847         node->tmin = dist_squared_ray_to_aabb_v3(&rcd->dist_ray_to_aabb_precalc, bb_min, bb_max, co_dummy, &depth);
1848         /* Ideally we would skip distances outside the range. */
1849         return depth > 0.0f;
1850 }
1851
1852 void BKE_pbvh_find_nearest_to_ray(
1853         PBVH *bvh, BKE_pbvh_SearchNearestCallback cb, void *data,
1854         const float ray_start[3], const float ray_normal[3],
1855         bool original)
1856 {
1857         FindNearestRayData ncd;
1858
1859         dist_squared_ray_to_aabb_v3_precalc(&ncd.dist_ray_to_aabb_precalc, ray_start, ray_normal);
1860         ncd.original = original;
1861
1862         BKE_pbvh_search_callback_occluded(bvh, nearest_to_ray_aabb_dist_sq, &ncd, cb, data);
1863 }
1864
1865
1866 static bool pbvh_faces_node_nearest_to_ray(
1867         PBVH *bvh, const PBVHNode *node,
1868         float (*origco)[3],
1869         const float ray_start[3], const float ray_normal[3],
1870         float *depth, float *dist_sq)
1871 {
1872         const MVert *vert = bvh->verts;
1873         const MLoop *mloop = bvh->mloop;
1874         const int *faces = node->prim_indices;
1875         int i, totface = node->totprim;
1876         bool hit = false;
1877
1878         for (i = 0; i < totface; ++i) {
1879                 const MLoopTri *lt = &bvh->looptri[faces[i]];
1880                 const int *face_verts = node->face_vert_indices[i];
1881
1882                 if (paint_is_face_hidden(lt, vert, mloop))
1883                         continue;
1884
1885                 if (origco) {
1886                         /* intersect with backuped original coordinates */
1887                         hit |= ray_face_nearest_tri(
1888                                 ray_start, ray_normal,
1889                                 origco[face_verts[0]],
1890                                 origco[face_verts[1]],
1891                                 origco[face_verts[2]],
1892                                 depth, dist_sq);
1893                 }
1894                 else {
1895                         /* intersect with current coordinates */
1896                         hit |= ray_face_nearest_tri(
1897                                 ray_start, ray_normal,
1898                                 vert[mloop[lt->tri[0]].v].co,
1899                                 vert[mloop[lt->tri[1]].v].co,
1900                                 vert[mloop[lt->tri[2]].v].co,
1901                                 depth, dist_sq);
1902                 }
1903         }
1904
1905         return hit;
1906 }
1907
1908 static bool pbvh_grids_node_nearest_to_ray(
1909         PBVH *bvh, PBVHNode *node,
1910         float (*origco)[3],
1911         const float ray_start[3], const float ray_normal[3],
1912         float *depth, float *dist_sq)
1913 {
1914         const int totgrid = node->totprim;
1915         const int gridsize = bvh->gridkey.grid_size;
1916         bool hit = false;
1917
1918         for (int i = 0; i < totgrid; ++i) {
1919                 CCGElem *grid = bvh->grids[node->prim_indices[i]];
1920                 BLI_bitmap *gh;
1921
1922                 if (!grid)
1923                         continue;
1924
1925                 gh = bvh->grid_hidden[node->prim_indices[i]];
1926
1927                 for (int y = 0; y < gridsize - 1; ++y) {
1928                         for (int x = 0; x < gridsize - 1; ++x) {
1929                                 /* check if grid face is hidden */
1930                                 if (gh) {
1931                                         if (paint_is_grid_face_hidden(gh, gridsize, x, y))
1932                                                 continue;
1933                                 }
1934
1935                                 if (origco) {
1936                                         hit |= ray_face_nearest_quad(
1937                                                 ray_start, ray_normal,
1938                                                 origco[y * gridsize + x],
1939                                                 origco[y * gridsize + x + 1],
1940                                                 origco[(y + 1) * gridsize + x + 1],
1941                                                 origco[(y + 1) * gridsize + x],
1942                                                 depth, dist_sq);
1943                                 }
1944                                 else {
1945                                         hit |= ray_face_nearest_quad(
1946                                                 ray_start, ray_normal,
1947                                                 CCG_grid_elem_co(&bvh->gridkey, grid, x, y),
1948                                                 CCG_grid_elem_co(&bvh->gridkey, grid, x + 1, y),
1949                                                 CCG_grid_elem_co(&bvh->gridkey, grid, x + 1, y + 1),
1950                                                 CCG_grid_elem_co(&bvh->gridkey, grid, x, y + 1),
1951                                                 depth, dist_sq);
1952                                 }
1953                         }
1954                 }
1955
1956                 if (origco)
1957                         origco += gridsize * gridsize;
1958         }
1959
1960         return hit;
1961 }
1962
1963 bool BKE_pbvh_node_find_nearest_to_ray(
1964         PBVH *bvh, PBVHNode *node, float (*origco)[3], bool use_origco,
1965         const float ray_start[3], const float ray_normal[3],
1966         float *depth, float *dist_sq)
1967 {
1968         bool hit = false;
1969
1970         if (node->flag & PBVH_FullyHidden)
1971                 return false;
1972
1973         switch (bvh->type) {
1974                 case PBVH_FACES:
1975                         hit |= pbvh_faces_node_nearest_to_ray(
1976                                 bvh, node, origco,
1977                                 ray_start, ray_normal, depth, dist_sq);
1978                         break;
1979                 case PBVH_GRIDS:
1980                         hit |= pbvh_grids_node_nearest_to_ray(
1981                                 bvh, node, origco,
1982                                 ray_start, ray_normal, depth, dist_sq);
1983                         break;
1984                 case PBVH_BMESH:
1985                         hit = pbvh_bmesh_node_nearest_to_ray(
1986                                 node, ray_start, ray_normal, depth, dist_sq, use_origco);
1987                         break;
1988         }
1989
1990         return hit;
1991 }
1992
1993 typedef enum {
1994         ISECT_INSIDE,
1995         ISECT_OUTSIDE,
1996         ISECT_INTERSECT
1997 } PlaneAABBIsect;
1998
1999 /* Adapted from:
2000  * http://www.gamedev.net/community/forums/topic.asp?topic_id=512123
2001  * Returns true if the AABB is at least partially within the frustum
2002  * (ok, not a real frustum), false otherwise.
2003  */
2004 static PlaneAABBIsect test_planes_aabb(const float bb_min[3],
2005                                        const float bb_max[3],
2006                                        const float (*planes)[4])
2007 {
2008         float vmin[3], vmax[3];
2009         PlaneAABBIsect ret = ISECT_INSIDE;
2010
2011         for (int i = 0; i < 4; ++i) {
2012                 for (int axis = 0; axis < 3; ++axis) {
2013                         if (planes[i][axis] > 0) {
2014                                 vmin[axis] = bb_min[axis];
2015                                 vmax[axis] = bb_max[axis];
2016                         }
2017                         else {
2018                                 vmin[axis] = bb_max[axis];
2019                                 vmax[axis] = bb_min[axis];
2020                         }
2021                 }
2022
2023                 if (dot_v3v3(planes[i], vmin) + planes[i][3] > 0)
2024                         return ISECT_OUTSIDE;
2025                 else if (dot_v3v3(planes[i], vmax) + planes[i][3] >= 0)
2026                         ret = ISECT_INTERSECT;
2027         }
2028
2029         return ret;
2030 }
2031
2032 bool BKE_pbvh_node_planes_contain_AABB(PBVHNode *node, void *data)
2033 {
2034         const float *bb_min, *bb_max;
2035         /* BKE_pbvh_node_get_BB */
2036         bb_min = node->vb.bmin;
2037         bb_max = node->vb.bmax;
2038
2039         return test_planes_aabb(bb_min, bb_max, data) != ISECT_OUTSIDE;
2040 }
2041
2042 bool BKE_pbvh_node_planes_exclude_AABB(PBVHNode *node, void *data)
2043 {
2044         const float *bb_min, *bb_max;
2045         /* BKE_pbvh_node_get_BB */
2046         bb_min = node->vb.bmin;
2047         bb_max = node->vb.bmax;
2048
2049         return test_planes_aabb(bb_min, bb_max, data) != ISECT_INSIDE;
2050 }
2051
2052 struct PBVHNodeDrawCallbackData {
2053         void (*draw_fn)(void *user_data, GPUBatch *batch);
2054         void *user_data;
2055         bool fast;
2056         bool only_mask; /* Only draw nodes that have mask data. */
2057 };
2058
2059 static void pbvh_node_draw_cb(PBVHNode *node, void *data_v)
2060 {
2061         struct PBVHNodeDrawCallbackData *data = data_v;
2062
2063         if (!(node->flag & PBVH_FullyHidden)) {
2064                 GPUBatch *triangles = GPU_pbvh_buffers_batch_get(node->draw_buffers, data->fast);
2065                 bool show_mask = GPU_pbvh_buffers_has_mask(node->draw_buffers);
2066                 if (!data->only_mask || show_mask) {
2067                         if (triangles != NULL) {
2068                                 data->draw_fn(data->user_data, triangles);
2069                         }
2070                 }
2071         }
2072 }
2073
2074 /**
2075  * Version of #BKE_pbvh_draw that runs a callback.
2076  */
2077 void BKE_pbvh_draw_cb(
2078         PBVH *bvh, float (*planes)[4], float (*fnors)[3], bool fast, bool only_mask,
2079         void (*draw_fn)(void *user_data, GPUBatch *batch), void *user_data)
2080 {
2081         struct PBVHNodeDrawCallbackData draw_data = {
2082                 .only_mask = only_mask,
2083                 .fast = fast,
2084                 .draw_fn = draw_fn,
2085                 .user_data = user_data,
2086         };
2087         PBVHNode **nodes;
2088         int totnode;
2089
2090         BKE_pbvh_search_gather(bvh, update_search_cb, POINTER_FROM_INT(PBVH_UpdateNormals | PBVH_UpdateDrawBuffers),
2091                                &nodes, &totnode);
2092
2093         pbvh_update_normals(bvh, nodes, totnode, fnors);
2094         pbvh_update_draw_buffers(bvh, nodes, totnode);
2095
2096         if (nodes) MEM_freeN(nodes);
2097
2098         if (planes) {
2099                 BKE_pbvh_search_callback(
2100                         bvh, BKE_pbvh_node_planes_contain_AABB,
2101                         planes, pbvh_node_draw_cb, &draw_data);
2102         }
2103         else {
2104                 BKE_pbvh_search_callback(
2105                         bvh, NULL,
2106                         NULL, pbvh_node_draw_cb, &draw_data);
2107         }
2108 #if 0
2109         if (G.debug_value == 14)
2110                 pbvh_draw_BB(bvh);
2111 #endif
2112 }
2113
2114 void BKE_pbvh_grids_update(PBVH *bvh, CCGElem **grids, void **gridfaces,
2115                            DMFlagMat *flagmats, BLI_bitmap **grid_hidden)
2116 {
2117         bvh->grids = grids;
2118         bvh->gridfaces = gridfaces;
2119
2120         if (flagmats != bvh->grid_flag_mats || bvh->grid_hidden != grid_hidden) {
2121                 bvh->grid_flag_mats = flagmats;
2122                 bvh->grid_hidden = grid_hidden;
2123
2124                 for (int a = 0; a < bvh->totnode; ++a)
2125                         BKE_pbvh_node_mark_rebuild_draw(&bvh->nodes[a]);
2126         }
2127 }
2128
2129 /* Get the node's displacement layer, creating it if necessary */
2130 float *BKE_pbvh_node_layer_disp_get(PBVH *bvh, PBVHNode *node)
2131 {
2132         if (!node->layer_disp) {
2133                 int totvert = 0;
2134                 BKE_pbvh_node_num_verts(bvh, node, &totvert, NULL);
2135                 node->layer_disp = MEM_callocN(sizeof(float) * totvert, "layer disp");
2136         }
2137         return node->layer_disp;
2138 }
2139
2140 /* If the node has a displacement layer, free it and set to null */
2141 void BKE_pbvh_node_layer_disp_free(PBVHNode *node)
2142 {
2143         if (node->layer_disp) {
2144                 MEM_freeN(node->layer_disp);
2145                 node->layer_disp = NULL;
2146         }
2147 }
2148
2149 float (*BKE_pbvh_get_vertCos(PBVH *pbvh))[3]
2150 {
2151         float (*vertCos)[3] = NULL;
2152
2153         if (pbvh->verts) {
2154                 MVert *mvert = pbvh->verts;
2155
2156                 vertCos = MEM_callocN(3 * pbvh->totvert * sizeof(float), "BKE_pbvh_get_vertCoords");
2157                 float *co = (float *)vertCos;
2158
2159                 for (int a = 0; a < pbvh->totvert; a++, mvert++, co += 3) {
2160                         copy_v3_v3(co, mvert->co);
2161                 }
2162         }
2163
2164         return vertCos;
2165 }
2166
2167 void BKE_pbvh_apply_vertCos(PBVH *pbvh, float (*vertCos)[3], const int totvert)
2168 {
2169         if (totvert != pbvh->totvert) {
2170                 BLI_assert(!"PBVH: Given deforming vcos number does not natch PBVH vertex number!");
2171                 return;
2172         }
2173
2174         if (!pbvh->deformed) {
2175                 if (pbvh->verts) {
2176                         /* if pbvh is not already deformed, verts/faces points to the */
2177                         /* original data and applying new coords to this arrays would lead to */
2178                         /* unneeded deformation -- duplicate verts/faces to avoid this */
2179
2180                         pbvh->verts   = MEM_dupallocN(pbvh->verts);
2181                         /* No need to dupalloc pbvh->looptri, this one is 'totally owned' by pbvh, it's never some mesh data. */
2182
2183                         pbvh->deformed = true;
2184                 }
2185         }
2186
2187         if (pbvh->verts) {
2188                 MVert *mvert = pbvh->verts;
2189                 /* copy new verts coords */
2190                 for (int a = 0; a < pbvh->totvert; ++a, ++mvert) {
2191                         /* no need for float comparison here (memory is exactly equal or not) */
2192                         if (memcmp(mvert->co, vertCos[a], sizeof(float[3])) != 0) {
2193                                 copy_v3_v3(mvert->co, vertCos[a]);
2194                                 mvert->flag |= ME_VERT_PBVH_UPDATE;
2195                         }
2196                 }
2197
2198                 /* coordinates are new -- normals should also be updated */
2199                 BKE_mesh_calc_normals_looptri(
2200                         pbvh->verts, pbvh->totvert,
2201                         pbvh->mloop,
2202                         pbvh->looptri, pbvh->totprim,
2203                         NULL);
2204
2205                 for (int a = 0; a < pbvh->totnode; ++a)
2206                         BKE_pbvh_node_mark_update(&pbvh->nodes[a]);
2207
2208                 BKE_pbvh_update(pbvh, PBVH_UpdateBB, NULL);
2209                 BKE_pbvh_update(pbvh, PBVH_UpdateOriginalBB, NULL);
2210
2211         }
2212 }
2213
2214 bool BKE_pbvh_isDeformed(PBVH *pbvh)
2215 {
2216         return pbvh->deformed;
2217 }
2218 /* Proxies */
2219
2220 PBVHProxyNode *BKE_pbvh_node_add_proxy(PBVH *bvh, PBVHNode *node)
2221 {
2222         int index, totverts;
2223
2224         index = node->proxy_count;
2225
2226         node->proxy_count++;
2227
2228         if (node->proxies)
2229                 node->proxies = MEM_reallocN(node->proxies, node->proxy_count * sizeof(PBVHProxyNode));
2230         else
2231                 node->proxies = MEM_mallocN(sizeof(PBVHProxyNode), "PBVHNodeProxy");
2232
2233         BKE_pbvh_node_num_verts(bvh, node, &totverts, NULL);
2234         node->proxies[index].co = MEM_callocN(sizeof(float[3]) * totverts, "PBVHNodeProxy.co");
2235
2236         return node->proxies + index;
2237 }
2238
2239 void BKE_pbvh_node_free_proxies(PBVHNode *node)
2240 {
2241         for (int p = 0; p < node->proxy_count; p++) {
2242                 MEM_freeN(node->proxies[p].co);
2243                 node->proxies[p].co = NULL;
2244         }
2245
2246         MEM_freeN(node->proxies);
2247         node->proxies = NULL;
2248
2249         node->proxy_count = 0;
2250 }
2251
2252 void BKE_pbvh_gather_proxies(PBVH *pbvh, PBVHNode ***r_array,  int *r_tot)
2253 {
2254         PBVHNode **array = NULL;
2255         int tot = 0, space = 0;
2256
2257         for (int n = 0; n < pbvh->totnode; n++) {
2258                 PBVHNode *node = pbvh->nodes + n;
2259
2260                 if (node->proxy_count > 0) {
2261                         if (tot == space) {
2262                                 /* resize array if needed */
2263                                 space = (tot == 0) ? 32 : space * 2;
2264                                 array = MEM_recallocN_id(array, sizeof(PBVHNode *) * space, __func__);
2265                         }
2266
2267                         array[tot] = node;
2268                         tot++;
2269                 }
2270         }
2271
2272         if (tot == 0 && array) {
2273                 MEM_freeN(array);
2274                 array = NULL;
2275         }
2276
2277         *r_array = array;
2278         *r_tot = tot;
2279 }
2280
2281 void pbvh_vertex_iter_init(PBVH *bvh, PBVHNode *node,
2282                            PBVHVertexIter *vi, int mode)
2283 {
2284         struct CCGElem **grids;
2285         struct MVert *verts;
2286         const int *vert_indices;
2287         int *grid_indices;
2288         int totgrid, gridsize, uniq_verts, totvert;
2289
2290         vi->grid = NULL;
2291         vi->no = NULL;
2292         vi->fno = NULL;
2293         vi->mvert = NULL;
2294
2295         BKE_pbvh_node_get_grids(bvh, node, &grid_indices, &totgrid, NULL, &gridsize, &grids);
2296         BKE_pbvh_node_num_verts(bvh, node, &uniq_verts, &totvert);
2297         BKE_pbvh_node_get_verts(bvh, node, &vert_indices, &verts);
2298         vi->key = &bvh->gridkey;
2299
2300         vi->grids = grids;
2301         vi->grid_indices = grid_indices;
2302         vi->totgrid = (grids) ? totgrid : 1;
2303         vi->gridsize = gridsize;
2304
2305         if (mode == PBVH_ITER_ALL)
2306                 vi->totvert = totvert;
2307         else
2308                 vi->totvert = uniq_verts;
2309         vi->vert_indices = vert_indices;
2310         vi->mverts = verts;
2311
2312         if (bvh->type == PBVH_BMESH) {
2313                 BLI_gsetIterator_init(&vi->bm_unique_verts, node->bm_unique_verts);
2314                 BLI_gsetIterator_init(&vi->bm_other_verts, node->bm_other_verts);
2315                 vi->bm_vdata = &bvh->bm->vdata;
2316                 vi->cd_vert_mask_offset = CustomData_get_offset(vi->bm_vdata, CD_PAINT_MASK);
2317         }
2318
2319         vi->gh = NULL;
2320         if (vi->grids && mode == PBVH_ITER_UNIQUE)
2321                 vi->grid_hidden = bvh->grid_hidden;
2322
2323         vi->mask = NULL;
2324         if (bvh->type == PBVH_FACES)
2325                 vi->vmask = CustomData_get_layer(bvh->vdata, CD_PAINT_MASK);
2326 }
2327
2328 bool pbvh_has_mask(PBVH *bvh)
2329 {
2330         switch (bvh->type) {
2331                 case PBVH_GRIDS:
2332                         return (bvh->gridkey.has_mask != 0);
2333                 case PBVH_FACES:
2334                         return (bvh->vdata && CustomData_get_layer(bvh->vdata,
2335                                               CD_PAINT_MASK));
2336                 case PBVH_BMESH:
2337                         return (bvh->bm && (CustomData_get_offset(&bvh->bm->vdata, CD_PAINT_MASK) != -1));
2338         }
2339
2340         return false;
2341 }
2342
2343 void pbvh_show_diffuse_color_set(PBVH *bvh, bool show_diffuse_color)
2344 {
2345         bvh->show_diffuse_color = !pbvh_has_mask(bvh) || show_diffuse_color;
2346 }
2347
2348 void pbvh_show_mask_set(PBVH *bvh, bool show_mask)
2349 {
2350         bvh->show_mask = show_mask;
2351 }