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