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