6697430a88df8e5c6baba209f266687bd32b133e
[blender.git] / source / blender / bmesh / intern / bmesh_mesh_conv.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_conv.c
24  *  \ingroup bmesh
25  *
26  * BM mesh conversion functions.
27  *
28  * \section bm_mesh_conv_shapekey Converting Shape Keys
29  *
30  * When converting to/from a Mesh/BMesh you can optionally pass a shape key to edit.
31  * This has the effect of editing the shape key-block rather then the original mesh vertex coords
32  * (although additional geometry is still allowed and uses fallback locations on converting).
33  *
34  * While this works for any mesh/bmesh this is made use of by entering and exiting edit-mode.
35  *
36  * There are comments in code but this should help explain the general
37  * intention as to how this works converting from/to bmesh.
38  *
39  *
40  * \subsection user_pov User Perspective
41  *
42  * - Editmode operations when a shape key-block is active edits only that key-block.
43  * - The first Basis key-block always matches the Mesh verts.
44  * - Changing vertex locations of _any_ Basis will apply offsets to those shape keys using this as their Basis.
45  *
46  *
47  * \subsection enter_editmode Entering EditMode - #BM_mesh_bm_from_me
48  *
49  * - the active key-block is used for BMesh vertex locations on entering edit-mode.
50  * So obviously the meshes vertex locations remain unchanged and the shape key its self is not being edited directly.
51  * Simply the #BMVert.co is a initialized from active shape key (when its set).
52  * - all key-blocks are added as CustomData layers (read code for details).
53  *
54  *
55  * \subsection exit_editmode Exiting EditMode - #BM_mesh_bm_to_me
56  *
57  * This is where the most confusing code is! Won't attempt to document the details here, for that read the code.
58  * But basics are as follows.
59  *
60  * - Vertex locations (possibly modified from initial active key-block) are copied directly into #MVert.co
61  * (special confusing note that these may be restored later, when editing the 'Basis', read on).
62  * - if the 'Key' is relative, and the active key-block is the basis for ANY other key-blocks - get an array of offsets
63  * between the new vertex locations and the original shape key (before entering edit-mode),
64  * these offsets get applied later on to inactive key-blocks using the active one (which we are editing) as their Basis.
65  *
66  * Copying the locations back to the shape keys is quite confusing...
67  * One main area of confusion is that when editing a 'Basis' key-block 'me->key->refkey'
68  * The coords are written into the mesh, from the users perspective the Basis coords are written into the mesh
69  * when exiting edit-mode.
70  *
71  * When _not_ editing the 'Basis', the original vertex locations (stored in the mesh and unchanged during edit-mode),
72  * are copied back into the mesh.
73  *
74  * This has the effect from the users POV of leaving the mesh un-touched, and only editing the active shape key-block.
75  *
76  */
77
78 #include "DNA_mesh_types.h"
79 #include "DNA_meshdata_types.h"
80 #include "DNA_object_types.h"
81 #include "DNA_modifier_types.h"
82 #include "DNA_key_types.h"
83
84 #include "MEM_guardedalloc.h"
85
86 #include "BLI_listbase.h"
87 #include "BLI_array.h"
88 #include "BLI_math_vector.h"
89
90 #include "BKE_mesh.h"
91 #include "BKE_customdata.h"
92 #include "BKE_multires.h"
93
94 #include "BKE_global.h" /* ugh - for looping over all objects */
95 #include "BKE_main.h"
96 #include "BKE_key.h"
97
98 #include "bmesh.h"
99 #include "intern/bmesh_private.h" /* for element checking */
100
101 void BM_mesh_cd_flag_ensure(BMesh *bm, Mesh *mesh, const char cd_flag)
102 {
103         const char cd_flag_all = BM_mesh_cd_flag_from_bmesh(bm) | cd_flag;
104         BM_mesh_cd_flag_apply(bm, cd_flag_all);
105         if (mesh) {
106                 mesh->cd_flag = cd_flag_all;
107         }
108 }
109
110 void BM_mesh_cd_flag_apply(BMesh *bm, const char cd_flag)
111 {
112         /* CustomData_bmesh_init_pool() must run first */
113         BLI_assert(bm->vdata.totlayer == 0 || bm->vdata.pool != NULL);
114         BLI_assert(bm->edata.totlayer == 0 || bm->edata.pool != NULL);
115
116         if (cd_flag & ME_CDFLAG_VERT_BWEIGHT) {
117                 if (!CustomData_has_layer(&bm->vdata, CD_BWEIGHT)) {
118                         BM_data_layer_add(bm, &bm->vdata, CD_BWEIGHT);
119                 }
120         }
121         else {
122                 if (CustomData_has_layer(&bm->vdata, CD_BWEIGHT)) {
123                         BM_data_layer_free(bm, &bm->vdata, CD_BWEIGHT);
124                 }
125         }
126
127         if (cd_flag & ME_CDFLAG_EDGE_BWEIGHT) {
128                 if (!CustomData_has_layer(&bm->edata, CD_BWEIGHT)) {
129                         BM_data_layer_add(bm, &bm->edata, CD_BWEIGHT);
130                 }
131         }
132         else {
133                 if (CustomData_has_layer(&bm->edata, CD_BWEIGHT)) {
134                         BM_data_layer_free(bm, &bm->edata, CD_BWEIGHT);
135                 }
136         }
137
138         if (cd_flag & ME_CDFLAG_EDGE_CREASE) {
139                 if (!CustomData_has_layer(&bm->edata, CD_CREASE)) {
140                         BM_data_layer_add(bm, &bm->edata, CD_CREASE);
141                 }
142         }
143         else {
144                 if (CustomData_has_layer(&bm->edata, CD_CREASE)) {
145                         BM_data_layer_free(bm, &bm->edata, CD_CREASE);
146                 }
147         }
148 }
149
150 char BM_mesh_cd_flag_from_bmesh(BMesh *bm)
151 {
152         char cd_flag = 0;
153         if (CustomData_has_layer(&bm->vdata, CD_BWEIGHT)) {
154                 cd_flag |= ME_CDFLAG_VERT_BWEIGHT;
155         }
156         if (CustomData_has_layer(&bm->edata, CD_BWEIGHT)) {
157                 cd_flag |= ME_CDFLAG_EDGE_BWEIGHT;
158         }
159         if (CustomData_has_layer(&bm->edata, CD_CREASE)) {
160                 cd_flag |= ME_CDFLAG_EDGE_CREASE;
161         }
162         return cd_flag;
163 }
164
165 /**
166  * \brief Mesh -> BMesh
167  *
168  * \warning This function doesn't calculate face normals.
169  */
170 void BM_mesh_bm_from_me(BMesh *bm, Mesh *me, bool set_key, int act_key_nr)
171 {
172         MVert *mvert;
173         BLI_array_declare(verts);
174         MEdge *medge;
175         MLoop *ml;
176         MPoly *mpoly;
177         KeyBlock *actkey, *block;
178         BMVert *v, **vt = NULL, **verts = NULL;
179         BMEdge *e, **fedges = NULL, **et = NULL;
180         BMFace *f;
181         BLI_array_declare(fedges);
182         float (*keyco)[3] = NULL;
183         int *keyi;
184         int totuv, i, j;
185
186         int cd_vert_bweight_offset;
187         int cd_edge_bweight_offset;
188         int cd_edge_crease_offset;
189
190         /* free custom data */
191         /* this isnt needed in most cases but do just incase */
192         CustomData_free(&bm->vdata, bm->totvert);
193         CustomData_free(&bm->edata, bm->totedge);
194         CustomData_free(&bm->ldata, bm->totloop);
195         CustomData_free(&bm->pdata, bm->totface);
196
197         if (!me || !me->totvert) {
198                 if (me) { /*no verts? still copy customdata layout*/
199                         CustomData_copy(&me->vdata, &bm->vdata, CD_MASK_BMESH, CD_ASSIGN, 0);
200                         CustomData_copy(&me->edata, &bm->edata, CD_MASK_BMESH, CD_ASSIGN, 0);
201                         CustomData_copy(&me->ldata, &bm->ldata, CD_MASK_BMESH, CD_ASSIGN, 0);
202                         CustomData_copy(&me->pdata, &bm->pdata, CD_MASK_BMESH, CD_ASSIGN, 0);
203
204                         CustomData_bmesh_init_pool(&bm->vdata, me->totvert, BM_VERT);
205                         CustomData_bmesh_init_pool(&bm->edata, me->totedge, BM_EDGE);
206                         CustomData_bmesh_init_pool(&bm->ldata, me->totloop, BM_LOOP);
207                         CustomData_bmesh_init_pool(&bm->pdata, me->totpoly, BM_FACE);
208                 }
209                 return; /* sanity check */
210         }
211
212         vt = MEM_mallocN(sizeof(void **) * me->totvert, "mesh to bmesh vtable");
213
214         CustomData_copy(&me->vdata, &bm->vdata, CD_MASK_BMESH, CD_CALLOC, 0);
215         CustomData_copy(&me->edata, &bm->edata, CD_MASK_BMESH, CD_CALLOC, 0);
216         CustomData_copy(&me->ldata, &bm->ldata, CD_MASK_BMESH, CD_CALLOC, 0);
217         CustomData_copy(&me->pdata, &bm->pdata, CD_MASK_BMESH, CD_CALLOC, 0);
218
219         /* make sure uv layer names are consisten */
220         totuv = CustomData_number_of_layers(&bm->pdata, CD_MTEXPOLY);
221         for (i = 0; i < totuv; i++) {
222                 int li = CustomData_get_layer_index_n(&bm->pdata, CD_MTEXPOLY, i);
223                 CustomData_set_layer_name(&bm->ldata, CD_MLOOPUV, i, bm->pdata.layers[li].name);
224         }
225
226         if ((act_key_nr != 0) && (me->key != NULL)) {
227                 actkey = BLI_findlink(&me->key->block, act_key_nr - 1);
228         }
229         else {
230                 actkey = NULL;
231         }
232
233         if (me->key) {
234                 CustomData_add_layer(&bm->vdata, CD_SHAPE_KEYINDEX, CD_ASSIGN, NULL, 0);
235
236                 /* check if we need to generate unique ids for the shapekeys.
237                  * this also exists in the file reading code, but is here for
238                  * a sanity check */
239                 if (!me->key->uidgen) {
240                         fprintf(stderr,
241                                 "%s had to generate shape key uid's in a situation we shouldn't need to! "
242                                 "(bmesh internal error)\n",
243                                 __func__);
244
245                         me->key->uidgen = 1;
246                         for (block = me->key->block.first; block; block = block->next) {
247                                 block->uid = me->key->uidgen++;
248                         }
249                 }
250
251                 if (actkey && actkey->totelem == me->totvert) {
252                         keyco = actkey->data;
253                         bm->shapenr = act_key_nr;
254                 }
255
256                 for (i = 0, block = me->key->block.first; block; block = block->next, i++) {
257                         CustomData_add_layer_named(&bm->vdata, CD_SHAPEKEY,
258                                                    CD_ASSIGN, NULL, 0, block->name);
259
260                         j = CustomData_get_layer_index_n(&bm->vdata, CD_SHAPEKEY, i);
261                         bm->vdata.layers[j].uid = block->uid;
262                 }
263         }
264
265         CustomData_bmesh_init_pool(&bm->vdata, me->totvert, BM_VERT);
266         CustomData_bmesh_init_pool(&bm->edata, me->totedge, BM_EDGE);
267         CustomData_bmesh_init_pool(&bm->ldata, me->totloop, BM_LOOP);
268         CustomData_bmesh_init_pool(&bm->pdata, me->totpoly, BM_FACE);
269
270         BM_mesh_cd_flag_apply(bm, me->cd_flag);
271
272         cd_vert_bweight_offset = CustomData_get_offset(&bm->vdata, CD_BWEIGHT);
273         cd_edge_bweight_offset = CustomData_get_offset(&bm->edata, CD_BWEIGHT);
274         cd_edge_crease_offset  = CustomData_get_offset(&bm->edata, CD_CREASE);
275
276         for (i = 0, mvert = me->mvert; i < me->totvert; i++, mvert++) {
277                 v = BM_vert_create(bm, keyco && set_key ? keyco[i] : mvert->co, NULL, BM_CREATE_SKIP_CD);
278                 BM_elem_index_set(v, i); /* set_ok */
279                 vt[i] = v;
280
281                 /* transfer flag */
282                 v->head.hflag = BM_vert_flag_from_mflag(mvert->flag & ~SELECT);
283
284                 /* this is necessary for selection counts to work properly */
285                 if (mvert->flag & SELECT) {
286                         BM_vert_select_set(bm, v, true);
287                 }
288
289                 normal_short_to_float_v3(v->no, mvert->no);
290
291                 /* Copy Custom Data */
292                 CustomData_to_bmesh_block(&me->vdata, &bm->vdata, i, &v->head.data, true);
293
294                 if (cd_vert_bweight_offset != -1) BM_ELEM_CD_SET_FLOAT(v, cd_vert_bweight_offset, (float)mvert->bweight / 255.0f);
295
296                 /* set shapekey data */
297                 if (me->key) {
298                         /* set shape key original index */
299                         keyi = CustomData_bmesh_get(&bm->vdata, v->head.data, CD_SHAPE_KEYINDEX);
300                         if (keyi) {
301                                 *keyi = i;
302                         }
303
304                         for (block = me->key->block.first, j = 0; block; block = block->next, j++) {
305                                 float *co = CustomData_bmesh_get_n(&bm->vdata, v->head.data, CD_SHAPEKEY, j);
306
307                                 if (co) {
308                                         copy_v3_v3(co, ((float *)block->data) + 3 * i);
309                                 }
310                         }
311                 }
312         }
313
314         bm->elem_index_dirty &= ~BM_VERT; /* added in order, clear dirty flag */
315
316         if (!me->totedge) {
317                 MEM_freeN(vt);
318                 return;
319         }
320
321         et = MEM_mallocN(sizeof(void **) * me->totedge, "mesh to bmesh etable");
322
323         medge = me->medge;
324         for (i = 0; i < me->totedge; i++, medge++) {
325                 e = BM_edge_create(bm, vt[medge->v1], vt[medge->v2], NULL, BM_CREATE_SKIP_CD);
326                 BM_elem_index_set(e, i); /* set_ok */
327                 et[i] = e;
328
329                 /* transfer flags */
330                 e->head.hflag = BM_edge_flag_from_mflag(medge->flag & ~SELECT);
331
332                 /* this is necessary for selection counts to work properly */
333                 if (medge->flag & SELECT) {
334                         BM_edge_select_set(bm, e, true);
335                 }
336
337                 /* Copy Custom Data */
338                 CustomData_to_bmesh_block(&me->edata, &bm->edata, i, &e->head.data, true);
339
340                 if (cd_edge_bweight_offset != -1) BM_ELEM_CD_SET_FLOAT(e, cd_edge_bweight_offset, (float)medge->bweight / 255.0f);
341                 if (cd_edge_crease_offset  != -1) BM_ELEM_CD_SET_FLOAT(e, cd_edge_crease_offset,  (float)medge->crease  / 255.0f);
342
343         }
344
345         bm->elem_index_dirty &= ~BM_EDGE; /* added in order, clear dirty flag */
346
347         mpoly = me->mpoly;
348         for (i = 0; i < me->totpoly; i++, mpoly++) {
349                 BMLoop *l_iter;
350                 BMLoop *l_first;
351
352                 BLI_array_empty(fedges);
353                 BLI_array_empty(verts);
354
355                 BLI_array_grow_items(fedges, mpoly->totloop);
356                 BLI_array_grow_items(verts, mpoly->totloop);
357
358                 for (j = 0; j < mpoly->totloop; j++) {
359                         ml = &me->mloop[mpoly->loopstart + j];
360                         v = vt[ml->v];
361                         e = et[ml->e];
362
363                         fedges[j] = e;
364                         verts[j] = v;
365                 }
366
367                 /* not sure what this block is supposed to do,
368                  * but its unused. so commenting - campbell */
369 #if 0
370                 {
371                         BMVert *v1, *v2;
372                         v1 = vt[me->mloop[mpoly->loopstart].v];
373                         v2 = vt[me->mloop[mpoly->loopstart + 1].v];
374
375                         if (v1 == fedges[0]->v1) {
376                                 v2 = fedges[0]->v2;
377                         }
378                         else {
379                                 v1 = fedges[0]->v2;
380                                 v2 = fedges[0]->v1;
381                         }
382                 }
383 #endif
384
385                 f = BM_face_create(bm, verts, fedges, mpoly->totloop, BM_CREATE_SKIP_CD);
386
387                 if (UNLIKELY(f == NULL)) {
388                         printf("%s: Warning! Bad face in mesh"
389                                " \"%s\" at index %d!, skipping\n",
390                                __func__, me->id.name + 2, i);
391                         continue;
392                 }
393
394                 /* don't use 'i' since we may have skipped the face */
395                 BM_elem_index_set(f, bm->totface - 1); /* set_ok */
396
397                 /* transfer flag */
398                 f->head.hflag = BM_face_flag_from_mflag(mpoly->flag & ~ME_FACE_SEL);
399
400                 /* this is necessary for selection counts to work properly */
401                 if (mpoly->flag & ME_FACE_SEL) {
402                         BM_face_select_set(bm, f, true);
403                 }
404
405                 f->mat_nr = mpoly->mat_nr;
406                 if (i == me->act_face) bm->act_face = f;
407
408                 j = mpoly->loopstart;
409                 l_iter = l_first = BM_FACE_FIRST_LOOP(f);
410                 do {
411                         /* Save index of correspsonding MLoop */
412                         CustomData_to_bmesh_block(&me->ldata, &bm->ldata, j++, &l_iter->head.data, true);
413                 } while ((l_iter = l_iter->next) != l_first);
414
415                 /* Copy Custom Data */
416                 CustomData_to_bmesh_block(&me->pdata, &bm->pdata, i, &f->head.data, true);
417         }
418
419         bm->elem_index_dirty &= ~BM_FACE; /* added in order, clear dirty flag */
420
421         if (me->mselect && me->totselect != 0) {
422
423                 BMVert **vert_array = MEM_mallocN(sizeof(BMVert *) * bm->totvert, "VSelConv");
424                 BMEdge **edge_array = MEM_mallocN(sizeof(BMEdge *) * bm->totedge, "ESelConv");
425                 BMFace **face_array = MEM_mallocN(sizeof(BMFace *) * bm->totface, "FSelConv");
426                 MSelect *msel;
427
428 #pragma omp parallel sections if (bm->totvert + bm->totedge + bm->totface >= BM_OMP_LIMIT)
429                 {
430 #pragma omp section
431                         { BM_iter_as_array(bm, BM_VERTS_OF_MESH, NULL, (void **)vert_array, bm->totvert); }
432 #pragma omp section
433                         { BM_iter_as_array(bm, BM_EDGES_OF_MESH, NULL, (void **)edge_array, bm->totedge); }
434 #pragma omp section
435                         { BM_iter_as_array(bm, BM_FACES_OF_MESH, NULL, (void **)face_array, bm->totface); }
436                 }
437
438                 for (i = 0, msel = me->mselect; i < me->totselect; i++, msel++) {
439                         switch (msel->type) {
440                                 case ME_VSEL:
441                                         BM_select_history_store(bm, (BMElem *)vert_array[msel->index]);
442                                         break;
443                                 case ME_ESEL:
444                                         BM_select_history_store(bm, (BMElem *)edge_array[msel->index]);
445                                         break;
446                                 case ME_FSEL:
447                                         BM_select_history_store(bm, (BMElem *)face_array[msel->index]);
448                                         break;
449                         }
450                 }
451
452                 MEM_freeN(vert_array);
453                 MEM_freeN(edge_array);
454                 MEM_freeN(face_array);
455         }
456         else {
457                 me->totselect = 0;
458                 if (me->mselect) {
459                         MEM_freeN(me->mselect);
460                         me->mselect = NULL;
461                 }
462         }
463
464         BLI_array_free(fedges);
465         BLI_array_free(verts);
466
467         MEM_freeN(vt);
468         MEM_freeN(et);
469 }
470
471
472 /**
473  * \brief BMesh -> Mesh
474  */
475 static BMVert **bm_to_mesh_vertex_map(BMesh *bm, int ototvert)
476 {
477         BMVert **vertMap = NULL;
478         BMVert *eve;
479         int index;
480         int i = 0;
481         BMIter iter;
482
483         /* caller needs to ensure this */
484         BLI_assert(ototvert > 0);
485
486         vertMap = MEM_callocN(sizeof(*vertMap) * ototvert, "vertMap");
487         if (CustomData_has_layer(&bm->vdata, CD_SHAPE_KEYINDEX)) {
488                 int *keyi;
489                 BM_ITER_MESH (eve, &iter, bm, BM_VERTS_OF_MESH) {
490                         keyi = CustomData_bmesh_get(&bm->vdata, eve->head.data, CD_SHAPE_KEYINDEX);
491                         if (keyi) {
492                                 if (((index = *keyi) != ORIGINDEX_NONE) && (index < ototvert)) {
493                                         vertMap[index] = eve;
494                                 }
495                         }
496                         else {
497                                 if (i < ototvert) {
498                                         vertMap[i] = eve;
499                                 }
500                         }
501                         i++;
502                 }
503         }
504         else {
505                 BM_ITER_MESH (eve, &iter, bm, BM_VERTS_OF_MESH) {
506                         if (i < ototvert) {
507                                 vertMap[i] = eve;
508                         }
509                         else {
510                                 break;
511                         }
512                         i++;
513                 }
514         }
515
516         return vertMap;
517 }
518
519 /**
520  * returns customdata shapekey index from a keyblock or -1
521  * \note could split this out into a more generic function */
522 static int bm_to_mesh_shape_layer_index_from_kb(BMesh *bm, KeyBlock *currkey)
523 {
524         int i;
525         int j = 0;
526
527         for (i = 0; i < bm->vdata.totlayer; i++) {
528                 if (bm->vdata.layers[i].type == CD_SHAPEKEY) {
529                         if (currkey->uid == bm->vdata.layers[i].uid) {
530                                 return j;
531                         }
532                         j++;
533                 }
534         }
535         return -1;
536 }
537
538 BLI_INLINE void bmesh_quick_edgedraw_flag(MEdge *med, BMEdge *e)
539 {
540         /* this is a cheap way to set the edge draw, its not precise and will
541          * pick the first 2 faces an edge uses.
542          * The dot comparison is a little arbitrary, but set so that a 5 subd
543          * IcoSphere won't vanish but subd 6 will (as with pre-bmesh blender) */
544
545
546         if ( /* (med->flag & ME_EDGEDRAW) && */ /* assume to be true */
547              (e->l && (e->l != e->l->radial_next)) &&
548              (dot_v3v3(e->l->f->no, e->l->radial_next->f->no) > 0.9995f))
549         {
550                 med->flag &= ~ME_EDGEDRAW;
551         }
552         else {
553                 med->flag |= ME_EDGEDRAW;
554         }
555 }
556
557 void BM_mesh_bm_to_me(BMesh *bm, Mesh *me, bool do_tessface)
558 {
559         MLoop *mloop;
560         MPoly *mpoly;
561         MVert *mvert, *oldverts;
562         MEdge *med, *medge;
563         BMVert *v, *eve;
564         BMEdge *e;
565         BMLoop *l;
566         BMFace *f;
567         BMIter iter, liter;
568         int i, j, ototvert;
569
570         const int cd_vert_bweight_offset = CustomData_get_offset(&bm->vdata, CD_BWEIGHT);
571         const int cd_edge_bweight_offset = CustomData_get_offset(&bm->edata, CD_BWEIGHT);
572         const int cd_edge_crease_offset  = CustomData_get_offset(&bm->edata, CD_CREASE);
573
574         ototvert = me->totvert;
575
576         /* new vertex block */
577         if (bm->totvert == 0) mvert = NULL;
578         else mvert = MEM_callocN(bm->totvert * sizeof(MVert), "loadeditbMesh vert");
579
580         /* new edge block */
581         if (bm->totedge == 0) medge = NULL;
582         else medge = MEM_callocN(bm->totedge * sizeof(MEdge), "loadeditbMesh edge");
583
584         /* new ngon face block */
585         if (bm->totface == 0) mpoly = NULL;
586         else mpoly = MEM_callocN(bm->totface * sizeof(MPoly), "loadeditbMesh poly");
587
588         /* new loop block */
589         if (bm->totloop == 0) mloop = NULL;
590         else mloop = MEM_callocN(bm->totloop * sizeof(MLoop), "loadeditbMesh loop");
591
592         /* lets save the old verts just in case we are actually working on
593          * a key ... we now do processing of the keys at the end */
594         oldverts = me->mvert;
595
596         /* don't free this yet */
597         if (oldverts) {
598                 CustomData_set_layer(&me->vdata, CD_MVERT, NULL);
599         }
600
601         /* free custom data */
602         CustomData_free(&me->vdata, me->totvert);
603         CustomData_free(&me->edata, me->totedge);
604         CustomData_free(&me->fdata, me->totface);
605         CustomData_free(&me->ldata, me->totloop);
606         CustomData_free(&me->pdata, me->totpoly);
607
608         /* add new custom data */
609         me->totvert = bm->totvert;
610         me->totedge = bm->totedge;
611         me->totloop = bm->totloop;
612         me->totpoly = bm->totface;
613         /* will be overwritten with a valid value if 'dotess' is set, otherwise we
614          * end up with 'me->totface' and me->mface == NULL which can crash [#28625]
615          */
616         me->totface = 0;
617
618         CustomData_copy(&bm->vdata, &me->vdata, CD_MASK_MESH, CD_CALLOC, me->totvert);
619         CustomData_copy(&bm->edata, &me->edata, CD_MASK_MESH, CD_CALLOC, me->totedge);
620         CustomData_copy(&bm->ldata, &me->ldata, CD_MASK_MESH, CD_CALLOC, me->totloop);
621         CustomData_copy(&bm->pdata, &me->pdata, CD_MASK_MESH, CD_CALLOC, me->totpoly);
622
623         CustomData_add_layer(&me->vdata, CD_MVERT, CD_ASSIGN, mvert, me->totvert);
624         CustomData_add_layer(&me->edata, CD_MEDGE, CD_ASSIGN, medge, me->totedge);
625         CustomData_add_layer(&me->ldata, CD_MLOOP, CD_ASSIGN, mloop, me->totloop);
626         CustomData_add_layer(&me->pdata, CD_MPOLY, CD_ASSIGN, mpoly, me->totpoly);
627
628         me->cd_flag = BM_mesh_cd_flag_from_bmesh(bm);
629
630         /* this is called again, 'dotess' arg is used there */
631         mesh_update_customdata_pointers(me, 0);
632
633         i = 0;
634         BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) {
635                 copy_v3_v3(mvert->co, v->co);
636                 normal_float_to_short_v3(mvert->no, v->no);
637
638                 mvert->flag = BM_vert_flag_to_mflag(v);
639
640                 BM_elem_index_set(v, i); /* set_inline */
641
642                 /* copy over customdat */
643                 CustomData_from_bmesh_block(&bm->vdata, &me->vdata, v->head.data, i);
644
645                 if (cd_vert_bweight_offset != -1) mvert->bweight = BM_ELEM_CD_GET_FLOAT_AS_UCHAR(v, cd_vert_bweight_offset);
646
647                 i++;
648                 mvert++;
649
650                 BM_CHECK_ELEMENT(v);
651         }
652         bm->elem_index_dirty &= ~BM_VERT;
653
654         med = medge;
655         i = 0;
656         BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
657                 med->v1 = BM_elem_index_get(e->v1);
658                 med->v2 = BM_elem_index_get(e->v2);
659
660                 med->flag = BM_edge_flag_to_mflag(e);
661
662                 BM_elem_index_set(e, i); /* set_inline */
663
664                 /* copy over customdata */
665                 CustomData_from_bmesh_block(&bm->edata, &me->edata, e->head.data, i);
666
667                 bmesh_quick_edgedraw_flag(med, e);
668
669                 if (cd_edge_crease_offset  != -1) med->crease  = BM_ELEM_CD_GET_FLOAT_AS_UCHAR(e, cd_edge_crease_offset);
670                 if (cd_edge_bweight_offset != -1) med->bweight = BM_ELEM_CD_GET_FLOAT_AS_UCHAR(e, cd_edge_bweight_offset);
671
672                 i++;
673                 med++;
674                 BM_CHECK_ELEMENT(e);
675         }
676         bm->elem_index_dirty &= ~BM_EDGE;
677
678         i = 0;
679         j = 0;
680         BM_ITER_MESH (f, &iter, bm, BM_FACES_OF_MESH) {
681                 mpoly->loopstart = j;
682                 mpoly->totloop = f->len;
683                 mpoly->mat_nr = f->mat_nr;
684                 mpoly->flag = BM_face_flag_to_mflag(f);
685
686                 l = BM_iter_new(&liter, bm, BM_LOOPS_OF_FACE, f);
687                 for ( ; l; l = BM_iter_step(&liter), j++, mloop++) {
688                         mloop->e = BM_elem_index_get(l->e);
689                         mloop->v = BM_elem_index_get(l->v);
690
691                         /* copy over customdat */
692                         CustomData_from_bmesh_block(&bm->ldata, &me->ldata, l->head.data, j);
693                         BM_CHECK_ELEMENT(l);
694                         BM_CHECK_ELEMENT(l->e);
695                         BM_CHECK_ELEMENT(l->v);
696                 }
697
698                 if (f == bm->act_face) me->act_face = i;
699
700                 /* copy over customdata */
701                 CustomData_from_bmesh_block(&bm->pdata, &me->pdata, f->head.data, i);
702
703                 i++;
704                 mpoly++;
705                 BM_CHECK_ELEMENT(f);
706         }
707
708         /* patch hook indices and vertex parents */
709         if (ototvert > 0) {
710                 Object *ob;
711                 ModifierData *md;
712                 BMVert **vertMap = NULL;
713                 int i, j;
714
715                 for (ob = G.main->object.first; ob; ob = ob->id.next) {
716                         if ((ob->parent) && (ob->parent->data == me) && ELEM(ob->partype, PARVERT1, PARVERT3)) {
717
718                                 if (vertMap == NULL) {
719                                         vertMap = bm_to_mesh_vertex_map(bm, ototvert);
720                                 }
721
722                                 if (ob->par1 < ototvert) {
723                                         eve = vertMap[ob->par1];
724                                         if (eve) ob->par1 = BM_elem_index_get(eve);
725                                 }
726                                 if (ob->par2 < ototvert) {
727                                         eve = vertMap[ob->par2];
728                                         if (eve) ob->par2 = BM_elem_index_get(eve);
729                                 }
730                                 if (ob->par3 < ototvert) {
731                                         eve = vertMap[ob->par3];
732                                         if (eve) ob->par3 = BM_elem_index_get(eve);
733                                 }
734
735                         }
736                         if (ob->data == me) {
737                                 for (md = ob->modifiers.first; md; md = md->next) {
738                                         if (md->type == eModifierType_Hook) {
739                                                 HookModifierData *hmd = (HookModifierData *) md;
740
741                                                 if (vertMap == NULL) {
742                                                         vertMap = bm_to_mesh_vertex_map(bm, ototvert);
743                                                 }
744
745                                                 for (i = j = 0; i < hmd->totindex; i++) {
746                                                         if (hmd->indexar[i] < ototvert) {
747                                                                 eve = vertMap[hmd->indexar[i]];
748
749                                                                 if (eve) {
750                                                                         hmd->indexar[j++] = BM_elem_index_get(eve);
751                                                                 }
752                                                         }
753                                                         else j++;
754                                                 }
755
756                                                 hmd->totindex = j;
757                                         }
758                                 }
759                         }
760                 }
761
762                 if (vertMap) MEM_freeN(vertMap);
763         }
764
765         if (do_tessface) {
766                 BKE_mesh_tessface_calc(me);
767         }
768
769         mesh_update_customdata_pointers(me, do_tessface);
770
771         {
772                 BMEditSelection *selected;
773                 me->totselect = BLI_countlist(&(bm->selected));
774
775                 if (me->mselect) MEM_freeN(me->mselect);
776
777                 me->mselect = MEM_callocN(sizeof(MSelect) * me->totselect, "Mesh selection history");
778
779
780                 for (i = 0, selected = bm->selected.first; selected; i++, selected = selected->next) {
781                         if (selected->htype == BM_VERT) {
782                                 me->mselect[i].type = ME_VSEL;
783
784                         }
785                         else if (selected->htype == BM_EDGE) {
786                                 me->mselect[i].type = ME_ESEL;
787
788                         }
789                         else if (selected->htype == BM_FACE) {
790                                 me->mselect[i].type = ME_FSEL;
791                         }
792
793                         me->mselect[i].index = BM_elem_index_get(selected->ele);
794                 }
795         }
796
797         /* see comment below, this logic is in twice */
798
799         if (me->key) {
800                 KeyBlock *currkey;
801                 KeyBlock *actkey = BLI_findlink(&me->key->block, bm->shapenr - 1);
802
803                 float (*ofs)[3] = NULL;
804
805                 /* go through and find any shapekey customdata layers
806                  * that might not have corresponding KeyBlocks, and add them if
807                  * necessary */
808                 j = 0;
809                 for (i = 0; i < bm->vdata.totlayer; i++) {
810                         if (bm->vdata.layers[i].type != CD_SHAPEKEY)
811                                 continue;
812
813                         for (currkey = me->key->block.first; currkey; currkey = currkey->next) {
814                                 if (currkey->uid == bm->vdata.layers[i].uid)
815                                         break;
816                         }
817
818                         if (!currkey) {
819                                 currkey = BKE_keyblock_add(me->key, bm->vdata.layers[i].name);
820                                 currkey->uid = bm->vdata.layers[i].uid;
821                         }
822
823                         j++;
824                 }
825
826
827                 /* editing the base key should update others */
828                 if ((me->key->type == KEY_RELATIVE) && /* only need offsets for relative shape keys */
829                     (actkey != NULL) &&                /* unlikely, but the active key may not be valid if the
830                                                         * bmesh and the mesh are out of sync */
831                     (oldverts != NULL))                /* not used here, but 'oldverts' is used later for applying 'ofs' */
832                 {
833                         bool act_is_basis = false;
834
835                         /* find if this key is a basis for any others */
836                         for (currkey = me->key->block.first; currkey; currkey = currkey->next) {
837                                 if (bm->shapenr - 1 == currkey->relative) {
838                                         act_is_basis = true;
839                                         break;
840                                 }
841                         }
842
843                         if (act_is_basis) { /* active key is a base */
844                                 float (*fp)[3] = actkey->data;
845                                 int *keyi;
846
847                                 ofs = MEM_callocN(sizeof(float) * 3 * bm->totvert,  "currkey->data");
848                                 mvert = me->mvert;
849                                 BM_ITER_MESH_INDEX (eve, &iter, bm, BM_VERTS_OF_MESH, i) {
850                                         keyi = CustomData_bmesh_get(&bm->vdata, eve->head.data, CD_SHAPE_KEYINDEX);
851                                         if (keyi && *keyi != ORIGINDEX_NONE) {
852                                                 sub_v3_v3v3(ofs[i], mvert->co, fp[*keyi]);
853                                         }
854                                         else {
855                                                 /* if there are new vertices in the mesh, we can't propagate the offset
856                                                  * because it will only work for the existing vertices and not the new
857                                                  * ones, creating a mess when doing e.g. subdivide + translate */
858                                                 MEM_freeN(ofs);
859                                                 ofs = NULL;
860                                                 break;
861                                         }
862
863                                         mvert++;
864                                 }
865                         }
866                 }
867
868                 for (currkey = me->key->block.first; currkey; currkey = currkey->next) {
869                         int apply_offset = (ofs && (currkey != actkey) && (bm->shapenr - 1 == currkey->relative));
870                         int *keyi;
871                         float (*ofs_pt)[3] = ofs;
872                         float *newkey, *oldkey, *fp;
873
874                         j = bm_to_mesh_shape_layer_index_from_kb(bm, currkey);
875
876
877                         fp = newkey = MEM_callocN(me->key->elemsize * bm->totvert,  "currkey->data");
878                         oldkey = currkey->data;
879
880                         mvert = me->mvert;
881                         BM_ITER_MESH (eve, &iter, bm, BM_VERTS_OF_MESH) {
882
883                                 if (currkey == actkey) {
884                                         copy_v3_v3(fp, eve->co);
885
886                                         if (actkey != me->key->refkey) { /* important see bug [#30771] */
887                                                 if (oldverts) {
888                                                         keyi = CustomData_bmesh_get(&bm->vdata, eve->head.data, CD_SHAPE_KEYINDEX);
889                                                         if (*keyi != ORIGINDEX_NONE && *keyi < currkey->totelem) { /* valid old vertex */
890                                                                 copy_v3_v3(mvert->co, oldverts[*keyi].co);
891                                                         }
892                                                 }
893                                         }
894                                 }
895                                 else if (j != -1) {
896                                         /* in most cases this runs */
897                                         copy_v3_v3(fp, CustomData_bmesh_get_n(&bm->vdata, eve->head.data, CD_SHAPEKEY, j));
898                                 }
899                                 else if (oldkey &&
900                                          (keyi = CustomData_bmesh_get(&bm->vdata, eve->head.data, CD_SHAPE_KEYINDEX)) &&
901                                          (*keyi != ORIGINDEX_NONE && *keyi < currkey->totelem))
902                                 {
903                                         /* old method of reconstructing keys via vertice's original key indices,
904                                          * currently used if the new method above fails (which is theoretically
905                                          * possible in certain cases of undo) */
906                                         copy_v3_v3(fp, &oldkey[3 * (*keyi)]);
907                                 }
908                                 else {
909                                         /* fail! fill in with dummy value */
910                                         copy_v3_v3(fp, mvert->co);
911                                 }
912
913                                 /* propagate edited basis offsets to other shapes */
914                                 if (apply_offset) {
915                                         add_v3_v3(fp, *ofs_pt++);
916                                 }
917
918                                 fp += 3;
919                                 mvert++;
920                         }
921
922                         currkey->totelem = bm->totvert;
923                         if (currkey->data) {
924                                 MEM_freeN(currkey->data);
925                         }
926                         currkey->data = newkey;
927                 }
928
929                 if (ofs) MEM_freeN(ofs);
930         }
931
932         if (oldverts) MEM_freeN(oldverts);
933
934         /* topology could be changed, ensure mdisps are ok */
935         multires_topology_changed(me);
936 }