bmesh api cleanup
[blender-staging.git] / source / blender / bmesh / intern / bmesh_newcore.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_newcore.c
24  *  \ingroup bmesh
25  *
26  */
27
28 #include "MEM_guardedalloc.h"
29
30 #include "BLI_math_vector.h"
31
32 #include "BKE_DerivedMesh.h"
33
34 #include "BLI_listbase.h"
35 #include "BLI_array.h"
36
37 #include "bmesh.h"
38 #include "bmesh_private.h"
39
40 /* use so valgrinds memcheck alerts us when undefined index is used.
41  * TESTING ONLY! */
42 // #define USE_DEBUG_INDEX_MEMCHECK
43
44 #ifdef USE_DEBUG_INDEX_MEMCHECK
45 #define DEBUG_MEMCHECK_INDEX_INVALIDATE(ele)               \
46         {                                                      \
47                 int undef_idx;                                     \
48                 BM_elem_index_set(ele, undef_idx); /* set_ok_invalid */  \
49         }                                                      \
50
51 #endif
52
53 BMVert *BM_vert_create(BMesh *bm, const float co[3], const struct BMVert *example)
54 {
55         BMVert *v = BLI_mempool_calloc(bm->vpool);
56
57 #ifdef USE_DEBUG_INDEX_MEMCHECK
58         DEBUG_MEMCHECK_INDEX_INVALIDATE(v)
59 #else
60         BM_elem_index_set(v, -1); /* set_ok_invalid */
61 #endif
62
63         bm->elem_index_dirty |= BM_VERT; /* may add to middle of the pool */
64
65         bm->totvert++;
66
67         v->head.htype = BM_VERT;
68
69         /* 'v->no' is handled by BM_elem_attrs_copy */
70         if (co) {
71                 copy_v3_v3(v->co, co);
72         }
73
74         /* allocate flag */
75         v->oflags = BLI_mempool_calloc(bm->toolflagpool);
76
77         CustomData_bmesh_set_default(&bm->vdata, &v->head.data);
78         
79         if (example) {
80                 BM_elem_attrs_copy(bm, bm, example, v);
81         }
82
83         BM_CHECK_ELEMENT(bm, v);
84
85         return v;
86 }
87
88 /**
89  *                      BMESH EDGE EXIST
90  *
91  *  Finds out if two vertices already have an edge
92  *  connecting them. Note that multiple edges may
93  *  exist between any two vertices, and therefore
94  *  This function only returns the first one found.
95  *
96  *  Returns -
97  *      BMEdge pointer
98  */
99 BMEdge *BM_edge_exists(BMVert *v1, BMVert *v2)
100 {
101         BMIter iter;
102         BMEdge *e;
103
104         BM_ITER(e, &iter, NULL, BM_EDGES_OF_VERT, v1) {
105                 if (e->v1 == v2 || e->v2 == v2)
106                         return e;
107         }
108
109         return NULL;
110 }
111
112 BMEdge *BM_edge_create(BMesh *bm, BMVert *v1, BMVert *v2, const BMEdge *example, int nodouble)
113 {
114         BMEdge *e;
115         
116         if (nodouble && (e = BM_edge_exists(v1, v2)))
117                 return e;
118         
119         e = BLI_mempool_calloc(bm->epool);
120
121 #ifdef USE_DEBUG_INDEX_MEMCHECK
122         DEBUG_MEMCHECK_INDEX_INVALIDATE(e)
123 #else
124         BM_elem_index_set(e, -1); /* set_ok_invalid */
125 #endif
126
127         bm->elem_index_dirty |= BM_EDGE; /* may add to middle of the pool */
128
129         bm->totedge++;
130
131         e->head.htype = BM_EDGE;
132         
133         /* allocate flag */
134         e->oflags = BLI_mempool_calloc(bm->toolflagpool);
135
136         e->v1 = v1;
137         e->v2 = v2;
138         
139         BM_elem_flag_enable(e, BM_ELEM_SMOOTH);
140         
141         CustomData_bmesh_set_default(&bm->edata, &e->head.data);
142         
143         bmesh_disk_append_edge(e, e->v1);
144         bmesh_disk_append_edge(e, e->v2);
145         
146         if (example)
147                 BM_elem_attrs_copy(bm, bm, example, e);
148         
149         BM_CHECK_ELEMENT(bm, e);
150
151         return e;
152 }
153
154 static BMLoop *bmesh_create_loop(BMesh *bm, BMVert *v, BMEdge *e, BMFace *f, const BMLoop *example)
155 {
156         BMLoop *l = NULL;
157
158         l = BLI_mempool_calloc(bm->lpool);
159         l->next = l->prev = NULL;
160         l->v = v;
161         l->e = e;
162         l->f = f;
163         l->radial_next = l->radial_prev = NULL;
164         l->head.data = NULL;
165         l->head.htype = BM_LOOP;
166
167         bm->totloop++;
168
169         if (example)
170                 CustomData_bmesh_copy_data(&bm->ldata, &bm->ldata, example->head.data, &l->head.data);
171         else
172                 CustomData_bmesh_set_default(&bm->ldata, &l->head.data);
173
174         return l;
175 }
176
177 static BMLoop *bm_face_boundary_add(BMesh *bm, BMFace *f, BMVert *startv, BMEdge *starte)
178 {
179 #ifdef USE_BMESH_HOLES
180         BMLoopList *lst = BLI_mempool_calloc(bm->looplistpool);
181 #endif
182         BMLoop *l = bmesh_create_loop(bm, startv, starte, f, NULL);
183         
184         bmesh_radial_append(starte, l);
185
186 #ifdef USE_BMESH_HOLES
187         lst->first = lst->last = l;
188         BLI_addtail(&f->loops, lst);
189 #else
190         f->l_first = l;
191 #endif
192
193         l->f = f;
194         
195         return l;
196 }
197
198 BMFace *BM_face_copy(BMesh *bm, BMFace *f, const short copyverts, const short copyedges)
199 {
200         BMEdge **edges = NULL;
201         BMVert **verts = NULL;
202         BLI_array_staticdeclare(edges, BM_NGON_STACK_SIZE);
203         BLI_array_staticdeclare(verts, BM_NGON_STACK_SIZE);
204         BMLoop *l_iter;
205         BMLoop *l_first;
206         BMLoop *l2;
207         BMFace *f2;
208         int i;
209
210         l_iter = l_first = BM_FACE_FIRST_LOOP(f);
211         do {
212                 if (copyverts) {
213                         BMVert *v = BM_vert_create(bm, l_iter->v->co, l_iter->v);
214                         BLI_array_append(verts, v);
215                 }
216                 else {
217                         BLI_array_append(verts, l_iter->v);
218                 }
219         } while ((l_iter = l_iter->next) != l_first);
220
221         l_iter = l_first = BM_FACE_FIRST_LOOP(f);
222         i = 0;
223         do {
224                 if (copyedges) {
225                         BMEdge *e;
226                         BMVert *v1, *v2;
227                         
228                         if (l_iter->e->v1 == verts[i]) {
229                                 v1 = verts[i];
230                                 v2 = verts[(i + 1) % f->len];
231                         }
232                         else {
233                                 v2 = verts[i];
234                                 v1 = verts[(i + 1) % f->len];
235                         }
236                         
237                         e = BM_edge_create(bm,  v1, v2, l_iter->e, FALSE);
238                         BLI_array_append(edges, e);
239                 }
240                 else {
241                         BLI_array_append(edges, l_iter->e);
242                 }
243                 
244                 i++;
245         } while ((l_iter = l_iter->next) != l_first);
246         
247         f2 = BM_face_create(bm, verts, edges, f->len, FALSE);
248         
249         BM_elem_attrs_copy(bm, bm, f, f2);
250         
251         l_iter = l_first = BM_FACE_FIRST_LOOP(f);
252         l2 = BM_FACE_FIRST_LOOP(f2);
253         do {
254                 BM_elem_attrs_copy(bm, bm, l_iter, l2);
255                 l2 = l2->next;
256         } while ((l_iter = l_iter->next) != l_first);
257         
258         return f2;
259 }
260
261 BMFace *BM_face_create(BMesh *bm, BMVert **verts, BMEdge **edges, const int len, int nodouble)
262 {
263         BMFace *f = NULL;
264         BMLoop *l, *startl, *lastl;
265         int i, overlap;
266         
267         if (len == 0) {
268                 /* just return NULL for no */
269                 return NULL;
270         }
271
272         if (nodouble) {
273                 /* Check if face already exists */
274                 overlap = BM_face_exists(bm, verts, len, &f);
275                 if (overlap) {
276                         return f;
277                 }
278                 else {
279                         BLI_assert(f == NULL);
280                 }
281         }
282         
283         f = BLI_mempool_calloc(bm->fpool);
284
285 #ifdef USE_DEBUG_INDEX_MEMCHECK
286         DEBUG_MEMCHECK_INDEX_INVALIDATE(f)
287 #else
288         BM_elem_index_set(f, -1); /* set_ok_invalid */
289 #endif
290
291         bm->elem_index_dirty |= BM_FACE; /* may add to middle of the pool */
292
293         bm->totface++;
294
295         f->head.htype = BM_FACE;
296
297         startl = lastl = bm_face_boundary_add(bm, f, verts[0], edges[0]);
298         
299         startl->v = verts[0];
300         startl->e = edges[0];
301         for (i = 1; i < len; i++) {
302                 l = bmesh_create_loop(bm, verts[i], edges[i], f, edges[i]->l);
303                 
304                 l->f = f;
305                 bmesh_radial_append(edges[i], l);
306
307                 l->prev = lastl;
308                 lastl->next = l;
309                 lastl = l;
310         }
311         
312         /* allocate flag */
313         f->oflags = BLI_mempool_calloc(bm->toolflagpool);
314
315         CustomData_bmesh_set_default(&bm->pdata, &f->head.data);
316         
317         startl->prev = lastl;
318         lastl->next = startl;
319         
320         f->len = len;
321
322 #ifdef USE_BMESH_HOLES
323         f->totbounds = 0;
324 #endif
325         
326         BM_CHECK_ELEMENT(bm, f);
327
328         return f;
329 }
330
331 int bmesh_check_element(BMesh *UNUSED(bm), void *element, const char htype)
332 {
333         BMHeader *head = element;
334         int err = 0;
335
336         if (!element)
337                 return 1;
338
339         if (head->htype != htype)
340                 return 2;
341         
342         switch (htype) {
343                 case BM_VERT: {
344                         BMVert *v = element;
345                         if (v->e && v->e->head.htype != BM_EDGE) {
346                                 err |= 4;
347                         }
348                         break;
349                 }
350                 case BM_EDGE: {
351                         BMEdge *e = element;
352                         if (e->l && e->l->head.htype != BM_LOOP)
353                                 err |= 8;
354                         if (e->l && e->l->f->head.htype != BM_FACE)
355                                 err |= 16;
356                         if (e->v1_disk_link.prev == NULL ||
357                             e->v2_disk_link.prev == NULL ||
358                             e->v1_disk_link.next == NULL ||
359                             e->v2_disk_link.next == NULL)
360                         {
361                                 err |= 32;
362                         }
363                         if (e->l && (e->l->radial_next == NULL || e->l->radial_prev == NULL))
364                                 err |= 64;
365                         if (e->l && e->l->f->len <= 0)
366                                 err |= 128;
367                         break;
368                 }
369                 case BM_LOOP: {
370                         BMLoop *l = element, *l2;
371                         int i;
372
373                         if (l->f->head.htype != BM_FACE)
374                                 err |= 256;
375                         if (l->e->head.htype != BM_EDGE)
376                                 err |= 512;
377                         if (l->v->head.htype !=  BM_VERT)
378                                 err |= 1024;
379                         if (!BM_vert_in_edge(l->e, l->v)) {
380                                 fprintf(stderr, "%s: fatal bmesh error (vert not in edge)! (bmesh internal error)\n", __func__);
381                                 err |= 2048;
382                         }
383
384                         if (l->radial_next == NULL || l->radial_prev == NULL)
385                                 err |= (1 << 12);
386                         if (l->f->len <= 0)
387                                 err |= (1 << 13);
388
389                         /* validate boundary loop--invalid for hole loops, of course,
390                  * but we won't be allowing those for a while ye */
391                         l2 = l;
392                         i = 0;
393                         do {
394                                 if (i >= BM_NGON_MAX) {
395                                         break;
396                                 }
397
398                                 i++;
399                         } while ((l2 = l2->next) != l);
400
401                         if (i != l->f->len || l2 != l)
402                                 err |= (1 << 14);
403
404                         if (!bmesh_radial_validate(bmesh_radial_length(l), l))
405                                 err |= (1 << 15);
406
407                         break;
408                 }
409                 case BM_FACE: {
410                         BMFace *f = element;
411                         BMLoop *l_iter;
412                         BMLoop *l_first;
413                         int len = 0;
414
415 #ifdef USE_BMESH_HOLES
416                         if (!f->loops.first)
417 #else
418                         if (!f->l_first)
419 #endif
420                         {
421                                 err |= (1 << 16);
422                         }
423                         l_iter = l_first = BM_FACE_FIRST_LOOP(f);
424                         do {
425                                 if (l_iter->f != f) {
426                                         fprintf(stderr, "%s: loop inside one face points to another! (bmesh internal error)\n", __func__);
427                                         err |= (1 << 17);
428                                 }
429
430                                 if (!l_iter->e)
431                                         err |= (1 << 18);
432                                 if (!l_iter->v)
433                                         err |= (1 << 19);
434                                 if (!BM_vert_in_edge(l_iter->e, l_iter->v) || !BM_vert_in_edge(l_iter->e, l_iter->next->v)) {
435                                         err |= (1 << 20);
436                                 }
437
438                                 if (!bmesh_radial_validate(bmesh_radial_length(l_iter), l_iter))
439                                         err |= (1 << 21);
440
441                                 if (!bmesh_disk_count(l_iter->v) || !bmesh_disk_count(l_iter->next->v))
442                                         err |= (1 << 22);
443
444                                 len++;
445                         } while ((l_iter = l_iter->next) != l_first);
446
447                         if (len != f->len)
448                                 err |= (1 << 23);
449                 }
450         }
451
452         if (err) {
453                 bmesh_error();
454         }
455
456         return err;
457 }
458
459 /* low level function, only free's,
460  * does not change adjust surrounding geometry */
461 static void bmesh_kill_only_vert(BMesh *bm, BMVert *v)
462 {
463         bm->totvert--;
464         bm->elem_index_dirty |= BM_VERT;
465
466         BM_select_history_remove(bm, (BMElem *)v);
467         if (v->head.data)
468                 CustomData_bmesh_free_block(&bm->vdata, &v->head.data);
469
470         BLI_mempool_free(bm->toolflagpool, v->oflags);
471         BLI_mempool_free(bm->vpool, v);
472 }
473
474 static void bmesh_kill_only_edge(BMesh *bm, BMEdge *e)
475 {
476         bm->totedge--;
477         bm->elem_index_dirty |= BM_EDGE;
478
479         BM_select_history_remove(bm, (BMElem *)e);
480
481         if (e->head.data)
482                 CustomData_bmesh_free_block(&bm->edata, &e->head.data);
483
484         BLI_mempool_free(bm->toolflagpool, e->oflags);
485         BLI_mempool_free(bm->epool, e);
486 }
487
488 static void bmesh_kill_only_face(BMesh *bm, BMFace *f)
489 {
490         if (bm->act_face == f)
491                 bm->act_face = NULL;
492
493         bm->totface--;
494         bm->elem_index_dirty |= BM_FACE;
495
496         BM_select_history_remove(bm, (BMElem *)f);
497
498         if (f->head.data)
499                 CustomData_bmesh_free_block(&bm->pdata, &f->head.data);
500
501         BLI_mempool_free(bm->toolflagpool, f->oflags);
502         BLI_mempool_free(bm->fpool, f);
503 }
504
505 static void bmesh_kill_only_loop(BMesh *bm, BMLoop *l)
506 {
507         bm->totloop--;
508         if (l->head.data)
509                 CustomData_bmesh_free_block(&bm->ldata, &l->head.data);
510
511         BLI_mempool_free(bm->lpool, l);
512 }
513
514 void BM_face_edges_kill(BMesh *bm, BMFace *f)
515 {
516         BMEdge **edges = NULL;
517         BLI_array_staticdeclare(edges, BM_NGON_STACK_SIZE);
518         BMLoop *l_iter;
519         BMLoop *l_first;
520         int i;
521         
522         l_iter = l_first = BM_FACE_FIRST_LOOP(f);
523         do {
524                 BLI_array_append(edges, l_iter->e);
525         } while ((l_iter = l_iter->next) != l_first);
526         
527         for (i = 0; i < BLI_array_count(edges); i++) {
528                 BM_edge_kill(bm, edges[i]);
529         }
530         
531         BLI_array_free(edges);
532 }
533
534 void BM_face_verts_kill(BMesh *bm, BMFace *f)
535 {
536         BMVert **verts = NULL;
537         BLI_array_staticdeclare(verts, BM_NGON_STACK_SIZE);
538         BMLoop *l_iter;
539         BMLoop *l_first;
540         int i;
541         
542         l_iter = l_first = BM_FACE_FIRST_LOOP(f);
543         do {
544                 BLI_array_append(verts, l_iter->v);
545         } while ((l_iter = l_iter->next) != l_first);
546         
547         for (i = 0; i < BLI_array_count(verts); i++) {
548                 BM_vert_kill(bm, verts[i]);
549         }
550         
551         BLI_array_free(verts);
552 }
553
554 void BM_face_kill(BMesh *bm, BMFace *f)
555 {
556 #ifdef USE_BMESH_HOLES
557         BMLoopList *ls, *ls_next;
558 #endif
559
560         BM_CHECK_ELEMENT(bm, f);
561
562 #ifdef USE_BMESH_HOLES
563         for (ls = f->loops.first; ls; ls = ls_next)
564 #else
565         if (f->l_first)
566 #endif
567         {
568                 BMLoop *l_iter, *l_next, *l_first;
569
570 #ifdef USE_BMESH_HOLES
571                 ls_next = ls->next;
572                 l_iter = l_first = ls->first;
573 #else
574                 l_iter = l_first = f->l_first;
575 #endif
576
577                 do {
578                         l_next = l_iter->next;
579
580                         bmesh_radial_remove_loop(l_iter, l_iter->e);
581                         bmesh_kill_only_loop(bm, l_iter);
582
583                 } while ((l_iter = l_next) != l_first);
584
585 #ifdef USE_BMESH_HOLES
586                 BLI_mempool_free(bm->looplistpool, ls);
587 #endif
588         }
589
590         bmesh_kill_only_face(bm, f);
591 }
592
593 void BM_edge_kill(BMesh *bm, BMEdge *e)
594 {
595
596         bmesh_disk_remove_edge(e, e->v1);
597         bmesh_disk_remove_edge(e, e->v2);
598
599         if (e->l) {
600                 BMLoop *l = e->l, *lnext, *startl = e->l;
601
602                 do {
603                         lnext = l->radial_next;
604                         if (lnext->f == l->f) {
605                                 BM_face_kill(bm, l->f);
606                                 break;
607                         }
608                         
609                         BM_face_kill(bm, l->f);
610
611                         if (l == lnext)
612                                 break;
613                         l = lnext;
614                 } while (l != startl);
615         }
616         
617         bmesh_kill_only_edge(bm, e);
618 }
619
620 void BM_vert_kill(BMesh *bm, BMVert *v)
621 {
622         if (v->e) {
623                 BMEdge *e, *nexte;
624                 
625                 e = v->e;
626                 while (v->e) {
627                         nexte = bmesh_disk_nextedge(e, v);
628                         BM_edge_kill(bm, e);
629                         e = nexte;
630                 }
631         }
632
633         bmesh_kill_only_vert(bm, v);
634 }
635
636 /********** private disk and radial cycle functions ********** */
637
638 /**
639  *                      bmesh_loop_reverse
640  *
641  *      FLIP FACE EULER
642  *
643  *      Changes the winding order of a face from CW to CCW or vice versa.
644  *      This euler is a bit peculiar in compairson to others as it is its
645  *      own inverse.
646  *
647  *      BMESH_TODO: reinsert validation code.
648  *
649  *  Returns -
650  *      1 for success, 0 for failure.
651  */
652
653 static int bmesh_loop_length(BMLoop *l)
654 {
655         BMLoop *l_first = l;
656         int i = 0;
657
658         do {
659                 i++;
660         } while ((l = l->next) != l_first);
661
662         return i;
663 }
664
665 static int bmesh_loop_reverse_loop(BMesh *bm, BMFace *f
666 #ifdef USE_BMESH_HOLES
667                                    , BMLoopList *lst
668 #endif
669                                    )
670 {
671
672 #ifdef USE_BMESH_HOLES
673         BMLoop *l_first = lst->first;
674 #else
675         BMLoop *l_first = f->l_first;
676 #endif
677
678         BMLoop *l_iter, *oldprev, *oldnext;
679         BMEdge **edar = NULL;
680         MDisps *md;
681         BLI_array_staticdeclare(edar, BM_NGON_STACK_SIZE);
682         int i, j, edok, len = 0, do_disps = CustomData_has_layer(&bm->ldata, CD_MDISPS);
683
684         len = bmesh_loop_length(l_first);
685
686         for (i = 0, l_iter = l_first; i < len; i++, l_iter = l_iter->next) {
687                 BMEdge *curedge = l_iter->e;
688                 bmesh_radial_remove_loop(l_iter, curedge);
689                 BLI_array_append(edar, curedge);
690         }
691
692         /* actually reverse the loop */
693         for (i = 0, l_iter = l_first; i < len; i++) {
694                 oldnext = l_iter->next;
695                 oldprev = l_iter->prev;
696                 l_iter->next = oldprev;
697                 l_iter->prev = oldnext;
698                 l_iter = oldnext;
699                 
700                 if (do_disps) {
701                         float (*co)[3];
702                         int x, y, sides;
703                         
704                         md = CustomData_bmesh_get(&bm->ldata, l_iter->head.data, CD_MDISPS);
705                         if (!md->totdisp || !md->disps)
706                                 continue;
707
708                         sides = (int)sqrt(md->totdisp);
709                         co = md->disps;
710                         
711                         for (x = 0; x < sides; x++) {
712                                 for (y = 0; y < x; y++) {
713                                         swap_v3_v3(co[y * sides + x], co[sides * x + y]);
714                                 }
715                         }
716                 }
717         }
718
719         if (len == 2) { /* two edged face */
720                 /* do some verification here! */
721                 l_first->e = edar[1];
722                 l_first->next->e = edar[0];
723         }
724         else {
725                 for (i = 0, l_iter = l_first; i < len; i++, l_iter = l_iter->next) {
726                         edok = 0;
727                         for (j = 0; j < len; j++) {
728                                 edok = bmesh_verts_in_edge(l_iter->v, l_iter->next->v, edar[j]);
729                                 if (edok) {
730                                         l_iter->e = edar[j];
731                                         break;
732                                 }
733                         }
734                 }
735         }
736         /* rebuild radia */
737         for (i = 0, l_iter = l_first; i < len; i++, l_iter = l_iter->next)
738                 bmesh_radial_append(l_iter->e, l_iter);
739
740         /* validate radia */
741         for (i = 0, l_iter = l_first; i < len; i++, l_iter = l_iter->next) {
742                 BM_CHECK_ELEMENT(bm, l_iter);
743                 BM_CHECK_ELEMENT(bm, l_iter->e);
744                 BM_CHECK_ELEMENT(bm, l_iter->v);
745                 BM_CHECK_ELEMENT(bm, l_iter->f);
746         }
747
748         BLI_array_free(edar);
749
750         BM_CHECK_ELEMENT(bm, f);
751
752         return 1;
753 }
754
755 int bmesh_loop_reverse(BMesh *bm, BMFace *f)
756 {
757 #ifdef USE_BMESH_HOLES
758         return bmesh_loop_reverse_loop(bm, f, f->loops.first);
759 #else
760         return bmesh_loop_reverse_loop(bm, f);
761 #endif
762 }
763
764 static void bmesh_systag_elements(BMesh *UNUSED(bm), void *veles, int tot, int flag)
765 {
766         BMHeader **eles = veles;
767         int i;
768
769         for (i = 0; i < tot; i++) {
770                 BM_ELEM_API_FLAG_ENABLE((BMElemF *)eles[i], flag);
771         }
772 }
773
774 static void bmesh_clear_systag_elements(BMesh *UNUSED(bm), void *veles, int tot, int flag)
775 {
776         BMHeader **eles = veles;
777         int i;
778
779         for (i = 0; i < tot; i++) {
780                 BM_ELEM_API_FLAG_DISABLE((BMElemF *)eles[i], flag);
781         }
782 }
783
784 #define FACE_MARK       (1 << 10)
785
786 static int count_flagged_radial(BMesh *bm, BMLoop *l, int flag)
787 {
788         BMLoop *l2 = l;
789         int i = 0, c = 0;
790
791         do {
792                 if (!l2) {
793                         bmesh_error();
794                         goto error;
795                 }
796                 
797                 i += BM_ELEM_API_FLAG_TEST(l2->f, flag) ? 1 : 0;
798                 l2 = bmesh_radial_nextloop(l2);
799                 if (c >= BM_LOOP_RADIAL_MAX) {
800                         bmesh_error();
801                         goto error;
802                 }
803                 c++;
804         } while (l2 != l);
805
806         return i;
807
808 error:
809         BMO_error_raise(bm, bm->currentop, BMERR_MESH_ERROR, NULL);
810         return 0;
811 }
812
813 static int UNUSED_FUNCTION(count_flagged_disk)(BMVert *v, int flag)
814 {
815         BMEdge *e = v->e;
816         int i = 0;
817
818         if (!e)
819                 return 0;
820
821         do {
822                 i += BM_ELEM_API_FLAG_TEST(e, flag) ? 1 : 0;
823                 e = bmesh_disk_nextedge(e, v);
824         } while (e != v->e);
825
826         return i;
827 }
828
829 static int disk_is_flagged(BMVert *v, int flag)
830 {
831         BMEdge *e = v->e;
832
833         if (!e)
834                 return FALSE;
835
836         do {
837                 BMLoop *l = e->l;
838
839                 if (!l) {
840                         return FALSE;
841                 }
842                 
843                 if (bmesh_radial_length(l) == 1)
844                         return FALSE;
845                 
846                 do {
847                         if (!BM_ELEM_API_FLAG_TEST(l->f, flag))
848                                 return FALSE;
849
850                         l = l->radial_next;
851                 } while (l != e->l);
852
853                 e = bmesh_disk_nextedge(e, v);
854         } while (e != v->e);
855
856         return TRUE;
857 }
858
859 /* Midlevel Topology Manipulation Functions */
860
861 /*
862  * BM_faces_join
863  *
864  * Joins a collected group of faces into one. Only restriction on
865  * the input data is that the faces must be connected to each other.
866  *
867  * If a pair of faces share multiple edges, the pair of
868  * faces will be joined at every edge.
869  *
870  * Returns a pointer to the combined face.
871  */
872 BMFace *BM_faces_join(BMesh *bm, BMFace **faces, int totface)
873 {
874         BMFace *f, *newf;
875 #ifdef USE_BMESH_HOLES
876         BMLoopList *lst;
877         ListBase holes = {NULL, NULL};
878 #endif
879         BMLoop *l_iter;
880         BMLoop *l_first;
881         BMEdge **edges = NULL;
882         BMEdge **deledges = NULL;
883         BMVert **delverts = NULL;
884         BLI_array_staticdeclare(edges,    BM_NGON_STACK_SIZE);
885         BLI_array_staticdeclare(deledges, BM_NGON_STACK_SIZE);
886         BLI_array_staticdeclare(delverts, BM_NGON_STACK_SIZE);
887         BMVert *v1 = NULL, *v2 = NULL;
888         const char *err = NULL;
889         int i, tote = 0;
890
891         if (!totface) {
892                 bmesh_error();
893                 return NULL;
894         }
895
896         if (totface == 1)
897                 return faces[0];
898
899         bmesh_systag_elements(bm, faces, totface, _FLAG_JF);
900
901         for (i = 0; i < totface; i++) {
902                 f = faces[i];
903                 l_iter = l_first = BM_FACE_FIRST_LOOP(f);
904                 do {
905                         int rlen = count_flagged_radial(bm, l_iter, _FLAG_JF);
906
907                         if (rlen > 2) {
908                                 err = "Input faces do not form a contiguous manifold region";
909                                 goto error;
910                         }
911                         else if (rlen == 1) {
912                                 BLI_array_append(edges, l_iter->e);
913
914                                 if (!v1) {
915                                         v1 = l_iter->v;
916                                         v2 = BM_edge_other_vert(l_iter->e, l_iter->v);
917                                 }
918                                 tote++;
919                         }
920                         else if (rlen == 2) {
921                                 int d1, d2;
922
923                                 d1 = disk_is_flagged(l_iter->e->v1, _FLAG_JF);
924                                 d2 = disk_is_flagged(l_iter->e->v2, _FLAG_JF);
925
926                                 if (!d1 && !d2 && !BM_ELEM_API_FLAG_TEST(l_iter->e, _FLAG_JF)) {
927                                         /* don't remove an edge it makes up the side of another face
928                                          * else this will remove the face as well - campbell */
929                                         if (BM_edge_face_count(l_iter->e) <= 2) {
930                                                 BLI_array_append(deledges, l_iter->e);
931                                                 BM_ELEM_API_FLAG_ENABLE(l_iter->e, _FLAG_JF);
932                                         }
933                                 }
934                                 else {
935                                         if (d1 && !BM_ELEM_API_FLAG_TEST(l_iter->e->v1, _FLAG_JF)) {
936                                                 BLI_array_append(delverts, l_iter->e->v1);
937                                                 BM_ELEM_API_FLAG_ENABLE(l_iter->e->v1, _FLAG_JF);
938                                         }
939
940                                         if (d2 && !BM_ELEM_API_FLAG_TEST(l_iter->e->v2, _FLAG_JF)) {
941                                                 BLI_array_append(delverts, l_iter->e->v2);
942                                                 BM_ELEM_API_FLAG_ENABLE(l_iter->e->v2, _FLAG_JF);
943                                         }
944                                 }
945                         }
946                 } while ((l_iter = l_iter->next) != l_first);
947
948 #ifdef USE_BMESH_HOLES
949                 for (lst = f->loops.first; lst; lst = lst->next) {
950                         if (lst == f->loops.first) continue;
951                         
952                         BLI_remlink(&f->loops, lst);
953                         BLI_addtail(&holes, lst);
954                 }
955 #endif
956
957         }
958
959         /* create region fac */
960         newf = BM_face_create_ngon(bm, v1, v2, edges, tote, FALSE);
961         if (!newf || BMO_error_occurred(bm)) {
962                 if (!BMO_error_occurred(bm))
963                         err = "Invalid boundary region to join faces";
964                 goto error;
965         }
966
967         /* copy over loop data */
968         l_iter = l_first = BM_FACE_FIRST_LOOP(newf);
969         do {
970                 BMLoop *l2 = l_iter->radial_next;
971
972                 do {
973                         if (BM_ELEM_API_FLAG_TEST(l2->f, _FLAG_JF))
974                                 break;
975                         l2 = l2->radial_next;
976                 } while (l2 != l_iter);
977
978                 if (l2 != l_iter) {
979                         /* I think this is correct */
980                         if (l2->v != l_iter->v) {
981                                 l2 = l2->next;
982                         }
983
984                         BM_elem_attrs_copy(bm, bm, l2, l_iter);
985                 }
986         } while ((l_iter = l_iter->next) != l_first);
987         
988         BM_elem_attrs_copy(bm, bm, faces[0], newf);
989
990 #ifdef USE_BMESH_HOLES
991         /* add hole */
992         BLI_movelisttolist(&newf->loops, &holes);
993 #endif
994
995         /* update loop face pointer */
996 #ifdef USE_BMESH_HOLES
997         for (lst = newf->loops.first; lst; lst = lst->next)
998 #endif
999         {
1000 #ifdef USE_BMESH_HOLES
1001                 l_iter = l_first = lst->first;
1002 #else
1003                 l_iter = l_first = BM_FACE_FIRST_LOOP(newf);
1004 #endif
1005                 do {
1006                         l_iter->f = newf;
1007                 } while ((l_iter = l_iter->next) != l_first);
1008         }
1009
1010         bmesh_clear_systag_elements(bm, faces, totface, _FLAG_JF);
1011         BM_ELEM_API_FLAG_DISABLE(newf, _FLAG_JF);
1012
1013         /* handle multires data */
1014         if (CustomData_has_layer(&bm->ldata, CD_MDISPS)) {
1015                 l_iter = l_first = BM_FACE_FIRST_LOOP(newf);
1016                 do {
1017                         for (i = 0; i < totface; i++) {
1018                                 BM_loop_interp_multires(bm, l_iter, faces[i]);
1019                         }
1020                 } while ((l_iter = l_iter->next) != l_first);
1021         }
1022
1023         /* delete old geometr */
1024         for (i = 0; i < BLI_array_count(deledges); i++) {
1025                 BM_edge_kill(bm, deledges[i]);
1026         }
1027
1028         for (i = 0; i < BLI_array_count(delverts); i++) {
1029                 BM_vert_kill(bm, delverts[i]);
1030         }
1031         
1032         BLI_array_free(edges);
1033         BLI_array_free(deledges);
1034         BLI_array_free(delverts);
1035
1036         BM_CHECK_ELEMENT(bm, newf);
1037         return newf;
1038 error:
1039         bmesh_clear_systag_elements(bm, faces, totface, _FLAG_JF);
1040         BLI_array_free(edges);
1041         BLI_array_free(deledges);
1042         BLI_array_free(delverts);
1043
1044         if (err) {
1045                 BMO_error_raise(bm, bm->currentop, BMERR_DISSOLVEFACES_FAILED, err);
1046         }
1047         return NULL;
1048 }
1049
1050 static BMFace *bmesh_addpolylist(BMesh *bm, BMFace *UNUSED(example))
1051 {
1052         BMFace *f;
1053 #ifdef USE_BMESH_HOLES
1054         BMLoopList *lst;
1055 #endif
1056
1057         f = BLI_mempool_calloc(bm->fpool);
1058 #ifdef USE_BMESH_HOLES
1059         lst = BLI_mempool_calloc(bm->looplistpool);
1060 #endif
1061
1062         f->head.htype = BM_FACE;
1063 #ifdef USE_BMESH_HOLES
1064         BLI_addtail(&f->loops, lst);
1065 #endif
1066
1067 #ifdef USE_DEBUG_INDEX_MEMCHECK
1068         DEBUG_MEMCHECK_INDEX_INVALIDATE(f)
1069 #else
1070         BM_elem_index_set(f, -1); /* set_ok_invalid */
1071 #endif
1072
1073         bm->elem_index_dirty |= BM_FACE; /* may add to middle of the pool */
1074
1075         bm->totface++;
1076
1077         /* allocate flag */
1078         f->oflags = BLI_mempool_calloc(bm->toolflagpool);
1079
1080         CustomData_bmesh_set_default(&bm->pdata, &f->head.data);
1081
1082         f->len = 0;
1083
1084 #ifdef USE_BMESH_HOLES
1085         f->totbounds = 1;
1086 #endif
1087
1088         return f;
1089 }
1090
1091 /**
1092  *                      bmesh_SFME
1093  *
1094  *      SPLIT FACE MAKE EDGE:
1095  *
1096  *      Takes as input two vertices in a single face. An edge is created which divides the original face
1097  *      into two distinct regions. One of the regions is assigned to the original face and it is closed off.
1098  *      The second region has a new face assigned to it.
1099  *
1100  *      Examples:
1101  *
1102  *     Before:               After:
1103  *       ----------           ----------
1104  *       |        |           |        |
1105  *       |        |           |   f1   |
1106  *      v1   f1   v2          v1======v2
1107  *       |        |           |   f2   |
1108  *       |        |           |        |
1109  *       ----------           ----------
1110  *
1111  *      Note that the input vertices can be part of the same edge. This will
1112  *  result in a two edged face. This is desirable for advanced construction
1113  *  tools and particularly essential for edge bevel. Because of this it is
1114  *  up to the caller to decide what to do with the extra edge.
1115  *
1116  *  If holes is NULL, then both faces will lose
1117  *  all holes from the original face.  Also, you cannot split between
1118  *  a hole vert and a boundary vert; that case is handled by higher-
1119  *  level wrapping functions (when holes are fully implemented, anyway).
1120  *
1121  *  Note that holes represents which holes goes to the new face, and of
1122  *  course this requires removing them from the exitsing face first, since
1123  *  you cannot have linked list links inside multiple lists.
1124  *
1125  *      Returns -
1126  *  A BMFace pointer
1127  */
1128 BMFace *bmesh_sfme(BMesh *bm, BMFace *f, BMVert *v1, BMVert *v2,
1129                    BMLoop **rl,
1130 #ifdef USE_BMESH_HOLES
1131                    ListBase *holes,
1132 #endif
1133                    BMEdge *example
1134                    )
1135 {
1136 #ifdef USE_BMESH_HOLES
1137         BMLoopList *lst, *lst2;
1138 #endif
1139
1140         BMFace *f2;
1141         BMLoop *l_iter, *l_first;
1142         BMLoop *v1loop = NULL, *v2loop = NULL, *f1loop = NULL, *f2loop = NULL;
1143         BMEdge *e;
1144         int i, len, f1len, f2len;
1145
1146         /* verify that v1 and v2 are in face */
1147         len = f->len;
1148         for (i = 0, l_iter = BM_FACE_FIRST_LOOP(f); i < len; i++, l_iter = l_iter->next) {
1149                 if (l_iter->v == v1) v1loop = l_iter;
1150                 else if (l_iter->v == v2) v2loop = l_iter;
1151         }
1152
1153         if (!v1loop || !v2loop) {
1154                 return NULL;
1155         }
1156
1157         /* allocate new edge between v1 and v2 */
1158         e = BM_edge_create(bm, v1, v2, example, FALSE);
1159
1160         f2 = bmesh_addpolylist(bm, f);
1161         f1loop = bmesh_create_loop(bm, v2, e, f, v2loop);
1162         f2loop = bmesh_create_loop(bm, v1, e, f2, v1loop);
1163
1164         f1loop->prev = v2loop->prev;
1165         f2loop->prev = v1loop->prev;
1166         v2loop->prev->next = f1loop;
1167         v1loop->prev->next = f2loop;
1168
1169         f1loop->next = v1loop;
1170         f2loop->next = v2loop;
1171         v1loop->prev = f1loop;
1172         v2loop->prev = f2loop;
1173
1174 #ifdef USE_BMESH_HOLES
1175         lst = f->loops.first;
1176         lst2 = f2->loops.first;
1177
1178         lst2->first = lst2->last = f2loop;
1179         lst->first = lst->last = f1loop;
1180 #else
1181         f2->l_first = f2loop;
1182         f->l_first = f1loop;
1183 #endif
1184
1185         /* validate both loop */
1186         /* I dont know how many loops are supposed to be in each face at this point! FIXME */
1187
1188         /* go through all of f2's loops and make sure they point to it properly */
1189         l_iter = l_first = BM_FACE_FIRST_LOOP(f2);
1190         f2len = 0;
1191         do {
1192                 l_iter->f = f2;
1193                 f2len++;
1194         } while ((l_iter = l_iter->next) != l_first);
1195
1196         /* link up the new loops into the new edges radia */
1197         bmesh_radial_append(e, f1loop);
1198         bmesh_radial_append(e, f2loop);
1199
1200         f2->len = f2len;
1201
1202         f1len = 0;
1203         l_iter = l_first = BM_FACE_FIRST_LOOP(f);
1204         do {
1205                 f1len++;
1206         } while ((l_iter = l_iter->next) != l_first);
1207
1208         f->len = f1len;
1209
1210         if (rl) *rl = f2loop;
1211
1212 #ifdef USE_BMESH_HOLES
1213         if (holes) {
1214                 BLI_movelisttolist(&f2->loops, holes);
1215         }
1216         else {
1217                 /* this code is not significant until holes actually work */
1218                 //printf("warning: call to split face euler without holes argument; holes will be tossed.\n");
1219                 for (lst = f->loops.last; lst != f->loops.first; lst = lst2) {
1220                         lst2 = lst->prev;
1221                         BLI_mempool_free(bm->looplistpool, lst);
1222                 }
1223         }
1224 #endif
1225
1226         BM_CHECK_ELEMENT(bm, e);
1227         BM_CHECK_ELEMENT(bm, f);
1228         BM_CHECK_ELEMENT(bm, f2);
1229         
1230         return f2;
1231 }
1232
1233 /**
1234  *                      bmesh_SEMV
1235  *
1236  *      SPLIT EDGE MAKE VERT:
1237  *      Takes a given edge and splits it into two, creating a new vert.
1238  *
1239  *
1240  *              Before: OV---------TV
1241  *              After:  OV----NV---TV
1242  *
1243  *  Returns -
1244  *      BMVert pointer.
1245  *
1246  */
1247
1248 BMVert *bmesh_semv(BMesh *bm, BMVert *tv, BMEdge *e, BMEdge **re)
1249 {
1250         BMLoop *nextl;
1251         BMEdge *ne;
1252         BMVert *nv, *ov;
1253         int i, edok, valence1 = 0, valence2 = 0;
1254
1255         if (bmesh_vert_in_edge(e, tv) == 0) {
1256                 return NULL;
1257         }
1258         ov = bmesh_edge_getothervert(e, tv);
1259
1260         /* count valence of v1 */
1261         valence1 = bmesh_disk_count(ov);
1262
1263         /* count valence of v2 */
1264         valence2 = bmesh_disk_count(tv);
1265
1266         nv = BM_vert_create(bm, tv->co, tv);
1267         ne = BM_edge_create(bm, nv, tv, e, FALSE);
1268
1269         bmesh_disk_remove_edge(ne, tv);
1270         bmesh_disk_remove_edge(ne, nv);
1271
1272         /* remove e from v2's disk cycle */
1273         bmesh_disk_remove_edge(e, tv);
1274
1275         /* swap out tv for nv in e */
1276         bmesh_edge_swapverts(e, tv, nv);
1277
1278         /* add e to nv's disk cycl */
1279         bmesh_disk_append_edge(e, nv);
1280
1281         /* add ne to nv's disk cycl */
1282         bmesh_disk_append_edge(ne, nv);
1283
1284         /* add ne to tv's disk cycl */
1285         bmesh_disk_append_edge(ne, tv);
1286
1287         /* verify disk cycle */
1288         edok = bmesh_disk_validate(valence1, ov->e, ov);
1289         if (!edok) bmesh_error();
1290         edok = bmesh_disk_validate(valence2, tv->e, tv);
1291         if (!edok) bmesh_error();
1292         edok = bmesh_disk_validate(2, nv->e, nv);
1293         if (!edok) bmesh_error();
1294
1295         /* Split the radial cycle if presen */
1296         nextl = e->l;
1297         e->l = NULL;
1298         if (nextl) {
1299                 BMLoop *nl, *l;
1300                 int radlen = bmesh_radial_length(nextl);
1301                 int first1 = 0, first2 = 0;
1302
1303                 /* Take the next loop. Remove it from radial. Split it. Append to appropriate radials */
1304                 while (nextl) {
1305                         l = nextl;
1306                         l->f->len++;
1307                         nextl = nextl != nextl->radial_next ? nextl->radial_next : NULL;
1308                         bmesh_radial_remove_loop(l, NULL);
1309
1310                         nl = bmesh_create_loop(bm, NULL, NULL, l->f, l);
1311                         nl->prev = l;
1312                         nl->next = (l->next);
1313                         nl->prev->next = nl;
1314                         nl->next->prev = nl;
1315                         nl->v = nv;
1316
1317                         /* assign the correct edge to the correct loo */
1318                         if (bmesh_verts_in_edge(nl->v, nl->next->v, e)) {
1319                                 nl->e = e;
1320                                 l->e = ne;
1321
1322                                 /* append l into ne's rad cycl */
1323                                 if (!first1) {
1324                                         first1 = 1;
1325                                         l->radial_next = l->radial_prev = NULL;
1326                                 }
1327
1328                                 if (!first2) {
1329                                         first2 = 1;
1330                                         l->radial_next = l->radial_prev = NULL;
1331                                 }
1332                                 
1333                                 bmesh_radial_append(nl->e, nl);
1334                                 bmesh_radial_append(l->e, l);
1335                         }
1336                         else if (bmesh_verts_in_edge(nl->v, nl->next->v, ne)) {
1337                                 nl->e = ne;
1338                                 l->e = e;
1339
1340                                 /* append l into ne's rad cycl */
1341                                 if (!first1) {
1342                                         first1 = 1;
1343                                         l->radial_next = l->radial_prev = NULL;
1344                                 }
1345
1346                                 if (!first2) {
1347                                         first2 = 1;
1348                                         l->radial_next = l->radial_prev = NULL;
1349                                 }
1350
1351                                 bmesh_radial_append(nl->e, nl);
1352                                 bmesh_radial_append(l->e, l);
1353                         }
1354
1355                 }
1356
1357                 /* verify length of radial cycl */
1358                 edok = bmesh_radial_validate(radlen, e->l);
1359                 if (!edok) bmesh_error();
1360                 edok = bmesh_radial_validate(radlen, ne->l);
1361                 if (!edok) bmesh_error();
1362
1363                 /* verify loop->v and loop->next->v pointers for  */
1364                 for (i = 0, l = e->l; i < radlen; i++, l = l->radial_next) {
1365                         if (!(l->e == e)) bmesh_error();
1366                         //if (!(l->radial_next == l)) bmesh_error();
1367                         if (l->prev->e != ne && l->next->e != ne) {
1368                                 bmesh_error();
1369                         }
1370                         edok = bmesh_verts_in_edge(l->v, l->next->v, e);
1371                         if (!edok)               bmesh_error();
1372                         if (l->v == l->next->v)  bmesh_error();
1373                         if (l->e == l->next->e)  bmesh_error();
1374
1375                         /* verify loop cycle for kloop-> */
1376                         BM_CHECK_ELEMENT(bm, l);
1377                         BM_CHECK_ELEMENT(bm, l->v);
1378                         BM_CHECK_ELEMENT(bm, l->e);
1379                         BM_CHECK_ELEMENT(bm, l->f);
1380                 }
1381                 /* verify loop->v and loop->next->v pointers for n */
1382                 for (i = 0, l = ne->l; i < radlen; i++, l = l->radial_next) {
1383                         if (!(l->e == ne)) bmesh_error();
1384                         //if (!(l->radial_next == l)) bmesh_error();
1385                         if (l->prev->e != e && l->next->e != e) bmesh_error();
1386                         edok = bmesh_verts_in_edge(l->v, l->next->v, ne);
1387                         if (!edok)                bmesh_error();
1388                         if (l->v == l->next->v)  bmesh_error();
1389                         if (l->e == l->next->e)  bmesh_error();
1390
1391                         BM_CHECK_ELEMENT(bm, l);
1392                         BM_CHECK_ELEMENT(bm, l->v);
1393                         BM_CHECK_ELEMENT(bm, l->e);
1394                         BM_CHECK_ELEMENT(bm, l->f);
1395                 }
1396         }
1397
1398         BM_CHECK_ELEMENT(bm, ne);
1399         BM_CHECK_ELEMENT(bm, nv);
1400         BM_CHECK_ELEMENT(bm, ov);
1401         BM_CHECK_ELEMENT(bm, e);
1402         BM_CHECK_ELEMENT(bm, tv);
1403
1404         if (re) *re = ne;
1405         return nv;
1406 }
1407
1408 /**
1409  *                      bmesh_JEKV
1410  *
1411  *      JOIN EDGE KILL VERT:
1412  *      Takes a an edge and pointer to one of its vertices and collapses
1413  *      the edge on that vertex.
1414  *
1415  *      Before:    OE      KE
1416  *               ------- -------
1417  *               |     ||      |
1418  *              OV     KV      TV
1419  *
1420  *
1421  *   After:             OE
1422  *               ---------------
1423  *               |             |
1424  *              OV             TV
1425  *
1426  *
1427  *      Restrictions:
1428  *      KV is a vertex that must have a valance of exactly two. Furthermore
1429  *  both edges in KV's disk cycle (OE and KE) must be unique (no double
1430  *  edges).
1431  *
1432  *      It should also be noted that this euler has the possibility of creating
1433  *      faces with just 2 edges. It is up to the caller to decide what to do with
1434  *  these faces.
1435  *
1436  *  Returns -
1437  *      1 for success, 0 for failure.
1438  */
1439 int bmesh_jekv(BMesh *bm, BMEdge *ke, BMVert *kv)
1440 {
1441         BMEdge *oe;
1442         BMVert *ov, *tv;
1443         BMLoop *killoop, *l;
1444         int len, radlen = 0, halt = 0, i, valence1, valence2, edok;
1445
1446         if (bmesh_vert_in_edge(ke, kv) == 0) {
1447                 return FALSE;
1448         }
1449
1450         len = bmesh_disk_count(kv);
1451         
1452         if (len == 2) {
1453                 oe = bmesh_disk_nextedge(ke, kv);
1454                 tv = bmesh_edge_getothervert(ke, kv);
1455                 ov = bmesh_edge_getothervert(oe, kv);
1456                 halt = bmesh_verts_in_edge(kv, tv, oe); /* check for double edge */
1457                 
1458                 if (halt) {
1459                         return FALSE;
1460                 }
1461                 else {
1462                         /* For verification later, count valence of ov and t */
1463                         valence1 = bmesh_disk_count(ov);
1464                         valence2 = bmesh_disk_count(tv);
1465                         
1466                         /* remove oe from kv's disk cycl */
1467                         bmesh_disk_remove_edge(oe, kv);
1468                         /* relink oe->kv to be oe->t */
1469                         bmesh_edge_swapverts(oe, kv, tv);
1470                         /* append oe to tv's disk cycl */
1471                         bmesh_disk_append_edge(oe, tv);
1472                         /* remove ke from tv's disk cycl */
1473                         bmesh_disk_remove_edge(ke, tv);
1474
1475                         /* deal with radial cycle of k */
1476                         radlen = bmesh_radial_length(ke->l);
1477                         if (ke->l) {
1478                                 /* first step, fix the neighboring loops of all loops in ke's radial cycl */
1479                                 for (i = 0, killoop = ke->l; i < radlen; i++, killoop = bmesh_radial_nextloop(killoop)) {
1480                                         /* relink loops and fix vertex pointer */
1481                                         if (killoop->next->v == kv) {
1482                                                 killoop->next->v = tv;
1483                                         }
1484
1485                                         killoop->next->prev = killoop->prev;
1486                                         killoop->prev->next = killoop->next;
1487                                         if (BM_FACE_FIRST_LOOP(killoop->f) == killoop) {
1488                                                 BM_FACE_FIRST_LOOP(killoop->f) = killoop->next;
1489                                         }
1490                                         killoop->next = NULL;
1491                                         killoop->prev = NULL;
1492
1493                                         /* fix len attribute of fac */
1494                                         killoop->f->len--;
1495                                 }
1496                                 /* second step, remove all the hanging loops attached to k */
1497                                 radlen = bmesh_radial_length(ke->l);
1498
1499                                 if (LIKELY(radlen)) {
1500                                         BMLoop **loops = NULL;
1501                                         BLI_array_fixedstack_declare(loops, BM_NGON_STACK_SIZE, radlen, __func__);
1502
1503                                         killoop = ke->l;
1504
1505                                         /* this should be wrapped into a bme_free_radial function to be used by bmesh_KF as well.. */
1506                                         for (i = 0; i < radlen; i++) {
1507                                                 loops[i] = killoop;
1508                                                 killoop = bmesh_radial_nextloop(killoop);
1509                                         }
1510                                         for (i = 0; i < radlen; i++) {
1511                                                 bm->totloop--;
1512                                                 BLI_mempool_free(bm->lpool, loops[i]);
1513                                         }
1514                                         BLI_array_fixedstack_free(loops);
1515                                 }
1516
1517                                 /* Validate radial cycle of o */
1518                                 edok = bmesh_radial_validate(radlen, oe->l);
1519                                 if (!edok) {
1520                                         bmesh_error();
1521                                 }
1522                         }
1523
1524                         /* deallocate edg */
1525                         bmesh_kill_only_edge(bm, ke);
1526
1527                         /* deallocate verte */
1528                         bmesh_kill_only_vert(bm, kv);
1529
1530                         /* Validate disk cycle lengths of ov, tv are unchange */
1531                         edok = bmesh_disk_validate(valence1, ov->e, ov);
1532                         if (!edok) bmesh_error();
1533                         edok = bmesh_disk_validate(valence2, tv->e, tv);
1534                         if (!edok) bmesh_error();
1535
1536                         /* Validate loop cycle of all faces attached to o */
1537                         for (i = 0, l = oe->l; i < radlen; i++, l = bmesh_radial_nextloop(l)) {
1538                                 if (l->e != oe) bmesh_error();
1539                                 edok = bmesh_verts_in_edge(l->v, l->next->v, oe);
1540                                 if (!edok) bmesh_error();
1541                                 edok = bmesh_loop_validate(l->f);
1542                                 if (!edok) bmesh_error();
1543
1544                                 BM_CHECK_ELEMENT(bm, l);
1545                                 BM_CHECK_ELEMENT(bm, l->v);
1546                                 BM_CHECK_ELEMENT(bm, l->e);
1547                                 BM_CHECK_ELEMENT(bm, l->f);
1548                         }
1549
1550                         BM_CHECK_ELEMENT(bm, ov);
1551                         BM_CHECK_ELEMENT(bm, tv);
1552                         BM_CHECK_ELEMENT(bm, oe);
1553
1554                         return TRUE;
1555                 }
1556         }
1557         return FALSE;
1558 }
1559
1560 /**
1561  *                      bmesh_JFKE
1562  *
1563  *      JOIN FACE KILL EDGE:
1564  *
1565  *      Takes two faces joined by a single 2-manifold edge and fuses them togather.
1566  *      The edge shared by the faces must not be connected to any other edges which have
1567  *      Both faces in its radial cycle
1568  *
1569  *      Examples:
1570  *
1571  *        A                   B
1572  *       ----------           ----------
1573  *       |        |           |        |
1574  *       |   f1   |           |   f1   |
1575  *      v1========v2 = Ok!    v1==V2==v3 == Wrong!
1576  *       |   f2   |           |   f2   |
1577  *       |        |           |        |
1578  *       ----------           ----------
1579  *
1580  *      In the example A, faces f1 and f2 are joined by a single edge, and the euler can safely be used.
1581  *      In example B however, f1 and f2 are joined by multiple edges and will produce an error. The caller
1582  *      in this case should call bmesh_JEKV on the extra edges before attempting to fuse f1 and f2.
1583  *
1584  *      Also note that the order of arguments decides whether or not certain per-face attributes are present
1585  *      in the resultant face. For instance vertex winding, material index, smooth flags, ect are inherited
1586  *      from f1, not f2.
1587  *
1588  *  Returns -
1589  *      A BMFace pointer
1590  */
1591 BMFace *bmesh_jfke(BMesh *bm, BMFace *f1, BMFace *f2, BMEdge *e)
1592 {
1593         BMLoop *l_iter, *f1loop = NULL, *f2loop = NULL;
1594         int newlen = 0, i, f1len = 0, f2len = 0, radlen = 0, edok, shared;
1595         BMIter iter;
1596
1597         /* can't join a face to itsel */
1598         if (f1 == f2) {
1599                 return NULL;
1600         }
1601
1602         /* verify that e is in both f1 and f2 */
1603         f1len = f1->len;
1604         f2len = f2->len;
1605         BM_ITER(l_iter, &iter, bm, BM_LOOPS_OF_FACE, f1) {
1606                 if (l_iter->e == e) {
1607                         f1loop = l_iter;
1608                         break;
1609                 }
1610         }
1611         BM_ITER(l_iter, &iter, bm, BM_LOOPS_OF_FACE, f2) {
1612                 if (l_iter->e == e) {
1613                         f2loop = l_iter;
1614                         break;
1615                 }
1616         }
1617         if (!(f1loop && f2loop)) {
1618                 return NULL;
1619         }
1620         
1621         /* validate that edge is 2-manifold edg */
1622         radlen = bmesh_radial_length(f1loop);
1623         if (radlen != 2) {
1624                 return NULL;
1625         }
1626
1627         /* validate direction of f2's loop cycle is compatible */
1628         if (f1loop->v == f2loop->v) {
1629                 return NULL;
1630         }
1631
1632         /* validate that for each face, each vertex has another edge in its disk cycle that is
1633          * not e, and not shared. */
1634         if ( bmesh_radial_find_face(f1loop->next->e, f2) ||
1635              bmesh_radial_find_face(f1loop->prev->e, f2) ||
1636              bmesh_radial_find_face(f2loop->next->e, f1) ||
1637              bmesh_radial_find_face(f2loop->prev->e, f1) )
1638         {
1639                 return NULL;
1640         }
1641
1642         /* validate only one shared edg */
1643         shared = BM_face_share_edges(f1, f2);
1644         if (shared > 1) {
1645                 return NULL;
1646         }
1647
1648         /* validate no internal join */
1649         for (i = 0, l_iter = BM_FACE_FIRST_LOOP(f1); i < f1len; i++, l_iter = l_iter->next) {
1650                 BM_elem_flag_disable(l_iter->v, BM_ELEM_TAG);
1651         }
1652         for (i = 0, l_iter = BM_FACE_FIRST_LOOP(f2); i < f2len; i++, l_iter = l_iter->next) {
1653                 BM_elem_flag_disable(l_iter->v, BM_ELEM_TAG);
1654         }
1655
1656         for (i = 0, l_iter = BM_FACE_FIRST_LOOP(f1); i < f1len; i++, l_iter = l_iter->next) {
1657                 if (l_iter != f1loop) {
1658                         BM_elem_flag_enable(l_iter->v, BM_ELEM_TAG);
1659                 }
1660         }
1661         for (i = 0, l_iter = BM_FACE_FIRST_LOOP(f2); i < f2len; i++, l_iter = l_iter->next) {
1662                 if (l_iter != f2loop) {
1663                         /* as soon as a duplicate is found, bail out */
1664                         if (BM_elem_flag_test(l_iter->v, BM_ELEM_TAG)) {
1665                                 return NULL;
1666                         }
1667                 }
1668         }
1669
1670         /* join the two loop */
1671         f1loop->prev->next = f2loop->next;
1672         f2loop->next->prev = f1loop->prev;
1673         
1674         f1loop->next->prev = f2loop->prev;
1675         f2loop->prev->next = f1loop->next;
1676         
1677         /* if f1loop was baseloop, make f1loop->next the base. */
1678         if (BM_FACE_FIRST_LOOP(f1) == f1loop)
1679                 BM_FACE_FIRST_LOOP(f1) = f1loop->next;
1680
1681         /* increase length of f1 */
1682         f1->len += (f2->len - 2);
1683
1684         /* make sure each loop points to the proper fac */
1685         newlen = f1->len;
1686         for (i = 0, l_iter = BM_FACE_FIRST_LOOP(f1); i < newlen; i++, l_iter = l_iter->next)
1687                 l_iter->f = f1;
1688         
1689         /* remove edge from the disk cycle of its two vertices */
1690         bmesh_disk_remove_edge(f1loop->e, f1loop->e->v1);
1691         bmesh_disk_remove_edge(f1loop->e, f1loop->e->v2);
1692         
1693         /* deallocate edge and its two loops as well as f2 */
1694         BLI_mempool_free(bm->toolflagpool, f1loop->e->oflags);
1695         BLI_mempool_free(bm->epool, f1loop->e);
1696         bm->totedge--;
1697         BLI_mempool_free(bm->lpool, f1loop);
1698         bm->totloop--;
1699         BLI_mempool_free(bm->lpool, f2loop);
1700         bm->totloop--;
1701         BLI_mempool_free(bm->toolflagpool, f2->oflags);
1702         BLI_mempool_free(bm->fpool, f2);
1703         bm->totface--;
1704         /* account for both above */
1705         bm->elem_index_dirty |= BM_EDGE | BM_FACE;
1706
1707         BM_CHECK_ELEMENT(bm, f1);
1708
1709         /* validate the new loop cycle */
1710         edok = bmesh_loop_validate(f1);
1711         if (!edok) bmesh_error();
1712         
1713         return f1;
1714 }
1715
1716 /*
1717  * BMESH SPLICE VERT
1718  *
1719  * merges two verts into one (v into vtarget).
1720  */
1721 static int bmesh_splicevert(BMesh *bm, BMVert *v, BMVert *vtarget)
1722 {
1723         BMEdge *e;
1724         BMLoop *l;
1725         BMIter liter;
1726
1727         /* verts already spliced */
1728         if (v == vtarget) {
1729                 return FALSE;
1730         }
1731
1732         /* retarget all the loops of v to vtarget */
1733         BM_ITER(l, &liter, bm, BM_LOOPS_OF_VERT, v) {
1734                 l->v = vtarget;
1735         }
1736
1737         /* move all the edges from v's disk to vtarget's disk */
1738         e = v->e;
1739         while (e != NULL) {
1740                 bmesh_disk_remove_edge(e, v);
1741                 bmesh_edge_swapverts(e, v, vtarget);
1742                 bmesh_disk_append_edge(e, vtarget);
1743                 e = v->e;
1744         }
1745
1746         BM_CHECK_ELEMENT(bm, v);
1747         BM_CHECK_ELEMENT(bm, vtarget);
1748
1749         /* v is unused now, and can be killed */
1750         BM_vert_kill(bm, v);
1751
1752         return TRUE;
1753 }
1754
1755 /* BMESH CUT VERT
1756  *
1757  * cut all disjoint fans that meet at a vertex, making a unique
1758  * vertex for each region. returns an array of all resulting
1759  * vertices.
1760  */
1761 static int bmesh_cutvert(BMesh *bm, BMVert *v, BMVert ***vout, int *len)
1762 {
1763         BMEdge **stack = NULL;
1764         BLI_array_declare(stack);
1765         BMVert **verts = NULL;
1766         GHash *visithash;
1767         BMIter eiter, liter;
1768         BMLoop *l;
1769         BMEdge *e;
1770         int i, maxindex;
1771         BMLoop *nl;
1772
1773         visithash = BLI_ghash_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp, "bmesh_cutvert visithash");
1774
1775         maxindex = 0;
1776         BM_ITER(e, &eiter, bm, BM_EDGES_OF_VERT, v) {
1777                 if (BLI_ghash_haskey(visithash, e)) {
1778                         continue;
1779                 }
1780
1781                 /* Prime the stack with this unvisited edge */
1782                 BLI_array_append(stack, e);
1783
1784                 /* Considering only edges and faces incident on vertex v, walk
1785                  * the edges & faces and assign an index to each connected set */
1786                 while ((e = BLI_array_pop(stack))) {
1787                         BLI_ghash_insert(visithash, e, SET_INT_IN_POINTER(maxindex));
1788
1789                         BM_ITER(l, &liter, bm, BM_LOOPS_OF_EDGE, e) {
1790                                 nl = (l->v == v) ? l->prev : l->next;
1791                                 if (!BLI_ghash_haskey(visithash, nl->e)) {
1792                                         BLI_array_append(stack, nl->e);
1793                                 }
1794                         }
1795                 }
1796
1797                 maxindex++;
1798         }
1799
1800         /* Make enough verts to split v for each group */
1801         verts = MEM_callocN(sizeof(BMVert *) * maxindex, "bmesh_cutvert");
1802         verts[0] = v;
1803         for (i = 1; i < maxindex; i++) {
1804                 verts[i] = BM_vert_create(bm, v->co, v);
1805         }
1806
1807         /* Replace v with the new verts in each group */
1808         BM_ITER(l, &liter, bm, BM_LOOPS_OF_VERT, v) {
1809                 i = GET_INT_FROM_POINTER(BLI_ghash_lookup(visithash, l->e));
1810                 if (i == 0) {
1811                         continue;
1812                 }
1813
1814                 /* Loops here should alway refer to an edge that has v as an
1815                  * endpoint. For each appearance of this vert in a face, there
1816                  * will actually be two iterations: one for the loop heading
1817                  * towards vertex v, and another for the loop heading out from
1818                  * vertex v. Only need to swap the vertex on one of those times,
1819                  * on the outgoing loop. */
1820                 if (l->v == v) {
1821                         l->v = verts[i];
1822                 }
1823         }
1824
1825         BM_ITER(e, &eiter, bm, BM_EDGES_OF_VERT, v) {
1826                 i = GET_INT_FROM_POINTER(BLI_ghash_lookup(visithash, e));
1827                 if (i == 0) {
1828                         continue;
1829                 }
1830
1831                 BLI_assert(e->v1 == v || e->v2 == v);
1832                 bmesh_disk_remove_edge(e, v);
1833                 bmesh_edge_swapverts(e, v, verts[i]);
1834                 bmesh_disk_append_edge(e, verts[i]);
1835         }
1836
1837         BLI_ghash_free(visithash, NULL, NULL);
1838         BLI_array_free(stack);
1839
1840         for (i = 0; i < maxindex; i++) {
1841                 BM_CHECK_ELEMENT(bm, verts[i]);
1842         }
1843
1844         if (len != NULL) {
1845                 *len = maxindex;
1846         }
1847
1848         if (vout != NULL) {
1849                 *vout = verts;
1850         }
1851         else {
1852                 MEM_freeN(verts);
1853         }
1854
1855         return TRUE;
1856 }
1857
1858 /* BMESH SPLICE EDGE
1859  *
1860  * splice two unique edges which share the same two vertices into one edge.
1861  *
1862  * edges must already have the same vertices
1863  */
1864 static int UNUSED_FUNCTION(bmesh_spliceedge)(BMesh *bm, BMEdge *e, BMEdge *etarget)
1865 {
1866         BMLoop *l;
1867
1868         if (!BM_vert_in_edge(e, etarget->v1) || !BM_vert_in_edge(e, etarget->v2)) {
1869                 /* not the same vertices can't splice */
1870                 return FALSE;
1871         }
1872
1873         while (e->l) {
1874                 l = e->l;
1875                 BLI_assert(BM_vert_in_edge(etarget, l->v));
1876                 BLI_assert(BM_vert_in_edge(etarget, l->next->v));
1877                 bmesh_radial_remove_loop(l, e);
1878                 bmesh_radial_append(etarget, l);
1879         }
1880
1881         BLI_assert(bmesh_radial_length(e->l) == 0);
1882
1883         BM_CHECK_ELEMENT(bm, e);
1884         BM_CHECK_ELEMENT(bm, etarget);
1885
1886         BM_edge_kill(bm, e);
1887
1888         return TRUE;
1889 }
1890
1891 /*
1892  * BMESH CUT EDGE
1893  *
1894  * Cuts a single edge into two edge: the original edge and
1895  * a new edge that has only "cutl" in its radial.
1896  *
1897  * Does nothing if cutl is already the only loop in the
1898  * edge radial.
1899  */
1900 static int bmesh_cutedge(BMesh *bm, BMEdge *e, BMLoop *cutl)
1901 {
1902         BMEdge *ne;
1903         int radlen;
1904
1905         BLI_assert(cutl->e == e);
1906         BLI_assert(e->l);
1907         
1908         radlen = bmesh_radial_length(e->l);
1909         if (radlen < 2) {
1910                 /* no cut required */
1911                 return TRUE;
1912         }
1913
1914         if (cutl == e->l) {
1915                 e->l = cutl->radial_next;
1916         }
1917
1918         ne = BM_edge_create(bm, e->v1, e->v2, e, FALSE);
1919         bmesh_radial_remove_loop(cutl, e);
1920         bmesh_radial_append(ne, cutl);
1921         cutl->e = ne;
1922
1923         BLI_assert(bmesh_radial_length(e->l) == radlen - 1);
1924         BLI_assert(bmesh_radial_length(ne->l) == 1);
1925
1926         BM_CHECK_ELEMENT(bm, ne);
1927         BM_CHECK_ELEMENT(bm, e);
1928
1929         return TRUE;
1930 }
1931
1932 /*
1933  * BMESH UNGLUE REGION MAKE VERT
1934  *
1935  * Disconnects a face from its vertex fan at loop sl.
1936  */
1937 static BMVert *bmesh_urmv_loop(BMesh *bm, BMLoop *sl)
1938 {
1939         BMVert **vtar;
1940         int len, i;
1941         BMVert *nv = NULL;
1942         BMVert *sv = sl->v;
1943
1944         /* peel the face from the edge radials on both sides of the
1945          * loop vert, disconnecting the face from its fan */
1946         bmesh_cutedge(bm, sl->e, sl);
1947         bmesh_cutedge(bm, sl->prev->e, sl->prev);
1948
1949         if (bmesh_disk_count(sv) == 2) {
1950                 /* If there are still only two edges out of sv, then
1951                  * this whole URMV was just a no-op, so exit now. */
1952                 return sv;
1953         }
1954
1955         /* Update the disk start, so that v->e points to an edge
1956          * not touching the split loop. This is so that bmesh_cutvert
1957          * will leave the original sv on some *other* fan (not the
1958          * one-face fan that holds the unglue face). */
1959         while (sv->e == sl->e || sv->e == sl->prev->e) {
1960                 sv->e = bmesh_disk_nextedge(sv->e, sv);
1961         }
1962
1963         /* Split all fans connected to the vert, duplicating it for
1964          * each fans. */
1965         bmesh_cutvert(bm, sv, &vtar, &len);
1966
1967         /* There should have been at least two fans cut apart here,
1968          * otherwise the early exit would have kicked in. */
1969         BLI_assert(len >= 2);
1970
1971         nv = sl->v;
1972
1973         /* Desired result here is that a new vert should always be
1974          * created for the unglue face. This is so we can glue any
1975          * extras back into the original vert. */
1976         BLI_assert(nv != sv);
1977         BLI_assert(sv == vtar[0]);
1978
1979         /* If there are more than two verts as a result, glue together
1980          * all the verts except the one this URMV intended to create */
1981         if (len > 2) {
1982                 for (i = 0; i < len; i++) {
1983                         if (vtar[i] == nv) {
1984                                 break;
1985                         }
1986                 }
1987
1988                 if (i != len) {
1989                         /* Swap the single vert that was needed for the
1990                          * unglue into the last array slot */
1991                         SWAP(BMVert *, vtar[i], vtar[len - 1]);
1992
1993                         /* And then glue the rest back together */
1994                         for (i = 1; i < len - 1; i++) {
1995                                 bmesh_splicevert(bm, vtar[i], vtar[0]);
1996                         }
1997                 }
1998         }
1999
2000         MEM_freeN(vtar);
2001
2002         return nv;
2003 }
2004
2005 /*
2006  * BMESH UNGLUE REGION MAKE VERT
2007  *
2008  * Disconnects sf from the vertex fan at sv
2009  */
2010 BMVert *bmesh_urmv(BMesh *bm, BMFace *sf, BMVert *sv)
2011 {
2012         BMLoop *l_first;
2013         BMLoop *l_iter;
2014
2015         l_iter = l_first = BM_FACE_FIRST_LOOP(sf);
2016         do {
2017                 if (l_iter->v == sv) {
2018                         break;
2019                 }
2020         } while ((l_iter = l_iter->next) != l_first);
2021
2022         if (l_iter->v != sv) {
2023                 /* sv is not part of sf */
2024                 return NULL;
2025         }
2026
2027         return bmesh_urmv_loop(bm, l_iter);
2028 }