Move editmesh undo into its own file
[blender.git] / source / blender / editors / mesh / editmesh_utils.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) 2004 by Blender Foundation.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): Joseph Eagar
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/editors/mesh/editmesh_utils.c
29  *  \ingroup edmesh
30  */
31
32 #include "MEM_guardedalloc.h"
33
34 #include "DNA_mesh_types.h"
35 #include "DNA_object_types.h"
36 #include "DNA_key_types.h"
37
38 #include "BLI_math.h"
39 #include "BLI_alloca.h"
40 #include "BLI_buffer.h"
41 #include "BLI_kdtree.h"
42 #include "BLI_listbase.h"
43
44 #include "BKE_DerivedMesh.h"
45 #include "BKE_context.h"
46 #include "BKE_global.h"
47 #include "BKE_depsgraph.h"
48 #include "BKE_main.h"
49 #include "BKE_mesh.h"
50 #include "BKE_mesh_mapping.h"
51 #include "BKE_report.h"
52 #include "BKE_editmesh.h"
53 #include "BKE_editmesh_bvh.h"
54
55 #include "BKE_object.h"  /* XXX. only for EDBM_mesh_ensure_valid_dm_hack() which will be removed */
56
57 #include "WM_api.h"
58 #include "WM_types.h"
59
60 #include "ED_mesh.h"
61 #include "ED_screen.h"
62 #include "ED_view3d.h"
63
64 #include "mesh_intern.h"  /* own include */
65
66 /* mesh backup implementation. This would greatly benefit from some sort of binary diffing
67  * just as the undo stack would. So leaving this as an interface for further work */
68
69 BMBackup EDBM_redo_state_store(BMEditMesh *em)
70 {
71         BMBackup backup;
72         backup.bmcopy = BM_mesh_copy(em->bm);
73         return backup;
74 }
75
76 void EDBM_redo_state_restore(BMBackup backup, BMEditMesh *em, int recalctess)
77 {
78         BMesh *tmpbm;
79         if (!em || !backup.bmcopy)
80                 return;
81
82         BM_mesh_data_free(em->bm);
83         tmpbm = BM_mesh_copy(backup.bmcopy);
84         *em->bm = *tmpbm;
85         MEM_freeN(tmpbm);
86         tmpbm = NULL;
87
88         if (recalctess)
89                 BKE_editmesh_tessface_calc(em);
90 }
91
92 void EDBM_redo_state_free(BMBackup *backup, BMEditMesh *em, int recalctess)
93 {
94         if (em && backup->bmcopy) {
95                 BM_mesh_data_free(em->bm);
96                 *em->bm = *backup->bmcopy;
97         }
98         else if (backup->bmcopy) {
99                 BM_mesh_data_free(backup->bmcopy);
100         }
101
102         if (backup->bmcopy)
103                 MEM_freeN(backup->bmcopy);
104         backup->bmcopy = NULL;
105
106         if (recalctess && em)
107                 BKE_editmesh_tessface_calc(em);
108 }
109
110 /* hack to workaround multiple operators being called within the same event loop without an update
111  * see: [#31811] */
112 void EDBM_mesh_ensure_valid_dm_hack(Scene *scene, BMEditMesh *em)
113 {
114         if ((((ID *)em->ob->data)->tag & LIB_TAG_ID_RECALC) ||
115             (em->ob->recalc & OB_RECALC_DATA))
116         {
117                 /* since we may not have done selection flushing */
118                 if ((em->ob->recalc & OB_RECALC_DATA) == 0) {
119                         DAG_id_tag_update(&em->ob->id, OB_RECALC_DATA);
120                 }
121                 BKE_object_handle_update(G.main->eval_ctx, scene, em->ob);
122         }
123 }
124
125 void EDBM_mesh_normals_update(BMEditMesh *em)
126 {
127         BM_mesh_normals_update(em->bm);
128 }
129
130 void EDBM_mesh_clear(BMEditMesh *em)
131 {
132         /* clear bmesh */
133         BM_mesh_clear(em->bm);
134         
135         /* free derived meshes */
136         BKE_editmesh_free_derivedmesh(em);
137         
138         /* free tessellation data */
139         em->tottri = 0;
140         if (em->looptris) {
141                 MEM_freeN(em->looptris);
142                 em->looptris = NULL;
143         }
144 }
145
146 void EDBM_stats_update(BMEditMesh *em)
147 {
148         const char iter_types[3] = {BM_VERTS_OF_MESH,
149                                     BM_EDGES_OF_MESH,
150                                     BM_FACES_OF_MESH};
151
152         BMIter iter;
153         BMElem *ele;
154         int *tots[3];
155         int i;
156
157         tots[0] = &em->bm->totvertsel;
158         tots[1] = &em->bm->totedgesel;
159         tots[2] = &em->bm->totfacesel;
160         
161         em->bm->totvertsel = em->bm->totedgesel = em->bm->totfacesel = 0;
162
163         for (i = 0; i < 3; i++) {
164                 ele = BM_iter_new(&iter, em->bm, iter_types[i], NULL);
165                 for ( ; ele; ele = BM_iter_step(&iter)) {
166                         if (BM_elem_flag_test(ele, BM_ELEM_SELECT)) {
167                                 (*tots[i])++;
168                         }
169                 }
170         }
171 }
172
173 DerivedMesh *EDBM_mesh_deform_dm_get(BMEditMesh *em)
174 {
175         return ((em->derivedFinal != NULL) &&
176                 (em->derivedFinal->type == DM_TYPE_EDITBMESH) &&
177                 (em->derivedFinal->deformedOnly != false)) ? em->derivedFinal : NULL;
178 }
179
180 bool EDBM_op_init(BMEditMesh *em, BMOperator *bmop, wmOperator *op, const char *fmt, ...)
181 {
182         BMesh *bm = em->bm;
183         va_list list;
184
185         va_start(list, fmt);
186
187         if (!BMO_op_vinitf(bm, bmop, BMO_FLAG_DEFAULTS, fmt, list)) {
188                 BKE_reportf(op->reports, RPT_ERROR, "Parse error in %s", __func__);
189                 va_end(list);
190                 return false;
191         }
192         
193         if (!em->emcopy)
194                 em->emcopy = BKE_editmesh_copy(em);
195         em->emcopyusers++;
196
197         va_end(list);
198
199         return true;
200 }
201
202
203 /* returns 0 on error, 1 on success.  executes and finishes a bmesh operator */
204 bool EDBM_op_finish(BMEditMesh *em, BMOperator *bmop, wmOperator *op, const bool do_report)
205 {
206         const char *errmsg;
207         
208         BMO_op_finish(em->bm, bmop);
209
210         if (BMO_error_get(em->bm, &errmsg, NULL)) {
211                 BMEditMesh *emcopy = em->emcopy;
212
213                 if (do_report) {
214                         BKE_report(op->reports, RPT_ERROR, errmsg);
215                 }
216
217                 EDBM_mesh_free(em);
218                 *em = *emcopy;
219
220                 MEM_freeN(emcopy);
221                 em->emcopyusers = 0;
222                 em->emcopy = NULL;
223
224                 /* when copying, tessellation isn't to for faster copying,
225                  * but means we need to re-tessellate here */
226                 if (em->looptris == NULL) {
227                         BKE_editmesh_tessface_calc(em);
228                 }
229
230                 return false;
231         }
232         else {
233                 em->emcopyusers--;
234                 if (em->emcopyusers < 0) {
235                         printf("warning: em->emcopyusers was less than zero.\n");
236                 }
237
238                 if (em->emcopyusers <= 0) {
239                         BKE_editmesh_free(em->emcopy);
240                         MEM_freeN(em->emcopy);
241                         em->emcopy = NULL;
242                 }
243
244                 return true;
245         }
246 }
247
248 bool EDBM_op_callf(BMEditMesh *em, wmOperator *op, const char *fmt, ...)
249 {
250         BMesh *bm = em->bm;
251         BMOperator bmop;
252         va_list list;
253
254         va_start(list, fmt);
255
256         if (!BMO_op_vinitf(bm, &bmop, BMO_FLAG_DEFAULTS, fmt, list)) {
257                 BKE_reportf(op->reports, RPT_ERROR, "Parse error in %s", __func__);
258                 va_end(list);
259                 return false;
260         }
261
262         if (!em->emcopy)
263                 em->emcopy = BKE_editmesh_copy(em);
264         em->emcopyusers++;
265
266         BMO_op_exec(bm, &bmop);
267
268         va_end(list);
269         return EDBM_op_finish(em, &bmop, op, true);
270 }
271
272 bool EDBM_op_call_and_selectf(BMEditMesh *em, wmOperator *op,
273                               const char *select_slot_out, const bool select_extend,
274                               const char *fmt, ...)
275 {
276         BMOpSlot *slot_select_out;
277         BMesh *bm = em->bm;
278         BMOperator bmop;
279         va_list list;
280         char hflag;
281
282         va_start(list, fmt);
283
284         if (!BMO_op_vinitf(bm, &bmop, BMO_FLAG_DEFAULTS, fmt, list)) {
285                 BKE_reportf(op->reports, RPT_ERROR, "Parse error in %s", __func__);
286                 va_end(list);
287                 return false;
288         }
289
290         if (!em->emcopy)
291                 em->emcopy = BKE_editmesh_copy(em);
292         em->emcopyusers++;
293
294         BMO_op_exec(bm, &bmop);
295
296         slot_select_out = BMO_slot_get(bmop.slots_out, select_slot_out);
297         hflag = slot_select_out->slot_subtype.elem & BM_ALL_NOLOOP;
298         BLI_assert(hflag != 0);
299
300         if (select_extend == false) {
301                 BM_mesh_elem_hflag_disable_all(em->bm, BM_VERT | BM_EDGE | BM_FACE, BM_ELEM_SELECT, false);
302         }
303
304         BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, select_slot_out, hflag, BM_ELEM_SELECT, true);
305
306         va_end(list);
307         return EDBM_op_finish(em, &bmop, op, true);
308 }
309
310 bool EDBM_op_call_silentf(BMEditMesh *em, const char *fmt, ...)
311 {
312         BMesh *bm = em->bm;
313         BMOperator bmop;
314         va_list list;
315
316         va_start(list, fmt);
317
318         if (!BMO_op_vinitf(bm, &bmop, BMO_FLAG_DEFAULTS, fmt, list)) {
319                 va_end(list);
320                 return false;
321         }
322
323         if (!em->emcopy)
324                 em->emcopy = BKE_editmesh_copy(em);
325         em->emcopyusers++;
326
327         BMO_op_exec(bm, &bmop);
328
329         va_end(list);
330         return EDBM_op_finish(em, &bmop, NULL, false);
331 }
332
333 void EDBM_selectmode_to_scene(bContext *C)
334 {
335         Scene *scene = CTX_data_scene(C);
336         Object *obedit = CTX_data_edit_object(C);
337         BMEditMesh *em = BKE_editmesh_from_object(obedit);
338
339         if (!em)
340                 return;
341
342         scene->toolsettings->selectmode = em->selectmode;
343
344         /* Request redraw of header buttons (to show new select mode) */
345         WM_event_add_notifier(C, NC_SCENE | ND_TOOLSETTINGS, scene);
346 }
347
348 void EDBM_mesh_make(ToolSettings *ts, Object *ob, const bool add_key_index)
349 {
350         Mesh *me = ob->data;
351         BMesh *bm;
352
353         if (UNLIKELY(!me->mpoly && me->totface)) {
354                 BKE_mesh_convert_mfaces_to_mpolys(me);
355         }
356
357         bm = BKE_mesh_to_bmesh(me, ob, add_key_index);
358
359         if (me->edit_btmesh) {
360                 /* this happens when switching shape keys */
361                 EDBM_mesh_free(me->edit_btmesh);
362                 MEM_freeN(me->edit_btmesh);
363         }
364
365         /* currently executing operators re-tessellates, so we can avoid doing here
366          * but at some point it may need to be added back. */
367 #if 0
368         me->edit_btmesh = BKE_editmesh_create(bm, true);
369 #else
370         me->edit_btmesh = BKE_editmesh_create(bm, false);
371 #endif
372
373         me->edit_btmesh->selectmode = me->edit_btmesh->bm->selectmode = ts->selectmode;
374         me->edit_btmesh->mat_nr = (ob->actcol > 0) ? ob->actcol - 1 : 0;
375         me->edit_btmesh->ob = ob;
376
377         /* we need to flush selection because the mode may have changed from when last in editmode */
378         EDBM_selectmode_flush(me->edit_btmesh);
379 }
380
381 /**
382  * \warning This can invalidate the #DerivedMesh cache of other objects (for linked duplicates).
383  * Most callers should run #DAG_id_tag_update on \a ob->data, see: T46738, T46913
384  */
385 void EDBM_mesh_load(Object *ob)
386 {
387         Mesh *me = ob->data;
388         BMesh *bm = me->edit_btmesh->bm;
389
390         /* Workaround for T42360, 'ob->shapenr' should be 1 in this case.
391          * however this isn't synchronized between objects at the moment. */
392         if (UNLIKELY((ob->shapenr == 0) && (me->key && !BLI_listbase_is_empty(&me->key->block)))) {
393                 bm->shapenr = 1;
394         }
395
396         BM_mesh_bm_to_me(bm, me, (&(struct BMeshToMeshParams){0}));
397
398 #ifdef USE_TESSFACE_DEFAULT
399         BKE_mesh_tessface_calc(me);
400 #endif
401
402         /* free derived mesh. usually this would happen through depsgraph but there
403          * are exceptions like file save that will not cause this, and we want to
404          * avoid ending up with an invalid derived mesh then */
405         BKE_object_free_derived_caches(ob);
406 }
407
408 /**
409  * Should only be called on the active editmesh, otherwise call #BKE_editmesh_free
410  */
411 void EDBM_mesh_free(BMEditMesh *em)
412 {
413         /* These tables aren't used yet, so it's not strictly necessary
414          * to 'end' them (with 'e' param) but if someone tries to start
415          * using them, having these in place will save a lot of pain */
416         ED_mesh_mirror_spatial_table(NULL, NULL, NULL, NULL, 'e');
417         ED_mesh_mirror_topo_table(NULL, NULL, 'e');
418
419         BKE_editmesh_free(em);
420 }
421
422 void EDBM_selectmode_flush_ex(BMEditMesh *em, const short selectmode)
423 {
424         BM_mesh_select_mode_flush_ex(em->bm, selectmode);
425 }
426
427 void EDBM_selectmode_flush(BMEditMesh *em)
428 {
429         EDBM_selectmode_flush_ex(em, em->selectmode);
430 }
431
432 void EDBM_deselect_flush(BMEditMesh *em)
433 {
434         /* function below doesnt use. just do this to keep the values in sync */
435         em->bm->selectmode = em->selectmode;
436         BM_mesh_deselect_flush(em->bm);
437 }
438
439
440 void EDBM_select_flush(BMEditMesh *em)
441 {
442         /* function below doesnt use. just do this to keep the values in sync */
443         em->bm->selectmode = em->selectmode;
444         BM_mesh_select_flush(em->bm);
445 }
446
447 void EDBM_select_more(BMEditMesh *em, const bool use_face_step)
448 {
449         BMOperator bmop;
450         const bool use_faces = (em->selectmode == SCE_SELECT_FACE);
451
452         BMO_op_initf(em->bm, &bmop, BMO_FLAG_DEFAULTS,
453                      "region_extend geom=%hvef use_contract=%b use_faces=%b use_face_step=%b",
454                      BM_ELEM_SELECT, false, use_faces, use_face_step);
455         BMO_op_exec(em->bm, &bmop);
456         /* don't flush selection in edge/vertex mode  */
457         BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "geom.out", BM_ALL_NOLOOP, BM_ELEM_SELECT, use_faces ? true : false);
458         BMO_op_finish(em->bm, &bmop);
459
460         EDBM_selectmode_flush(em);
461 }
462
463 void EDBM_select_less(BMEditMesh *em, const bool use_face_step)
464 {
465         BMOperator bmop;
466         const bool use_faces = (em->selectmode == SCE_SELECT_FACE);
467
468         BMO_op_initf(em->bm, &bmop, BMO_FLAG_DEFAULTS,
469                      "region_extend geom=%hvef use_contract=%b use_faces=%b use_face_step=%b",
470                      BM_ELEM_SELECT, true, use_faces, use_face_step);
471         BMO_op_exec(em->bm, &bmop);
472         /* don't flush selection in edge/vertex mode  */
473         BMO_slot_buffer_hflag_disable(em->bm, bmop.slots_out, "geom.out", BM_ALL_NOLOOP, BM_ELEM_SELECT, use_faces ? true : false);
474         BMO_op_finish(em->bm, &bmop);
475
476         EDBM_selectmode_flush(em);
477
478         /* only needed for select less, ensure we don't have isolated elements remaining */
479         BM_mesh_select_mode_clean(em->bm);
480 }
481
482 void EDBM_flag_disable_all(BMEditMesh *em, const char hflag)
483 {
484         BM_mesh_elem_hflag_disable_all(em->bm, BM_VERT | BM_EDGE | BM_FACE, hflag, false);
485 }
486
487 void EDBM_flag_enable_all(BMEditMesh *em, const char hflag)
488 {
489         BM_mesh_elem_hflag_enable_all(em->bm, BM_VERT | BM_EDGE | BM_FACE, hflag, true);
490 }
491
492 /**
493  * Return a new UVVertMap from the editmesh
494  */
495 UvVertMap *BM_uv_vert_map_create(
496         BMesh *bm,
497         const float limit[2], const bool use_select, const bool use_winding)
498 {
499         BMVert *ev;
500         BMFace *efa;
501         BMLoop *l;
502         BMIter iter, liter;
503         /* vars from original func */
504         UvVertMap *vmap;
505         UvMapVert *buf;
506         /* MTexPoly *tf; */ /* UNUSED */
507         MLoopUV *luv;
508         unsigned int a;
509         int totverts, i, totuv, totfaces;
510         const int cd_loop_uv_offset = CustomData_get_offset(&bm->ldata, CD_MLOOPUV);
511         bool *winding = NULL;
512         BLI_buffer_declare_static(vec2f, tf_uv_buf, BLI_BUFFER_NOP, BM_DEFAULT_NGON_STACK_SIZE);
513
514         BM_mesh_elem_index_ensure(bm, BM_VERT | BM_FACE);
515         
516         totfaces = bm->totface;
517         totverts = bm->totvert;
518         totuv = 0;
519
520         /* generate UvMapVert array */
521         BM_ITER_MESH (efa, &iter, bm, BM_FACES_OF_MESH) {
522                 if ((use_select == false) || BM_elem_flag_test(efa, BM_ELEM_SELECT)) {
523                         totuv += efa->len;
524                 }
525         }
526
527         if (totuv == 0) {
528                 return NULL;
529         }
530         vmap = (UvVertMap *)MEM_callocN(sizeof(*vmap), "UvVertMap");
531         if (!vmap) {
532                 return NULL;
533         }
534
535         vmap->vert = (UvMapVert **)MEM_callocN(sizeof(*vmap->vert) * totverts, "UvMapVert_pt");
536         buf = vmap->buf = (UvMapVert *)MEM_callocN(sizeof(*vmap->buf) * totuv, "UvMapVert");
537         if (use_winding) {
538                 winding = MEM_callocN(sizeof(*winding) * totfaces, "winding");
539         }
540
541         if (!vmap->vert || !vmap->buf) {
542                 BKE_mesh_uv_vert_map_free(vmap);
543                 return NULL;
544         }
545         
546         BM_ITER_MESH_INDEX (efa, &iter, bm, BM_FACES_OF_MESH, a) {
547                 if ((use_select == false) || BM_elem_flag_test(efa, BM_ELEM_SELECT)) {
548                         float (*tf_uv)[2];
549
550                         if (use_winding) {
551                                 tf_uv = (float (*)[2])BLI_buffer_reinit_data(&tf_uv_buf, vec2f, efa->len);
552                         }
553
554                         BM_ITER_ELEM_INDEX(l, &liter, efa, BM_LOOPS_OF_FACE, i) {
555                                 buf->tfindex = i;
556                                 buf->f = a;
557                                 buf->separate = 0;
558                                 
559                                 buf->next = vmap->vert[BM_elem_index_get(l->v)];
560                                 vmap->vert[BM_elem_index_get(l->v)] = buf;
561                                 buf++;
562
563                                 if (use_winding) {
564                                         luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
565                                         copy_v2_v2(tf_uv[i], luv->uv);
566                                 }
567                         }
568
569                         if (use_winding) {
570                                 winding[a] = cross_poly_v2((const float (*)[2])tf_uv, efa->len) > 0;
571                         }
572                 }
573         }
574         
575         /* sort individual uvs for each vert */
576         BM_ITER_MESH_INDEX (ev, &iter, bm, BM_VERTS_OF_MESH, a) {
577                 UvMapVert *newvlist = NULL, *vlist = vmap->vert[a];
578                 UvMapVert *iterv, *v, *lastv, *next;
579                 float *uv, *uv2, uvdiff[2];
580
581                 while (vlist) {
582                         v = vlist;
583                         vlist = vlist->next;
584                         v->next = newvlist;
585                         newvlist = v;
586
587                         efa = BM_face_at_index(bm, v->f);
588                         /* tf = CustomData_bmesh_get(&bm->pdata, efa->head.data, CD_MTEXPOLY); */ /* UNUSED */
589                         
590                         l = BM_iter_at_index(bm, BM_LOOPS_OF_FACE, efa, v->tfindex);
591                         luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
592                         uv = luv->uv;
593                         
594                         lastv = NULL;
595                         iterv = vlist;
596
597                         while (iterv) {
598                                 next = iterv->next;
599                                 efa = BM_face_at_index(bm, iterv->f);
600                                 /* tf = CustomData_bmesh_get(&bm->pdata, efa->head.data, CD_MTEXPOLY); */ /* UNUSED */
601                                 
602                                 l = BM_iter_at_index(bm, BM_LOOPS_OF_FACE, efa, iterv->tfindex);
603                                 luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
604                                 uv2 = luv->uv;
605                                 
606                                 sub_v2_v2v2(uvdiff, uv2, uv);
607
608                                 if (fabsf(uvdiff[0]) < limit[0] && fabsf(uvdiff[1]) < limit[1] &&
609                                     (!use_winding || winding[iterv->f] == winding[v->f]))
610                                 {
611                                         if (lastv) lastv->next = next;
612                                         else vlist = next;
613                                         iterv->next = newvlist;
614                                         newvlist = iterv;
615                                 }
616                                 else {
617                                         lastv = iterv;
618                                 }
619
620                                 iterv = next;
621                         }
622
623                         newvlist->separate = 1;
624                 }
625
626                 vmap->vert[a] = newvlist;
627         }
628
629         if (use_winding) {
630                 MEM_freeN(winding);
631         }
632
633         BLI_buffer_free(&tf_uv_buf);
634
635         return vmap;
636 }
637
638
639 UvMapVert *BM_uv_vert_map_at_index(UvVertMap *vmap, unsigned int v)
640 {
641         return vmap->vert[v];
642 }
643
644
645 /* A specialized vert map used by stitch operator */
646 UvElementMap *BM_uv_element_map_create(
647         BMesh *bm,
648         const bool selected, const bool use_winding, const bool do_islands)
649 {
650         BMVert *ev;
651         BMFace *efa;
652         BMLoop *l;
653         BMIter iter, liter;
654         /* vars from original func */
655         UvElementMap *element_map;
656         UvElement *buf;
657         bool *winding;
658         BLI_buffer_declare_static(vec2f, tf_uv_buf, BLI_BUFFER_NOP, BM_DEFAULT_NGON_STACK_SIZE);
659
660         MLoopUV *luv;
661         int totverts, totfaces, i, totuv, j;
662
663         const int cd_loop_uv_offset = CustomData_get_offset(&bm->ldata, CD_MLOOPUV);
664
665         BM_mesh_elem_index_ensure(bm, BM_VERT | BM_FACE);
666
667         totfaces = bm->totface;
668         totverts = bm->totvert;
669         totuv = 0;
670
671         /* generate UvElement array */
672         BM_ITER_MESH (efa, &iter, bm, BM_FACES_OF_MESH) {
673                 if (!selected || BM_elem_flag_test(efa, BM_ELEM_SELECT)) {
674                         totuv += efa->len;
675                 }
676         }
677
678         if (totuv == 0) {
679                 return NULL;
680         }
681
682         element_map = (UvElementMap *)MEM_callocN(sizeof(*element_map), "UvElementMap");
683         element_map->totalUVs = totuv;
684         element_map->vert = (UvElement **)MEM_callocN(sizeof(*element_map->vert) * totverts, "UvElementVerts");
685         buf = element_map->buf = (UvElement *)MEM_callocN(sizeof(*element_map->buf) * totuv, "UvElement");
686
687         if (use_winding) {
688                 winding = MEM_mallocN(sizeof(*winding) * totfaces, "winding");
689         }
690
691         BM_ITER_MESH_INDEX (efa, &iter, bm, BM_FACES_OF_MESH, j) {
692
693                 if (use_winding) {
694                         winding[j] = false;
695                 }
696
697                 if (!selected || BM_elem_flag_test(efa, BM_ELEM_SELECT)) {
698                         float (*tf_uv)[2];
699
700                         if (use_winding) {
701                                 tf_uv = (float (*)[2])BLI_buffer_reinit_data(&tf_uv_buf, vec2f, efa->len);
702                         }
703
704                         BM_ITER_ELEM_INDEX (l, &liter, efa, BM_LOOPS_OF_FACE, i) {
705                                 buf->l = l;
706                                 buf->separate = 0;
707                                 buf->island = INVALID_ISLAND;
708                                 buf->tfindex = i;
709
710                                 buf->next = element_map->vert[BM_elem_index_get(l->v)];
711                                 element_map->vert[BM_elem_index_get(l->v)] = buf;
712
713                                 if (use_winding) {
714                                         luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
715                                         copy_v2_v2(tf_uv[i], luv->uv);
716                                 }
717
718                                 buf++;
719                         }
720
721                         if (use_winding) {
722                                 winding[j] = cross_poly_v2((const float (*)[2])tf_uv, efa->len) > 0;
723                         }
724                 }
725         }
726
727         /* sort individual uvs for each vert */
728         BM_ITER_MESH_INDEX (ev, &iter, bm, BM_VERTS_OF_MESH, i) {
729                 UvElement *newvlist = NULL, *vlist = element_map->vert[i];
730                 UvElement *iterv, *v, *lastv, *next;
731                 float *uv, *uv2, uvdiff[2];
732
733                 while (vlist) {
734                         v = vlist;
735                         vlist = vlist->next;
736                         v->next = newvlist;
737                         newvlist = v;
738
739                         l = v->l;
740                         luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
741                         uv = luv->uv;
742
743                         lastv = NULL;
744                         iterv = vlist;
745
746                         while (iterv) {
747                                 next = iterv->next;
748
749                                 l = iterv->l;
750                                 luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
751                                 uv2 = luv->uv;
752
753                                 sub_v2_v2v2(uvdiff, uv2, uv);
754
755                                 if (fabsf(uvdiff[0]) < STD_UV_CONNECT_LIMIT && fabsf(uvdiff[1]) < STD_UV_CONNECT_LIMIT &&
756                                     (!use_winding || winding[BM_elem_index_get(iterv->l->f)] == winding[BM_elem_index_get(v->l->f)]))
757                                 {
758                                         if (lastv) lastv->next = next;
759                                         else vlist = next;
760                                         iterv->next = newvlist;
761                                         newvlist = iterv;
762                                 }
763                                 else {
764                                         lastv = iterv;
765                                 }
766
767                                 iterv = next;
768                         }
769
770                         newvlist->separate = 1;
771                 }
772
773                 element_map->vert[i] = newvlist;
774         }
775
776         if (use_winding) {
777                 MEM_freeN(winding);
778         }
779
780         if (do_islands) {
781                 unsigned int *map;
782                 BMFace **stack;
783                 int stacksize = 0;
784                 UvElement *islandbuf;
785                 /* island number for faces */
786                 int *island_number = NULL;
787
788                 int nislands = 0, islandbufsize = 0;
789
790                 /* map holds the map from current vmap->buf to the new, sorted map */
791                 map = MEM_mallocN(sizeof(*map) * totuv, "uvelement_remap");
792                 stack = MEM_mallocN(sizeof(*stack) * bm->totface, "uv_island_face_stack");
793                 islandbuf = MEM_callocN(sizeof(*islandbuf) * totuv, "uvelement_island_buffer");
794                 island_number = MEM_mallocN(sizeof(*island_number) * totfaces, "uv_island_number_face");
795                 copy_vn_i(island_number, totfaces, INVALID_ISLAND);
796
797                 /* at this point, every UvElement in vert points to a UvElement sharing the same vertex. Now we should sort uv's in islands. */
798                 for (i = 0; i < totuv; i++) {
799                         if (element_map->buf[i].island == INVALID_ISLAND) {
800                                 element_map->buf[i].island = nislands;
801                                 stack[0] = element_map->buf[i].l->f;
802                                 island_number[BM_elem_index_get(stack[0])] = nislands;
803                                 stacksize = 1;
804
805                                 while (stacksize > 0) {
806                                         efa = stack[--stacksize];
807
808                                         BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
809                                                 UvElement *element, *initelement = element_map->vert[BM_elem_index_get(l->v)];
810
811                                                 for (element = initelement; element; element = element->next) {
812                                                         if (element->separate)
813                                                                 initelement = element;
814
815                                                         if (element->l->f == efa) {
816                                                                 /* found the uv corresponding to our face and vertex. Now fill it to the buffer */
817                                                                 element->island = nislands;
818                                                                 map[element - element_map->buf] = islandbufsize;
819                                                                 islandbuf[islandbufsize].l = element->l;
820                                                                 islandbuf[islandbufsize].separate = element->separate;
821                                                                 islandbuf[islandbufsize].tfindex = element->tfindex;
822                                                                 islandbuf[islandbufsize].island =  nislands;
823                                                                 islandbufsize++;
824
825                                                                 for (element = initelement; element; element = element->next) {
826                                                                         if (element->separate && element != initelement)
827                                                                                 break;
828
829                                                                         if (island_number[BM_elem_index_get(element->l->f)] == INVALID_ISLAND) {
830                                                                                 stack[stacksize++] = element->l->f;
831                                                                                 island_number[BM_elem_index_get(element->l->f)] = nislands;
832                                                                         }
833                                                                 }
834                                                                 break;
835                                                         }
836                                                 }
837                                         }
838                                 }
839
840                                 nislands++;
841                         }
842                 }
843
844                 MEM_freeN(island_number);
845
846                 /* remap */
847                 for (i = 0; i < bm->totvert; i++) {
848                         /* important since we may do selection only. Some of these may be NULL */
849                         if (element_map->vert[i])
850                                 element_map->vert[i] = &islandbuf[map[element_map->vert[i] - element_map->buf]];
851                 }
852
853                 element_map->islandIndices = MEM_callocN(sizeof(*element_map->islandIndices) * nislands, "UvElementMap_island_indices");
854                 j = 0;
855                 for (i = 0; i < totuv; i++) {
856                         UvElement *element = element_map->buf[i].next;
857                         if (element == NULL)
858                                 islandbuf[map[i]].next = NULL;
859                         else
860                                 islandbuf[map[i]].next = &islandbuf[map[element - element_map->buf]];
861
862                         if (islandbuf[i].island != j) {
863                                 j++;
864                                 element_map->islandIndices[j] = i;
865                         }
866                 }
867
868                 MEM_freeN(element_map->buf);
869
870                 element_map->buf = islandbuf;
871                 element_map->totalIslands = nislands;
872                 MEM_freeN(stack);
873                 MEM_freeN(map);
874         }
875
876         BLI_buffer_free(&tf_uv_buf);
877
878         return element_map;
879 }
880
881 void BM_uv_vert_map_free(UvVertMap *vmap)
882 {
883         if (vmap) {
884                 if (vmap->vert) MEM_freeN(vmap->vert);
885                 if (vmap->buf) MEM_freeN(vmap->buf);
886                 MEM_freeN(vmap);
887         }
888 }
889
890 void BM_uv_element_map_free(UvElementMap *element_map)
891 {
892         if (element_map) {
893                 if (element_map->vert) MEM_freeN(element_map->vert);
894                 if (element_map->buf) MEM_freeN(element_map->buf);
895                 if (element_map->islandIndices) MEM_freeN(element_map->islandIndices);
896                 MEM_freeN(element_map);
897         }
898 }
899
900 UvElement *BM_uv_element_get(UvElementMap *map, BMFace *efa, BMLoop *l)
901 {
902         UvElement *element;
903
904         element = map->vert[BM_elem_index_get(l->v)];
905
906         for (; element; element = element->next)
907                 if (element->l->f == efa)
908                         return element;
909
910         return NULL;
911 }
912
913 /* last_sel, use em->act_face otherwise get the last selected face in the editselections
914  * at the moment, last_sel is mainly useful for making sure the space image dosnt flicker */
915 MTexPoly *EDBM_mtexpoly_active_get(BMEditMesh *em, BMFace **r_act_efa, const bool sloppy, const bool selected)
916 {
917         BMFace *efa = NULL;
918         
919         if (!EDBM_mtexpoly_check(em))
920                 return NULL;
921         
922         efa = BM_mesh_active_face_get(em->bm, sloppy, selected);
923
924         if (efa) {
925                 if (r_act_efa) *r_act_efa = efa;
926                 return CustomData_bmesh_get(&em->bm->pdata, efa->head.data, CD_MTEXPOLY);
927         }
928
929         if (r_act_efa) *r_act_efa = NULL;
930         return NULL;
931 }
932
933 /* can we edit UV's for this mesh?*/
934 bool EDBM_mtexpoly_check(BMEditMesh *em)
935 {
936         /* some of these checks could be a touch overkill */
937         return em && em->bm->totface && CustomData_has_layer(&em->bm->pdata, CD_MTEXPOLY) &&
938                CustomData_has_layer(&em->bm->ldata, CD_MLOOPUV);
939 }
940
941 bool EDBM_vert_color_check(BMEditMesh *em)
942 {
943         /* some of these checks could be a touch overkill */
944         return em && em->bm->totface && CustomData_has_layer(&em->bm->ldata, CD_MLOOPCOL);
945 }
946
947 static BMVert *cache_mirr_intptr_as_bmvert(intptr_t *index_lookup, int index)
948 {
949         intptr_t eve_i = index_lookup[index];
950         return (eve_i == -1) ? NULL : (BMVert *)eve_i;
951 }
952
953 /**
954  * Mirror editing API, usage:
955  *
956  * \code{.c}
957  * EDBM_verts_mirror_cache_begin(em, ...);
958  *
959  * BM_ITER_MESH (v, &iter, em->bm, BM_VERTS_OF_MESH) {
960  *     v_mirror = EDBM_verts_mirror_get(em, v);
961  *     e_mirror = EDBM_verts_mirror_get_edge(em, e);
962  *     f_mirror = EDBM_verts_mirror_get_face(em, f);
963  * }
964  *
965  * EDBM_verts_mirror_cache_end(em);
966  * \endcode
967  */
968
969 /* BM_SEARCH_MAXDIST is too big, copied from 2.6x MOC_THRESH, should become a
970  * preference */
971 #define BM_SEARCH_MAXDIST_MIRR 0.00002f
972 #define BM_CD_LAYER_ID "__mirror_index"
973 /**
974  * \param em  Editmesh.
975  * \param use_self  Allow a vertex to point to its self (middle verts).
976  * \param use_select  Restrict to selected verts.
977  * \param use_topology  Use topology mirror.
978  * \param maxdist  Distance for close point test.
979  * \param r_index  Optional array to write into, as an alternative to a customdata layer (length of total verts).
980  */
981 void EDBM_verts_mirror_cache_begin_ex(BMEditMesh *em, const int axis, const bool use_self, const bool use_select,
982                                       /* extra args */
983                                       const bool use_topology, float maxdist, int *r_index)
984 {
985         Mesh *me = (Mesh *)em->ob->data;
986         BMesh *bm = em->bm;
987         BMIter iter;
988         BMVert *v;
989         int cd_vmirr_offset;
990         int i;
991         const float maxdist_sq = SQUARE(maxdist);
992
993         /* one or the other is used depending if topo is enabled */
994         KDTree *tree = NULL;
995         MirrTopoStore_t mesh_topo_store = {NULL, -1, -1, -1};
996
997         BM_mesh_elem_table_ensure(bm, BM_VERT);
998
999         if (r_index == NULL) {
1000                 const char *layer_id = BM_CD_LAYER_ID;
1001                 em->mirror_cdlayer = CustomData_get_named_layer_index(&bm->vdata, CD_PROP_INT, layer_id);
1002                 if (em->mirror_cdlayer == -1) {
1003                         BM_data_layer_add_named(bm, &bm->vdata, CD_PROP_INT, layer_id);
1004                         em->mirror_cdlayer = CustomData_get_named_layer_index(&bm->vdata, CD_PROP_INT, layer_id);
1005                 }
1006
1007                 cd_vmirr_offset = CustomData_get_n_offset(&bm->vdata, CD_PROP_INT,
1008                                                           em->mirror_cdlayer - CustomData_get_layer_index(&bm->vdata, CD_PROP_INT));
1009
1010                 bm->vdata.layers[em->mirror_cdlayer].flag |= CD_FLAG_TEMPORARY;
1011         }
1012
1013         BM_mesh_elem_index_ensure(bm, BM_VERT);
1014
1015         if (use_topology) {
1016                 ED_mesh_mirrtopo_init(me, NULL, -1, &mesh_topo_store, true);
1017         }
1018         else {
1019                 tree = BLI_kdtree_new(bm->totvert);
1020                 BM_ITER_MESH_INDEX (v, &iter, bm, BM_VERTS_OF_MESH, i) {
1021                         BLI_kdtree_insert(tree, i, v->co);
1022                 }
1023                 BLI_kdtree_balance(tree);
1024         }
1025
1026 #define VERT_INTPTR(_v, _i) r_index ? &r_index[_i] : BM_ELEM_CD_GET_VOID_P(_v, cd_vmirr_offset);
1027
1028         BM_ITER_MESH_INDEX (v, &iter, bm, BM_VERTS_OF_MESH, i) {
1029                 BLI_assert(BM_elem_index_get(v) == i);
1030
1031                 /* temporary for testing, check for selection */
1032                 if (use_select && !BM_elem_flag_test(v, BM_ELEM_SELECT)) {
1033                         /* do nothing */
1034                 }
1035                 else {
1036                         BMVert *v_mirr;
1037                         int *idx = VERT_INTPTR(v, i);
1038
1039                         if (use_topology) {
1040                                 v_mirr = cache_mirr_intptr_as_bmvert(mesh_topo_store.index_lookup, i);
1041                         }
1042                         else {
1043                                 int i_mirr;
1044                                 float co[3];
1045                                 copy_v3_v3(co, v->co);
1046                                 co[axis] *= -1.0f;
1047
1048                                 v_mirr = NULL;
1049                                 i_mirr = BLI_kdtree_find_nearest(tree, co, NULL);
1050                                 if (i_mirr != -1) {
1051                                         BMVert *v_test = BM_vert_at_index(bm, i_mirr);
1052                                         if (len_squared_v3v3(co, v_test->co) < maxdist_sq) {
1053                                                 v_mirr = v_test;
1054                                         }
1055                                 }
1056                         }
1057
1058                         if (v_mirr && (use_self || (v_mirr != v))) {
1059                                 const int i_mirr = BM_elem_index_get(v_mirr);
1060                                 *idx = i_mirr;
1061                                 idx = VERT_INTPTR(v_mirr, i_mirr);
1062                                 *idx = i;
1063                         }
1064                         else {
1065                                 *idx = -1;
1066                         }
1067                 }
1068
1069         }
1070
1071 #undef VERT_INTPTR
1072
1073         if (use_topology) {
1074                 ED_mesh_mirrtopo_free(&mesh_topo_store);
1075         }
1076         else {
1077                 BLI_kdtree_free(tree);
1078         }
1079 }
1080
1081 void EDBM_verts_mirror_cache_begin(BMEditMesh *em, const int axis,
1082                                    const bool use_self, const bool use_select,
1083                                    const bool use_topology)
1084 {
1085         EDBM_verts_mirror_cache_begin_ex(em, axis,
1086                                          use_self, use_select,
1087                                          /* extra args */
1088                                          use_topology, BM_SEARCH_MAXDIST_MIRR, NULL);
1089 }
1090
1091 BMVert *EDBM_verts_mirror_get(BMEditMesh *em, BMVert *v)
1092 {
1093         const int *mirr = CustomData_bmesh_get_layer_n(&em->bm->vdata, v->head.data, em->mirror_cdlayer);
1094
1095         BLI_assert(em->mirror_cdlayer != -1); /* invalid use */
1096
1097         if (mirr && *mirr >= 0 && *mirr < em->bm->totvert) {
1098                 if (!em->bm->vtable) {
1099                         printf("err: should only be called between "
1100                                "EDBM_verts_mirror_cache_begin and EDBM_verts_mirror_cache_end");
1101                         return NULL;
1102                 }
1103
1104                 return em->bm->vtable[*mirr];
1105         }
1106
1107         return NULL;
1108 }
1109
1110 BMEdge *EDBM_verts_mirror_get_edge(BMEditMesh *em, BMEdge *e)
1111 {
1112         BMVert *v1_mirr = EDBM_verts_mirror_get(em, e->v1);
1113         if (v1_mirr) {
1114                 BMVert *v2_mirr = EDBM_verts_mirror_get(em, e->v2);
1115                 if (v2_mirr) {
1116                         return BM_edge_exists(v1_mirr, v2_mirr);
1117                 }
1118         }
1119
1120         return NULL;
1121 }
1122
1123 BMFace *EDBM_verts_mirror_get_face(BMEditMesh *em, BMFace *f)
1124 {
1125         BMFace *f_mirr = NULL;
1126         BMVert **v_mirr_arr = BLI_array_alloca(v_mirr_arr, f->len);
1127
1128         BMLoop *l_iter, *l_first;
1129         unsigned int i = 0;
1130
1131         l_iter = l_first = BM_FACE_FIRST_LOOP(f);
1132         do {
1133                 if ((v_mirr_arr[i++] = EDBM_verts_mirror_get(em, l_iter->v)) == NULL) {
1134                         return NULL;
1135                 }
1136         } while ((l_iter = l_iter->next) != l_first);
1137
1138         BM_face_exists(v_mirr_arr, f->len, &f_mirr);
1139         return f_mirr;
1140 }
1141
1142 void EDBM_verts_mirror_cache_clear(BMEditMesh *em, BMVert *v)
1143 {
1144         int *mirr = CustomData_bmesh_get_layer_n(&em->bm->vdata, v->head.data, em->mirror_cdlayer);
1145
1146         BLI_assert(em->mirror_cdlayer != -1); /* invalid use */
1147
1148         if (mirr) {
1149                 *mirr = -1;
1150         }
1151 }
1152
1153 void EDBM_verts_mirror_cache_end(BMEditMesh *em)
1154 {
1155         em->mirror_cdlayer = -1;
1156 }
1157
1158 void EDBM_verts_mirror_apply(BMEditMesh *em, const int sel_from, const int sel_to)
1159 {
1160         BMIter iter;
1161         BMVert *v;
1162
1163         BLI_assert((em->bm->vtable != NULL) && ((em->bm->elem_table_dirty & BM_VERT) == 0));
1164
1165         BM_ITER_MESH (v, &iter, em->bm, BM_VERTS_OF_MESH) {
1166                 if (BM_elem_flag_test(v, BM_ELEM_SELECT) == sel_from) {
1167                         BMVert *mirr = EDBM_verts_mirror_get(em, v);
1168                         if (mirr) {
1169                                 if (BM_elem_flag_test(mirr, BM_ELEM_SELECT) == sel_to) {
1170                                         copy_v3_v3(mirr->co, v->co);
1171                                         mirr->co[0] *= -1.0f;
1172                                 }
1173                         }
1174                 }
1175         }
1176 }
1177
1178
1179 /* swap is 0 or 1, if 1 it hides not selected */
1180 void EDBM_mesh_hide(BMEditMesh *em, bool swap)
1181 {
1182         BMIter iter;
1183         BMElem *ele;
1184         int itermode;
1185         char hflag_swap = swap ? BM_ELEM_SELECT : 0;
1186
1187         if (em == NULL) return;
1188
1189         if (em->selectmode & SCE_SELECT_VERTEX)
1190                 itermode = BM_VERTS_OF_MESH;
1191         else if (em->selectmode & SCE_SELECT_EDGE)
1192                 itermode = BM_EDGES_OF_MESH;
1193         else
1194                 itermode = BM_FACES_OF_MESH;
1195
1196         BM_ITER_MESH (ele, &iter, em->bm, itermode) {
1197                 if (BM_elem_flag_test(ele, BM_ELEM_SELECT) ^ hflag_swap)
1198                         BM_elem_hide_set(em->bm, ele, true);
1199         }
1200
1201         EDBM_selectmode_flush(em);
1202
1203         /* original hide flushing comment (OUTDATED):
1204          * hide happens on least dominant select mode, and flushes up, not down! (helps preventing errors in subsurf) */
1205         /* - vertex hidden, always means edge is hidden too
1206          * - edge hidden, always means face is hidden too
1207          * - face hidden, only set face hide
1208          * - then only flush back down what's absolute hidden
1209          */
1210 }
1211
1212
1213 void EDBM_mesh_reveal(BMEditMesh *em)
1214 {
1215         const char iter_types[3] = {BM_VERTS_OF_MESH,
1216                                     BM_EDGES_OF_MESH,
1217                                     BM_FACES_OF_MESH};
1218
1219         const bool sels[3] = {
1220             (em->selectmode & SCE_SELECT_VERTEX) != 0,
1221             (em->selectmode & SCE_SELECT_EDGE) != 0,
1222             (em->selectmode & SCE_SELECT_FACE) != 0,
1223         };
1224         int i;
1225
1226         /* Use tag flag to remember what was hidden before all is revealed.
1227          * BM_ELEM_HIDDEN --> BM_ELEM_TAG */
1228 #pragma omp parallel for schedule(static) if (em->bm->totvert + em->bm->totedge + em->bm->totface >= BM_OMP_LIMIT)
1229         for (i = 0; i < 3; i++) {
1230                 BMIter iter;
1231                 BMElem *ele;
1232
1233                 BM_ITER_MESH (ele, &iter, em->bm, iter_types[i]) {
1234                         BM_elem_flag_set(ele, BM_ELEM_TAG, BM_elem_flag_test(ele, BM_ELEM_HIDDEN));
1235                 }
1236         }
1237
1238         /* Reveal everything */
1239         EDBM_flag_disable_all(em, BM_ELEM_HIDDEN);
1240
1241         /* Select relevant just-revealed elements */
1242         for (i = 0; i < 3; i++) {
1243                 BMIter iter;
1244                 BMElem *ele;
1245
1246                 if (!sels[i]) {
1247                         continue;
1248                 }
1249
1250                 BM_ITER_MESH (ele, &iter, em->bm, iter_types[i]) {
1251                         if (BM_elem_flag_test(ele, BM_ELEM_TAG)) {
1252                                 BM_elem_select_set(em->bm, ele, true);
1253                         }
1254                 }
1255         }
1256
1257         EDBM_selectmode_flush(em);
1258
1259         /* hidden faces can have invalid normals */
1260         EDBM_mesh_normals_update(em);
1261 }
1262
1263 /* so many tools call these that we better make it a generic function.
1264  */
1265 void EDBM_update_generic(BMEditMesh *em, const bool do_tessface, const bool is_destructive)
1266 {
1267         Object *ob = em->ob;
1268         /* order of calling isn't important */
1269         DAG_id_tag_update(ob->data, OB_RECALC_DATA);
1270         WM_main_add_notifier(NC_GEOM | ND_DATA, ob->data);
1271
1272         if (do_tessface) {
1273                 BKE_editmesh_tessface_calc(em);
1274         }
1275
1276         if (is_destructive) {
1277                 /* TODO. we may be able to remove this now! - Campbell */
1278                 // BM_mesh_elem_table_free(em->bm, BM_ALL_NOLOOP);
1279         }
1280         else {
1281                 /* in debug mode double check we didn't need to recalculate */
1282                 BLI_assert(BM_mesh_elem_table_check(em->bm) == true);
1283         }
1284
1285         /* don't keep stale derivedMesh data around, see: [#38872] */
1286         BKE_editmesh_free_derivedmesh(em);
1287
1288 #ifdef DEBUG
1289         {
1290                 BMEditSelection *ese;
1291                 for (ese = em->bm->selected.first; ese; ese = ese->next) {
1292                         BLI_assert(BM_elem_flag_test(ese->ele, BM_ELEM_SELECT));
1293                 }
1294         }
1295 #endif
1296 }
1297
1298 /* poll call for mesh operators requiring a view3d context */
1299 int EDBM_view3d_poll(bContext *C)
1300 {
1301         if (ED_operator_editmesh(C) && ED_operator_view3d_active(C))
1302                 return 1;
1303
1304         return 0;
1305 }
1306
1307 BMElem *EDBM_elem_from_selectmode(BMEditMesh *em, BMVert *eve, BMEdge *eed, BMFace *efa)
1308 {
1309         BMElem *ele = NULL;
1310
1311         if ((em->selectmode & SCE_SELECT_VERTEX) && eve) {
1312                 ele = (BMElem *)eve;
1313         }
1314         else if ((em->selectmode & SCE_SELECT_EDGE) && eed) {
1315                 ele = (BMElem *)eed;
1316         }
1317         else if ((em->selectmode & SCE_SELECT_FACE) && efa) {
1318                 ele = (BMElem *)efa;
1319         }
1320
1321         return ele;
1322 }
1323
1324 /**
1325  * Used when we want to store a single index for any vert/edge/face.
1326  *
1327  * Intended for use with operators.
1328  */
1329 int EDBM_elem_to_index_any(BMEditMesh *em, BMElem *ele)
1330 {
1331         BMesh *bm = em->bm;
1332         int index = BM_elem_index_get(ele);
1333
1334         if (ele->head.htype == BM_VERT) {
1335                 BLI_assert(!(bm->elem_index_dirty & BM_VERT));
1336         }
1337         else if (ele->head.htype == BM_EDGE) {
1338                 BLI_assert(!(bm->elem_index_dirty & BM_EDGE));
1339                 index += bm->totvert;
1340         }
1341         else if (ele->head.htype == BM_FACE) {
1342                 BLI_assert(!(bm->elem_index_dirty & BM_FACE));
1343                 index += bm->totvert + bm->totedge;
1344         }
1345         else {
1346                 BLI_assert(0);
1347         }
1348
1349         return index;
1350 }
1351
1352 BMElem *EDBM_elem_from_index_any(BMEditMesh *em, int index)
1353 {
1354         BMesh *bm = em->bm;
1355
1356         if (index < bm->totvert) {
1357                 return (BMElem *)BM_vert_at_index_find_or_table(bm, index);
1358         }
1359         index -= bm->totvert;
1360         if (index < bm->totedge) {
1361                 return (BMElem *)BM_edge_at_index_find_or_table(bm, index);
1362         }
1363         index -= bm->totedge;
1364         if (index < bm->totface) {
1365                 return (BMElem *)BM_face_at_index_find_or_table(bm, index);
1366         }
1367
1368         return NULL;
1369 }
1370
1371 /* -------------------------------------------------------------------- */
1372 /* BMBVH functions */
1373 // XXX
1374 #if 0 //BMESH_TODO: not implemented yet
1375 int BMBVH_VertVisible(BMBVHTree *tree, BMEdge *e, RegionView3D *r3d)
1376 {
1377
1378 }
1379 #endif
1380
1381 static BMFace *edge_ray_cast(struct BMBVHTree *tree, const float co[3], const float dir[3], float *r_hitout, BMEdge *e)
1382 {
1383         BMFace *f = BKE_bmbvh_ray_cast(tree, co, dir, 0.0f, NULL, r_hitout, NULL);
1384
1385         if (f && BM_edge_in_face(e, f))
1386                 return NULL;
1387
1388         return f;
1389 }
1390
1391 static void scale_point(float c1[3], const float p[3], const float s)
1392 {
1393         sub_v3_v3(c1, p);
1394         mul_v3_fl(c1, s);
1395         add_v3_v3(c1, p);
1396 }
1397
1398 bool BMBVH_EdgeVisible(struct BMBVHTree *tree, BMEdge *e, ARegion *ar, View3D *v3d, Object *obedit)
1399 {
1400         BMFace *f;
1401         float co1[3], co2[3], co3[3], dir1[3], dir2[3], dir3[3];
1402         float origin[3], invmat[4][4];
1403         float epsilon = 0.01f;
1404         float end[3];
1405         const float mval_f[2] = {ar->winx / 2.0f,
1406                                  ar->winy / 2.0f};
1407
1408         ED_view3d_win_to_segment(ar, v3d, mval_f, origin, end, false);
1409
1410         invert_m4_m4(invmat, obedit->obmat);
1411         mul_m4_v3(invmat, origin);
1412
1413         copy_v3_v3(co1, e->v1->co);
1414         mid_v3_v3v3(co2, e->v1->co, e->v2->co);
1415         copy_v3_v3(co3, e->v2->co);
1416
1417         scale_point(co1, co2, 0.99);
1418         scale_point(co3, co2, 0.99);
1419
1420         /* ok, idea is to generate rays going from the camera origin to the
1421          * three points on the edge (v1, mid, v2)*/
1422         sub_v3_v3v3(dir1, origin, co1);
1423         sub_v3_v3v3(dir2, origin, co2);
1424         sub_v3_v3v3(dir3, origin, co3);
1425
1426         normalize_v3(dir1);
1427         normalize_v3(dir2);
1428         normalize_v3(dir3);
1429
1430         mul_v3_fl(dir1, epsilon);
1431         mul_v3_fl(dir2, epsilon);
1432         mul_v3_fl(dir3, epsilon);
1433
1434         /* offset coordinates slightly along view vectors, to avoid
1435          * hitting the faces that own the edge.*/
1436         add_v3_v3v3(co1, co1, dir1);
1437         add_v3_v3v3(co2, co2, dir2);
1438         add_v3_v3v3(co3, co3, dir3);
1439
1440         normalize_v3(dir1);
1441         normalize_v3(dir2);
1442         normalize_v3(dir3);
1443
1444         /* do three samplings: left, middle, right */
1445         f = edge_ray_cast(tree, co1, dir1, NULL, e);
1446         if (f && !edge_ray_cast(tree, co2, dir2, NULL, e))
1447                 return true;
1448         else if (f && !edge_ray_cast(tree, co3, dir3, NULL, e))
1449                 return true;
1450         else if (!f)
1451                 return true;
1452
1453         return false;
1454 }