BMesh: edge-offset feature (Ctrl+Shift+R)
[blender-staging.git] / source / blender / editors / mesh / editmesh_tools.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_tools.c
29  *  \ingroup edmesh
30  */
31
32 #include <stddef.h>
33
34 #include "MEM_guardedalloc.h"
35
36 #include "DNA_key_types.h"
37 #include "DNA_material_types.h"
38 #include "DNA_mesh_types.h"
39 #include "DNA_meshdata_types.h"
40 #include "DNA_modifier_types.h"
41 #include "DNA_object_types.h"
42 #include "DNA_scene_types.h"
43
44 #include "BLI_listbase.h"
45 #include "BLI_noise.h"
46 #include "BLI_math.h"
47 #include "BLI_rand.h"
48 #include "BLI_sort_utils.h"
49
50 #include "BKE_material.h"
51 #include "BKE_context.h"
52 #include "BKE_depsgraph.h"
53 #include "BKE_report.h"
54 #include "BKE_texture.h"
55 #include "BKE_main.h"
56 #include "BKE_editmesh.h"
57
58 #include "BLF_translation.h"
59
60 #include "RNA_define.h"
61 #include "RNA_access.h"
62 #include "RNA_enum_types.h"
63
64 #include "WM_api.h"
65 #include "WM_types.h"
66
67 #include "ED_mesh.h"
68 #include "ED_object.h"
69 #include "ED_screen.h"
70 #include "ED_transform.h"
71 #include "ED_uvedit.h"
72 #include "ED_view3d.h"
73
74 #include "RE_render_ext.h"
75
76 #include "UI_interface.h"
77 #include "UI_resources.h"
78
79 #include "mesh_intern.h"  /* own include */
80
81 #define USE_FACE_CREATE_SEL_EXTEND
82
83 static int edbm_subdivide_exec(bContext *C, wmOperator *op)
84 {
85         Object *obedit = CTX_data_edit_object(C);
86         BMEditMesh *em = BKE_editmesh_from_object(obedit);
87         const int cuts = RNA_int_get(op->ptr, "number_cuts");
88         float smooth = 0.292f * RNA_float_get(op->ptr, "smoothness");
89         const float fractal = RNA_float_get(op->ptr, "fractal") / 2.5f;
90         const float along_normal = RNA_float_get(op->ptr, "fractal_along_normal");
91
92         if (RNA_boolean_get(op->ptr, "quadtri") && 
93             RNA_enum_get(op->ptr, "quadcorner") == SUBD_CORNER_STRAIGHT_CUT)
94         {
95                 RNA_enum_set(op->ptr, "quadcorner", SUBD_CORNER_INNERVERT);
96         }
97         
98         BM_mesh_esubdivide(em->bm, BM_ELEM_SELECT,
99                            smooth, SUBD_FALLOFF_INVSQUARE, false,
100                            fractal, along_normal,
101                            cuts,
102                            SUBDIV_SELECT_ORIG, RNA_enum_get(op->ptr, "quadcorner"),
103                            RNA_boolean_get(op->ptr, "quadtri"), true, false,
104                            RNA_int_get(op->ptr, "seed"));
105
106         EDBM_update_generic(em, true, true);
107
108         return OPERATOR_FINISHED;
109 }
110
111 /* Note, these values must match delete_mesh() event values */
112 static EnumPropertyItem prop_mesh_cornervert_types[] = {
113         {SUBD_CORNER_INNERVERT,     "INNERVERT", 0,      "Inner Vert", ""},
114         {SUBD_CORNER_PATH,          "PATH", 0,           "Path", ""},
115         {SUBD_CORNER_STRAIGHT_CUT,  "STRAIGHT_CUT", 0,   "Straight Cut", ""},
116         {SUBD_CORNER_FAN,           "FAN", 0,            "Fan", ""},
117         {0, NULL, 0, NULL, NULL}
118 };
119
120 void MESH_OT_subdivide(wmOperatorType *ot)
121 {
122         PropertyRNA *prop;
123
124         /* identifiers */
125         ot->name = "Subdivide";
126         ot->description = "Subdivide selected edges";
127         ot->idname = "MESH_OT_subdivide";
128
129         /* api callbacks */
130         ot->exec = edbm_subdivide_exec;
131         ot->poll = ED_operator_editmesh;
132
133         /* flags */
134         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
135
136         /* properties */
137         prop = RNA_def_int(ot->srna, "number_cuts", 1, 1, INT_MAX, "Number of Cuts", "", 1, 10);
138         /* avoid re-using last var because it can cause _very_ high poly meshes and annoy users (or worse crash) */
139         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
140
141         RNA_def_float(ot->srna, "smoothness", 0.0f, 0.0f, FLT_MAX, "Smoothness", "Smoothness factor", 0.0f, 1.0f);
142
143         RNA_def_boolean(ot->srna, "quadtri", 0, "Quad/Tri Mode", "Tries to prevent ngons");
144         RNA_def_enum(ot->srna, "quadcorner", prop_mesh_cornervert_types, SUBD_CORNER_STRAIGHT_CUT,
145                      "Quad Corner Type", "How to subdivide quad corners (anything other than Straight Cut will prevent ngons)");
146
147         RNA_def_float(ot->srna, "fractal", 0.0f, 0.0f, FLT_MAX, "Fractal", "Fractal randomness factor", 0.0f, 1000.0f);
148         RNA_def_float(ot->srna, "fractal_along_normal", 0.0f, 0.0f, 1.0f, "Along Normal", "Apply fractal displacement along normal only", 0.0f, 1.0f);
149         RNA_def_int(ot->srna, "seed", 0, 0, 10000, "Random Seed", "Seed for the random number generator", 0, 50);
150 }
151
152 /* -------------------------------------------------------------------- */
153 /* Edge Ring Subdiv
154  * (bridge code shares props)
155  */
156
157 struct EdgeRingOpSubdProps {
158         int interp_mode;
159         int cuts;
160         float smooth;
161
162         int profile_shape;
163         float profile_shape_factor;
164 };
165
166
167 static void mesh_operator_edgering_props(wmOperatorType *ot, const int cuts_default)
168 {
169         /* Note, these values must match delete_mesh() event values */
170         static EnumPropertyItem prop_subd_edgering_types[] = {
171                 {SUBD_RING_INTERP_LINEAR, "LINEAR", 0, "Linear", ""},
172                 {SUBD_RING_INTERP_PATH, "PATH", 0, "Blend Path", ""},
173                 {SUBD_RING_INTERP_SURF, "SURFACE", 0, "Blend Surface", ""},
174                 {0, NULL, 0, NULL, NULL}
175         };
176
177         PropertyRNA *prop;
178
179         prop = RNA_def_int(ot->srna, "number_cuts", cuts_default, 0, INT_MAX, "Number of Cuts", "", 0, 64);
180         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
181
182         RNA_def_enum(ot->srna, "interpolation", prop_subd_edgering_types, SUBD_RING_INTERP_PATH,
183                      "Interpolation", "Interpolation method");
184
185         RNA_def_float(ot->srna, "smoothness", 1.0f, 0.0f, FLT_MAX,
186                       "Smoothness", "Smoothness factor", 0.0f, 2.0f);
187
188         /* profile-shape */
189         RNA_def_float(ot->srna, "profile_shape_factor", 0.0f, -FLT_MAX, FLT_MAX,
190                       "Profile Factor", "", -2.0f, 2.0f);
191
192         prop = RNA_def_property(ot->srna, "profile_shape", PROP_ENUM, PROP_NONE);
193         RNA_def_property_enum_items(prop, proportional_falloff_curve_only_items);
194         RNA_def_property_enum_default(prop, PROP_SMOOTH);
195         RNA_def_property_ui_text(prop, "Profile Shape", "Shape of the profile");
196         RNA_def_property_translation_context(prop, BLF_I18NCONTEXT_ID_CURVE); /* Abusing id_curve :/ */
197 }
198
199 static void mesh_operator_edgering_props_get(wmOperator *op, struct EdgeRingOpSubdProps *op_props)
200 {
201         op_props->interp_mode = RNA_enum_get(op->ptr, "interpolation");
202         op_props->cuts = RNA_int_get(op->ptr, "number_cuts");
203         op_props->smooth = RNA_float_get(op->ptr, "smoothness");
204
205         op_props->profile_shape = RNA_enum_get(op->ptr, "profile_shape");
206         op_props->profile_shape_factor = RNA_float_get(op->ptr, "profile_shape_factor");
207 }
208
209 static int edbm_subdivide_edge_ring_exec(bContext *C, wmOperator *op)
210 {
211         Object *obedit = CTX_data_edit_object(C);
212         BMEditMesh *em = BKE_editmesh_from_object(obedit);
213         struct EdgeRingOpSubdProps op_props;
214
215         mesh_operator_edgering_props_get(op, &op_props);
216
217         if (!EDBM_op_callf(em, op,
218                            "subdivide_edgering edges=%he interp_mode=%i cuts=%i smooth=%f "
219                            "profile_shape=%i profile_shape_factor=%f",
220                            BM_ELEM_SELECT, op_props.interp_mode, op_props.cuts, op_props.smooth,
221                            op_props.profile_shape, op_props.profile_shape_factor))
222         {
223                 return OPERATOR_CANCELLED;
224         }
225
226         EDBM_update_generic(em, true, true);
227
228         return OPERATOR_FINISHED;
229 }
230
231 void MESH_OT_subdivide_edgering(wmOperatorType *ot)
232 {
233         /* identifiers */
234         ot->name = "Subdivide Edge-Ring";
235         ot->description = "";
236         ot->idname = "MESH_OT_subdivide_edgering";
237
238         /* api callbacks */
239         ot->exec = edbm_subdivide_edge_ring_exec;
240         ot->poll = ED_operator_editmesh;
241
242         /* flags */
243         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
244
245         /* properties */
246         mesh_operator_edgering_props(ot, 10);
247 }
248
249
250 static int edbm_unsubdivide_exec(bContext *C, wmOperator *op)
251 {
252         Object *obedit = CTX_data_edit_object(C);
253         BMEditMesh *em = BKE_editmesh_from_object(obedit);
254         BMOperator bmop;
255
256         const int iterations = RNA_int_get(op->ptr, "iterations");
257
258         EDBM_op_init(em, &bmop, op,
259                      "unsubdivide verts=%hv iterations=%i", BM_ELEM_SELECT, iterations);
260
261         BMO_op_exec(em->bm, &bmop);
262
263         if (!EDBM_op_finish(em, &bmop, op, true)) {
264                 return 0;
265         }
266
267         if ((em->selectmode & SCE_SELECT_VERTEX) == 0) {
268                 EDBM_selectmode_flush_ex(em, SCE_SELECT_VERTEX);  /* need to flush vert->face first */
269         }
270         EDBM_selectmode_flush(em);
271
272         EDBM_update_generic(em, true, true);
273
274         return OPERATOR_FINISHED;
275 }
276
277 void MESH_OT_unsubdivide(wmOperatorType *ot)
278 {
279         /* identifiers */
280         ot->name = "Un-Subdivide";
281         ot->description = "UnSubdivide selected edges & faces";
282         ot->idname = "MESH_OT_unsubdivide";
283
284         /* api callbacks */
285         ot->exec = edbm_unsubdivide_exec;
286         ot->poll = ED_operator_editmesh;
287
288         /* flags */
289         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
290
291         /* props */
292         RNA_def_int(ot->srna, "iterations", 2, 1, INT_MAX, "Iterations", "Number of times to unsubdivide", 1, 100);
293 }
294
295 void EMBM_project_snap_verts(bContext *C, ARegion *ar, BMEditMesh *em)
296 {
297         Object *obedit = em->ob;
298         BMIter iter;
299         BMVert *eve;
300
301         ED_view3d_init_mats_rv3d(obedit, ar->regiondata);
302
303         BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
304                 if (BM_elem_flag_test(eve, BM_ELEM_SELECT)) {
305                         float mval[2], co_proj[3], no_dummy[3];
306                         float dist_px_dummy;
307                         if (ED_view3d_project_float_object(ar, eve->co, mval, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
308                                 if (snapObjectsContext(C, mval, &dist_px_dummy, co_proj, no_dummy, SNAP_NOT_OBEDIT)) {
309                                         mul_v3_m4v3(eve->co, obedit->imat, co_proj);
310                                 }
311                         }
312                 }
313         }
314 }
315
316 static void edbm_report_delete_info(ReportList *reports, BMesh *bm, const int totelem[3])
317 {
318         BKE_reportf(reports, RPT_INFO,
319                     "Removed: %d vertices, %d edges, %d faces",
320                     totelem[0] - bm->totvert, totelem[1] - bm->totedge, totelem[2] - bm->totface);
321 }
322
323 /* Note, these values must match delete_mesh() event values */
324 static EnumPropertyItem prop_mesh_delete_types[] = {
325         {0, "VERT",      0, "Vertices", ""},
326         {1,  "EDGE",      0, "Edges", ""},
327         {2,  "FACE",      0, "Faces", ""},
328         {3,  "EDGE_FACE", 0, "Only Edges & Faces", ""},
329         {4,  "ONLY_FACE", 0, "Only Faces", ""},
330         {0, NULL, 0, NULL, NULL}
331 };
332
333 static int edbm_delete_exec(bContext *C, wmOperator *op)
334 {
335         Object *obedit = CTX_data_edit_object(C);
336         BMEditMesh *em = BKE_editmesh_from_object(obedit);
337         const int type = RNA_enum_get(op->ptr, "type");
338
339         if (type == 0) {
340                 if (!EDBM_op_callf(em, op, "delete geom=%hv context=%i", BM_ELEM_SELECT, DEL_VERTS)) /* Erase Vertices */
341                         return OPERATOR_CANCELLED;
342         }
343         else if (type == 1) {
344                 if (!EDBM_op_callf(em, op, "delete geom=%he context=%i", BM_ELEM_SELECT, DEL_EDGES)) /* Erase Edges */
345                         return OPERATOR_CANCELLED;
346         }
347         else if (type == 2) {
348                 if (!EDBM_op_callf(em, op, "delete geom=%hf context=%i", BM_ELEM_SELECT, DEL_FACES)) /* Erase Faces */
349                         return OPERATOR_CANCELLED;
350         }
351         else if (type == 3) {
352                 if (!EDBM_op_callf(em, op, "delete geom=%hef context=%i", BM_ELEM_SELECT, DEL_EDGESFACES)) /* Edges and Faces */
353                         return OPERATOR_CANCELLED;
354         }
355         else if (type == 4) {
356                 //"Erase Only Faces";
357                 if (!EDBM_op_callf(em, op, "delete geom=%hf context=%i",
358                                    BM_ELEM_SELECT, DEL_ONLYFACES))
359                 {
360                         return OPERATOR_CANCELLED;
361                 }
362         }
363
364         EDBM_flag_disable_all(em, BM_ELEM_SELECT);
365
366         EDBM_update_generic(em, true, true);
367         
368         return OPERATOR_FINISHED;
369 }
370
371 void MESH_OT_delete(wmOperatorType *ot)
372 {
373         /* identifiers */
374         ot->name = "Delete";
375         ot->description = "Delete selected vertices, edges or faces";
376         ot->idname = "MESH_OT_delete";
377         
378         /* api callbacks */
379         ot->invoke = WM_menu_invoke;
380         ot->exec = edbm_delete_exec;
381         
382         ot->poll = ED_operator_editmesh;
383         
384         /* flags */
385         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
386
387         /* props */
388         ot->prop = RNA_def_enum(ot->srna, "type", prop_mesh_delete_types, 0, "Type", "Method used for deleting mesh data");
389 }
390
391
392 static bool bm_face_is_loose(BMFace *f)
393 {
394         BMLoop *l_iter, *l_first;
395
396         l_iter = l_first = BM_FACE_FIRST_LOOP(f);
397         do {
398                 if (!BM_edge_is_boundary(l_iter->e)) {
399                         return false;
400                 }
401         } while ((l_iter = l_iter->next) != l_first);
402
403         return true;
404 }
405
406 static int edbm_delete_loose_exec(bContext *C, wmOperator *op)
407 {
408         Object *obedit = CTX_data_edit_object(C);
409         BMEditMesh *em = BKE_editmesh_from_object(obedit);
410         BMesh *bm = em->bm;
411         BMIter iter;
412
413         const bool use_verts = (RNA_boolean_get(op->ptr, "use_verts") && bm->totvertsel);
414         const bool use_edges = (RNA_boolean_get(op->ptr, "use_edges") && bm->totedgesel);
415         const bool use_faces = (RNA_boolean_get(op->ptr, "use_faces") && bm->totfacesel);
416
417         const int totelem[3] = {bm->totvert, bm->totedge, bm->totface};
418
419
420         BM_mesh_elem_hflag_disable_all(bm, BM_VERT | BM_EDGE | BM_FACE, BM_ELEM_TAG, false);
421
422         if (use_faces) {
423                 BMFace *f;
424
425                 BM_ITER_MESH (f, &iter, bm, BM_FACES_OF_MESH) {
426                         if (BM_elem_flag_test(f, BM_ELEM_SELECT)) {
427                                 BM_elem_flag_set(f, BM_ELEM_TAG, bm_face_is_loose(f));
428                         }
429                 }
430
431                 BM_mesh_delete_hflag_context(bm, BM_ELEM_TAG, DEL_FACES);
432         }
433
434         if (use_edges) {
435                 BMEdge *e;
436
437                 BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
438                         if (BM_elem_flag_test(e, BM_ELEM_SELECT)) {
439                                 BM_elem_flag_set(e, BM_ELEM_TAG, BM_edge_is_wire(e));
440                         }
441                 }
442
443                 BM_mesh_delete_hflag_context(bm, BM_ELEM_TAG, DEL_EDGES);
444         }
445
446         if (use_verts) {
447                 BMVert *v;
448
449                 BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) {
450                         if (BM_elem_flag_test(v, BM_ELEM_SELECT)) {
451                                 BM_elem_flag_set(v, BM_ELEM_TAG, (v->e == NULL));
452                         }
453                 }
454
455                 BM_mesh_delete_hflag_context(bm, BM_ELEM_TAG, DEL_VERTS);
456         }
457
458         EDBM_flag_disable_all(em, BM_ELEM_SELECT);
459
460         EDBM_update_generic(em, true, true);
461
462         edbm_report_delete_info(op->reports, bm, totelem);
463
464         return OPERATOR_FINISHED;
465 }
466
467
468 void MESH_OT_delete_loose(wmOperatorType *ot)
469 {
470         /* identifiers */
471         ot->name = "Delete Loose";
472         ot->description = "Delete loose vertices, edges or faces";
473         ot->idname = "MESH_OT_delete_loose";
474
475         /* api callbacks */
476         ot->exec = edbm_delete_loose_exec;
477
478         ot->poll = ED_operator_editmesh;
479
480         /* flags */
481         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
482
483         /* props */
484         RNA_def_boolean(ot->srna, "use_verts", true, "Vertices", "Remove loose vertices");
485         RNA_def_boolean(ot->srna, "use_edges", true, "Edges", "Remove loose edges");
486         RNA_def_boolean(ot->srna, "use_faces", false, "Faces", "Remove loose faces");
487 }
488
489
490 static int edbm_collapse_edge_exec(bContext *C, wmOperator *op)
491 {
492         Object *obedit = CTX_data_edit_object(C);
493         BMEditMesh *em = BKE_editmesh_from_object(obedit);
494
495         if (!EDBM_op_callf(em, op, "collapse edges=%he uvs=%b", BM_ELEM_SELECT, true))
496                 return OPERATOR_CANCELLED;
497
498         EDBM_update_generic(em, true, true);
499
500         return OPERATOR_FINISHED;
501 }
502
503 void MESH_OT_edge_collapse(wmOperatorType *ot)
504 {
505         /* identifiers */
506         ot->name = "Edge Collapse";
507         ot->description = "Collapse selected edges";
508         ot->idname = "MESH_OT_edge_collapse";
509
510         /* api callbacks */
511         ot->exec = edbm_collapse_edge_exec;
512         ot->poll = ED_operator_editmesh;
513
514         /* flags */
515         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
516 }
517
518 static int edbm_add_edge_face__smooth_get(BMesh *bm)
519 {
520         BMEdge *e;
521         BMIter iter;
522
523         unsigned int vote_on_smooth[2] = {0, 0};
524
525         BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
526                 if (BM_elem_flag_test(e, BM_ELEM_SELECT) && e->l) {
527                         vote_on_smooth[BM_elem_flag_test_bool(e->l->f, BM_ELEM_SMOOTH)]++;
528                 }
529         }
530
531         return (vote_on_smooth[0] < vote_on_smooth[1]);
532 }
533
534 #ifdef USE_FACE_CREATE_SEL_EXTEND
535 /**
536  * Function used to get a fixed number of edges linked to a vertex that passes a test function.
537  * This is used so we can request all boundary edges connected to a vertex for eg.
538  */
539 static int edbm_add_edge_face_exec__vert_edge_lookup(
540         BMVert *v, BMEdge *e_used, BMEdge **e_arr, const int e_arr_len,
541         bool (* func)(const BMEdge *))
542 {
543         BMIter iter;
544         BMEdge *e_iter;
545         int i = 0;
546         BM_ITER_ELEM (e_iter, &iter, v, BM_EDGES_OF_VERT) {
547                 if (BM_elem_flag_test(e_iter, BM_ELEM_HIDDEN) == false) {
548                         if ((e_used == NULL) || (e_used != e_iter)) {
549                                 if (func(e_iter)) {
550                                         e_arr[i++] = e_iter;
551                                         if (i >= e_arr_len) {
552                                                 break;
553                                         }
554                                 }
555                         }
556                 }
557         }
558         return i;
559 }
560
561 static BMElem *edbm_add_edge_face_exec__tricky_extend_sel(BMesh *bm)
562 {
563         BMIter iter;
564         bool found = false;
565
566         if (bm->totvertsel == 1 && bm->totedgesel == 0 && bm->totfacesel == 0) {
567                 /* first look for 2 boundary edges */
568                 BMVert *v;
569
570                 BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) {
571                         if (BM_elem_flag_test(v, BM_ELEM_SELECT)) {
572                                 found = true;
573                                 break;
574                         }
575                 }
576
577                 if (found) {
578                         BMEdge *ed_pair[3];
579                         if (
580                             ((edbm_add_edge_face_exec__vert_edge_lookup(v, NULL, ed_pair, 3, BM_edge_is_wire) == 2) &&
581                              (BM_edge_share_face_check(ed_pair[0], ed_pair[1]) == false)) ||
582
583                             ((edbm_add_edge_face_exec__vert_edge_lookup(v, NULL, ed_pair, 3, BM_edge_is_boundary) == 2) &&
584                              (BM_edge_share_face_check(ed_pair[0], ed_pair[1]) == false))
585                             )
586                         {
587                                 BMEdge *e_other = BM_edge_exists(BM_edge_other_vert(ed_pair[0], v),
588                                                                  BM_edge_other_vert(ed_pair[1], v));
589                                 BM_edge_select_set(bm, ed_pair[0], true);
590                                 BM_edge_select_set(bm, ed_pair[1], true);
591                                 if (e_other) {
592                                         BM_edge_select_set(bm, e_other, true);
593                                 }
594                                 return (BMElem *)v;
595                         }
596                 }
597         }
598         else if (bm->totvertsel == 2 && bm->totedgesel == 1 && bm->totfacesel == 0) {
599                 /* first look for 2 boundary edges */
600                 BMEdge *e;
601
602                 BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
603                         if (BM_elem_flag_test(e, BM_ELEM_SELECT)) {
604                                 found = true;
605                                 break;
606                         }
607                 }
608                 if (found) {
609                         BMEdge *ed_pair_v1[2];
610                         BMEdge *ed_pair_v2[2];
611                         if (
612                             ((edbm_add_edge_face_exec__vert_edge_lookup(e->v1, e, ed_pair_v1, 2, BM_edge_is_wire) == 1) &&
613                              (edbm_add_edge_face_exec__vert_edge_lookup(e->v2, e, ed_pair_v2, 2, BM_edge_is_wire) == 1) &&
614                              (BM_edge_share_face_check(e, ed_pair_v1[0]) == false) &&
615                              (BM_edge_share_face_check(e, ed_pair_v2[0]) == false)) ||
616
617 #if 1  /* better support mixed cases [#37203] */
618                             ((edbm_add_edge_face_exec__vert_edge_lookup(e->v1, e, ed_pair_v1, 2, BM_edge_is_wire)     == 1) &&
619                              (edbm_add_edge_face_exec__vert_edge_lookup(e->v2, e, ed_pair_v2, 2, BM_edge_is_boundary) == 1) &&
620                              (BM_edge_share_face_check(e, ed_pair_v1[0]) == false) &&
621                              (BM_edge_share_face_check(e, ed_pair_v2[0]) == false)) ||
622
623                             ((edbm_add_edge_face_exec__vert_edge_lookup(e->v1, e, ed_pair_v1, 2, BM_edge_is_boundary) == 1) &&
624                              (edbm_add_edge_face_exec__vert_edge_lookup(e->v2, e, ed_pair_v2, 2, BM_edge_is_wire)     == 1) &&
625                              (BM_edge_share_face_check(e, ed_pair_v1[0]) == false) &&
626                              (BM_edge_share_face_check(e, ed_pair_v2[0]) == false)) ||
627 #endif
628
629                             ((edbm_add_edge_face_exec__vert_edge_lookup(e->v1, e, ed_pair_v1, 2, BM_edge_is_boundary) == 1) &&
630                              (edbm_add_edge_face_exec__vert_edge_lookup(e->v2, e, ed_pair_v2, 2, BM_edge_is_boundary) == 1) &&
631                              (BM_edge_share_face_check(e, ed_pair_v1[0]) == false) &&
632                              (BM_edge_share_face_check(e, ed_pair_v2[0]) == false))
633                             )
634                         {
635                                 BMVert *v1_other = BM_edge_other_vert(ed_pair_v1[0], e->v1);
636                                 BMVert *v2_other = BM_edge_other_vert(ed_pair_v2[0], e->v2);
637                                 BMEdge *e_other = (v1_other != v2_other) ? BM_edge_exists(v1_other, v2_other) : NULL;
638                                 BM_edge_select_set(bm, ed_pair_v1[0], true);
639                                 BM_edge_select_set(bm, ed_pair_v2[0], true);
640                                 if (e_other) {
641                                         BM_edge_select_set(bm, e_other, true);
642                                 }
643                                 return (BMElem *)e;
644                         }
645                 }
646         }
647
648         return NULL;
649 }
650 static void edbm_add_edge_face_exec__tricky_finalize_sel(BMesh *bm, BMElem *ele_desel, BMFace *f)
651 {
652         /* now we need to find the edge that isnt connected to this element */
653         BM_select_history_clear(bm);
654
655         if (ele_desel->head.htype == BM_VERT) {
656                 BMLoop *l = BM_face_vert_share_loop(f, (BMVert *)ele_desel);
657                 BLI_assert(f->len == 3);
658                 BM_face_select_set(bm, f, false);
659                 BM_vert_select_set(bm, (BMVert *)ele_desel, false);
660
661                 BM_edge_select_set(bm, l->next->e, true);
662                 BM_select_history_store(bm, l->next->e);
663         }
664         else {
665                 BMLoop *l = BM_face_edge_share_loop(f, (BMEdge *)ele_desel);
666                 BLI_assert(f->len == 4 || f->len == 3);
667                 BM_face_select_set(bm, f, false);
668                 BM_edge_select_set(bm, (BMEdge *)ele_desel, false);
669                 if (f->len == 4) {
670                         BM_edge_select_set(bm, l->next->next->e, true);
671                         BM_select_history_store(bm, l->next->next->e);
672                 }
673                 else {
674                         BM_vert_select_set(bm, l->next->next->v, true);
675                         BM_select_history_store(bm, l->next->next->v);
676                 }
677         }
678 }
679 #endif  /* USE_FACE_CREATE_SEL_EXTEND */
680
681 static int edbm_add_edge_face_exec(bContext *C, wmOperator *op)
682 {
683         BMOperator bmop;
684         Object *obedit = CTX_data_edit_object(C);
685         BMEditMesh *em = BKE_editmesh_from_object(obedit);
686         const short use_smooth = edbm_add_edge_face__smooth_get(em->bm);
687         const int totedge_orig = em->bm->totedge;
688         const int totface_orig = em->bm->totface;
689         /* when this is used to dissolve we could avoid this, but checking isnt too slow */
690
691 #ifdef USE_FACE_CREATE_SEL_EXTEND
692         BMElem *ele_desel;
693         BMFace *ele_desel_face;
694
695         /* be extra clever, figure out if a partial selection should be extended so we can create geometry
696          * with single vert or single edge selection */
697         ele_desel = edbm_add_edge_face_exec__tricky_extend_sel(em->bm);
698 #endif
699
700         if (!EDBM_op_init(em, &bmop, op,
701                           "contextual_create geom=%hfev mat_nr=%i use_smooth=%b",
702                           BM_ELEM_SELECT, em->mat_nr, use_smooth))
703         {
704                 return OPERATOR_CANCELLED;
705         }
706         
707         BMO_op_exec(em->bm, &bmop);
708
709         /* cancel if nothing was done */
710         if ((totedge_orig == em->bm->totedge) &&
711             (totface_orig == em->bm->totface))
712         {
713                 EDBM_op_finish(em, &bmop, op, true);
714                 return OPERATOR_CANCELLED;
715         }
716
717 #ifdef USE_FACE_CREATE_SEL_EXTEND
718         /* normally we would want to leave the new geometry selected,
719          * but being able to press F many times to add geometry is too useful! */
720         if (ele_desel &&
721             (BMO_slot_buffer_count(bmop.slots_out, "faces.out") == 1) &&
722             (ele_desel_face = BMO_slot_buffer_get_first(bmop.slots_out, "faces.out")))
723         {
724                 edbm_add_edge_face_exec__tricky_finalize_sel(em->bm, ele_desel, ele_desel_face);
725         }
726         else
727 #endif
728         {
729                 BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "faces.out", BM_FACE, BM_ELEM_SELECT, true);
730                 BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "edges.out", BM_EDGE, BM_ELEM_SELECT, true);
731         }
732
733         if (!EDBM_op_finish(em, &bmop, op, true)) {
734                 return OPERATOR_CANCELLED;
735         }
736
737         EDBM_update_generic(em, true, true);
738
739         return OPERATOR_FINISHED;
740 }
741
742 void MESH_OT_edge_face_add(wmOperatorType *ot)
743 {
744         /* identifiers */
745         ot->name = "Make Edge/Face";
746         ot->description = "Add an edge or face to selected";
747         ot->idname = "MESH_OT_edge_face_add";
748         
749         /* api callbacks */
750         ot->exec = edbm_add_edge_face_exec;
751         ot->poll = ED_operator_editmesh;
752         
753         /* flags */
754         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
755 }
756
757 /* ************************* SEAMS AND EDGES **************** */
758
759 static int edbm_mark_seam_exec(bContext *C, wmOperator *op)
760 {
761         Scene *scene = CTX_data_scene(C);
762         Object *obedit = CTX_data_edit_object(C);
763         Mesh *me = ((Mesh *)obedit->data);
764         BMEditMesh *em = BKE_editmesh_from_object(obedit);
765         BMesh *bm = em->bm;
766         BMEdge *eed;
767         BMIter iter;
768         const bool clear = RNA_boolean_get(op->ptr, "clear");
769         
770         /* auto-enable seams drawing */
771         if (clear == 0) {
772                 me->drawflag |= ME_DRAWSEAMS;
773         }
774
775         if (clear) {
776                 BM_ITER_MESH (eed, &iter, bm, BM_EDGES_OF_MESH) {
777                         if (!BM_elem_flag_test(eed, BM_ELEM_SELECT) || BM_elem_flag_test(eed, BM_ELEM_HIDDEN))
778                                 continue;
779                         
780                         BM_elem_flag_disable(eed, BM_ELEM_SEAM);
781                 }
782         }
783         else {
784                 BM_ITER_MESH (eed, &iter, bm, BM_EDGES_OF_MESH) {
785                         if (!BM_elem_flag_test(eed, BM_ELEM_SELECT) || BM_elem_flag_test(eed, BM_ELEM_HIDDEN))
786                                 continue;
787                         BM_elem_flag_enable(eed, BM_ELEM_SEAM);
788                 }
789         }
790
791         ED_uvedit_live_unwrap(scene, obedit);
792         EDBM_update_generic(em, true, false);
793
794         return OPERATOR_FINISHED;
795 }
796
797 void MESH_OT_mark_seam(wmOperatorType *ot)
798 {
799         PropertyRNA *prop;
800
801         /* identifiers */
802         ot->name = "Mark Seam";
803         ot->idname = "MESH_OT_mark_seam";
804         ot->description = "(Un)mark selected edges as a seam";
805         
806         /* api callbacks */
807         ot->exec = edbm_mark_seam_exec;
808         ot->poll = ED_operator_editmesh;
809         
810         /* flags */
811         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
812         
813         prop = RNA_def_boolean(ot->srna, "clear", 0, "Clear", "");
814         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
815 }
816
817 static int edbm_mark_sharp_exec(bContext *C, wmOperator *op)
818 {
819         Object *obedit = CTX_data_edit_object(C);
820         Mesh *me = ((Mesh *)obedit->data);
821         BMEditMesh *em = BKE_editmesh_from_object(obedit);
822         BMesh *bm = em->bm;
823         BMEdge *eed;
824         BMIter iter;
825         const bool clear = RNA_boolean_get(op->ptr, "clear");
826         const bool use_verts = RNA_boolean_get(op->ptr, "use_verts");
827
828         /* auto-enable sharp edge drawing */
829         if (clear == 0) {
830                 me->drawflag |= ME_DRAWSHARP;
831         }
832
833         BM_ITER_MESH (eed, &iter, bm, BM_EDGES_OF_MESH) {
834                 if (use_verts) {
835                         if (!(BM_elem_flag_test(eed->v1, BM_ELEM_SELECT) || BM_elem_flag_test(eed->v2, BM_ELEM_SELECT))) {
836                                 continue;
837                         }
838                 }
839                 else if (!BM_elem_flag_test(eed, BM_ELEM_SELECT)) {
840                         continue;
841                 }
842
843                 BM_elem_flag_set(eed, BM_ELEM_SMOOTH, clear);
844         }
845
846         EDBM_update_generic(em, true, false);
847
848         return OPERATOR_FINISHED;
849 }
850
851 void MESH_OT_mark_sharp(wmOperatorType *ot)
852 {
853         PropertyRNA *prop;
854
855         /* identifiers */
856         ot->name = "Mark Sharp";
857         ot->idname = "MESH_OT_mark_sharp";
858         ot->description = "(Un)mark selected edges as sharp";
859         
860         /* api callbacks */
861         ot->exec = edbm_mark_sharp_exec;
862         ot->poll = ED_operator_editmesh;
863         
864         /* flags */
865         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
866         
867         prop = RNA_def_boolean(ot->srna, "clear", false, "Clear", "");
868         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
869         prop = RNA_def_boolean(ot->srna, "use_verts", false, "Vertices",
870                                "Consider vertices instead of edges to select which edges to (un)tag as sharp");
871         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
872 }
873
874 static int edbm_vert_connect_exec(bContext *C, wmOperator *op)
875 {
876         Object *obedit = CTX_data_edit_object(C);
877         BMEditMesh *em = BKE_editmesh_from_object(obedit);
878         BMesh *bm = em->bm;
879         BMOperator bmop;
880         bool is_pair = (bm->totvertsel == 2);
881         int len = 0;
882         bool check_degenerate = true;
883         const int verts_len = bm->totvertsel;
884         BMVert **verts;
885
886         verts = MEM_mallocN(sizeof(*verts) * verts_len, __func__);
887         {
888                 BMIter iter;
889                 BMVert *v;
890                 int i = 0;
891
892                 BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) {
893                         if (BM_elem_flag_test(v, BM_ELEM_SELECT)) {
894                                 verts[i++] = v;
895                         }
896                 }
897
898                 if (is_pair) {
899                         if (BM_vert_pair_share_face_check_cb(
900                                 verts[0], verts[1],
901                                 BM_elem_cb_check_hflag_disabled_simple(BMFace *, BM_ELEM_HIDDEN)))
902                         {
903                                 check_degenerate = false;
904                                 is_pair = false;
905                         }
906                 }
907         }
908
909         if (is_pair) {
910                 if (!EDBM_op_init(em, &bmop, op,
911                                   "connect_vert_pair verts=%eb verts_exclude=%hv faces_exclude=%hf",
912                                   verts, verts_len, BM_ELEM_HIDDEN, BM_ELEM_HIDDEN))
913                 {
914                         goto finally;
915                 }
916         }
917         else {
918                 if (!EDBM_op_init(em, &bmop, op,
919                                   "connect_verts verts=%eb faces_exclude=%hf check_degenerate=%b",
920                                   verts, verts_len, BM_ELEM_HIDDEN, check_degenerate))
921                 {
922                         goto finally;
923                 }
924         }
925
926         BMO_op_exec(bm, &bmop);
927         len = BMO_slot_get(bmop.slots_out, "edges.out")->len;
928
929         if (len) {
930                 if (is_pair) {
931                         /* new verts have been added, we have to select the edges, not just flush */
932                         BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "edges.out", BM_EDGE, BM_ELEM_SELECT, true);
933                 }
934         }
935
936         if (!EDBM_op_finish(em, &bmop, op, true)) {
937                 len = 0;
938         }
939         else {
940                 EDBM_selectmode_flush(em);  /* so newly created edges get the selection state from the vertex */
941
942                 EDBM_update_generic(em, true, true);
943         }
944
945
946 finally:
947         MEM_freeN(verts);
948         return len ? OPERATOR_FINISHED : OPERATOR_CANCELLED;
949 }
950
951 void MESH_OT_vert_connect(wmOperatorType *ot)
952 {
953         /* identifiers */
954         ot->name = "Vertex Connect";
955         ot->idname = "MESH_OT_vert_connect";
956         ot->description = "Connect selected vertices of faces, splitting the face";
957         
958         /* api callbacks */
959         ot->exec = edbm_vert_connect_exec;
960         ot->poll = ED_operator_editmesh;
961         
962         /* flags */
963         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
964 }
965
966
967 /**
968  * check that endpoints are verts and only have a single selected edge connected.
969  */
970 static bool bm_vert_is_select_history_open(BMesh *bm)
971 {
972         BMEditSelection *ele_a = bm->selected.first;
973         BMEditSelection *ele_b = bm->selected.last;
974         if ((ele_a->htype == BM_VERT) &&
975             (ele_b->htype == BM_VERT))
976         {
977                 if ((BM_iter_elem_count_flag(BM_EDGES_OF_VERT, (BMVert *)ele_a->ele, BM_ELEM_SELECT, true) == 1) &&
978                     (BM_iter_elem_count_flag(BM_EDGES_OF_VERT, (BMVert *)ele_b->ele, BM_ELEM_SELECT, true) == 1))
979                 {
980                         return true;
981                 }
982         }
983
984         return false;
985 }
986
987 static bool bm_vert_connect_pair(BMesh *bm, BMVert *v_a, BMVert *v_b)
988 {
989         BMOperator bmop;
990         BMVert **verts;
991         const int totedge_orig = bm->totedge;
992
993         BMO_op_init(bm, &bmop, BMO_FLAG_DEFAULTS, "connect_vert_pair");
994
995         verts = BMO_slot_buffer_alloc(&bmop, bmop.slots_in, "verts", 2);
996         verts[0] = v_a;
997         verts[1] = v_b;
998
999         BM_vert_normal_update(verts[0]);
1000         BM_vert_normal_update(verts[1]);
1001
1002         BMO_op_exec(bm, &bmop);
1003         BMO_slot_buffer_hflag_enable(bm, bmop.slots_out, "edges.out", BM_EDGE, BM_ELEM_SELECT, true);
1004         BMO_op_finish(bm, &bmop);
1005         return (bm->totedge != totedge_orig);
1006 }
1007
1008 static bool bm_vert_connect_select_history(BMesh *bm)
1009 {
1010         /* Logic is as follows:
1011          *
1012          * - If there are any isolated/wire verts - connect as edges.
1013          * - Otherwise connect faces.
1014          * - If all edges have been created already, closed the loop.
1015          */
1016         if (BLI_listbase_count_ex(&bm->selected, 2) == 2 && (bm->totvertsel > 2)) {
1017                 BMEditSelection *ese;
1018                 int tot = 0;
1019                 bool changed = false;
1020                 bool has_wire = false;
1021                 // bool all_verts;
1022
1023                 /* ensure all verts have history */
1024                 for (ese = bm->selected.first; ese; ese = ese->next, tot++) {
1025                         BMVert *v;
1026                         if (ese->htype != BM_VERT) {
1027                                 break;
1028                         }
1029                         v = (BMVert *)ese->ele;
1030                         if ((has_wire == false) && ((v->e == NULL) || BM_vert_is_wire(v))) {
1031                                 has_wire = true;
1032                         }
1033                 }
1034                 // all_verts = (ese == NULL);
1035
1036                 if (has_wire == false) {
1037                         /* all verts have faces , connect verts via faces! */
1038                         if (tot == bm->totvertsel) {
1039                                 BMEditSelection *ese_last;
1040                                 ese_last = bm->selected.first;
1041                                 ese = ese_last->next;
1042
1043                                 do {
1044
1045                                         if (BM_edge_exists((BMVert *)ese_last->ele, (BMVert *)ese->ele)) {
1046                                                 /* pass, edge exists (and will be selected) */
1047                                         }
1048                                         else {
1049                                                 changed |= bm_vert_connect_pair(bm, (BMVert *)ese_last->ele, (BMVert *)ese->ele);
1050                                         }
1051                                 } while ((ese_last = ese),
1052                                          (ese = ese->next));
1053
1054                                 if (changed) {
1055                                         return true;
1056                                 }
1057                         }
1058
1059                         if (changed == false) {
1060                                 /* existing loops: close the selection */
1061                                 if (bm_vert_is_select_history_open(bm)) {
1062                                         changed |= bm_vert_connect_pair(
1063                                                 bm,
1064                                                 (BMVert *)((BMEditSelection *)bm->selected.first)->ele,
1065                                                 (BMVert *)((BMEditSelection *)bm->selected.last)->ele);
1066
1067                                         if (changed) {
1068                                                 return true;
1069                                         }
1070                                 }
1071                         }
1072                 }
1073
1074                 else {
1075                         /* no faces, simply connect the verts by edges */
1076                         BMEditSelection *ese_prev;
1077                         ese_prev = bm->selected.first;
1078                         ese = ese_prev->next;
1079
1080
1081                         do {
1082                                 if (BM_edge_exists((BMVert *)ese_prev->ele, (BMVert *)ese->ele)) {
1083                                         /* pass, edge exists (and will be selected) */
1084                                 }
1085                                 else {
1086                                         BMEdge *e;
1087                                         e = BM_edge_create(bm, (BMVert *)ese_prev->ele, (BMVert *)ese->ele, NULL, 0);
1088                                         BM_edge_select_set(bm, e, true);
1089                                         changed = true;
1090                                 }
1091                         } while ((ese_prev = ese),
1092                                  (ese = ese->next));
1093
1094                         if (changed == false) {
1095                                 /* existing loops: close the selection */
1096                                 if (bm_vert_is_select_history_open(bm)) {
1097                                         BMEdge *e;
1098                                         ese_prev = bm->selected.first;
1099                                         ese = bm->selected.last;
1100                                         e = BM_edge_create(bm, (BMVert *)ese_prev->ele, (BMVert *)ese->ele, NULL, 0);
1101                                         BM_edge_select_set(bm, e, true);
1102                                 }
1103                         }
1104
1105                         return true;
1106                 }
1107         }
1108
1109         return false;
1110 }
1111
1112 /**
1113  * Convert an edge selection to a temp vertex selection
1114  * (which must be cleared after use as a path to connect).
1115  */
1116 static bool bm_vert_connect_select_history_edge_to_vert_path(BMesh *bm, ListBase *r_selected)
1117 {
1118         ListBase selected_orig = {NULL, NULL};
1119         BMEditSelection *ese;
1120         int edges_len = 0;
1121         bool side = false;
1122
1123         /* first check all edges are OK */
1124         for (ese = bm->selected.first; ese; ese = ese->next) {
1125                 if (ese->htype == BM_EDGE) {
1126                         edges_len += 1;
1127                 }
1128                 else {
1129                         return false;
1130                 }
1131         }
1132         /* if this is a mixed selection, bail out! */
1133         if (bm->totedgesel != edges_len) {
1134                 return false;
1135         }
1136
1137         SWAP(ListBase, bm->selected, selected_orig);
1138
1139         /* convert edge selection into 2 ordered loops (where the first edge ends up in the middle) */
1140         for (ese = selected_orig.first; ese; ese = ese->next) {
1141                 BMEdge *e_curr = (BMEdge *)ese->ele;
1142                 BMEdge *e_prev = ese->prev ? (BMEdge *)ese->prev->ele : NULL;
1143                 BMLoop *l_curr;
1144                 BMLoop *l_prev;
1145                 BMVert *v;
1146
1147                 if (e_prev) {
1148                         BMFace *f = BM_edge_pair_share_face_by_len(e_curr, e_prev, &l_curr, &l_prev, true);
1149                         if (f) {
1150                                 if ((e_curr->v1 != l_curr->v) == (e_prev->v1 != l_prev->v)) {
1151                                         side = !side;
1152                                 }
1153                         }
1154                         else if (is_quad_flip_v3(e_curr->v1->co, e_curr->v2->co, e_prev->v2->co, e_prev->v1->co)) {
1155                                 side = !side;
1156                         }
1157                 }
1158
1159                 v = (&e_curr->v1)[side];
1160                 if (!bm->selected.last || (BMVert *)((BMEditSelection *)bm->selected.last)->ele != v) {
1161                         BM_select_history_store_notest(bm, v);
1162                 }
1163
1164                 v = (&e_curr->v1)[!side];
1165                 if (!bm->selected.first || (BMVert *)((BMEditSelection *)bm->selected.first)->ele != v) {
1166                         BM_select_history_store_head_notest(bm, v);
1167                 }
1168
1169                 e_prev = e_curr;
1170         }
1171
1172         *r_selected = bm->selected;
1173         bm->selected = selected_orig;
1174
1175         return true;
1176 }
1177
1178 static int edbm_vert_connect_path_exec(bContext *C, wmOperator *op)
1179 {
1180         Object *obedit = CTX_data_edit_object(C);
1181         BMEditMesh *em = BKE_editmesh_from_object(obedit);
1182         BMesh *bm = em->bm;
1183         bool is_pair = (em->bm->totvertsel == 2);
1184         ListBase selected_orig = {NULL, NULL};
1185         int retval;
1186
1187         /* when there is only 2 vertices, we can ignore selection order */
1188         if (is_pair) {
1189                 return edbm_vert_connect_exec(C, op);
1190         }
1191
1192         if (bm->selected.first) {
1193                 BMEditSelection *ese = bm->selected.first;
1194                 if (ese->htype == BM_EDGE) {
1195                         if (bm_vert_connect_select_history_edge_to_vert_path(bm, &selected_orig)) {
1196                                 SWAP(ListBase, bm->selected, selected_orig);
1197                         }
1198                 }
1199         }
1200
1201         if (bm_vert_connect_select_history(bm)) {
1202                 EDBM_selectmode_flush(em);
1203                 EDBM_update_generic(em, true, true);
1204                 retval = OPERATOR_FINISHED;
1205         }
1206         else {
1207                 BKE_report(op->reports, RPT_ERROR, "Invalid selection order");
1208                 retval = OPERATOR_CANCELLED;
1209         }
1210
1211         if (!BLI_listbase_is_empty(&selected_orig)) {
1212                 BM_select_history_clear(bm);
1213                 bm->selected = selected_orig;
1214         }
1215
1216         return retval;
1217 }
1218
1219 void MESH_OT_vert_connect_path(wmOperatorType *ot)
1220 {
1221         /* identifiers */
1222         ot->name = "Vertex Connect Path";
1223         ot->idname = "MESH_OT_vert_connect_path";
1224         ot->description = "Connect vertices by their selection order, creating edges, splitting faces";
1225
1226         /* api callbacks */
1227         ot->exec = edbm_vert_connect_path_exec;
1228         ot->poll = ED_operator_editmesh;
1229
1230         /* flags */
1231         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1232 }
1233
1234 static int edbm_vert_connect_concave_exec(bContext *C, wmOperator *op)
1235 {
1236         Object *obedit = CTX_data_edit_object(C);
1237         BMEditMesh *em = BKE_editmesh_from_object(obedit);
1238
1239         if (!EDBM_op_call_and_selectf(
1240                      em, op,
1241                      "faces.out", true,
1242                      "connect_verts_concave faces=%hf",
1243                      BM_ELEM_SELECT))
1244         {
1245                 return OPERATOR_CANCELLED;
1246         }
1247
1248
1249         EDBM_update_generic(em, true, true);
1250         return OPERATOR_FINISHED;
1251 }
1252
1253 void MESH_OT_vert_connect_concave(wmOperatorType *ot)
1254 {
1255         /* identifiers */
1256         ot->name = "Split Concave Faces";
1257         ot->idname = "MESH_OT_vert_connect_concave";
1258         ot->description = "Make all faces convex";
1259
1260         /* api callbacks */
1261         ot->exec = edbm_vert_connect_concave_exec;
1262         ot->poll = ED_operator_editmesh;
1263
1264         /* flags */
1265         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1266 }
1267
1268
1269 static int edbm_vert_connect_nonplaner_exec(bContext *C, wmOperator *op)
1270 {
1271         Object *obedit = CTX_data_edit_object(C);
1272         BMEditMesh *em = BKE_editmesh_from_object(obedit);
1273
1274         const float angle_limit = RNA_float_get(op->ptr, "angle_limit");
1275
1276         if (!EDBM_op_call_and_selectf(
1277                      em, op,
1278                      "faces.out", true,
1279                      "connect_verts_nonplanar faces=%hf angle_limit=%f",
1280                      BM_ELEM_SELECT, angle_limit))
1281         {
1282                 return OPERATOR_CANCELLED;
1283         }
1284
1285
1286         EDBM_update_generic(em, true, true);
1287         return OPERATOR_FINISHED;
1288 }
1289
1290 void MESH_OT_vert_connect_nonplanar(wmOperatorType *ot)
1291 {
1292         PropertyRNA *prop;
1293
1294         /* identifiers */
1295         ot->name = "Split Non-Planar Faces";
1296         ot->idname = "MESH_OT_vert_connect_nonplanar";
1297         ot->description = "Split non-planar faces that exceed the angle threshold";
1298
1299         /* api callbacks */
1300         ot->exec = edbm_vert_connect_nonplaner_exec;
1301         ot->poll = ED_operator_editmesh;
1302
1303         /* flags */
1304         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1305
1306         /* props */
1307         prop = RNA_def_float_rotation(ot->srna, "angle_limit", 0, NULL, 0.0f, DEG2RADF(180.0f),
1308                                       "Max Angle", "Angle limit", 0.0f, DEG2RADF(180.0f));
1309         RNA_def_property_float_default(prop, DEG2RADF(5.0f));
1310 }
1311
1312 static int edbm_face_make_planar_exec(bContext *C, wmOperator *op)
1313 {
1314         Object *obedit = CTX_data_edit_object(C);
1315         BMEditMesh *em = BKE_editmesh_from_object(obedit);
1316         const int repeat = RNA_int_get(op->ptr, "repeat");
1317         const float fac = RNA_float_get(op->ptr, "factor");
1318
1319         if (!EDBM_op_callf(
1320                 em, op, "planar_faces faces=%hf iterations=%i factor=%f",
1321                 BM_ELEM_SELECT, repeat, fac))
1322         {
1323                 return OPERATOR_CANCELLED;
1324         }
1325
1326         EDBM_update_generic(em, true, true);
1327         return OPERATOR_FINISHED;
1328 }
1329
1330 void MESH_OT_face_make_planar(wmOperatorType *ot)
1331 {
1332         /* identifiers */
1333         ot->name = "Make Planar Faces";
1334         ot->idname = "MESH_OT_face_make_planar";
1335         ot->description = "Flatten selected faces";
1336
1337         /* api callbacks */
1338         ot->exec = edbm_face_make_planar_exec;
1339         ot->poll = ED_operator_editmesh;
1340
1341         /* flags */
1342         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1343
1344         /* props */
1345         RNA_def_float(ot->srna, "factor", 0.5f, -10.0f, 10.0f, "Factor", "", 0.0f, 1.0f);
1346         RNA_def_int(ot->srna, "repeat", 1, 1, 200,
1347                     "Number of iterations to flatten faces", "", 1, 200);
1348 }
1349
1350
1351 static int edbm_edge_split_exec(bContext *C, wmOperator *op)
1352 {
1353         Object *obedit = CTX_data_edit_object(C);
1354         BMEditMesh *em = BKE_editmesh_from_object(obedit);
1355
1356         if (!EDBM_op_call_and_selectf(
1357                 em, op,
1358                 "edges.out", false,
1359                 "split_edges edges=%he",
1360                 BM_ELEM_SELECT))
1361         {
1362                 return OPERATOR_CANCELLED;
1363         }
1364         
1365         if (em->selectmode == SCE_SELECT_FACE) {
1366                 EDBM_select_flush(em);
1367         }
1368
1369         EDBM_update_generic(em, true, true);
1370
1371         return OPERATOR_FINISHED;
1372 }
1373
1374 void MESH_OT_edge_split(wmOperatorType *ot)
1375 {
1376         /* identifiers */
1377         ot->name = "Edge Split";
1378         ot->idname = "MESH_OT_edge_split";
1379         ot->description = "Split selected edges so that each neighbor face gets its own copy";
1380         
1381         /* api callbacks */
1382         ot->exec = edbm_edge_split_exec;
1383         ot->poll = ED_operator_editmesh;
1384         
1385         /* flags */
1386         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1387 }
1388
1389 /****************** add duplicate operator ***************/
1390
1391 static int edbm_duplicate_exec(bContext *C, wmOperator *op)
1392 {
1393         Object *ob = CTX_data_edit_object(C);
1394         BMEditMesh *em = BKE_editmesh_from_object(ob);
1395         BMesh *bm = em->bm;
1396         BMOperator bmop;
1397
1398         EDBM_op_init(
1399                 em, &bmop, op,
1400                 "duplicate geom=%hvef use_select_history=%b",
1401                 BM_ELEM_SELECT, true);
1402
1403         BMO_op_exec(bm, &bmop);
1404
1405         /* de-select all would clear otherwise */
1406         BM_SELECT_HISTORY_BACKUP(bm);
1407
1408         EDBM_flag_disable_all(em, BM_ELEM_SELECT);
1409
1410         BMO_slot_buffer_hflag_enable(bm, bmop.slots_out, "geom.out", BM_ALL_NOLOOP, BM_ELEM_SELECT, true);
1411
1412         /* rebuild editselection */
1413         BM_SELECT_HISTORY_RESTORE(bm);
1414
1415         if (!EDBM_op_finish(em, &bmop, op, true)) {
1416                 return OPERATOR_CANCELLED;
1417         }
1418
1419         EDBM_update_generic(em, true, true);
1420         
1421         return OPERATOR_FINISHED;
1422 }
1423
1424 static int edbm_duplicate_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1425 {
1426         WM_cursor_wait(1);
1427         edbm_duplicate_exec(C, op);
1428         WM_cursor_wait(0);
1429         
1430         return OPERATOR_FINISHED;
1431 }
1432
1433 void MESH_OT_duplicate(wmOperatorType *ot)
1434 {
1435         /* identifiers */
1436         ot->name = "Duplicate";
1437         ot->description = "Duplicate selected vertices, edges or faces";
1438         ot->idname = "MESH_OT_duplicate";
1439         
1440         /* api callbacks */
1441         ot->invoke = edbm_duplicate_invoke;
1442         ot->exec = edbm_duplicate_exec;
1443         
1444         ot->poll = ED_operator_editmesh;
1445         
1446         /* to give to transform */
1447         RNA_def_int(ot->srna, "mode", TFM_TRANSLATION, 0, INT_MAX, "Mode", "", 0, INT_MAX);
1448 }
1449
1450 static int edbm_flip_normals_exec(bContext *C, wmOperator *op)
1451 {
1452         Object *obedit = CTX_data_edit_object(C);
1453         BMEditMesh *em = BKE_editmesh_from_object(obedit);
1454         
1455         if (!EDBM_op_callf(em, op, "reverse_faces faces=%hf", BM_ELEM_SELECT))
1456                 return OPERATOR_CANCELLED;
1457         
1458         EDBM_update_generic(em, true, false);
1459
1460         return OPERATOR_FINISHED;
1461 }
1462
1463 void MESH_OT_flip_normals(wmOperatorType *ot)
1464 {
1465         /* identifiers */
1466         ot->name = "Flip Normals";
1467         ot->description = "Flip the direction of selected faces' normals (and of their vertices)";
1468         ot->idname = "MESH_OT_flip_normals";
1469         
1470         /* api callbacks */
1471         ot->exec = edbm_flip_normals_exec;
1472         ot->poll = ED_operator_editmesh;
1473         
1474         /* flags */
1475         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1476 }
1477
1478 /* only accepts 1 selected edge, or 2 selected faces */
1479 static int edbm_edge_rotate_selected_exec(bContext *C, wmOperator *op)
1480 {
1481         Object *obedit = CTX_data_edit_object(C);
1482         BMEditMesh *em = BKE_editmesh_from_object(obedit);
1483         BMOperator bmop;
1484         BMEdge *eed;
1485         BMIter iter;
1486         const bool use_ccw = RNA_boolean_get(op->ptr, "use_ccw");
1487         int tot = 0;
1488
1489         if (em->bm->totedgesel == 0) {
1490                 BKE_report(op->reports, RPT_ERROR, "Select edges or face pairs for edge loops to rotate about");
1491                 return OPERATOR_CANCELLED;
1492         }
1493
1494         /* first see if we have two adjacent faces */
1495         BM_ITER_MESH (eed, &iter, em->bm, BM_EDGES_OF_MESH) {
1496                 BM_elem_flag_disable(eed, BM_ELEM_TAG);
1497                 if (BM_elem_flag_test(eed, BM_ELEM_SELECT)) {
1498                         BMFace *fa, *fb;
1499                         if (BM_edge_face_pair(eed, &fa, &fb)) {
1500                                 /* if both faces are selected we rotate between them,
1501                                  * otherwise - rotate between 2 unselected - but not mixed */
1502                                 if (BM_elem_flag_test(fa, BM_ELEM_SELECT) == BM_elem_flag_test(fb, BM_ELEM_SELECT)) {
1503                                         BM_elem_flag_enable(eed, BM_ELEM_TAG);
1504                                         tot++;
1505                                 }
1506                         }
1507                 }
1508         }
1509         
1510         /* ok, we don't have two adjacent faces, but we do have two selected ones.
1511          * that's an error condition.*/
1512         if (tot == 0) {
1513                 BKE_report(op->reports, RPT_ERROR, "Could not find any selected edges that can be rotated");
1514                 return OPERATOR_CANCELLED;
1515         }
1516
1517         EDBM_op_init(em, &bmop, op, "rotate_edges edges=%he use_ccw=%b", BM_ELEM_TAG, use_ccw);
1518
1519         /* avoids leaving old verts selected which can be a problem running multiple times,
1520          * since this means the edges become selected around the face which then attempt to rotate */
1521         BMO_slot_buffer_hflag_disable(em->bm, bmop.slots_in, "edges", BM_EDGE, BM_ELEM_SELECT, true);
1522
1523         BMO_op_exec(em->bm, &bmop);
1524         /* edges may rotate into hidden vertices, if this does _not_ run we get an ilogical state */
1525         BMO_slot_buffer_hflag_disable(em->bm, bmop.slots_out, "edges.out", BM_EDGE, BM_ELEM_HIDDEN, true);
1526         BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "edges.out", BM_EDGE, BM_ELEM_SELECT, true);
1527         EDBM_selectmode_flush(em);
1528
1529         if (!EDBM_op_finish(em, &bmop, op, true)) {
1530                 return OPERATOR_CANCELLED;
1531         }
1532
1533         EDBM_update_generic(em, true, true);
1534
1535         return OPERATOR_FINISHED;
1536 }
1537
1538 void MESH_OT_edge_rotate(wmOperatorType *ot)
1539 {
1540         /* identifiers */
1541         ot->name = "Rotate Selected Edge";
1542         ot->description = "Rotate selected edge or adjoining faces";
1543         ot->idname = "MESH_OT_edge_rotate";
1544
1545         /* api callbacks */
1546         ot->exec = edbm_edge_rotate_selected_exec;
1547         ot->poll = ED_operator_editmesh;
1548
1549         /* flags */
1550         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1551
1552         /* props */
1553         RNA_def_boolean(ot->srna, "use_ccw", false, "Counter Clockwise", "");
1554 }
1555
1556
1557 static int edbm_hide_exec(bContext *C, wmOperator *op)
1558 {
1559         Object *obedit = CTX_data_edit_object(C);
1560         BMEditMesh *em = BKE_editmesh_from_object(obedit);
1561         
1562         EDBM_mesh_hide(em, RNA_boolean_get(op->ptr, "unselected"));
1563
1564         EDBM_update_generic(em, true, false);
1565
1566         return OPERATOR_FINISHED;
1567 }
1568
1569 void MESH_OT_hide(wmOperatorType *ot)
1570 {
1571         /* identifiers */
1572         ot->name = "Hide Selection";
1573         ot->idname = "MESH_OT_hide";
1574         ot->description = "Hide (un)selected vertices, edges or faces";
1575         
1576         /* api callbacks */
1577         ot->exec = edbm_hide_exec;
1578         ot->poll = ED_operator_editmesh;
1579
1580         /* flags */
1581         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1582         
1583         /* props */
1584         RNA_def_boolean(ot->srna, "unselected", 0, "Unselected", "Hide unselected rather than selected");
1585 }
1586
1587 static int edbm_reveal_exec(bContext *C, wmOperator *UNUSED(op))
1588 {
1589         Object *obedit = CTX_data_edit_object(C);
1590         BMEditMesh *em = BKE_editmesh_from_object(obedit);
1591         
1592         EDBM_mesh_reveal(em);
1593
1594         EDBM_update_generic(em, true, false);
1595
1596         return OPERATOR_FINISHED;
1597 }
1598
1599 void MESH_OT_reveal(wmOperatorType *ot)
1600 {
1601         /* identifiers */
1602         ot->name = "Reveal Hidden";
1603         ot->idname = "MESH_OT_reveal";
1604         ot->description = "Reveal all hidden vertices, edges and faces";
1605         
1606         /* api callbacks */
1607         ot->exec = edbm_reveal_exec;
1608         ot->poll = ED_operator_editmesh;
1609         
1610         /* flags */
1611         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1612 }
1613
1614 static int edbm_normals_make_consistent_exec(bContext *C, wmOperator *op)
1615 {
1616         Object *obedit = CTX_data_edit_object(C);
1617         BMEditMesh *em = BKE_editmesh_from_object(obedit);
1618         
1619         /* doflip has to do with bmesh_rationalize_normals, it's an internal
1620          * thing */
1621         if (!EDBM_op_callf(em, op, "recalc_face_normals faces=%hf", BM_ELEM_SELECT))
1622                 return OPERATOR_CANCELLED;
1623
1624         if (RNA_boolean_get(op->ptr, "inside"))
1625                 EDBM_op_callf(em, op, "reverse_faces faces=%hf", BM_ELEM_SELECT);
1626
1627         EDBM_update_generic(em, true, false);
1628
1629         return OPERATOR_FINISHED;
1630 }
1631
1632 void MESH_OT_normals_make_consistent(wmOperatorType *ot)
1633 {
1634         /* identifiers */
1635         ot->name = "Make Normals Consistent";
1636         ot->description = "Make face and vertex normals point either outside or inside the mesh";
1637         ot->idname = "MESH_OT_normals_make_consistent";
1638         
1639         /* api callbacks */
1640         ot->exec = edbm_normals_make_consistent_exec;
1641         ot->poll = ED_operator_editmesh;
1642         
1643         /* flags */
1644         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1645         
1646         RNA_def_boolean(ot->srna, "inside", 0, "Inside", "");
1647 }
1648
1649
1650
1651 static int edbm_do_smooth_vertex_exec(bContext *C, wmOperator *op)
1652 {
1653         Object *obedit = CTX_data_edit_object(C);
1654         Mesh *me = obedit->data;
1655         BMEditMesh *em = BKE_editmesh_from_object(obedit);
1656         ModifierData *md;
1657         bool mirrx = false, mirry = false, mirrz = false;
1658         int i, repeat;
1659         float clip_dist = 0.0f;
1660         const float fac = RNA_float_get(op->ptr, "factor");
1661         const bool use_topology = (me->editflag & ME_EDIT_MIRROR_TOPO) != 0;
1662
1663         const bool xaxis = RNA_boolean_get(op->ptr, "xaxis");
1664         const bool yaxis = RNA_boolean_get(op->ptr, "yaxis");
1665         const bool zaxis = RNA_boolean_get(op->ptr, "zaxis");
1666
1667         /* mirror before smooth */
1668         if (((Mesh *)obedit->data)->editflag & ME_EDIT_MIRROR_X) {
1669                 EDBM_verts_mirror_cache_begin(em, 0, false, true, use_topology);
1670         }
1671
1672         /* if there is a mirror modifier with clipping, flag the verts that
1673          * are within tolerance of the plane(s) of reflection 
1674          */
1675         for (md = obedit->modifiers.first; md; md = md->next) {
1676                 if (md->type == eModifierType_Mirror && (md->mode & eModifierMode_Realtime)) {
1677                         MirrorModifierData *mmd = (MirrorModifierData *)md;
1678                 
1679                         if (mmd->flag & MOD_MIR_CLIPPING) {
1680                                 if (mmd->flag & MOD_MIR_AXIS_X)
1681                                         mirrx = true;
1682                                 if (mmd->flag & MOD_MIR_AXIS_Y)
1683                                         mirry = true;
1684                                 if (mmd->flag & MOD_MIR_AXIS_Z)
1685                                         mirrz = true;
1686
1687                                 clip_dist = mmd->tolerance;
1688                         }
1689                 }
1690         }
1691
1692         repeat = RNA_int_get(op->ptr, "repeat");
1693         if (!repeat)
1694                 repeat = 1;
1695
1696         for (i = 0; i < repeat; i++) {
1697                 if (!EDBM_op_callf(em, op,
1698                                    "smooth_vert verts=%hv factor=%f mirror_clip_x=%b mirror_clip_y=%b mirror_clip_z=%b "
1699                                    "clip_dist=%f use_axis_x=%b use_axis_y=%b use_axis_z=%b",
1700                                    BM_ELEM_SELECT, fac, mirrx, mirry, mirrz, clip_dist, xaxis, yaxis, zaxis))
1701                 {
1702                         return OPERATOR_CANCELLED;
1703                 }
1704         }
1705
1706         /* apply mirror */
1707         if (((Mesh *)obedit->data)->editflag & ME_EDIT_MIRROR_X) {
1708                 EDBM_verts_mirror_apply(em, BM_ELEM_SELECT, 0);
1709                 EDBM_verts_mirror_cache_end(em);
1710         }
1711
1712         EDBM_update_generic(em, true, false);
1713
1714         return OPERATOR_FINISHED;
1715 }       
1716         
1717 void MESH_OT_vertices_smooth(wmOperatorType *ot)
1718 {
1719         /* identifiers */
1720         ot->name = "Smooth Vertex";
1721         ot->description = "Flatten angles of selected vertices";
1722         ot->idname = "MESH_OT_vertices_smooth";
1723         
1724         /* api callbacks */
1725         ot->exec = edbm_do_smooth_vertex_exec;
1726         ot->poll = ED_operator_editmesh;
1727         
1728         /* flags */
1729         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1730
1731         RNA_def_float(ot->srna, "factor", 0.5f, -10.0f, 10.0f, "Smoothing", "Smoothing factor", 0.0f, 1.0f);
1732         RNA_def_int(ot->srna, "repeat", 1, 1, 1000, "Repeat", "Number of times to smooth the mesh", 1, 100);
1733         RNA_def_boolean(ot->srna, "xaxis", 1, "X-Axis", "Smooth along the X axis");
1734         RNA_def_boolean(ot->srna, "yaxis", 1, "Y-Axis", "Smooth along the Y axis");
1735         RNA_def_boolean(ot->srna, "zaxis", 1, "Z-Axis", "Smooth along the Z axis");
1736 }
1737
1738 static int edbm_do_smooth_laplacian_vertex_exec(bContext *C, wmOperator *op)
1739 {
1740         Object *obedit = CTX_data_edit_object(C);
1741         BMEditMesh *em = BKE_editmesh_from_object(obedit);
1742         Mesh *me = obedit->data;
1743         bool use_topology = (me->editflag & ME_EDIT_MIRROR_TOPO) != 0;
1744         bool usex = true, usey = true, usez = true, preserve_volume = true;
1745         int i, repeat;
1746         float lambda_factor;
1747         float lambda_border;
1748         BMIter fiter;
1749         BMFace *f;
1750
1751         /* Check if select faces are triangles  */
1752         BM_ITER_MESH (f, &fiter, em->bm, BM_FACES_OF_MESH) {
1753                 if (BM_elem_flag_test(f, BM_ELEM_SELECT)) {
1754                         if (f->len > 4) {
1755                                 BKE_report(op->reports, RPT_WARNING, "Selected faces must be triangles or quads");
1756                                 return OPERATOR_CANCELLED;
1757                         }       
1758                 }
1759         }
1760
1761         /* mirror before smooth */
1762         if (((Mesh *)obedit->data)->editflag & ME_EDIT_MIRROR_X) {
1763                 EDBM_verts_mirror_cache_begin(em, 0, false, true, use_topology);
1764         }
1765
1766         repeat = RNA_int_get(op->ptr, "repeat");
1767         lambda_factor = RNA_float_get(op->ptr, "lambda_factor");
1768         lambda_border = RNA_float_get(op->ptr, "lambda_border");
1769         usex = RNA_boolean_get(op->ptr, "use_x");
1770         usey = RNA_boolean_get(op->ptr, "use_y");
1771         usez = RNA_boolean_get(op->ptr, "use_z");
1772         preserve_volume = RNA_boolean_get(op->ptr, "preserve_volume");
1773         if (!repeat)
1774                 repeat = 1;
1775         
1776         for (i = 0; i < repeat; i++) {
1777                 if (!EDBM_op_callf(em, op,
1778                                    "smooth_laplacian_vert verts=%hv lambda_factor=%f lambda_border=%f use_x=%b use_y=%b use_z=%b preserve_volume=%b",
1779                                    BM_ELEM_SELECT, lambda_factor, lambda_border, usex, usey, usez, preserve_volume))
1780                 {
1781                         return OPERATOR_CANCELLED;
1782                 }
1783         }
1784
1785         /* apply mirror */
1786         if (((Mesh *)obedit->data)->editflag & ME_EDIT_MIRROR_X) {
1787                 EDBM_verts_mirror_apply(em, BM_ELEM_SELECT, 0);
1788                 EDBM_verts_mirror_cache_end(em);
1789         }
1790
1791         EDBM_update_generic(em, true, false);
1792
1793         return OPERATOR_FINISHED;
1794 }
1795
1796 void MESH_OT_vertices_smooth_laplacian(wmOperatorType *ot)
1797 {
1798         /* identifiers */
1799         ot->name = "Laplacian Smooth Vertex";
1800         ot->description = "Laplacian smooth of selected vertices";
1801         ot->idname = "MESH_OT_vertices_smooth_laplacian";
1802         
1803         /* api callbacks */
1804         ot->exec = edbm_do_smooth_laplacian_vertex_exec;
1805         ot->poll = ED_operator_editmesh;
1806         
1807         /* flags */
1808         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1809
1810         RNA_def_int(ot->srna, "repeat", 1, 1, 200,
1811                     "Number of iterations to smooth the mesh", "", 1, 200);
1812         RNA_def_float(ot->srna, "lambda_factor", 0.00005f, 0.0000001f, 1000.0f,
1813                       "Lambda factor", "", 0.0000001f, 1000.0f);
1814         RNA_def_float(ot->srna, "lambda_border", 0.00005f, 0.0000001f, 1000.0f,
1815                       "Lambda factor in border", "", 0.0000001f, 1000.0f);
1816         RNA_def_boolean(ot->srna, "use_x", 1, "Smooth X Axis", "Smooth object along X axis");
1817         RNA_def_boolean(ot->srna, "use_y", 1, "Smooth Y Axis", "Smooth object along Y axis");
1818         RNA_def_boolean(ot->srna, "use_z", 1, "Smooth Z Axis", "Smooth object along Z axis");
1819         RNA_def_boolean(ot->srna, "preserve_volume", 1, "Preserve Volume", "Apply volume preservation after smooth");
1820 }
1821
1822 /********************** Smooth/Solid Operators *************************/
1823
1824 static void mesh_set_smooth_faces(BMEditMesh *em, short smooth)
1825 {
1826         BMIter iter;
1827         BMFace *efa;
1828
1829         if (em == NULL) return;
1830         
1831         BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
1832                 if (BM_elem_flag_test(efa, BM_ELEM_SELECT)) {
1833                         BM_elem_flag_set(efa, BM_ELEM_SMOOTH, smooth);
1834                 }
1835         }
1836 }
1837
1838 static int edbm_faces_shade_smooth_exec(bContext *C, wmOperator *UNUSED(op))
1839 {
1840         Object *obedit = CTX_data_edit_object(C);
1841         BMEditMesh *em = BKE_editmesh_from_object(obedit);
1842
1843         mesh_set_smooth_faces(em, 1);
1844
1845         EDBM_update_generic(em, false, false);
1846
1847         return OPERATOR_FINISHED;
1848 }
1849
1850 void MESH_OT_faces_shade_smooth(wmOperatorType *ot)
1851 {
1852         /* identifiers */
1853         ot->name = "Shade Smooth";
1854         ot->description = "Display faces smooth (using vertex normals)";
1855         ot->idname = "MESH_OT_faces_shade_smooth";
1856
1857         /* api callbacks */
1858         ot->exec = edbm_faces_shade_smooth_exec;
1859         ot->poll = ED_operator_editmesh;
1860
1861         /* flags */
1862         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1863 }
1864
1865 static int edbm_faces_shade_flat_exec(bContext *C, wmOperator *UNUSED(op))
1866 {
1867         Object *obedit = CTX_data_edit_object(C);
1868         BMEditMesh *em = BKE_editmesh_from_object(obedit);
1869
1870         mesh_set_smooth_faces(em, 0);
1871
1872         EDBM_update_generic(em, false, false);
1873
1874         return OPERATOR_FINISHED;
1875 }
1876
1877 void MESH_OT_faces_shade_flat(wmOperatorType *ot)
1878 {
1879         /* identifiers */
1880         ot->name = "Shade Flat";
1881         ot->description = "Display faces flat";
1882         ot->idname = "MESH_OT_faces_shade_flat";
1883
1884         /* api callbacks */
1885         ot->exec = edbm_faces_shade_flat_exec;
1886         ot->poll = ED_operator_editmesh;
1887
1888         /* flags */
1889         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1890 }
1891
1892
1893 /********************** UV/Color Operators *************************/
1894
1895 static int edbm_rotate_uvs_exec(bContext *C, wmOperator *op)
1896 {
1897         Object *ob = CTX_data_edit_object(C);
1898         BMEditMesh *em = BKE_editmesh_from_object(ob);
1899         BMOperator bmop;
1900
1901         /* get the direction from RNA */
1902         const bool use_ccw = RNA_boolean_get(op->ptr, "use_ccw");
1903
1904         /* initialize the bmop using EDBM api, which does various ui error reporting and other stuff */
1905         EDBM_op_init(em, &bmop, op, "rotate_uvs faces=%hf use_ccw=%b", BM_ELEM_SELECT, use_ccw);
1906
1907         /* execute the operator */
1908         BMO_op_exec(em->bm, &bmop);
1909
1910         /* finish the operator */
1911         if (!EDBM_op_finish(em, &bmop, op, true)) {
1912                 return OPERATOR_CANCELLED;
1913         }
1914
1915         EDBM_update_generic(em, false, false);
1916
1917         return OPERATOR_FINISHED;
1918 }
1919
1920 static int edbm_reverse_uvs_exec(bContext *C, wmOperator *op)
1921 {
1922         Object *ob = CTX_data_edit_object(C);
1923         BMEditMesh *em = BKE_editmesh_from_object(ob);
1924         BMOperator bmop;
1925
1926         /* initialize the bmop using EDBM api, which does various ui error reporting and other stuff */
1927         EDBM_op_init(em, &bmop, op, "reverse_uvs faces=%hf", BM_ELEM_SELECT);
1928
1929         /* execute the operator */
1930         BMO_op_exec(em->bm, &bmop);
1931
1932         /* finish the operator */
1933         if (!EDBM_op_finish(em, &bmop, op, true)) {
1934                 return OPERATOR_CANCELLED;
1935         }
1936
1937         EDBM_update_generic(em, false, false);
1938
1939         return OPERATOR_FINISHED;
1940 }
1941
1942 static int edbm_rotate_colors_exec(bContext *C, wmOperator *op)
1943 {
1944         Object *ob = CTX_data_edit_object(C);
1945         BMEditMesh *em = BKE_editmesh_from_object(ob);
1946         BMOperator bmop;
1947
1948         /* get the direction from RNA */
1949         const bool use_ccw = RNA_boolean_get(op->ptr, "use_ccw");
1950
1951         /* initialize the bmop using EDBM api, which does various ui error reporting and other stuff */
1952         EDBM_op_init(em, &bmop, op, "rotate_colors faces=%hf use_ccw=%b", BM_ELEM_SELECT, use_ccw);
1953
1954         /* execute the operator */
1955         BMO_op_exec(em->bm, &bmop);
1956
1957         /* finish the operator */
1958         if (!EDBM_op_finish(em, &bmop, op, true)) {
1959                 return OPERATOR_CANCELLED;
1960         }
1961
1962         /* dependencies graph and notification stuff */
1963         EDBM_update_generic(em, false, false);
1964
1965         return OPERATOR_FINISHED;
1966 }
1967
1968
1969 static int edbm_reverse_colors_exec(bContext *C, wmOperator *op)
1970 {
1971         Object *ob = CTX_data_edit_object(C);
1972         BMEditMesh *em = BKE_editmesh_from_object(ob);
1973         BMOperator bmop;
1974
1975         /* initialize the bmop using EDBM api, which does various ui error reporting and other stuff */
1976         EDBM_op_init(em, &bmop, op, "reverse_colors faces=%hf", BM_ELEM_SELECT);
1977
1978         /* execute the operator */
1979         BMO_op_exec(em->bm, &bmop);
1980
1981         /* finish the operator */
1982         if (!EDBM_op_finish(em, &bmop, op, true)) {
1983                 return OPERATOR_CANCELLED;
1984         }
1985
1986         EDBM_update_generic(em, false, false);
1987
1988         return OPERATOR_FINISHED;
1989 }
1990
1991 void MESH_OT_uvs_rotate(wmOperatorType *ot)
1992 {
1993         /* identifiers */
1994         ot->name = "Rotate UVs";
1995         ot->idname = "MESH_OT_uvs_rotate";
1996         ot->description = "Rotate UV coordinates inside faces";
1997
1998         /* api callbacks */
1999         ot->exec = edbm_rotate_uvs_exec;
2000         ot->poll = ED_operator_editmesh;
2001
2002         /* flags */
2003         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2004
2005         /* props */
2006         RNA_def_boolean(ot->srna, "use_ccw", false, "Counter Clockwise", "");
2007 }
2008
2009 void MESH_OT_uvs_reverse(wmOperatorType *ot)
2010 {
2011         /* identifiers */
2012         ot->name = "Reverse UVs";
2013         ot->idname = "MESH_OT_uvs_reverse";
2014         ot->description = "Flip direction of UV coordinates inside faces";
2015
2016         /* api callbacks */
2017         ot->exec = edbm_reverse_uvs_exec;
2018         ot->poll = ED_operator_editmesh;
2019
2020         /* flags */
2021         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2022
2023         /* props */
2024         //RNA_def_enum(ot->srna, "axis", axis_items, DIRECTION_CW, "Axis", "Axis to mirror UVs around");
2025 }
2026
2027 void MESH_OT_colors_rotate(wmOperatorType *ot)
2028 {
2029         /* identifiers */
2030         ot->name = "Rotate Colors";
2031         ot->idname = "MESH_OT_colors_rotate";
2032         ot->description = "Rotate vertex colors inside faces";
2033
2034         /* api callbacks */
2035         ot->exec = edbm_rotate_colors_exec;
2036         ot->poll = ED_operator_editmesh;
2037
2038         /* flags */
2039         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2040
2041         /* props */
2042         RNA_def_boolean(ot->srna, "use_ccw", false, "Counter Clockwise", "");
2043 }
2044
2045 void MESH_OT_colors_reverse(wmOperatorType *ot)
2046 {
2047         /* identifiers */
2048         ot->name = "Reverse Colors";
2049         ot->idname = "MESH_OT_colors_reverse";
2050         ot->description = "Flip direction of vertex colors inside faces";
2051
2052         /* api callbacks */
2053         ot->exec = edbm_reverse_colors_exec;
2054         ot->poll = ED_operator_editmesh;
2055
2056         /* flags */
2057         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2058
2059         /* props */
2060         //RNA_def_enum(ot->srna, "axis", axis_items, DIRECTION_CW, "Axis", "Axis to mirror colors around");
2061 }
2062
2063
2064 static bool merge_firstlast(BMEditMesh *em, const bool use_first, const bool use_uvmerge, wmOperator *wmop)
2065 {
2066         BMVert *mergevert;
2067         BMEditSelection *ese;
2068
2069         /* operator could be called directly from shortcut or python,
2070          * so do extra check for data here
2071          */
2072
2073         /* do sanity check in mergemenu in edit.c ?*/
2074         if (use_first == false) {
2075                 if (!em->bm->selected.last || ((BMEditSelection *)em->bm->selected.last)->htype != BM_VERT)
2076                         return false;
2077
2078                 ese = em->bm->selected.last;
2079                 mergevert = (BMVert *)ese->ele;
2080         }
2081         else {
2082                 if (!em->bm->selected.first || ((BMEditSelection *)em->bm->selected.first)->htype != BM_VERT)
2083                         return false;
2084
2085                 ese = em->bm->selected.first;
2086                 mergevert = (BMVert *)ese->ele;
2087         }
2088
2089         if (!BM_elem_flag_test(mergevert, BM_ELEM_SELECT))
2090                 return false;
2091         
2092         if (use_uvmerge) {
2093                 if (!EDBM_op_callf(em, wmop, "pointmerge_facedata verts=%hv vert_snap=%e", BM_ELEM_SELECT, mergevert))
2094                         return false;
2095         }
2096
2097         if (!EDBM_op_callf(em, wmop, "pointmerge verts=%hv merge_co=%v", BM_ELEM_SELECT, mergevert->co))
2098                 return false;
2099
2100         return true;
2101 }
2102
2103 static bool merge_target(BMEditMesh *em, Scene *scene, View3D *v3d, Object *ob,
2104                          const bool use_cursor, const bool use_uvmerge, wmOperator *wmop)
2105 {
2106         BMIter iter;
2107         BMVert *v;
2108         float co[3], cent[3] = {0.0f, 0.0f, 0.0f};
2109         const float *vco = NULL;
2110
2111         if (use_cursor) {
2112                 vco = ED_view3d_cursor3d_get(scene, v3d);
2113                 copy_v3_v3(co, vco);
2114                 mul_m4_v3(ob->imat, co);
2115         }
2116         else {
2117                 float fac;
2118                 int i = 0;
2119                 BM_ITER_MESH (v, &iter, em->bm, BM_VERTS_OF_MESH) {
2120                         if (!BM_elem_flag_test(v, BM_ELEM_SELECT))
2121                                 continue;
2122                         add_v3_v3(cent, v->co);
2123                         i++;
2124                 }
2125                 
2126                 if (!i)
2127                         return false;
2128
2129                 fac = 1.0f / (float)i;
2130                 mul_v3_fl(cent, fac);
2131                 copy_v3_v3(co, cent);
2132                 vco = co;
2133         }
2134
2135         if (!vco)
2136                 return false;
2137         
2138         if (use_uvmerge) {
2139                 if (!EDBM_op_callf(em, wmop, "average_vert_facedata verts=%hv", BM_ELEM_SELECT))
2140                         return false;
2141         }
2142
2143         if (!EDBM_op_callf(em, wmop, "pointmerge verts=%hv merge_co=%v", BM_ELEM_SELECT, co))
2144                 return false;
2145
2146         return true;
2147 }
2148
2149 static int edbm_merge_exec(bContext *C, wmOperator *op)
2150 {
2151         Scene *scene = CTX_data_scene(C);
2152         View3D *v3d = CTX_wm_view3d(C);
2153         Object *obedit = CTX_data_edit_object(C);
2154         BMEditMesh *em = BKE_editmesh_from_object(obedit);
2155         const int type = RNA_enum_get(op->ptr, "type");
2156         const bool uvs = RNA_boolean_get(op->ptr, "uvs");
2157         bool ok = false;
2158
2159         switch (type) {
2160                 case 3:
2161                         ok = merge_target(em, scene, v3d, obedit, false, uvs, op);
2162                         break;
2163                 case 4:
2164                         ok = merge_target(em, scene, v3d, obedit, true, uvs, op);
2165                         break;
2166                 case 1:
2167                         ok = merge_firstlast(em, false, uvs, op);
2168                         break;
2169                 case 6:
2170                         ok = merge_firstlast(em, true, uvs, op);
2171                         break;
2172                 case 5:
2173                         ok = EDBM_op_callf(em, op, "collapse edges=%he uvs=%b", BM_ELEM_SELECT, uvs);
2174                         break;
2175                 default:
2176                         BLI_assert(0);
2177                         break;
2178         }
2179
2180         if (!ok) {
2181                 return OPERATOR_CANCELLED;
2182         }
2183
2184         EDBM_update_generic(em, true, true);
2185
2186         return OPERATOR_FINISHED;
2187 }
2188
2189 static EnumPropertyItem merge_type_items[] = {
2190         {6, "FIRST", 0, "At First", ""},
2191         {1, "LAST", 0, "At Last", ""},
2192         {3, "CENTER", 0, "At Center", ""},
2193         {4, "CURSOR", 0, "At Cursor", ""},
2194         {5, "COLLAPSE", 0, "Collapse", ""},
2195         {0, NULL, 0, NULL, NULL}
2196 };
2197
2198 static EnumPropertyItem *merge_type_itemf(bContext *C, PointerRNA *UNUSED(ptr),  PropertyRNA *UNUSED(prop), bool *r_free)
2199 {       
2200         Object *obedit;
2201         EnumPropertyItem *item = NULL;
2202         int totitem = 0;
2203         
2204         if (!C) /* needed for docs */
2205                 return merge_type_items;
2206         
2207         obedit = CTX_data_edit_object(C);
2208         if (obedit && obedit->type == OB_MESH) {
2209                 BMEditMesh *em = BKE_editmesh_from_object(obedit);
2210
2211                 if (em->selectmode & SCE_SELECT_VERTEX) {
2212                         if (em->bm->selected.first && em->bm->selected.last &&
2213                             ((BMEditSelection *)em->bm->selected.first)->htype == BM_VERT &&
2214                             ((BMEditSelection *)em->bm->selected.last)->htype == BM_VERT)
2215                         {
2216                                 RNA_enum_items_add_value(&item, &totitem, merge_type_items, 6);
2217                                 RNA_enum_items_add_value(&item, &totitem, merge_type_items, 1);
2218                         }
2219                         else if (em->bm->selected.first && ((BMEditSelection *)em->bm->selected.first)->htype == BM_VERT) {
2220                                 RNA_enum_items_add_value(&item, &totitem, merge_type_items, 6);
2221                         }
2222                         else if (em->bm->selected.last && ((BMEditSelection *)em->bm->selected.last)->htype == BM_VERT) {
2223                                 RNA_enum_items_add_value(&item, &totitem, merge_type_items, 1);
2224                         }
2225                 }
2226
2227                 RNA_enum_items_add_value(&item, &totitem, merge_type_items, 3);
2228                 RNA_enum_items_add_value(&item, &totitem, merge_type_items, 4);
2229                 RNA_enum_items_add_value(&item, &totitem, merge_type_items, 5);
2230                 RNA_enum_item_end(&item, &totitem);
2231
2232                 *r_free = true;
2233
2234                 return item;
2235         }
2236         
2237         return NULL;
2238 }
2239
2240 void MESH_OT_merge(wmOperatorType *ot)
2241 {
2242         /* identifiers */
2243         ot->name = "Merge";
2244         ot->description = "Merge selected vertices";
2245         ot->idname = "MESH_OT_merge";
2246
2247         /* api callbacks */
2248         ot->exec = edbm_merge_exec;
2249         ot->invoke = WM_menu_invoke;
2250         ot->poll = ED_operator_editmesh;
2251
2252         /* flags */
2253         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2254
2255         /* properties */
2256         ot->prop = RNA_def_enum(ot->srna, "type", merge_type_items, 3, "Type", "Merge method to use");
2257         RNA_def_enum_funcs(ot->prop, merge_type_itemf);
2258         RNA_def_boolean(ot->srna, "uvs", 0, "UVs", "Move UVs according to merge");
2259 }
2260
2261
2262 static int edbm_remove_doubles_exec(bContext *C, wmOperator *op)
2263 {
2264         Object *obedit = CTX_data_edit_object(C);
2265         BMEditMesh *em = BKE_editmesh_from_object(obedit);
2266         BMOperator bmop;
2267         const float threshold = RNA_float_get(op->ptr, "threshold");
2268         const bool use_unselected = RNA_boolean_get(op->ptr, "use_unselected");
2269         const int totvert_orig = em->bm->totvert;
2270         int count;
2271         char htype_select;
2272
2273         /* avoid loosing selection state (select -> tags) */
2274         if      (em->selectmode & SCE_SELECT_VERTEX) htype_select = BM_VERT;
2275         else if (em->selectmode & SCE_SELECT_EDGE)   htype_select = BM_EDGE;
2276         else                                         htype_select = BM_FACE;
2277
2278         /* store selection as tags */
2279         BM_mesh_elem_hflag_enable_test(em->bm, htype_select, BM_ELEM_TAG, true, true, BM_ELEM_SELECT);
2280
2281
2282         if (use_unselected) {
2283                 EDBM_op_init(em, &bmop, op,
2284                              "automerge verts=%hv dist=%f",
2285                              BM_ELEM_SELECT, threshold);
2286                 BMO_op_exec(em->bm, &bmop);
2287
2288                 if (!EDBM_op_finish(em, &bmop, op, true)) {
2289                         return OPERATOR_CANCELLED;
2290                 }
2291         }
2292         else {
2293                 EDBM_op_init(em, &bmop, op,
2294                              "find_doubles verts=%hv dist=%f",
2295                              BM_ELEM_SELECT, threshold);
2296                 BMO_op_exec(em->bm, &bmop);
2297
2298                 if (!EDBM_op_callf(em, op, "weld_verts targetmap=%S", &bmop, "targetmap.out")) {
2299                         BMO_op_finish(em->bm, &bmop);
2300                         return OPERATOR_CANCELLED;
2301                 }
2302
2303                 if (!EDBM_op_finish(em, &bmop, op, true)) {
2304                         return OPERATOR_CANCELLED;
2305                 }
2306         }
2307         
2308         count = totvert_orig - em->bm->totvert;
2309         BKE_reportf(op->reports, RPT_INFO, "Removed %d vertices", count);
2310
2311         /* restore selection from tags */
2312         BM_mesh_elem_hflag_enable_test(em->bm, htype_select, BM_ELEM_SELECT, true, true, BM_ELEM_TAG);
2313         EDBM_selectmode_flush(em);
2314
2315         EDBM_update_generic(em, true, true);
2316
2317         return OPERATOR_FINISHED;
2318 }
2319
2320 void MESH_OT_remove_doubles(wmOperatorType *ot)
2321 {
2322         /* identifiers */
2323         ot->name = "Remove Doubles";
2324         ot->description = "Remove duplicate vertices";
2325         ot->idname = "MESH_OT_remove_doubles";
2326
2327         /* api callbacks */
2328         ot->exec = edbm_remove_doubles_exec;
2329         ot->poll = ED_operator_editmesh;
2330
2331         /* flags */
2332         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2333
2334         RNA_def_float(ot->srna, "threshold", 0.0001f, 0.000001f, 50.0f,  "Merge Distance",
2335                       "Minimum distance between elements to merge", 0.00001, 10.0);
2336         RNA_def_boolean(ot->srna, "use_unselected", 0, "Unselected", "Merge selected to other unselected vertices");
2337 }
2338
2339
2340 /************************ Shape Operators *************************/
2341
2342 /* BMESH_TODO this should be properly encapsulated in a bmop.  but later.*/
2343 static void shape_propagate(BMEditMesh *em, wmOperator *op)
2344 {
2345         BMIter iter;
2346         BMVert *eve = NULL;
2347         float *co;
2348         int i, totshape = CustomData_number_of_layers(&em->bm->vdata, CD_SHAPEKEY);
2349
2350         if (!CustomData_has_layer(&em->bm->vdata, CD_SHAPEKEY)) {
2351                 BKE_report(op->reports, RPT_ERROR, "Mesh does not have shape keys");
2352                 return;
2353         }
2354         
2355         BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
2356                 if (!BM_elem_flag_test(eve, BM_ELEM_SELECT) || BM_elem_flag_test(eve, BM_ELEM_HIDDEN))
2357                         continue;
2358
2359                 for (i = 0; i < totshape; i++) {
2360                         co = CustomData_bmesh_get_n(&em->bm->vdata, eve->head.data, CD_SHAPEKEY, i);
2361                         copy_v3_v3(co, eve->co);
2362                 }
2363         }
2364
2365 #if 0
2366         //TAG Mesh Objects that share this data
2367         for (base = scene->base.first; base; base = base->next) {
2368                 if (base->object && base->object->data == me) {
2369                         DAG_id_tag_update(&base->object->id, OB_RECALC_DATA);
2370                 }
2371         }
2372 #endif
2373 }
2374
2375
2376 static int edbm_shape_propagate_to_all_exec(bContext *C, wmOperator *op)
2377 {
2378         Object *obedit = CTX_data_edit_object(C);
2379         Mesh *me = obedit->data;
2380         BMEditMesh *em = me->edit_btmesh;
2381
2382         shape_propagate(em, op);
2383
2384         EDBM_update_generic(em, false, false);
2385
2386         return OPERATOR_FINISHED;
2387 }
2388
2389
2390 void MESH_OT_shape_propagate_to_all(wmOperatorType *ot)
2391 {
2392         /* identifiers */
2393         ot->name = "Shape Propagate";
2394         ot->description = "Apply selected vertex locations to all other shape keys";
2395         ot->idname = "MESH_OT_shape_propagate_to_all";
2396
2397         /* api callbacks */
2398         ot->exec = edbm_shape_propagate_to_all_exec;
2399         ot->poll = ED_operator_editmesh;
2400
2401         /* flags */
2402         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2403 }
2404
2405 /* BMESH_TODO this should be properly encapsulated in a bmop.  but later.*/
2406 static int edbm_blend_from_shape_exec(bContext *C, wmOperator *op)
2407 {
2408         Object *obedit = CTX_data_edit_object(C);
2409         Mesh *me = obedit->data;
2410         Key *key = me->key;
2411         KeyBlock *kb = NULL;
2412         BMEditMesh *em = me->edit_btmesh;
2413         BMVert *eve;
2414         BMIter iter;
2415         float co[3], *sco;
2416         int totshape;
2417
2418         const float blend = RNA_float_get(op->ptr, "blend");
2419         const int shape = RNA_enum_get(op->ptr, "shape");
2420         const bool use_add = RNA_boolean_get(op->ptr, "add");
2421
2422         /* sanity check */
2423         totshape = CustomData_number_of_layers(&em->bm->vdata, CD_SHAPEKEY);
2424         if (totshape == 0 || shape < 0 || shape >= totshape)
2425                 return OPERATOR_CANCELLED;
2426
2427         /* get shape key - needed for finding reference shape (for add mode only) */
2428         if (key) {
2429                 kb = BLI_findlink(&key->block, shape);
2430         }
2431         
2432         /* perform blending on selected vertices*/
2433         BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
2434                 if (!BM_elem_flag_test(eve, BM_ELEM_SELECT) || BM_elem_flag_test(eve, BM_ELEM_HIDDEN))
2435                         continue;
2436                 
2437                 /* get coordinates of shapekey we're blending from */
2438                 sco = CustomData_bmesh_get_n(&em->bm->vdata, eve->head.data, CD_SHAPEKEY, shape);
2439                 copy_v3_v3(co, sco);
2440                 
2441                 if (use_add) {
2442                         /* in add mode, we add relative shape key offset */
2443                         if (kb) {
2444                                 const float *rco = CustomData_bmesh_get_n(&em->bm->vdata, eve->head.data, CD_SHAPEKEY, kb->relative);
2445                                 sub_v3_v3v3(co, co, rco);
2446                         }
2447                         
2448                         madd_v3_v3fl(eve->co, co, blend);
2449                 }
2450                 else {
2451                         /* in blend mode, we interpolate to the shape key */
2452                         interp_v3_v3v3(eve->co, eve->co, co, blend);
2453                 }
2454         }
2455
2456         EDBM_update_generic(em, true, false);
2457
2458         return OPERATOR_FINISHED;
2459 }
2460
2461 static EnumPropertyItem *shape_itemf(bContext *C, PointerRNA *UNUSED(ptr),  PropertyRNA *UNUSED(prop), bool *r_free)
2462 {       
2463         Object *obedit = CTX_data_edit_object(C);
2464         BMEditMesh *em;
2465         EnumPropertyItem *item = NULL;
2466         int totitem = 0;
2467
2468         if ((obedit && obedit->type == OB_MESH) &&
2469             (em = BKE_editmesh_from_object(obedit)) &&
2470             CustomData_has_layer(&em->bm->vdata, CD_SHAPEKEY))
2471         {
2472                 EnumPropertyItem tmp = {0, "", 0, "", ""};
2473                 int a;
2474
2475                 for (a = 0; a < em->bm->vdata.totlayer; a++) {
2476                         if (em->bm->vdata.layers[a].type != CD_SHAPEKEY)
2477                                 continue;
2478
2479                         tmp.value = totitem;
2480                         tmp.identifier = em->bm->vdata.layers[a].name;
2481                         tmp.name = em->bm->vdata.layers[a].name;
2482                         /* RNA_enum_item_add sets totitem itself! */
2483                         RNA_enum_item_add(&item, &totitem, &tmp);
2484                 }
2485         }
2486
2487         RNA_enum_item_end(&item, &totitem);
2488         *r_free = true;
2489
2490         return item;
2491 }
2492
2493 static void edbm_blend_from_shape_ui(bContext *C, wmOperator *op)
2494 {
2495         uiLayout *layout = op->layout;
2496         PointerRNA ptr;
2497         Object *obedit = CTX_data_edit_object(C);
2498         Mesh *me = obedit->data;
2499         PointerRNA ptr_key;
2500
2501         RNA_pointer_create(NULL, op->type->srna, op->properties, &ptr);
2502         RNA_id_pointer_create((ID *)me->key, &ptr_key);
2503
2504         uiItemPointerR(layout, &ptr, "shape", &ptr_key, "key_blocks", "", ICON_SHAPEKEY_DATA);
2505         uiItemR(layout, &ptr, "blend", 0, NULL, ICON_NONE);
2506         uiItemR(layout, &ptr, "add", 0, NULL, ICON_NONE);
2507 }
2508
2509 void MESH_OT_blend_from_shape(wmOperatorType *ot)
2510 {
2511         PropertyRNA *prop;
2512
2513         /* identifiers */
2514         ot->name = "Blend From Shape";
2515         ot->description = "Blend in shape from a shape key";
2516         ot->idname = "MESH_OT_blend_from_shape";
2517
2518         /* api callbacks */
2519         ot->exec = edbm_blend_from_shape_exec;
2520 //      ot->invoke = WM_operator_props_popup_call;  /* disable because search popup closes too easily */
2521         ot->ui = edbm_blend_from_shape_ui;
2522         ot->poll = ED_operator_editmesh;
2523
2524         /* flags */
2525         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2526
2527         /* properties */
2528         prop = RNA_def_enum(ot->srna, "shape", DummyRNA_NULL_items, 0, "Shape", "Shape key to use for blending");
2529         RNA_def_enum_funcs(prop, shape_itemf);
2530         RNA_def_property_flag(prop, PROP_ENUM_NO_TRANSLATE | PROP_NEVER_UNLINK);
2531         RNA_def_float(ot->srna, "blend", 1.0f, -FLT_MAX, FLT_MAX, "Blend", "Blending factor", -2.0f, 2.0f);
2532         RNA_def_boolean(ot->srna, "add", 1, "Add", "Add rather than blend between shapes");
2533 }
2534
2535 static int edbm_solidify_exec(bContext *C, wmOperator *op)
2536 {
2537         Object *obedit = CTX_data_edit_object(C);
2538         Mesh *me = obedit->data;
2539         BMEditMesh *em = me->edit_btmesh;
2540         BMesh *bm = em->bm;
2541         BMOperator bmop;
2542
2543         const float thickness = RNA_float_get(op->ptr, "thickness");
2544
2545         if (!EDBM_op_init(em, &bmop, op, "solidify geom=%hf thickness=%f", BM_ELEM_SELECT, thickness)) {
2546                 return OPERATOR_CANCELLED;
2547         }
2548
2549         /* deselect only the faces in the region to be solidified (leave wire
2550          * edges and loose verts selected, as there will be no corresponding
2551          * geometry selected below) */
2552         BMO_slot_buffer_hflag_disable(bm, bmop.slots_in, "geom", BM_FACE, BM_ELEM_SELECT, true);
2553
2554         /* run the solidify operator */
2555         BMO_op_exec(bm, &bmop);
2556
2557         /* select the newly generated faces */
2558         BMO_slot_buffer_hflag_enable(bm, bmop.slots_out, "geom.out", BM_FACE, BM_ELEM_SELECT, true);
2559
2560         if (!EDBM_op_finish(em, &bmop, op, true)) {
2561                 return OPERATOR_CANCELLED;
2562         }
2563
2564         EDBM_update_generic(em, true, true);
2565
2566         return OPERATOR_FINISHED;
2567 }
2568
2569
2570 void MESH_OT_solidify(wmOperatorType *ot)
2571 {
2572         PropertyRNA *prop;
2573         /* identifiers */
2574         ot->name = "Solidify";
2575         ot->description = "Create a solid skin by extruding, compensating for sharp angles";
2576         ot->idname = "MESH_OT_solidify";
2577
2578         /* api callbacks */
2579         ot->exec = edbm_solidify_exec;
2580         ot->poll = ED_operator_editmesh;
2581
2582         /* flags */
2583         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2584
2585         prop = RNA_def_float(ot->srna, "thickness", 0.01f, -FLT_MAX, FLT_MAX, "thickness", "", -10.0f, 10.0f);
2586         RNA_def_property_ui_range(prop, -10, 10, 0.1, 4);
2587 }
2588
2589 /* ******************************************************************** */
2590 /* Knife Subdivide Tool.  Subdivides edges intersected by a mouse trail
2591  * drawn by user.
2592  *
2593  * Currently mapped to KKey when in MeshEdit mode.
2594  * Usage:
2595  * - Hit Shift K, Select Centers or Exact
2596  * - Hold LMB down to draw path, hit RETKEY.
2597  * - ESC cancels as expected.
2598  *
2599  * Contributed by Robert Wenzlaff (Det. Thorn).
2600  *
2601  * 2.5 Revamp:
2602  *  - non modal (no menu before cutting)
2603  *  - exit on mouse release
2604  *  - polygon/segment drawing can become handled by WM cb later
2605  *
2606  * bmesh port version
2607  */
2608
2609 #define KNIFE_EXACT     1
2610 #define KNIFE_MIDPOINT  2
2611 #define KNIFE_MULTICUT  3
2612
2613 static EnumPropertyItem knife_items[] = {
2614         {KNIFE_EXACT, "EXACT", 0, "Exact", ""},
2615         {KNIFE_MIDPOINT, "MIDPOINTS", 0, "Midpoints", ""},
2616         {KNIFE_MULTICUT, "MULTICUT", 0, "Multicut", ""},
2617         {0, NULL, 0, NULL, NULL}
2618 };
2619
2620 /* bm_edge_seg_isect() Determines if and where a mouse trail intersects an BMEdge */
2621
2622 static float bm_edge_seg_isect(const float sco_a[2], const float sco_b[2],
2623                                float (*mouse_path)[2], int len, char mode, int *isected)
2624 {
2625 #define MAXSLOPE 100000
2626         float x11, y11, x12 = 0, y12 = 0, x2max, x2min, y2max;
2627         float y2min, dist, lastdist = 0, xdiff2, xdiff1;
2628         float m1, b1, m2, b2, x21, x22, y21, y22, xi;
2629         float yi, x1min, x1max, y1max, y1min, perc = 0;
2630         float threshold = 0.0;
2631         int i;
2632         
2633         //threshold = 0.000001; /* tolerance for vertex intersection */
2634         // XXX threshold = scene->toolsettings->select_thresh / 100;
2635         
2636         /* Get screen coords of verts */
2637         x21 = sco_a[0];
2638         y21 = sco_a[1];
2639         
2640         x22 = sco_b[0];
2641         y22 = sco_b[1];
2642         
2643         xdiff2 = (x22 - x21);
2644         if (xdiff2) {
2645                 m2 = (y22 - y21) / xdiff2;
2646                 b2 = ((x22 * y21) - (x21 * y22)) / xdiff2;
2647         }
2648         else {
2649                 m2 = MAXSLOPE;  /* Verticle slope  */
2650                 b2 = x22;
2651         }
2652
2653         *isected = 0;
2654
2655         /* check for _exact_ vertex intersection first */
2656         if (mode != KNIFE_MULTICUT) {
2657                 for (i = 0; i < len; i++) {
2658                         if (i > 0) {
2659                                 x11 = x12;
2660                                 y11 = y12;
2661                         }
2662                         else {
2663                                 x11 = mouse_path[i][0];
2664                                 y11 = mouse_path[i][1];
2665                         }
2666                         x12 = mouse_path[i][0];
2667                         y12 = mouse_path[i][1];
2668                         
2669                         /* test e->v1 */
2670                         if ((x11 == x21 && y11 == y21) || (x12 == x21 && y12 == y21)) {
2671                                 perc = 0;
2672                                 *isected = 1;
2673                                 return perc;
2674                         }
2675                         /* test e->v2 */
2676                         else if ((x11 == x22 && y11 == y22) || (x12 == x22 && y12 == y22)) {
2677                                 perc = 0;
2678                                 *isected = 2;
2679                                 return perc;
2680                         }
2681                 }
2682         }
2683         
2684         /* now check for edge intersect (may produce vertex intersection as well) */
2685         for (i = 0; i < len; i++) {
2686                 if (i > 0) {
2687                         x11 = x12;
2688                         y11 = y12;
2689                 }
2690                 else {
2691                         x11 = mouse_path[i][0];
2692                         y11 = mouse_path[i][1];
2693                 }
2694                 x12 = mouse_path[i][0];
2695                 y12 = mouse_path[i][1];
2696                 
2697                 /* Perp. Distance from point to line */
2698                 if (m2 != MAXSLOPE) dist = (y12 - m2 * x12 - b2);  /* /sqrt(m2 * m2 + 1); Only looking for */
2699                 /* change in sign.  Skip extra math */
2700                 else dist = x22 - x12;
2701                 
2702                 if (i == 0) lastdist = dist;
2703                 
2704                 /* if dist changes sign, and intersect point in edge's Bound Box */
2705                 if ((lastdist * dist) <= 0) {
2706                         xdiff1 = (x12 - x11); /* Equation of line between last 2 points */
2707                         if (xdiff1) {
2708                                 m1 = (y12 - y11) / xdiff1;
2709                                 b1 = ((x12 * y11) - (x11 * y12)) / xdiff1;
2710                         }
2711                         else {
2712                                 m1 = MAXSLOPE;
2713                                 b1 = x12;
2714                         }
2715                         x2max = max_ff(x21, x22) + 0.001f; /* prevent missed edges   */
2716                         x2min = min_ff(x21, x22) - 0.001f; /* due to round off error */
2717                         y2max = max_ff(y21, y22) + 0.001f;
2718                         y2min = min_ff(y21, y22) - 0.001f;
2719                         
2720                         /* Found an intersect,  calc intersect point */
2721                         if (m1 == m2) { /* co-incident lines */
2722                                 /* cut at 50% of overlap area */
2723                                 x1max = max_ff(x11, x12);
2724                                 x1min = min_ff(x11, x12);
2725                                 xi = (min_ff(x2max, x1max) + max_ff(x2min, x1min)) / 2.0f;
2726                                 
2727                                 y1max = max_ff(y11, y12);
2728                                 y1min = min_ff(y11, y12);
2729                                 yi = (min_ff(y2max, y1max) + max_ff(y2min, y1min)) / 2.0f;
2730                         }
2731                         else if (m2 == MAXSLOPE) {
2732                                 xi = x22;
2733                                 yi = m1 * x22 + b1;
2734                         }
2735                         else if (m1 == MAXSLOPE) {
2736                                 xi = x12;
2737                                 yi = m2 * x12 + b2;
2738                         }
2739                         else {
2740                                 xi = (b1 - b2) / (m2 - m1);
2741                                 yi = (b1 * m2 - m1 * b2) / (m2 - m1);
2742                         }
2743                         
2744                         /* Intersect inside bounding box of edge?*/
2745                         if ((xi >= x2min) && (xi <= x2max) && (yi <= y2max) && (yi >= y2min)) {
2746                                 /* test for vertex intersect that may be 'close enough'*/
2747                                 if (mode != KNIFE_MULTICUT) {
2748                                         if (xi <= (x21 + threshold) && xi >= (x21 - threshold)) {
2749                                                 if (yi <= (y21 + threshold) && yi >= (y21 - threshold)) {
2750                                                         *isected = 1;
2751                                                         perc = 0;
2752                                                         break;
2753                                                 }
2754                                         }
2755                                         if (xi <= (x22 + threshold) && xi >= (x22 - threshold)) {
2756                                                 if (yi <= (y22 + threshold) && yi >= (y22 - threshold)) {
2757                                                         *isected = 2;
2758                                                         perc = 0;
2759                                                         break;
2760                                                 }
2761                                         }
2762                                 }
2763                                 if ((m2 <= 1.0f) && (m2 >= -1.0f)) perc = (xi - x21) / (x22 - x21);
2764                                 else perc = (yi - y21) / (y22 - y21);  /* lower slope more accurate */
2765                                 //isect = 32768.0 * (perc + 0.0000153); /* Percentage in 1 / 32768ths */
2766                                 
2767                                 break;
2768                         }
2769                 }
2770                 lastdist = dist;
2771         }
2772         return perc;
2773 }
2774
2775 #define ELE_EDGE_CUT 1
2776
2777 static int edbm_knife_cut_exec(bContext *C, wmOperator *op)
2778 {
2779         Object *obedit = CTX_data_edit_object(C);
2780         BMEditMesh *em = BKE_editmesh_from_object(obedit);
2781         BMesh *bm = em->bm;
2782         ARegion *ar = CTX_wm_region(C);
2783         BMVert *bv;
2784         BMIter iter;
2785         BMEdge *be;
2786         BMOperator bmop;
2787         float isect = 0.0f;
2788         int len = 0, isected, i;
2789         short numcuts = 1;
2790         const short mode = RNA_int_get(op->ptr, "type");
2791         BMOpSlot *slot_edge_percents;
2792
2793         /* allocd vars */
2794         float (*screen_vert_coords)[2], (*sco)[2], (*mouse_path)[2];
2795         
2796         /* edit-object needed for matrix, and ar->regiondata for projections to work */
2797         if (ELEM(NULL, obedit, ar, ar->regiondata))
2798                 return OPERATOR_CANCELLED;
2799         
2800         if (bm->totvertsel < 2) {
2801                 BKE_report(op->reports, RPT_ERROR, "No edges are selected to operate on");
2802                 return OPERATOR_CANCELLED;
2803         }
2804
2805         len = RNA_collection_length(op->ptr, "path");
2806
2807         if (len < 2) {
2808                 BKE_report(op->reports, RPT_ERROR, "Mouse path too short");
2809                 return OPERATOR_CANCELLED;
2810         }
2811
2812         mouse_path = MEM_mallocN(len * sizeof(*mouse_path), __func__);
2813
2814         /* get the cut curve */
2815         RNA_BEGIN (op->ptr, itemptr, "path")
2816         {
2817                 RNA_float_get_array(&itemptr, "loc", (float *)&mouse_path[len]);
2818         }
2819         RNA_END;
2820
2821         /* for ED_view3d_project_float_object */
2822         ED_view3d_init_mats_rv3d(obedit, ar->regiondata);
2823
2824         /* TODO, investigate using index lookup for screen_vert_coords() rather then a hash table */
2825
2826         /* the floating point coordinates of verts in screen space will be stored in a hash table according to the vertices pointer */
2827         screen_vert_coords = sco = MEM_mallocN(bm->totvert * sizeof(float) * 2, __func__);
2828
2829         BM_ITER_MESH_INDEX (bv, &iter, bm, BM_VERTS_OF_MESH, i) {
2830                 if (ED_view3d_project_float_object(ar, bv->co, *sco, V3D_PROJ_TEST_CLIP_NEAR) != V3D_PROJ_RET_OK) {
2831                         copy_v2_fl(*sco, FLT_MAX);  /* set error value */
2832                 }
2833                 BM_elem_index_set(bv, i); /* set_inline */
2834                 sco++;
2835
2836         }
2837         bm->elem_index_dirty &= ~BM_VERT; /* clear dirty flag */
2838
2839         if (!EDBM_op_init(em, &bmop, op, "subdivide_edges")) {
2840                 MEM_freeN(mouse_path);
2841                 MEM_freeN(screen_vert_coords);
2842                 return OPERATOR_CANCELLED;
2843         }
2844
2845         /* store percentage of edge cut for KNIFE_EXACT here.*/
2846         slot_edge_percents = BMO_slot_get(bmop.slots_in, "edge_percents");
2847         BM_ITER_MESH (be, &iter, bm, BM_EDGES_OF_MESH) {
2848                 bool is_cut = false;
2849                 if (BM_elem_flag_test(be, BM_ELEM_SELECT)) {
2850                         const float *sco_a = screen_vert_coords[BM_elem_index_get(be->v1)];
2851                         const float *sco_b = screen_vert_coords[BM_elem_index_get(be->v2)];
2852
2853                         /* check for error value (vert cant be projected) */
2854                         if ((sco_a[0] != FLT_MAX) && (sco_b[0] != FLT_MAX)) {
2855                                 isect = bm_edge_seg_isect(sco_a, sco_b, mouse_path, len, mode, &isected);
2856
2857                                 if (isect != 0.0f) {
2858                                         if (mode != KNIFE_MULTICUT && mode != KNIFE_MIDPOINT) {
2859                                                 BMO_slot_map_float_insert(&bmop, slot_edge_percents, be, isect);
2860                                         }
2861                                 }
2862                         }
2863                 }
2864
2865                 BMO_elem_flag_set(bm, be, ELE_EDGE_CUT, is_cut);
2866         }
2867
2868
2869         /* free all allocs */
2870         MEM_freeN(screen_vert_coords);
2871         MEM_freeN(mouse_path);
2872
2873
2874         BMO_slot_buffer_from_enabled_flag(bm, &bmop, bmop.slots_in, "edges", BM_EDGE, ELE_EDGE_CUT);
2875
2876         if (mode == KNIFE_MIDPOINT) numcuts = 1;
2877         BMO_slot_int_set(bmop.slots_in, "cuts", numcuts);
2878
2879         BMO_slot_int_set(bmop.slots_in, "quad_corner_type", SUBD_CORNER_STRAIGHT_CUT);
2880         BMO_slot_bool_set(bmop.slots_in, "use_single_edge", false);
2881         BMO_slot_bool_set(bmop.slots_in, "use_grid_fill", false);
2882
2883         BMO_slot_float_set(bmop.slots_in, "radius", 0);
2884         
2885         BMO_op_exec(bm, &bmop);
2886         if (!EDBM_op_finish(em, &bmop, op, true)) {
2887                 return OPERATOR_CANCELLED;
2888         }
2889
2890         EDBM_update_generic(em, true, true);
2891
2892         return OPERATOR_FINISHED;
2893 }
2894
2895 #undef ELE_EDGE_CUT
2896
2897 void MESH_OT_knife_cut(wmOperatorType *ot)
2898 {
2899         PropertyRNA *prop;
2900         
2901         ot->name = "Knife Cut";
2902         ot->description = "Cut selected edges and faces into parts";
2903         ot->idname = "MESH_OT_knife_cut";
2904         
2905         ot->invoke = WM_gesture_lines_invoke;
2906         ot->modal = WM_gesture_lines_modal;
2907         ot->exec = edbm_knife_cut_exec;
2908         
2909         ot->poll = EDBM_view3d_poll;
2910         
2911         /* flags */
2912         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2913         
2914         RNA_def_enum(ot->srna, "type", knife_items, KNIFE_EXACT, "Type", "");
2915         prop = RNA_def_property(ot->srna, "path", PROP_COLLECTION, PROP_NONE);
2916         RNA_def_property_struct_runtime(prop, &RNA_OperatorMousePath);
2917         
2918         /* internal */
2919         RNA_def_int(ot->srna, "cursor", BC_KNIFECURSOR, 0, INT_MAX, "Cursor", "", 0, INT_MAX);
2920 }
2921
2922 static Base *mesh_separate_tagged(Main *bmain, Scene *scene, Base *base_old, BMesh *bm_old)
2923 {
2924         Base *base_new;
2925         Object *obedit = base_old->object;
2926         BMesh *bm_new;
2927
2928         bm_new = BM_mesh_create(&bm_mesh_allocsize_default);
2929         BM_mesh_elem_toolflags_ensure(bm_new);  /* needed for 'duplicate' bmo */
2930
2931         CustomData_copy(&bm_old->vdata, &bm_new->vdata, CD_MASK_BMESH, CD_CALLOC, 0);
2932         CustomData_copy(&bm_old->edata, &bm_new->edata, CD_MASK_BMESH, CD_CALLOC, 0);
2933         CustomData_copy(&bm_old->ldata, &bm_new->ldata, CD_MASK_BMESH, CD_CALLOC, 0);
2934         CustomData_copy(&bm_old->pdata, &bm_new->pdata, CD_MASK_BMESH, CD_CALLOC, 0);
2935
2936         CustomData_bmesh_init_pool(&bm_new->vdata, bm_mesh_allocsize_default.totvert, BM_VERT);
2937         CustomData_bmesh_init_pool(&bm_new->edata, bm_mesh_allocsize_default.totedge, BM_EDGE);
2938         CustomData_bmesh_init_pool(&bm_new->ldata, bm_mesh_allocsize_default.totloop, BM_LOOP);
2939         CustomData_bmesh_init_pool(&bm_new->pdata, bm_mesh_allocsize_default.totface, BM_FACE);
2940
2941         base_new = ED_object_add_duplicate(bmain, scene, base_old, USER_DUP_MESH);
2942         /* DAG_relations_tag_update(bmain); */ /* normally would call directly after but in this case delay recalc */
2943         assign_matarar(base_new->object, give_matarar(obedit), *give_totcolp(obedit)); /* new in 2.5 */
2944
2945         ED_base_object_select(base_new, BA_SELECT);
2946
2947         BMO_op_callf(bm_old, (BMO_FLAG_DEFAULTS & ~BMO_FLAG_RESPECT_HIDE),
2948                      "duplicate geom=%hvef dest=%p", BM_ELEM_TAG, bm_new);
2949         BMO_op_callf(bm_old, (BMO_FLAG_DEFAULTS & ~BMO_FLAG_RESPECT_HIDE),
2950                      "delete geom=%hvef context=%i", BM_ELEM_TAG, DEL_FACES);
2951
2952         /* deselect loose data - this used to get deleted,
2953          * we could de-select edges and verts only, but this turns out to be less complicated
2954          * since de-selecting all skips selection flushing logic */
2955         BM_mesh_elem_hflag_disable_all(bm_old, BM_VERT | BM_EDGE | BM_FACE, BM_ELEM_SELECT, false);
2956
2957         BM_mesh_normals_update(bm_new);
2958
2959         BM_mesh_bm_to_me(bm_new, base_new->object->data, false);
2960
2961         BM_mesh_free(bm_new);
2962         ((Mesh *)base_new->object->data)->edit_btmesh = NULL;
2963         
2964         return base_new;
2965 }
2966
2967 static bool mesh_separate_selected(Main *bmain, Scene *scene, Base *base_old, BMesh *bm_old)
2968 {
2969         /* we may have tags from previous operators */
2970         BM_mesh_elem_hflag_disable_all(bm_old, BM_FACE | BM_EDGE | BM_VERT, BM_ELEM_TAG, false);
2971
2972         /* sel -> tag */
2973         BM_mesh_elem_hflag_enable_test(bm_old, BM_FACE | BM_EDGE | BM_VERT, BM_ELEM_TAG, true, false, BM_ELEM_SELECT);
2974
2975         return (mesh_separate_tagged(bmain, scene, base_old, bm_old) != NULL);
2976 }
2977
2978 /* flush a hflag to from verts to edges/faces */
2979 static void bm_mesh_hflag_flush_vert(BMesh *bm, const char hflag)
2980 {
2981         BMEdge *e;
2982         BMLoop *l_iter;
2983         BMLoop *l_first;
2984         BMFace *f;
2985
2986         BMIter eiter;
2987         BMIter fiter;
2988
2989         bool ok;
2990
2991         BM_ITER_MESH (e, &eiter, bm, BM_EDGES_OF_MESH) {
2992                 if (BM_elem_flag_test(e->v1, hflag) &&
2993                     BM_elem_flag_test(e->v2, hflag))
2994                 {
2995                         BM_elem_flag_enable(e, hflag);
2996                 }
2997                 else {
2998                         BM_elem_flag_disable(e, hflag);
2999                 }
3000         }
3001         BM_ITER_MESH (f, &fiter, bm, BM_FACES_OF_MESH) {
3002                 ok = true;
3003                 l_iter = l_first = BM_FACE_FIRST_LOOP(f);
3004                 do {
3005                         if (!BM_elem_flag_test(l_iter->v, hflag)) {
3006                                 ok = false;
3007                                 break;
3008                         }
3009                 } while ((l_iter = l_iter->next) != l_first);
3010
3011                 BM_elem_flag_set(f, hflag, ok);
3012         }
3013 }
3014
3015 /**
3016  * Sets an object to a single material. from one of its slots.
3017  *
3018  * \note This could be used for split-by-material for non mesh types.
3019  * \note This could take material data from another object or args.
3020  */
3021 static void mesh_separate_material_assign_mat_nr(Object *ob, const short mat_nr)
3022 {
3023         ID *obdata = ob->data;
3024
3025         Material ***matarar;
3026         const short *totcolp;
3027
3028         totcolp = give_totcolp_id(obdata);
3029         matarar = give_matarar_id(obdata);
3030
3031         if ((totcolp && matarar) == 0) {
3032                 BLI_assert(0);
3033                 return;
3034         }
3035
3036         if (*totcolp) {
3037                 Material *ma_ob;
3038                 Material *ma_obdata;
3039                 char matbit;
3040
3041                 if (mat_nr < ob->totcol) {
3042                         ma_ob = ob->mat[mat_nr];
3043                         matbit = ob->matbits[mat_nr];
3044                 }
3045                 else {
3046                         ma_ob = NULL;
3047                         matbit = 0;
3048                 }
3049
3050                 if (mat_nr < *totcolp) {
3051                         ma_obdata = (*matarar)[mat_nr];
3052                 }
3053                 else {
3054                         ma_obdata = NULL;
3055                 }
3056
3057                 BKE_material_clear_id(obdata, true);
3058                 BKE_material_resize_object(ob, 1, true);
3059                 BKE_material_resize_id(obdata, 1, true);
3060
3061                 ob->mat[0] = ma_ob;
3062                 ob->matbits[0] = matbit;
3063                 (*matarar)[0] = ma_obdata;
3064         }
3065         else {
3066                 BKE_material_clear_id(obdata, true);
3067                 BKE_material_resize_object(ob, 0, true);
3068                 BKE_material_resize_id(obdata, 0, true);
3069         }
3070 }
3071
3072 static bool mesh_separate_material(Main *bmain, Scene *scene, Base *base_old, BMesh *bm_old)
3073 {
3074         BMFace *f_cmp, *f;
3075         BMIter iter;
3076         bool result = false;
3077
3078         while ((f_cmp = BM_iter_at_index(bm_old, BM_FACES_OF_MESH, NULL, 0))) {
3079                 Base *base_new;
3080                 const short mat_nr = f_cmp->mat_nr;
3081                 int tot = 0;
3082
3083                 BM_mesh_elem_hflag_disable_all(bm_old, BM_VERT | BM_EDGE | BM_FACE, BM_ELEM_TAG, false);
3084
3085                 BM_ITER_MESH (f, &iter, bm_old, BM_FACES_OF_MESH) {
3086                         if (f->mat_nr == mat_nr) {
3087                                 BMLoop *l_iter;
3088                                 BMLoop *l_first;
3089
3090                                 BM_elem_flag_enable(f, BM_ELEM_TAG);
3091                                 l_iter = l_first = BM_FACE_FIRST_LOOP(f);
3092                                 do {
3093                                         BM_elem_flag_enable(l_iter->v, BM_ELEM_TAG);
3094                                         BM_elem_flag_enable(l_iter->e, BM_ELEM_TAG);
3095                                 } while ((l_iter = l_iter->next) != l_first);
3096
3097                                 tot++;
3098                         }
3099                 }
3100
3101                 /* leave the current object with some materials */
3102                 if (tot == bm_old->totface) {
3103                         mesh_separate_material_assign_mat_nr(base_old->object, mat_nr);
3104
3105                         /* since we're in editmode, must set faces here */
3106                         BM_ITER_MESH (f, &iter, bm_old, BM_FACES_OF_MESH) {
3107                                 f->mat_nr = 0;
3108                         }
3109                         break;
3110                 }
3111
3112                 /* Move selection into a separate object */
3113                 base_new = mesh_separate_tagged(bmain, scene, base_old, bm_old);
3114                 if (base_new) {
3115                         mesh_separate_material_assign_mat_nr(base_new->object, mat_nr);
3116                 }
3117
3118                 result |= (base_new != NULL);
3119         }
3120
3121         return result;
3122 }
3123
3124 static bool mesh_separate_loose(Main *bmain, Scene *scene, Base *base_old, BMesh *bm_old)
3125 {
3126         int i;
3127         BMEdge *e;
3128         BMVert *v_seed;
3129         BMWalker walker;
3130         bool result = false;
3131         int max_iter = bm_old->totvert;
3132
3133         /* Clear all selected vertices */
3134         BM_mesh_elem_hflag_disable_all(bm_old, BM_VERT | BM_EDGE | BM_FACE, BM_ELEM_TAG, false);
3135
3136         /* A "while (true)" loop should work here as each iteration should
3137          * select and remove at least one vertex and when all vertices
3138          * are selected the loop will break out. But guard against bad
3139          * behavior by limiting iterations to the number of vertices in the
3140          * original mesh.*/
3141         for (i = 0; i < max_iter; i++) {
3142                 int tot = 0;
3143                 /* Get a seed vertex to start the walk */
3144                 v_seed = BM_iter_at_index(bm_old, BM_VERTS_OF_MESH, NULL, 0);
3145
3146                 /* No vertices available, can't do anything */
3147                 if (v_seed == NULL) {
3148                         break;
3149                 }
3150
3151                 /* Select the seed explicitly, in case it has no edges */
3152                 if (!BM_elem_flag_test(v_seed, BM_ELEM_TAG)) { BM_elem_flag_enable(v_seed, BM_ELEM_TAG); tot++; }
3153
3154                 /* Walk from the single vertex, selecting everything connected
3155                  * to it */
3156                 BMW_init(&walker, bm_old, BMW_VERT_SHELL,
3157                          BMW_MASK_NOP, BMW_MASK_NOP, BMW_MASK_NOP,
3158                          BMW_FLAG_NOP,
3159                          BMW_NIL_LAY);
3160
3161                 for (e = BMW_begin(&walker, v_seed); e; e = BMW_step(&walker)) {
3162                         if (!BM_elem_flag_test(e->v1, BM_ELEM_TAG)) { BM_elem_flag_enable(e->v1, BM_ELEM_TAG); tot++; }
3163                         if (!BM_elem_flag_test(e->v2, BM_ELEM_TAG)) { BM_elem_flag_enable(e->v2, BM_ELEM_TAG); tot++; }
3164                 }
3165                 BMW_end(&walker);
3166
3167                 if (bm_old->totvert == tot) {
3168                         /* Every vertex selected, nothing to separate, work is done */
3169                         break;
3170                 }
3171
3172                 /* Flush the selection to get edge/face selections matching
3173                  * the vertex selection */
3174                 bm_mesh_hflag_flush_vert(bm_old, BM_ELEM_TAG);
3175
3176                 /* Move selection into a separate object */
3177                 result |= (mesh_separate_tagged(bmain, scene, base_old, bm_old) != NULL);
3178         }
3179
3180         return result;
3181 }
3182
3183 static int edbm_separate_exec(bContext *C, wmOperator *op)
3184 {
3185         Main *bmain = CTX_data_main(C);
3186         Scene *scene = CTX_data_scene(C);
3187         const int type = RNA_enum_get(op->ptr, "type");
3188         int retval = 0;
3189         
3190         if (ED_operator_editmesh(C)) {
3191                 Base *base = CTX_data_active_base(C);
3192                 BMEditMesh *em = BKE_editmesh_from_object(base->object);
3193
3194                 if (type == 0) {
3195                    &nbs