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