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