Cleanup: comment line length (editors)
[blender.git] / source / blender / editors / mesh / editmesh_rip.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  * The Original Code is Copyright (C) 2004 by Blender Foundation.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): Joseph Eagar
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/editors/mesh/editmesh_rip.c
29  *  \ingroup edmesh
30  */
31
32 #include "MEM_guardedalloc.h"
33
34 #include "DNA_object_types.h"
35
36 #include "BLI_math.h"
37 #include "BLI_array.h"
38
39 #include "BKE_context.h"
40 #include "BKE_report.h"
41 #include "BKE_editmesh.h"
42
43 #include "RNA_define.h"
44 #include "RNA_access.h"
45
46 #include "WM_types.h"
47
48 #include "ED_mesh.h"
49 #include "ED_screen.h"
50 #include "ED_transform.h"
51 #include "ED_view3d.h"
52
53 #include "bmesh.h"
54 #include "bmesh_tools.h"
55
56 #include "mesh_intern.h"  /* own include */
57
58 /**
59  * helper to find edge for edge_rip,
60  *
61  * \param inset: is used so we get some useful distance
62  * when comparing multiple edges that meet at the same
63  * point and would result in the same distance.
64  */
65 #define INSET_DEFAULT 0.00001f
66 static float edbm_rip_edgedist_squared(
67         ARegion *ar, float mat[4][4],
68         const float co1[3], const float co2[3], const float mvalf[2],
69         const float inset)
70 {
71         float vec1[2], vec2[2], dist_sq;
72
73         ED_view3d_project_float_v2_m4(ar, co1, vec1, mat);
74         ED_view3d_project_float_v2_m4(ar, co2, vec2, mat);
75
76         if (inset != 0.0f) {
77                 const float dist_2d = len_v2v2(vec1, vec2);
78                 if (dist_2d > FLT_EPSILON) {
79                         const float dist = inset / dist_2d;
80                         BLI_assert(isfinite(dist));
81                         interp_v2_v2v2(vec1, vec1, vec2, dist);
82                         interp_v2_v2v2(vec2, vec2, vec1, dist);
83                 }
84         }
85
86         dist_sq = dist_squared_to_line_segment_v2(mvalf, vec1, vec2);
87         BLI_assert(isfinite(dist_sq));
88
89         return dist_sq;
90 }
91
92 #if 0
93 static float edbm_rip_linedist(
94         ARegion *ar, float mat[4][4],
95         const float co1[3], const float co2[3], const float mvalf[2])
96 {
97         float vec1[2], vec2[2];
98
99         ED_view3d_project_float_v2_m4(ar, co1, vec1, mat);
100         ED_view3d_project_float_v2_m4(ar, co2, vec2, mat);
101
102         return dist_to_line_v2(mvalf, vec1, vec2);
103 }
104 #endif
105
106 /* calculaters a point along the loop tangent which can be used to measure against edges */
107 static void edbm_calc_loop_co(BMLoop *l, float l_mid_co[3])
108 {
109         BM_loop_calc_face_tangent(l, l_mid_co);
110
111         /* scale to average of surrounding edge size, only needs to be approx, but should
112          * be roughly equivalent to the check below which uses the middle of the edge. */
113         mul_v3_fl(l_mid_co, (BM_edge_calc_length(l->e) + BM_edge_calc_length(l->prev->e)) / 2.0f);
114
115         add_v3_v3(l_mid_co, l->v->co);
116 }
117
118
119 static float edbm_rip_edge_side_measure(
120         BMEdge *e, BMLoop *e_l,
121         ARegion *ar,
122         float projectMat[4][4], const float fmval[2])
123 {
124         float cent[3] = {0, 0, 0}, mid[3];
125
126         float vec[2];
127         float fmval_tweak[2];
128         float e_v1_co[2], e_v2_co[2];
129         float score;
130
131         BMVert *v1_other;
132         BMVert *v2_other;
133
134         BLI_assert(BM_vert_in_edge(e, e_l->v));
135
136         /* method for calculating distance:
137          *
138          * for each edge: calculate face center, then made a vector
139          * from edge midpoint to face center.  offset edge midpoint
140          * by a small amount along this vector. */
141
142         /* rather then the face center, get the middle of
143          * both edge verts connected to this one */
144         v1_other = BM_face_other_vert_loop(e_l->f, e->v2, e->v1)->v;
145         v2_other = BM_face_other_vert_loop(e_l->f, e->v1, e->v2)->v;
146         mid_v3_v3v3(cent, v1_other->co, v2_other->co);
147         mid_v3_v3v3(mid, e->v1->co, e->v2->co);
148
149         ED_view3d_project_float_v2_m4(ar, cent, cent, projectMat);
150         ED_view3d_project_float_v2_m4(ar, mid, mid, projectMat);
151
152         ED_view3d_project_float_v2_m4(ar, e->v1->co, e_v1_co, projectMat);
153         ED_view3d_project_float_v2_m4(ar, e->v2->co, e_v2_co, projectMat);
154
155         sub_v2_v2v2(vec, cent, mid);
156         normalize_v2_length(vec, 0.01f);
157
158         /* rather then adding to both verts, subtract from the mouse */
159         sub_v2_v2v2(fmval_tweak, fmval, vec);
160
161         score = len_v2v2(e_v1_co, e_v2_co);
162
163         if (dist_squared_to_line_segment_v2(fmval_tweak, e_v1_co, e_v2_co) >
164             dist_squared_to_line_segment_v2(fmval,       e_v1_co, e_v2_co))
165         {
166                 return score;
167         }
168         else {
169                 return -score;
170         }
171 }
172
173
174 /* - Advanced selection handling 'ripsel' functions ----- */
175
176 /**
177  * How rip selection works
178  *
179  * Firstly - rip is basically edge split with side-selection & grab.
180  * Things would be much more simple if we didn't have to worry about side selection
181  *
182  * The method used for checking the side of selection is as follows...
183  * - First tag all rip-able edges.
184  * - Build a contiguous edge list by looping over tagged edges and following each ones tagged siblings in both
185  *   directions.
186  *   - The loops are not stored in an array, Instead both loops on either side of each edge has its index values set
187  *     to count down from the last edge, this way, once we have the 'last' edge its very easy to walk down the
188  *     connected edge loops.
189  *     The reason for using loops like this is because when the edges are split we don't which face user gets the newly
190  *     created edge (its as good as random so we cant assume new edges will be on once side).
191  *     After splitting, its very simple to walk along boundary loops since each only has one edge from a single side.
192  * - The end loop pairs are stored in an array however to support multiple edge-selection-islands, so you can rip
193  *   multiple selections at once.
194  * - * Execute the split *
195  * - For each #EdgeLoopPair walk down both sides of the split using the loops and measure which is facing the mouse.
196  * - Deselect the edge loop facing away.
197  *
198  * Limitation!
199  * This currently works very poorly with intersecting edge islands (verts with more than 2 tagged edges)
200  * This is nice to but for now not essential.
201  *
202  * - campbell.
203  */
204
205
206 #define IS_VISIT_POSSIBLE(e)   (BM_edge_is_manifold(e) && BM_elem_flag_test(e, BM_ELEM_TAG))
207 #define IS_VISIT_DONE(e) ((e)->l && (BM_elem_index_get((e)->l) != INVALID_UID))
208 #define INVALID_UID INT_MIN
209
210 /* mark, assign uid and step */
211 static BMEdge *edbm_ripsel_edge_mark_step(BMVert *v, const int uid)
212 {
213         BMIter iter;
214         BMEdge *e;
215         BM_ITER_ELEM (e, &iter, v, BM_EDGES_OF_VERT) {
216                 if (IS_VISIT_POSSIBLE(e) && !IS_VISIT_DONE(e)) {
217                         BMLoop *l_a, *l_b;
218
219                         BM_edge_loop_pair(e, &l_a, &l_b); /* no need to check, we know this will be true */
220
221                         /* so (IS_VISIT_DONE == true) */
222                         BM_elem_index_set(l_a, uid);  /* set_dirty */
223                         BM_elem_index_set(l_b, uid);  /* set_dirty */
224
225                         return e;
226                 }
227         }
228         return NULL;
229 }
230
231 typedef struct EdgeLoopPair {
232         BMLoop *l_a;
233         BMLoop *l_b;
234 } EdgeLoopPair;
235
236 static EdgeLoopPair *edbm_ripsel_looptag_helper(BMesh *bm)
237 {
238         BMIter fiter;
239         BMIter liter;
240
241         BMFace *f;
242         BMLoop *l;
243
244         int uid_start;
245         int uid_end;
246         int uid = bm->totedge; /* can start anywhere */
247
248         EdgeLoopPair *eloop_pairs = NULL;
249         BLI_array_declare(eloop_pairs);
250         EdgeLoopPair *lp;
251
252         /* initialize loops with dummy invalid index values */
253         BM_ITER_MESH (f, &fiter, bm, BM_FACES_OF_MESH) {
254                 BM_ITER_ELEM (l, &liter, f, BM_LOOPS_OF_FACE) {
255                         BM_elem_index_set(l, INVALID_UID);  /* set_dirty */
256                 }
257         }
258         bm->elem_index_dirty |= BM_LOOP;
259
260         /* set contiguous loops ordered 'uid' values for walking after split */
261         while (true) {
262                 int tot = 0;
263                 BMIter eiter;
264                 BMEdge *e_step;
265                 BMVert *v_step;
266                 BMEdge *e;
267                 BMEdge *e_first;
268                 BMEdge *e_last;
269
270                 e_first = NULL;
271                 BM_ITER_MESH (e, &eiter, bm, BM_EDGES_OF_MESH) {
272                         if (IS_VISIT_POSSIBLE(e) && !IS_VISIT_DONE(e)) {
273                                 e_first = e;
274                                 break;
275                         }
276                 }
277
278                 if (e_first == NULL) {
279                         break;
280                 }
281
282                 /* initialize  */
283                 e_first = e;
284                 v_step = e_first->v1;
285                 e_step = NULL; /* quiet warning, will never remain this value */
286
287                 uid_start = uid;
288                 while ((e = edbm_ripsel_edge_mark_step(v_step, uid))) {
289                         v_step = BM_edge_other_vert((e_step = e), v_step);
290                         uid++; /* only different line */
291                         tot++;
292                 }
293
294                 /* this edges loops have the highest uid's, store this to walk down later */
295                 e_last = e_step;
296
297                 /* always store the highest 'uid' edge for the stride */
298                 uid_end = uid - 1;
299                 uid = uid_start - 1;
300
301                 /* initialize */
302                 v_step = e_first->v1;
303
304                 while ((e = edbm_ripsel_edge_mark_step(v_step, uid))) {
305                         v_step = BM_edge_other_vert((e_step = e), v_step);
306                         uid--; /* only different line */
307                         tot++;
308                 }
309
310                 /* stride far enough not to _ever_ overlap range */
311                 uid_start = uid;
312                 uid = uid_end + bm->totedge;
313
314                 lp = BLI_array_append_ret(eloop_pairs);
315                 /* no need to check, we know this will be true */
316                 BM_edge_loop_pair(e_last, &lp->l_a, &lp->l_b);
317
318
319                 BLI_assert(tot == uid_end - uid_start);
320
321 #if 0
322                 printf("%s: found contiguous edge loop of (%d)\n", __func__, uid_end - uid_start);
323 #endif
324
325         }
326
327         /* null terminate */
328         lp = BLI_array_append_ret(eloop_pairs);
329         lp->l_a = lp->l_b = NULL;
330
331         return eloop_pairs;
332 }
333
334
335 /* - De-Select the worst rip-edge side -------------------------------- */
336
337
338 static BMEdge *edbm_ripsel_edge_uid_step(BMEdge *e_orig, BMVert **v_prev)
339 {
340         BMIter eiter;
341         BMEdge *e;
342         BMVert *v = BM_edge_other_vert(e_orig, *v_prev);
343         const int uid_cmp = BM_elem_index_get(e_orig->l) - 1;
344
345         BM_ITER_ELEM (e, &eiter, v, BM_EDGES_OF_VERT) {
346                 if (BM_elem_index_get(e->l) == uid_cmp) {
347                         *v_prev = v;
348                         return e;
349                 }
350         }
351         return NULL;
352 }
353
354 static BMVert *edbm_ripsel_edloop_pair_start_vert(BMEdge *e)
355 {
356         /* try step in a direction, if it fails we know do go the other way */
357         BMVert *v_test = e->v1;
358         return (edbm_ripsel_edge_uid_step(e, &v_test)) ? e->v1 : e->v2;
359 }
360
361 static void edbm_ripsel_deselect_helper(BMesh *bm, EdgeLoopPair *eloop_pairs,
362                                         ARegion *ar, float projectMat[4][4], float fmval[2])
363 {
364         EdgeLoopPair *lp;
365
366         for (lp = eloop_pairs; lp->l_a; lp++) {
367                 BMEdge *e;
368                 BMVert *v_prev;
369
370                 float score_a = 0.0f;
371                 float score_b = 0.0f;
372
373                 e = lp->l_a->e;
374                 v_prev = edbm_ripsel_edloop_pair_start_vert(e);
375                 for (; e; e = edbm_ripsel_edge_uid_step(e, &v_prev)) {
376                         score_a += edbm_rip_edge_side_measure(e, e->l, ar, projectMat, fmval);
377                 }
378                 e = lp->l_b->e;
379                 v_prev = edbm_ripsel_edloop_pair_start_vert(e);
380                 for (; e; e = edbm_ripsel_edge_uid_step(e, &v_prev)) {
381                         score_b += edbm_rip_edge_side_measure(e, e->l, ar, projectMat, fmval);
382                 }
383
384                 e = (score_a > score_b) ? lp->l_a->e : lp->l_b->e;
385                 v_prev = edbm_ripsel_edloop_pair_start_vert(e);
386                 for (; e; e = edbm_ripsel_edge_uid_step(e, &v_prev)) {
387                         BM_edge_select_set(bm, e, false);
388                 }
389         }
390 }
391 /* --- end 'ripsel' selection handling code --- */
392
393
394 /* --- face-fill code --- */
395 /**
396  * return an un-ordered array of loop pairs
397  * use for rebuilding face-fill
398  *
399  * \note the method currently used fails for edges with 3+ face users and gives
400  *       nasty holes in the mesh, there isnt a good way of knowing ahead of time
401  *       which loops will be split apart (its possible to figure out but quite involved).
402  *       So for now this is a known limitation of current rip-fill option.
403  */
404
405 typedef struct UnorderedLoopPair {
406         BMLoop *l_pair[2];
407         char    flag;
408 } UnorderedLoopPair;
409 enum {
410         ULP_FLIP_0 = (1 << 0),
411         ULP_FLIP_1 = (1 << 1)
412 };
413
414 static UnorderedLoopPair *edbm_tagged_loop_pairs_to_fill(BMesh *bm)
415 {
416         BMIter iter;
417         BMEdge *e;
418
419         unsigned int total_tag = 0;
420         /* count tags, could be pre-calculated */
421         BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
422                 if (BM_elem_flag_test(e, BM_ELEM_TAG)) {
423                         total_tag++;
424                 }
425         }
426
427         if (total_tag) {
428                 UnorderedLoopPair *uloop_pairs = MEM_mallocN(total_tag * sizeof(UnorderedLoopPair), __func__);
429                 UnorderedLoopPair *ulp = uloop_pairs;
430
431                 BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
432                         if (BM_elem_flag_test(e, BM_ELEM_TAG)) {
433                                 BMLoop *l1, *l2;
434                                 if (BM_edge_loop_pair(e, &l1, &l2)) {
435                                         BMVert *v_cmp = l1->e->v1;
436                                         ulp->flag = (((l1->v != v_cmp) ? ULP_FLIP_0 : 0) |
437                                                      ((l2->v == v_cmp) ? ULP_FLIP_1 : 0));
438                                 }
439                                 else {
440                                         ulp->flag = 0;
441                                 }
442                                 ulp->l_pair[0] = l1;
443                                 ulp->l_pair[1] = l2;
444
445                                 ulp++;
446                         }
447                 }
448
449                 return uloop_pairs;
450         }
451         else {
452                 return NULL;
453         }
454 }
455
456 static void edbm_tagged_loop_pairs_do_fill_faces(BMesh *bm, UnorderedLoopPair *uloop_pairs)
457 {
458         UnorderedLoopPair *ulp;
459         unsigned int total_tag = MEM_allocN_len(uloop_pairs) / sizeof(UnorderedLoopPair);
460         unsigned int i;
461
462         for (i = 0, ulp = uloop_pairs; i < total_tag; i++, ulp++) {
463                 if ((ulp->l_pair[0]    && ulp->l_pair[1]) &&
464                     (ulp->l_pair[0]->e != ulp->l_pair[1]->e))
465                 {
466                         /* time has come to make a face! */
467                         BMVert *v_shared = BM_edge_share_vert(ulp->l_pair[0]->e, ulp->l_pair[1]->e);
468                         BMFace *f, *f_example = ulp->l_pair[0]->f;
469                         BMLoop *l_iter;
470                         BMVert *f_verts[4];
471
472                         if (v_shared == NULL) {
473                                 /* quad */
474                                 f_verts[0] = ulp->l_pair[0]->e->v1;
475                                 f_verts[1] = ulp->l_pair[1]->e->v1;
476                                 f_verts[2] = ulp->l_pair[1]->e->v2;
477                                 f_verts[3] = ulp->l_pair[0]->e->v2;
478
479                                 if (ulp->flag & ULP_FLIP_0) {
480                                         SWAP(BMVert *, f_verts[0], f_verts[3]);
481                                 }
482                                 if (ulp->flag & ULP_FLIP_1) {
483                                         SWAP(BMVert *, f_verts[1], f_verts[2]);
484                                 }
485                         }
486                         else {
487                                 /* tri */
488                                 f_verts[0] = v_shared;
489                                 f_verts[1] = BM_edge_other_vert(ulp->l_pair[0]->e, v_shared);
490                                 f_verts[2] = BM_edge_other_vert(ulp->l_pair[1]->e, v_shared);
491                                 f_verts[3] = NULL;
492
493                                 /* don't use the flip flags */
494                                 if (v_shared == ulp->l_pair[0]->v) {
495                                         SWAP(BMVert *, f_verts[0], f_verts[1]);
496                                 }
497                         }
498
499                         /* face should never exist */
500                         BLI_assert(!BM_face_exists(f_verts, f_verts[3] ? 4 : 3));
501
502                         f = BM_face_create_verts(bm, f_verts, f_verts[3] ? 4 : 3, f_example, BM_CREATE_NOP, true);
503
504                         l_iter = BM_FACE_FIRST_LOOP(f);
505
506                         if (f_verts[3]) {
507                                 BM_elem_attrs_copy(bm, bm, BM_edge_other_loop(ulp->l_pair[0]->e, l_iter), l_iter); l_iter = l_iter->next;
508                                 BM_elem_attrs_copy(bm, bm, BM_edge_other_loop(ulp->l_pair[1]->e, l_iter), l_iter); l_iter = l_iter->next;
509                                 BM_elem_attrs_copy(bm, bm, BM_edge_other_loop(ulp->l_pair[1]->e, l_iter), l_iter); l_iter = l_iter->next;
510                                 BM_elem_attrs_copy(bm, bm, BM_edge_other_loop(ulp->l_pair[0]->e, l_iter), l_iter);
511                         }
512                         else {
513                                 BM_elem_attrs_copy(bm, bm, BM_edge_other_loop(ulp->l_pair[0]->e, l_iter), l_iter); l_iter = l_iter->next;
514                                 BM_elem_attrs_copy(bm, bm, BM_edge_other_loop(ulp->l_pair[0]->e, l_iter), l_iter); l_iter = l_iter->next;
515                                 BM_elem_attrs_copy(bm, bm, BM_edge_other_loop(ulp->l_pair[1]->e, l_iter), l_iter);
516                         }
517
518                 }
519         }
520 }
521
522 /* --- end 'face-fill' code --- */
523
524 /**
525  * This is the main vert ripping function (rip when one vertex is selected)
526  */
527 static int edbm_rip_invoke__vert(bContext *C, wmOperator *op, const wmEvent *event)
528 {
529         const bool do_fill = RNA_boolean_get(op->ptr, "use_fill");
530         UnorderedLoopPair *fill_uloop_pairs = NULL;
531         Object *obedit = CTX_data_edit_object(C);
532         ARegion *ar = CTX_wm_region(C);
533         RegionView3D *rv3d = CTX_wm_region_view3d(C);
534         BMEditMesh *em = BKE_editmesh_from_object(obedit);
535         BMesh *bm = em->bm;
536         BMIter iter, liter;
537         BMLoop *l;
538         BMEdge *e_best;
539         BMVert *v;
540         const int totvert_orig = bm->totvert;
541         int i;
542         float projectMat[4][4], fmval[3] = {event->mval[0], event->mval[1]};
543         float dist_sq = FLT_MAX;
544         float d;
545         bool is_wire, is_manifold_region;
546
547         BMEditSelection ese;
548         int totboundary_edge = 0;
549
550         ED_view3d_ob_project_mat_get(rv3d, obedit, projectMat);
551
552         /* find selected vert - same some time and check history first */
553         if (BM_select_history_active_get(bm, &ese) && ese.htype == BM_VERT) {
554                 v = (BMVert *)ese.ele;
555         }
556         else {
557                 ese.ele = NULL;
558
559                 BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) {
560                         if (BM_elem_flag_test(v, BM_ELEM_SELECT))
561                                 break;
562                 }
563         }
564
565         /* (v == NULL) should be impossible */
566         if ((v == NULL) || (v->e == NULL)) {
567                 return OPERATOR_CANCELLED;
568         }
569
570         is_wire = BM_vert_is_wire(v);
571         is_manifold_region = BM_vert_is_manifold_region(v);
572
573         e_best = NULL;
574
575         {
576                 BMEdge *e;
577                 /* find closest edge to mouse cursor */
578                 BM_ITER_ELEM (e, &iter, v, BM_EDGES_OF_VERT) {
579                         /* consider wire as boundary for this purpose,
580                          * otherwise we can't a face away from a wire edge */
581                         totboundary_edge += (BM_edge_is_boundary(e) || BM_edge_is_wire(e));
582                         if (!BM_elem_flag_test(e, BM_ELEM_HIDDEN)) {
583                                 if ((is_manifold_region == false) || BM_edge_is_manifold(e)) {
584                                         d = edbm_rip_edgedist_squared(ar, projectMat, e->v1->co, e->v2->co, fmval, INSET_DEFAULT);
585                                         if ((e_best == NULL) || (d < dist_sq)) {
586                                                 dist_sq = d;
587                                                 e_best = e;
588                                         }
589                                 }
590                         }
591                 }
592         }
593
594         if (e_best && e_best->l && (is_manifold_region == false)) {
595                 /* Try to split off a non-manifold fan (when we have multiple disconnected fans) */
596                 BMLoop *l_sep = e_best->l->v == v ? e_best->l : e_best->l->next;
597                 BMVert *v_new;
598
599                 BLI_assert(l_sep->v == v);
600                 v_new = BM_face_loop_separate_multi_isolated(bm, l_sep);
601                 BLI_assert(BM_vert_find_first_loop(v));
602
603                 BM_vert_select_set(bm, v, false);
604                 BM_select_history_remove(bm, v);
605
606                 BM_vert_select_set(bm, v_new, true);
607                 if (ese.ele) {
608                         BM_select_history_store(bm, v_new);
609                 }
610
611                 if (do_fill) {
612                         BM_edge_create(bm, v, v_new, NULL, BM_CREATE_NOP);
613                 }
614
615                 return OPERATOR_FINISHED;
616         }
617
618         /* if we are ripping a single vertex from 3 faces,
619          * then measure the distance to the face corner as well as the edge */
620         if (BM_vert_face_count_is_equal(v, 3) &&
621             BM_vert_edge_count_is_equal(v, 3))
622         {
623                 BMEdge *e_all[3];
624                 BMLoop *l_all[3];
625                 int i1, i2;
626
627                 BM_iter_as_array(bm, BM_EDGES_OF_VERT, v, (void **)e_all, 3);
628                 BM_iter_as_array(bm, BM_LOOPS_OF_VERT, v, (void **)l_all, 3);
629
630                 /* not do a loop similar to the one above, but test against loops */
631                 for (i1 = 0; i1 < 3; i1++) {
632                         /* consider wire as boundary for this purpose,
633                          * otherwise we can't a face away from a wire edge */
634                         float l_mid_co[3];
635                         l = l_all[i1];
636                         edbm_calc_loop_co(l, l_mid_co);
637                         d = edbm_rip_edgedist_squared(ar, projectMat, l->v->co, l_mid_co, fmval, INSET_DEFAULT);
638                         if ((e_best == NULL) || (d < dist_sq)) {
639                                 dist_sq = d;
640
641                                 /* find the edge that is not in this loop */
642                                 e_best = NULL;
643                                 for (i2 = 0; i2 < 3; i2++) {
644                                         if (!BM_edge_in_loop(e_all[i2], l)) {
645                                                 e_best = e_all[i2];
646                                                 break;
647                                         }
648                                 }
649                                 BLI_assert(e_best != NULL);
650                         }
651                 }
652         }
653
654         /* should we go ahead with edge rip or do we need to do special case, split off vertex?:
655          * split off vertex if...
656          * - we cant find an edge - this means we are ripping a faces vert that is connected to other
657          *   geometry only at the vertex.
658          * - the boundary edge total is greater than 2,
659          *   in this case edge split _can_ work but we get far nicer results if we use this special case.
660          * - there are only 2 edges but we are a wire vert. */
661         if ((is_wire == false && totboundary_edge > 2) ||
662             (is_wire == true  && totboundary_edge > 1))
663         {
664                 BMVert **vout;
665                 int vout_len;
666
667                 BM_vert_select_set(bm, v, false);
668
669                 bmesh_kernel_vert_separate(bm, v, &vout, &vout_len, true);
670
671                 if (vout_len < 2) {
672                         MEM_freeN(vout);
673                         /* set selection back to avoid active-unselected vertex */
674                         BM_vert_select_set(bm, v, true);
675                         /* should never happen */
676                         BKE_report(op->reports, RPT_ERROR, "Error ripping vertex from faces");
677                         return OPERATOR_CANCELLED;
678                 }
679                 else {
680                         int vi_best = 0;
681
682                         if (ese.ele) {
683                                 BM_select_history_remove(bm, ese.ele);
684                         }
685
686                         dist_sq = FLT_MAX;
687
688                         /* in the loop below we find the best vertex to drag based on its connected geometry,
689                          * either by its face corner, or connected edge (when no faces are attached) */
690                         for (i = 0; i < vout_len; i++) {
691
692                                 if (BM_vert_is_wire(vout[i]) == false) {
693                                         /* find the best face corner */
694                                         BM_ITER_ELEM (l, &iter, vout[i], BM_LOOPS_OF_VERT) {
695                                                 if (!BM_elem_flag_test(l->f, BM_ELEM_HIDDEN)) {
696                                                         float l_mid_co[3];
697
698                                                         edbm_calc_loop_co(l, l_mid_co);
699                                                         d = edbm_rip_edgedist_squared(ar, projectMat, v->co, l_mid_co, fmval, INSET_DEFAULT);
700
701                                                         if (d < dist_sq) {
702                                                                 dist_sq = d;
703                                                                 vi_best = i;
704                                                         }
705                                                 }
706                                         }
707                                 }
708                                 else {
709                                         BMEdge *e;
710                                         /* a wire vert, find the best edge */
711                                         BM_ITER_ELEM (e, &iter, vout[i], BM_EDGES_OF_VERT) {
712                                                 if (!BM_elem_flag_test(e, BM_ELEM_HIDDEN)) {
713                                                         float e_mid_co[3];
714
715                                                         mid_v3_v3v3(e_mid_co, e->v1->co, e->v2->co);
716                                                         d = edbm_rip_edgedist_squared(ar, projectMat, v->co, e_mid_co, fmval, INSET_DEFAULT);
717
718                                                         if (d < dist_sq) {
719                                                                 dist_sq = d;
720                                                                 vi_best = i;
721                                                         }
722                                                 }
723                                         }
724                                 }
725                         }
726
727                         /* vout[0]  == best
728                          * vout[1]  == glue
729                          * vout[2+] == splice with glue (when vout_len > 2)
730                          */
731                         if (vi_best != 0) {
732                                 SWAP(BMVert *, vout[0], vout[vi_best]);
733                                 vi_best = 0;
734                         }
735
736                         /* select the vert from the best region */
737                         v = vout[vi_best];
738                         BM_vert_select_set(bm, v, true);
739
740                         if (ese.ele) {
741                                 BM_select_history_store(bm, v);
742                         }
743
744                         /* splice all others back together */
745                         if (vout_len > 2) {
746                                 for (i = 2; i < vout_len; i++) {
747                                         BM_vert_splice(bm, vout[1], vout[i]);
748                                 }
749                         }
750
751                         if (do_fill) {
752                                 /* match extrude vert-order */
753                                 BM_edge_create(bm, vout[1], vout[0], NULL, BM_CREATE_NOP);
754                         }
755
756                         MEM_freeN(vout);
757
758                         return OPERATOR_FINISHED;
759                 }
760         }
761
762         if (!e_best) {
763                 BKE_report(op->reports, RPT_ERROR, "Selected vertex has no edge/face pairs attached");
764                 return OPERATOR_CANCELLED;
765         }
766
767         /* *** Execute the split! *** */
768         /* unlike edge split, for single vertex split we only use the operator in one of the cases
769          * but both allocate fill */
770
771         {
772                 BMVert *v_rip;
773                 BMLoop *larr[2];
774                 int larr_len = 0;
775
776                 /* rip two adjacent edges */
777                 if (BM_edge_is_boundary(e_best) || BM_vert_face_count_is_equal(v, 2)) {
778                         /* Don't run the edge split operator in this case */
779
780                         l = BM_edge_vert_share_loop(e_best->l, v);
781                         larr[larr_len] = l;
782                         larr_len++;
783
784                         /* only tag for face-fill (we don't call the operator) */
785                         if (BM_edge_is_boundary(e_best)) {
786                                 BM_elem_flag_enable(e_best, BM_ELEM_TAG);
787                         }
788                         else {
789                                 BM_elem_flag_enable(l->e, BM_ELEM_TAG);
790                                 BM_elem_flag_enable(l->prev->e, BM_ELEM_TAG);
791                         }
792                 }
793                 else {
794                         if (BM_edge_is_manifold(e_best)) {
795                                 BMLoop *l_iter, *l_first;
796                                 l_iter = l_first = e_best->l;
797                                 do {
798                                         larr[larr_len] = BM_edge_vert_share_loop(l_iter, v);
799
800                                         if (do_fill) {
801                                                 /* Only needed when filling...
802                                                  * Also, we never want to tag best edge,
803                                                  * that one won't change during split. See T44618. */
804                                                 if (larr[larr_len]->e == e_best) {
805                                                         BM_elem_flag_enable(larr[larr_len]->prev->e, BM_ELEM_TAG);
806                                                 }
807                                                 else {
808                                                         BM_elem_flag_enable(larr[larr_len]->e, BM_ELEM_TAG);
809                                                 }
810                                         }
811                                         larr_len++;
812                                 } while ((l_iter = l_iter->radial_next) != l_first);
813                         }
814                         else {
815                                 /* looks like there are no split edges, we could just return/report-error? - Campbell */
816                         }
817                 }
818
819                 /* keep directly before edgesplit */
820                 if (do_fill) {
821                         fill_uloop_pairs = edbm_tagged_loop_pairs_to_fill(bm);
822                 }
823
824                 if (larr_len) {
825                         v_rip = BM_face_loop_separate_multi(bm, larr, larr_len);
826                 }
827                 else {
828                         v_rip = NULL;
829                 }
830
831                 if (v_rip) {
832                         BM_vert_select_set(bm, v_rip, true);
833                 }
834                 else {
835                         if (fill_uloop_pairs) MEM_freeN(fill_uloop_pairs);
836                         return OPERATOR_CANCELLED;
837                 }
838         }
839
840         {
841                 /* --- select which vert --- */
842                 BMVert *v_best = NULL;
843                 float l_corner_co[3];
844
845                 dist_sq = FLT_MAX;
846                 BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) {
847                         if (BM_elem_flag_test(v, BM_ELEM_SELECT)) {
848                                 /* disable by default, re-enable winner at end */
849                                 BM_vert_select_set(bm, v, false);
850                                 BM_select_history_remove(bm, v);
851
852                                 BM_ITER_ELEM (l, &liter, v, BM_LOOPS_OF_VERT) {
853
854                                         /* check if v_best is null in the _rare_ case there are numeric issues */
855                                         edbm_calc_loop_co(l, l_corner_co);
856                                         d = edbm_rip_edgedist_squared(ar, projectMat, l->v->co, l_corner_co, fmval, INSET_DEFAULT);
857                                         if ((v_best == NULL) || (d < dist_sq)) {
858                                                 v_best = v;
859                                                 dist_sq = d;
860                                         }
861                                 }
862                         }
863                 }
864
865                 if (v_best) {
866                         BM_vert_select_set(bm, v_best, true);
867                         if (ese.ele) {
868                                 BM_select_history_store(bm, v_best);
869                         }
870                 }
871         }
872
873         if (do_fill && fill_uloop_pairs) {
874                 edbm_tagged_loop_pairs_do_fill_faces(bm, fill_uloop_pairs);
875                 MEM_freeN(fill_uloop_pairs);
876         }
877
878
879         if (totvert_orig == bm->totvert) {
880                 BKE_report(op->reports, RPT_ERROR, "No vertices could be ripped");
881                 return OPERATOR_CANCELLED;
882         }
883
884         return OPERATOR_FINISHED;
885 }
886
887 /**
888  * This is the main edge ripping function
889  */
890 static int edbm_rip_invoke__edge(bContext *C, wmOperator *op, const wmEvent *event)
891 {
892         const bool do_fill = RNA_boolean_get(op->ptr, "use_fill");
893         UnorderedLoopPair *fill_uloop_pairs = NULL;
894         Object *obedit = CTX_data_edit_object(C);
895         ARegion *ar = CTX_wm_region(C);
896         RegionView3D *rv3d = CTX_wm_region_view3d(C);
897         BMEditMesh *em = BKE_editmesh_from_object(obedit);
898         BMesh *bm = em->bm;
899         BMIter iter, eiter;
900         BMLoop *l;
901         BMEdge *e_best;
902         BMVert *v;
903         const int totedge_orig = bm->totedge;
904         float projectMat[4][4], fmval[3] = {event->mval[0], event->mval[1]};
905
906         EdgeLoopPair *eloop_pairs;
907
908         ED_view3d_ob_project_mat_get(rv3d, obedit, projectMat);
909
910         /* important this runs on the original selection, before tampering with tagging */
911         eloop_pairs = edbm_ripsel_looptag_helper(bm);
912
913         /* expand edge selection */
914         BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) {
915                 BMEdge *e;
916                 bool all_manifold;
917                 int totedge_manifold;  /* manifold, visible edges */
918                 int i;
919
920                 e_best = NULL;
921                 i = 0;
922                 totedge_manifold = 0;
923                 all_manifold = true;
924                 BM_ITER_ELEM (e, &eiter, v, BM_EDGES_OF_VERT) {
925
926                         if (!BM_edge_is_wire(e) &&
927                             !BM_elem_flag_test(e, BM_ELEM_HIDDEN))
928                         {
929                                 /* important to check selection rather then tag here
930                                  * else we get feedback loop */
931                                 if (BM_elem_flag_test(e, BM_ELEM_SELECT)) {
932                                         e_best = e;
933                                         i++;
934                                 }
935                                 totedge_manifold++;
936                         }
937
938                         /** #BM_vert_other_disk_edge has no hidden checks so don't check hidden here */
939                         if ((all_manifold == true) && (BM_edge_is_manifold(e) == false)) {
940                                 all_manifold = false;
941                         }
942                 }
943
944                 /* single edge, extend */
945                 if (i == 1 && e_best->l) {
946                         /* note: if the case of 3 edges has one change in loop stepping,
947                          * if this becomes more involved we may be better off splitting
948                          * the 3 edge case into its own else-if branch */
949                         if ((totedge_manifold == 4 || totedge_manifold == 3) || (all_manifold == false)) {
950                                 BMLoop *l_a = e_best->l;
951                                 BMLoop *l_b = l_a->radial_next;
952
953                                 /* find the best face to follow, this way the edge won't point away from
954                                  * the mouse when there are more than 4 (takes the shortest face fan around) */
955                                 l = (edbm_rip_edge_side_measure(e_best, l_a, ar, projectMat, fmval) <
956                                      edbm_rip_edge_side_measure(e_best, l_b, ar, projectMat, fmval)) ? l_a : l_b;
957
958                                 l = BM_loop_other_edge_loop(l, v);
959                                 /* important edge is manifold else we can be attempting to split off a fan that don't budge,
960                                  * not crashing but adds duplicate edge. */
961                                 if (BM_edge_is_manifold(l->e)) {
962                                         l = l->radial_next;
963
964                                         if (totedge_manifold != 3)
965                                                 l = BM_loop_other_edge_loop(l, v);
966
967                                         if (l) {
968                                                 BLI_assert(!BM_elem_flag_test(l->e, BM_ELEM_TAG));
969                                                 BM_elem_flag_enable(l->e, BM_ELEM_TAG);
970                                         }
971                                 }
972                         }
973                         else {
974                                 e = BM_vert_other_disk_edge(v, e_best);
975
976                                 if (e) {
977                                         BLI_assert(!BM_elem_flag_test(e, BM_ELEM_TAG));
978                                         BM_elem_flag_enable(e, BM_ELEM_TAG);
979                                 }
980                         }
981                 }
982         }
983
984         /* keep directly before edgesplit */
985         if (do_fill) {
986                 fill_uloop_pairs = edbm_tagged_loop_pairs_to_fill(bm);
987         }
988
989         BM_mesh_edgesplit(em->bm, true, true, true);
990
991         /* note: the output of the bmesh operator is ignored, since we built
992          * the contiguous loop pairs to split already, its possible that some
993          * edge did not split even though it was tagged which would not work
994          * as expected (but not crash), however there are checks to ensure
995          * tagged edges will split. So far its not been an issue. */
996         edbm_ripsel_deselect_helper(bm, eloop_pairs,
997                                     ar, projectMat, fmval);
998         MEM_freeN(eloop_pairs);
999
1000         /* deselect loose verts */
1001         BM_mesh_select_mode_clean_ex(bm, SCE_SELECT_EDGE);
1002
1003         if (do_fill && fill_uloop_pairs) {
1004                 edbm_tagged_loop_pairs_do_fill_faces(bm, fill_uloop_pairs);
1005                 MEM_freeN(fill_uloop_pairs);
1006         }
1007
1008         if (totedge_orig == bm->totedge) {
1009                 BKE_report(op->reports, RPT_ERROR, "No edges could be ripped");
1010                 return OPERATOR_CANCELLED;
1011         }
1012
1013         BM_select_history_validate(bm);
1014
1015         return OPERATOR_FINISHED;
1016 }
1017
1018 /* based on mouse cursor position, it defines how is being ripped */
1019 static int edbm_rip_invoke(bContext *C, wmOperator *op, const wmEvent *event)
1020 {
1021         Object *obedit = CTX_data_edit_object(C);
1022         BMEditMesh *em = BKE_editmesh_from_object(obedit);
1023         BMesh *bm = em->bm;
1024         BMIter iter;
1025         BMEdge *e;
1026         const bool singlesel = (bm->totvertsel == 1 && bm->totedgesel == 0 && bm->totfacesel == 0);
1027         int ret;
1028
1029         /* running in face mode hardly makes sense, so convert to region loop and rip */
1030         if (bm->totfacesel) {
1031                 /* highly nifty but hard to support since the operator can fail and we're left
1032                  * with modified selection */
1033                 // WM_operator_name_call(C, "MESH_OT_region_to_loop", WM_OP_INVOKE_DEFAULT, NULL);
1034
1035                 BKE_report(op->reports, RPT_ERROR, "Cannot rip selected faces");
1036                 return OPERATOR_CANCELLED;
1037         }
1038
1039         /* we could support this, but not for now */
1040         if ((bm->totvertsel > 1) && (bm->totedgesel == 0)) {
1041                 BKE_report(op->reports, RPT_ERROR, "Cannot rip multiple disconnected vertices");
1042                 return OPERATOR_CANCELLED;
1043         }
1044
1045         /* note on selection:
1046          * When calling edge split we operate on tagged edges rather then selected
1047          * this is important because the edges to operate on are extended by one,
1048          * but the selection is left alone.
1049          *
1050          * After calling edge split - the duplicated edges have the same selection state as the
1051          * original, so all we do is de-select the far side from the mouse and we have a
1052          * useful selection for grabbing.
1053          */
1054
1055         /* BM_ELEM_SELECT --> BM_ELEM_TAG */
1056         BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
1057                 BM_elem_flag_set(e, BM_ELEM_TAG, BM_elem_flag_test(e, BM_ELEM_SELECT));
1058         }
1059
1060         /* split 2 main parts of this operator out into vertex and edge ripping */
1061         if (singlesel) {
1062                 ret = edbm_rip_invoke__vert(C, op, event);
1063         }
1064         else {
1065                 ret = edbm_rip_invoke__edge(C, op, event);
1066         }
1067
1068         if (ret == OPERATOR_CANCELLED) {
1069                 return OPERATOR_CANCELLED;
1070         }
1071
1072         BLI_assert(singlesel ? (bm->totvertsel > 0) : (bm->totedgesel > 0));
1073
1074         if (bm->totvertsel == 0) {
1075                 return OPERATOR_CANCELLED;
1076         }
1077
1078         EDBM_update_generic(em, true, true);
1079
1080         return OPERATOR_FINISHED;
1081 }
1082
1083
1084 void MESH_OT_rip(wmOperatorType *ot)
1085 {
1086         /* identifiers */
1087         ot->name = "Rip";
1088         ot->idname = "MESH_OT_rip";
1089         ot->description = "Disconnect vertex or edges from connected geometry";
1090
1091         /* api callbacks */
1092         ot->invoke = edbm_rip_invoke;
1093         ot->poll = EDBM_view3d_poll;
1094
1095         /* flags */
1096         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1097
1098         /* to give to transform */
1099         Transform_Properties(ot, P_PROPORTIONAL | P_MIRROR_DUMMY);
1100         RNA_def_boolean(ot->srna, "use_fill", false, "Fill", "Fill the ripped region");
1101 }