OpenGL: manage built-in shaders better
[blender.git] / source / blender / bmesh / intern / bmesh_core.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): Joseph Eagar, Geoffrey Bantle, Campbell Barton
19  *
20  * ***** END GPL LICENSE BLOCK *****
21  */
22
23 /** \file blender/bmesh/intern/bmesh_core.c
24  *  \ingroup bmesh
25  *
26  * Core BMesh functions for adding, removing BMesh elements.
27  */
28
29 #include "MEM_guardedalloc.h"
30
31 #include "BLI_math_vector.h"
32 #include "BLI_array.h"
33 #include "BLI_alloca.h"
34 #include "BLI_linklist_stack.h"
35 #include "BLI_stackdefines.h"
36
37 #include "BLT_translation.h"
38
39 #include "BKE_DerivedMesh.h"
40 #include "BKE_mesh.h"
41
42 #include "bmesh.h"
43 #include "intern/bmesh_private.h"
44
45 /* use so valgrinds memcheck alerts us when undefined index is used.
46  * TESTING ONLY! */
47 // #define USE_DEBUG_INDEX_MEMCHECK
48
49 #ifdef USE_DEBUG_INDEX_MEMCHECK
50 #define DEBUG_MEMCHECK_INDEX_INVALIDATE(ele)                                  \
51         {                                                                         \
52                 int undef_idx;                                                        \
53                 BM_elem_index_set(ele, undef_idx); /* set_ok_invalid */               \
54         } (void)0
55
56 #endif
57
58 /**
59  * \brief Main function for creating a new vertex.
60  */
61 BMVert *BM_vert_create(
62         BMesh *bm, const float co[3],
63         const BMVert *v_example, const eBMCreateFlag create_flag)
64 {
65         BMVert *v = BLI_mempool_alloc(bm->vpool);
66
67         BLI_assert((v_example == NULL) || (v_example->head.htype == BM_VERT));
68         BLI_assert(!(create_flag & 1));
69
70         /* --- assign all members --- */
71         v->head.data = NULL;
72
73 #ifdef USE_DEBUG_INDEX_MEMCHECK
74         DEBUG_MEMCHECK_INDEX_INVALIDATE(v)
75 #else
76         BM_elem_index_set(v, -1); /* set_ok_invalid */
77 #endif
78
79         v->head.htype = BM_VERT;
80         v->head.hflag = 0;
81         v->head.api_flag = 0;
82
83         /* allocate flags */
84         if (bm->use_toolflags) {
85                 ((BMVert_OFlag *)v)->oflags = bm->vtoolflagpool ? BLI_mempool_calloc(bm->vtoolflagpool) : NULL;
86         }
87
88         /* 'v->no' is handled by BM_elem_attrs_copy */
89         if (co) {
90                 copy_v3_v3(v->co, co);
91         }
92         else {
93                 zero_v3(v->co);
94         }
95         /* 'v->no' set below */
96
97         v->e = NULL;
98         /* --- done --- */
99
100
101         /* disallow this flag for verts - its meaningless */
102         BLI_assert((create_flag & BM_CREATE_NO_DOUBLE) == 0);
103
104         /* may add to middle of the pool */
105         bm->elem_index_dirty |= BM_VERT;
106         bm->elem_table_dirty |= BM_VERT;
107
108         bm->totvert++;
109
110         if (!(create_flag & BM_CREATE_SKIP_CD)) {
111                 if (v_example) {
112                         int *keyi;
113
114                         /* handles 'v->no' too */
115                         BM_elem_attrs_copy(bm, bm, v_example, v);
116
117                         /* exception: don't copy the original shapekey index */
118                         keyi = CustomData_bmesh_get(&bm->vdata, v->head.data, CD_SHAPE_KEYINDEX);
119                         if (keyi) {
120                                 *keyi = ORIGINDEX_NONE;
121                         }
122                 }
123                 else {
124                         CustomData_bmesh_set_default(&bm->vdata, &v->head.data);
125                         zero_v3(v->no);
126                 }
127         }
128         else {
129                 if (v_example) {
130                         copy_v3_v3(v->no, v_example->no);
131                 }
132                 else {
133                         zero_v3(v->no);
134                 }
135         }
136
137         BM_CHECK_ELEMENT(v);
138
139         return v;
140 }
141
142 /**
143  * \brief Main function for creating a new edge.
144  *
145  * \note Duplicate edges are supported by the API however users should _never_ see them.
146  * so unless you need a unique edge or know the edge won't exist, you should call with \a no_double = true
147  */
148 BMEdge *BM_edge_create(
149         BMesh *bm, BMVert *v1, BMVert *v2,
150         const BMEdge *e_example, const eBMCreateFlag create_flag)
151 {
152         BMEdge *e;
153
154         BLI_assert(v1 != v2);
155         BLI_assert(v1->head.htype == BM_VERT && v2->head.htype == BM_VERT);
156         BLI_assert((e_example == NULL) || (e_example->head.htype == BM_EDGE));
157         BLI_assert(!(create_flag & 1));
158
159         if ((create_flag & BM_CREATE_NO_DOUBLE) && (e = BM_edge_exists(v1, v2)))
160                 return e;
161         
162         e = BLI_mempool_alloc(bm->epool);
163
164
165         /* --- assign all members --- */
166         e->head.data = NULL;
167
168 #ifdef USE_DEBUG_INDEX_MEMCHECK
169         DEBUG_MEMCHECK_INDEX_INVALIDATE(e)
170 #else
171         BM_elem_index_set(e, -1); /* set_ok_invalid */
172 #endif
173
174         e->head.htype = BM_EDGE;
175         e->head.hflag = BM_ELEM_SMOOTH | BM_ELEM_DRAW;
176         e->head.api_flag = 0;
177
178         /* allocate flags */
179         if (bm->use_toolflags) {
180                 ((BMEdge_OFlag *)e)->oflags = bm->etoolflagpool ? BLI_mempool_calloc(bm->etoolflagpool) : NULL;
181         }
182
183         e->v1 = v1;
184         e->v2 = v2;
185         e->l = NULL;
186
187         memset(&e->v1_disk_link, 0, sizeof(BMDiskLink) * 2);
188         /* --- done --- */
189
190
191         bmesh_disk_edge_append(e, e->v1);
192         bmesh_disk_edge_append(e, e->v2);
193
194         /* may add to middle of the pool */
195         bm->elem_index_dirty |= BM_EDGE;
196         bm->elem_table_dirty |= BM_EDGE;
197
198         bm->totedge++;
199
200         if (!(create_flag & BM_CREATE_SKIP_CD)) {
201                 if (e_example) {
202                         BM_elem_attrs_copy(bm, bm, e_example, e);
203                 }
204                 else {
205                         CustomData_bmesh_set_default(&bm->edata, &e->head.data);
206                 }
207         }
208
209         BM_CHECK_ELEMENT(e);
210
211         return e;
212 }
213
214 /**
215  * \note In most cases a \a l_example should be NULL,
216  * since this is a low level API and we shouldn't attempt to be clever and guess whats intended.
217  * In cases where copying adjacent loop-data is useful, see #BM_face_copy_shared.
218  */
219 static BMLoop *bm_loop_create(
220         BMesh *bm, BMVert *v, BMEdge *e, BMFace *f,
221         const BMLoop *l_example, const eBMCreateFlag create_flag)
222 {
223         BMLoop *l = NULL;
224
225         l = BLI_mempool_alloc(bm->lpool);
226
227         BLI_assert((l_example == NULL) || (l_example->head.htype == BM_LOOP));
228         BLI_assert(!(create_flag & 1));
229
230 #ifndef NDEBUG
231         if (l_example) {
232                 /* ensure passing a loop is either sharing the same vertex, or entirely disconnected
233                  * use to catch mistake passing in loop offset-by-one. */
234                 BLI_assert((v == l_example->v) || !ELEM(v, l_example->prev->v, l_example->next->v));
235         }
236 #endif
237
238         /* --- assign all members --- */
239         l->head.data = NULL;
240
241 #ifdef USE_DEBUG_INDEX_MEMCHECK
242         DEBUG_MEMCHECK_INDEX_INVALIDATE(l)
243 #else
244         BM_elem_index_set(l, -1); /* set_ok_invalid */
245 #endif
246
247         l->head.htype = BM_LOOP;
248         l->head.hflag = 0;
249         l->head.api_flag = 0;
250
251         l->v = v;
252         l->e = e;
253         l->f = f;
254
255         l->radial_next = NULL;
256         l->radial_prev = NULL;
257         l->next = NULL;
258         l->prev = NULL;
259         /* --- done --- */
260
261         /* may add to middle of the pool */
262         bm->elem_index_dirty |= BM_LOOP;
263
264         bm->totloop++;
265
266         if (!(create_flag & BM_CREATE_SKIP_CD)) {
267                 if (l_example) {
268                         /* no need to copy attrs, just handle customdata */
269                         // BM_elem_attrs_copy(bm, bm, l_example, l);
270                         CustomData_bmesh_free_block_data(&bm->ldata, l->head.data);
271                         CustomData_bmesh_copy_data(&bm->ldata, &bm->ldata, l_example->head.data, &l->head.data);
272                 }
273                 else {
274                         CustomData_bmesh_set_default(&bm->ldata, &l->head.data);
275                 }
276         }
277
278         return l;
279 }
280
281 static BMLoop *bm_face_boundary_add(
282         BMesh *bm, BMFace *f, BMVert *startv, BMEdge *starte,
283         const eBMCreateFlag create_flag)
284 {
285 #ifdef USE_BMESH_HOLES
286         BMLoopList *lst = BLI_mempool_calloc(bm->looplistpool);
287 #endif
288         BMLoop *l = bm_loop_create(bm, startv, starte, f, NULL /* starte->l */, create_flag);
289         
290         bmesh_radial_loop_append(starte, l);
291
292 #ifdef USE_BMESH_HOLES
293         lst->first = lst->last = l;
294         BLI_addtail(&f->loops, lst);
295 #else
296         f->l_first = l;
297 #endif
298         
299         return l;
300 }
301
302 BMFace *BM_face_copy(
303         BMesh *bm_dst, BMesh *bm_src, BMFace *f,
304         const bool copy_verts, const bool copy_edges)
305 {
306         BMVert **verts = BLI_array_alloca(verts, f->len);
307         BMEdge **edges = BLI_array_alloca(edges, f->len);
308         BMLoop *l_iter;
309         BMLoop *l_first;
310         BMLoop *l_copy;
311         BMFace *f_copy;
312         int i;
313
314         BLI_assert((bm_dst == bm_src) || (copy_verts && copy_edges));
315
316         l_iter = l_first = BM_FACE_FIRST_LOOP(f);
317         i = 0;
318         do {
319                 if (copy_verts) {
320                         verts[i] = BM_vert_create(bm_dst, l_iter->v->co, l_iter->v, BM_CREATE_NOP);
321                 }
322                 else {
323                         verts[i] = l_iter->v;
324                 }
325                 i++;
326         } while ((l_iter = l_iter->next) != l_first);
327
328         l_iter = l_first = BM_FACE_FIRST_LOOP(f);
329         i = 0;
330         do {
331                 if (copy_edges) {
332                         BMVert *v1, *v2;
333                         
334                         if (l_iter->e->v1 == verts[i]) {
335                                 v1 = verts[i];
336                                 v2 = verts[(i + 1) % f->len];
337                         }
338                         else {
339                                 v2 = verts[i];
340                                 v1 = verts[(i + 1) % f->len];
341                         }
342                         
343                         edges[i] = BM_edge_create(bm_dst, v1, v2, l_iter->e, BM_CREATE_NOP);
344                 }
345                 else {
346                         edges[i] = l_iter->e;
347                 }
348                 i++;
349         } while ((l_iter = l_iter->next) != l_first);
350         
351         f_copy = BM_face_create(bm_dst, verts, edges, f->len, NULL, BM_CREATE_SKIP_CD);
352         
353         BM_elem_attrs_copy(bm_src, bm_dst, f, f_copy);
354         
355         l_iter = l_first = BM_FACE_FIRST_LOOP(f);
356         l_copy = BM_FACE_FIRST_LOOP(f_copy);
357         do {
358                 BM_elem_attrs_copy(bm_src, bm_dst, l_iter, l_copy);
359                 l_copy = l_copy->next;
360         } while ((l_iter = l_iter->next) != l_first);
361
362         return f_copy;
363 }
364
365 /**
366  * only create the face, since this calloc's the length is initialized to 0,
367  * leave adding loops to the caller.
368  *
369  * \note, caller needs to handle customdata.
370  */
371 BLI_INLINE BMFace *bm_face_create__internal(BMesh *bm)
372 {
373         BMFace *f;
374
375         f = BLI_mempool_alloc(bm->fpool);
376
377
378         /* --- assign all members --- */
379         f->head.data = NULL;
380 #ifdef USE_DEBUG_INDEX_MEMCHECK
381         DEBUG_MEMCHECK_INDEX_INVALIDATE(f)
382 #else
383         BM_elem_index_set(f, -1); /* set_ok_invalid */
384 #endif
385
386         f->head.htype = BM_FACE;
387         f->head.hflag = 0;
388         f->head.api_flag = 0;
389
390         /* allocate flags */
391         if (bm->use_toolflags) {
392                 ((BMFace_OFlag *)f)->oflags = bm->ftoolflagpool ? BLI_mempool_calloc(bm->ftoolflagpool) : NULL;
393         }
394
395 #ifdef USE_BMESH_HOLES
396         BLI_listbase_clear(&f->loops);
397 #else
398         f->l_first = NULL;
399 #endif
400         f->len = 0;
401         /* caller must initialize */
402         // zero_v3(f->no);
403         f->mat_nr = 0;
404         /* --- done --- */
405
406
407         /* may add to middle of the pool */
408         bm->elem_index_dirty |= BM_FACE;
409         bm->elem_table_dirty |= BM_FACE;
410
411         bm->totface++;
412
413 #ifdef USE_BMESH_HOLES
414         f->totbounds = 0;
415 #endif
416
417         return f;
418 }
419
420 /**
421  * Main face creation function
422  *
423  * \param bm  The mesh
424  * \param verts  A sorted array of verts size of len
425  * \param edges  A sorted array of edges size of len
426  * \param len  Length of the face
427  * \param create_flag  Options for creating the face
428  */
429 BMFace *BM_face_create(
430         BMesh *bm, BMVert **verts, BMEdge **edges, const int len,
431         const BMFace *f_example, const eBMCreateFlag create_flag)
432 {
433         BMFace *f = NULL;
434         BMLoop *l, *startl, *lastl;
435         int i;
436
437         BLI_assert((f_example == NULL) || (f_example->head.htype == BM_FACE));
438         BLI_assert(!(create_flag & 1));
439
440         if (len == 0) {
441                 /* just return NULL for now */
442                 return NULL;
443         }
444
445         if (create_flag & BM_CREATE_NO_DOUBLE) {
446                 /* Check if face already exists */
447                 const bool is_overlap = BM_face_exists(verts, len, &f);
448                 if (is_overlap) {
449                         return f;
450                 }
451                 else {
452                         BLI_assert(f == NULL);
453                 }
454         }
455
456         f = bm_face_create__internal(bm);
457
458         startl = lastl = bm_face_boundary_add(bm, f, verts[0], edges[0], create_flag);
459
460         for (i = 1; i < len; i++) {
461                 l = bm_loop_create(bm, verts[i], edges[i], f, NULL /* edges[i]->l */, create_flag);
462
463                 bmesh_radial_loop_append(edges[i], l);
464
465                 l->prev = lastl;
466                 lastl->next = l;
467                 lastl = l;
468         }
469         
470         startl->prev = lastl;
471         lastl->next = startl;
472         
473         f->len = len;
474         
475         if (!(create_flag & BM_CREATE_SKIP_CD)) {
476                 if (f_example) {
477                         BM_elem_attrs_copy(bm, bm, f_example, f);
478                 }
479                 else {
480                         CustomData_bmesh_set_default(&bm->pdata, &f->head.data);
481                         zero_v3(f->no);
482                 }
483         }
484         else {
485                 if (f_example) {
486                         copy_v3_v3(f->no, f_example->no);
487                 }
488                 else {
489                         zero_v3(f->no);
490                 }
491         }
492
493         BM_CHECK_ELEMENT(f);
494
495         return f;
496 }
497
498 /**
499  * Wrapper for #BM_face_create when you don't have an edge array
500  */
501 BMFace *BM_face_create_verts(
502         BMesh *bm, BMVert **vert_arr, const int len,
503         const BMFace *f_example, const eBMCreateFlag create_flag, const bool create_edges)
504 {
505         BMEdge **edge_arr = BLI_array_alloca(edge_arr, len);
506
507         if (create_edges) {
508                 BM_edges_from_verts_ensure(bm, edge_arr, vert_arr, len);
509         }
510         else {
511                 if (BM_edges_from_verts(edge_arr, vert_arr, len) == false) {
512                         return NULL;
513                 }
514         }
515
516         return BM_face_create(bm, vert_arr, edge_arr, len, f_example, create_flag);
517 }
518
519 #ifndef NDEBUG
520
521 /**
522  * Check the element is valid.
523  *
524  * BMESH_TODO, when this raises an error the output is incredibly confusing.
525  * need to have some nice way to print/debug what the heck's going on.
526  */
527 int bmesh_elem_check(void *element, const char htype)
528 {
529         BMHeader *head = element;
530         enum {
531                 IS_NULL                                     = (1 << 0),
532                 IS_WRONG_TYPE                               = (1 << 1),
533
534                 IS_VERT_WRONG_EDGE_TYPE                     = (1 << 2),
535
536                 IS_EDGE_NULL_DISK_LINK                      = (1 << 3),
537                 IS_EDGE_WRONG_LOOP_TYPE                     = (1 << 4),
538                 IS_EDGE_WRONG_FACE_TYPE                     = (1 << 5),
539                 IS_EDGE_NULL_RADIAL_LINK                    = (1 << 6),
540                 IS_EDGE_ZERO_FACE_LENGTH                    = (1 << 7),
541
542                 IS_LOOP_WRONG_FACE_TYPE                     = (1 << 8),
543                 IS_LOOP_WRONG_EDGE_TYPE                     = (1 << 9),
544                 IS_LOOP_WRONG_VERT_TYPE                     = (1 << 10),
545                 IS_LOOP_VERT_NOT_IN_EDGE                    = (1 << 11),
546                 IS_LOOP_NULL_CYCLE_LINK                     = (1 << 12),
547                 IS_LOOP_ZERO_FACE_LENGTH                    = (1 << 13),
548                 IS_LOOP_WRONG_FACE_LENGTH                   = (1 << 14),
549                 IS_LOOP_WRONG_RADIAL_LENGTH                 = (1 << 15),
550
551                 IS_FACE_NULL_LOOP                           = (1 << 16),
552                 IS_FACE_WRONG_LOOP_FACE                     = (1 << 17),
553                 IS_FACE_NULL_EDGE                           = (1 << 18),
554                 IS_FACE_NULL_VERT                           = (1 << 19),
555                 IS_FACE_LOOP_VERT_NOT_IN_EDGE               = (1 << 20),
556                 IS_FACE_LOOP_WRONG_RADIAL_LENGTH            = (1 << 21),
557                 IS_FACE_LOOP_WRONG_DISK_LENGTH              = (1 << 22),
558                 IS_FACE_LOOP_DUPE_LOOP                      = (1 << 23),
559                 IS_FACE_LOOP_DUPE_VERT                      = (1 << 24),
560                 IS_FACE_LOOP_DUPE_EDGE                      = (1 << 25),
561                 IS_FACE_WRONG_LENGTH                        = (1 << 26),
562         } err = 0;
563
564         if (!element)
565                 return IS_NULL;
566
567         if (head->htype != htype)
568                 return IS_WRONG_TYPE;
569         
570         switch (htype) {
571                 case BM_VERT:
572                 {
573                         BMVert *v = element;
574                         if (v->e && v->e->head.htype != BM_EDGE) {
575                                 err |= IS_VERT_WRONG_EDGE_TYPE;
576                         }
577                         break;
578                 }
579                 case BM_EDGE:
580                 {
581                         BMEdge *e = element;
582                         if (e->v1_disk_link.prev == NULL ||
583                             e->v2_disk_link.prev == NULL ||
584                             e->v1_disk_link.next == NULL ||
585                             e->v2_disk_link.next == NULL)
586                         {
587                                 err |= IS_EDGE_NULL_DISK_LINK;
588                         }
589
590                         if (e->l && e->l->head.htype != BM_LOOP) {
591                                 err |= IS_EDGE_WRONG_LOOP_TYPE;
592                         }
593                         if (e->l && e->l->f->head.htype != BM_FACE) {
594                                 err |= IS_EDGE_WRONG_FACE_TYPE;
595                         }
596                         if (e->l && (e->l->radial_next == NULL || e->l->radial_prev == NULL)) {
597                                 err |= IS_EDGE_NULL_RADIAL_LINK;
598                         }
599                         if (e->l && e->l->f->len <= 0) {
600                                 err |= IS_EDGE_ZERO_FACE_LENGTH;
601                         }
602                         break;
603                 }
604                 case BM_LOOP:
605                 {
606                         BMLoop *l = element, *l2;
607                         int i;
608
609                         if (l->f->head.htype != BM_FACE) {
610                                 err |= IS_LOOP_WRONG_FACE_TYPE;
611                         }
612                         if (l->e->head.htype != BM_EDGE) {
613                                 err |= IS_LOOP_WRONG_EDGE_TYPE;
614                         }
615                         if (l->v->head.htype != BM_VERT) {
616                                 err |= IS_LOOP_WRONG_VERT_TYPE;
617                         }
618                         if (!BM_vert_in_edge(l->e, l->v)) {
619                                 fprintf(stderr, "%s: fatal bmesh error (vert not in edge)! (bmesh internal error)\n", __func__);
620                                 err |= IS_LOOP_VERT_NOT_IN_EDGE;
621                         }
622
623                         if (l->radial_next == NULL || l->radial_prev == NULL) {
624                                 err |= IS_LOOP_NULL_CYCLE_LINK;
625                         }
626                         if (l->f->len <= 0) {
627                                 err |= IS_LOOP_ZERO_FACE_LENGTH;
628                         }
629
630                         /* validate boundary loop -- invalid for hole loops, of course,
631                          * but we won't be allowing those for a while yet */
632                         l2 = l;
633                         i = 0;
634                         do {
635                                 if (i >= BM_NGON_MAX) {
636                                         break;
637                                 }
638
639                                 i++;
640                         } while ((l2 = l2->next) != l);
641
642                         if (i != l->f->len || l2 != l) {
643                                 err |= IS_LOOP_WRONG_FACE_LENGTH;
644                         }
645
646                         if (!bmesh_radial_validate(bmesh_radial_length(l), l)) {
647                                 err |= IS_LOOP_WRONG_RADIAL_LENGTH;
648                         }
649
650                         break;
651                 }
652                 case BM_FACE:
653                 {
654                         BMFace *f = element;
655                         BMLoop *l_iter;
656                         BMLoop *l_first;
657                         int len = 0;
658
659 #ifdef USE_BMESH_HOLES
660                         if (!f->loops.first)
661 #else
662                         if (!f->l_first)
663 #endif
664                         {
665                                 err |= IS_FACE_NULL_LOOP;
666                         }
667                         l_iter = l_first = BM_FACE_FIRST_LOOP(f);
668                         do {
669                                 if (l_iter->f != f) {
670                                         fprintf(stderr, "%s: loop inside one face points to another! (bmesh internal error)\n", __func__);
671                                         err |= IS_FACE_WRONG_LOOP_FACE;
672                                 }
673
674                                 if (!l_iter->e) {
675                                         err |= IS_FACE_NULL_EDGE;
676                                 }
677                                 if (!l_iter->v) {
678                                         err |= IS_FACE_NULL_VERT;
679                                 }
680                                 if (l_iter->e && l_iter->v) {
681                                         if (!BM_vert_in_edge(l_iter->e, l_iter->v) ||
682                                             !BM_vert_in_edge(l_iter->e, l_iter->next->v))
683                                         {
684                                                 err |= IS_FACE_LOOP_VERT_NOT_IN_EDGE;
685                                         }
686
687                                         if (!bmesh_radial_validate(bmesh_radial_length(l_iter), l_iter)) {
688                                                 err |= IS_FACE_LOOP_WRONG_RADIAL_LENGTH;
689                                         }
690
691                                         if (bmesh_disk_count_ex(l_iter->v, 2) < 2) {
692                                                 err |= IS_FACE_LOOP_WRONG_DISK_LENGTH;
693                                         }
694                                 }
695
696                                 /* check for duplicates */
697                                 if (BM_ELEM_API_FLAG_TEST(l_iter, _FLAG_ELEM_CHECK)) {
698                                         err |= IS_FACE_LOOP_DUPE_LOOP;
699                                 }
700                                 BM_ELEM_API_FLAG_ENABLE(l_iter, _FLAG_ELEM_CHECK);
701                                 if (l_iter->v) {
702                                         if (BM_ELEM_API_FLAG_TEST(l_iter->v, _FLAG_ELEM_CHECK)) {
703                                                 err |= IS_FACE_LOOP_DUPE_VERT;
704                                         }
705                                         BM_ELEM_API_FLAG_ENABLE(l_iter->v, _FLAG_ELEM_CHECK);
706                                 }
707                                 if (l_iter->e) {
708                                         if (BM_ELEM_API_FLAG_TEST(l_iter->e, _FLAG_ELEM_CHECK)) {
709                                                 err |= IS_FACE_LOOP_DUPE_EDGE;
710                                         }
711                                         BM_ELEM_API_FLAG_ENABLE(l_iter->e, _FLAG_ELEM_CHECK);
712                                 }
713
714                                 len++;
715                         } while ((l_iter = l_iter->next) != l_first);
716
717                         /* cleanup duplicates flag */
718                         l_iter = l_first = BM_FACE_FIRST_LOOP(f);
719                         do {
720                                 BM_ELEM_API_FLAG_DISABLE(l_iter, _FLAG_ELEM_CHECK);
721                                 if (l_iter->v) {
722                                         BM_ELEM_API_FLAG_DISABLE(l_iter->v, _FLAG_ELEM_CHECK);
723                                 }
724                                 if (l_iter->e) {
725                                         BM_ELEM_API_FLAG_DISABLE(l_iter->e, _FLAG_ELEM_CHECK);
726                                 }
727                         } while ((l_iter = l_iter->next) != l_first);
728
729                         if (len != f->len) {
730                                 err |= IS_FACE_WRONG_LENGTH;
731                         }
732                         break;
733                 }
734                 default:
735                         BLI_assert(0);
736                         break;
737         }
738
739         BMESH_ASSERT(err == 0);
740
741         return err;
742 }
743
744 #endif /* NDEBUG */
745
746 /**
747  * low level function, only frees the vert,
748  * doesn't change or adjust surrounding geometry
749  */
750 static void bm_kill_only_vert(BMesh *bm, BMVert *v)
751 {
752         bm->totvert--;
753         bm->elem_index_dirty |= BM_VERT;
754         bm->elem_table_dirty |= BM_VERT;
755
756         BM_select_history_remove(bm, v);
757
758         if (v->head.data)
759                 CustomData_bmesh_free_block(&bm->vdata, &v->head.data);
760
761         if (bm->vtoolflagpool) {
762                 BLI_mempool_free(bm->vtoolflagpool, ((BMVert_OFlag *)v)->oflags);
763         }
764         BLI_mempool_free(bm->vpool, v);
765 }
766
767 /**
768  * low level function, only frees the edge,
769  * doesn't change or adjust surrounding geometry
770  */
771 static void bm_kill_only_edge(BMesh *bm, BMEdge *e)
772 {
773         bm->totedge--;
774         bm->elem_index_dirty |= BM_EDGE;
775         bm->elem_table_dirty |= BM_EDGE;
776
777         BM_select_history_remove(bm, (BMElem *)e);
778
779         if (e->head.data)
780                 CustomData_bmesh_free_block(&bm->edata, &e->head.data);
781
782         if (bm->etoolflagpool) {
783                 BLI_mempool_free(bm->etoolflagpool, ((BMEdge_OFlag *)e)->oflags);
784         }
785         BLI_mempool_free(bm->epool, e);
786 }
787
788 /**
789  * low level function, only frees the face,
790  * doesn't change or adjust surrounding geometry
791  */
792 static void bm_kill_only_face(BMesh *bm, BMFace *f)
793 {
794         if (bm->act_face == f)
795                 bm->act_face = NULL;
796
797         bm->totface--;
798         bm->elem_index_dirty |= BM_FACE;
799         bm->elem_table_dirty |= BM_FACE;
800
801         BM_select_history_remove(bm, (BMElem *)f);
802
803         if (f->head.data)
804                 CustomData_bmesh_free_block(&bm->pdata, &f->head.data);
805
806         if (bm->ftoolflagpool) {
807                 BLI_mempool_free(bm->ftoolflagpool, ((BMFace_OFlag *)f)->oflags);
808         }
809         BLI_mempool_free(bm->fpool, f);
810 }
811
812 /**
813  * low level function, only frees the loop,
814  * doesn't change or adjust surrounding geometry
815  */
816 static void bm_kill_only_loop(BMesh *bm, BMLoop *l)
817 {
818         bm->totloop--;
819         bm->elem_index_dirty |= BM_LOOP;
820         if (l->head.data)
821                 CustomData_bmesh_free_block(&bm->ldata, &l->head.data);
822
823         BLI_mempool_free(bm->lpool, l);
824 }
825
826 /**
827  * kills all edges associated with \a f, along with any other faces containing
828  * those edges
829  */
830 void BM_face_edges_kill(BMesh *bm, BMFace *f)
831 {
832         BMEdge **edges = BLI_array_alloca(edges, f->len);
833         BMLoop *l_iter;
834         BMLoop *l_first;
835         int i = 0;
836         
837         l_iter = l_first = BM_FACE_FIRST_LOOP(f);
838         do {
839                 edges[i++] = l_iter->e;
840         } while ((l_iter = l_iter->next) != l_first);
841         
842         for (i = 0; i < f->len; i++) {
843                 BM_edge_kill(bm, edges[i]);
844         }
845 }
846
847 /**
848  * kills all verts associated with \a f, along with any other faces containing
849  * those vertices
850  */
851 void BM_face_verts_kill(BMesh *bm, BMFace *f)
852 {
853         BMVert **verts = BLI_array_alloca(verts, f->len);
854         BMLoop *l_iter;
855         BMLoop *l_first;
856         int i = 0;
857         
858         l_iter = l_first = BM_FACE_FIRST_LOOP(f);
859         do {
860                 verts[i++] = l_iter->v;
861         } while ((l_iter = l_iter->next) != l_first);
862         
863         for (i = 0; i < f->len; i++) {
864                 BM_vert_kill(bm, verts[i]);
865         }
866 }
867
868 /**
869  * Kills \a f and its loops.
870  */
871 void BM_face_kill(BMesh *bm, BMFace *f)
872 {
873 #ifdef USE_BMESH_HOLES
874         BMLoopList *ls, *ls_next;
875 #endif
876
877 #ifdef NDEBUG
878         /* check length since we may be removing degenerate faces */
879         if (f->len >= 3) {
880                 BM_CHECK_ELEMENT(f);
881         }
882 #endif
883
884 #ifdef USE_BMESH_HOLES
885         for (ls = f->loops.first; ls; ls = ls_next)
886 #else
887         if (f->l_first)
888 #endif
889         {
890                 BMLoop *l_iter, *l_next, *l_first;
891
892 #ifdef USE_BMESH_HOLES
893                 ls_next = ls->next;
894                 l_iter = l_first = ls->first;
895 #else
896                 l_iter = l_first = f->l_first;
897 #endif
898
899                 do {
900                         l_next = l_iter->next;
901
902                         bmesh_radial_loop_remove(l_iter->e, l_iter);
903                         bm_kill_only_loop(bm, l_iter);
904
905                 } while ((l_iter = l_next) != l_first);
906
907 #ifdef USE_BMESH_HOLES
908                 BLI_mempool_free(bm->looplistpool, ls);
909 #endif
910         }
911
912         bm_kill_only_face(bm, f);
913 }
914
915 /**
916  * A version of #BM_face_kill which removes edges and verts
917  * which have no remaining connected geometry.
918  */
919 void BM_face_kill_loose(BMesh *bm, BMFace *f)
920 {
921 #ifdef USE_BMESH_HOLES
922         BMLoopList *ls, *ls_next;
923 #endif
924
925         BM_CHECK_ELEMENT(f);
926
927 #ifdef USE_BMESH_HOLES
928         for (ls = f->loops.first; ls; ls = ls_next)
929 #else
930         if (f->l_first)
931 #endif
932         {
933                 BMLoop *l_iter, *l_next, *l_first;
934
935 #ifdef USE_BMESH_HOLES
936                 ls_next = ls->next;
937                 l_iter = l_first = ls->first;
938 #else
939                 l_iter = l_first = f->l_first;
940 #endif
941
942                 do {
943                         BMEdge *e;
944                         l_next = l_iter->next;
945
946                         e = l_iter->e;
947                         bmesh_radial_loop_remove(e, l_iter);
948                         bm_kill_only_loop(bm, l_iter);
949
950                         if (e->l == NULL) {
951                                 BMVert *v1 = e->v1, *v2 = e->v2;
952
953                                 bmesh_disk_edge_remove(e, e->v1);
954                                 bmesh_disk_edge_remove(e, e->v2);
955                                 bm_kill_only_edge(bm, e);
956
957                                 if (v1->e == NULL) {
958                                         bm_kill_only_vert(bm, v1);
959                                 }
960                                 if (v2->e == NULL) {
961                                         bm_kill_only_vert(bm, v2);
962                                 }
963                         }
964                 } while ((l_iter = l_next) != l_first);
965
966 #ifdef USE_BMESH_HOLES
967                 BLI_mempool_free(bm->looplistpool, ls);
968 #endif
969         }
970
971         bm_kill_only_face(bm, f);
972 }
973
974 /**
975  * kills \a e and all faces that use it.
976  */
977 void BM_edge_kill(BMesh *bm, BMEdge *e)
978 {
979         while (e->l) {
980                 BM_face_kill(bm, e->l->f);
981         }
982
983         bmesh_disk_edge_remove(e, e->v1);
984         bmesh_disk_edge_remove(e, e->v2);
985         
986         bm_kill_only_edge(bm, e);
987 }
988
989 /**
990  * kills \a v and all edges that use it.
991  */
992 void BM_vert_kill(BMesh *bm, BMVert *v)
993 {
994         while (v->e) {
995                 BM_edge_kill(bm, v->e);
996         }
997
998         bm_kill_only_vert(bm, v);
999 }
1000
1001 /********** private disk and radial cycle functions ********** */
1002
1003 /**
1004  * return the length of the face, should always equal \a l->f->len
1005  */
1006 static int UNUSED_FUNCTION(bm_loop_length)(BMLoop *l)
1007 {
1008         BMLoop *l_first = l;
1009         int i = 0;
1010
1011         do {
1012                 i++;
1013         } while ((l = l->next) != l_first);
1014
1015         return i;
1016 }
1017
1018 /**
1019  * \brief Loop Reverse
1020  *
1021  * Changes the winding order of a face from CW to CCW or vice versa.
1022  * This euler is a bit peculiar in comparison to others as it is its
1023  * own inverse.
1024  *
1025  * BMESH_TODO: reinsert validation code.
1026  *
1027  * \param cd_loop_mdisp_offset: Cached result of `CustomData_get_offset(&bm->ldata, CD_MDISPS)`.
1028  * \param use_loop_mdisp_flip: When set, flip the Z-depth of the mdisp,
1029  * (use when flipping normals, disable when mirroring, eg: symmetrize).
1030  *
1031  * \return Success
1032  */
1033 static bool bm_loop_reverse_loop(
1034         BMesh *bm, BMFace *f,
1035 #ifdef USE_BMESH_HOLES
1036         BMLoopList *lst,
1037 #endif
1038         const int cd_loop_mdisp_offset, const bool use_loop_mdisp_flip)
1039 {
1040
1041 #ifdef USE_BMESH_HOLES
1042         BMLoop *l_first = lst->first;
1043 #else
1044         BMLoop *l_first = f->l_first;
1045 #endif
1046
1047         const int len = f->len;
1048         BMLoop *l_iter, *oldprev, *oldnext;
1049         BMEdge **edar = BLI_array_alloca(edar, len);
1050         int i, j, edok;
1051
1052         for (i = 0, l_iter = l_first; i < len; i++, l_iter = l_iter->next) {
1053                 bmesh_radial_loop_remove((edar[i] = l_iter->e), l_iter);
1054         }
1055
1056         /* actually reverse the loop */
1057         for (i = 0, l_iter = l_first; i < len; i++) {
1058                 oldnext = l_iter->next;
1059                 oldprev = l_iter->prev;
1060                 l_iter->next = oldprev;
1061                 l_iter->prev = oldnext;
1062                 l_iter = oldnext;
1063                 
1064                 if (cd_loop_mdisp_offset != -1) {
1065                         MDisps *md = BM_ELEM_CD_GET_VOID_P(l_iter, cd_loop_mdisp_offset);
1066                         BKE_mesh_mdisp_flip(md, use_loop_mdisp_flip);
1067                 }
1068         }
1069
1070         if (len == 2) { /* two edged face */
1071                 /* do some verification here! */
1072                 l_first->e = edar[1];
1073                 l_first->next->e = edar[0];
1074         }
1075         else {
1076                 for (i = 0, l_iter = l_first; i < len; i++, l_iter = l_iter->next) {
1077                         edok = 0;
1078                         for (j = 0; j < len; j++) {
1079                                 edok = BM_verts_in_edge(l_iter->v, l_iter->next->v, edar[j]);
1080                                 if (edok) {
1081                                         l_iter->e = edar[j];
1082                                         break;
1083                                 }
1084                         }
1085                 }
1086         }
1087         /* rebuild radial */
1088         for (i = 0, l_iter = l_first; i < len; i++, l_iter = l_iter->next)
1089                 bmesh_radial_loop_append(l_iter->e, l_iter);
1090
1091 #ifndef NDEBUG
1092         /* validate radial */
1093         for (i = 0, l_iter = l_first; i < len; i++, l_iter = l_iter->next) {
1094                 BM_CHECK_ELEMENT(l_iter);
1095                 BM_CHECK_ELEMENT(l_iter->e);
1096                 BM_CHECK_ELEMENT(l_iter->v);
1097                 BM_CHECK_ELEMENT(l_iter->f);
1098         }
1099
1100         BM_CHECK_ELEMENT(f);
1101 #endif
1102
1103         /* Loop indices are no more valid! */
1104         bm->elem_index_dirty |= BM_LOOP;
1105
1106         return true;
1107 }
1108
1109 /**
1110  * \brief Flip the faces direction
1111  */
1112 bool bmesh_loop_reverse(
1113         BMesh *bm, BMFace *f,
1114         const int cd_loop_mdisp_offset, const bool use_loop_mdisp_flip)
1115 {
1116 #ifdef USE_BMESH_HOLES
1117         return bm_loop_reverse_loop(bm, f, f->loops.first, cd_loop_mdisp_offset, use_loop_mdisp_flip);
1118 #else
1119         return bm_loop_reverse_loop(bm, f, cd_loop_mdisp_offset, use_loop_mdisp_flip);
1120 #endif
1121 }
1122
1123 static void bm_elements_systag_enable(void *veles, int tot, const char api_flag)
1124 {
1125         BMHeader **eles = veles;
1126         int i;
1127
1128         for (i = 0; i < tot; i++) {
1129                 BM_ELEM_API_FLAG_ENABLE((BMElemF *)eles[i], api_flag);
1130         }
1131 }
1132
1133 static void bm_elements_systag_disable(void *veles, int tot, const char api_flag)
1134 {
1135         BMHeader **eles = veles;
1136         int i;
1137
1138         for (i = 0; i < tot; i++) {
1139                 BM_ELEM_API_FLAG_DISABLE((BMElemF *)eles[i], api_flag);
1140         }
1141 }
1142
1143 static int bm_loop_systag_count_radial(BMLoop *l, const char api_flag)
1144 {
1145         BMLoop *l_iter = l;
1146         int i = 0;
1147         do {
1148                 i += BM_ELEM_API_FLAG_TEST(l_iter->f, api_flag) ? 1 : 0;
1149         } while ((l_iter = l_iter->radial_next) != l);
1150
1151         return i;
1152 }
1153
1154 static int UNUSED_FUNCTION(bm_vert_systag_count_disk)(BMVert *v, const char api_flag)
1155 {
1156         BMEdge *e = v->e;
1157         int i = 0;
1158
1159         if (!e)
1160                 return 0;
1161
1162         do {
1163                 i += BM_ELEM_API_FLAG_TEST(e, api_flag) ? 1 : 0;
1164         } while ((e = bmesh_disk_edge_next(e, v)) != v->e);
1165
1166         return i;
1167 }
1168
1169 static bool disk_is_flagged(BMVert *v, const char api_flag)
1170 {
1171         BMEdge *e = v->e;
1172
1173         if (!e)
1174                 return false;
1175
1176         do {
1177                 BMLoop *l = e->l;
1178
1179                 if (!l) {
1180                         return false;
1181                 }
1182                 
1183                 if (BM_edge_is_boundary(l->e)) {
1184                         return false;
1185                 }
1186                 
1187                 do {
1188                         if (!BM_ELEM_API_FLAG_TEST(l->f, api_flag))
1189                                 return false;
1190                 } while ((l = l->radial_next) != e->l);
1191         } while ((e = bmesh_disk_edge_next(e, v)) != v->e);
1192
1193         return true;
1194 }
1195
1196 /* Mid-level Topology Manipulation Functions */
1197
1198 /**
1199  * \brief Join Connected Faces
1200  *
1201  * Joins a collected group of faces into one. Only restriction on
1202  * the input data is that the faces must be connected to each other.
1203  *
1204  * \return The newly created combine BMFace.
1205  *
1206  * \note If a pair of faces share multiple edges,
1207  * the pair of faces will be joined at every edge.
1208  *
1209  * \note this is a generic, flexible join faces function,
1210  * almost everything uses this, including #BM_faces_join_pair
1211  */
1212 BMFace *BM_faces_join(BMesh *bm, BMFace **faces, int totface, const bool do_del)
1213 {
1214         BMFace *f, *f_new;
1215 #ifdef USE_BMESH_HOLES
1216         BMLoopList *lst;
1217         ListBase holes = {NULL, NULL};
1218 #endif
1219         BMLoop *l_iter;
1220         BMLoop *l_first;
1221         BMEdge **edges = NULL;
1222         BMEdge **deledges = NULL;
1223         BMVert **delverts = NULL;
1224         BLI_array_staticdeclare(edges,    BM_DEFAULT_NGON_STACK_SIZE);
1225         BLI_array_staticdeclare(deledges, BM_DEFAULT_NGON_STACK_SIZE);
1226         BLI_array_staticdeclare(delverts, BM_DEFAULT_NGON_STACK_SIZE);
1227         BMVert *v1 = NULL, *v2 = NULL;
1228         int i, tote = 0;
1229         const int cd_loop_mdisp_offset = CustomData_get_offset(&bm->ldata, CD_MDISPS);
1230
1231         if (UNLIKELY(!totface)) {
1232                 BMESH_ASSERT(0);
1233                 return NULL;
1234         }
1235
1236         if (totface == 1)
1237                 return faces[0];
1238
1239         bm_elements_systag_enable(faces, totface, _FLAG_JF);
1240
1241         for (i = 0; i < totface; i++) {
1242                 f = faces[i];
1243                 l_iter = l_first = BM_FACE_FIRST_LOOP(f);
1244                 do {
1245                         int rlen = bm_loop_systag_count_radial(l_iter, _FLAG_JF);
1246
1247                         if (rlen > 2) {
1248                                 /* Input faces do not form a contiguous manifold region */
1249                                 goto error;
1250                         }
1251                         else if (rlen == 1) {
1252                                 BLI_array_append(edges, l_iter->e);
1253
1254                                 if (!v1) {
1255                                         v1 = l_iter->v;
1256                                         v2 = BM_edge_other_vert(l_iter->e, l_iter->v);
1257                                 }
1258                                 tote++;
1259                         }
1260                         else if (rlen == 2) {
1261                                 int d1, d2;
1262
1263                                 d1 = disk_is_flagged(l_iter->e->v1, _FLAG_JF);
1264                                 d2 = disk_is_flagged(l_iter->e->v2, _FLAG_JF);
1265
1266                                 if (!d1 && !d2 && !BM_ELEM_API_FLAG_TEST(l_iter->e, _FLAG_JF)) {
1267                                         /* don't remove an edge it makes up the side of another face
1268                                          * else this will remove the face as well - campbell */
1269                                         if (!BM_edge_face_count_is_over(l_iter->e, 2)) {
1270                                                 if (do_del) {
1271                                                         BLI_array_append(deledges, l_iter->e);
1272                                                 }
1273                                                 BM_ELEM_API_FLAG_ENABLE(l_iter->e, _FLAG_JF);
1274                                         }
1275                                 }
1276                                 else {
1277                                         if (d1 && !BM_ELEM_API_FLAG_TEST(l_iter->e->v1, _FLAG_JF)) {
1278                                                 if (do_del) {
1279                                                         BLI_array_append(delverts, l_iter->e->v1);
1280                                                 }
1281                                                 BM_ELEM_API_FLAG_ENABLE(l_iter->e->v1, _FLAG_JF);
1282                                         }
1283
1284                                         if (d2 && !BM_ELEM_API_FLAG_TEST(l_iter->e->v2, _FLAG_JF)) {
1285                                                 if (do_del) {
1286                                                         BLI_array_append(delverts, l_iter->e->v2);
1287                                                 }
1288                                                 BM_ELEM_API_FLAG_ENABLE(l_iter->e->v2, _FLAG_JF);
1289                                         }
1290                                 }
1291                         }
1292                 } while ((l_iter = l_iter->next) != l_first);
1293
1294 #ifdef USE_BMESH_HOLES
1295                 for (lst = f->loops.first; lst; lst = lst->next) {
1296                         if (lst == f->loops.first) {
1297                                 continue;
1298                         }
1299
1300                         BLI_remlink(&f->loops, lst);
1301                         BLI_addtail(&holes, lst);
1302                 }
1303 #endif
1304
1305         }
1306
1307         /* create region face */
1308         f_new = tote ? BM_face_create_ngon(bm, v1, v2, edges, tote, faces[0], BM_CREATE_NOP) : NULL;
1309         if (UNLIKELY(f_new == NULL)) {
1310                 /* Invalid boundary region to join faces */
1311                 goto error;
1312         }
1313
1314         /* copy over loop data */
1315         l_iter = l_first = BM_FACE_FIRST_LOOP(f_new);
1316         do {
1317                 BMLoop *l2 = l_iter->radial_next;
1318
1319                 do {
1320                         if (BM_ELEM_API_FLAG_TEST(l2->f, _FLAG_JF))
1321                                 break;
1322                         l2 = l2->radial_next;
1323                 } while (l2 != l_iter);
1324
1325                 if (l2 != l_iter) {
1326                         /* I think this is correct? */
1327                         if (l2->v != l_iter->v) {
1328                                 l2 = l2->next;
1329                         }
1330
1331                         BM_elem_attrs_copy(bm, bm, l2, l_iter);
1332                 }
1333         } while ((l_iter = l_iter->next) != l_first);
1334
1335 #ifdef USE_BMESH_HOLES
1336         /* add holes */
1337         BLI_movelisttolist(&f_new->loops, &holes);
1338 #endif
1339
1340         /* update loop face pointer */
1341 #ifdef USE_BMESH_HOLES
1342         for (lst = f_new->loops.first; lst; lst = lst->next)
1343 #endif
1344         {
1345 #ifdef USE_BMESH_HOLES
1346                 l_iter = l_first = lst->first;
1347 #else
1348                 l_iter = l_first = BM_FACE_FIRST_LOOP(f_new);
1349 #endif
1350                 do {
1351                         l_iter->f = f_new;
1352                 } while ((l_iter = l_iter->next) != l_first);
1353         }
1354
1355         bm_elements_systag_disable(faces, totface, _FLAG_JF);
1356         BM_ELEM_API_FLAG_DISABLE(f_new, _FLAG_JF);
1357
1358         /* handle multi-res data */
1359         if (cd_loop_mdisp_offset != -1) {
1360                 float f_center[3];
1361                 float (*faces_center)[3] = BLI_array_alloca(faces_center, totface);
1362
1363                 BM_face_calc_center_mean(f_new, f_center);
1364                 for (i = 0; i < totface; i++) {
1365                         BM_face_calc_center_mean(faces[i], faces_center[i]);
1366                 }
1367
1368                 l_iter = l_first = BM_FACE_FIRST_LOOP(f_new);
1369                 do {
1370                         for (i = 0; i < totface; i++) {
1371                                 BM_loop_interp_multires_ex(bm, l_iter, faces[i], f_center, faces_center[i], cd_loop_mdisp_offset);
1372                         }
1373                 } while ((l_iter = l_iter->next) != l_first);
1374         }
1375
1376         /* delete old geometry */
1377         if (do_del) {
1378                 for (i = 0; i < BLI_array_count(deledges); i++) {
1379                         BM_edge_kill(bm, deledges[i]);
1380                 }
1381
1382                 for (i = 0; i < BLI_array_count(delverts); i++) {
1383                         BM_vert_kill(bm, delverts[i]);
1384                 }
1385         }
1386         else {
1387                 /* otherwise we get both old and new faces */
1388                 for (i = 0; i < totface; i++) {
1389                         BM_face_kill(bm, faces[i]);
1390                 }
1391         }
1392         
1393         BLI_array_free(edges);
1394         BLI_array_free(deledges);
1395         BLI_array_free(delverts);
1396
1397         BM_CHECK_ELEMENT(f_new);
1398         return f_new;
1399
1400 error:
1401         bm_elements_systag_disable(faces, totface, _FLAG_JF);
1402         BLI_array_free(edges);
1403         BLI_array_free(deledges);
1404         BLI_array_free(delverts);
1405
1406         return NULL;
1407 }
1408
1409 static BMFace *bm_face_create__sfme(BMesh *bm, BMFace *f_example)
1410 {
1411         BMFace *f;
1412 #ifdef USE_BMESH_HOLES
1413         BMLoopList *lst;
1414 #endif
1415
1416         f = bm_face_create__internal(bm);
1417
1418 #ifdef USE_BMESH_HOLES
1419         lst = BLI_mempool_calloc(bm->looplistpool);
1420         BLI_addtail(&f->loops, lst);
1421 #endif
1422
1423 #ifdef USE_BMESH_HOLES
1424         f->totbounds = 1;
1425 #endif
1426
1427         BM_elem_attrs_copy(bm, bm, f_example, f);
1428
1429         return f;
1430 }
1431
1432 /**
1433  * \brief Split Face Make Edge (SFME)
1434  *
1435  * \warning this is a low level function, most likely you want to use #BM_face_split()
1436  *
1437  * Takes as input two vertices in a single face. An edge is created which divides the original face
1438  * into two distinct regions. One of the regions is assigned to the original face and it is closed off.
1439  * The second region has a new face assigned to it.
1440  *
1441  * \par Examples:
1442  * <pre>
1443  *     Before:               After:
1444  *      +--------+           +--------+
1445  *      |        |           |        |
1446  *      |        |           |   f1   |
1447  *     v1   f1   v2          v1======v2
1448  *      |        |           |   f2   |
1449  *      |        |           |        |
1450  *      +--------+           +--------+
1451  * </pre>
1452  *
1453  * \note the input vertices can be part of the same edge. This will
1454  * result in a two edged face. This is desirable for advanced construction
1455  * tools and particularly essential for edge bevel. Because of this it is
1456  * up to the caller to decide what to do with the extra edge.
1457  *
1458  * \note If \a holes is NULL, then both faces will lose
1459  * all holes from the original face.  Also, you cannot split between
1460  * a hole vert and a boundary vert; that case is handled by higher-
1461  * level wrapping functions (when holes are fully implemented, anyway).
1462  *
1463  * \note that holes represents which holes goes to the new face, and of
1464  * course this requires removing them from the existing face first, since
1465  * you cannot have linked list links inside multiple lists.
1466  *
1467  * \return A BMFace pointer
1468  */
1469 BMFace *bmesh_sfme(
1470         BMesh *bm, BMFace *f, BMLoop *l_v1, BMLoop *l_v2,
1471         BMLoop **r_l,
1472 #ifdef USE_BMESH_HOLES
1473         ListBase *holes,
1474 #endif
1475         BMEdge *e_example,
1476         const bool no_double)
1477 {
1478 #ifdef USE_BMESH_HOLES
1479         BMLoopList *lst, *lst2;
1480 #else
1481         int first_loop_f1;
1482 #endif
1483
1484         BMFace *f2;
1485         BMLoop *l_iter, *l_first;
1486         BMLoop *l_f1 = NULL, *l_f2 = NULL;
1487         BMEdge *e;
1488         BMVert *v1 = l_v1->v, *v2 = l_v2->v;
1489         int f1len, f2len;
1490
1491         BLI_assert(f == l_v1->f && f == l_v2->f);
1492
1493         /* allocate new edge between v1 and v2 */
1494         e = BM_edge_create(bm, v1, v2, e_example, no_double ? BM_CREATE_NO_DOUBLE : BM_CREATE_NOP);
1495
1496         f2 = bm_face_create__sfme(bm, f);
1497         l_f1 = bm_loop_create(bm, v2, e, f, l_v2, 0);
1498         l_f2 = bm_loop_create(bm, v1, e, f2, l_v1, 0);
1499
1500         l_f1->prev = l_v2->prev;
1501         l_f2->prev = l_v1->prev;
1502         l_v2->prev->next = l_f1;
1503         l_v1->prev->next = l_f2;
1504
1505         l_f1->next = l_v1;
1506         l_f2->next = l_v2;
1507         l_v1->prev = l_f1;
1508         l_v2->prev = l_f2;
1509
1510 #ifdef USE_BMESH_HOLES
1511         lst = f->loops.first;
1512         lst2 = f2->loops.first;
1513
1514         lst2->first = lst2->last = l_f2;
1515         lst->first = lst->last = l_f1;
1516 #else
1517         /* find which of the faces the original first loop is in */
1518         l_iter = l_first = l_f1;
1519         first_loop_f1 = 0;
1520         do {
1521                 if (l_iter == f->l_first)
1522                         first_loop_f1 = 1;
1523         } while ((l_iter = l_iter->next) != l_first);
1524
1525         if (first_loop_f1) {
1526                 /* original first loop was in f1, find a suitable first loop for f2
1527                  * which is as similar as possible to f1. the order matters for tools
1528                  * such as duplifaces. */
1529                 if (f->l_first->prev == l_f1)
1530                         f2->l_first = l_f2->prev;
1531                 else if (f->l_first->next == l_f1)
1532                         f2->l_first = l_f2->next;
1533                 else
1534                         f2->l_first = l_f2;
1535         }
1536         else {
1537                 /* original first loop was in f2, further do same as above */
1538                 f2->l_first = f->l_first;
1539
1540                 if (f->l_first->prev == l_f2)
1541                         f->l_first = l_f1->prev;
1542                 else if (f->l_first->next == l_f2)
1543                         f->l_first = l_f1->next;
1544                 else
1545                         f->l_first = l_f1;
1546         }
1547 #endif
1548
1549         /* validate both loop */
1550         /* I don't know how many loops are supposed to be in each face at this point! FIXME */
1551
1552         /* go through all of f2's loops and make sure they point to it properly */
1553         l_iter = l_first = BM_FACE_FIRST_LOOP(f2);
1554         f2len = 0;
1555         do {
1556                 l_iter->f = f2;
1557                 f2len++;
1558         } while ((l_iter = l_iter->next) != l_first);
1559
1560         /* link up the new loops into the new edges radial */
1561         bmesh_radial_loop_append(e, l_f1);
1562         bmesh_radial_loop_append(e, l_f2);
1563
1564         f2->len = f2len;
1565
1566         f1len = 0;
1567         l_iter = l_first = BM_FACE_FIRST_LOOP(f);
1568         do {
1569                 f1len++;
1570         } while ((l_iter = l_iter->next) != l_first);
1571
1572         f->len = f1len;
1573
1574         if (r_l) *r_l = l_f2;
1575
1576 #ifdef USE_BMESH_HOLES
1577         if (holes) {
1578                 BLI_movelisttolist(&f2->loops, holes);
1579         }
1580         else {
1581                 /* this code is not significant until holes actually work */
1582                 //printf("warning: call to split face euler without holes argument; holes will be tossed.\n");
1583                 for (lst = f->loops.last; lst != f->loops.first; lst = lst2) {
1584                         lst2 = lst->prev;
1585                         BLI_mempool_free(bm->looplistpool, lst);
1586                 }
1587         }
1588 #endif
1589
1590         BM_CHECK_ELEMENT(e);
1591         BM_CHECK_ELEMENT(f);
1592         BM_CHECK_ELEMENT(f2);
1593         
1594         return f2;
1595 }
1596
1597 /**
1598  * \brief Split Edge Make Vert (SEMV)
1599  *
1600  * Takes \a e edge and splits it into two, creating a new vert.
1601  * \a tv should be one end of \a e : the newly created edge
1602  * will be attached to that end and is returned in \a r_e.
1603  *
1604  * \par Examples:
1605  *
1606  * <pre>
1607  *                     E
1608  *     Before: OV-------------TV
1609  *                 E       RE
1610  *     After:  OV------NV-----TV
1611  * </pre>
1612  *
1613  * \return The newly created BMVert pointer.
1614  */
1615 BMVert *bmesh_semv(BMesh *bm, BMVert *tv, BMEdge *e, BMEdge **r_e)
1616 {
1617         BMLoop *l_next;
1618         BMEdge *e_new;
1619         BMVert *v_new, *v_old;
1620 #ifndef NDEBUG
1621         int valence1, valence2;
1622         bool edok;
1623         int i;
1624 #endif
1625
1626         BLI_assert(BM_vert_in_edge(e, tv) != false);
1627
1628         v_old = BM_edge_other_vert(e, tv);
1629
1630 #ifndef NDEBUG
1631         valence1 = bmesh_disk_count(v_old);
1632         valence2 = bmesh_disk_count(tv);
1633 #endif
1634
1635         /* order of 'e_new' verts should match 'e'
1636          * (so extruded faces don't flip) */
1637         v_new = BM_vert_create(bm, tv->co, tv, BM_CREATE_NOP);
1638         e_new = BM_edge_create(bm, tv, v_new, e, BM_CREATE_NOP);
1639
1640         bmesh_disk_edge_remove(e_new, tv);
1641         bmesh_disk_edge_remove(e_new, v_new);
1642
1643         bmesh_disk_vert_replace(e, v_new, tv);
1644
1645         /* add e_new to v_new's disk cycle */
1646         bmesh_disk_edge_append(e_new, v_new);
1647
1648         /* add e_new to tv's disk cycle */
1649         bmesh_disk_edge_append(e_new, tv);
1650
1651 #ifndef NDEBUG
1652         /* verify disk cycles */
1653         edok = bmesh_disk_validate(valence1, v_old->e, v_old);
1654         BMESH_ASSERT(edok != false);
1655         edok = bmesh_disk_validate(valence2, tv->e, tv);
1656         BMESH_ASSERT(edok != false);
1657         edok = bmesh_disk_validate(2, v_new->e, v_new);
1658         BMESH_ASSERT(edok != false);
1659 #endif
1660
1661         /* Split the radial cycle if present */
1662         l_next = e->l;
1663         e->l = NULL;
1664         if (l_next) {
1665                 BMLoop *l_new, *l;
1666 #ifndef NDEBUG
1667                 int radlen = bmesh_radial_length(l_next);
1668 #endif
1669                 int first1 = 0, first2 = 0;
1670
1671                 /* Take the next loop. Remove it from radial. Split it. Append to appropriate radials */
1672                 while (l_next) {
1673                         l = l_next;
1674                         l->f->len++;
1675                         l_next = l_next != l_next->radial_next ? l_next->radial_next : NULL;
1676                         bmesh_radial_loop_unlink(l);
1677
1678                         l_new = bm_loop_create(bm, NULL, NULL, l->f, l, 0);
1679                         l_new->prev = l;
1680                         l_new->next = (l->next);
1681                         l_new->prev->next = l_new;
1682                         l_new->next->prev = l_new;
1683                         l_new->v = v_new;
1684
1685                         /* assign the correct edge to the correct loop */
1686                         if (BM_verts_in_edge(l_new->v, l_new->next->v, e)) {
1687                                 l_new->e = e;
1688                                 l->e = e_new;
1689
1690                                 /* append l into e_new's rad cycle */
1691                                 if (!first1) {
1692                                         first1 = 1;
1693                                         l->radial_next = l->radial_prev = NULL;
1694                                 }
1695
1696                                 if (!first2) {
1697                                         first2 = 1;
1698                                         l->radial_next = l->radial_prev = NULL;
1699                                 }
1700                                 
1701                                 bmesh_radial_loop_append(l_new->e, l_new);
1702                                 bmesh_radial_loop_append(l->e, l);
1703                         }
1704                         else if (BM_verts_in_edge(l_new->v, l_new->next->v, e_new)) {
1705                                 l_new->e = e_new;
1706                                 l->e = e;
1707
1708                                 /* append l into e_new's rad cycle */
1709                                 if (!first1) {
1710                                         first1 = 1;
1711                                         l->radial_next = l->radial_prev = NULL;
1712                                 }
1713
1714                                 if (!first2) {
1715                                         first2 = 1;
1716                                         l->radial_next = l->radial_prev = NULL;
1717                                 }
1718
1719                                 bmesh_radial_loop_append(l_new->e, l_new);
1720                                 bmesh_radial_loop_append(l->e, l);
1721                         }
1722
1723                 }
1724
1725 #ifndef NDEBUG
1726                 /* verify length of radial cycle */
1727                 edok = bmesh_radial_validate(radlen, e->l);
1728                 BMESH_ASSERT(edok != false);
1729                 edok = bmesh_radial_validate(radlen, e_new->l);
1730                 BMESH_ASSERT(edok != false);
1731
1732                 /* verify loop->v and loop->next->v pointers for e */
1733                 for (i = 0, l = e->l; i < radlen; i++, l = l->radial_next) {
1734                         BMESH_ASSERT(l->e == e);
1735                         //BMESH_ASSERT(l->radial_next == l);
1736                         BMESH_ASSERT(!(l->prev->e != e_new && l->next->e != e_new));
1737
1738                         edok = BM_verts_in_edge(l->v, l->next->v, e);
1739                         BMESH_ASSERT(edok != false);
1740                         BMESH_ASSERT(l->v != l->next->v);
1741                         BMESH_ASSERT(l->e != l->next->e);
1742
1743                         /* verify loop cycle for kloop->f */
1744                         BM_CHECK_ELEMENT(l);
1745                         BM_CHECK_ELEMENT(l->v);
1746                         BM_CHECK_ELEMENT(l->e);
1747                         BM_CHECK_ELEMENT(l->f);
1748                 }
1749                 /* verify loop->v and loop->next->v pointers for e_new */
1750                 for (i = 0, l = e_new->l; i < radlen; i++, l = l->radial_next) {
1751                         BMESH_ASSERT(l->e == e_new);
1752                         // BMESH_ASSERT(l->radial_next == l);
1753                         BMESH_ASSERT(!(l->prev->e != e && l->next->e != e));
1754                         edok = BM_verts_in_edge(l->v, l->next->v, e_new);
1755                         BMESH_ASSERT(edok != false);
1756                         BMESH_ASSERT(l->v != l->next->v);
1757                         BMESH_ASSERT(l->e != l->next->e);
1758
1759                         BM_CHECK_ELEMENT(l);
1760                         BM_CHECK_ELEMENT(l->v);
1761                         BM_CHECK_ELEMENT(l->e);
1762                         BM_CHECK_ELEMENT(l->f);
1763                 }
1764 #endif
1765         }
1766
1767         BM_CHECK_ELEMENT(e_new);
1768         BM_CHECK_ELEMENT(v_new);
1769         BM_CHECK_ELEMENT(v_old);
1770         BM_CHECK_ELEMENT(e);
1771         BM_CHECK_ELEMENT(tv);
1772
1773         if (r_e) *r_e = e_new;
1774         return v_new;
1775 }
1776
1777 /**
1778  * \brief Join Edge Kill Vert (JEKV)
1779  *
1780  * Takes an edge \a e_kill and pointer to one of its vertices \a v_kill
1781  * and collapses the edge on that vertex.
1782  *
1783  * \par Examples:
1784  *
1785  * <pre>
1786  *     Before:    e_old  e_kill
1787  *              +-------+-------+
1788  *              |       |       |
1789  *              v_old   v_kill  v_target
1790  *
1791  *     After:           e_old
1792  *              +---------------+
1793  *              |               |
1794  *              v_old           v_target
1795  * </pre>
1796  *
1797  * \par Restrictions:
1798  * KV is a vertex that must have a valance of exactly two. Furthermore
1799  * both edges in KV's disk cycle (OE and KE) must be unique (no double edges).
1800  *
1801  * \return The resulting edge, NULL for failure.
1802  *
1803  * \note This euler has the possibility of creating
1804  * faces with just 2 edges. It is up to the caller to decide what to do with
1805  * these faces.
1806  */
1807 BMEdge *bmesh_jekv(
1808         BMesh *bm, BMEdge *e_kill, BMVert *v_kill,
1809         const bool do_del, const bool check_edge_double,
1810         const bool kill_degenerate_faces)
1811 {
1812         BMEdge *e_old;
1813         BMVert *v_old, *v_target;
1814         BMLoop *l_kill;
1815         bool halt = false;
1816 #ifndef NDEBUG
1817         int radlen, i;
1818         bool edok;
1819 #endif
1820
1821         BLI_assert(BM_vert_in_edge(e_kill, v_kill));
1822
1823         if (BM_vert_in_edge(e_kill, v_kill) == 0) {
1824                 return NULL;
1825         }
1826         
1827         if (bmesh_disk_count_ex(v_kill, 3) == 2) {
1828 #ifndef NDEBUG
1829                 int valence1, valence2;
1830                 BMLoop *l;
1831 #endif
1832
1833                 e_old = bmesh_disk_edge_next(e_kill, v_kill);
1834                 v_target = BM_edge_other_vert(e_kill, v_kill);
1835                 v_old = BM_edge_other_vert(e_old, v_kill);
1836                 halt = BM_verts_in_edge(v_kill, v_target, e_old); /* check for double edges */
1837                 
1838                 if (halt) {
1839                         return NULL;
1840                 }
1841                 else {
1842                         BMEdge *e_splice;
1843                         BLI_SMALLSTACK_DECLARE(faces_degenerate, BMFace *);
1844                         BMLoop *l_kill_next;
1845
1846 #ifndef NDEBUG
1847                         /* For verification later, count valence of 'v_old' and 'v_target' */
1848                         valence1 = bmesh_disk_count(v_old);
1849                         valence2 = bmesh_disk_count(v_target);
1850 #endif
1851
1852                         if (check_edge_double) {
1853                                 e_splice = BM_edge_exists(v_target, v_old);
1854                         }
1855
1856                         bmesh_disk_vert_replace(e_old, v_target, v_kill);
1857
1858                         /* remove e_kill from 'v_target's disk cycle */
1859                         bmesh_disk_edge_remove(e_kill, v_target);
1860
1861 #ifndef NDEBUG
1862                         /* deal with radial cycle of e_kill */
1863                         radlen = bmesh_radial_length(e_kill->l);
1864 #endif
1865                         if (e_kill->l) {
1866
1867
1868                                 /* fix the neighboring loops of all loops in e_kill's radial cycle */
1869                                 l_kill = e_kill->l;
1870                                 do {
1871                                         /* relink loops and fix vertex pointer */
1872                                         if (l_kill->next->v == v_kill) {
1873                                                 l_kill->next->v = v_target;
1874                                         }
1875
1876                                         l_kill->next->prev = l_kill->prev;
1877                                         l_kill->prev->next = l_kill->next;
1878                                         if (BM_FACE_FIRST_LOOP(l_kill->f) == l_kill) {
1879                                                 BM_FACE_FIRST_LOOP(l_kill->f) = l_kill->next;
1880                                         }
1881
1882                                         /* fix len attribute of face */
1883                                         l_kill->f->len--;
1884                                         if (kill_degenerate_faces) {
1885                                                 if (l_kill->f->len < 3) {
1886                                                         BLI_SMALLSTACK_PUSH(faces_degenerate, l_kill->f);
1887                                                 }
1888                                         }
1889                                         l_kill_next = l_kill->radial_next;
1890
1891                                         bm_kill_only_loop(bm, l_kill);
1892
1893                                 } while ((l_kill = l_kill_next) != e_kill->l);
1894                                 /* `e_kill->l` is invalid but the edge is freed next. */
1895 #ifndef NDEBUG
1896                                 /* Validate radial cycle of e_old */
1897                                 edok = bmesh_radial_validate(radlen, e_old->l);
1898                                 BMESH_ASSERT(edok != false);
1899 #endif
1900                         }
1901                         /* deallocate edge */
1902                         bm_kill_only_edge(bm, e_kill);
1903
1904                         /* deallocate vertex */
1905                         if (do_del) {
1906                                 bm_kill_only_vert(bm, v_kill);
1907                         }
1908                         else {
1909                                 v_kill->e = NULL;
1910                         }
1911
1912 #ifndef NDEBUG
1913                         /* Validate disk cycle lengths of 'v_old', 'v_target' are unchanged */
1914                         edok = bmesh_disk_validate(valence1, v_old->e, v_old);
1915                         BMESH_ASSERT(edok != false);
1916                         edok = bmesh_disk_validate(valence2, v_target->e, v_target);
1917                         BMESH_ASSERT(edok != false);
1918
1919                         /* Validate loop cycle of all faces attached to 'e_old' */
1920                         for (i = 0, l = e_old->l; i < radlen; i++, l = l->radial_next) {
1921                                 BMESH_ASSERT(l->e == e_old);
1922                                 edok = BM_verts_in_edge(l->v, l->next->v, e_old);
1923                                 BMESH_ASSERT(edok != false);
1924                                 edok = bmesh_loop_validate(l->f);
1925                                 BMESH_ASSERT(edok != false);
1926
1927                                 BM_CHECK_ELEMENT(l);
1928                                 BM_CHECK_ELEMENT(l->v);
1929                                 BM_CHECK_ELEMENT(l->e);
1930                                 BM_CHECK_ELEMENT(l->f);
1931                         }
1932 #endif
1933                         if (check_edge_double) {
1934                                 if (e_splice) {
1935                                         /* removes e_splice */
1936                                         BM_edge_splice(bm, e_old, e_splice);
1937                                 }
1938                         }
1939
1940                         if (kill_degenerate_faces) {
1941                                 BMFace *f_kill;
1942                                 while ((f_kill = BLI_SMALLSTACK_POP(faces_degenerate))) {
1943                                         BM_face_kill(bm, f_kill);
1944                                 }
1945                         }
1946
1947                         BM_CHECK_ELEMENT(v_old);
1948                         BM_CHECK_ELEMENT(v_target);
1949                         BM_CHECK_ELEMENT(e_old);
1950
1951                         return e_old;
1952                 }
1953         }
1954         return NULL;
1955 }
1956
1957 /**
1958  * \brief Join Vert Kill Edge (JVKE)
1959  *
1960  * Collapse an edge, merging surrounding data.
1961  *
1962  * Unlike #BM_vert_collapse_edge & #bmesh_jekv which only handle 2 valence verts,
1963  * this can handle any number of connected edges/faces.
1964  *
1965  * <pre>
1966  * Before: -> After:
1967  * +-+-+-+    +-+-+-+
1968  * | | | |    | \ / |
1969  * +-+-+-+    +--+--+
1970  * | | | |    | / \ |
1971  * +-+-+-+    +-+-+-+
1972  * </pre>
1973  */
1974 BMVert *bmesh_jvke(
1975         BMesh *bm, BMEdge *e_kill, BMVert *v_kill,
1976         const bool do_del, const bool check_edge_double,
1977         const bool kill_degenerate_faces)
1978 {
1979         BLI_SMALLSTACK_DECLARE(faces_degenerate, BMFace *);
1980         BMVert *v_target = BM_edge_other_vert(e_kill, v_kill);
1981
1982         BLI_assert(BM_vert_in_edge(e_kill, v_kill));
1983
1984         if (e_kill->l) {
1985                 BMLoop *l_kill, *l_first, *l_kill_next;
1986                 l_kill = l_first = e_kill->l;
1987                 do {
1988                         /* relink loops and fix vertex pointer */
1989                         if (l_kill->next->v == v_kill) {
1990                                 l_kill->next->v = v_target;
1991                         }
1992
1993                         l_kill->next->prev = l_kill->prev;
1994                         l_kill->prev->next = l_kill->next;
1995                         if (BM_FACE_FIRST_LOOP(l_kill->f) == l_kill) {
1996                                 BM_FACE_FIRST_LOOP(l_kill->f) = l_kill->next;
1997                         }
1998
1999                         /* fix len attribute of face */
2000                         l_kill->f->len--;
2001                         if (kill_degenerate_faces) {
2002                                 if (l_kill->f->len < 3) {
2003                                         BLI_SMALLSTACK_PUSH(faces_degenerate, l_kill->f);
2004                                 }
2005                         }
2006                         l_kill_next = l_kill->radial_next;
2007
2008                         bm_kill_only_loop(bm, l_kill);
2009
2010                 } while ((l_kill = l_kill_next) != l_first);
2011
2012                 e_kill->l = NULL;
2013         }
2014
2015         BM_edge_kill(bm, e_kill);
2016         BM_CHECK_ELEMENT(v_kill);
2017         BM_CHECK_ELEMENT(v_target);
2018
2019         if (v_target->e && v_kill->e) {
2020                 /* inline BM_vert_splice(bm, v_target, v_kill); */
2021                 BMEdge *e;
2022                 while ((e = v_kill->e)) {
2023                         BMEdge *e_target;
2024
2025                         if (check_edge_double) {
2026                                 e_target = BM_edge_exists(v_target, BM_edge_other_vert(e, v_kill));
2027                         }
2028
2029                         bmesh_edge_vert_swap(e, v_target, v_kill);
2030                         BLI_assert(e->v1 != e->v2);
2031
2032                         if (check_edge_double) {
2033                                 if (e_target) {
2034                                         BM_edge_splice(bm, e_target, e);
2035                                 }
2036                         }
2037                 }
2038         }
2039
2040         if (kill_degenerate_faces) {
2041                 BMFace *f_kill;
2042                 while ((f_kill = BLI_SMALLSTACK_POP(faces_degenerate))) {
2043                         BM_face_kill(bm, f_kill);
2044                 }
2045         }
2046
2047         if (do_del) {
2048                 BLI_assert(v_kill->e == NULL);
2049                 bm_kill_only_vert(bm, v_kill);
2050         }
2051
2052         return v_target;
2053 }
2054
2055 /**
2056  * \brief Join Face Kill Edge (JFKE)
2057  *
2058  * Takes two faces joined by a single 2-manifold edge and fuses them together.
2059  * The edge shared by the faces must not be connected to any other edges which have
2060  * Both faces in its radial cycle
2061  *
2062  * \par Examples:
2063  * <pre>
2064  *           A                   B
2065  *      +--------+           +--------+
2066  *      |        |           |        |
2067  *      |   f1   |           |   f1   |
2068  *     v1========v2 = Ok!    v1==V2==v3 == Wrong!
2069  *      |   f2   |           |   f2   |
2070  *      |        |           |        |
2071  *      +--------+           +--------+
2072  * </pre>
2073  *
2074  * In the example A, faces \a f1 and \a f2 are joined by a single edge,
2075  * and the euler can safely be used.
2076  * In example B however, \a f1 and \a f2 are joined by multiple edges and will produce an error.
2077  * The caller in this case should call #bmesh_jekv on the extra edges
2078  * before attempting to fuse \a f1 and \a f2.
2079  *
2080  * \note The order of arguments decides whether or not certain per-face attributes are present
2081  * in the resultant face. For instance vertex winding, material index, smooth flags, etc are inherited
2082  * from \a f1, not \a f2.
2083  *
2084  * \return A BMFace pointer
2085  */
2086 BMFace *bmesh_jfke(BMesh *bm, BMFace *f1, BMFace *f2, BMEdge *e)
2087 {
2088         BMLoop *l_iter, *l_f1 = NULL, *l_f2 = NULL;
2089         int newlen = 0, i, f1len = 0, f2len = 0;
2090         bool edok;
2091         /* can't join a face to itself */
2092         if (f1 == f2) {
2093                 return NULL;
2094         }
2095
2096         /* validate that edge is 2-manifold edge */
2097         if (!BM_edge_is_manifold(e)) {
2098                 return NULL;
2099         }
2100
2101         /* verify that e is in both f1 and f2 */
2102         f1len = f1->len;
2103         f2len = f2->len;
2104
2105         if (!((l_f1 = BM_face_edge_share_loop(f1, e)) &&
2106               (l_f2 = BM_face_edge_share_loop(f2, e))))
2107         {
2108                 return NULL;
2109         }
2110
2111         /* validate direction of f2's loop cycle is compatible */
2112         if (l_f1->v == l_f2->v) {
2113                 return NULL;
2114         }
2115
2116         /* validate that for each face, each vertex has another edge in its disk cycle that is
2117          * not e, and not shared. */
2118         if (BM_edge_in_face(l_f1->next->e, f2) ||
2119             BM_edge_in_face(l_f1->prev->e, f2) ||
2120             BM_edge_in_face(l_f2->next->e, f1) ||
2121             BM_edge_in_face(l_f2->prev->e, f1) )
2122         {
2123                 return NULL;
2124         }
2125
2126         /* validate only one shared edge */
2127         if (BM_face_share_edge_count(f1, f2) > 1) {
2128                 return NULL;
2129         }
2130
2131         /* validate no internal join */
2132         for (i = 0, l_iter = BM_FACE_FIRST_LOOP(f1); i < f1len; i++, l_iter = l_iter->next) {
2133                 BM_elem_flag_disable(l_iter->v, BM_ELEM_INTERNAL_TAG);
2134         }
2135         for (i = 0, l_iter = BM_FACE_FIRST_LOOP(f2); i < f2len; i++, l_iter = l_iter->next) {
2136                 BM_elem_flag_disable(l_iter->v, BM_ELEM_INTERNAL_TAG);
2137         }
2138
2139         for (i = 0, l_iter = BM_FACE_FIRST_LOOP(f1); i < f1len; i++, l_iter = l_iter->next) {
2140                 if (l_iter != l_f1) {
2141                         BM_elem_flag_enable(l_iter->v, BM_ELEM_INTERNAL_TAG);
2142                 }
2143         }
2144         for (i = 0, l_iter = BM_FACE_FIRST_LOOP(f2); i < f2len; i++, l_iter = l_iter->next) {
2145                 if (l_iter != l_f2) {
2146                         /* as soon as a duplicate is found, bail out */
2147                         if (BM_elem_flag_test(l_iter->v, BM_ELEM_INTERNAL_TAG)) {
2148                                 return NULL;
2149                         }
2150                 }
2151         }
2152
2153         /* join the two loop */
2154         l_f1->prev->next = l_f2->next;
2155         l_f2->next->prev = l_f1->prev;
2156         
2157         l_f1->next->prev = l_f2->prev;
2158         l_f2->prev->next = l_f1->next;
2159         
2160         /* if l_f1 was baseloop, make l_f1->next the base. */
2161         if (BM_FACE_FIRST_LOOP(f1) == l_f1)
2162                 BM_FACE_FIRST_LOOP(f1) = l_f1->next;
2163
2164         /* increase length of f1 */
2165         f1->len += (f2->len - 2);
2166
2167         /* make sure each loop points to the proper face */
2168         newlen = f1->len;
2169         for (i = 0, l_iter = BM_FACE_FIRST_LOOP(f1); i < newlen; i++, l_iter = l_iter->next)
2170                 l_iter->f = f1;
2171         
2172         /* remove edge from the disk cycle of its two vertices */
2173         bmesh_disk_edge_remove(l_f1->e, l_f1->e->v1);
2174         bmesh_disk_edge_remove(l_f1->e, l_f1->e->v2);
2175         
2176         /* deallocate edge and its two loops as well as f2 */
2177         if (bm->etoolflagpool) {
2178                 BLI_mempool_free(bm->etoolflagpool, ((BMEdge_OFlag *)l_f1->e)->oflags);
2179         }
2180         BLI_mempool_free(bm->epool, l_f1->e);
2181         bm->totedge--;
2182         BLI_mempool_free(bm->lpool, l_f1);
2183         bm->totloop--;
2184         BLI_mempool_free(bm->lpool, l_f2);
2185         bm->totloop--;
2186         if (bm->ftoolflagpool) {
2187                 BLI_mempool_free(bm->ftoolflagpool, ((BMFace_OFlag *)f2)->oflags);
2188         }
2189         BLI_mempool_free(bm->fpool, f2);
2190         bm->totface--;
2191         /* account for both above */
2192         bm->elem_index_dirty |= BM_EDGE | BM_LOOP | BM_FACE;
2193
2194         BM_CHECK_ELEMENT(f1);
2195
2196         /* validate the new loop cycle */
2197         edok = bmesh_loop_validate(f1);
2198         BMESH_ASSERT(edok != false);
2199         
2200         return f1;
2201 }
2202
2203 /**
2204  * Check if splicing vertices would create any double edges.
2205  *
2206  * \note assume caller will handle case where verts share an edge.
2207  */
2208 bool BM_vert_splice_check_double(BMVert *v_a, BMVert *v_b)
2209 {
2210         bool is_double = false;
2211
2212         BLI_assert(BM_edge_exists(v_a, v_b) == false);
2213
2214         if (v_a->e && v_b->e) {
2215                 BMEdge *e, *e_first;
2216
2217 #define VERT_VISIT _FLAG_WALK
2218
2219                 /* tag 'v_a' */
2220                 e = e_first = v_a->e;
2221                 do {
2222                         BMVert *v_other = BM_edge_other_vert(e, v_a);
2223                         BLI_assert(!BM_ELEM_API_FLAG_TEST(v_other, VERT_VISIT));
2224                         BM_ELEM_API_FLAG_ENABLE(v_other, VERT_VISIT);
2225                 } while ((e = BM_DISK_EDGE_NEXT(e, v_a)) != e_first);
2226
2227                 /* check 'v_b' connects to 'v_a' edges */
2228                 e = e_first = v_b->e;
2229                 do {
2230                         BMVert *v_other = BM_edge_other_vert(e, v_b);
2231                         if (BM_ELEM_API_FLAG_TEST(v_other, VERT_VISIT)) {
2232                                 is_double = true;
2233                                 break;
2234                         }
2235                 } while ((e = BM_DISK_EDGE_NEXT(e, v_b)) != e_first);
2236
2237                 /* cleanup */
2238                 e = e_first = v_a->e;
2239                 do {
2240                         BMVert *v_other = BM_edge_other_vert(e, v_a);
2241                         BLI_assert(BM_ELEM_API_FLAG_TEST(v_other, VERT_VISIT));
2242                         BM_ELEM_API_FLAG_DISABLE(v_other, VERT_VISIT);
2243                 } while ((e = BM_DISK_EDGE_NEXT(e, v_a)) != e_first);
2244
2245 #undef VERT_VISIT
2246
2247         }
2248
2249         return is_double;
2250 }
2251
2252 /**
2253  * \brief Splice Vert
2254  *
2255  * Merges two verts into one
2256  * (\a v_src into \a v_dst, removing \a v_src).
2257  *
2258  * \return Success
2259  *
2260  * \warning This doesn't work for collapsing edges,
2261  * where \a v and \a vtarget are connected by an edge
2262  * (assert checks for this case).
2263  */
2264 bool BM_vert_splice(BMesh *bm, BMVert *v_dst, BMVert *v_src)
2265 {
2266         BMEdge *e;
2267
2268         /* verts already spliced */
2269         if (v_src == v_dst) {
2270                 return false;
2271         }
2272
2273         BLI_assert(BM_vert_pair_share_face_check(v_src, v_dst) == false);
2274
2275         /* move all the edges from 'v_src' disk to 'v_dst' */
2276         while ((e = v_src->e)) {
2277                 bmesh_edge_vert_swap(e, v_dst, v_src);
2278                 BLI_assert(e->v1 != e->v2);
2279         }
2280
2281         BM_CHECK_ELEMENT(v_src);
2282         BM_CHECK_ELEMENT(v_dst);
2283
2284         /* 'v_src' is unused now, and can be killed */
2285         BM_vert_kill(bm, v_src);
2286
2287         return true;
2288 }
2289
2290
2291 /** \name BM_vert_separate, bmesh_vert_separate and friends
2292  * \{ */
2293
2294 /* BM_edge_face_count(e) >= 1 */
2295 BLI_INLINE bool bm_edge_supports_separate(const BMEdge *e)
2296 {
2297         return (e->l && e->l->radial_next != e->l);
2298 }
2299
2300 /**
2301  * \brief Separate Vert
2302  *
2303  * Separates all disjoint fans that meet at a vertex, making a unique
2304  * vertex for each region. returns an array of all resulting vertices.
2305  *
2306  * \note this is a low level function, bm_edge_separate needs to run on edges first
2307  * or, the faces sharing verts must not be sharing edges for them to split at least.
2308  *
2309  * \return Success
2310  */
2311 void bmesh_vert_separate(
2312         BMesh *bm, BMVert *v, BMVert ***r_vout, int *r_vout_len,
2313         const bool copy_select)
2314 {
2315         int v_edges_num = 0;
2316
2317         /* Detailed notes on array use since this is stack memory, we have to be careful */
2318
2319         /* newly created vertices, only use when 'r_vout' is set
2320          * (total size will be number of fans) */
2321         BLI_SMALLSTACK_DECLARE(verts_new, BMVert *);
2322         /* fill with edges from the face-fan, clearing on completion
2323          * (total size will be max fan edge count) */
2324         BLI_SMALLSTACK_DECLARE(edges, BMEdge *);
2325         /* temp store edges to walk over when filling 'edges',
2326          * (total size will be max radial edges of any edge) */
2327         BLI_SMALLSTACK_DECLARE(edges_search, BMEdge *);
2328
2329         /* number of resulting verts, include self */
2330         int verts_num = 1;
2331         /* track the total number of edges handled, so we know when we've found the last fan */
2332         int edges_found = 0;
2333
2334 #define EDGE_VISIT _FLAG_WALK
2335
2336         /* count and flag at once */
2337         if (v->e) {
2338                 BMEdge *e_first, *e_iter;
2339                 e_iter = e_first = v->e;
2340                 do {
2341                         v_edges_num += 1;
2342
2343                         BLI_assert(!BM_ELEM_API_FLAG_TEST(e_iter, EDGE_VISIT));
2344                         BM_ELEM_API_FLAG_ENABLE(e_iter, EDGE_VISIT);
2345                 } while ((e_iter = bmesh_disk_edge_next(e_iter, v)) != e_first);
2346         }
2347
2348         while (true) {
2349                 /* Considering only edges and faces incident on vertex v, walk
2350                  * the edges & collect in the 'edges' list for splitting */
2351
2352                 BMEdge *e = v->e;
2353                 BM_ELEM_API_FLAG_DISABLE(e, EDGE_VISIT);
2354
2355                 do {
2356                         BLI_assert(!BM_ELEM_API_FLAG_TEST(e, EDGE_VISIT));
2357                         BLI_SMALLSTACK_PUSH(edges, e);
2358                         edges_found += 1;
2359
2360                         if (e->l) {
2361                                 BMLoop *l_iter, *l_first;
2362                                 l_iter = l_first = e->l;
2363                                 do {
2364                                         BMLoop *l_adjacent = (l_iter->v == v) ? l_iter->prev : l_iter->next;
2365                                         BLI_assert(BM_vert_in_edge(l_adjacent->e, v));
2366                                         if (BM_ELEM_API_FLAG_TEST(l_adjacent->e, EDGE_VISIT)) {
2367                                                 BM_ELEM_API_FLAG_DISABLE(l_adjacent->e, EDGE_VISIT);
2368                                                 BLI_SMALLSTACK_PUSH(edges_search, l_adjacent->e);
2369                                         }
2370                                 } while ((l_iter = l_iter->radial_next) != l_first);
2371                         }
2372                 } while ((e = BLI_SMALLSTACK_POP(edges_search)));
2373
2374                 /* now we have all edges connected to 'v->e' */
2375
2376                 BLI_assert(edges_found <= v_edges_num);
2377
2378                 if (edges_found == v_edges_num) {
2379                         /* We're done! The remaining edges in 'edges' form the last fan,
2380                          * which can be left as is.
2381                          * if 'edges' were alloc'd it'd be freed here. */
2382                         break;
2383                 }
2384                 else {
2385                         BMVert *v_new;
2386
2387                         v_new = BM_vert_create(bm, v->co, v, BM_CREATE_NOP);
2388                         if (copy_select) {
2389                                 BM_elem_select_copy(bm, bm, v_new, v);
2390                         }
2391
2392                         while ((e = BLI_SMALLSTACK_POP(edges))) {
2393                                 bmesh_edge_vert_swap(e, v_new, v);
2394                         }
2395
2396                         if (r_vout) {
2397                                 BLI_SMALLSTACK_PUSH(verts_new, v_new);
2398                         }
2399                         verts_num += 1;
2400                 }
2401         }
2402
2403 #undef EDGE_VISIT
2404
2405         /* flags are clean now, handle return values */
2406
2407         if (r_vout_len != NULL) {
2408                 *r_vout_len = verts_num;
2409         }
2410
2411         if (r_vout != NULL) {
2412                 BMVert **verts;
2413
2414                 verts = MEM_mallocN(sizeof(BMVert *) * verts_num, __func__);
2415                 *r_vout = verts;
2416
2417                 verts[0] = v;
2418                 BLI_SMALLSTACK_AS_TABLE(verts_new, &verts[1]);
2419         }
2420 }
2421
2422 /**
2423  * Utility function for #BM_vert_separate
2424  *
2425  * Takes a list of edges, which have been split from their original.
2426  *
2427  * Any edges which failed to split off in #bmesh_vert_separate will be merged back into the original edge.
2428  *
2429  * \param edges_separate
2430  * A list-of-lists, each list is from a single original edge (the first edge is the original),
2431  * Check for duplicates (not just with the first) but between all.
2432  * This is O(n2) but radial edges are very rarely >2 and almost never >~10.
2433  *
2434  * \note typically its best to avoid creating the data in the first place,
2435  * but inspecting all loops connectivity is quite involved.
2436  *
2437  * \note this function looks like it could become slow,
2438  * but in common cases its only going to iterate a few times.
2439  */
2440 static void bmesh_vert_separate__cleanup(BMesh *bm, LinkNode *edges_separate)
2441 {
2442         do {
2443                 LinkNode *n_orig = edges_separate->link;
2444                 do {
2445                         BMEdge *e_orig = n_orig->link;
2446                         LinkNode *n_step = n_orig->next;
2447                         LinkNode *n_prev = n_orig;
2448                         do {
2449                                 BMEdge *e = n_step->link;
2450                                 BLI_assert(e != e_orig);
2451                                 if ((e->v1 == e_orig->v1) && (e->v2 == e_orig->v2)) {
2452                                         BM_edge_splice(bm, e_orig, e);
2453                                         n_prev->next = n_step->next;
2454                                         n_step = n_prev;
2455                                 }
2456                         } while ((void)
2457                                  (n_prev = n_step),
2458                                  (n_step = n_step->next));
2459
2460                 } while ((n_orig = n_orig->next) && n_orig->next);
2461         } while ((edges_separate = edges_separate->next));
2462 }
2463
2464 /**
2465  * High level function which wraps both #bmesh_vert_separate and #bmesh_edge_separate
2466  */
2467 void BM_vert_separate(
2468         BMesh *bm, BMVert *v,
2469         BMEdge **e_in, int e_in_len,
2470         const bool copy_select,
2471         BMVert ***r_vout, int *r_vout_len)
2472 {
2473         LinkNode *edges_separate = NULL;
2474         int i;
2475
2476         for (i = 0; i < e_in_len; i++) {
2477                 BMEdge *e = e_in[i];
2478                 if (bm_edge_supports_separate(e)) {
2479                         LinkNode *edges_orig = NULL;
2480                         do {
2481                                 BMLoop *l_sep = e->l;
2482                                 bmesh_edge_separate(bm, e, l_sep, copy_select);
2483                                 BLI_linklist_prepend_alloca(&edges_orig, l_sep->e);
2484                                 BLI_assert(e != l_sep->e);
2485                         } while (bm_edge_supports_separate(e));
2486                         BLI_linklist_prepend_alloca(&edges_orig, e);
2487                         BLI_linklist_prepend_alloca(&edges_separate, edges_orig);
2488                 }
2489         }
2490
2491         bmesh_vert_separate(bm, v, r_vout, r_vout_len, copy_select);
2492
2493         if (edges_separate) {
2494                 bmesh_vert_separate__cleanup(bm, edges_separate);
2495         }
2496 }
2497
2498
2499 /**
2500  * A version of #BM_vert_separate which takes a flag.
2501  */
2502 void BM_vert_separate_hflag(
2503         BMesh *bm, BMVert *v,
2504         const char hflag,
2505         const bool copy_select,
2506         BMVert ***r_vout, int *r_vout_len)
2507 {
2508         LinkNode *edges_separate = NULL;
2509         BMEdge *e_iter, *e_first;
2510
2511         e_iter = e_first = v->e;
2512         do {
2513                 if (BM_elem_flag_test(e_iter, hflag)) {
2514                         BMEdge *e = e_iter;
2515                         if (bm_edge_supports_separate(e)) {
2516                                 LinkNode *edges_orig = NULL;
2517                                 do {
2518                                         BMLoop *l_sep = e->l;
2519                                         bmesh_edge_separate(bm, e, l_sep, copy_select);
2520                                         /* trick to avoid looping over separated edges */
2521                                         if (edges_separate == NULL && edges_orig == NULL) {
2522                                                 e_first = l_sep->e;
2523                                         }
2524                                         BLI_linklist_prepend_alloca(&edges_orig, l_sep->e);
2525                                         BLI_assert(e != l_sep->e);
2526                                 } while (bm_edge_supports_separate(e));
2527                                 BLI_linklist_prepend_alloca(&edges_orig, e);
2528                                 BLI_linklist_prepend_alloca(&edges_separate, edges_orig);
2529                         }
2530                 }
2531         } while ((e_iter = BM_DISK_EDGE_NEXT(e_iter, v)) != e_first);
2532
2533         bmesh_vert_separate(bm, v, r_vout, r_vout_len, copy_select);
2534
2535         if (edges_separate) {
2536                 bmesh_vert_separate__cleanup(bm, edges_separate);
2537         }
2538 }
2539
2540 void BM_vert_separate_wire_hflag(
2541         BMesh *UNUSED(bm), BMVert *v_dst, BMVert *v_src,
2542         const char hflag)
2543 {
2544         LinkNode *edges_hflag = NULL;
2545         BMEdge *e_iter, *e_first;
2546
2547         e_iter = e_first = v_src->e;
2548         do {
2549                 if (BM_elem_flag_test(e_iter, hflag)) {
2550                         if (BM_edge_is_wire(e_iter)) {
2551                                 BLI_linklist_prepend_alloca(&edges_hflag, e_iter);
2552                         }
2553                 }
2554         } while ((e_iter = BM_DISK_EDGE_NEXT(e_iter, v_src)) != e_first);
2555
2556         if (edges_hflag) {
2557                 do {
2558                         e_iter = edges_hflag->link;
2559                         bmesh_disk_vert_replace(e_iter, v_dst, v_src);
2560                 } while ((edges_hflag = edges_hflag->next));
2561         }
2562 }
2563
2564 /** \} */
2565
2566
2567 /**
2568  * \brief Splice Edge
2569  *
2570  * Splice two unique edges which share the same two vertices into one edge.
2571  *  (\a e_src into \a e_dst, removing e_src).
2572  *
2573  * \return Success
2574  *
2575  * \note Edges must already have the same vertices.
2576  */
2577 bool BM_edge_splice(BMesh *bm, BMEdge *e_dst, BMEdge *e_src)
2578 {
2579         BMLoop *l;
2580
2581         if (!BM_vert_in_edge(e_src, e_dst->v1) || !BM_vert_in_edge(e_src, e_dst->v2)) {
2582                 /* not the same vertices can't splice */
2583
2584                 /* the caller should really make sure this doesn't happen ever
2585                  * so assert on release builds */
2586                 BLI_assert(0);
2587
2588                 return false;
2589         }
2590
2591         while (e_src->l) {
2592                 l = e_src->l;
2593                 BLI_assert(BM_vert_in_edge(e_dst, l->v));
2594                 BLI_assert(BM_vert_in_edge(e_dst, l->next->v));
2595                 bmesh_radial_loop_remove(e_src, l);
2596                 bmesh_radial_loop_append(e_dst, l);
2597         }
2598
2599         BLI_assert(bmesh_radial_length(e_src->l) == 0);
2600
2601         BM_CHECK_ELEMENT(e_src);
2602         BM_CHECK_ELEMENT(e_dst);
2603
2604         /* removes from disks too */
2605         BM_edge_kill(bm, e_src);
2606
2607         return true;
2608 }
2609
2610 /**
2611  * \brief Separate Edge
2612  *
2613  * Separates a single edge into two edge: the original edge and
2614  * a new edge that has only \a l_sep in its radial.
2615  *
2616  * \return Success
2617  *
2618  * \note Does nothing if \a l_sep is already the only loop in the
2619  * edge radial.
2620  */
2621 void bmesh_edge_separate(
2622         BMesh *bm, BMEdge *e, BMLoop *l_sep,
2623         const bool copy_select)
2624 {
2625         BMEdge *e_new;
2626 #ifndef NDEBUG
2627         const int radlen = bmesh_radial_length(e->l);
2628 #endif
2629
2630         BLI_assert(l_sep->e == e);
2631         BLI_assert(e->l);
2632         
2633         if (BM_edge_is_boundary(e)) {
2634                 BLI_assert(0); /* no cut required */
2635                 return;
2636         }
2637
2638         if (l_sep == e->l) {
2639                 e->l = l_sep->radial_next;
2640         }
2641
2642         e_new = BM_edge_create(bm, e->v1, e->v2, e, BM_CREATE_NOP);
2643         bmesh_radial_loop_remove(e, l_sep);
2644         bmesh_radial_loop_append(e_new, l_sep);
2645         l_sep->e = e_new;
2646
2647         if (copy_select) {
2648                 BM_elem_select_copy(bm, bm, e_new, e);
2649         }
2650
2651         BLI_assert(bmesh_radial_length(e->l) == radlen - 1);
2652         BLI_assert(bmesh_radial_length(e_new->l) == 1);
2653
2654         BM_CHECK_ELEMENT(e_new);
2655         BM_CHECK_ELEMENT(e);
2656 }
2657
2658 /**
2659  * \brief Un-glue Region Make Vert (URMV)
2660  *
2661  * Disconnects a face from its vertex fan at loop \a l_sep
2662  *
2663  * \return The newly created BMVert
2664  *
2665  * \note Will be a no-op and return original vertex if only two edges at that vertex.
2666  */
2667 BMVert *bmesh_urmv_loop(BMesh *bm, BMLoop *l_sep)
2668 {
2669         BMVert *v_new = NULL;
2670         BMVert *v_sep = l_sep->v;
2671         BMEdge *e_iter;
2672         BMEdge *edges[2];
2673         int i;
2674
2675         /* peel the face from the edge radials on both sides of the
2676          * loop vert, disconnecting the face from its fan */
2677         if (!BM_edge_is_boundary(l_sep->e))
2678                 bmesh_edge_separate(bm, l_sep->e, l_sep, false);
2679         if (!BM_edge_is_boundary(l_sep->prev->e))
2680                 bmesh_edge_separate(bm, l_sep->prev->e, l_sep->prev, false);
2681
2682         /* do inline, below */
2683 #if 0
2684         if (BM_vert_edge_count_is_equal(v_sep, 2)) {
2685                 return v_sep;
2686         }
2687 #endif
2688
2689         /* Search for an edge unattached to this loop */
2690         e_iter = v_sep->e;
2691         while (!ELEM(e_iter, l_sep->e, l_sep->prev->e)) {
2692                 e_iter = bmesh_disk_edge_next(e_iter, v_sep);
2693
2694                 /* We've come back around to the initial edge, all touch this loop.
2695                  * If there are still only two edges out of v_sep,
2696                  * then this whole URMV was just a no-op, so exit now. */
2697                 if (e_iter == v_sep->e) {
2698                         BLI_assert(BM_vert_edge_count_is_equal(v_sep, 2));
2699                         return v_sep;
2700                 }
2701         }
2702
2703         v_sep->e = l_sep->e;
2704
2705         v_new = BM_vert_create(bm, v_sep->co, v_sep, BM_CREATE_NOP);
2706
2707         edges[0] = l_sep->e;
2708         edges[1] = l_sep->prev->e;
2709
2710         for (i = 0; i < ARRAY_SIZE(edges); i++) {
2711                 BMEdge *e = edges[i];
2712                 bmesh_edge_vert_swap(e, v_new, v_sep);
2713         }
2714
2715         BLI_assert(v_sep != l_sep->v);
2716         BLI_assert(v_sep->e != l_sep->v->e);
2717
2718         BM_CHECK_ELEMENT(l_sep);
2719         BM_CHECK_ELEMENT(v_sep);
2720         BM_CHECK_ELEMENT(edges[0]);
2721         BM_CHECK_ELEMENT(edges[1]);
2722         BM_CHECK_ELEMENT(v_new);
2723
2724         return v_new;
2725 }
2726
2727 /**
2728  * A version of #bmesh_urmv_loop that disconnects multiple loops at once.
2729  *
2730  * Handles the task of finding fans boundaries.
2731  */
2732 BMVert *bmesh_urmv_loop_multi(
2733         BMesh *bm, BMLoop **larr, int larr_len)
2734 {
2735         BMVert *v_sep = larr[0]->v;
2736         BMVert *v_new;
2737         int i;
2738         bool is_mixed_any = false;
2739
2740         BLI_SMALLSTACK_DECLARE(edges, BMEdge *);
2741
2742 #define LOOP_VISIT _FLAG_WALK
2743 #define EDGE_VISIT _FLAG_WALK
2744
2745         for (i = 0; i < larr_len; i++) {
2746                 BMLoop *l_sep = larr[i];
2747
2748                 /* all must be from the same vert! */
2749                 BLI_assert(v_sep == l_sep->v);
2750
2751                 BLI_assert(!BM_ELEM_API_FLAG_TEST(l_sep, LOOP_VISIT));
2752                 BM_ELEM_API_FLAG_ENABLE(l_sep, LOOP_VISIT);
2753
2754                 /* weak! but it makes it simpler to check for edges to split
2755                  * while doing a radial loop (where loops may be adjacent) */
2756                 BM_ELEM_API_FLAG_ENABLE(l_sep->next, LOOP_VISIT);
2757                 BM_ELEM_API_FLAG_ENABLE(l_sep->prev, LOOP_VISIT);
2758         }
2759
2760         for (i = 0; i < larr_len; i++) {
2761                 BMLoop *l_sep = larr[i];
2762
2763                 BMLoop *loop_pair[2] = {l_sep, l_sep->prev};
2764                 int j;
2765                 for (j = 0; j < ARRAY_SIZE(loop_pair); j++) {
2766                         BMEdge *e = loop_pair[j]->e;
2767                         if (!BM_ELEM_API_FLAG_TEST(e, EDGE_VISIT)) {
2768                                 BMLoop *l_iter, *l_first;
2769                                 bool is_mixed = false;
2770
2771                                 BM_ELEM_API_FLAG_ENABLE(e, EDGE_VISIT);
2772
2773                                 l_iter = l_first = e->l;
2774                                 do {
2775                                         if (!BM_ELEM_API_FLAG_TEST(l_iter, LOOP_VISIT)) {
2776                                                 is_mixed = true;
2777                                                 is_mixed_any = true;
2778                                                 break;
2779                                         }
2780                                 } while ((l_iter = l_iter->radial_next) != l_first);
2781
2782                                 if (is_mixed) {
2783                                         /* ensure the first loop is one we don't own so we can do a quick check below
2784                                          * on the edge's loop-flag to see if the edge is mixed or not. */
2785                                         e->l = l_iter;
2786                                 }
2787                                 BLI_SMALLSTACK_PUSH(edges, e);
2788                         }
2789                 }
2790         }
2791
2792         if (is_mixed_any == false) {
2793                 /* all loops in 'larr' are the sole owners of their edges.
2794                  * nothing to split away from, this is a no-op */
2795                 v_new = v_sep;
2796         }
2797         else {
2798                 BMEdge *e;
2799
2800                 BLI_assert(!BLI_SMALLSTACK_IS_EMPTY(edges));
2801
2802                 v_new = BM_vert_create(bm, v_sep->co, v_sep, BM_CREATE_NOP);
2803                 while ((e = BLI_SMALLSTACK_POP(edges))) {
2804                         BMLoop *l_iter, *l_first, *l_next;
2805                         BMEdge *e_new;
2806
2807                         /* disable so copied edge isn't left dirty (loop edges are cleared last too) */
2808                         BM_ELEM_API_FLAG_DISABLE(e, EDGE_VISIT);
2809
2810                         if (!BM_ELEM_API_FLAG_TEST(e->l, LOOP_VISIT)) {
2811                                 /* edge has some loops owned by us, some owned by other loops */
2812                                 BMVert *e_new_v_pair[2];
2813
2814                                 if (e->v1 == v_sep) {
2815                                         e_new_v_pair[0] = v_new;
2816                                         e_new_v_pair[1] = e->v2;
2817                                 }
2818                                 else {
2819                                         BLI_assert(v_sep == e->v2);
2820                                         e_new_v_pair[0] = e->v1;
2821                                         e_new_v_pair[1] = v_new;
2822                                 }
2823
2824                                 e_new = BM_edge_create(bm, UNPACK2(e_new_v_pair), e, BM_CREATE_NOP);
2825
2826                                 /* now moved all loops from 'larr' to this newly created edge */
2827                                 l_iter = l_first = e->l;
2828                                 do {
2829                                         l_next = l_iter->radial_next;
2830                                         if (BM_ELEM_API_FLAG_TEST(l_iter, LOOP_VISIT)) {
2831                                                 bmesh_radial_loop_remove(e, l_iter);
2832                                                 bmesh_radial_loop_append(e_new, l_iter);
2833                                                 l_iter->e = e_new;
2834                                         }
2835                                 } while ((l_iter = l_next) != l_first);
2836                         }
2837                         else {
2838                                 /* we own the edge entirely, replace the vert */
2839                                 bmesh_disk_vert_replace(e, v_new, v_sep);
2840                         }
2841
2842                         /* loop vert is handled last! */
2843                 }
2844         }
2845
2846         for (i = 0; i < larr_len; i++) {
2847                 BMLoop *l_sep = larr[i];
2848
2849                 l_sep->v = v_new;
2850
2851                 BLI_assert(BM_ELEM_API_FLAG_TEST(l_sep, LOOP_VISIT));
2852                 BLI_assert(BM_ELEM_API_FLAG_TEST(l_sep->prev, LOOP_VISIT));
2853                 BLI_assert(BM_ELEM_API_FLAG_TEST(l_sep->next, LOOP_VISIT));
2854                 BM_ELEM_API_FLAG_DISABLE(l_sep, LOOP_VISIT);
2855                 BM_ELEM_API_FLAG_DISABLE(l_sep->prev, LOOP_VISIT);
2856                 BM_ELEM_API_FLAG_DISABLE(l_sep->next, LOOP_VISIT);
2857
2858
2859                 BM_ELEM_API_FLAG_DISABLE(l_sep->prev->e, EDGE_VISIT);
2860                 BM_ELEM_API_FLAG_DISABLE(l_sep->e, EDGE_VISIT);
2861         }
2862
2863 #undef LOOP_VISIT
2864 #undef EDGE_VISIT
2865
2866         return v_new;
2867 }
2868
2869 static void bmesh_edge_vert_swap__recursive(BMEdge *e, BMVert *v_dst, BMVert *v_src)
2870 {
2871         BMLoop *l_iter, *l_first;
2872
2873         BLI_assert(ELEM(v_src, e->v1, e->v2));
2874         bmesh_disk_vert_replace(e, v_dst, v_src);
2875
2876         l_iter = l_first = e->l;
2877         do {
2878                 if (l_iter->v == v_src) {
2879                         l_iter->v = v_dst;
2880                         if (BM_vert_in_edge(l_iter->prev->e, v_src)) {
2881                                 bmesh_edge_vert_swap__recursive(l_iter->prev->e, v_dst, v_src);
2882                         }
2883                 }
2884                 else if (l_iter->next->v == v_src) {
2885                         l_iter->next->v = v_dst;
2886                         if (BM_vert_in_edge(l_iter->next->e, v_src)) {
2887                                 bmesh_edge_vert_swap__recursive(l_iter->next->e, v_dst, v_src);
2888                         }
2889                 }
2890                 else {
2891                         BLI_assert(l_iter->prev->v != v_src);
2892                 }
2893         } while ((l_iter = l_iter->radial_next) != l_first);
2894 }
2895
2896 /**
2897  * This function assumes l_sep is apart of a larger fan which has already been
2898  * isolated by calling bmesh_edge_separate to segregate it radially.
2899  */
2900 BMVert *bmesh_urmv_loop_region(BMesh *bm, BMLoop *l_sep)
2901 {
2902         BMVert *v_new = BM_vert_create(bm, l_sep->v->co, l_sep->v, BM_CREATE_NOP);
2903         /* passing either 'l_sep->e', 'l_sep->prev->e' will work */
2904         bmesh_edge_vert_swap__recursive(l_sep->e, v_new, l_sep->v);
2905         BLI_assert(l_sep->v == v_new);
2906         return v_new;
2907 }
2908
2909
2910 /**
2911  * \brief Unglue Region Make Vert (URMV)
2912  *
2913  * Disconnects f_sep from the vertex fan at \a v_sep
2914  *
2915  * \return The newly created BMVert
2916  */
2917 BMVert *bmesh_urmv(BMesh *bm, BMFace *f_sep, BMVert *v_sep)
2918 {
2919         BMLoop *l = BM_face_vert_share_loop(f_sep, v_sep);
2920         return bmesh_urmv_loop(bm, l);
2921 }
2922
2923 /**
2924  * Avoid calling this where possible,
2925  * low level function so both face pointers remain intact but point to swapped data.
2926  * \note must be from the same bmesh.
2927  */
2928 void bmesh_face_swap_data(BMFace *f_a, BMFace *f_b)
2929 {
2930         BMLoop *l_iter, *l_first;
2931
2932         BLI_assert(f_a != f_b);
2933
2934         l_iter = l_first = BM_FACE_FIRST_LOOP(f_a);
2935         do {
2936                 l_iter->f = f_b;
2937         } while ((l_iter = l_iter->next) != l_first);
2938
2939         l_iter = l_first = BM_FACE_FIRST_LOOP(f_b);
2940         do {
2941                 l_iter->f = f_a;
2942         } while ((l_iter = l_iter->next) != l_first);
2943
2944         SWAP(BMFace, (*f_a), (*f_b));
2945
2946         /* swap back */
2947         SWAP(void *, f_a->head.data, f_b->head.data);
2948         SWAP(int, f_a->head.index, f_b->head.index);
2949 }