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