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