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