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