a195f37b60e563eb8d6a9df0d45b21f95340c899
[blender-staging.git] / source / blender / editors / mesh / editmesh_knife.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) 2007 Blender Foundation.
19  * All rights reserved.
20  *
21  * 
22  * Contributor(s): Joseph Eagar, Joshua Leung, Howard Trickey,
23  *                 Campbell Barton
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/editors/mesh/editmesh_knife.c
29  *  \ingroup edmesh
30  */
31
32 #ifdef _MSC_VER
33 #  define _USE_MATH_DEFINES
34 #endif
35
36 #include "MEM_guardedalloc.h"
37
38 #include "BLI_blenlib.h"
39 #include "BLI_array.h"
40 #include "BLI_math.h"
41 #include "BLI_smallhash.h"
42 #include "BLI_memarena.h"
43
44 #include "BKE_DerivedMesh.h"
45 #include "BKE_context.h"
46
47 #include "BIF_gl.h"
48 #include "BIF_glutil.h" /* for paint cursor */
49
50 #include "ED_screen.h"
51 #include "ED_space_api.h"
52 #include "ED_view3d.h"
53 #include "ED_mesh.h"
54
55 #include "WM_api.h"
56 #include "WM_types.h"
57
58 #include "DNA_scene_types.h"
59 #include "DNA_object_types.h"
60 #include "BKE_tessmesh.h"
61 #include "UI_resources.h"
62
63 #include "RNA_access.h"
64 #include "RNA_define.h"
65
66 #include "mesh_intern.h"
67
68 /* this code here is kindof messy. . .I might need to eventually rework it - joeedh */
69
70 #define KMAXDIST    10  /* max mouse distance from edge before not detecting it */
71
72 #define KNIFE_FLT_EPS          0.00001f
73 #define KNIFE_FLT_EPS_SQUARED  (KNIFE_FLT_EPS * KNIFE_FLT_EPS)
74
75 typedef struct KnifeColors {
76         unsigned char line[3];
77         unsigned char edge[3];
78         unsigned char curpoint[3];
79         unsigned char curpoint_a[4];
80         unsigned char point[3];
81         unsigned char point_a[4];
82 } KnifeColors;
83
84 /* knifetool operator */
85 typedef struct KnifeVert {
86         BMVert *v; /* non-NULL if this is an original vert */
87         ListBase edges;
88         ListBase faces;
89
90         float co[3], cageco[3], sco[3]; /* sco is screen coordinates for cageco */
91         short flag, draw, isface, inspace;
92 } KnifeVert;
93
94 typedef struct Ref {
95         struct Ref *next, *prev;
96         void *ref;
97 } Ref;
98
99 typedef struct KnifeEdge {
100         KnifeVert *v1, *v2;
101         BMFace *basef; /* face to restrict face fill to */
102         ListBase faces;
103         int draw;
104
105         BMEdge *e, *oe; /* non-NULL if this is an original edge */
106 } KnifeEdge;
107
108 typedef struct BMEdgeHit {
109         KnifeEdge *kfe;
110         float hit[3], cagehit[3];
111         float realhit[3]; /* used in midpoint mode */
112         float schit[3];
113         float l; /* lambda along cut line */
114         float perc; /* lambda along hit line */
115         KnifeVert *v; /* set if snapped to a vert */
116         BMFace *f;
117 } BMEdgeHit;
118
119 typedef struct KnifePosData {
120         float co[3];
121         float cage[3];
122
123         /* At most one of vert, edge, or bmface should be non-NULL,
124          * saying whether the point is snapped to a vertex, edge, or in a face.
125          * If none are set, this point is in space and is_space should be true. */
126         KnifeVert *vert;
127         KnifeEdge *edge;
128         BMFace *bmface;
129         int is_space;
130
131         int mval[2]; /* mouse screen position */
132 } KnifePosData;
133
134 /* struct for properties used while drawing */
135 typedef struct KnifeTool_OpData {
136         ARegion *ar;        /* region that knifetool was activated in */
137         void *draw_handle;  /* for drawing preview loop */
138         ViewContext vc;
139         //bContext *C;
140
141         Object *ob;
142         BMEditMesh *em;
143
144         MemArena *arena;
145
146         GHash *origvertmap;
147         GHash *origedgemap;
148
149         GHash *kedgefacemap;
150
151         BMBVHTree *bmbvh;
152
153         BLI_mempool *kverts;
154         BLI_mempool *kedges;
155
156         float vthresh;
157         float ethresh;
158
159         /* used for drag-cutting */
160         BMEdgeHit *linehits;
161         int totlinehit;
162
163         /* Data for mouse-position-derived data (cur) and previous click (prev) */
164         KnifePosData curr, prev;
165
166         int totkedge, totkvert;
167
168         BLI_mempool *refs;
169
170         float projmat[4][4];
171
172         KnifeColors colors;
173
174         /* operatpr options */
175         char cut_through;    /* preference, can be modified at runtime (that feature may go) */
176         char only_select;    /* set on initialization */
177         char select_result;  /* set on initialization */
178
179         short is_ortho;
180         float ortho_extent;
181         float clipsta, clipend;
182
183         enum {
184                 MODE_IDLE,
185                 MODE_DRAGGING,
186                 MODE_CONNECT,
187                 MODE_PANNING
188         } mode;
189
190         int snap_midpoints, prevmode, extend;
191         int ignore_edge_snapping, ignore_vert_snapping;
192
193         enum {
194                 ANGLE_FREE,
195                 ANGLE_0,
196                 ANGLE_45,
197                 ANGLE_90,
198                 ANGLE_135
199         } angle_snapping;
200
201         float (*cagecos)[3];
202 } KnifeTool_OpData;
203
204 static ListBase *knife_get_face_kedges(KnifeTool_OpData *kcd, BMFace *f);
205
206 #if 0
207 static void knife_input_ray_cast(KnifeTool_OpData *kcd, const int mval_i[2],
208                                  float r_origin[3], float r_ray[3]);
209 #endif
210 static void knife_input_ray_segment(KnifeTool_OpData *kcd, const int mval_i[2], const float ofs,
211                                     float r_origin[3], float r_dest[3]);
212
213 static void knife_update_header(bContext *C, KnifeTool_OpData *kcd)
214 {
215         #define HEADER_LENGTH 190
216         char header[HEADER_LENGTH];
217
218         BLI_snprintf(header, HEADER_LENGTH, "LMB: define cut lines, Return/Spacebar: confirm, Esc or RMB: cancel, E: new cut, Ctrl: midpoint snap (%s), "
219                      "Shift: ignore snap (%s), C: angle constrain (%s), Z: cut through (%s)",
220                      kcd->snap_midpoints ? "On" : "Off",
221                      kcd->ignore_edge_snapping ?  "On" : "Off",
222                      kcd->angle_snapping ? "On" : "Off",
223                      kcd->cut_through ? "On" : "Off");
224
225         ED_area_headerprint(CTX_wm_area(C), header);
226 }
227
228
229 static void knife_project_v3(KnifeTool_OpData *kcd, const float co[3], float sco[3])
230 {
231         ED_view3d_project_float_v3_m4(kcd->ar, co, sco, kcd->projmat);
232 }
233
234 static void knife_pos_data_clear(KnifePosData *kpd)
235 {
236         zero_v3(kpd->co);
237         zero_v3(kpd->cage);
238         kpd->vert = NULL;
239         kpd->edge = NULL;
240         kpd->bmface = NULL;
241         kpd->mval[0] = 0;
242         kpd->mval[1] = 0;
243 }
244
245 static ListBase *knife_empty_list(KnifeTool_OpData *kcd)
246 {
247         ListBase *lst;
248
249         lst = BLI_memarena_alloc(kcd->arena, sizeof(ListBase));
250         lst->first = lst->last = NULL;
251         return lst;
252 }
253
254 static void knife_append_list(KnifeTool_OpData *kcd, ListBase *lst, void *elem)
255 {
256         Ref *ref;
257
258         ref = BLI_mempool_calloc(kcd->refs);
259         ref->ref = elem;
260         BLI_addtail(lst, ref);
261 }
262
263 static Ref *find_ref(ListBase *lb, void *ref)
264 {
265         Ref *ref1;
266
267         for (ref1 = lb->first; ref1; ref1 = ref1->next) {
268                 if (ref1->ref == ref)
269                         return ref1;
270         }
271
272         return NULL;
273 }
274
275 static KnifeEdge *new_knife_edge(KnifeTool_OpData *kcd)
276 {
277         kcd->totkedge++;
278         return BLI_mempool_calloc(kcd->kedges);
279 }
280
281 static void knife_add_to_vert_edges(KnifeTool_OpData *kcd, KnifeEdge *kfe)
282 {
283         knife_append_list(kcd, &kfe->v1->edges, kfe);
284         knife_append_list(kcd, &kfe->v2->edges, kfe);
285 }
286
287 /* Add faces of an edge to a KnifeVert's faces list.  No checks for dups. */
288 static void knife_add_edge_faces_to_vert(KnifeTool_OpData *kcd, KnifeVert *kfv, BMEdge *e)
289 {
290         BMIter bmiter;
291         BMFace *f;
292
293         BM_ITER_ELEM(f, &bmiter, e, BM_FACES_OF_EDGE) {
294                 knife_append_list(kcd, &kfv->faces, f);
295         }
296 }
297
298 /* Find a face in common in the two faces lists.
299  * If more than one, return the first; if none, return NULL */
300 static BMFace *knife_find_common_face(ListBase *faces1, ListBase *faces2)
301 {
302         Ref *ref1, *ref2;
303
304         for (ref1 = faces1->first; ref1; ref1 = ref1->next) {
305                 for (ref2 = faces2->first; ref2; ref2 = ref2->next) {
306                         if (ref1->ref == ref2->ref)
307                                 return (BMFace *)(ref1->ref);
308                 }
309         }
310         return NULL;
311 }
312
313 static KnifeVert *new_knife_vert(KnifeTool_OpData *kcd, const float co[3], float *cageco)
314 {
315         KnifeVert *kfv = BLI_mempool_calloc(kcd->kverts);
316
317         kcd->totkvert++;
318
319         copy_v3_v3(kfv->co, co);
320         copy_v3_v3(kfv->cageco, cageco);
321         copy_v3_v3(kfv->sco, co);
322
323         knife_project_v3(kcd, kfv->co, kfv->sco);
324
325         return kfv;
326 }
327
328 /* get a KnifeVert wrapper for an existing BMVert */
329 static KnifeVert *get_bm_knife_vert(KnifeTool_OpData *kcd, BMVert *v)
330 {
331         KnifeVert *kfv = BLI_ghash_lookup(kcd->origvertmap, v);
332
333         if (!kfv) {
334                 BMIter bmiter;
335                 BMFace *f;
336
337                 kfv = new_knife_vert(kcd, v->co, kcd->cagecos[BM_elem_index_get(v)]);
338                 kfv->v = v;
339                 BLI_ghash_insert(kcd->origvertmap, v, kfv);
340                 BM_ITER_ELEM(f, &bmiter, v, BM_FACES_OF_VERT) {
341                         knife_append_list(kcd, &kfv->faces, f);
342                 }
343         }
344
345         return kfv;
346 }
347
348 /* get a KnifeEdge wrapper for an existing BMEdge */
349 static KnifeEdge *get_bm_knife_edge(KnifeTool_OpData *kcd, BMEdge *e)
350 {
351         KnifeEdge *kfe = BLI_ghash_lookup(kcd->origedgemap, e);
352         if (!kfe) {
353                 BMIter bmiter;
354                 BMFace *f;
355
356                 kfe = new_knife_edge(kcd);
357                 kfe->e = e;
358                 kfe->v1 = get_bm_knife_vert(kcd, e->v1);
359                 kfe->v2 = get_bm_knife_vert(kcd, e->v2);
360
361                 knife_add_to_vert_edges(kcd, kfe);
362
363                 BLI_ghash_insert(kcd->origedgemap, e, kfe);
364
365                 BM_ITER_ELEM(f, &bmiter, e, BM_FACES_OF_EDGE) {
366                         knife_append_list(kcd, &kfe->faces, f);
367                 }
368         }
369
370         return kfe;
371 }
372
373 /* User has just clicked for first time or first time after a restart (E key).
374  * Copy the current position data into prev. */
375 static void knife_start_cut(KnifeTool_OpData *kcd)
376 {
377         kcd->prev = kcd->curr;
378         kcd->curr.is_space = 0; /*TODO: why do we do this? */
379
380         if (kcd->prev.vert == NULL && kcd->prev.edge == NULL && is_zero_v3(kcd->prev.cage)) {
381                 /* Make prevcage a point on the view ray to mouse closest to a point on model: choose vertex 0 */
382                 float origin[3], origin_ofs[3];
383                 BMVert *v0;
384
385                 knife_input_ray_segment(kcd, kcd->curr.mval, 1.0f, origin, origin_ofs);
386                 v0 = BM_vert_at_index(kcd->em->bm, 0);
387                 if (v0) {
388                         closest_to_line_v3(kcd->prev.cage, v0->co, origin_ofs, origin);
389                         copy_v3_v3(kcd->prev.co, kcd->prev.cage); /*TODO: do we need this? */
390                         copy_v3_v3(kcd->curr.cage, kcd->prev.cage);
391                         copy_v3_v3(kcd->curr.co, kcd->prev.co);
392                 }
393         }
394 }
395
396 static ListBase *knife_get_face_kedges(KnifeTool_OpData *kcd, BMFace *f)
397 {
398         ListBase *lst = BLI_ghash_lookup(kcd->kedgefacemap, f);
399
400         if (!lst) {
401                 BMIter bmiter;
402                 BMEdge *e;
403
404                 lst = knife_empty_list(kcd);
405
406                 BM_ITER_ELEM(e, &bmiter, f, BM_EDGES_OF_FACE) {
407                         knife_append_list(kcd, lst, get_bm_knife_edge(kcd, e));
408                 }
409
410                 BLI_ghash_insert(kcd->kedgefacemap, f, lst);
411         }
412
413         return lst;
414 }
415
416 /* finds the proper face to restrict face fill to */
417 static void knife_find_basef(KnifeEdge *kfe)
418 {
419         kfe->basef = knife_find_common_face(&kfe->v1->faces, &kfe->v2->faces);
420 }
421
422 static void knife_edge_append_face(KnifeTool_OpData *kcd, KnifeEdge *kfe, BMFace *f)
423 {
424         knife_append_list(kcd, knife_get_face_kedges(kcd, f), kfe);
425         knife_append_list(kcd, &kfe->faces, f);
426 }
427
428 static KnifeVert *knife_split_edge(KnifeTool_OpData *kcd, KnifeEdge *kfe, float co[3], KnifeEdge **newkfe_out)
429 {
430         KnifeEdge *newkfe = new_knife_edge(kcd);
431         Ref *ref;
432         BMFace *f;
433         float perc, cageco[3], l12;
434
435         l12 = len_v3v3(kfe->v1->co, kfe->v2->co);
436         if (l12 < KNIFE_FLT_EPS) {
437                 copy_v3_v3(cageco, kfe->v1->cageco);
438         }
439         else {
440                 perc = len_v3v3(co, kfe->v1->co) / l12;
441                 interp_v3_v3v3(cageco, kfe->v1->cageco, kfe->v2->cageco, perc);
442         }
443
444         newkfe->v1 = kfe->v1;
445         newkfe->v2 = new_knife_vert(kcd, co, cageco);
446         newkfe->v2->draw = 1;
447         if (kfe->e) {
448                 knife_add_edge_faces_to_vert(kcd, newkfe->v2, kfe->e);
449         }
450         else {
451                 /* kfe cuts across an existing face.
452                  * If v1 and v2 are in multiple faces together (e.g., if they
453                  * are in doubled polys) then this arbitrarily chooses one of them */
454                 f = knife_find_common_face(&kfe->v1->faces, &kfe->v2->faces);
455                 if (f)
456                         knife_append_list(kcd, &newkfe->v2->faces, f);
457         }
458         newkfe->basef = kfe->basef;
459
460         ref = find_ref(&kfe->v1->edges, kfe);
461         BLI_remlink(&kfe->v1->edges, ref);
462
463         kfe->v1 = newkfe->v2;
464         BLI_addtail(&kfe->v1->edges, ref);
465
466         for (ref = kfe->faces.first; ref; ref = ref->next)
467                 knife_edge_append_face(kcd, newkfe, ref->ref);
468
469         knife_add_to_vert_edges(kcd, newkfe);
470
471         newkfe->draw = kfe->draw;
472         newkfe->e = kfe->e;
473
474         *newkfe_out = newkfe;
475
476         return newkfe->v2;
477 }
478
479 /* Make a single KnifeEdge for cut from kcd->prev to kcd->curr.
480  * and move cur data to prev. */
481 static void knife_add_single_cut(KnifeTool_OpData *kcd)
482 {
483         KnifeEdge *kfe = new_knife_edge(kcd), *kfe2 = NULL, *kfe3 = NULL;
484
485         if (kcd->prev.vert && kcd->prev.vert == kcd->curr.vert)
486                 return;
487         if (kcd->prev.edge && kcd->prev.edge == kcd->curr.edge)
488                 return;
489
490         kfe->draw = 1;
491
492         if (kcd->prev.vert) {
493                 kfe->v1 = kcd->prev.vert;
494         }
495         else if (kcd->prev.edge) {
496                 kfe->v1 = knife_split_edge(kcd, kcd->prev.edge, kcd->prev.co, &kfe2);
497         }
498         else {
499                 kfe->v1 = new_knife_vert(kcd, kcd->prev.co, kcd->prev.co);
500                 kfe->v1->draw = kfe->draw = !kcd->prev.is_space;
501                 kfe->v1->inspace = kcd->prev.is_space;
502                 kfe->draw = !kcd->prev.is_space;
503                 kfe->v1->isface = 1;
504                 if (kfe->v1->draw && kcd->prev.bmface)
505                         knife_append_list(kcd, &kfe->v1->faces, kcd->prev.bmface);
506         }
507
508         if (kcd->curr.vert) {
509                 kfe->v2 = kcd->curr.vert;
510         }
511         else if (kcd->curr.edge) {
512                 kfe->v2 = knife_split_edge(kcd, kcd->curr.edge, kcd->curr.co, &kfe3);
513                 kcd->curr.vert = kfe->v2;
514         }
515         else {
516                 kfe->v2 = new_knife_vert(kcd, kcd->curr.co, kcd->curr.co);
517                 kfe->v2->draw = !kcd->curr.is_space;
518                 kfe->v2->isface = 1;
519                 kfe->v2->inspace = kcd->curr.is_space;
520                 if (kfe->v2->draw && kcd->curr.bmface)
521                         knife_append_list(kcd, &kfe->v2->faces, kcd->curr.bmface);
522
523                 if (kcd->curr.is_space)
524                         kfe->draw = 0;
525
526                 kcd->curr.vert = kfe->v2;
527         }
528
529         knife_find_basef(kfe);
530
531         knife_add_to_vert_edges(kcd, kfe);
532
533         if (kfe->basef && !find_ref(&kfe->faces, kfe->basef))
534                 knife_edge_append_face(kcd, kfe, kfe->basef);
535
536         /* sanity check to make sure we're in the right edge/face lists */
537         if (kcd->curr.bmface) {
538                 if (!find_ref(&kfe->faces, kcd->curr.bmface)) {
539                         knife_edge_append_face(kcd, kfe, kcd->curr.bmface);
540                 }
541
542                 if (kcd->prev.bmface && kcd->prev.bmface != kcd->curr.bmface) {
543                         if (!find_ref(&kfe->faces, kcd->prev.bmface)) {
544                                 knife_edge_append_face(kcd, kfe, kcd->prev.bmface);
545                         }
546                 }
547         }
548
549         /* set up for next cut */
550         kcd->prev = kcd->curr;
551 }
552
553 static int verge_linehit(const void *vlh1, const void *vlh2)
554 {
555         const BMEdgeHit *lh1 = vlh1, *lh2 = vlh2;
556
557         if      (lh1->l < lh2->l) return -1;
558         else if (lh1->l > lh2->l) return 1;
559         else return 0;
560 }
561
562 /* If there's a linehit connected (same face) as testi in range [firsti, lasti], return the first such, else -1.
563  * If testi is out of range, look for connection to f instead, if f is non-NULL */
564 static int find_connected_linehit(KnifeTool_OpData *kcd, int testi, BMFace *f, int firsti, int lasti)
565 {
566         int i;
567
568         for (i = firsti; i <= lasti; i++) {
569                 if (testi >= 0 && testi < kcd->totlinehit) {
570                         if (knife_find_common_face(&kcd->linehits[testi].kfe->faces,
571                                                    &kcd->linehits[i].kfe->faces))
572                         {
573                                 return i;
574                         }
575                 }
576                 else if (f) {
577                         if (find_ref(&kcd->linehits[i].kfe->faces, f))
578                                 return i;
579                 }
580         }
581         return -1;
582 }
583
584 /* Sort in order of distance along cut line, but take care when distances are equal */
585 static void knife_sort_linehits(KnifeTool_OpData *kcd)
586 {
587         int i, j, k, nexti, nsame;
588
589         qsort(kcd->linehits, kcd->totlinehit, sizeof(BMEdgeHit), verge_linehit);
590
591         /* for ranges of equal "l", swap if neccesary to make predecessor and
592          * successor faces connected to the linehits at either end of the range */
593         for (i = 0; i < kcd->totlinehit - 1; i = nexti) {
594                 for (j = i + 1; j < kcd->totlinehit; j++) {
595                         if (fabsf(kcd->linehits[j].l - kcd->linehits[i].l) > KNIFE_FLT_EPS)
596                                 break;
597                 }
598                 nexti = j;
599                 j--;
600                 nsame = j - i;
601                 if (nsame > 0) {
602                         /* find something connected to predecessor of equal range */
603                         k = find_connected_linehit(kcd, i - 1, kcd->prev.bmface, i, j);
604                         if (k != -1) {
605                                 if (k != i) {
606                                         SWAP(BMEdgeHit, kcd->linehits[i], kcd->linehits[k]);
607                                 }
608                                 i++;
609                                 nsame--;
610                         }
611                         if (nsame > 0) {
612                                 /* find something connected to successor of equal range */
613                                 k = find_connected_linehit(kcd, j + 1, kcd->curr.bmface, i, j);
614                                 if (k != -1 && k != j) {
615                                         SWAP(BMEdgeHit, kcd->linehits[j], kcd->linehits[k]);
616                                 }
617                         }
618                         /* rest of same range doesn't matter because we won't connect them */
619                 }
620         }
621 }
622
623 static void knife_add_single_cut_through(KnifeTool_OpData *kcd, KnifeVert *v1, KnifeVert *v2, BMFace *f)
624 {
625         KnifeEdge *kfenew;
626
627         kfenew = new_knife_edge(kcd);
628         kfenew->draw = 1;
629         kfenew->basef = f;
630         kfenew->v1 = v1;
631         kfenew->v2 = v2;
632         kfenew->draw = 1;
633
634         knife_add_to_vert_edges(kcd, kfenew);
635
636         if (!find_ref(&kfenew->faces, f))
637                 knife_edge_append_face(kcd, kfenew, f);
638 }
639
640 static void knife_get_vert_faces(KnifeTool_OpData *kcd, KnifeVert *kfv, BMFace *facef, ListBase *lst)
641 {
642         BMIter bmiter;
643         BMFace *f;
644
645         if (kfv->isface && facef) {
646                 knife_append_list(kcd, lst, facef);
647         }
648         else if (kfv->v) {
649                 BM_ITER_ELEM (f, &bmiter, kfv->v, BM_FACES_OF_VERT) {
650                         knife_append_list(kcd, lst, f);
651                 }
652         }
653 }
654
655 static void knife_get_edge_faces(KnifeTool_OpData *kcd, KnifeEdge *kfe, ListBase *lst)
656 {
657         BMIter bmiter;
658         BMFace *f;
659
660         if (kfe->e) {
661                 BM_ITER_ELEM (f, &bmiter, kfe->e, BM_FACES_OF_EDGE) {
662                         knife_append_list(kcd, lst, f);
663                 }
664         }
665 }
666
667 /* BMESH_TODO: add more functionality to cut-through:
668  *    - cutting "in face" (e.g., holes) should cut in all faces, not just visible one
669  *    - perhaps improve O(n^2) algorithm used here */
670 static void knife_cut_through(KnifeTool_OpData *kcd)
671 {
672         BMEdgeHit *lh, *lh2;
673         BMFace *f;
674         KnifeEdge *kfe, *kfe2, *kfe3;
675         KnifeVert *v1, *v2, *firstv = NULL, *lastv = NULL;
676         ListBase firstfaces = {NULL, NULL}, lastfaces = {NULL, NULL};
677         Ref *r, *r2;
678         KnifeEdge **splitkfe;
679         int i, j, found;
680
681         if (!kcd->totlinehit) {
682                 /* if no linehits then no interesting back face stuff to do */
683                 knife_add_single_cut(kcd);
684                 return;
685         }
686
687         /* TODO: probably don't need to sort at all */
688         qsort(kcd->linehits, kcd->totlinehit, sizeof(BMEdgeHit), verge_linehit);
689         splitkfe = MEM_callocN(kcd->totlinehit * sizeof(KnifeEdge *), "knife_cut_through");
690
691         if (kcd->prev.vert) {
692                 if (kcd->prev.vert == kcd->curr.vert)
693                         return;
694                 firstv = kcd->prev.vert;
695                 knife_get_vert_faces(kcd, firstv, kcd->prev.bmface, &firstfaces);
696         }
697         else if (kcd->prev.edge) {
698                 if (kcd->prev.edge == kcd->curr.edge)
699                         return;
700                 firstv = knife_split_edge(kcd, kcd->prev.edge, kcd->prev.co, &kfe3);
701                 knife_get_edge_faces(kcd, kcd->prev.edge, &firstfaces);
702         }
703
704         if (kcd->curr.vert) {
705                 lastv = kcd->curr.vert;
706                 knife_get_vert_faces(kcd, lastv, kcd->curr.bmface, &lastfaces);
707         }
708         else if (kcd->curr.edge) {
709                 lastv = knife_split_edge(kcd, kcd->curr.edge, kcd->curr.co, &kfe3);
710                 knife_get_edge_faces(kcd, kcd->curr.edge, &lastfaces);
711         }
712
713         if (firstv) {
714                 /* For each face incident to firstv,
715                  * find the first following linehit (if any) sharing that face and connect */
716                 for (r = firstfaces.first; r; r = r->next) {
717                         f = r->ref;
718                         found = 0;
719                         for (j = 0, lh2 = kcd->linehits; j < kcd->totlinehit && !found; j++, lh2++) {
720                                 kfe2 = lh2->kfe;
721                                 for (r2 = kfe2->faces.first; r2; r2 = r2->next) {
722                                         if (r2->ref == f) {
723                                                 v2 = splitkfe[j] ? kfe2->v1 : knife_split_edge(kcd, kfe2, lh2->hit, &splitkfe[j]);
724                                                 knife_add_single_cut_through(kcd, firstv, v2, f);
725                                                 found = 1;
726                                                 break;
727                                         }
728                                 }
729                         }
730                         if (!found && lastv) {
731                                 for (r2 = lastfaces.first; r2; r2 = r2->next) {
732                                         if (r2->ref == f) {
733                                                 knife_add_single_cut_through(kcd, firstv, lastv, f);
734                                                 break;
735                                         }
736                                 }
737                         }
738                 }
739         }
740
741         for (i = 0, lh = kcd->linehits; i < kcd->totlinehit; i++, lh++) {
742                 kfe = lh->kfe;
743
744                 /* For each face attached to edge for this linehit,
745                  * find the first following linehit (if any) sharing that face and connect */
746                 for (r = kfe->faces.first; r; r = r->next) {
747                         f = r->ref;
748                         found = 0;
749                         for (j = i + 1, lh2 = lh + 1; j < kcd->totlinehit && !found; j++, lh2++) {
750                                 kfe2 = lh2->kfe;
751                                 for (r2 = kfe2->faces.first; r2; r2 = r2->next) {
752                                         if (r2->ref == f) {
753                                                 v1 = splitkfe[i] ? kfe->v1 : knife_split_edge(kcd, kfe, lh->hit, &splitkfe[i]);
754                                                 v2 = splitkfe[j] ? kfe2->v1 : knife_split_edge(kcd, kfe2, lh2->hit, &splitkfe[j]);
755                                                 knife_add_single_cut_through(kcd, v1, v2, f);
756                                                 found = 1;
757                                                 break;
758                                         }
759                                 }
760                         }
761                         if (!found && lastv) {
762                                 for (r2 = lastfaces.first; r2; r2 = r2->next) {
763                                         if (r2->ref == f) {
764                                                 v1 = splitkfe[i] ? kfe->v1 : knife_split_edge(kcd, kfe, lh->hit, &splitkfe[i]);
765                                                 knife_add_single_cut_through(kcd, v1, lastv, f);
766                                                 break;
767                                         }
768                                 }
769                         }
770                 }
771         }
772
773         MEM_freeN(splitkfe);
774         MEM_freeN(kcd->linehits);
775         kcd->linehits = NULL;
776         kcd->totlinehit = 0;
777
778         /* set up for next cut */
779         kcd->prev = kcd->curr;
780 }
781
782 /* User has just left-clicked after the first time.
783  * Add all knife cuts implied by line from prev to curr.
784  * If that line crossed edges then kcd->linehits will be non-NULL. */
785 static void knife_add_cut(KnifeTool_OpData *kcd)
786 {
787         KnifePosData savcur = kcd->curr;
788
789         if (kcd->cut_through) {
790                 knife_cut_through(kcd);
791         }
792         else if (kcd->linehits) {
793                 BMEdgeHit *lh, *lastlh, *firstlh;
794                 int i;
795
796                 knife_sort_linehits(kcd);
797
798                 lh = kcd->linehits;
799                 lastlh = firstlh = NULL;
800                 for (i = 0; i < kcd->totlinehit; i++, (lastlh = lh), lh++) {
801                         BMFace *f = lastlh ? lastlh->f : lh->f;
802
803                         if (lastlh && len_squared_v3v3(lastlh->hit, lh->hit) == 0.0f) {
804                                 if (!firstlh)
805                                         firstlh = lastlh;
806                                 continue;
807                         }
808                         else if (lastlh && firstlh) {
809                                 if (firstlh->v || lastlh->v) {
810                                         KnifeVert *kfv = firstlh->v ? firstlh->v : lastlh->v;
811
812                                         kcd->prev.vert = kfv;
813                                         copy_v3_v3(kcd->prev.co, firstlh->hit);
814                                         copy_v3_v3(kcd->prev.cage, firstlh->cagehit);
815                                         kcd->prev.edge = NULL;
816                                         kcd->prev.bmface = f;
817                                         /* TODO: should we set prev.in_space = 0 ? */
818                                 }
819                                 lastlh = firstlh = NULL;
820                         }
821
822                         if (len_squared_v3v3(kcd->prev.cage, lh->realhit) < KNIFE_FLT_EPS_SQUARED)
823                                 continue;
824                         if (len_squared_v3v3(kcd->curr.cage, lh->realhit) < KNIFE_FLT_EPS_SQUARED)
825                                 continue;
826
827                         /* first linehit may be down face parallel to view */
828                         if (!lastlh && fabsf(lh->l) < KNIFE_FLT_EPS)
829                                 continue;
830
831                         if (kcd->prev.is_space) {
832                                 kcd->prev.is_space = 0;
833                                 copy_v3_v3(kcd->prev.co, lh->hit);
834                                 copy_v3_v3(kcd->prev.cage, lh->cagehit);
835                                 kcd->prev.vert = NULL;
836                                 kcd->prev.edge = lh->kfe;
837                                 kcd->prev.bmface = lh->f;
838                                 continue;
839                         }
840
841                         kcd->curr.is_space = 0;
842                         kcd->curr.edge = lh->kfe;
843                         kcd->curr.bmface = lh->f;
844                         kcd->curr.vert = lh->v;
845                         copy_v3_v3(kcd->curr.co, lh->hit);
846                         copy_v3_v3(kcd->curr.cage, lh->cagehit);
847
848                         /* don't draw edges down faces parallel to view */
849                         if (lastlh && fabsf(lastlh->l - lh->l) < KNIFE_FLT_EPS) {
850                                 kcd->prev = kcd->curr;
851                                 continue;
852                         }
853
854                         knife_add_single_cut(kcd);
855                 }
856
857                 if (savcur.is_space) {
858                         kcd->prev = savcur;
859                 }
860                 else {
861                         kcd->curr = savcur;
862                         knife_add_single_cut(kcd);
863                 }
864
865                 MEM_freeN(kcd->linehits);
866                 kcd->linehits = NULL;
867                 kcd->totlinehit = 0;
868         }
869         else {
870                 knife_add_single_cut(kcd);
871         }
872 }
873
874 static void knife_finish_cut(KnifeTool_OpData *UNUSED(kcd))
875 {
876
877 }
878
879 static void knifetool_draw_angle_snapping(KnifeTool_OpData *kcd)
880 {
881         bglMats mats;
882         double u[3], u1[2], u2[2], v1[3], v2[3], dx, dy;
883         double wminx, wminy, wmaxx, wmaxy;
884
885         /* make u the window coords of prevcage */
886         view3d_get_transformation(kcd->ar, kcd->vc.rv3d, kcd->ob, &mats);
887         gluProject(kcd->prev.cage[0], kcd->prev.cage[1], kcd->prev.cage[2],
888                    mats.modelview, mats.projection, mats.viewport,
889                    &u[0], &u[1], &u[2]);
890
891         /* make u1, u2 the points on window going through u at snap angle */
892         wminx = kcd->ar->winrct.xmin;
893         wmaxx = kcd->ar->winrct.xmin + kcd->ar->winx;
894         wminy = kcd->ar->winrct.ymin;
895         wmaxy = kcd->ar->winrct.ymin + kcd->ar->winy;
896
897         switch (kcd->angle_snapping) {
898                 case ANGLE_0:
899                         u1[0] = wminx;
900                         u2[0] = wmaxx;
901                         u1[1] = u2[1] = u[1];
902                         break;
903                 case ANGLE_90:
904                         u1[0] = u2[0] = u[0];
905                         u1[1] = wminy;
906                         u2[1] = wmaxy;
907                         break;
908                 case ANGLE_45:
909                         /* clip against left or bottom */
910                         dx = u[0] - wminx;
911                         dy = u[1] - wminy;
912                         if (dy > dx) {
913                                 u1[0] = wminx;
914                                 u1[1] = u[1] - dx;
915                         }
916                         else {
917                                 u1[0] = u[0] - dy;
918                                 u1[1] = wminy;
919                         }
920                         /* clip against right or top */
921                         dx = wmaxx - u[0];
922                         dy = wmaxy - u[1];
923                         if (dy > dx) {
924                                 u2[0] = wmaxx;
925                                 u2[1] = u[1] + dx;
926                         }
927                         else {
928                                 u2[0] = u[0] + dy;
929                                 u2[1] = wmaxy;
930                         }
931                         break;
932                 case ANGLE_135:
933                         /* clip against right or bottom */
934                         dx = wmaxx - u[0];
935                         dy = u[1] - wminy;
936                         if (dy > dx) {
937                                 u1[0] = wmaxx;
938                                 u1[1] = u[1] - dx;
939                         }
940                         else {
941                                 u1[0] = u[0] + dy;
942                                 u1[1] = wminy;
943                         }
944                         /* clip against left or top */
945                         dx = u[0] - wminx;
946                         dy = wmaxy - u[1];
947                         if (dy > dx) {
948                                 u2[0] = wminx;
949                                 u2[1] = u[1] + dx;
950                         }
951                         else {
952                                 u2[0] = u[0] - dy;
953                                 u2[1] = wmaxy;
954                         }
955                         break;
956                 default:
957                         return;
958         }
959
960         /* unproject u1 and u2 back into object space */
961         gluUnProject(u1[0], u1[1], 0.0,
962                      mats.modelview, mats.projection, mats.viewport,
963                      &v1[0], &v1[1], &v1[2]);
964         gluUnProject(u2[0], u2[1], 0.0,
965                      mats.modelview, mats.projection, mats.viewport,
966                      &v2[0], &v2[1], &v2[2]);
967
968         UI_ThemeColor(TH_TRANSFORM);
969         glLineWidth(2.0);
970         glBegin(GL_LINES);
971         glVertex3dv(v1);
972         glVertex3dv(v2);
973         glEnd();
974 }
975
976 static void knife_init_colors(KnifeColors *colors)
977 {
978         /* possible BMESH_TODO: add explicit themes or calculate these by
979          * figuring out contrasting colors with grid / edges / verts
980          * a la UI_make_axis_color */
981         UI_GetThemeColor3ubv(TH_NURB_VLINE, colors->line);
982         UI_GetThemeColor3ubv(TH_NURB_ULINE, colors->edge);
983         UI_GetThemeColor3ubv(TH_HANDLE_SEL_VECT, colors->curpoint);
984         UI_GetThemeColor3ubv(TH_HANDLE_SEL_VECT, colors->curpoint_a);
985         colors->curpoint_a[3] = 102;
986         UI_GetThemeColor3ubv(TH_ACTIVE_SPLINE, colors->point);
987         UI_GetThemeColor3ubv(TH_ACTIVE_SPLINE, colors->point_a);
988         colors->point_a[3] = 102;
989 }
990
991 /* modal loop selection drawing callback */
992 static void knifetool_draw(const bContext *C, ARegion *UNUSED(ar), void *arg)
993 {
994         View3D *v3d = CTX_wm_view3d(C);
995         KnifeTool_OpData *kcd = arg;
996
997         if (v3d->zbuf) glDisable(GL_DEPTH_TEST);
998
999         glPolygonOffset(1.0f, 1.0f);
1000
1001         glPushMatrix();
1002         glMultMatrixf(kcd->ob->obmat);
1003
1004         if (kcd->mode == MODE_DRAGGING) {
1005                 if (kcd->angle_snapping != ANGLE_FREE)
1006                         knifetool_draw_angle_snapping(kcd);
1007
1008                 glColor3ubv(kcd->colors.line);
1009                 
1010                 glLineWidth(2.0);
1011
1012                 glBegin(GL_LINES);
1013                 glVertex3fv(kcd->prev.cage);
1014                 glVertex3fv(kcd->curr.cage);
1015                 glEnd();
1016
1017                 glLineWidth(1.0);
1018         }
1019
1020         if (kcd->curr.edge) {
1021                 glColor3ubv(kcd->colors.edge);
1022                 glLineWidth(2.0);
1023
1024                 glBegin(GL_LINES);
1025                 glVertex3fv(kcd->curr.edge->v1->cageco);
1026                 glVertex3fv(kcd->curr.edge->v2->cageco);
1027                 glEnd();
1028
1029                 glLineWidth(1.0);
1030         }
1031         else if (kcd->curr.vert) {
1032                 glColor3ubv(kcd->colors.point);
1033                 glPointSize(11);
1034
1035                 glBegin(GL_POINTS);
1036                 glVertex3fv(kcd->curr.cage);
1037                 glEnd();
1038         }
1039
1040         if (kcd->curr.bmface) {
1041                 glColor3ubv(kcd->colors.curpoint);
1042                 glPointSize(9);
1043
1044                 glBegin(GL_POINTS);
1045                 glVertex3fv(kcd->curr.cage);
1046                 glEnd();
1047         }
1048
1049         if (kcd->totlinehit > 0) {
1050                 const float vthresh4 = kcd->vthresh / 4.0f;
1051                 const float vthresh4_squared = vthresh4 * vthresh4;
1052
1053                 BMEdgeHit *lh;
1054                 int i;
1055
1056                 glEnable(GL_BLEND);
1057                 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1058
1059                 /* draw any snapped verts first */
1060                 glColor4ubv(kcd->colors.point_a);
1061                 glPointSize(11);
1062                 glBegin(GL_POINTS);
1063                 lh = kcd->linehits;
1064                 for (i = 0; i < kcd->totlinehit; i++, lh++) {
1065                         float sv1[3], sv2[3];
1066
1067                         knife_project_v3(kcd, lh->kfe->v1->cageco, sv1);
1068                         knife_project_v3(kcd, lh->kfe->v2->cageco, sv2);
1069                         knife_project_v3(kcd, lh->cagehit, lh->schit);
1070
1071                         if (len_squared_v2v2(lh->schit, sv1) < vthresh4_squared) {
1072                                 copy_v3_v3(lh->cagehit, lh->kfe->v1->cageco);
1073                                 glVertex3fv(lh->cagehit);
1074                                 lh->v = lh->kfe->v1;
1075                         }
1076                         else if (len_squared_v2v2(lh->schit, sv2) < vthresh4_squared) {
1077                                 copy_v3_v3(lh->cagehit, lh->kfe->v2->cageco);
1078                                 glVertex3fv(lh->cagehit);
1079                                 lh->v = lh->kfe->v2;
1080                         }
1081                 }
1082                 glEnd();
1083
1084                 /* now draw the rest */
1085                 glColor4ubv(kcd->colors.curpoint_a);
1086                 glPointSize(7);
1087                 glBegin(GL_POINTS);
1088                 lh = kcd->linehits;
1089                 for (i = 0; i < kcd->totlinehit; i++, lh++) {
1090                         glVertex3fv(lh->cagehit);
1091                 }
1092                 glEnd();
1093                 glDisable(GL_BLEND);
1094         }
1095
1096         if (kcd->totkedge > 0) {
1097                 BLI_mempool_iter iter;
1098                 KnifeEdge *kfe;
1099
1100                 glLineWidth(1.0);
1101                 glBegin(GL_LINES);
1102
1103                 BLI_mempool_iternew(kcd->kedges, &iter);
1104                 for (kfe = BLI_mempool_iterstep(&iter); kfe; kfe = BLI_mempool_iterstep(&iter)) {
1105                         if (!kfe->draw)
1106                                 continue;
1107
1108                         glColor3ubv(kcd->colors.line);
1109
1110                         glVertex3fv(kfe->v1->cageco);
1111                         glVertex3fv(kfe->v2->cageco);
1112                 }
1113
1114                 glEnd();
1115                 glLineWidth(1.0);
1116         }
1117
1118         if (kcd->totkvert > 0) {
1119                 BLI_mempool_iter iter;
1120                 KnifeVert *kfv;
1121
1122                 glPointSize(5.0);
1123
1124                 glBegin(GL_POINTS);
1125                 BLI_mempool_iternew(kcd->kverts, &iter);
1126                 for (kfv = BLI_mempool_iterstep(&iter); kfv; kfv = BLI_mempool_iterstep(&iter)) {
1127                         if (!kfv->draw)
1128                                 continue;
1129
1130                         glColor3ubv(kcd->colors.point);
1131
1132                         glVertex3fv(kfv->cageco);
1133                 }
1134
1135                 glEnd();
1136         }
1137
1138         glPopMatrix();
1139
1140         if (v3d->zbuf) glEnable(GL_DEPTH_TEST);
1141 }
1142
1143 static float len_v3_tri_side_max(const float v1[3], const float v2[3], const float v3[3])
1144 {
1145         const float s1 = len_squared_v3v3(v1, v2);
1146         const float s2 = len_squared_v3v3(v2, v3);
1147         const float s3 = len_squared_v3v3(v3, v1);
1148
1149         return sqrtf(MAX3(s1, s2, s3));
1150 }
1151
1152 static BMEdgeHit *knife_edge_tri_isect(KnifeTool_OpData *kcd, BMBVHTree *bmtree,
1153                                        const float v1[3],  const float v2[3], const float v3[3],
1154                                        SmallHash *ehash, bglMats *mats, int *count)
1155 {
1156         BVHTree *tree2 = BLI_bvhtree_new(3, FLT_EPSILON * 4, 8, 8), *tree = BMBVH_BVHTree(bmtree);
1157         BMEdgeHit *edges = NULL;
1158         BLI_array_declare(edges);
1159         BVHTreeOverlap *results, *result;
1160         BMLoop **ls;
1161         float cos[9], lambda;
1162         unsigned int tot = 0;
1163         int i;
1164
1165         /* for comparing distances, error of intersection depends on triangle scale.
1166          * need to scale down before squaring for accurate comparison */
1167         const float depsilon = (FLT_EPSILON / 2.0f) * len_v3_tri_side_max(v1, v2, v3);
1168         const float depsilon_squared = depsilon * depsilon;
1169
1170         copy_v3_v3(cos + 0, v1);
1171         copy_v3_v3(cos + 3, v2);
1172         copy_v3_v3(cos + 6, v3);
1173
1174         BLI_bvhtree_insert(tree2, 0, cos, 3);
1175         BLI_bvhtree_balance(tree2);
1176
1177         result = results = BLI_bvhtree_overlap(tree, tree2, &tot);
1178
1179         for (i = 0; i < tot; i++, result++) {
1180                 BMLoop *l1;
1181                 BMFace *hitf;
1182                 ListBase *lst;
1183                 Ref *ref;
1184
1185                 ls = (BMLoop **)kcd->em->looptris[result->indexA];
1186
1187                 l1 = ls[0];
1188                 lst = knife_get_face_kedges(kcd, l1->f);
1189
1190                 for (ref = lst->first; ref; ref = ref->next) {
1191                         KnifeEdge *kfe = ref->ref;
1192
1193                         if (BLI_smallhash_haskey(ehash, (intptr_t)kfe)) {
1194                                 continue;  /* We already found a hit on this knife edge */
1195                         }
1196
1197                         if (isect_line_tri_v3(kfe->v1->cageco, kfe->v2->cageco, v1, v2, v3, &lambda, NULL)) {
1198                                 float p[3], no[3], view[3], sp[3];
1199
1200                                 interp_v3_v3v3(p, kfe->v1->cageco, kfe->v2->cageco, lambda);
1201
1202                                 if (kcd->curr.vert && len_squared_v3v3(kcd->curr.vert->cageco, p) < depsilon_squared) {
1203                                         continue;
1204                                 }
1205                                 if (kcd->prev.vert && len_squared_v3v3(kcd->prev.vert->cageco, p) < depsilon_squared) {
1206                                         continue;
1207                                 }
1208                                 if (len_squared_v3v3(kcd->prev.cage, p) < depsilon_squared ||
1209                                     len_squared_v3v3(kcd->curr.cage, p) < depsilon_squared)
1210                                 {
1211                                         continue;
1212                                 }
1213                                 if ((kcd->vc.rv3d->rflag & RV3D_CLIPPING) &&
1214                                     ED_view3d_clipping_test(kcd->vc.rv3d, p, TRUE))
1215                                 {
1216                                         continue;
1217                                 }
1218
1219                                 knife_project_v3(kcd, p, sp);
1220                                 ED_view3d_unproject(mats, view, sp[0], sp[1], 0.0f);
1221                                 mul_m4_v3(kcd->ob->imat, view);
1222
1223                                 if (kcd->cut_through) {
1224                                         hitf = FALSE;
1225                                 }
1226                                 else {
1227                                         /* check if this point is visible in the viewport */
1228                                         float p1[3], lambda1;
1229
1230                                         /* if face isn't planer, p may be behind the current tesselated tri,
1231                                          * so move it onto that and then a little towards eye */
1232                                         if (isect_line_tri_v3(p, view, ls[0]->v->co, ls[1]->v->co, ls[2]->v->co, &lambda1, NULL)) {
1233                                                 interp_v3_v3v3(p1, p, view, lambda1);
1234                                         }
1235                                         else {
1236                                                 copy_v3_v3(p1, p);
1237                                         }
1238                                         sub_v3_v3(view, p1);
1239                                         normalize_v3(view);
1240
1241                                         copy_v3_v3(no, view);
1242                                         mul_v3_fl(no, 0.003);
1243
1244                                         /* go towards view a bit */
1245                                         add_v3_v3(p1, no);
1246                                                 
1247                                         /* ray cast */
1248                                         hitf = BMBVH_RayCast(bmtree, p1, no, NULL, NULL);
1249                                 }
1250
1251                                 /* ok, if visible add the new point */
1252                                 if (!hitf && !BLI_smallhash_haskey(ehash, (intptr_t)kfe)) {
1253                                         BMEdgeHit hit;
1254         
1255                                         if (len_squared_v3v3(p, kcd->curr.co) < depsilon_squared ||
1256                                             len_squared_v3v3(p, kcd->prev.co) < depsilon_squared)
1257                                         {
1258                                                 continue;
1259                                         }
1260
1261                                         hit.kfe = kfe;
1262                                         hit.v = NULL;
1263
1264                                         knife_find_basef(kfe);
1265                                         hit.f = kfe->basef;
1266                                         hit.perc = len_v3v3(p, kfe->v1->cageco) / len_v3v3(kfe->v1->cageco, kfe->v2->cageco);
1267                                         copy_v3_v3(hit.cagehit, p);
1268
1269                                         interp_v3_v3v3(p, kfe->v1->co, kfe->v2->co, hit.perc);
1270                                         copy_v3_v3(hit.realhit, p);
1271
1272                                         /* BMESH_TODO: should also snap to vertices */
1273                                         if (kcd->snap_midpoints) {
1274                                                 float perc = hit.perc;
1275
1276                                                 /* select the closest from the edge endpoints or the midpoint */
1277                                                 if (perc < 0.25f) {
1278                                                         perc = 0.0f;
1279                                                 }
1280                                                 else if (perc < 0.75f) {
1281                                                         perc = 0.5f;
1282                                                 }
1283                                                 else {
1284                                                         perc = 1.0f;
1285                                                 }
1286
1287                                                 interp_v3_v3v3(hit.hit, kfe->v1->co, kfe->v2->co, perc);
1288                                                 interp_v3_v3v3(hit.cagehit, kfe->v1->cageco, kfe->v2->cageco, perc);
1289                                         }
1290                                         else {
1291                                                 copy_v3_v3(hit.hit, p);
1292                                         }
1293                                         knife_project_v3(kcd, hit.cagehit, hit.schit);
1294
1295                                         BLI_array_append(edges, hit);
1296                                         BLI_smallhash_insert(ehash, (intptr_t)kfe, NULL);
1297                                 }
1298                         }
1299                 }
1300         }
1301
1302         if (results)
1303                 MEM_freeN(results);
1304
1305         BLI_bvhtree_free(tree2);
1306         *count = BLI_array_count(edges);
1307
1308         return edges;
1309 }
1310
1311 static void knife_bgl_get_mats(KnifeTool_OpData *UNUSED(kcd), bglMats *mats)
1312 {
1313         bgl_get_mats(mats);
1314         //copy_m4_m4(mats->modelview, kcd->vc.rv3d->viewmat);
1315         //copy_m4_m4(mats->projection, kcd->vc.rv3d->winmat);
1316 }
1317
1318 /* Calculate maximum excursion (doubled) from (0,0,0) of mesh */
1319 static void calc_ortho_extent(KnifeTool_OpData *kcd)
1320 {
1321         BMIter iter;
1322         BMVert *v;
1323         BMesh* bm = kcd->em->bm;
1324         float max_xyz = 0.0f;
1325         int i;
1326
1327         BM_ITER_MESH(v, &iter, bm, BM_VERTS_OF_MESH) {
1328                 for (i = 0; i < 3; i++)
1329                         max_xyz = max_ff(max_xyz, fabs(v->co[i]));
1330         }
1331         kcd->ortho_extent = 2 * max_xyz;
1332 }
1333
1334 /* Finds visible (or all, if cutting through) edges that intersects the current screen drag line */
1335 static void knife_find_line_hits(KnifeTool_OpData *kcd)
1336 {
1337         bglMats mats;
1338         BMEdgeHit *e1, *e2;
1339         SmallHash hash, *ehash = &hash;
1340         float v1[3], v2[3], v3[3], v4[4], s1[3], s2[3];
1341         int i, c1, c2;
1342
1343         knife_bgl_get_mats(kcd, &mats);
1344
1345         if (kcd->linehits) {
1346                 MEM_freeN(kcd->linehits);
1347                 kcd->linehits = NULL;
1348                 kcd->totlinehit = 0;
1349         }
1350
1351         copy_v3_v3(v1, kcd->prev.cage);
1352         copy_v3_v3(v2, kcd->curr.cage);
1353
1354         /* project screen line's 3d coordinates back into 2d */
1355         knife_project_v3(kcd, v1, s1);
1356         knife_project_v3(kcd, v2, s2);
1357
1358         if (len_v2v2(s1, s2) < 1)
1359                 return;
1360
1361         /* unproject screen line */
1362         ED_view3d_win_to_segment_clip(kcd->ar, kcd->vc.v3d, s1, v1, v3);
1363         ED_view3d_win_to_segment_clip(kcd->ar, kcd->vc.v3d, s2, v2, v4);
1364
1365         mul_m4_v3(kcd->ob->imat, v1);
1366         mul_m4_v3(kcd->ob->imat, v2);
1367         mul_m4_v3(kcd->ob->imat, v3);
1368         mul_m4_v3(kcd->ob->imat, v4);
1369
1370         /* numeric error, 'v1' -> 'v2', 'v2' -> 'v4' can end up being ~2000 units apart in otho mode
1371          * (from ED_view3d_win_to_segment_clip() above)
1372          * this gives precision error in 'knife_edge_tri_isect', rather then solving properly
1373          * (which may involve using doubles everywhere!),
1374          * limit the distance between these points */
1375         if (kcd->is_ortho) {
1376                 if (kcd->ortho_extent == 0.0f)
1377                         calc_ortho_extent(kcd);
1378                 limit_dist_v3(v1, v3, kcd->ortho_extent + 10.0f);
1379                 limit_dist_v3(v2, v4, kcd->ortho_extent + 10.0f);
1380         }
1381
1382         BLI_smallhash_init(ehash);
1383
1384         /* test two triangles of sceen line's plane */
1385         e1 = knife_edge_tri_isect(kcd, kcd->bmbvh, v1, v2, v3, ehash, &mats, &c1);
1386         e2 = knife_edge_tri_isect(kcd, kcd->bmbvh, v2, v3, v4, ehash, &mats, &c2);
1387         if (c1 && c2) {
1388                 e1 = MEM_reallocN(e1, sizeof(BMEdgeHit) * (c1 + c2));
1389                 memcpy(e1 + c1, e2, sizeof(BMEdgeHit) * c2);
1390                 MEM_freeN(e2);
1391         }
1392         else if (c2) {
1393                 e1 = e2;
1394         }
1395
1396         kcd->linehits = e1;
1397         kcd->totlinehit = c1 + c2;
1398
1399         /* find position along screen line, used for sorting */
1400         for (i = 0; i < kcd->totlinehit; i++) {
1401                 BMEdgeHit *lh = e1 + i;
1402
1403                 lh->l = len_v2v2(lh->schit, s1) / len_v2v2(s2, s1);
1404         }
1405
1406         BLI_smallhash_release(ehash);
1407 }
1408
1409 /* this works but gives numeric problems [#33400] */
1410 #if 0
1411 static void knife_input_ray_cast(KnifeTool_OpData *kcd, const int mval_i[2],
1412                                  float r_origin[3], float r_ray[3])
1413 {
1414         bglMats mats;
1415         float mval[2], imat[3][3];
1416
1417         knife_bgl_get_mats(kcd, &mats);
1418
1419         mval[0] = (float)mval_i[0];
1420         mval[1] = (float)mval_i[1];
1421
1422         /* unproject to find view ray */
1423         ED_view3d_unproject(&mats, r_origin, mval[0], mval[1], 0.0f);
1424
1425         if (kcd->is_ortho) {
1426                 negate_v3_v3(r_ray, kcd->vc.rv3d->viewinv[2]);
1427         }
1428         else {
1429                 sub_v3_v3v3(r_ray, r_origin, kcd->vc.rv3d->viewinv[3]);
1430         }
1431         normalize_v3(r_ray);
1432
1433         /* transform into object space */
1434         invert_m4_m4(kcd->ob->imat, kcd->ob->obmat);
1435         copy_m3_m4(imat, kcd->ob->obmat);
1436         invert_m3(imat);
1437
1438         mul_m4_v3(kcd->ob->imat, r_origin);
1439         mul_m3_v3(imat, r_ray);
1440 }
1441 #endif
1442
1443 static void knife_input_ray_segment(KnifeTool_OpData *kcd, const int mval_i[2], const float ofs,
1444                                     float r_origin[3], float r_origin_ofs[3])
1445 {
1446         bglMats mats;
1447         float mval[2];
1448
1449         knife_bgl_get_mats(kcd, &mats);
1450
1451         mval[0] = (float)mval_i[0];
1452         mval[1] = (float)mval_i[1];
1453
1454         /* unproject to find view ray */
1455         ED_view3d_unproject(&mats, r_origin,     mval[0], mval[1], 0.0f);
1456         ED_view3d_unproject(&mats, r_origin_ofs, mval[0], mval[1], ofs);
1457
1458         /* transform into object space */
1459         invert_m4_m4(kcd->ob->imat, kcd->ob->obmat);
1460
1461         mul_m4_v3(kcd->ob->imat, r_origin);
1462         mul_m4_v3(kcd->ob->imat, r_origin_ofs);
1463 }
1464
1465 static BMFace *knife_find_closest_face(KnifeTool_OpData *kcd, float co[3], float cageco[3], int *is_space)
1466 {
1467         BMFace *f;
1468         float dist = KMAXDIST;
1469         float origin[3];
1470         float origin_ofs[3];
1471         float ray[3];
1472
1473         /* unproject to find view ray */
1474         knife_input_ray_segment(kcd, kcd->vc.mval, 1.0f, origin, origin_ofs);
1475         sub_v3_v3v3(ray, origin_ofs, origin);
1476
1477         f = BMBVH_RayCast(kcd->bmbvh, origin, ray, co, cageco);
1478
1479         if (is_space)
1480                 *is_space = !f;
1481
1482         if (!f) {
1483                 /* try to use backbuffer selection method if ray casting failed */
1484                 f = EDBM_face_find_nearest(&kcd->vc, &dist);
1485
1486                 /* cheat for now; just put in the origin instead
1487                  * of a true coordinate on the face.
1488                  * This just puts a point 1.0f infront of the view. */
1489                 add_v3_v3v3(co, origin, ray);
1490         }
1491
1492         return f;
1493 }
1494
1495 /* find the 2d screen space density of vertices within a radius.  used to scale snapping
1496  * distance for picking edges/verts.*/
1497 static int knife_sample_screen_density(KnifeTool_OpData *kcd, float radius)
1498 {
1499         BMFace *f;
1500         int is_space;
1501         float co[3], cageco[3], sco[3];
1502
1503         f = knife_find_closest_face(kcd, co, cageco, &is_space);
1504
1505         if (f && !is_space) {
1506                 ListBase *lst;
1507                 Ref *ref;
1508                 float dis;
1509                 int c = 0;
1510
1511                 knife_project_v3(kcd, cageco, sco);
1512
1513                 lst = knife_get_face_kedges(kcd, f);
1514                 for (ref = lst->first; ref; ref = ref->next) {
1515                         KnifeEdge *kfe = ref->ref;
1516                         int i;
1517
1518                         for (i = 0; i < 2; i++) {
1519                                 KnifeVert *kfv = i ? kfe->v2 : kfe->v1;
1520
1521                                 knife_project_v3(kcd, kfv->cageco, kfv->sco);
1522
1523                                 dis = len_v2v2(kfv->sco, sco);
1524                                 if (dis < radius) {
1525                                         if (kcd->vc.rv3d->rflag & RV3D_CLIPPING) {
1526                                                 if (ED_view3d_clipping_test(kcd->vc.rv3d, kfv->cageco, TRUE) == 0) {
1527                                                         c++;
1528                                                 }
1529                                         }
1530                                         else {
1531                                                 c++;
1532                                         }
1533                                 }
1534                         }
1535                 }
1536
1537                 return c;
1538         }
1539
1540         return 0;
1541 }
1542
1543 /* returns snapping distance for edges/verts, scaled by the density of the
1544  * surrounding mesh (in screen space)*/
1545 static float knife_snap_size(KnifeTool_OpData *kcd, float maxsize)
1546 {
1547         float density = (float)knife_sample_screen_density(kcd, maxsize * 2.0f);
1548
1549         if (density < 1.0f)
1550                 density = 1.0f;
1551
1552         return min_ff(maxsize / (density * 0.5f), maxsize);
1553 }
1554
1555 /* p is closest point on edge to the mouse cursor */
1556 static KnifeEdge *knife_find_closest_edge(KnifeTool_OpData *kcd, float p[3], float cagep[3], BMFace **fptr, int *is_space)
1557 {
1558         BMFace *f;
1559         float co[3], cageco[3], sco[3], maxdist = knife_snap_size(kcd, kcd->ethresh);
1560
1561         if (kcd->ignore_vert_snapping)
1562                 maxdist *= 0.5f;
1563
1564         f = knife_find_closest_face(kcd, co, cageco, NULL);
1565         *is_space = !f;
1566
1567         /* set p to co, in case we don't find anything, means a face cut */
1568         copy_v3_v3(p, co);
1569         copy_v3_v3(cagep, cageco);
1570
1571         kcd->curr.bmface = f;
1572
1573         if (f) {
1574                 KnifeEdge *cure = NULL;
1575                 ListBase *lst;
1576                 Ref *ref;
1577                 float dis, curdis = FLT_MAX;
1578
1579                 knife_project_v3(kcd, cageco, sco);
1580
1581                 /* look through all edges associated with this face */
1582                 lst = knife_get_face_kedges(kcd, f);
1583                 for (ref = lst->first; ref; ref = ref->next) {
1584                         KnifeEdge *kfe = ref->ref;
1585
1586                         /* project edge vertices into screen space */
1587                         knife_project_v3(kcd, kfe->v1->cageco, kfe->v1->sco);
1588                         knife_project_v3(kcd, kfe->v2->cageco, kfe->v2->sco);
1589
1590                         dis = dist_to_line_segment_v2(sco, kfe->v1->sco, kfe->v2->sco);
1591                         if (dis < curdis && dis < maxdist) {
1592                                 if (kcd->vc.rv3d->rflag & RV3D_CLIPPING) {
1593                                         float lambda = line_point_factor_v2(sco, kfe->v1->sco, kfe->v2->sco);
1594                                         float vec[3];
1595
1596                                         interp_v3_v3v3(vec, kfe->v1->cageco, kfe->v2->cageco, lambda);
1597
1598                                         if (ED_view3d_clipping_test(kcd->vc.rv3d, vec, TRUE) == 0) {
1599                                                 cure = kfe;
1600                                                 curdis = dis;
1601                                         }
1602                                 }
1603                                 else {
1604                                         cure = kfe;
1605                                         curdis = dis;
1606                                 }
1607                         }
1608                 }
1609
1610                 if (fptr)
1611                         *fptr = f;
1612
1613                 if (cure && p) {
1614                         if (!kcd->ignore_edge_snapping || !(cure->e)) {
1615                                 KnifeVert *edgesnap = NULL;
1616
1617                                 if (kcd->snap_midpoints) {
1618                                         mid_v3_v3v3(p, cure->v1->co, cure->v2->co);
1619                                         mid_v3_v3v3(cagep, cure->v1->cageco, cure->v2->cageco);
1620                                 }
1621                                 else {
1622                                         float d;
1623
1624                                         closest_to_line_segment_v3(cagep, cageco, cure->v1->cageco, cure->v2->cageco);
1625                                         d = len_v3v3(cagep, cure->v1->cageco) / len_v3v3(cure->v1->cageco, cure->v2->cageco);
1626                                         interp_v3_v3v3(p, cure->v1->co, cure->v2->co, d);
1627                                 }
1628
1629                                 /* update mouse coordinates to the snapped-to edge's screen coordinates
1630                                  * this is important for angle snap, which uses the previous mouse position */
1631                                 edgesnap = new_knife_vert(kcd, p, cagep);
1632                                 kcd->curr.mval[0] = (int)edgesnap->sco[0];
1633                                 kcd->curr.mval[1] = (int)edgesnap->sco[1];
1634
1635                         }
1636                         else {
1637                                 return NULL;
1638                         }
1639                 }
1640
1641                 return cure;
1642         }
1643
1644         if (fptr)
1645                 *fptr = NULL;
1646
1647         return NULL;
1648 }
1649
1650 /* find a vertex near the mouse cursor, if it exists */
1651 static KnifeVert *knife_find_closest_vert(KnifeTool_OpData *kcd, float p[3], float cagep[3], BMFace **fptr,
1652                                           int *is_space)
1653 {
1654         BMFace *f;
1655         float co[3], cageco[3], sco[3], maxdist = knife_snap_size(kcd, kcd->vthresh);
1656
1657         if (kcd->ignore_vert_snapping)
1658                 maxdist *= 0.5f;
1659
1660         f = knife_find_closest_face(kcd, co, cageco, is_space);
1661
1662         /* set p to co, in case we don't find anything, means a face cut */
1663         copy_v3_v3(p, co);
1664         copy_v3_v3(cagep, p);
1665         kcd->curr.bmface = f;
1666
1667         if (f) {
1668                 ListBase *lst;
1669                 Ref *ref;
1670                 KnifeVert *curv = NULL;
1671                 float dis, curdis = FLT_MAX;
1672
1673                 knife_project_v3(kcd, cageco, sco);
1674
1675                 lst = knife_get_face_kedges(kcd, f);
1676                 for (ref = lst->first; ref; ref = ref->next) {
1677                         KnifeEdge *kfe = ref->ref;
1678                         int i;
1679
1680                         for (i = 0; i < 2; i++) {
1681                                 KnifeVert *kfv = i ? kfe->v2 : kfe->v1;
1682
1683                                 knife_project_v3(kcd, kfv->cageco, kfv->sco);
1684
1685                                 dis = len_v2v2(kfv->sco, sco);
1686                                 if (dis < curdis && dis < maxdist) {
1687                                         if (kcd->vc.rv3d->rflag & RV3D_CLIPPING) {
1688                                                 if (ED_view3d_clipping_test(kcd->vc.rv3d, kfv->cageco, TRUE) == 0) {
1689                                                         curv = kfv;
1690                                                         curdis = dis;
1691                                                 }
1692                                         }
1693                                         else {
1694                                                 curv = kfv;
1695                                                 curdis = dis;
1696                                         }
1697                                 }
1698                         }
1699                 }
1700
1701                 if (!kcd->ignore_vert_snapping || !(curv && curv->v)) {
1702                         if (fptr)
1703                                 *fptr = f;
1704
1705                         if (curv && p) {
1706                                 copy_v3_v3(p, curv->co);
1707                                 copy_v3_v3(cagep, curv->cageco);
1708
1709                                 /* update mouse coordinates to the snapped-to vertex's screen coordinates
1710                                  * this is important for angle snap, which uses the previous mouse position */
1711                                 kcd->curr.mval[0] = (int)curv->sco[0];
1712                                 kcd->curr.mval[1] = (int)curv->sco[1];
1713                         }
1714
1715                         return curv;
1716                 }
1717                 else {
1718                         if (fptr)
1719                                 *fptr = f;
1720
1721                         return NULL;
1722                 }
1723         }
1724
1725         if (fptr)
1726                 *fptr = NULL;
1727
1728         return NULL;
1729 }
1730
1731 static void knife_snap_angle(KnifeTool_OpData *kcd)
1732 {
1733         int dx, dy;
1734         float w, abs_tan;
1735
1736         dx = kcd->vc.mval[0] - kcd->prev.mval[0];
1737         dy = kcd->vc.mval[1] - kcd->prev.mval[1];
1738         if (dx == 0 || dy == 0)
1739                 return;
1740
1741         w = (float)dy / (float)dx;
1742         abs_tan = fabsf(w);
1743         if (abs_tan <= 0.4142f) { /* tan(22.5 degrees) = 0.4142 */
1744                 kcd->angle_snapping = ANGLE_0;
1745                 kcd->vc.mval[1] = kcd->prev.mval[1];
1746         }
1747         else if (abs_tan < 2.4142f) { /* tan(67.5 degrees) = 2.4142 */
1748                 if (w > 0) {
1749                         kcd->angle_snapping = ANGLE_45;
1750                         kcd->vc.mval[1] = kcd->prev.mval[1] + dx;
1751                 }
1752                 else {
1753                         kcd->angle_snapping = ANGLE_135;
1754                         kcd->vc.mval[1] = kcd->prev.mval[1] - dx;
1755                 }
1756         }
1757         else {
1758                 kcd->angle_snapping = ANGLE_90;
1759                 kcd->vc.mval[0] = kcd->prev.mval[0];
1760         }
1761 }
1762
1763 /* update active knife edge/vert pointers */
1764 static int knife_update_active(KnifeTool_OpData *kcd)
1765 {
1766         if (kcd->angle_snapping != ANGLE_FREE && kcd->mode == MODE_DRAGGING)
1767                 knife_snap_angle(kcd);
1768
1769         knife_pos_data_clear(&kcd->curr);
1770         kcd->curr.mval[0] = kcd->vc.mval[0];
1771         kcd->curr.mval[1] = kcd->vc.mval[1];
1772
1773         /* XXX knife_snap_angle updates the view coordinate mouse values to constrained angles,
1774          * which current mouse values are set to current mouse values are then used
1775          * for vertex and edge snap detection, without regard to the exact angle constraint */
1776         kcd->curr.vert = knife_find_closest_vert(kcd, kcd->curr.co, kcd->curr.cage, &kcd->curr.bmface, &kcd->curr.is_space);
1777
1778         if (!kcd->curr.vert) {
1779                 kcd->curr.edge = knife_find_closest_edge(kcd, kcd->curr.co, kcd->curr.cage, &kcd->curr.bmface, &kcd->curr.is_space);
1780         }
1781
1782         /* if no hits are found this would normally default to (0, 0, 0) so instead
1783          * get a point at the mouse ray closest to the previous point.
1784          * Note that drawing lines in `free-space` isn't properly supported
1785          * but theres no guarantee (0, 0, 0) has any geometry either - campbell */
1786         if (kcd->curr.vert == NULL && kcd->curr.edge == NULL) {
1787                 float origin[3];
1788                 float origin_ofs[3];
1789
1790                 knife_input_ray_segment(kcd, kcd->vc.mval, 1.0f, origin, origin_ofs);
1791
1792                 closest_to_line_v3(kcd->curr.cage, kcd->prev.cage, origin_ofs, origin);
1793         }
1794
1795         if (kcd->mode == MODE_DRAGGING) {
1796                 knife_find_line_hits(kcd);
1797         }
1798         return 1;
1799 }
1800
1801 #define SCANFILL_CUTS 0
1802 #if SCANFILL_CUTS
1803
1804 #define MARK            4
1805 #define DEL             8
1806 #define VERT_ON_EDGE    16
1807 #define VERT_ORIG       32
1808 #define FACE_FLIP       64
1809 #define BOUNDARY        128
1810 #define FACE_NEW        256
1811
1812 typedef struct facenet_entry {
1813         struct facenet_entry *next, *prev;
1814         KnifeEdge *kfe;
1815 } facenet_entry;
1816
1817 static void rnd_offset_co(float co[3], float scale)
1818 {
1819         int i;
1820
1821         for (i = 0; i < 3; i++) {
1822                 co[i] += (BLI_frand() - 0.5) * scale;
1823         }
1824 }
1825
1826 static void remerge_faces(KnifeTool_OpData *kcd)
1827 {
1828         BMesh *bm = kcd->em->bm;
1829         SmallHash svisit, *visit = &svisit;
1830         BMIter iter;
1831         BMFace *f;
1832         BMFace **stack = NULL;
1833         BLI_array_declare(stack);
1834         BMFace **faces = NULL;
1835         BLI_array_declare(faces);
1836         BMOperator bmop;
1837         int idx;
1838
1839         BMO_op_initf(bm, &bmop, "beautify_fill faces=%ff constrain_edges=%fe", FACE_NEW, BOUNDARY);
1840
1841         BMO_op_exec(bm, &bmop);
1842         BMO_slot_buffer_flag_enable(bm, &bmop, "geom.out", BM_FACE, FACE_NEW);
1843
1844         BMO_op_finish(bm, &bmop);
1845
1846         BLI_smallhash_init(visit);
1847         BM_ITER_MESH (f, &iter, bm, BM_FACES_OF_MESH) {
1848                 BMIter eiter;
1849                 BMEdge *e;
1850                 BMFace *f2;
1851
1852                 if (!BMO_elem_flag_test(bm, f, FACE_NEW))
1853                         continue;
1854
1855                 if (BLI_smallhash_haskey(visit, (intptr_t)f))
1856                         continue;
1857
1858                 BLI_array_empty(stack);
1859                 BLI_array_empty(faces);
1860                 BLI_array_append(stack, f);
1861                 BLI_smallhash_insert(visit, (intptr_t)f, NULL);
1862
1863                 do {
1864                         f2 = BLI_array_pop(stack);
1865
1866                         BLI_array_append(faces, f2);
1867
1868                         BM_ITER_ELEM (e, &eiter, f2, BM_EDGES_OF_FACE) {
1869                                 BMIter fiter;
1870                                 BMFace *f3;
1871
1872                                 if (BMO_elem_flag_test(bm, e, BOUNDARY))
1873                                         continue;
1874
1875                                 BM_ITER_ELEM (f3, &fiter, e, BM_FACES_OF_EDGE) {
1876                                         if (!BMO_elem_flag_test(bm, f3, FACE_NEW))
1877                                                 continue;
1878                                         if (BLI_smallhash_haskey(visit, (intptr_t)f3))
1879                                                 continue;
1880
1881                                         BLI_smallhash_insert(visit, (intptr_t)f3, NULL);
1882                                         BLI_array_append(stack, f3);
1883                                 }
1884                         }
1885                 } while (BLI_array_count(stack) > 0);
1886
1887                 if (BLI_array_count(faces) > 0) {
1888                         idx = BM_elem_index_get(faces[0]);
1889
1890                         f2 = BM_faces_join(bm, faces, BLI_array_count(faces), TRUE);
1891                         if (f2) {
1892                                 BMO_elem_flag_enable(bm, f2, FACE_NEW);
1893                                 BM_elem_index_set(f2, idx); /* set_dirty! *//* BMESH_TODO, check if this is valid or not */
1894                         }
1895                 }
1896         }
1897         /* BMESH_TODO, check if the code above validates the indices */
1898         /* bm->elem_index_dirty &= ~BM_FACE; */
1899         bm->elem_index_dirty |= BM_FACE;
1900
1901         BLI_smallhash_release(visit);
1902
1903         BLI_array_free(stack);
1904         BLI_array_free(faces);
1905 }
1906
1907 /* use edgenet to fill faces.  this is a bit annoying and convoluted.*/
1908 static void knifenet_fill_faces(KnifeTool_OpData *kcd)
1909 {
1910         ScanFillContext sf_ctx;
1911         BMesh *bm = kcd->em->bm;
1912         BMIter bmiter;
1913         BLI_mempool_iter iter;
1914         BMFace *f;
1915         BMEdge *e;
1916         KnifeVert *kfv;
1917         KnifeEdge *kfe;
1918         facenet_entry *entry;
1919         ListBase *face_nets = MEM_callocN(sizeof(ListBase) * bm->totface, "face_nets");
1920         BMFace **faces = MEM_callocN(sizeof(BMFace *) * bm->totface, "faces knife");
1921         MemArena *arena = BLI_memarena_new(1 << 16, "knifenet_fill_faces");
1922         SmallHash shash;
1923         int i, j, k = 0, totface = bm->totface;
1924
1925         BMO_push(bm, NULL);
1926         bmesh_edit_begin(bm, BMO_OP_FLAG_UNTAN_MULTIRES);
1927
1928         /* BMESH_TODO this should be valid now, leaving here until we can ensure this - campbell */
1929         i = 0;
1930         BM_ITER_MESH (f, &bmiter, bm, BM_FACES_OF_MESH) {
1931                 BM_elem_index_set(f, i); /* set_inline */
1932                 faces[i] = f;
1933                 i++;
1934         }
1935         bm->elem_index_dirty &= ~BM_FACE;
1936
1937         BM_ITER_MESH (e, &bmiter, bm, BM_EDGES_OF_MESH) {
1938                 BMO_elem_flag_enable(bm, e, BOUNDARY);
1939         }
1940
1941         /* turn knife verts into real verts, as necessary */
1942         BLI_mempool_iternew(kcd->kverts, &iter);
1943         for (kfv = BLI_mempool_iterstep(&iter); kfv; kfv = BLI_mempool_iterstep(&iter)) {
1944                 if (!kfv->v) {
1945                         /* shouldn't we be at least copying the normal? - if not some comment here should explain why - campbell */
1946                         kfv->v = BM_vert_create(bm, kfv->co, NULL);
1947                         kfv->flag = 1;
1948                         BMO_elem_flag_enable(bm, kfv->v, DEL);
1949                 }
1950                 else {
1951                         kfv->flag = 0;
1952                         BMO_elem_flag_enable(bm, kfv->v, VERT_ORIG);
1953                 }
1954
1955                 BMO_elem_flag_enable(bm, kfv->v, MARK);
1956         }
1957
1958         /* we want to only do changed faces.  first, go over new edges and add to
1959          * face net lists.*/
1960         i = j = k = 0;
1961         BLI_mempool_iternew(kcd->kedges, &iter);
1962         for (kfe = BLI_mempool_iterstep(&iter); kfe; kfe = BLI_mempool_iterstep(&iter)) {
1963                 Ref *ref;
1964                 if (!kfe->v1 || !kfe->v2 || kfe->v1->inspace || kfe->v2->inspace)
1965                         continue;
1966
1967                 i++;
1968
1969                 if (kfe->e && kfe->v1->v == kfe->e->v1 && kfe->v2->v == kfe->e->v2) {
1970                         kfe->oe = kfe->e;
1971                         continue;
1972                 }
1973
1974                 j++;
1975
1976                 if (kfe->e) {
1977                         kfe->oe = kfe->e;
1978
1979                         BMO_elem_flag_enable(bm, kfe->e, DEL);
1980                         BMO_elem_flag_disable(bm, kfe->e, BOUNDARY);
1981                         kfe->e = NULL;
1982                 }
1983
1984                 kfe->e = BM_edge_create(bm, kfe->v1->v, kfe->v2->v, NULL, BM_CREATE_NO_DOUBLE);
1985                 BMO_elem_flag_enable(bm, kfe->e, BOUNDARY);
1986
1987                 for (ref = kfe->faces.first; ref; ref = ref->next) {
1988                         f = ref->ref;
1989
1990                         entry = BLI_memarena_alloc(arena, sizeof(*entry));
1991                         entry->kfe = kfe;
1992                         BLI_addtail(face_nets + BM_elem_index_get(f), entry);
1993                 }
1994         }
1995
1996         /* go over original edges, and add to faces with new geometry */
1997         BLI_mempool_iternew(kcd->kedges, &iter);
1998         for (kfe = BLI_mempool_iterstep(&iter); kfe; kfe = BLI_mempool_iterstep(&iter)) {
1999                 Ref *ref;
2000
2001                 if (!kfe->v1 || !kfe->v2 || kfe->v1->inspace || kfe->v2->inspace)
2002                         continue;
2003                 if (!(kfe->oe && kfe->v1->v == kfe->oe->v1 && kfe->v2->v == kfe->oe->v2))
2004                         continue;
2005
2006                 k++;
2007
2008                 BMO_elem_flag_enable(bm, kfe->e, BOUNDARY);
2009                 kfe->oe = kfe->e;
2010
2011                 for (ref = kfe->faces.first; ref; ref = ref->next) {
2012                         f = ref->ref;
2013
2014                         if (face_nets[BM_elem_index_get(f)].first) {
2015                                 entry = BLI_memarena_alloc(arena, sizeof(*entry));
2016                                 entry->kfe = kfe;
2017                                 BLI_addtail(face_nets + BM_elem_index_get(f), entry);
2018                         }
2019                 }
2020         }
2021
2022         BLI_srand(0);
2023
2024         for (i = 0; i < totface; i++) {
2025                 SmallHash *hash = &shash;
2026                 ScanFillFace *sf_tri;
2027                 ScanFillVert *sf_vert, *sf_vert_last;
2028                 int j;
2029                 float rndscale = (KNIFE_FLT_EPS / 4.0f);
2030
2031                 f = faces[i];
2032                 BLI_smallhash_init(hash);
2033
2034                 if (face_nets[i].first)
2035                         BMO_elem_flag_enable(bm, f, DEL);
2036
2037                 BLI_scanfill_begin(&sf_ctx);
2038
2039                 for (entry = face_nets[i].first; entry; entry = entry->next) {
2040                         if (!BLI_smallhash_haskey(hash, (intptr_t)entry->kfe->v1)) {
2041                                 sf_vert = BLI_scanfill_vert_add(&sf_ctx, entry->kfe->v1->v->co);
2042                                 sf_vert->poly_nr = 0;
2043                                 rnd_offset_co(sf_vert->co, rndscale);
2044                                 sf_vert->tmp.p = entry->kfe->v1->v;
2045                                 BLI_smallhash_insert(hash, (intptr_t)entry->kfe->v1, sf_vert);
2046                         }
2047
2048                         if (!BLI_smallhash_haskey(hash, (intptr_t)entry->kfe->v2)) {
2049                                 sf_vert = BLI_scanfill_vert_add(&sf_ctx, entry->kfe->v2->v->co);
2050                                 sf_vert->poly_nr = 0;
2051                                 rnd_offset_co(sf_vert->co, rndscale);
2052                                 sf_vert->tmp.p = entry->kfe->v2->v;
2053                                 BLI_smallhash_insert(hash, (intptr_t)entry->kfe->v2, sf_vert);
2054                         }
2055                 }
2056
2057                 for (j = 0, entry = face_nets[i].first; entry; entry = entry->next, j++) {
2058                         sf_vert_last = BLI_smallhash_lookup(hash, (intptr_t)entry->kfe->v1);
2059                         sf_vert = BLI_smallhash_lookup(hash, (intptr_t)entry->kfe->v2);
2060
2061                         sf_vert->poly_nr++;
2062                         sf_vert_last->poly_nr++;
2063                 }
2064
2065                 for (j = 0, entry = face_nets[i].first; entry; entry = entry->next, j++) {
2066                         sf_vert_last = BLI_smallhash_lookup(hash, (intptr_t)entry->kfe->v1);
2067                         sf_vert = BLI_smallhash_lookup(hash, (intptr_t)entry->kfe->v2);
2068
2069                         if (sf_vert->poly_nr > 1 && sf_vert_last->poly_nr > 1) {
2070                                 ScanFillEdge *sf_edge;
2071                                 sf_edge = BLI_scanfill_edge_add(&sf_ctx, sf_vert_last, sf_vert);
2072                                 if (entry->kfe->oe)
2073                                         sf_edge->f = SF_EDGE_BOUNDARY;  /* mark as original boundary edge */
2074
2075                                 BMO_elem_flag_disable(bm, entry->kfe->e->v1, DEL);
2076                                 BMO_elem_flag_disable(bm, entry->kfe->e->v2, DEL);
2077                         }
2078                         else {
2079                                 if (sf_vert_last->poly_nr < 2)
2080                                         BLI_remlink(&sf_ctx.fillvertbase, sf_vert_last);
2081                                 if (sf_vert->poly_nr < 2)
2082                                         BLI_remlink(&sf_ctx.fillvertbase, sf_vert);
2083                         }
2084                 }
2085
2086                 BLI_scanfill_calc(&sf_ctx, 0);
2087
2088                 for (sf_tri = sf_ctx.fillfacebase.first; sf_tri; sf_tri = sf_tri->next) {
2089                         BMVert *v1 = sf_tri->v3->tmp.p, *v2 = sf_tri->v2->tmp.p, *v3 = sf_tri->v1->tmp.p;
2090                         BMFace *f2;
2091                         BMLoop *l_iter;
2092                         BMVert *verts[3] = {v1, v2, v3};
2093
2094                         if (v1 == v2 || v2 == v3 || v1 == v3)
2095                                 continue;
2096                         if (BM_face_exists(bm, verts, 3, &f2))
2097                                 continue;
2098
2099                         f2 = BM_face_create_quad_tri(bm,
2100                                                      v1, v2, v3, NULL,
2101                                                      NULL, FALSE);
2102
2103                         BMO_elem_flag_enable(bm, f2, FACE_NEW);
2104
2105                         l_iter = BM_FACE_FIRST_LOOP(f2);
2106                         do {
2107                                 BMO_elem_flag_disable(bm, l_iter->e, DEL);
2108                         } while ((l_iter = l_iter->next) != BM_FACE_FIRST_LOOP(f2));
2109
2110                         BMO_elem_flag_disable(bm, f2, DEL);
2111                         BM_elem_index_set(f2, i); /* set_dirty! *//* note, not 100% sure this is dirty? need to check */
2112
2113                         BM_face_normal_update(f2);
2114                         if (dot_v3v3(f->no, f2->no) < 0.0f) {
2115                                 BM_face_normal_flip(bm, f2);
2116                         }
2117                 }
2118
2119                 BLI_scanfill_end(&sf_ctx);
2120                 BLI_smallhash_release(hash);
2121         }
2122         bm->elem_index_dirty |= BM_FACE;
2123
2124         /* interpolate customdata */
2125         BM_ITER_MESH (f, &bmiter, bm, BM_FACES_OF_MESH) {
2126                 BMLoop *l1;
2127                 BMFace *f2;
2128                 BMIter liter1;
2129
2130                 if (!BMO_elem_flag_test(bm, f, FACE_NEW))
2131                         continue;
2132
2133                 f2 = faces[BM_elem_index_get(f)];
2134                 if (BM_elem_index_get(f) < 0 || BM_elem_index_get(f) >= totface) {
2135                         fprintf(stderr, "%s: face index out of range! (bmesh internal error)\n", __func__);
2136                 }
2137
2138                 BM_elem_attrs_copy(bm, bm, f2, f);
2139
2140                 BM_ITER_ELEM (l1, &liter1, f, BM_LOOPS_OF_FACE) {
2141                         BM_loop_interp_from_face(bm, l1, f2, TRUE, TRUE);
2142                 }
2143         }
2144
2145         /* merge triangles back into faces */
2146         remerge_faces(kcd);
2147
2148         /* delete left over faces */
2149         BMO_op_callf(bm, BMO_FLAG_DEFAULTS, "delete geom=%ff context=%i", DEL, DEL_ONLYFACES);
2150         BMO_op_callf(bm, BMO_FLAG_DEFAULTS, "delete geom=%fe context=%i", DEL, DEL_EDGES);
2151         BMO_op_callf(bm, BMO_FLAG_DEFAULTS, "delete geom=%fv context=%i", DEL, DEL_VERTS);
2152
2153         if (face_nets) 
2154                 MEM_freeN(face_nets);
2155         if (faces)
2156                 MEM_freeN(faces);
2157         BLI_memarena_free(arena);
2158
2159         BMO_error_clear(bm); /* remerge_faces sometimes raises errors, so make sure to clear them */
2160
2161         bmesh_edit_end(bm, BMO_OP_FLAG_UNTAN_MULTIRES);
2162         BMO_pop(bm);
2163 }
2164
2165 #else  /* use direct (non-scanfill) method for cuts */
2166
2167 /* assuming v is on line ab, what fraction of the way is v from a to b? */
2168 static float frac_along(const float a[3], const float b[3], const float v[3])
2169 {
2170         float lab;
2171
2172         lab = len_v3v3(a, b);
2173         if (lab == 0.0f) {
2174                 return 0.0f;
2175         }
2176         else {
2177                 return len_v3v3(a, v) / lab;
2178         }
2179 }
2180
2181 /* sort list of kverts by fraction along edge e */
2182 static void sort_by_frac_along(ListBase *lst, BMEdge *e)
2183 {
2184         KnifeVert *vcur, *vprev;
2185         float *v1co, *v2co;
2186         Ref *cur = NULL, *prev = NULL, *next = NULL;
2187
2188         if (lst->first == lst->last)
2189                 return;
2190
2191         v1co = e->v1->co;
2192         v2co = e->v2->co;
2193
2194         for (cur = ((Ref *)lst->first)->next; cur; cur = next) {
2195                 next = cur->next;
2196                 prev = cur->prev;
2197
2198                 BLI_remlink(lst, cur);
2199
2200                 vcur = cur->ref;
2201                 while (prev) {
2202                         vprev = prev->ref;
2203                         if (frac_along(v1co, v2co, vprev->co) <= frac_along(v1co, v2co, vcur->co))
2204                                 break;
2205                         prev = prev->prev;
2206                 }
2207
2208                 BLI_insertlinkafter(lst, prev, cur);
2209         }
2210 }
2211
2212 /* The chain so far goes from an instantiated vertex to kfv (some may be reversed).
2213  * If possible, complete the chain to another instantiated vertex and return 1, else return 0.
2214  * The visited hash says which KnifeVert's have already been tried, not including kfv. */
2215 static int find_chain_search(KnifeTool_OpData *kcd, KnifeVert *kfv, ListBase *fedges, SmallHash *visited,
2216                              ListBase *chain)
2217 {
2218         Ref *r;
2219         KnifeEdge *kfe;
2220         KnifeVert *kfv_other;
2221
2222         if (kfv->v)
2223                 return TRUE;
2224
2225         BLI_smallhash_insert(visited, (uintptr_t)kfv, NULL);
2226         /* Try all possible next edges. Could either go through fedges
2227          * (all the KnifeEdges for the face being cut) or could go through
2228          * kve->edges and restrict to cutting face and uninstantiated edges.
2229          * Not clear which is better. Let's do the first. */
2230         for (r = fedges->first; r; r = r->next) {
2231                 kfe = r->ref;
2232                 kfv_other = NULL;
2233                 if (kfe->v1 == kfv)
2234                         kfv_other = kfe->v2;
2235                 else if (kfe->v2 == kfv)
2236                         kfv_other = kfe->v1;
2237                 if (kfv_other && !BLI_smallhash_haskey(visited, (uintptr_t)kfv_other)) {
2238                         knife_append_list(kcd, chain, kfe);
2239                         if (find_chain_search(kcd, kfv_other, fedges, visited, chain))
2240                                 return TRUE;
2241                         BLI_remlink(chain, chain->last);
2242                 }
2243         }
2244         return FALSE;
2245 }
2246
2247 static ListBase *find_chain_from_vertex(KnifeTool_OpData *kcd, KnifeEdge *kfe, BMVert *v, ListBase *fedges)
2248 {
2249         SmallHash visited_, *visited = &visited_;
2250         ListBase *ans;
2251         int found;
2252
2253         ans = knife_empty_list(kcd);
2254         knife_append_list(kcd, ans, kfe);
2255         found = 0;
2256         BLI_smallhash_init(visited);
2257         if (kfe->v1->v == v) {
2258                 BLI_smallhash_insert(visited, (uintptr_t)(kfe->v1), NULL);
2259                 found = find_chain_search(kcd, kfe->v2, fedges, visited, ans);
2260         }
2261         else {
2262                 BLI_assert(kfe->v2->v == v);
2263                 BLI_smallhash_insert(visited, (uintptr_t)(kfe->v2), NULL);
2264                 found = find_chain_search(kcd, kfe->v1, fedges, visited, ans);
2265         }
2266
2267         BLI_smallhash_release(visited);
2268
2269         if (found)
2270                 return ans;
2271         else
2272                 return NULL;
2273 }
2274
2275 /* Find a chain in fedges from one instantiated vertex to another.
2276  * Remove the edges in the chain from fedges and return a separate list of the chain. */
2277 static ListBase *find_chain(KnifeTool_OpData *kcd, ListBase *fedges)
2278 {
2279         Ref *r, *ref;
2280         KnifeEdge *kfe;
2281         BMVert *v1, *v2;
2282         ListBase *ans;
2283
2284         ans = NULL;
2285
2286         for (r = fedges->first; r; r = r->next) {
2287                 kfe = r->ref;
2288                 v1 = kfe->v1->v;
2289                 v2 = kfe->v2->v;
2290                 if (v1 && v2) {
2291                         ans = knife_empty_list(kcd);
2292                         knife_append_list(kcd, ans, kfe);
2293                         break;
2294                 }
2295                 if (v1)
2296                         ans = find_chain_from_vertex(kcd, kfe, v1, fedges);
2297                 else if (v2)
2298                         ans = find_chain_from_vertex(kcd, kfe, v2, fedges);
2299                 if (ans)
2300                         break;
2301         }
2302         if (ans) {
2303                 BLI_assert(BLI_countlist(ans) > 0);
2304                 for (r = ans->first; r; r = r->next) {
2305                         ref = find_ref(fedges, r->ref);
2306                         BLI_assert(ref != NULL);
2307                         BLI_remlink(fedges, ref);
2308                 }
2309         }
2310         return ans;
2311 }
2312
2313 /* The hole so far goes from kfvfirst to kfv (some may be reversed).
2314  * If possible, complete the hole back to kfvfirst and return 1, else return 0.
2315  * The visited hash says which KnifeVert's have already been tried, not including kfv or kfvfirst. */
2316 static int find_hole_search(KnifeTool_OpData *kcd, KnifeVert *kfvfirst, KnifeVert *kfv, ListBase *fedges,
2317                             SmallHash *visited, ListBase *hole)
2318 {
2319         Ref *r;
2320         KnifeEdge *kfe, *kfelast;
2321         KnifeVert *kfv_other;
2322
2323         if (kfv == kfvfirst)
2324                 return TRUE;
2325
2326         BLI_smallhash_insert(visited, (uintptr_t)kfv, NULL);
2327         kfelast = ((Ref *)hole->last)->ref;
2328         for (r = fedges->first; r; r = r->next) {
2329                 kfe = r->ref;
2330                 if (kfe == kfelast)
2331                         continue;
2332                 if (kfe->v1->v || kfe->v2->v)
2333                         continue;
2334                 kfv_other = NULL;
2335                 if (kfe->v1 == kfv)
2336                         kfv_other = kfe->v2;
2337                 else if (kfe->v2 == kfv)
2338                         kfv_other = kfe->v1;
2339                 if (kfv_other && !BLI_smallhash_haskey(visited, (uintptr_t)kfv_other)) {
2340                         knife_append_list(kcd, hole, kfe);
2341                         if (find_hole_search(kcd, kfvfirst, kfv_other, fedges, visited, hole))
2342                                 return TRUE;
2343                         BLI_remlink(hole, hole->last);
2344                 }
2345         }
2346         return FALSE;
2347 }
2348
2349 /* Find a hole (simple cycle with no instantiated vertices).
2350  * Remove the edges in the cycle from fedges and return a separate list of the cycle */
2351 static ListBase *find_hole(KnifeTool_OpData *kcd, ListBase *fedges)
2352 {
2353         ListBase *ans;
2354         Ref *r, *ref;
2355         KnifeEdge *kfe;
2356         SmallHash visited_, *visited = &visited_;
2357         int found;
2358
2359         ans = NULL;
2360         found = FALSE;
2361
2362         for (r = fedges->first; r && !found; r = r->next) {
2363                 kfe = r->ref;
2364                 if (kfe->v1->v || kfe->v2->v || kfe->v1 == kfe->v2)
2365                         continue;
2366
2367                 BLI_smallhash_init(visited);
2368                 ans = knife_empty_list(kcd);
2369                 knife_append_list(kcd, ans, kfe);
2370
2371                 found = find_hole_search(kcd, kfe->v1, kfe->v2, fedges, visited, ans);
2372
2373                 BLI_smallhash_release(visited);
2374         }
2375
2376         if (found) {
2377                 for (r = ans->first; r; r = r->next) {
2378                         kfe = r->ref;
2379                         ref = find_ref(fedges, r->ref);
2380                         if (ref)
2381                                 BLI_remlink(fedges, ref);
2382                 }
2383                 return ans;
2384         }
2385         else {
2386                 return NULL;
2387         }
2388 }
2389
2390 /* Try to find "nice" diagonals - short, and far apart from each other.
2391  * If found, return TRUE and make a 'main chain' going across f which uses
2392  * the two diagonals and one part of the hole, and a 'side chain' that
2393  * completes the hole. */
2394 static int find_hole_chains(KnifeTool_OpData *kcd, ListBase *hole, BMFace *f, ListBase **mainchain,
2395                             ListBase **sidechain)
2396 {
2397         float **fco, **hco;
2398         BMVert **fv;
2399         KnifeVert **hv;
2400         KnifeEdge **he;
2401         Ref *r;
2402         KnifeVert *kfv, *kfvother;
2403         KnifeEdge *kfe;
2404         ListBase *chain;
2405         BMVert *v;
2406         BMIter iter;
2407         int nh, nf, i, j, k, m, ax, ay, ok, sep = 0 /* Quite warnings */, bestsep;
2408         int besti[2], bestj[2];
2409         float d, bestd;
2410
2411         nh = BLI_countlist(hole);
2412         nf = f->len;
2413         if (nh < 2 || nf < 3)
2414                 return 0;
2415
2416         /* Gather 2d projections of hole and face vertex coordinates.
2417          * Use best-axis projection - not completely accurate, maybe revisit */
2418         axis_dominant_v3(&ax, &ay, f->no);
2419         hco = BLI_memarena_alloc(kcd->arena, nh * sizeof(float *));
2420         fco = BLI_memarena_alloc(kcd->arena, nf * sizeof(float *));
2421         hv = BLI_memarena_alloc(kcd->arena, nh * sizeof(KnifeVert *));
2422         fv = BLI_memarena_alloc(kcd->arena, nf * sizeof(BMVert *));
2423         he = BLI_memarena_alloc(kcd->arena, nh * sizeof(KnifeEdge *));
2424
2425         i = 0;
2426         kfv = NULL;
2427         kfvother = NULL;
2428         for (r = hole->first; r; r = r->next) {
2429                 kfe = r->ref;
2430                 he[i] = kfe;
2431                 if (kfvother == NULL) {
2432                         kfv = kfe->v1;
2433                 }
2434                 else {
2435                         kfv = kfvother;
2436                         BLI_assert(kfv == kfe->v1 || kfv == kfe->v2);
2437                 }
2438                 hco[i] = BLI_memarena_alloc(kcd->arena, 2 * sizeof(float));
2439                 hco[i][0] = kfv->co[ax];
2440                 hco[i][1] = kfv->co[ay];
2441                 hv[i] = kfv;
2442                 kfvother = (kfe->v1 == kfv) ? kfe->v2 : kfe->v1;
2443                 i++;
2444         }
2445
2446         j = 0;
2447         BM_ITER_ELEM (v, &iter, f, BM_VERTS_OF_FACE) {
2448                 fco[j] = BLI_memarena_alloc(kcd->arena, 2 * sizeof(float));
2449                 fco[j][0] = v->co[ax];
2450                 fco[j][1] = v->co[ay];
2451                 fv[j] = v;
2452                 j++;
2453         }
2454
2455         /* For first diagonal  (m == 0), want shortest length.
2456          * For second diagonal (m == 1), want max separation of index of hole
2457          * vertex from the hole vertex used in the first diagonal, and from there
2458          * want the one with shortest length not to the same vertex as the first diagonal. */
2459         for (m = 0; m < 2; m++) {
2460                 besti[m] = -1;
2461                 bestj[m] = -1;
2462                 bestd = FLT_MAX;
2463                 bestsep = 0;
2464                 for (i = 0; i < nh; i++) {
2465                         if (m == 1) {
2466                                 if (i == besti[0])
2467                                         continue;
2468                                 sep = (i + nh - besti[0]) % nh;
2469                                 sep = MIN2(sep, nh - sep);
2470                                 if (sep < bestsep)
2471                                         continue;
2472                                 bestd = FLT_MAX;
2473                         }
2474                         for (j = 0; j < nf; j++) {
2475                                 if (m == 1 && j == bestj[0])
2476                                         continue;
2477                                 d = len_squared_v2v2(hco[i], fco[j]);
2478                                 if (d > bestd)
2479                                         continue;
2480
2481                                 ok = TRUE;
2482                                 for (k = 0; k < nh && ok; k++) {
2483                                         if (k == i || (k + 1) % nh == i)
2484                                                 continue;
2485                                         if (isect_line_line_v2(hco[i], fco[j], hco[k], hco[(k + 1) % nh]))
2486                                                 ok = FALSE;
2487                                 }
2488                                 if (!ok)
2489                                         continue;
2490                                 for (k = 0; k < nf && ok; k++) {
2491                                         if (k == j || (k + 1) % nf == j)
2492                                                 continue;
2493                                         if (isect_line_line_v2(hco[i], fco[j], fco[k], fco[(k + 1) % nf]))
2494                                                 ok = FALSE;
2495                                 }
2496                                 if (ok) {
2497                                         besti[m] = i;
2498                                         bestj[m] = j;
2499                                         if (m == 1)
2500                                                 bestsep = sep;
2501                                         bestd = d;
2502                                 }
2503                         }
2504                 }
2505         }
2506
2507         if (besti[0] != -1 && besti[1] != -1) {
2508                 BLI_assert(besti[0] != besti[1] && bestj[0] != bestj[1]);
2509                 kfe = new_knife_edge(kcd);
2510                 kfe->v1 = get_bm_knife_vert(kcd, fv[bestj[0]]);
2511                 kfe->v2 = hv[besti[0]];
2512                 chain = knife_empty_list(kcd);
2513                 knife_append_list(kcd, chain, kfe);
2514                 for (i = besti[0]; i != besti[1]; i = (i + 1) % nh) {
2515                         knife_append_list(kcd, chain, he[i]);
2516                 }
2517                 kfe = new_knife_edge(kcd);
2518                 kfe->v1 = hv[besti[1]];
2519                 kfe->v2 = get_bm_knife_vert(kcd, fv[bestj[1]]);
2520                 knife_append_list(kcd, chain, kfe);
2521                 *mainchain = chain;
2522
2523                 chain = knife_empty_list(kcd);
2524                 for (i = besti[1]; i != besti[0]; i = (i + 1) % nh) {
2525                         knife_append_list(kcd, chain, he[i]);
2526                 }
2527                 *sidechain = chain;
2528
2529                 return TRUE;
2530         }
2531         else {
2532                 return FALSE;
2533         }
2534 }
2535
2536 static int knife_edge_in_face(KnifeTool_OpData *UNUSED(kcd), KnifeEdge *kfe, BMFace *f)
2537 {
2538         /* BMesh *bm = kcd->em->bm; */ /* UNUSED */
2539         BMVert *v1, *v2;
2540         BMLoop *l1, *l2, *l;
2541         float mid[3];
2542         BMIter iter;
2543         int v1inside, v2inside;
2544
2545         if (!f)
2546                 return FALSE;
2547
2548         v1 = kfe->v1->v;
2549         v2 = kfe->v2->v;
2550         l1 = NULL;
2551         l2 = NULL;
2552
2553         /* find out if v1 and v2, if set, are part of the face */
2554         BM_ITER_ELEM (l, &iter, f, BM_LOOPS_OF_FACE) {
2555                 if (v1 && l->v == v1)
2556                         l1 = l;
2557                 if (v2 && l->v == v2)
2558                         l2 = l;
2559         }
2560
2561         /* BM_face_point_inside_test uses best-axis projection so this isn't most accurate test... */
2562         v1inside = l1 ? 0 : BM_face_point_inside_test(f, kfe->v1->co);
2563         v2inside = l2 ? 0 : BM_face_point_inside_test(f, kfe->v2->co);
2564         if ((l1 && v2inside) || (l2 && v1inside) || (v1inside && v2inside))
2565                 return TRUE;
2566         if (l1 && l2) {
2567                 /* Can have case where v1 and v2 are on shared chain between two faces.
2568                  * BM_face_legal_splits does visibility and self-intersection tests,
2569                  * but it is expensive and maybe a bit buggy, so use a simple
2570                  * "is the midpoint in the face" test */
2571                 mid_v3_v3v3(mid, kfe->v1->co, kfe->v2->co);
2572                 return BM_face_point_inside_test(f, mid);
2573         }
2574         return FALSE;
2575 }
2576
2577 /* Split face f with KnifeEdges on chain.  f remains as one side, the face formed is put in *newface.
2578  * The new face will be on the left side of the chain as viewed from the normal-out side of f. */
2579 static void knife_make_chain_cut(KnifeTool_OpData *kcd, BMFace *f, ListBase *chain, BMFace **newface)
2580 {
2581         BMesh *bm = kcd->em->bm;
2582         KnifeEdge *kfe, *kfelast;
2583         BMVert *v1, *v2;
2584         BMFace *fnew;
2585         Ref *ref;
2586         KnifeVert *kfv, *kfvprev;
2587         BMLoop *lnew, *l_iter;
2588         int i;
2589         int nco = BLI_countlist(chain) - 1;
2590         float (*cos)[3] = BLI_array_alloca(cos, nco);
2591         KnifeVert **kverts = BLI_array_alloca(kverts, nco);
2592
2593         kfe = ((Ref *)chain->first)->ref;
2594         v1 = kfe->v1->v ? kfe->v1->v : kfe->v2->v;
2595         kfelast = ((Ref *)chain->last)->ref;
2596         v2 = kfelast->v2->v ? kfelast->v2->v : kfelast->v1->v;
2597         BLI_assert(v1 != NULL && v2 != NULL);
2598         kfvprev = kfe->v1->v == v1 ? kfe->v1 : kfe->v2;
2599         for (ref = chain->first, i = 0; i < nco && ref != chain->last; ref = ref->next, i++) {
2600                 kfe = ref->ref;
2601                 BLI_assert(kfvprev == kfe->v1 || kfvprev == kfe->v2);
2602                 kfv = kfe->v1 == kfvprev ? kfe->v2 : kfe->v1;
2603                 copy_v3_v3(cos[i], kfv->co);
2604                 kverts[i] = kfv;
2605                 kfvprev = kfv;
2606         }
2607         BLI_assert(i == nco);
2608         lnew = NULL;
2609         if (nco == 0) {
2610                 /* Want to prevent creating two-sided polygons */
2611                 if (BM_edge_exists(v1, v2)) {
2612                         *newface = NULL;
2613                 }
2614                 else {
2615                         *newface = BM_face_split(bm, f, v1, v2, &lnew, NULL, TRUE);
2616                 }
2617         }
2618         else {
2619                 fnew = BM_face_split_n(bm, f, v1, v2, cos, nco, &lnew, NULL);
2620                 *newface = fnew;
2621
2622                 if (fnew) {
2623                         /* Now go through lnew chain matching up chain kv's and assign real v's to them */
2624                         for (l_iter = lnew->next, i = 0; i < nco; l_iter = l_iter->next, i++) {
2625                                 BLI_assert(equals_v3v3(cos[i], l_iter->v->co));
2626                                 if (kcd->select_result) {
2627                                         BM_edge_select_set(bm, l_iter->e, TRUE);
2628                                 }
2629                                 kverts[i]->v = l_iter->v;
2630                         }
2631                 }
2632         }
2633
2634         /* the select chain above doesnt account for the first loop */
2635         if (kcd->select_result) {
2636                 if (lnew) {
2637                         BM_edge_select_set(bm, lnew->e, TRUE);
2638                 }
2639         }
2640 }
2641
2642 static void knife_make_face_cuts(KnifeTool_OpData *kcd, BMFace *f, ListBase *kfedges)
2643 {
2644         BMesh *bm = kcd->em->bm;
2645         KnifeEdge *kfe;
2646         BMFace *fnew, *fnew2, *fhole;
2647         ListBase *chain, *hole, *sidechain;
2648         ListBase *fnew_kfedges, *fnew2_kfedges;
2649         Ref *ref, *refnext;
2650         int count, oldcount;
2651
2652         oldcount = BLI_countlist(kfedges);
2653         while ((chain = find_chain(kcd, kfedges)) != NULL) {
2654                 knife_make_chain_cut(kcd, f, chain, &fnew);
2655                 if (!fnew) {
2656                         return;
2657                 }
2658
2659                 /* Move kfedges to fnew_kfedges if they are now in fnew.
2660                  * The chain edges were removed already */
2661                 fnew_kfedges = knife_empty_list(kcd);
2662                 for (ref = kfedges->first; ref; ref = refnext) {
2663                         kfe = ref->ref;
2664                         refnext = ref->next;
2665                         if (knife_edge_in_face(kcd, kfe, fnew)) {
2666                                 BLI_remlink(kfedges, ref);
2667                                 kfe->basef = fnew;
2668                                 knife_append_list(kcd, fnew_kfedges, kfe);
2669                         }
2670                 }
2671                 if (fnew_kfedges->first)
2672                         knife_make_face_cuts(kcd, fnew, fnew_kfedges);
2673
2674                 /* find_chain should always remove edges if it returns TRUE,
2675                  * but guard against infinite loop anyway */
2676                 count = BLI_countlist(kfedges);
2677                 if (count >= oldcount) {
2678                         BLI_assert(!"knife find_chain infinite loop");
2679                         return;
2680                 }
2681                 oldcount = count;
2682         }
2683
2684         while ((hole = find_hole(kcd, kfedges)) != NULL) {
2685                 if (find_hole_chains(kcd, hole, f, &chain, &sidechain)) {
2686                         /* chain goes across f and sidechain comes back
2687                          * from the second last vertex to the second vertex.
2688                          */
2689                         knife_make_chain_cut(kcd, f, chain, &fnew);
2690                         if (!fnew) {
2691                                 BLI_assert(!"knife failed hole cut");
2692                                 return;
2693                         }
2694                         kfe = ((Ref *)sidechain->first)->ref;
2695                         if (knife_edge_in_face(kcd, kfe, f)) {
2696                                 knife_make_chain_cut(kcd, f, sidechain, &fnew2);
2697                                 fhole = f;
2698                         }
2699                         else if (knife_edge_in_face(kcd, kfe, fnew)) {
2700                                 knife_make_chain_cut(kcd, fnew, sidechain, &fnew2);
2701                                 fhole = fnew2;
2702                         }
2703                         else {
2704                                 /* shouldn't happen except in funny edge cases */
2705                                 return;
2706                         }
2707                         BM_face_kill(bm, fhole);
2708                         /* Move kfedges to either fnew or fnew2 if appropriate.
2709                          * The hole edges were removed already */
2710                         fnew_kfedges = knife_empty_list(kcd);
2711                         fnew2_kfedges = knife_empty_list(kcd);
2712                         for (ref = kfedges->first; ref; ref = refnext) {
2713                                 kfe = ref->ref;
2714                                 refnext = ref->next;
2715                                 if (knife_edge_in_face(kcd, kfe, fnew)) {
2716                                         BLI_remlink(kfedges, ref);
2717                                         kfe->basef = fnew;
2718                                         knife_append_list(kcd, fnew_kfedges, kfe);
2719                                 }
2720                                 else if (knife_edge_in_face(kcd, kfe, fnew2)) {
2721                                         BLI_remlink(kfedges, ref);
2722                                         kfe->basef = fnew2;
2723                                         knife_append_list(kcd, fnew2_kfedges, kfe);
2724                                 }
2725                         }
2726                         /* We'll skip knife edges that are in the newly formed hole.
2727                          * (Maybe we shouldn't have made a hole in the first place?) */
2728                         if (fnew != fhole && fnew_kfedges->first)
2729                                 knife_make_face_cuts(kcd, fnew, fnew_kfedges);
2730                         if (fnew2 != fhole && fnew2_kfedges->first)
2731                                 knife_make_face_cuts(kcd, fnew2, fnew2_kfedges);
2732                         if (f == fhole)
2733                                 break;
2734                         /* find_hole should always remove edges if it returns TRUE,
2735                          * but guard against infinite loop anyway */
2736                         count = BLI_countlist(kfedges);
2737                         if (count >= oldcount) {
2738                                 BLI_assert(!"knife find_hole infinite loop");
2739                                 return;
2740                         }
2741                         oldcount = count;
2742                 }
2743         }
2744 }
2745
2746 /* Use the network of KnifeEdges and KnifeVerts accumulated to make real BMVerts and BMEdedges */
2747 static void knife_make_cuts(KnifeTool_OpData *kcd)
2748 {
2749         BMesh *bm = kcd->em->bm;
2750         KnifeEdge *kfe;
2751         KnifeVert *kfv;
2752         BMFace *f;
2753         BMEdge *e, *enew;
2754         ListBase *lst;
2755         Ref *ref;
2756         float pct;
2757         SmallHashIter hiter;
2758         BLI_mempool_iter iter;
2759         SmallHash fhash_, *fhash = &fhash_;
2760         SmallHash ehash_, *ehash = &ehash_;
2761
2762         BLI_smallhash_init(fhash);
2763         BLI_smallhash_init(ehash);
2764
2765         /* put list of cutting edges for a face into fhash, keyed by face */
2766         BLI_mempool_iternew(kcd->kedges, &iter);
2767         for (kfe = BLI_mempool_iterstep(&iter); kfe; kfe = BLI_mempool_iterstep(&iter)) {
2768                 f = kfe->basef;
2769                 if (!f || kfe->e)
2770                         continue;
2771                 lst = BLI_smallhash_lookup(fhash, (uintptr_t)f);
2772                 if (!lst) {
2773                         lst = knife_empty_list(kcd);
2774                         BLI_smallhash_insert(fhash, (uintptr_t)f, lst);
2775                 }
2776                 knife_append_list(kcd, lst, kfe);
2777         }
2778
2779         /* put list of splitting vertices for an edge into ehash, keyed by edge */
2780         BLI_mempool_iternew(kcd->kverts, &iter);
2781         for (kfv = BLI_mempool_iterstep(&iter); kfv; kfv = BLI_mempool_iterstep(&iter)) {
2782                 if (kfv->v)
2783                         continue;  /* already have a BMVert */
2784                 for (ref = kfv->edges.first; ref; ref = ref->next) {
2785                         kfe = ref->ref;
2786                         e = kfe->e;
2787                         if (!e)
2788                                 continue;
2789                         lst = BLI_smallhash_lookup(ehash, (uintptr_t)e);
2790                         if (!lst) {
2791                                 lst = knife_empty_list(kcd);
2792                                 BLI_smallhash_insert(ehash, (uintptr_t)e, lst);
2793                         }
2794                         /* there can be more than one kfe in kfv's list with same e */
2795                         if (!find_ref(lst, kfv))
2796                                 knife_append_list(kcd, lst, kfv);
2797                 }
2798         }
2799
2800         /* split bmesh edges where needed */
2801         for (lst = BLI_smallhash_iternew(ehash, &hiter, (uintptr_t *)&e); lst;
2802              lst = BLI_smallhash_iternext(&hiter, (uintptr_t *)&e))
2803         {
2804                 sort_by_frac_along(lst, e);
2805                 for (ref = lst->first; ref; ref = ref->next) {
2806                         kfv = ref->ref;
2807                         pct = frac_along(e->v1->co, e->v2->co, kfv->co);
2808                         kfv->v = BM_edge_split(bm, e, e->v1, &enew, pct);
2809                 }
2810         }
2811
2812         if (kcd->only_select) {
2813                 EDBM_flag_disable_all(kcd->em, BM_ELEM_SELECT);
2814         }
2815
2816         /* do cuts for each face */
2817         for (lst = BLI_smallhash_iternew(fhash, &hiter, (uintptr_t *)&f); lst;
2818              lst = BLI_smallhash_iternext(&hiter, (uintptr_t *)&f))
2819         {
2820                 knife_make_face_cuts(kcd, f, lst);
2821         }
2822
2823         BLI_smallhash_release(fhash);
2824         BLI_smallhash_release(ehash);
2825 }
2826 #endif
2827
2828 /* called on tool confirmation */
2829 static void knifetool_finish(wmOperator *op)
2830 {
2831         KnifeTool_OpData *kcd = op->customdata;
2832
2833 #if SCANFILL_CUTS
2834         knifenet_fill_faces(kcd);
2835 #else
2836         knife_make_cuts(kcd);
2837 #endif
2838
2839         EDBM_mesh_normals_update(kcd->em);
2840         EDBM_update_generic(kcd->em, TRUE, TRUE);
2841 }
2842
2843 /* copied from paint_image.c */
2844 static int project_knife_view_clip(View3D *v3d, RegionView3D *rv3d, float *clipsta, float *clipend)
2845 {
2846         int orth = ED_view3d_clip_range_get(v3d, rv3d, clipsta, clipend);
2847
2848         if (orth) { /* only needed for ortho */
2849                 float fac = 2.0f / ((*clipend) - (*clipsta));
2850                 *clipsta *= fac;
2851                 *clipend *= fac;
2852         }
2853
2854         return orth;
2855 }
2856
2857 static void knife_recalc_projmat(KnifeTool_OpData *kcd)
2858 {
2859         invert_m4_m4(kcd->ob->imat, kcd->ob->obmat);
2860         ED_view3d_ob_project_mat_get(kcd->ar->regiondata, kcd->ob, kcd->projmat);
2861         //mult_m4_m4m4(kcd->projmat, kcd->vc.rv3d->winmat, kcd->vc.rv3d->viewmat);
2862
2863         kcd->is_ortho = project_knife_view_clip(kcd->vc.v3d, kcd->vc.rv3d, 
2864                                                 &kcd->clipsta, &kcd->clipend);
2865 }
2866
2867 /* called when modal loop selection is done... */
2868 static void knifetool_exit(bContext *C, wmOperator *op)
2869 {
2870         KnifeTool_OpData *kcd = op->customdata;
2871
2872         if (!kcd)
2873                 return;
2874
2875         WM_cursor_restore(CTX_wm_window(C));
2876
2877         /* deactivate the extra drawing stuff in 3D-View */
2878         ED_region_draw_cb_exit(kcd->ar->type, kcd->draw_handle);
2879
2880         /* free the custom data */
2881         BLI_mempool_destroy(kcd->refs);
2882         BLI_mempool_destroy(kcd->kverts);
2883         BLI_mempool_destroy(kcd->kedges);
2884
2885         BLI_ghash_free(kcd->origedgemap, NULL, NULL);
2886         BLI_ghash_free(kcd->origvertmap, NULL, NULL);
2887         BLI_ghash_free(kcd->kedgefacemap, NULL, NULL);
2888
2889         BMBVH_FreeBVH(kcd->bmbvh);
2890         BLI_memarena_free(kcd->arena);
2891
2892         /* tag for redraw */
2893         ED_region_tag_redraw(kcd->ar);
2894
2895         if (kcd->cagecos)
2896                 MEM_freeN(kcd->cagecos);
2897
2898         if (kcd->linehits)
2899                 MEM_freeN(kcd->linehits);
2900
2901         /* destroy kcd itself */
2902         MEM_freeN(kcd);
2903         op->customdata = NULL;
2904 }
2905
2906 static void cage_mapped_verts_callback(void *userData, int index, const float co[3],
2907                                        const float UNUSED(no_f[3]), const short UNUSED(no_s[3]))
2908 {
2909         void **data = userData;
2910         BMEditMesh *em = data[0];
2911         float (*cagecos)[3] = data[1];
2912         SmallHash *hash = data[2];
2913
2914         if (index >= 0 && index < em->bm->totvert && !BLI_smallhash_haskey(hash, index)) {
2915                 BLI_smallhash_insert(hash, index, NULL);
2916                 copy_v3_v3(cagecos[index], co);
2917         }
2918 }
2919
2920 static void knifetool_update_mval(KnifeTool_OpData *kcd, int mval[2])
2921 {
2922         knife_recalc_projmat(kcd);
2923         kcd->vc.mval[0] = mval[0];
2924         kcd->vc.mval[1] = mval[1];
2925
2926         if (knife_update_active(kcd)) {
2927                 ED_region_tag_redraw(kcd->ar);
2928         }
2929 }
2930
2931 /* called when modal loop selection gets set up... */
2932 static int knifetool_init(bContext *C, wmOperator *op, int UNUSED(do_cut))
2933 {
2934         KnifeTool_OpData *kcd;
2935         Scene *scene = CTX_data_scene(C);
2936         Object *obedit = CTX_data_edit_object(C);
2937         DerivedMesh *cage, *final;
2938         SmallHash shash;
2939         void *data[3];
2940         const short only_select = RNA_boolean_get(op->ptr, "only_selected");
2941
2942         /* alloc new customdata */
2943         kcd = op->customdata = MEM_callocN(sizeof(KnifeTool_OpData), "knifetool Modal Op Data");
2944
2945         /* assign the drawing handle for drawing preview line... */
2946         kcd->ob = obedit;
2947         kcd->ar = CTX_wm_region(C);
2948         kcd->draw_handle = ED_region_draw_cb_activate(kcd->ar->type, knifetool_draw, kcd, REGION_DRAW_POST_VIEW);
2949         em_setup_viewcontext(C, &kcd->vc);
2950
2951         kcd->em = BMEdit_FromObject(kcd->ob);
2952
2953         BM_mesh_elem_index_ensure(kcd->em->bm, BM_VERT);
2954
2955         cage = editbmesh_get_derived_cage_and_final(scene, obedit, kcd->em, &final, CD_MASK_DERIVEDMESH);
2956         kcd->cagecos = MEM_callocN(sizeof(float) * 3 * kcd->em->bm->totvert, "knife cagecos");
2957         data[0] = kcd->em;
2958         data[1] = kcd->cagecos;
2959         data[2] = &shash;
2960
2961         BLI_smallhash_init(&shash);
2962         cage->foreachMappedVert(cage, cage_mapped_verts_callback, data);
2963         BLI_smallhash_release(&shash);
2964
2965         kcd->bmbvh = BMBVH_NewBVH(kcd->em,
2966                                   (BMBVH_USE_CAGE | BMBVH_RETURN_ORIG) |
2967                                   (only_select ? BMBVH_RESPECT_SELECT : BMBVH_RESPECT_HIDDEN),
2968                                   scene, obedit);
2969
2970         kcd->arena = BLI_memarena_new(1 << 15, "knife");
2971         kcd->vthresh = KMAXDIST - 1;
2972         kcd->ethresh = KMAXDIST;
2973
2974         kcd->extend = 1;
2975
2976         knife_recalc_projmat(kcd);
2977
2978         ED_region_tag_redraw(kcd->ar);
2979
2980         kcd->refs = BLI_mempool_create(sizeof(Ref), 1, 2048, 0);
2981         kcd->kverts = BLI_mempool_create(sizeof(KnifeVert), 1, 512, BLI_MEMPOOL_ALLOW_ITER);
2982         kcd->kedges = BLI_mempool_create(sizeof(KnifeEdge), 1, 512, BLI_MEMPOOL_ALLOW_ITER);
2983
2984         kcd->origedgemap = BLI_ghash_ptr_new("knife origedgemap");
2985         kcd->origvertmap = BLI_ghash_ptr_new("knife origvertmap");
2986         kcd->kedgefacemap = BLI_ghash_ptr_new("knife origvertmap");
2987
2988         /* cut all the way through the mesh if use_occlude_geometry button not pushed */
2989         kcd->cut_through = !RNA_boolean_get(op->ptr, "use_occlude_geometry");
2990         kcd->only_select = only_select;
2991
2992         /* can't usefully select resulting edges in face mode */
2993         kcd->select_result = (kcd->em->selectmode != SCE_SELECT_FACE);
2994
2995         knife_pos_data_clear(&kcd->curr);
2996         knife_pos_data_clear(&kcd->prev);
2997
2998         knife_init_colors(&kcd->colors);
2999
3000         return 1;
3001 }
3002
3003 static int knifetool_cancel(bContext *C, wmOperator *op)
3004 {
3005         /* this is just a wrapper around exit() */
3006         knifetool_exit(C, op);
3007         return OPERATOR_CANCELLED;
3008 }
3009
3010 static int knifetool_invoke(bContext *C, wmOperator *op, wmEvent *evt)
3011 {
3012         KnifeTool_OpData *kcd;
3013
3014         view3d_operator_needs_opengl(C);
3015
3016         if (!knifetool_init(C, op, 0))
3017                 return OPERATOR_CANCELLED;
3018
3019         /* add a modal handler for this operator - handles loop selection */
3020         WM_cursor_modal(CTX_wm_window(C), BC_KNIFECURSOR);
3021         WM_event_add_modal_handler(C, op);
3022
3023         kcd = op->customdata;
3024         knifetool_update_mval(kcd, evt->mval);
3025
3026         knife_update_header(C, kcd);
3027
3028         return OPERATOR_RUNNING_MODAL;
3029 }
3030
3031 enum {
3032         KNF_MODAL_CANCEL = 1,
3033         KNF_MODAL_CONFIRM,
3034         KNF_MODAL_MIDPOINT_ON,
3035         KNF_MODAL_MIDPOINT_OFF,
3036         KNF_MODAL_NEW_CUT,
3037         KNF_MODEL_IGNORE_SNAP_ON,
3038         KNF_MODEL_IGNORE_SNAP_OFF,
3039         KNF_MODAL_ADD_CUT,
3040         KNF_MODAL_ANGLE_SNAP_TOGGLE,
3041         KNF_MODAL_CUT_THROUGH_TOGGLE
3042 };
3043
3044 wmKeyMap *knifetool_modal_keymap(wmKeyConfig *keyconf)
3045 {
3046         static EnumPropertyItem modal_items[] = {
3047                 {KNF_MODAL_CANCEL, "CANCEL", 0, "Cancel", ""},
3048                 {KNF_MODAL_CONFIRM, "CONFIRM", 0, "Confirm", ""},
3049                 {KNF_MODAL_MIDPOINT_ON, "SNAP_MIDPOINTS_ON", 0, "Snap To Midpoints On", ""},
3050                 {KNF_MODAL_MIDPOINT_OFF, "SNAP_MIDPOINTS_OFF", 0, "Snap To Midpoints Off", ""},
3051                 {KNF_MODEL_IGNORE_SNAP_ON, "IGNORE_SNAP_ON", 0, "Ignore Snapping On", ""},
3052                 {KNF_MODEL_IGNORE_SNAP_OFF, "IGNORE_SNAP_OFF", 0, "Ignore Snapping Off", ""},
3053                 {KNF_MODAL_ANGLE_SNAP_TOGGLE, "ANGLE_SNAP_TOGGLE", 0, "Toggle Angle Snapping", ""},
3054                 {KNF_MODAL_CUT_THROUGH_TOGGLE, "CUT_THROUGH_TOGGLE", 0, "Toggle Cut Through", ""},
3055                 {KNF_MOD