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