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