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