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