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