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