Cleanup: strip trailing space in bmesh module
[blender.git] / source / blender / bmesh / intern / bmesh_mesh.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  * Contributor(s): Geoffrey Bantle.
19  *
20  * ***** END GPL LICENSE BLOCK *****
21  */
22
23 /** \file blender/bmesh/intern/bmesh_mesh.c
24  *  \ingroup bmesh
25  *
26  * BM mesh level functions.
27  */
28
29 #include "MEM_guardedalloc.h"
30
31 #include "DNA_listBase.h"
32 #include "DNA_object_types.h"
33
34 #include "BLI_linklist_stack.h"
35 #include "BLI_listbase.h"
36 #include "BLI_math.h"
37 #include "BLI_stack.h"
38 #include "BLI_task.h"
39 #include "BLI_utildefines.h"
40
41 #include "BKE_cdderivedmesh.h"
42 #include "BKE_editmesh.h"
43 #include "BKE_mesh.h"
44 #include "BKE_multires.h"
45
46 #include "atomic_ops.h"
47
48 #include "intern/bmesh_private.h"
49
50 /* used as an extern, defined in bmesh.h */
51 const BMAllocTemplate bm_mesh_allocsize_default = {512, 1024, 2048, 512};
52 const BMAllocTemplate bm_mesh_chunksize_default = {512, 1024, 2048, 512};
53
54 static void bm_mempool_init_ex(
55         const BMAllocTemplate *allocsize, const bool use_toolflags,
56         BLI_mempool **r_vpool, BLI_mempool **r_epool, BLI_mempool **r_lpool, BLI_mempool **r_fpool)
57 {
58         size_t vert_size, edge_size, loop_size, face_size;
59
60         if (use_toolflags == true) {
61                 vert_size = sizeof(BMVert_OFlag);
62                 edge_size = sizeof(BMEdge_OFlag);
63                 loop_size = sizeof(BMLoop);
64                 face_size = sizeof(BMFace_OFlag);
65         }
66         else {
67                 vert_size = sizeof(BMVert);
68                 edge_size = sizeof(BMEdge);
69                 loop_size = sizeof(BMLoop);
70                 face_size = sizeof(BMFace);
71         }
72
73         if (r_vpool) {
74                 *r_vpool = BLI_mempool_create(
75                         vert_size, allocsize->totvert,
76                         bm_mesh_chunksize_default.totvert, BLI_MEMPOOL_ALLOW_ITER);
77         }
78         if (r_epool) {
79                 *r_epool = BLI_mempool_create(
80                         edge_size, allocsize->totedge,
81                         bm_mesh_chunksize_default.totedge, BLI_MEMPOOL_ALLOW_ITER);
82         }
83         if (r_lpool) {
84                 *r_lpool = BLI_mempool_create(
85                         loop_size, allocsize->totloop,
86                         bm_mesh_chunksize_default.totloop, BLI_MEMPOOL_NOP);
87         }
88         if (r_fpool) {
89                 *r_fpool = BLI_mempool_create(
90                         face_size, allocsize->totface,
91                         bm_mesh_chunksize_default.totface, BLI_MEMPOOL_ALLOW_ITER);
92         }
93 }
94
95 static void bm_mempool_init(BMesh *bm, const BMAllocTemplate *allocsize, const bool use_toolflags)
96 {
97         bm_mempool_init_ex(
98                 allocsize, use_toolflags,
99                 &bm->vpool, &bm->epool, &bm->lpool, &bm->fpool);
100
101 #ifdef USE_BMESH_HOLES
102         bm->looplistpool = BLI_mempool_create(sizeof(BMLoopList), 512, 512, BLI_MEMPOOL_NOP);
103 #endif
104 }
105
106 void BM_mesh_elem_toolflags_ensure(BMesh *bm)
107 {
108         BLI_assert(bm->use_toolflags);
109
110         if (bm->vtoolflagpool && bm->etoolflagpool && bm->ftoolflagpool) {
111                 return;
112         }
113
114         bm->vtoolflagpool = BLI_mempool_create(sizeof(BMFlagLayer), bm->totvert, 512, BLI_MEMPOOL_NOP);
115         bm->etoolflagpool = BLI_mempool_create(sizeof(BMFlagLayer), bm->totedge, 512, BLI_MEMPOOL_NOP);
116         bm->ftoolflagpool = BLI_mempool_create(sizeof(BMFlagLayer), bm->totface, 512, BLI_MEMPOOL_NOP);
117
118         BMIter iter;
119         BMVert_OFlag *v_olfag;
120         BLI_mempool *toolflagpool = bm->vtoolflagpool;
121         BM_ITER_MESH (v_olfag, &iter, bm, BM_VERTS_OF_MESH) {
122                 v_olfag->oflags = BLI_mempool_calloc(toolflagpool);
123         }
124
125         BMEdge_OFlag *e_olfag;
126         toolflagpool = bm->etoolflagpool;
127         BM_ITER_MESH (e_olfag, &iter, bm, BM_EDGES_OF_MESH) {
128                 e_olfag->oflags = BLI_mempool_calloc(toolflagpool);
129         }
130
131         BMFace_OFlag *f_olfag;
132         toolflagpool = bm->ftoolflagpool;
133         BM_ITER_MESH (f_olfag, &iter, bm, BM_FACES_OF_MESH) {
134                 f_olfag->oflags = BLI_mempool_calloc(toolflagpool);
135         }
136
137         bm->totflags = 1;
138 }
139
140 void BM_mesh_elem_toolflags_clear(BMesh *bm)
141 {
142         if (bm->vtoolflagpool) {
143                 BLI_mempool_destroy(bm->vtoolflagpool);
144                 bm->vtoolflagpool = NULL;
145         }
146         if (bm->etoolflagpool) {
147                 BLI_mempool_destroy(bm->etoolflagpool);
148                 bm->etoolflagpool = NULL;
149         }
150         if (bm->ftoolflagpool) {
151                 BLI_mempool_destroy(bm->ftoolflagpool);
152                 bm->ftoolflagpool = NULL;
153         }
154 }
155
156 /**
157  * \brief BMesh Make Mesh
158  *
159  * Allocates a new BMesh structure.
160  *
161  * \return The New bmesh
162  *
163  * \note ob is needed by multires
164  */
165 BMesh *BM_mesh_create(
166         const BMAllocTemplate *allocsize,
167         const struct BMeshCreateParams *params)
168 {
169         /* allocate the structure */
170         BMesh *bm = MEM_callocN(sizeof(BMesh), __func__);
171
172         /* allocate the memory pools for the mesh elements */
173         bm_mempool_init(bm, allocsize, params->use_toolflags);
174
175         /* allocate one flag pool that we don't get rid of. */
176         bm->use_toolflags = params->use_toolflags;
177         bm->toolflag_index = 0;
178         bm->totflags = 0;
179
180         CustomData_reset(&bm->vdata);
181         CustomData_reset(&bm->edata);
182         CustomData_reset(&bm->ldata);
183         CustomData_reset(&bm->pdata);
184
185         return bm;
186 }
187
188 /**
189  * \brief BMesh Free Mesh Data
190  *
191  *      Frees a BMesh structure.
192  *
193  * \note frees mesh, but not actual BMesh struct
194  */
195 void BM_mesh_data_free(BMesh *bm)
196 {
197         BMVert *v;
198         BMEdge *e;
199         BMLoop *l;
200         BMFace *f;
201
202         BMIter iter;
203         BMIter itersub;
204
205         const bool is_ldata_free = CustomData_bmesh_has_free(&bm->ldata);
206         const bool is_pdata_free = CustomData_bmesh_has_free(&bm->pdata);
207
208         /* Check if we have to call free, if not we can avoid a lot of looping */
209         if (CustomData_bmesh_has_free(&(bm->vdata))) {
210                 BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) {
211                         CustomData_bmesh_free_block(&(bm->vdata), &(v->head.data));
212                 }
213         }
214         if (CustomData_bmesh_has_free(&(bm->edata))) {
215                 BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
216                         CustomData_bmesh_free_block(&(bm->edata), &(e->head.data));
217                 }
218         }
219
220         if (is_ldata_free || is_pdata_free) {
221                 BM_ITER_MESH (f, &iter, bm, BM_FACES_OF_MESH) {
222                         if (is_pdata_free)
223                                 CustomData_bmesh_free_block(&(bm->pdata), &(f->head.data));
224                         if (is_ldata_free) {
225                                 BM_ITER_ELEM (l, &itersub, f, BM_LOOPS_OF_FACE) {
226                                         CustomData_bmesh_free_block(&(bm->ldata), &(l->head.data));
227                                 }
228                         }
229                 }
230         }
231
232         /* Free custom data pools, This should probably go in CustomData_free? */
233         if (bm->vdata.totlayer) BLI_mempool_destroy(bm->vdata.pool);
234         if (bm->edata.totlayer) BLI_mempool_destroy(bm->edata.pool);
235         if (bm->ldata.totlayer) BLI_mempool_destroy(bm->ldata.pool);
236         if (bm->pdata.totlayer) BLI_mempool_destroy(bm->pdata.pool);
237
238         /* free custom data */
239         CustomData_free(&bm->vdata, 0);
240         CustomData_free(&bm->edata, 0);
241         CustomData_free(&bm->ldata, 0);
242         CustomData_free(&bm->pdata, 0);
243
244         /* destroy element pools */
245         BLI_mempool_destroy(bm->vpool);
246         BLI_mempool_destroy(bm->epool);
247         BLI_mempool_destroy(bm->lpool);
248         BLI_mempool_destroy(bm->fpool);
249
250         if (bm->vtable) MEM_freeN(bm->vtable);
251         if (bm->etable) MEM_freeN(bm->etable);
252         if (bm->ftable) MEM_freeN(bm->ftable);
253
254         /* destroy flag pool */
255         BM_mesh_elem_toolflags_clear(bm);
256
257 #ifdef USE_BMESH_HOLES
258         BLI_mempool_destroy(bm->looplistpool);
259 #endif
260
261         BLI_freelistN(&bm->selected);
262
263         BMO_error_clear(bm);
264 }
265
266 /**
267  * \brief BMesh Clear Mesh
268  *
269  * Clear all data in bm
270  */
271 void BM_mesh_clear(BMesh *bm)
272 {
273         const bool use_toolflags = bm->use_toolflags;
274
275         /* free old mesh */
276         BM_mesh_data_free(bm);
277         memset(bm, 0, sizeof(BMesh));
278
279         /* allocate the memory pools for the mesh elements */
280         bm_mempool_init(bm, &bm_mesh_allocsize_default, use_toolflags);
281
282         bm->use_toolflags = use_toolflags;
283         bm->toolflag_index = 0;
284         bm->totflags = 0;
285
286         CustomData_reset(&bm->vdata);
287         CustomData_reset(&bm->edata);
288         CustomData_reset(&bm->ldata);
289         CustomData_reset(&bm->pdata);
290 }
291
292 /**
293  * \brief BMesh Free Mesh
294  *
295  *      Frees a BMesh data and its structure.
296  */
297 void BM_mesh_free(BMesh *bm)
298 {
299         BM_mesh_data_free(bm);
300
301         if (bm->py_handle) {
302                 /* keep this out of 'BM_mesh_data_free' because we want python
303                  * to be able to clear the mesh and maintain access. */
304                 bpy_bm_generic_invalidate(bm->py_handle);
305                 bm->py_handle = NULL;
306         }
307
308         MEM_freeN(bm);
309 }
310
311
312 /**
313  * Helpers for #BM_mesh_normals_update and #BM_verts_calc_normal_vcos
314  */
315
316 typedef struct BMEdgesCalcVectorsData {
317         /* Read-only data. */
318         const float (*vcos)[3];
319
320         /* Read-write data, but no need to protect it, no concurrency to fear here. */
321         float (*edgevec)[3];
322 } BMEdgesCalcVectorsData;
323
324
325 static void mesh_edges_calc_vectors_cb(void *userdata, MempoolIterData *mp_e)
326 {
327         BMEdgesCalcVectorsData *data = userdata;
328         BMEdge *e = (BMEdge *)mp_e;
329
330         if (e->l) {
331                 const float *v1_co = data->vcos ? data->vcos[BM_elem_index_get(e->v1)] : e->v1->co;
332                 const float *v2_co = data->vcos ? data->vcos[BM_elem_index_get(e->v2)] : e->v2->co;
333                 sub_v3_v3v3(data->edgevec[BM_elem_index_get(e)], v2_co, v1_co);
334                 normalize_v3(data->edgevec[BM_elem_index_get(e)]);
335         }
336         else {
337                 /* the edge vector will not be needed when the edge has no radial */
338         }
339 }
340
341 static void bm_mesh_edges_calc_vectors(BMesh *bm, float (*edgevec)[3], const float (*vcos)[3])
342 {
343         BM_mesh_elem_index_ensure(bm, BM_EDGE | (vcos ?  BM_VERT : 0));
344
345         BMEdgesCalcVectorsData data = {
346             .vcos = vcos,
347             .edgevec = edgevec
348         };
349
350         BM_iter_parallel(bm, BM_EDGES_OF_MESH, mesh_edges_calc_vectors_cb, &data, bm->totedge >= BM_OMP_LIMIT);
351 }
352
353
354 typedef struct BMVertsCalcNormalsData {
355         /* Read-only data. */
356         const float (*fnos)[3];
357         const float (*edgevec)[3];
358         const float (*vcos)[3];
359
360         /* Read-write data, protected by an atomic-based fake spinlock-like system... */
361         float (*vnos)[3];
362 } BMVertsCalcNormalsData;
363
364 static void mesh_verts_calc_normals_accum_cb(void *userdata, MempoolIterData *mp_f)
365 {
366         BMVertsCalcNormalsData *data = userdata;
367         BMFace *f = (BMFace *)mp_f;
368
369         const float *f_no = data->fnos ? data->fnos[BM_elem_index_get(f)] : f->no;
370
371         BMLoop *l_first, *l_iter;
372         l_iter = l_first = BM_FACE_FIRST_LOOP(f);
373         do {
374                 const float *e1diff, *e2diff;
375                 float dotprod;
376                 float fac;
377
378                 /* calculate the dot product of the two edges that
379                  * meet at the loop's vertex */
380                 e1diff = data->edgevec[BM_elem_index_get(l_iter->prev->e)];
381                 e2diff = data->edgevec[BM_elem_index_get(l_iter->e)];
382                 dotprod = dot_v3v3(e1diff, e2diff);
383
384                 /* edge vectors are calculated from e->v1 to e->v2, so
385                  * adjust the dot product if one but not both loops
386                  * actually runs from from e->v2 to e->v1 */
387                 if ((l_iter->prev->e->v1 == l_iter->prev->v) ^ (l_iter->e->v1 == l_iter->v)) {
388                         dotprod = -dotprod;
389                 }
390
391                 fac = saacos(-dotprod);
392
393                 /* accumulate weighted face normal into the vertex's normal */
394                 float *v_no = data->vnos ? data->vnos[BM_elem_index_get(l_iter->v)] : l_iter->v->no;
395
396                 /* This block is a lockless threadsafe madd_v3_v3fl.
397                  * It uses the first float of the vector as a sort of cheap spinlock,
398                  * assuming FLT_MAX is a safe 'illegal' value that cannot be set here otherwise.
399                  * It also assumes that collisions between threads are highly unlikely,
400                  * else performances would be quite bad here. */
401                 float virtual_lock = v_no[0];
402                 while (true) {
403                         /* This loops until following conditions are met:
404                          *   - v_no[0] has same value as virtual_lock (i.e. it did not change since last try).
405                          *   - v_no[0] was not FLT_MAX, i.e. it was not locked by another thread.
406                          */
407                         const float vl = atomic_cas_float(&v_no[0], virtual_lock, FLT_MAX);
408                         if (vl == virtual_lock && vl != FLT_MAX) {
409                                 break;
410                         }
411                         virtual_lock = vl;
412                 }
413                 BLI_assert(v_no[0] == FLT_MAX);
414                 /* Now we own that normal value, and can change it.
415                  * But first scalar of the vector must not be changed yet, it's our lock! */
416                 virtual_lock += f_no[0] * fac;
417                 v_no[1] += f_no[1] * fac;
418                 v_no[2] += f_no[2] * fac;
419                 /* Second atomic operation to 'release' our lock on that vector and set its first scalar value. */
420                 /* Note that we do not need to loop here, since we 'locked' v_no[0],
421                  * nobody should have changed it in the mean time. */
422                 virtual_lock = atomic_cas_float(&v_no[0], FLT_MAX, virtual_lock);
423                 BLI_assert(virtual_lock == FLT_MAX);
424
425         } while ((l_iter = l_iter->next) != l_first);
426 }
427
428 static void mesh_verts_calc_normals_normalize_cb(void *userdata, MempoolIterData *mp_v)
429 {
430         BMVertsCalcNormalsData *data = userdata;
431         BMVert *v = (BMVert *)mp_v;
432
433         float *v_no = data->vnos ? data->vnos[BM_elem_index_get(v)] : v->no;
434         if (UNLIKELY(normalize_v3(v_no) == 0.0f)) {
435                 const float *v_co = data->vcos ? data->vcos[BM_elem_index_get(v)] : v->co;
436                 normalize_v3_v3(v_no, v_co);
437         }
438 }
439
440 static void bm_mesh_verts_calc_normals(
441         BMesh *bm, const float (*edgevec)[3], const float (*fnos)[3],
442         const float (*vcos)[3], float (*vnos)[3])
443 {
444         BM_mesh_elem_index_ensure(bm, (BM_EDGE | BM_FACE) | ((vnos || vcos) ?  BM_VERT : 0));
445
446         BMVertsCalcNormalsData data = {
447             .fnos = fnos,
448             .edgevec = edgevec,
449             .vcos = vcos,
450             .vnos = vnos
451         };
452
453         BM_iter_parallel(bm, BM_FACES_OF_MESH, mesh_verts_calc_normals_accum_cb, &data, bm->totface >= BM_OMP_LIMIT);
454
455         /* normalize the accumulated vertex normals */
456         BM_iter_parallel(bm, BM_VERTS_OF_MESH, mesh_verts_calc_normals_normalize_cb, &data, bm->totvert >= BM_OMP_LIMIT);
457 }
458
459
460 static void mesh_faces_calc_normals_cb(void *UNUSED(userdata), MempoolIterData *mp_f)
461 {
462         BMFace *f = (BMFace *)mp_f;
463
464         BM_face_normal_update(f);
465 }
466
467
468 /**
469  * \brief BMesh Compute Normals
470  *
471  * Updates the normals of a mesh.
472  */
473 void BM_mesh_normals_update(BMesh *bm)
474 {
475         float (*edgevec)[3] = MEM_mallocN(sizeof(*edgevec) * bm->totedge, __func__);
476
477         /* Parallel mempool iteration does not allow to generate indices inline anymore... */
478         BM_mesh_elem_index_ensure(bm, (BM_EDGE | BM_FACE));
479
480         /* calculate all face normals */
481         BM_iter_parallel(bm, BM_FACES_OF_MESH, mesh_faces_calc_normals_cb, NULL, bm->totface >= BM_OMP_LIMIT);
482
483         /* Zero out vertex normals */
484         BMIter viter;
485         BMVert *v;
486         int i;
487
488         BM_ITER_MESH_INDEX (v, &viter, bm, BM_VERTS_OF_MESH, i) {
489                 BM_elem_index_set(v, i); /* set_inline */
490                 zero_v3(v->no);
491         }
492         bm->elem_index_dirty &= ~BM_VERT;
493
494         /* Compute normalized direction vectors for each edge.
495          * Directions will be used for calculating the weights of the face normals on the vertex normals.
496          */
497         bm_mesh_edges_calc_vectors(bm, edgevec, NULL);
498
499         /* Add weighted face normals to vertices, and normalize vert normals. */
500         bm_mesh_verts_calc_normals(bm, (const float(*)[3])edgevec, NULL, NULL, NULL);
501         MEM_freeN(edgevec);
502 }
503
504 /**
505  * \brief BMesh Compute Normals from/to external data.
506  *
507  * Computes the vertex normals of a mesh into vnos, using given vertex coordinates (vcos) and polygon normals (fnos).
508  */
509 void BM_verts_calc_normal_vcos(BMesh *bm, const float (*fnos)[3], const float (*vcos)[3], float (*vnos)[3])
510 {
511         float (*edgevec)[3] = MEM_mallocN(sizeof(*edgevec) * bm->totedge, __func__);
512
513         /* Compute normalized direction vectors for each edge.
514          * Directions will be used for calculating the weights of the face normals on the vertex normals.
515          */
516         bm_mesh_edges_calc_vectors(bm, edgevec, vcos);
517
518         /* Add weighted face normals to vertices, and normalize vert normals. */
519         bm_mesh_verts_calc_normals(bm, (const float(*)[3])edgevec, fnos, vcos, vnos);
520         MEM_freeN(edgevec);
521 }
522
523 /**
524  * Helpers for #BM_mesh_loop_normals_update and #BM_loops_calc_normal_vcos
525  */
526 static void bm_mesh_edges_sharp_tag(
527         BMesh *bm,
528         const float (*vnos)[3], const float (*fnos)[3], float (*r_lnos)[3],
529         const float split_angle, const bool do_sharp_edges_tag)
530 {
531         BMIter eiter;
532         BMEdge *e;
533         int i;
534
535         const bool check_angle = (split_angle < (float)M_PI);
536         const float split_angle_cos = check_angle ? cosf(split_angle) : -1.0f;
537
538         {
539                 char htype = BM_VERT | BM_LOOP;
540                 if (fnos) {
541                         htype |= BM_FACE;
542                 }
543                 BM_mesh_elem_index_ensure(bm, htype);
544         }
545
546         /* This first loop checks which edges are actually smooth, and pre-populate lnos with vnos (as if they were
547          * all smooth).
548          */
549         BM_ITER_MESH_INDEX (e, &eiter, bm, BM_EDGES_OF_MESH, i) {
550                 BMLoop *l_a, *l_b;
551
552                 BM_elem_index_set(e, i); /* set_inline */
553                 BM_elem_flag_disable(e, BM_ELEM_TAG); /* Clear tag (means edge is sharp). */
554
555                 /* An edge with only two loops, might be smooth... */
556                 if (BM_edge_loop_pair(e, &l_a, &l_b)) {
557                         bool is_angle_smooth = true;
558                         if (check_angle) {
559                                 const float *no_a = fnos ? fnos[BM_elem_index_get(l_a->f)] : l_a->f->no;
560                                 const float *no_b = fnos ? fnos[BM_elem_index_get(l_b->f)] : l_b->f->no;
561                                 is_angle_smooth = (dot_v3v3(no_a, no_b) >= split_angle_cos);
562                         }
563
564                         /* We only tag edges that are *really* smooth:
565                          * If the angle between both its polys' normals is below split_angle value,
566                          * and it is tagged as such,
567                          * and both its faces are smooth,
568                          * and both its faces have compatible (non-flipped) normals,
569                          * i.e. both loops on the same edge do not share the same vertex.
570                          */
571                         if (BM_elem_flag_test(e, BM_ELEM_SMOOTH) &&
572                             BM_elem_flag_test(l_a->f, BM_ELEM_SMOOTH) &&
573                             BM_elem_flag_test(l_b->f, BM_ELEM_SMOOTH) &&
574                             l_a->v != l_b->v)
575                         {
576                                 if (is_angle_smooth) {
577                                         const float *no;
578                                         BM_elem_flag_enable(e, BM_ELEM_TAG);
579
580                                         /* linked vertices might be fully smooth, copy their normals to loop ones. */
581                                         if (r_lnos) {
582                                                 no = vnos ? vnos[BM_elem_index_get(l_a->v)] : l_a->v->no;
583                                                 copy_v3_v3(r_lnos[BM_elem_index_get(l_a)], no);
584                                                 no = vnos ? vnos[BM_elem_index_get(l_b->v)] : l_b->v->no;
585                                                 copy_v3_v3(r_lnos[BM_elem_index_get(l_b)], no);
586                                         }
587                                 }
588                                 else if (do_sharp_edges_tag) {
589                                         /* Note that we do not care about the other sharp-edge cases (sharp poly, non-manifold edge, etc.),
590                                          * only tag edge as sharp when it is due to angle threashold. */
591                                         BM_elem_flag_disable(e, BM_ELEM_SMOOTH);
592                                 }
593                         }
594                 }
595         }
596
597         bm->elem_index_dirty &= ~BM_EDGE;
598 }
599
600 /**
601  * Check whether given loop is part of an unknown-so-far cyclic smooth fan, or not.
602  * Needed because cyclic smooth fans have no obvious 'entry point', and yet we need to walk them once, and only once.
603  */
604 bool BM_loop_check_cyclic_smooth_fan(BMLoop *l_curr)
605 {
606         BMLoop *lfan_pivot_next = l_curr;
607         BMEdge *e_next = l_curr->e;
608
609         BLI_assert(!BM_elem_flag_test(lfan_pivot_next, BM_ELEM_TAG));
610         BM_elem_flag_enable(lfan_pivot_next, BM_ELEM_TAG);
611
612         while (true) {
613                 /* Much simpler than in sibling code with basic Mesh data! */
614                 lfan_pivot_next = BM_vert_step_fan_loop(lfan_pivot_next, &e_next);
615
616                 if (!lfan_pivot_next || !BM_elem_flag_test(e_next, BM_ELEM_TAG)) {
617                         /* Sharp loop/edge, so not a cyclic smooth fan... */
618                         return false;
619                 }
620                 /* Smooth loop/edge... */
621                 else if (BM_elem_flag_test(lfan_pivot_next, BM_ELEM_TAG)) {
622                         if (lfan_pivot_next == l_curr) {
623                                 /* We walked around a whole cyclic smooth fan without finding any already-processed loop, means we can
624                                  * use initial l_curr/l_prev edge as start for this smooth fan. */
625                                 return true;
626                         }
627                         /* ... already checked in some previous looping, we can abort. */
628                         return false;
629                 }
630                 else {
631                         /* ... we can skip it in future, and keep checking the smooth fan. */
632                         BM_elem_flag_enable(lfan_pivot_next, BM_ELEM_TAG);
633                 }
634         }
635 }
636
637 /* BMesh version of BKE_mesh_normals_loop_split() in mesh_evaluate.c
638  * Will use first clnors_data array, and fallback to cd_loop_clnors_offset (use NULL and -1 to not use clnors). */
639 static void bm_mesh_loops_calc_normals(
640         BMesh *bm, const float (*vcos)[3], const float (*fnos)[3], float (*r_lnos)[3],
641         MLoopNorSpaceArray *r_lnors_spacearr, short (*clnors_data)[2], const int cd_loop_clnors_offset)
642 {
643         BMIter fiter;
644         BMFace *f_curr;
645         const bool has_clnors = clnors_data || (cd_loop_clnors_offset != -1);
646
647         MLoopNorSpaceArray _lnors_spacearr = {NULL};
648
649         /* Temp normal stack. */
650         BLI_SMALLSTACK_DECLARE(normal, float *);
651         /* Temp clnors stack. */
652         BLI_SMALLSTACK_DECLARE(clnors, short *);
653         /* Temp edge vectors stack, only used when computing lnor spacearr. */
654         BLI_Stack *edge_vectors = NULL;
655
656         {
657                 char htype = 0;
658                 if (vcos) {
659                         htype |= BM_VERT;
660                 }
661                 /* Face/Loop indices are set inline below. */
662                 BM_mesh_elem_index_ensure(bm, htype);
663         }
664
665         if (!r_lnors_spacearr && has_clnors) {
666                 /* We need to compute lnor spacearr if some custom lnor data are given to us! */
667                 r_lnors_spacearr = &_lnors_spacearr;
668         }
669         if (r_lnors_spacearr) {
670                 BKE_lnor_spacearr_init(r_lnors_spacearr, bm->totloop, MLNOR_SPACEARR_BMLOOP_PTR);
671                 edge_vectors = BLI_stack_new(sizeof(float[3]), __func__);
672         }
673
674         /* Clear all loops' tags (means none are to be skipped for now). */
675         int index_face, index_loop = 0;
676         BM_ITER_MESH_INDEX (f_curr, &fiter, bm, BM_FACES_OF_MESH, index_face) {
677                 BMLoop *l_curr, *l_first;
678
679                 BM_elem_index_set(f_curr, index_face); /* set_inline */
680
681                 l_curr = l_first = BM_FACE_FIRST_LOOP(f_curr);
682                 do {
683                         BM_elem_index_set(l_curr, index_loop++); /* set_inline */
684                         BM_elem_flag_disable(l_curr, BM_ELEM_TAG);
685                 } while ((l_curr = l_curr->next) != l_first);
686         }
687         bm->elem_index_dirty &= ~(BM_FACE | BM_LOOP);
688
689         /* We now know edges that can be smoothed (they are tagged), and edges that will be hard (they aren't).
690          * Now, time to generate the normals.
691          */
692         BM_ITER_MESH (f_curr, &fiter, bm, BM_FACES_OF_MESH) {
693                 BMLoop *l_curr, *l_first;
694
695                 l_curr = l_first = BM_FACE_FIRST_LOOP(f_curr);
696                 do {
697                         /* A smooth edge, we have to check for cyclic smooth fan case.
698                          * If we find a new, never-processed cyclic smooth fan, we can do it now using that loop/edge as
699                          * 'entry point', otherwise we can skip it. */
700                         /* Note: In theory, we could make bm_mesh_loop_check_cyclic_smooth_fan() store mlfan_pivot's in a stack,
701                          * to avoid having to fan again around the vert during actual computation of clnor & clnorspace.
702                          * However, this would complicate the code, add more memory usage, and BM_vert_step_fan_loop()
703                          * is quite cheap in term of CPU cycles, so really think it's not worth it. */
704                         if (BM_elem_flag_test(l_curr->e, BM_ELEM_TAG) &&
705                             (BM_elem_flag_test(l_curr, BM_ELEM_TAG) || !BM_loop_check_cyclic_smooth_fan(l_curr)))
706                         {
707                         }
708                         else if (!BM_elem_flag_test(l_curr->e, BM_ELEM_TAG) &&
709                                  !BM_elem_flag_test(l_curr->prev->e, BM_ELEM_TAG))
710                         {
711                                 /* Simple case (both edges around that vertex are sharp in related polygon),
712                                  * this vertex just takes its poly normal.
713                                  */
714                                 const int l_curr_index = BM_elem_index_get(l_curr);
715                                 const float *no = fnos ? fnos[BM_elem_index_get(f_curr)] : f_curr->no;
716                                 copy_v3_v3(r_lnos[l_curr_index], no);
717
718                                 /* If needed, generate this (simple!) lnor space. */
719                                 if (r_lnors_spacearr) {
720                                         float vec_curr[3], vec_prev[3];
721                                         MLoopNorSpace *lnor_space = BKE_lnor_space_create(r_lnors_spacearr);
722
723                                         {
724                                                 const BMVert *v_pivot = l_curr->v;
725                                                 const float *co_pivot = vcos ? vcos[BM_elem_index_get(v_pivot)] : v_pivot->co;
726                                                 const BMVert *v_1 = BM_edge_other_vert(l_curr->e, v_pivot);
727                                                 const float *co_1 = vcos ? vcos[BM_elem_index_get(v_1)] : v_1->co;
728                                                 const BMVert *v_2 = BM_edge_other_vert(l_curr->prev->e, v_pivot);
729                                                 const float *co_2 = vcos ? vcos[BM_elem_index_get(v_2)] : v_2->co;
730
731                                                 sub_v3_v3v3(vec_curr, co_1, co_pivot);
732                                                 normalize_v3(vec_curr);
733                                                 sub_v3_v3v3(vec_prev, co_2, co_pivot);
734                                                 normalize_v3(vec_prev);
735                                         }
736
737                                         BKE_lnor_space_define(lnor_space, r_lnos[l_curr_index], vec_curr, vec_prev, NULL);
738                                         /* We know there is only one loop in this space, no need to create a linklist in this case... */
739                                         BKE_lnor_space_add_loop(r_lnors_spacearr, lnor_space, l_curr_index, l_curr, true);
740
741                                         if (has_clnors) {
742                                                 short (*clnor)[2] = clnors_data ? &clnors_data[l_curr_index] :
743                                                                                   BM_ELEM_CD_GET_VOID_P(l_curr, cd_loop_clnors_offset);
744                                                 BKE_lnor_space_custom_data_to_normal(lnor_space, *clnor, r_lnos[l_curr_index]);
745                                         }
746                                 }
747                         }
748                         /* We *do not need* to check/tag loops as already computed!
749                          * Due to the fact a loop only links to one of its two edges, a same fan *will never be walked more than
750                          * once!*
751                          * Since we consider edges having neighbor faces with inverted (flipped) normals as sharp, we are sure that
752                          * no fan will be skipped, even only considering the case (sharp curr_edge, smooth prev_edge), and not the
753                          * alternative (smooth curr_edge, sharp prev_edge).
754                          * All this due/thanks to link between normals and loop ordering.
755                          */
756                         else {
757                                 /* We have to fan around current vertex, until we find the other non-smooth edge,
758                                  * and accumulate face normals into the vertex!
759                                  * Note in case this vertex has only one sharp edge, this is a waste because the normal is the same as
760                                  * the vertex normal, but I do not see any easy way to detect that (would need to count number
761                                  * of sharp edges per vertex, I doubt the additional memory usage would be worth it, especially as
762                                  * it should not be a common case in real-life meshes anyway).
763                                  */
764                                 BMVert *v_pivot = l_curr->v;
765                                 BMEdge *e_next;
766                                 const BMEdge *e_org = l_curr->e;
767                                 BMLoop *lfan_pivot, *lfan_pivot_next;
768                                 int lfan_pivot_index;
769                                 float lnor[3] = {0.0f, 0.0f, 0.0f};
770                                 float vec_curr[3], vec_next[3], vec_org[3];
771
772                                 /* We validate clnors data on the fly - cheapest way to do! */
773                                 int clnors_avg[2] = {0, 0};
774                                 short (*clnor_ref)[2] = NULL;
775                                 int clnors_nbr = 0;
776                                 bool clnors_invalid = false;
777
778                                 const float *co_pivot = vcos ? vcos[BM_elem_index_get(v_pivot)] : v_pivot->co;
779
780                                 MLoopNorSpace *lnor_space = r_lnors_spacearr ? BKE_lnor_space_create(r_lnors_spacearr) : NULL;
781
782                                 BLI_assert((edge_vectors == NULL) || BLI_stack_is_empty(edge_vectors));
783
784                                 lfan_pivot = l_curr;
785                                 lfan_pivot_index = BM_elem_index_get(lfan_pivot);
786                                 e_next = lfan_pivot->e;  /* Current edge here, actually! */
787
788                                 /* Only need to compute previous edge's vector once, then we can just reuse old current one! */
789                                 {
790                                         const BMVert *v_2 = BM_edge_other_vert(e_next, v_pivot);
791                                         const float *co_2 = vcos ? vcos[BM_elem_index_get(v_2)] : v_2->co;
792
793                                         sub_v3_v3v3(vec_org, co_2, co_pivot);
794                                         normalize_v3(vec_org);
795                                         copy_v3_v3(vec_curr, vec_org);
796
797                                         if (r_lnors_spacearr) {
798                                                 BLI_stack_push(edge_vectors, vec_org);
799                                         }
800                                 }
801
802                                 while (true) {
803                                         /* Much simpler than in sibling code with basic Mesh data! */
804                                         lfan_pivot_next = BM_vert_step_fan_loop(lfan_pivot, &e_next);
805                                         if (lfan_pivot_next) {
806                                                 BLI_assert(lfan_pivot_next->v == v_pivot);
807                                         }
808                                         else {
809                                                 /* next edge is non-manifold, we have to find it ourselves! */
810                                                 e_next = (lfan_pivot->e == e_next) ? lfan_pivot->prev->e : lfan_pivot->e;
811                                         }
812
813                                         /* Compute edge vector.
814                                          * NOTE: We could pre-compute those into an array, in the first iteration, instead of computing them
815                                          *       twice (or more) here. However, time gained is not worth memory and time lost,
816                                          *       given the fact that this code should not be called that much in real-life meshes...
817                                          */
818                                         {
819                                                 const BMVert *v_2 = BM_edge_other_vert(e_next, v_pivot);
820                                                 const float *co_2 = vcos ? vcos[BM_elem_index_get(v_2)] : v_2->co;
821
822                                                 sub_v3_v3v3(vec_next, co_2, co_pivot);
823                                                 normalize_v3(vec_next);
824                                         }
825
826                                         {
827                                                 /* Code similar to accumulate_vertex_normals_poly_v3. */
828                                                 /* Calculate angle between the two poly edges incident on this vertex. */
829                                                 const BMFace *f = lfan_pivot->f;
830                                                 const float fac = saacos(dot_v3v3(vec_next, vec_curr));
831                                                 const float *no = fnos ? fnos[BM_elem_index_get(f)] : f->no;
832                                                 /* Accumulate */
833                                                 madd_v3_v3fl(lnor, no, fac);
834
835                                                 if (has_clnors) {
836                                                         /* Accumulate all clnors, if they are not all equal we have to fix that! */
837                                                         short (*clnor)[2] = clnors_data ? &clnors_data[lfan_pivot_index] :
838                                                                                           BM_ELEM_CD_GET_VOID_P(lfan_pivot, cd_loop_clnors_offset);
839                                                         if (clnors_nbr) {
840                                                                 clnors_invalid |= ((*clnor_ref)[0] != (*clnor)[0] || (*clnor_ref)[1] != (*clnor)[1]);
841                                                         }
842                                                         else {
843                                                                 clnor_ref = clnor;
844                                                         }
845                                                         clnors_avg[0] += (*clnor)[0];
846                                                         clnors_avg[1] += (*clnor)[1];
847                                                         clnors_nbr++;
848                                                         /* We store here a pointer to all custom lnors processed. */
849                                                         BLI_SMALLSTACK_PUSH(clnors, (short *)*clnor);
850                                                 }
851                                         }
852
853                                         /* We store here a pointer to all loop-normals processed. */
854                                         BLI_SMALLSTACK_PUSH(normal, (float *)r_lnos[lfan_pivot_index]);
855
856                                         if (r_lnors_spacearr) {
857                                                 /* Assign current lnor space to current 'vertex' loop. */
858                                                 BKE_lnor_space_add_loop(r_lnors_spacearr, lnor_space, lfan_pivot_index, lfan_pivot, false);
859                                                 if (e_next != e_org) {
860                                                         /* We store here all edges-normalized vectors processed. */
861                                                         BLI_stack_push(edge_vectors, vec_next);
862                                                 }
863                                         }
864
865                                         if (!BM_elem_flag_test(e_next, BM_ELEM_TAG) || (e_next == e_org)) {
866                                                 /* Next edge is sharp, we have finished with this fan of faces around this vert! */
867                                                 break;
868                                         }
869
870                                         /* Copy next edge vector to current one. */
871                                         copy_v3_v3(vec_curr, vec_next);
872                                         /* Next pivot loop to current one. */
873                                         lfan_pivot = lfan_pivot_next;
874                                         lfan_pivot_index = BM_elem_index_get(lfan_pivot);
875                                 }
876
877                                 {
878                                         float lnor_len = normalize_v3(lnor);
879
880                                         /* If we are generating lnor spacearr, we can now define the one for this fan. */
881                                         if (r_lnors_spacearr) {
882                                                 if (UNLIKELY(lnor_len == 0.0f)) {
883                                                         /* Use vertex normal as fallback! */
884                                                         copy_v3_v3(lnor, r_lnos[lfan_pivot_index]);
885                                                         lnor_len = 1.0f;
886                                                 }
887
888                                                 BKE_lnor_space_define(lnor_space, lnor, vec_org, vec_next, edge_vectors);
889
890                                                 if (has_clnors) {
891                                                         if (clnors_invalid) {
892                                                                 short *clnor;
893
894                                                                 clnors_avg[0] /= clnors_nbr;
895                                                                 clnors_avg[1] /= clnors_nbr;
896                                                                 /* Fix/update all clnors of this fan with computed average value. */
897                                                                 printf("Invalid clnors in this fan!\n");
898                                                                 while ((clnor = BLI_SMALLSTACK_POP(clnors))) {
899                                                                         //print_v2("org clnor", clnor);
900                                                                         clnor[0] = (short)clnors_avg[0];
901                                                                         clnor[1] = (short)clnors_avg[1];
902                                                                 }
903                                                                 //print_v2("new clnors", clnors_avg);
904                                                         }
905                                                         else {
906                                                                 /* We still have to consume the stack! */
907                                                                 while (BLI_SMALLSTACK_POP(clnors));
908                                                         }
909                                                         BKE_lnor_space_custom_data_to_normal(lnor_space, *clnor_ref, lnor);
910                                                 }
911                                         }
912
913                                         /* In case we get a zero normal here, just use vertex normal already set! */
914                                         if (LIKELY(lnor_len != 0.0f)) {
915                                                 /* Copy back the final computed normal into all related loop-normals. */
916                                                 float *nor;
917
918                                                 while ((nor = BLI_SMALLSTACK_POP(normal))) {
919                                                         copy_v3_v3(nor, lnor);
920                                                 }
921                                         }
922                                         else {
923                                                 /* We still have to consume the stack! */
924                                                 while (BLI_SMALLSTACK_POP(normal));
925                                         }
926                                 }
927
928                                 /* Tag related vertex as sharp, to avoid fanning around it again (in case it was a smooth one). */
929                                 if (r_lnors_spacearr) {
930                                         BM_elem_flag_enable(l_curr->v, BM_ELEM_TAG);
931                                 }
932                         }
933                 } while ((l_curr = l_curr->next) != l_first);
934         }
935
936         if (r_lnors_spacearr) {
937                 BLI_stack_free(edge_vectors);
938                 if (r_lnors_spacearr == &_lnors_spacearr) {
939                         BKE_lnor_spacearr_free(r_lnors_spacearr);
940                 }
941         }
942 }
943
944 static void bm_mesh_loops_calc_normals_no_autosmooth(
945         BMesh *bm, const float (*vnos)[3], const float (*fnos)[3], float (*r_lnos)[3])
946 {
947         BMIter fiter;
948         BMFace *f_curr;
949
950         {
951                 char htype = BM_LOOP;
952                 if (vnos) {
953                         htype |= BM_VERT;
954                 }
955                 if (fnos) {
956                         htype |= BM_FACE;
957                 }
958                 BM_mesh_elem_index_ensure(bm, htype);
959         }
960
961         BM_ITER_MESH (f_curr, &fiter, bm, BM_FACES_OF_MESH) {
962                 BMLoop *l_curr, *l_first;
963                 const bool is_face_flat = !BM_elem_flag_test(f_curr, BM_ELEM_SMOOTH);
964
965                 l_curr = l_first = BM_FACE_FIRST_LOOP(f_curr);
966                 do {
967                         const float *no = is_face_flat ? (fnos ? fnos[BM_elem_index_get(f_curr)] : f_curr->no) :
968                                                          (vnos ? vnos[BM_elem_index_get(l_curr->v)] : l_curr->v->no);
969                         copy_v3_v3(r_lnos[BM_elem_index_get(l_curr)], no);
970
971                 } while ((l_curr = l_curr->next) != l_first);
972         }
973 }
974
975 #if 0  /* Unused currently */
976 /**
977  * \brief BMesh Compute Loop Normals
978  *
979  * Updates the loop normals of a mesh. Assumes vertex and face normals are valid (else call BM_mesh_normals_update()
980  * first)!
981  */
982 void BM_mesh_loop_normals_update(
983         BMesh *bm, const bool use_split_normals, const float split_angle, float (*r_lnos)[3],
984         MLoopNorSpaceArray *r_lnors_spacearr, short (*clnors_data)[2], const int cd_loop_clnors_offset)
985 {
986         const bool has_clnors = clnors_data || (cd_loop_clnors_offset != -1);
987
988         if (use_split_normals) {
989                 /* Tag smooth edges and set lnos from vnos when they might be completely smooth...
990                  * When using custom loop normals, disable the angle feature! */
991                 bm_mesh_edges_sharp_tag(bm, NULL, NULL, has_clnors ? (float)M_PI : split_angle, r_lnos);
992
993                 /* Finish computing lnos by accumulating face normals in each fan of faces defined by sharp edges. */
994                 bm_mesh_loops_calc_normals(bm, NULL, NULL, r_lnos, r_lnors_spacearr, clnors_data, cd_loop_clnors_offset);
995         }
996         else {
997                 BLI_assert(!r_lnors_spacearr);
998                 bm_mesh_loops_calc_normals_no_autosmooth(bm, NULL, NULL, r_lnos);
999         }
1000 }
1001 #endif
1002
1003 /**
1004  * \brief BMesh Compute Loop Normals from/to external data.
1005  *
1006  * Compute split normals, i.e. vertex normals associated with each poly (hence 'loop normals').
1007  * Useful to materialize sharp edges (or non-smooth faces) without actually modifying the geometry (splitting edges).
1008  */
1009 void BM_loops_calc_normal_vcos(
1010         BMesh *bm, const float (*vcos)[3], const float (*vnos)[3], const float (*fnos)[3],
1011         const bool use_split_normals, const float split_angle, float (*r_lnos)[3],
1012         MLoopNorSpaceArray *r_lnors_spacearr, short (*clnors_data)[2], const int cd_loop_clnors_offset)
1013 {
1014         const bool has_clnors = clnors_data || (cd_loop_clnors_offset != -1);
1015
1016         if (use_split_normals) {
1017                 /* Tag smooth edges and set lnos from vnos when they might be completely smooth...
1018                  * When using custom loop normals, disable the angle feature! */
1019                 bm_mesh_edges_sharp_tag(bm, vnos, fnos, r_lnos, has_clnors ? (float)M_PI : split_angle, false);
1020
1021                 /* Finish computing lnos by accumulating face normals in each fan of faces defined by sharp edges. */
1022                 bm_mesh_loops_calc_normals(bm, vcos, fnos, r_lnos, r_lnors_spacearr, clnors_data, cd_loop_clnors_offset);
1023         }
1024         else {
1025                 BLI_assert(!r_lnors_spacearr);
1026                 bm_mesh_loops_calc_normals_no_autosmooth(bm, vnos, fnos, r_lnos);
1027         }
1028 }
1029
1030 /** Define sharp edges as needed to mimic 'autosmooth' from angle threshold.
1031  *
1032  * Used when defining an empty custom loop normals data layer, to keep same shading as with autosmooth!
1033  */
1034 void BM_edges_sharp_from_angle_set(BMesh *bm, const float split_angle)
1035 {
1036         if (split_angle >= (float)M_PI) {
1037                 /* Nothing to do! */
1038                 return;
1039         }
1040
1041         bm_mesh_edges_sharp_tag(bm, NULL, NULL, NULL, split_angle, true);
1042 }
1043
1044 static void UNUSED_FUNCTION(bm_mdisps_space_set)(Object *ob, BMesh *bm, int from, int to)
1045 {
1046         /* switch multires data out of tangent space */
1047         if (CustomData_has_layer(&bm->ldata, CD_MDISPS)) {
1048                 BMEditMesh *em = BKE_editmesh_create(bm, false);
1049                 DerivedMesh *dm = CDDM_from_editbmesh(em, true, false);
1050                 MDisps *mdisps;
1051                 BMFace *f;
1052                 BMIter iter;
1053                 // int i = 0; // UNUSED
1054
1055                 multires_set_space(dm, ob, from, to);
1056
1057                 mdisps = CustomData_get_layer(&dm->loopData, CD_MDISPS);
1058
1059                 BM_ITER_MESH (f, &iter, bm, BM_FACES_OF_MESH) {
1060                         BMLoop *l;
1061                         BMIter liter;
1062                         BM_ITER_ELEM (l, &liter, f, BM_LOOPS_OF_FACE) {
1063                                 MDisps *lmd = CustomData_bmesh_get(&bm->ldata, l->head.data, CD_MDISPS);
1064
1065                                 if (!lmd->disps) {
1066                                         printf("%s: warning - 'lmd->disps' == NULL\n", __func__);
1067                                 }
1068
1069                                 if (lmd->disps && lmd->totdisp == mdisps->totdisp) {
1070                                         memcpy(lmd->disps, mdisps->disps, sizeof(float) * 3 * lmd->totdisp);
1071                                 }
1072                                 else if (mdisps->disps) {
1073                                         if (lmd->disps)
1074                                                 MEM_freeN(lmd->disps);
1075
1076                                         lmd->disps = MEM_dupallocN(mdisps->disps);
1077                                         lmd->totdisp = mdisps->totdisp;
1078                                         lmd->level = mdisps->level;
1079                                 }
1080
1081                                 mdisps++;
1082                                 // i += 1;
1083                         }
1084                 }
1085
1086                 dm->needsFree = 1;
1087                 dm->release(dm);
1088
1089                 /* setting this to NULL prevents BKE_editmesh_free from freeing it */
1090                 em->bm = NULL;
1091                 BKE_editmesh_free(em);
1092                 MEM_freeN(em);
1093         }
1094 }
1095
1096 /**
1097  * \brief BMesh Begin Edit
1098  *
1099  * Functions for setting up a mesh for editing and cleaning up after
1100  * the editing operations are done. These are called by the tools/operator
1101  * API for each time a tool is executed.
1102  */
1103 void bmesh_edit_begin(BMesh *UNUSED(bm), BMOpTypeFlag UNUSED(type_flag))
1104 {
1105         /* Most operators seem to be using BMO_OPTYPE_FLAG_UNTAN_MULTIRES to change the MDisps to
1106          * absolute space during mesh edits. With this enabled, changes to the topology
1107          * (loop cuts, edge subdivides, etc) are not reflected in the higher levels of
1108          * the mesh at all, which doesn't seem right. Turning off completely for now,
1109          * until this is shown to be better for certain types of mesh edits. */
1110 #ifdef BMOP_UNTAN_MULTIRES_ENABLED
1111         /* switch multires data out of tangent space */
1112         if ((type_flag & BMO_OPTYPE_FLAG_UNTAN_MULTIRES) && CustomData_has_layer(&bm->ldata, CD_MDISPS)) {
1113                 bmesh_mdisps_space_set(bm, MULTIRES_SPACE_TANGENT, MULTIRES_SPACE_ABSOLUTE);
1114
1115                 /* ensure correct normals, if possible */
1116                 bmesh_rationalize_normals(bm, 0);
1117                 BM_mesh_normals_update(bm);
1118         }
1119 #endif
1120 }
1121
1122 /**
1123  * \brief BMesh End Edit
1124  */
1125 void bmesh_edit_end(BMesh *bm, BMOpTypeFlag type_flag)
1126 {
1127         ListBase select_history;
1128
1129         /* BMO_OPTYPE_FLAG_UNTAN_MULTIRES disabled for now, see comment above in bmesh_edit_begin. */
1130 #ifdef BMOP_UNTAN_MULTIRES_ENABLED
1131         /* switch multires data into tangent space */
1132         if ((flag & BMO_OPTYPE_FLAG_UNTAN_MULTIRES) && CustomData_has_layer(&bm->ldata, CD_MDISPS)) {
1133                 /* set normals to their previous winding */
1134                 bmesh_rationalize_normals(bm, 1);
1135                 bmesh_mdisps_space_set(bm, MULTIRES_SPACE_ABSOLUTE, MULTIRES_SPACE_TANGENT);
1136         }
1137         else if (flag & BMO_OP_FLAG_RATIONALIZE_NORMALS) {
1138                 bmesh_rationalize_normals(bm, 1);
1139         }
1140 #endif
1141
1142         /* compute normals, clear temp flags and flush selections */
1143         if (type_flag & BMO_OPTYPE_FLAG_NORMALS_CALC) {
1144                 BM_mesh_normals_update(bm);
1145         }
1146
1147
1148         if ((type_flag & BMO_OPTYPE_FLAG_SELECT_VALIDATE) == 0) {
1149                 select_history = bm->selected;
1150                 BLI_listbase_clear(&bm->selected);
1151         }
1152
1153         if (type_flag & BMO_OPTYPE_FLAG_SELECT_FLUSH) {
1154                 BM_mesh_select_mode_flush(bm);
1155         }
1156
1157         if ((type_flag & BMO_OPTYPE_FLAG_SELECT_VALIDATE) == 0) {
1158                 bm->selected = select_history;
1159         }
1160 }
1161
1162 void BM_mesh_elem_index_ensure(BMesh *bm, const char htype)
1163 {
1164         const char htype_needed = bm->elem_index_dirty & htype;
1165
1166 #ifdef DEBUG
1167         BM_ELEM_INDEX_VALIDATE(bm, "Should Never Fail!", __func__);
1168 #endif
1169
1170         if (0 && htype_needed == 0) {
1171                 goto finally;
1172         }
1173
1174         if (htype & BM_VERT) {
1175                 if (bm->elem_index_dirty & BM_VERT) {
1176                         BMIter iter;
1177                         BMElem *ele;
1178
1179                         int index;
1180                         BM_ITER_MESH_INDEX (ele, &iter, bm, BM_VERTS_OF_MESH, index) {
1181                                 BM_elem_index_set(ele, index); /* set_ok */
1182                         }
1183                         BLI_assert(index == bm->totvert);
1184                 }
1185                 else {
1186                         // printf("%s: skipping vert index calc!\n", __func__);
1187                 }
1188         }
1189
1190         if (htype & BM_EDGE) {
1191                 if (bm->elem_index_dirty & BM_EDGE) {
1192                         BMIter iter;
1193                         BMElem *ele;
1194
1195                         int index;
1196                         BM_ITER_MESH_INDEX (ele, &iter, bm, BM_EDGES_OF_MESH, index) {
1197                                 BM_elem_index_set(ele, index); /* set_ok */
1198                         }
1199                         BLI_assert(index == bm->totedge);
1200                 }
1201                 else {
1202                         // printf("%s: skipping edge index calc!\n", __func__);
1203                 }
1204         }
1205
1206         if (htype & (BM_FACE | BM_LOOP)) {
1207                 if (bm->elem_index_dirty & (BM_FACE | BM_LOOP)) {
1208                         BMIter iter;
1209                         BMElem *ele;
1210
1211                         const bool update_face = (htype & BM_FACE) && (bm->elem_index_dirty & BM_FACE);
1212                         const bool update_loop = (htype & BM_LOOP) && (bm->elem_index_dirty & BM_LOOP);
1213
1214                         int index;
1215                         int index_loop = 0;
1216
1217                         BM_ITER_MESH_INDEX (ele, &iter, bm, BM_FACES_OF_MESH, index) {
1218                                 if (update_face) {
1219                                         BM_elem_index_set(ele, index); /* set_ok */
1220                                 }
1221
1222                                 if (update_loop) {
1223                                         BMLoop *l_iter, *l_first;
1224
1225                                         l_iter = l_first = BM_FACE_FIRST_LOOP((BMFace *)ele);
1226                                         do {
1227                                                 BM_elem_index_set(l_iter, index_loop++); /* set_ok */
1228                                         } while ((l_iter = l_iter->next) != l_first);
1229                                 }
1230                         }
1231
1232                         BLI_assert(index == bm->totface);
1233                         if (update_loop) {
1234                                 BLI_assert(index_loop == bm->totloop);
1235                         }
1236                 }
1237                 else {
1238                         // printf("%s: skipping face/loop index calc!\n", __func__);
1239                 }
1240         }
1241
1242 finally:
1243         bm->elem_index_dirty &= ~htype;
1244 }
1245
1246
1247 /**
1248  * Array checking/setting macros
1249  *
1250  * Currently vert/edge/loop/face index data is being abused, in a few areas of the code.
1251  *
1252  * To avoid correcting them afterwards, set 'bm->elem_index_dirty' however its possible
1253  * this flag is set incorrectly which could crash blender.
1254  *
1255  * These functions ensure its correct and are called more often in debug mode.
1256  */
1257
1258 void BM_mesh_elem_index_validate(
1259         BMesh *bm, const char *location, const char *func,
1260         const char *msg_a, const char *msg_b)
1261 {
1262         const char iter_types[3] = {BM_VERTS_OF_MESH,
1263                                     BM_EDGES_OF_MESH,
1264                                     BM_FACES_OF_MESH};
1265
1266         const char flag_types[3] = {BM_VERT, BM_EDGE, BM_FACE};
1267         const char *type_names[3] = {"vert", "edge", "face"};
1268
1269         BMIter iter;
1270         BMElem *ele;
1271         int i;
1272         bool is_any_error = 0;
1273
1274         for (i = 0; i < 3; i++) {
1275                 const bool is_dirty = (flag_types[i] & bm->elem_index_dirty) != 0;
1276                 int index = 0;
1277                 bool is_error = false;
1278                 int err_val = 0;
1279                 int err_idx = 0;
1280
1281                 BM_ITER_MESH (ele, &iter, bm, iter_types[i]) {
1282                         if (!is_dirty) {
1283                                 if (BM_elem_index_get(ele) != index) {
1284                                         err_val = BM_elem_index_get(ele);
1285                                         err_idx = index;
1286                                         is_error = true;
1287                                 }
1288                         }
1289
1290                         BM_elem_index_set(ele, index); /* set_ok */
1291                         index++;
1292                 }
1293
1294                 if ((is_error == true) && (is_dirty == false)) {
1295                         is_any_error = true;
1296                         fprintf(stderr,
1297                                 "Invalid Index: at %s, %s, %s[%d] invalid index %d, '%s', '%s'\n",
1298                                 location, func, type_names[i], err_idx, err_val, msg_a, msg_b);
1299                 }
1300                 else if ((is_error == false) && (is_dirty == true)) {
1301
1302 #if 0       /* mostly annoying */
1303
1304                         /* dirty may have been incorrectly set */
1305                         fprintf(stderr,
1306                                 "Invalid Dirty: at %s, %s (%s), dirty flag was set but all index values are correct, '%s', '%s'\n",
1307                                 location, func, type_names[i], msg_a, msg_b);
1308 #endif
1309                 }
1310         }
1311
1312 #if 0 /* mostly annoying, even in debug mode */
1313 #ifdef DEBUG
1314         if (is_any_error == 0) {
1315                 fprintf(stderr,
1316                         "Valid Index Success: at %s, %s, '%s', '%s'\n",
1317                         location, func, msg_a, msg_b);
1318         }
1319 #endif
1320 #endif
1321         (void) is_any_error; /* shut up the compiler */
1322
1323 }
1324
1325 /* debug check only - no need to optimize */
1326 #ifndef NDEBUG
1327 bool BM_mesh_elem_table_check(BMesh *bm)
1328 {
1329         BMIter iter;
1330         BMElem *ele;
1331         int i;
1332
1333         if (bm->vtable && ((bm->elem_table_dirty & BM_VERT) == 0)) {
1334                 BM_ITER_MESH_INDEX (ele, &iter, bm, BM_VERTS_OF_MESH, i) {
1335                         if (ele != (BMElem *)bm->vtable[i]) {
1336                                 return false;
1337                         }
1338                 }
1339         }
1340
1341         if (bm->etable && ((bm->elem_table_dirty & BM_EDGE) == 0)) {
1342                 BM_ITER_MESH_INDEX (ele, &iter, bm, BM_EDGES_OF_MESH, i) {
1343                         if (ele != (BMElem *)bm->etable[i]) {
1344                                 return false;
1345                         }
1346                 }
1347         }
1348
1349         if (bm->ftable && ((bm->elem_table_dirty & BM_FACE) == 0)) {
1350                 BM_ITER_MESH_INDEX (ele, &iter, bm, BM_FACES_OF_MESH, i) {
1351                         if (ele != (BMElem *)bm->ftable[i]) {
1352                                 return false;
1353                         }
1354                 }
1355         }
1356
1357         return true;
1358 }
1359 #endif
1360
1361
1362
1363 void BM_mesh_elem_table_ensure(BMesh *bm, const char htype)
1364 {
1365         /* assume if the array is non-null then its valid and no need to recalc */
1366         const char htype_needed = (((bm->vtable && ((bm->elem_table_dirty & BM_VERT) == 0)) ? 0 : BM_VERT) |
1367                                    ((bm->etable && ((bm->elem_table_dirty & BM_EDGE) == 0)) ? 0 : BM_EDGE) |
1368                                    ((bm->ftable && ((bm->elem_table_dirty & BM_FACE) == 0)) ? 0 : BM_FACE)) & htype;
1369
1370         BLI_assert((htype & ~BM_ALL_NOLOOP) == 0);
1371
1372         /* in debug mode double check we didn't need to recalculate */
1373         BLI_assert(BM_mesh_elem_table_check(bm) == true);
1374
1375         if (htype_needed == 0) {
1376                 goto finally;
1377         }
1378
1379         if (htype_needed & BM_VERT) {
1380                 if (bm->vtable && bm->totvert <= bm->vtable_tot && bm->totvert * 2 >= bm->vtable_tot) {
1381                         /* pass (re-use the array) */
1382                 }
1383                 else {
1384                         if (bm->vtable)
1385                                 MEM_freeN(bm->vtable);
1386                         bm->vtable = MEM_mallocN(sizeof(void **) * bm->totvert, "bm->vtable");
1387                         bm->vtable_tot = bm->totvert;
1388                 }
1389         }
1390         if (htype_needed & BM_EDGE) {
1391                 if (bm->etable && bm->totedge <= bm->etable_tot && bm->totedge * 2 >= bm->etable_tot) {
1392                         /* pass (re-use the array) */
1393                 }
1394                 else {
1395                         if (bm->etable)
1396                                 MEM_freeN(bm->etable);
1397                         bm->etable = MEM_mallocN(sizeof(void **) * bm->totedge, "bm->etable");
1398                         bm->etable_tot = bm->totedge;
1399                 }
1400         }
1401         if (htype_needed & BM_FACE) {
1402                 if (bm->ftable && bm->totface <= bm->ftable_tot && bm->totface * 2 >= bm->ftable_tot) {
1403                         /* pass (re-use the array) */
1404                 }
1405                 else {
1406                         if (bm->ftable)
1407                                 MEM_freeN(bm->ftable);
1408                         bm->ftable = MEM_mallocN(sizeof(void **) * bm->totface, "bm->ftable");
1409                         bm->ftable_tot = bm->totface;
1410                 }
1411         }
1412
1413         if (htype_needed & BM_VERT) {
1414                 BM_iter_as_array(bm, BM_VERTS_OF_MESH, NULL, (void **)bm->vtable, bm->totvert);
1415         }
1416
1417         if (htype_needed & BM_EDGE) {
1418                 BM_iter_as_array(bm, BM_EDGES_OF_MESH, NULL, (void **)bm->etable, bm->totedge);
1419         }
1420
1421         if (htype_needed & BM_FACE) {
1422                 BM_iter_as_array(bm, BM_FACES_OF_MESH, NULL, (void **)bm->ftable, bm->totface);
1423         }
1424
1425 finally:
1426         /* Only clear dirty flags when all the pointers and data are actually valid.
1427          * This prevents possible threading issues when dirty flag check failed but
1428          * data wasn't ready still.
1429          */
1430         bm->elem_table_dirty &= ~htype_needed;
1431 }
1432
1433 /* use BM_mesh_elem_table_ensure where possible to avoid full rebuild */
1434 void BM_mesh_elem_table_init(BMesh *bm, const char htype)
1435 {
1436         BLI_assert((htype & ~BM_ALL_NOLOOP) == 0);
1437
1438         /* force recalc */
1439         BM_mesh_elem_table_free(bm, BM_ALL_NOLOOP);
1440         BM_mesh_elem_table_ensure(bm, htype);
1441 }
1442
1443 void BM_mesh_elem_table_free(BMesh *bm, const char htype)
1444 {
1445         if (htype & BM_VERT) {
1446                 MEM_SAFE_FREE(bm->vtable);
1447         }
1448
1449         if (htype & BM_EDGE) {
1450                 MEM_SAFE_FREE(bm->etable);
1451         }
1452
1453         if (htype & BM_FACE) {
1454                 MEM_SAFE_FREE(bm->ftable);
1455         }
1456 }
1457
1458 BMVert *BM_vert_at_index(BMesh *bm, const int index)
1459 {
1460         BLI_assert((index >= 0) && (index < bm->totvert));
1461         BLI_assert((bm->elem_table_dirty & BM_VERT) == 0);
1462         return bm->vtable[index];
1463 }
1464
1465 BMEdge *BM_edge_at_index(BMesh *bm, const int index)
1466 {
1467         BLI_assert((index >= 0) && (index < bm->totedge));
1468         BLI_assert((bm->elem_table_dirty & BM_EDGE) == 0);
1469         return bm->etable[index];
1470 }
1471
1472 BMFace *BM_face_at_index(BMesh *bm, const int index)
1473 {
1474         BLI_assert((index >= 0) && (index < bm->totface));
1475         BLI_assert((bm->elem_table_dirty & BM_FACE) == 0);
1476         return bm->ftable[index];
1477 }
1478
1479
1480 BMVert *BM_vert_at_index_find(BMesh *bm, const int index)
1481 {
1482         return BLI_mempool_findelem(bm->vpool, index);
1483 }
1484
1485 BMEdge *BM_edge_at_index_find(BMesh *bm, const int index)
1486 {
1487         return BLI_mempool_findelem(bm->epool, index);
1488 }
1489
1490 BMFace *BM_face_at_index_find(BMesh *bm, const int index)
1491 {
1492         return BLI_mempool_findelem(bm->fpool, index);
1493 }
1494
1495 /**
1496  * Use lookup table when available, else use slower find functions.
1497  *
1498  * \note Try to use #BM_mesh_elem_table_ensure instead.
1499  */
1500 BMVert *BM_vert_at_index_find_or_table(BMesh *bm, const int index)
1501 {
1502         if ((bm->elem_table_dirty & BM_VERT) == 0) {
1503                 return (index < bm->totvert) ? bm->vtable[index] : NULL;
1504         }
1505         else {
1506                 return BM_vert_at_index_find(bm, index);
1507         }
1508 }
1509
1510 BMEdge *BM_edge_at_index_find_or_table(BMesh *bm, const int index)
1511 {
1512         if ((bm->elem_table_dirty & BM_EDGE) == 0) {
1513                 return (index < bm->totedge) ? bm->etable[index] : NULL;
1514         }
1515         else {
1516                 return BM_edge_at_index_find(bm, index);
1517         }
1518 }
1519
1520 BMFace *BM_face_at_index_find_or_table(BMesh *bm, const int index)
1521 {
1522         if ((bm->elem_table_dirty & BM_FACE) == 0) {
1523                 return (index < bm->totface) ? bm->ftable[index] : NULL;
1524         }
1525         else {
1526                 return BM_face_at_index_find(bm, index);
1527         }
1528 }
1529
1530
1531 /**
1532  * Return the amount of element of type 'type' in a given bmesh.
1533  */
1534 int BM_mesh_elem_count(BMesh *bm, const char htype)
1535 {
1536         BLI_assert((htype & ~BM_ALL_NOLOOP) == 0);
1537
1538         switch (htype) {
1539                 case BM_VERT: return bm->totvert;
1540                 case BM_EDGE: return bm->totedge;
1541                 case BM_FACE: return bm->totface;
1542                 default:
1543                 {
1544                         BLI_assert(0);
1545                         return 0;
1546                 }
1547         }
1548 }
1549
1550
1551 /**
1552  * Remaps the vertices, edges and/or faces of the bmesh as indicated by vert/edge/face_idx arrays
1553  * (xxx_idx[org_index] = new_index).
1554  *
1555  * A NULL array means no changes.
1556  *
1557  * Note: - Does not mess with indices, just sets elem_index_dirty flag.
1558  *       - For verts/edges/faces only (as loops must remain "ordered" and "aligned"
1559  *         on a per-face basis...).
1560  *
1561  * WARNING: Be careful if you keep pointers to affected BM elements, or arrays, when using this func!
1562  */
1563 void BM_mesh_remap(
1564         BMesh *bm,
1565         const uint *vert_idx,
1566         const uint *edge_idx,
1567         const uint *face_idx)
1568 {
1569         /* Mapping old to new pointers. */
1570         GHash *vptr_map = NULL, *eptr_map = NULL, *fptr_map = NULL;
1571         BMIter iter, iterl;
1572         BMVert *ve;
1573         BMEdge *ed;
1574         BMFace *fa;
1575         BMLoop *lo;
1576
1577         if (!(vert_idx || edge_idx || face_idx))
1578                 return;
1579
1580         BM_mesh_elem_table_ensure(
1581                 bm,
1582                 (vert_idx ? BM_VERT : 0) |
1583                 (edge_idx ? BM_EDGE : 0) |
1584                 (face_idx ? BM_FACE : 0));
1585
1586         /* Remap Verts */
1587         if (vert_idx) {
1588                 BMVert **verts_pool, *verts_copy, **vep;
1589                 int i, totvert = bm->totvert;
1590                 const uint *new_idx;
1591                 /* Special case: Python uses custom - data layers to hold PyObject references.
1592                  * These have to be kept in - place, else the PyObject's we point to, wont point back to us. */
1593                 const int cd_vert_pyptr  = CustomData_get_offset(&bm->vdata, CD_BM_ELEM_PYPTR);
1594
1595                 /* Init the old-to-new vert pointers mapping */
1596                 vptr_map = BLI_ghash_ptr_new_ex("BM_mesh_remap vert pointers mapping", bm->totvert);
1597
1598                 /* Make a copy of all vertices. */
1599                 verts_pool = bm->vtable;
1600                 verts_copy = MEM_mallocN(sizeof(BMVert) * totvert, "BM_mesh_remap verts copy");
1601                 void **pyptrs = (cd_vert_pyptr != -1) ? MEM_mallocN(sizeof(void *) * totvert, __func__) : NULL;
1602                 for (i = totvert, ve = verts_copy + totvert - 1, vep = verts_pool + totvert - 1; i--; ve--, vep--) {
1603                         *ve = **vep;
1604 /*                      printf("*vep: %p, verts_pool[%d]: %p\n", *vep, i, verts_pool[i]);*/
1605                         if (cd_vert_pyptr != -1) {
1606                                 void **pyptr = BM_ELEM_CD_GET_VOID_P(((BMElem *)ve), cd_vert_pyptr);
1607                                 pyptrs[i] = *pyptr;
1608                         }
1609                 }
1610
1611                 /* Copy back verts to their new place, and update old2new pointers mapping. */
1612                 new_idx = vert_idx + totvert - 1;
1613                 ve = verts_copy + totvert - 1;
1614                 vep = verts_pool + totvert - 1; /* old, org pointer */
1615                 for (i = totvert; i--; new_idx--, ve--, vep--) {
1616                         BMVert *new_vep = verts_pool[*new_idx];
1617                         *new_vep = *ve;
1618 /*                      printf("mapping vert from %d to %d (%p/%p to %p)\n", i, *new_idx, *vep, verts_pool[i], new_vep);*/
1619                         BLI_ghash_insert(vptr_map, *vep, new_vep);
1620                         if (cd_vert_pyptr != -1) {
1621                                 void **pyptr = BM_ELEM_CD_GET_VOID_P(((BMElem *)new_vep), cd_vert_pyptr);
1622                                 *pyptr = pyptrs[*new_idx];
1623                         }
1624                 }
1625                 bm->elem_index_dirty |= BM_VERT;
1626                 bm->elem_table_dirty |= BM_VERT;
1627
1628                 MEM_freeN(verts_copy);
1629                 if (pyptrs) {
1630                         MEM_freeN(pyptrs);
1631                 }
1632         }
1633
1634         /* Remap Edges */
1635         if (edge_idx) {
1636                 BMEdge **edges_pool, *edges_copy, **edp;
1637                 int i, totedge = bm->totedge;
1638                 const uint *new_idx;
1639                 /* Special case: Python uses custom - data layers to hold PyObject references.
1640                  * These have to be kept in - place, else the PyObject's we point to, wont point back to us. */
1641                 const int cd_edge_pyptr  = CustomData_get_offset(&bm->edata, CD_BM_ELEM_PYPTR);
1642
1643                 /* Init the old-to-new vert pointers mapping */
1644                 eptr_map = BLI_ghash_ptr_new_ex("BM_mesh_remap edge pointers mapping", bm->totedge);
1645
1646                 /* Make a copy of all vertices. */
1647                 edges_pool = bm->etable;
1648                 edges_copy = MEM_mallocN(sizeof(BMEdge) * totedge, "BM_mesh_remap edges copy");
1649                 void **pyptrs = (cd_edge_pyptr != -1) ? MEM_mallocN(sizeof(void *) * totedge, __func__) : NULL;
1650                 for (i = totedge, ed = edges_copy + totedge - 1, edp = edges_pool + totedge - 1; i--; ed--, edp--) {
1651                         *ed = **edp;
1652                         if (cd_edge_pyptr != -1) {
1653                                 void **pyptr = BM_ELEM_CD_GET_VOID_P(((BMElem *)ed), cd_edge_pyptr);
1654                                 pyptrs[i] = *pyptr;
1655                         }
1656                 }
1657
1658                 /* Copy back verts to their new place, and update old2new pointers mapping. */
1659                 new_idx = edge_idx + totedge - 1;
1660                 ed = edges_copy + totedge - 1;
1661                 edp = edges_pool + totedge - 1; /* old, org pointer */
1662                 for (i = totedge; i--; new_idx--, ed--, edp--) {
1663                         BMEdge *new_edp = edges_pool[*new_idx];
1664                         *new_edp = *ed;
1665                         BLI_ghash_insert(eptr_map, *edp, new_edp);
1666 /*                      printf("mapping edge from %d to %d (%p/%p to %p)\n", i, *new_idx, *edp, edges_pool[i], new_edp);*/
1667                         if (cd_edge_pyptr != -1) {
1668                                 void **pyptr = BM_ELEM_CD_GET_VOID_P(((BMElem *)new_edp), cd_edge_pyptr);
1669                                 *pyptr = pyptrs[*new_idx];
1670                         }
1671                 }
1672                 bm->elem_index_dirty |= BM_EDGE;
1673                 bm->elem_table_dirty |= BM_EDGE;
1674
1675                 MEM_freeN(edges_copy);
1676                 if (pyptrs) {
1677                         MEM_freeN(pyptrs);
1678                 }
1679         }
1680
1681         /* Remap Faces */
1682         if (face_idx) {
1683                 BMFace **faces_pool, *faces_copy, **fap;
1684                 int i, totface = bm->totface;
1685                 const uint *new_idx;
1686                 /* Special case: Python uses custom - data layers to hold PyObject references.
1687                  * These have to be kept in - place, else the PyObject's we point to, wont point back to us. */
1688                 const int cd_poly_pyptr  = CustomData_get_offset(&bm->pdata, CD_BM_ELEM_PYPTR);
1689
1690                 /* Init the old-to-new vert pointers mapping */
1691                 fptr_map = BLI_ghash_ptr_new_ex("BM_mesh_remap face pointers mapping", bm->totface);
1692
1693                 /* Make a copy of all vertices. */
1694                 faces_pool = bm->ftable;
1695                 faces_copy = MEM_mallocN(sizeof(BMFace) * totface, "BM_mesh_remap faces copy");
1696                 void **pyptrs = (cd_poly_pyptr != -1) ? MEM_mallocN(sizeof(void *) * totface, __func__) : NULL;
1697                 for (i = totface, fa = faces_copy + totface - 1, fap = faces_pool + totface - 1; i--; fa--, fap--) {
1698                         *fa = **fap;
1699                         if (cd_poly_pyptr != -1) {
1700                                 void **pyptr = BM_ELEM_CD_GET_VOID_P(((BMElem *)fa), cd_poly_pyptr);
1701                                 pyptrs[i] = *pyptr;
1702                         }
1703                 }
1704
1705                 /* Copy back verts to their new place, and update old2new pointers mapping. */
1706                 new_idx = face_idx + totface - 1;
1707                 fa = faces_copy + totface - 1;
1708                 fap = faces_pool + totface - 1; /* old, org pointer */
1709                 for (i = totface; i--; new_idx--, fa--, fap--) {
1710                         BMFace *new_fap = faces_pool[*new_idx];
1711                         *new_fap = *fa;
1712                         BLI_ghash_insert(fptr_map, *fap, new_fap);
1713                         if (cd_poly_pyptr != -1) {
1714                                 void **pyptr = BM_ELEM_CD_GET_VOID_P(((BMElem *)new_fap), cd_poly_pyptr);
1715                                 *pyptr = pyptrs[*new_idx];
1716                         }
1717                 }
1718
1719                 bm->elem_index_dirty |= BM_FACE | BM_LOOP;
1720                 bm->elem_table_dirty |= BM_FACE;
1721
1722                 MEM_freeN(faces_copy);
1723                 if (pyptrs) {
1724                         MEM_freeN(pyptrs);
1725                 }
1726         }
1727
1728         /* And now, fix all vertices/edges/faces/loops pointers! */
1729         /* Verts' pointers, only edge pointers... */
1730         if (eptr_map) {
1731                 BM_ITER_MESH (ve, &iter, bm, BM_VERTS_OF_MESH) {
1732 /*                      printf("Vert e: %p -> %p\n", ve->e, BLI_ghash_lookup(eptr_map, ve->e));*/
1733                         if (ve->e) {
1734                                 ve->e = BLI_ghash_lookup(eptr_map, ve->e);
1735                                 BLI_assert(ve->e);
1736                         }
1737                 }
1738         }
1739
1740         /* Edges' pointers, only vert pointers (as we don't mess with loops!), and - ack! - edge pointers,
1741          * as we have to handle disklinks... */
1742         if (vptr_map || eptr_map) {
1743                 BM_ITER_MESH (ed, &iter, bm, BM_EDGES_OF_MESH) {
1744                         if (vptr_map) {
1745 /*                              printf("Edge v1: %p -> %p\n", ed->v1, BLI_ghash_lookup(vptr_map, ed->v1));*/
1746 /*                              printf("Edge v2: %p -> %p\n", ed->v2, BLI_ghash_lookup(vptr_map, ed->v2));*/
1747                                 ed->v1 = BLI_ghash_lookup(vptr_map, ed->v1);
1748                                 ed->v2 = BLI_ghash_lookup(vptr_map, ed->v2);
1749                                 BLI_assert(ed->v1);
1750                                 BLI_assert(ed->v2);
1751                         }
1752                         if (eptr_map) {
1753 /*                              printf("Edge v1_disk_link prev: %p -> %p\n", ed->v1_disk_link.prev,*/
1754 /*                                     BLI_ghash_lookup(eptr_map, ed->v1_disk_link.prev));*/
1755 /*                              printf("Edge v1_disk_link next: %p -> %p\n", ed->v1_disk_link.next,*/
1756 /*                                     BLI_ghash_lookup(eptr_map, ed->v1_disk_link.next));*/
1757 /*                              printf("Edge v2_disk_link prev: %p -> %p\n", ed->v2_disk_link.prev,*/
1758 /*                                     BLI_ghash_lookup(eptr_map, ed->v2_disk_link.prev));*/
1759 /*                              printf("Edge v2_disk_link next: %p -> %p\n", ed->v2_disk_link.next,*/
1760 /*                                     BLI_ghash_lookup(eptr_map, ed->v2_disk_link.next));*/
1761                                 ed->v1_disk_link.prev = BLI_ghash_lookup(eptr_map, ed->v1_disk_link.prev);
1762                                 ed->v1_disk_link.next = BLI_ghash_lookup(eptr_map, ed->v1_disk_link.next);
1763                                 ed->v2_disk_link.prev = BLI_ghash_lookup(eptr_map, ed->v2_disk_link.prev);
1764                                 ed->v2_disk_link.next = BLI_ghash_lookup(eptr_map, ed->v2_disk_link.next);
1765                                 BLI_assert(ed->v1_disk_link.prev);
1766                                 BLI_assert(ed->v1_disk_link.next);
1767                                 BLI_assert(ed->v2_disk_link.prev);
1768                                 BLI_assert(ed->v2_disk_link.next);
1769                         }
1770                 }
1771         }
1772
1773         /* Faces' pointers (loops, in fact), always needed... */
1774         BM_ITER_MESH (fa, &iter, bm, BM_FACES_OF_MESH) {
1775                 BM_ITER_ELEM (lo, &iterl, fa, BM_LOOPS_OF_FACE) {
1776                         if (vptr_map) {
1777 /*                              printf("Loop v: %p -> %p\n", lo->v, BLI_ghash_lookup(vptr_map, lo->v));*/
1778                                 lo->v = BLI_ghash_lookup(vptr_map, lo->v);
1779                                 BLI_assert(lo->v);
1780                         }
1781                         if (eptr_map) {
1782 /*                              printf("Loop e: %p -> %p\n", lo->e, BLI_ghash_lookup(eptr_map, lo->e));*/
1783                                 lo->e = BLI_ghash_lookup(eptr_map, lo->e);
1784                                 BLI_assert(lo->e);
1785                         }
1786                         if (fptr_map) {
1787 /*                              printf("Loop f: %p -> %p\n", lo->f, BLI_ghash_lookup(fptr_map, lo->f));*/
1788                                 lo->f = BLI_ghash_lookup(fptr_map, lo->f);
1789                                 BLI_assert(lo->f);
1790                         }
1791                 }
1792         }
1793
1794         /* Selection history */
1795         {
1796                 BMEditSelection *ese;
1797                 for (ese = bm->selected.first; ese; ese = ese->next) {
1798                         switch (ese->htype) {
1799                                 case BM_VERT:
1800                                         if (vptr_map) {
1801                                                 ese->ele = BLI_ghash_lookup(vptr_map, ese->ele);
1802                                                 BLI_assert(ese->ele);
1803                                         }
1804                                         break;
1805                                 case BM_EDGE:
1806                                         if (eptr_map) {
1807                                                 ese->ele = BLI_ghash_lookup(eptr_map, ese->ele);
1808                                                 BLI_assert(ese->ele);
1809                                         }
1810                                         break;
1811                                 case BM_FACE:
1812                                         if (fptr_map) {
1813                                                 ese->ele = BLI_ghash_lookup(fptr_map, ese->ele);
1814                                                 BLI_assert(ese->ele);
1815                                         }
1816                                         break;
1817                         }
1818                 }
1819         }
1820
1821         if (fptr_map) {
1822                 if (bm->act_face) {
1823                         bm->act_face = BLI_ghash_lookup(fptr_map, bm->act_face);
1824                         BLI_assert(bm->act_face);
1825                 }
1826         }
1827
1828         if (vptr_map)
1829                 BLI_ghash_free(vptr_map, NULL, NULL);
1830         if (eptr_map)
1831                 BLI_ghash_free(eptr_map, NULL, NULL);
1832         if (fptr_map)
1833                 BLI_ghash_free(fptr_map, NULL, NULL);
1834 }
1835
1836 /**
1837  * Use new memory pools for this mesh.
1838  *
1839  * \note needed for re-sizing elements (adding/removing tool flags)
1840  * but could also be used for packing fragmented bmeshes.
1841  */
1842 void BM_mesh_rebuild(
1843         BMesh *bm, const struct BMeshCreateParams *params,
1844         BLI_mempool *vpool_dst, BLI_mempool *epool_dst, BLI_mempool *lpool_dst, BLI_mempool *fpool_dst)
1845 {
1846         const char remap =
1847                 (vpool_dst ? BM_VERT : 0) |
1848                 (epool_dst ? BM_EDGE : 0) |
1849                 (lpool_dst ? BM_LOOP : 0) |
1850                 (fpool_dst ? BM_FACE : 0);
1851
1852         BMVert **vtable_dst = (remap & BM_VERT) ? MEM_mallocN(bm->totvert * sizeof(BMVert *), __func__) : NULL;
1853         BMEdge **etable_dst = (remap & BM_EDGE) ? MEM_mallocN(bm->totedge * sizeof(BMEdge *), __func__) : NULL;
1854         BMLoop **ltable_dst = (remap & BM_LOOP) ? MEM_mallocN(bm->totloop * sizeof(BMLoop *), __func__) : NULL;
1855         BMFace **ftable_dst = (remap & BM_FACE) ? MEM_mallocN(bm->totface * sizeof(BMFace *), __func__) : NULL;
1856
1857         const bool use_toolflags = params->use_toolflags;
1858
1859         if (remap & BM_VERT) {
1860                 BMIter iter;
1861                 int index;
1862                 BMVert *v_src;
1863                 BM_ITER_MESH_INDEX (v_src, &iter, bm, BM_VERTS_OF_MESH, index) {
1864                         BMVert *v_dst = BLI_mempool_alloc(vpool_dst);
1865                         memcpy(v_dst, v_src, sizeof(BMVert));
1866                         if (use_toolflags) {
1867                                 ((BMVert_OFlag *)v_dst)->oflags = bm->vtoolflagpool ? BLI_mempool_calloc(bm->vtoolflagpool) : NULL;
1868                         }
1869
1870                         vtable_dst[index] = v_dst;
1871                         BM_elem_index_set(v_src, index);  /* set_ok */
1872                 }
1873         }
1874
1875         if (remap & BM_EDGE) {
1876                 BMIter iter;
1877                 int index;
1878                 BMEdge *e_src;
1879                 BM_ITER_MESH_INDEX (e_src, &iter, bm, BM_EDGES_OF_MESH, index) {
1880                         BMEdge *e_dst = BLI_mempool_alloc(epool_dst);
1881                         memcpy(e_dst, e_src, sizeof(BMEdge));
1882                         if (use_toolflags) {
1883                                 ((BMEdge_OFlag *)e_dst)->oflags = bm->etoolflagpool ? BLI_mempool_calloc(bm->etoolflagpool) : NULL;
1884                         }
1885
1886                         etable_dst[index] = e_dst;
1887                         BM_elem_index_set(e_src, index);  /* set_ok */
1888                 }
1889         }
1890
1891         if (remap & (BM_LOOP | BM_FACE)) {
1892                 BMIter iter;
1893                 int index, index_loop = 0;
1894                 BMFace *f_src;
1895                 BM_ITER_MESH_INDEX (f_src, &iter, bm, BM_FACES_OF_MESH, index) {
1896
1897                         if (remap & BM_FACE) {
1898                                 BMFace *f_dst = BLI_mempool_alloc(fpool_dst);
1899                                 memcpy(f_dst, f_src, sizeof(BMFace));
1900                                 if (use_toolflags) {
1901                                         ((BMFace_OFlag *)f_dst)->oflags = bm->ftoolflagpool ? BLI_mempool_calloc(bm->ftoolflagpool) : NULL;
1902                                 }
1903
1904                                 ftable_dst[index] = f_dst;
1905                                 BM_elem_index_set(f_src, index);  /* set_ok */
1906                         }
1907
1908                         /* handle loops */
1909                         if (remap & BM_LOOP) {
1910                                 BMLoop *l_iter_src, *l_first_src;
1911                                 l_iter_src = l_first_src = BM_FACE_FIRST_LOOP((BMFace *)f_src);
1912                                 do {
1913                                         BMLoop *l_dst = BLI_mempool_alloc(lpool_dst);
1914                                         memcpy(l_dst, l_iter_src, sizeof(BMLoop));
1915                                         ltable_dst[index_loop] = l_dst;
1916                                         BM_elem_index_set(l_iter_src, index_loop++); /* set_ok */
1917                                 } while ((l_iter_src = l_iter_src->next) != l_first_src);
1918                         }
1919                 }
1920         }
1921
1922 #define MAP_VERT(ele) vtable_dst[BM_elem_index_get(ele)]
1923 #define MAP_EDGE(ele) etable_dst[BM_elem_index_get(ele)]
1924 #define MAP_LOOP(ele) ltable_dst[BM_elem_index_get(ele)]
1925 #define MAP_FACE(ele) ftable_dst[BM_elem_index_get(ele)]
1926
1927 #define REMAP_VERT(ele) { if (remap & BM_VERT) { ele = MAP_VERT(ele); }} ((void)0)
1928 #define REMAP_EDGE(ele) { if (remap & BM_EDGE) { ele = MAP_EDGE(ele); }} ((void)0)
1929 #define REMAP_LOOP(ele) { if (remap & BM_LOOP) { ele = MAP_LOOP(ele); }} ((void)0)
1930 #define REMAP_FACE(ele) { if (remap & BM_FACE) { ele = MAP_FACE(ele); }} ((void)0)
1931
1932         /* verts */
1933         {
1934                 for (int i = 0; i < bm->totvert; i++) {
1935                         BMVert *v = vtable_dst[i];
1936                         if (v->e) {
1937                                 REMAP_EDGE(v->e);
1938                         }
1939                 }
1940         }
1941
1942         /* edges */
1943         {
1944                 for (int i = 0; i < bm->totedge; i++) {
1945                         BMEdge *e = etable_dst[i];
1946                         REMAP_VERT(e->v1);
1947                         REMAP_VERT(e->v2);
1948                         REMAP_EDGE(e->v1_disk_link.next);
1949                         REMAP_EDGE(e->v1_disk_link.prev);
1950                         REMAP_EDGE(e->v2_disk_link.next);
1951                         REMAP_EDGE(e->v2_disk_link.prev);
1952                         if (e->l) {
1953                                 REMAP_LOOP(e->l);
1954                         }
1955                 }
1956         }
1957
1958         /* faces */
1959         {
1960                 for (int i = 0; i < bm->totface; i++) {
1961                         BMFace *f = ftable_dst[i];
1962                         REMAP_LOOP(f->l_first);
1963
1964                         {
1965                                 BMLoop *l_iter, *l_first;
1966                                 l_iter = l_first = BM_FACE_FIRST_LOOP((BMFace *)f);
1967                                 do {
1968                                         REMAP_VERT(l_iter->v);
1969                                         REMAP_EDGE(l_iter->e);
1970                                         REMAP_FACE(l_iter->f);
1971
1972                                         REMAP_LOOP(l_iter->radial_next);
1973                                         REMAP_LOOP(l_iter->radial_prev);
1974                                         REMAP_LOOP(l_iter->next);
1975                                         REMAP_LOOP(l_iter->prev);
1976                                 } while ((l_iter = l_iter->next) != l_first);
1977                         }
1978                 }
1979         }
1980
1981         for (BMEditSelection *ese = bm->selected.first; ese; ese = ese->next) {
1982                 switch (ese->htype) {
1983                         case BM_VERT:
1984                                 if (remap & BM_VERT) {
1985                                         ese->ele = (BMElem *)MAP_VERT(ese->ele);
1986                                 }
1987                                 break;
1988                         case BM_EDGE:
1989                                 if (remap & BM_EDGE) {
1990                                         ese->ele = (BMElem *)MAP_EDGE(ese->ele);
1991                                 }
1992                                 break;
1993                         case BM_FACE:
1994                                 if (remap & BM_FACE) {
1995                                         ese->ele = (BMElem *)MAP_FACE(ese->ele);
1996                                 }
1997                                 break;
1998                 }
1999         }
2000
2001         if (bm->act_face) {
2002                 REMAP_FACE(bm->act_face);
2003         }
2004
2005 #undef MAP_VERT
2006 #undef MAP_EDGE
2007 #undef MAP_LOOP
2008 #undef MAP_EDGE
2009
2010 #undef REMAP_VERT
2011 #undef REMAP_EDGE
2012 #undef REMAP_LOOP
2013 #undef REMAP_EDGE
2014
2015         /* Cleanup, re-use local tables if the current mesh had tables allocated.
2016          * could use irrespective but it may use more memory then the caller wants (and not be needed). */
2017         if (remap & BM_VERT) {
2018                 if (bm->vtable) {
2019                         SWAP(BMVert **, vtable_dst, bm->vtable);
2020                         bm->vtable_tot = bm->totvert;
2021                         bm->elem_table_dirty &= ~BM_VERT;
2022                 }
2023                 MEM_freeN(vtable_dst);
2024                 BLI_mempool_destroy(bm->vpool);
2025                 bm->vpool = vpool_dst;
2026         }
2027
2028         if (remap & BM_EDGE) {
2029                 if (bm->etable) {
2030                         SWAP(BMEdge **, etable_dst, bm->etable);
2031                         bm->etable_tot = bm->totedge;
2032                         bm->elem_table_dirty &= ~BM_EDGE;
2033                 }
2034                 MEM_freeN(etable_dst);
2035                 BLI_mempool_destroy(bm->epool);
2036                 bm->epool = epool_dst;
2037         }
2038
2039         if (remap & BM_LOOP) {
2040                 /* no loop table */
2041                 MEM_freeN(ltable_dst);
2042                 BLI_mempool_destroy(bm->lpool);
2043                 bm->lpool = lpool_dst;
2044         }
2045
2046         if (remap & BM_FACE) {
2047                 if (bm->ftable) {
2048                         SWAP(BMFace **, ftable_dst, bm->ftable);
2049                         bm->ftable_tot = bm->totface;
2050                         bm->elem_table_dirty &= ~BM_FACE;
2051                 }
2052                 MEM_freeN(ftable_dst);
2053                 BLI_mempool_destroy(bm->fpool);
2054                 bm->fpool = fpool_dst;
2055         }
2056 }
2057
2058 /**
2059  * Re-allocates mesh data with/without toolflags.
2060  */
2061 void BM_mesh_toolflags_set(BMesh *bm, bool use_toolflags)
2062 {
2063         if (bm->use_toolflags == use_toolflags) {
2064                 return;
2065         }
2066
2067         const BMAllocTemplate allocsize = BMALLOC_TEMPLATE_FROM_BM(bm);
2068
2069         BLI_mempool *vpool_dst = NULL;
2070         BLI_mempool *epool_dst = NULL;
2071         BLI_mempool *fpool_dst = NULL;
2072
2073         bm_mempool_init_ex(
2074                 &allocsize, use_toolflags,
2075                 &vpool_dst, &epool_dst, NULL, &fpool_dst);
2076
2077         if (use_toolflags == false) {
2078                 BLI_mempool_destroy(bm->vtoolflagpool);
2079                 BLI_mempool_destroy(bm->etoolflagpool);
2080                 BLI_mempool_destroy(bm->ftoolflagpool);
2081
2082                 bm->vtoolflagpool = NULL;
2083                 bm->etoolflagpool = NULL;
2084                 bm->ftoolflagpool = NULL;
2085         }
2086
2087         BM_mesh_rebuild(
2088                 bm,
2089                 &((struct BMeshCreateParams){.use_toolflags = use_toolflags,}),
2090                 vpool_dst, epool_dst, NULL, fpool_dst);
2091
2092         bm->use_toolflags = use_toolflags;
2093 }