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