BLI_stackdefines
[blender.git] / source / blender / bmesh / tools / bmesh_bisect_plane.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  * Contributor(s): Campbell Barton
19  *
20  * ***** END GPL LICENSE BLOCK *****
21  */
22
23 /** \file blender/bmesh/tools/bmesh_bisect_plane.c
24  *  \ingroup bmesh
25  *
26  * Cut the geometry in half using a plane.
27  *
28  * \par Implementation
29  * This simply works by splitting tagged edges whos verts span either side of
30  * the plane, then splitting faces along their dividing verts.
31  * The only complex case is when a ngon spans the axis multiple times,
32  * in this case we need to do some extra checks to correctly bisect the ngon.
33  * see: #bm_face_bisect_verts
34  */
35
36 #include <limits.h>
37
38 #include "MEM_guardedalloc.h"
39
40 #include "BLI_utildefines.h"
41 #include "BLI_stackdefines.h"
42 #include "BLI_alloca.h"
43 #include "BLI_linklist.h"
44 #include "BLI_linklist_stack.h"
45 #include "BLI_math.h"
46
47 #include "bmesh.h"
48 #include "bmesh_bisect_plane.h"  /* own include */
49
50 #include "BLI_strict_flags.h"  /* keep last */
51
52
53 /* -------------------------------------------------------------------- */
54 /* Math utils */
55
56 static int plane_point_test_v3(const float plane[4], const float co[3], const float eps, float *r_depth)
57 {
58         const float f = plane_point_side_v3(plane, co);
59         *r_depth = f;
60
61         if      (f <= -eps) return -1;
62         else if (f >=  eps) return  1;
63         else                return  0;
64 }
65
66
67 /* -------------------------------------------------------------------- */
68 /* Wrappers to hide internal data-structure abuse,
69  * later we may want to move this into some hash lookup
70  * to a separate struct, but for now we can store in BMesh data */
71
72 #define BM_VERT_DIR(v)     ((v)->head.index)    /* Direction -1/0/1 */
73 #define BM_VERT_DIST(v)    ((v)->no[0])         /* Distance from the plane. */
74 #define BM_VERT_SORTVAL(v) ((v)->no[1])         /* Temp value for sorting. */
75 #define BM_VERT_LOOPINDEX(v)                    /* The verts index within a face (temp var) */ \
76         (*((unsigned int *)(&(v)->no[2])))
77
78 /**
79  * Hide flag access
80  * (for more readable code since same flag is used differently for vert/edgeface)...
81  */
82
83 /* enable when vertex is in the center and its faces have been added to the stack */
84 BLI_INLINE void vert_is_center_enable(BMVert *v) { BM_elem_flag_enable(v, BM_ELEM_TAG); }
85 BLI_INLINE void vert_is_center_disable(BMVert *v) { BM_elem_flag_disable(v, BM_ELEM_TAG); }
86 BLI_INLINE bool vert_is_center_test(BMVert *v) { return (BM_elem_flag_test(v, BM_ELEM_TAG) != 0); }
87
88 /* enable when the edge can be cut */
89 BLI_INLINE void edge_is_cut_enable(BMEdge *e) { BM_elem_flag_enable(e, BM_ELEM_TAG); }
90 BLI_INLINE void edge_is_cut_disable(BMEdge *e) { BM_elem_flag_disable(e, BM_ELEM_TAG); }
91 BLI_INLINE bool edge_is_cut_test(BMEdge *e) { return (BM_elem_flag_test(e, BM_ELEM_TAG) != 0); }
92
93 /* enable when the faces are added to the stack */
94 BLI_INLINE void face_in_stack_enable(BMFace *f) { BM_elem_flag_disable(f, BM_ELEM_TAG); }
95 BLI_INLINE void face_in_stack_disable(BMFace *f) { BM_elem_flag_enable(f, BM_ELEM_TAG); }
96 BLI_INLINE bool face_in_stack_test(BMFace *f) { return (BM_elem_flag_test(f, BM_ELEM_TAG) == 0); }
97
98 /* -------------------------------------------------------------------- */
99 /* BMesh utils */
100
101 static int bm_vert_sortval_cb(const void *v_a_v, const void *v_b_v)
102 {
103         const float val_a = BM_VERT_SORTVAL(*((BMVert **)v_a_v));
104         const float val_b = BM_VERT_SORTVAL(*((BMVert **)v_b_v));
105
106         if      (val_a > val_b) return  1;
107         else if (val_a < val_b) return -1;
108                                 return  0;
109 }
110
111
112 static void bm_face_bisect_verts(BMesh *bm, BMFace *f, const float plane[4], const short oflag_center)
113 {
114         /* unlikely more then 2 verts are needed */
115         const unsigned int f_len_orig = (unsigned int)f->len;
116         BMVert **vert_split_arr = BLI_array_alloca(vert_split_arr, f_len_orig);
117         STACK_DECLARE(vert_split_arr);
118         BMLoop *l_iter, *l_first;
119         bool use_dirs[3] = {false, false, false};
120
121         STACK_INIT(vert_split_arr, f_len_orig);
122
123         l_first = BM_FACE_FIRST_LOOP(f);
124
125         /* add plane-aligned verts to the stack
126          * and check we have verts from both sides in this face,
127          * ... that the face doesn't only have boundry verts on the plane for eg. */
128         l_iter = l_first;
129         do {
130                 if (vert_is_center_test(l_iter->v)) {
131                         BLI_assert(BM_VERT_DIR(l_iter->v) == 0);
132                         STACK_PUSH(vert_split_arr, l_iter->v);
133                 }
134                 use_dirs[BM_VERT_DIR(l_iter->v) + 1] = true;
135         } while ((l_iter = l_iter->next) != l_first);
136
137         if ((STACK_SIZE(vert_split_arr) > 1) &&
138             (use_dirs[0] && use_dirs[2]))
139         {
140                 if (LIKELY(STACK_SIZE(vert_split_arr) == 2)) {
141                         BMLoop *l_new;
142                         BMLoop *l_a, *l_b;
143
144                         l_a = BM_face_vert_share_loop(f, vert_split_arr[0]);
145                         l_b = BM_face_vert_share_loop(f, vert_split_arr[1]);
146
147                         /* common case, just cut the face once */
148                         BM_face_split(bm, f, l_a, l_b, &l_new, NULL, true);
149                         if (l_new) {
150                                 if (oflag_center) {
151                                         BMO_elem_flag_enable(bm, l_new->e, oflag_center);
152                                         BMO_elem_flag_enable(bm, l_new->f, oflag_center);
153                                         BMO_elem_flag_enable(bm, f,        oflag_center);
154                                 }
155                         }
156                 }
157                 else {
158                         /* less common case, _complicated_ we need to calculate how to do multiple cuts */
159                         float (*face_verts_proj_2d)[2] = BLI_array_alloca(face_verts_proj_2d, f_len_orig);
160                         float axis_mat[3][3];
161
162                         BMFace **face_split_arr = BLI_array_alloca(face_split_arr, STACK_SIZE(vert_split_arr));
163                         STACK_DECLARE(face_split_arr);
164
165                         float sort_dir[3];
166                         unsigned int i;
167
168
169                         /* ---- */
170                         /* Calculate the direction to sort verts in the face intersecting the plane */
171
172                         /* exact dir isn't so important,
173                          * just need a dir for sorting verts across face,
174                          * 'sort_dir' could be flipped either way, it not important, we only need to order the array
175                          */
176                         cross_v3_v3v3(sort_dir, f->no, plane);
177                         if (UNLIKELY(normalize_v3(sort_dir) == 0.0f)) {
178                                 /* find any 2 verts and get their direction */
179                                 for (i = 0; i < STACK_SIZE(vert_split_arr); i++) {
180                                         if (!equals_v3v3(vert_split_arr[0]->co, vert_split_arr[i]->co)) {
181                                                 sub_v3_v3v3(sort_dir, vert_split_arr[0]->co, vert_split_arr[i]->co);
182                                                 normalize_v3(sort_dir);
183                                         }
184                                 }
185                                 if (UNLIKELY(i == STACK_SIZE(vert_split_arr))) {
186                                         /* ok, we can't do anything useful here,
187                                          * face has no area or so, bail out, this is highly unlikely but not impossible */
188                                         goto finally;
189                                 }
190                         }
191
192
193                         /* ---- */
194                         /* Calculate 2d coords to use for intersection checks */
195
196                         /* get the faces 2d coords */
197                         BLI_assert(BM_face_is_normal_valid(f));
198                         axis_dominant_v3_to_m3(axis_mat, f->no);
199
200                         l_iter = l_first;
201                         i = 0;
202                         do {
203                                 BM_VERT_LOOPINDEX(l_iter->v) = i;
204                                 mul_v2_m3v3(face_verts_proj_2d[i], axis_mat, l_iter->v->co);
205                                 i++;
206                         } while ((l_iter = l_iter->next) != l_first);
207
208
209                         /* ---- */
210                         /* Sort the verts across the face from one side to another */
211                         for (i = 0; i < STACK_SIZE(vert_split_arr); i++) {
212                                 BMVert *v = vert_split_arr[i];
213                                 BM_VERT_SORTVAL(v) = dot_v3v3(sort_dir, v->co);
214                         }
215
216                         qsort(vert_split_arr, STACK_SIZE(vert_split_arr), sizeof(*vert_split_arr), bm_vert_sortval_cb);
217
218
219                         /* ---- */
220                         /* Split the face across sorted splits */
221
222                         /* note: we don't know which face gets which splits,
223                          * so at the moment we have to search all faces for the vert pair,
224                          * while not all that nice, typically there are < 5 resulting faces,
225                          * so its not _that_ bad. */
226
227                         STACK_INIT(face_split_arr, STACK_SIZE(vert_split_arr));
228                         STACK_PUSH(face_split_arr, f);
229
230                         for (i = 0; i < STACK_SIZE(vert_split_arr) - 1; i++) {
231                                 BMVert *v_a = vert_split_arr[i];
232                                 BMVert *v_b = vert_split_arr[i + 1];
233                                 float co_mid[2];
234
235                                 /* geometric test before doing face lookups,
236                                  * find if the split spans a filled region of the polygon. */
237                                 mid_v2_v2v2(co_mid,
238                                             face_verts_proj_2d[BM_VERT_LOOPINDEX(v_a)],
239                                             face_verts_proj_2d[BM_VERT_LOOPINDEX(v_b)]);
240
241                                 if (isect_point_poly_v2(co_mid, (const float (*)[2])face_verts_proj_2d, f_len_orig, false)) {
242                                         BMLoop *l_a, *l_b;
243                                         bool found = false;
244                                         unsigned int j;
245
246                                         for (j = 0; j < STACK_SIZE(face_split_arr); j++) {
247                                                 /* would be nice to avoid loop lookup here,
248                                                  * but we need to know which face the verts are in */
249                                                 if ((l_a = BM_face_vert_share_loop(face_split_arr[j], v_a)) &&
250                                                     (l_b = BM_face_vert_share_loop(face_split_arr[j], v_b)))
251                                                 {
252                                                         found = true;
253                                                         break;
254                                                 }
255                                         }
256
257                                         BLI_assert(found == true);
258
259                                         /* in fact this simple test is good enough,
260                                          * test if the loops are adjacent */
261                                         if (found && !BM_loop_is_adjacent(l_a, l_b)) {
262                                                 BMFace *f_tmp;
263                                                 f_tmp = BM_face_split(bm, face_split_arr[j], l_a, l_b, NULL, NULL, true);
264                                                 if (f_tmp) {
265                                                         if (f_tmp != face_split_arr[j]) {
266                                                                 STACK_PUSH(face_split_arr, f_tmp);
267                                                                 BLI_assert(STACK_SIZE(face_split_arr) <= STACK_SIZE(vert_split_arr));
268                                                         }
269                                                 }
270                                         }
271                                 }
272                                 else {
273                                         // printf("no intersect\n");
274                                 }
275                         }
276                 }
277         }
278
279
280 finally:
281         (void)vert_split_arr;
282 }
283
284 /* -------------------------------------------------------------------- */
285 /* Main logic */
286
287 /**
288  * \param use_snap_center  Snap verts onto the plane.
289  * \param use_tag  Only bisect tagged edges and faces.
290  * \param oflag_center  Operator flag, enabled for geometry on the axis (existing and created)
291  */
292 void BM_mesh_bisect_plane(BMesh *bm, float plane[4],
293                           const bool use_snap_center, const bool use_tag,
294                           const short oflag_center, const float eps)
295 {
296         unsigned int einput_len;
297         unsigned int i;
298         BMEdge **edges_arr = MEM_mallocN(sizeof(*edges_arr) * (size_t)bm->totedge, __func__);
299
300         BLI_LINKSTACK_DECLARE(face_stack, BMFace *);
301
302         BMVert *v;
303         BMFace *f;
304
305         BMIter iter;
306
307         if (use_tag) {
308                 /* build tagged edge array */
309                 BMEdge *e;
310                 einput_len = 0;
311
312                 /* flush edge tags to verts */
313                 BM_mesh_elem_hflag_disable_all(bm, BM_VERT, BM_ELEM_TAG, false);
314
315                 /* keep face tags as is */
316                 BM_ITER_MESH_INDEX (e, &iter, bm, BM_EDGES_OF_MESH, i) {
317                         if (edge_is_cut_test(e)) {
318                                 edges_arr[einput_len++] = e;
319
320                                 /* flush edge tags to verts */
321                                 BM_elem_flag_enable(e->v1, BM_ELEM_TAG);
322                                 BM_elem_flag_enable(e->v2, BM_ELEM_TAG);
323                         }
324                 }
325
326                 /* face tags are set by caller */
327         }
328         else {
329                 BMEdge *e;
330                 einput_len = (unsigned int)bm->totedge;
331                 BM_ITER_MESH_INDEX (e, &iter, bm, BM_EDGES_OF_MESH, i) {
332                         edge_is_cut_enable(e);
333                         edges_arr[i] = e;
334                 }
335
336                 BM_ITER_MESH (f, &iter, bm, BM_FACES_OF_MESH) {
337                         face_in_stack_disable(f);
338                 }
339         }
340
341
342         BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) {
343
344                 if (use_tag && !BM_elem_flag_test(v, BM_ELEM_TAG)) {
345                         vert_is_center_disable(v);
346
347                         /* these should never be accessed */
348                         BM_VERT_DIR(v) = 0;
349                         BM_VERT_DIST(v) = 0.0f;
350
351                         continue;
352                 }
353
354                 vert_is_center_disable(v);
355                 BM_VERT_DIR(v) = plane_point_test_v3(plane, v->co, eps, &(BM_VERT_DIST(v)));
356
357                 if (BM_VERT_DIR(v) == 0) {
358                         if (oflag_center) {
359                                 BMO_elem_flag_enable(bm, v, oflag_center);
360                         }
361                         if (use_snap_center) {
362                                 closest_to_plane_v3(v->co, plane, v->co);
363                         }
364                 }
365         }
366
367         /* store a stack of faces to be evaluated for splitting */
368         BLI_LINKSTACK_INIT(face_stack);
369
370         for (i = 0; i < einput_len; i++) {
371                 /* we could check edge_is_cut_test(e) but there is no point */
372                 BMEdge *e = edges_arr[i];
373                 const int side[2] = {BM_VERT_DIR(e->v1), BM_VERT_DIR(e->v2)};
374                 const float dist[2] = {BM_VERT_DIST(e->v1), BM_VERT_DIST(e->v2)};
375
376                 if (side[0] && side[1] && (side[0] != side[1])) {
377                         const float e_fac = fabsf(dist[0]) / fabsf(dist[0] - dist[1]);
378                         BMVert *v_new;
379
380                         if (e->l) {
381                                 BMLoop *l_iter, *l_first;
382                                 l_iter = l_first = e->l;
383                                 do {
384                                         if (!face_in_stack_test(l_iter->f)) {
385                                                 face_in_stack_enable(l_iter->f);
386                                                 BLI_LINKSTACK_PUSH(face_stack, l_iter->f);
387                                         }
388                                 } while ((l_iter = l_iter->radial_next) != l_first);
389                         }
390
391                         v_new = BM_edge_split(bm, e, e->v1, NULL, e_fac);
392                         vert_is_center_enable(v_new);
393                         if (oflag_center) {
394                                 BMO_elem_flag_enable(bm, v_new, oflag_center);
395                         }
396
397                         BM_VERT_DIR(v_new) = 0;
398                         BM_VERT_DIST(v_new) = 0.0f;
399                 }
400                 else if (side[0] == 0 || side[1] == 0) {
401                         /* check if either edge verts are aligned,
402                          * if so - tag and push all faces that use it into the stack */
403                         unsigned int j;
404                         BM_ITER_ELEM_INDEX (v, &iter, e, BM_VERTS_OF_EDGE, j) {
405                                 if (side[j] == 0) {
406                                         if (vert_is_center_test(v) == 0) {
407                                                 BMIter itersub;
408                                                 BMLoop *l_iter;
409
410                                                 vert_is_center_enable(v);
411
412                                                 BM_ITER_ELEM (l_iter, &itersub, v, BM_LOOPS_OF_VERT) {
413                                                         if (!face_in_stack_test(l_iter->f)) {
414                                                                 face_in_stack_enable(l_iter->f);
415                                                                 BLI_LINKSTACK_PUSH(face_stack, l_iter->f);
416                                                         }
417                                                 }
418
419                                         }
420                                 }
421                         }
422
423                         /* if both verts are on the center - tag it */
424                         if (oflag_center) {
425                                 if (side[0] == 0 && side[1] == 0) {
426                                         BMO_elem_flag_enable(bm, e, oflag_center);
427                                 }
428                         }
429                 }
430         }
431
432         MEM_freeN(edges_arr);
433
434         while ((f = BLI_LINKSTACK_POP(face_stack))) {
435                 bm_face_bisect_verts(bm, f, plane, oflag_center);
436         }
437
438         /* now we have all faces to split in the stack */
439         BLI_LINKSTACK_FREE(face_stack);
440 }