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